blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
0925cd9f06c57a0439fcfd1a6a4172ce2adfa620
a512ac4454eac4d2ffc7c0484269ae33522425bd
/trtlab/core/include/trtlab/core/ranges.h
0bea580826d46a50ba8d4da11ef04f637c867e5f
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
junkin/tensorrt-laboratory
443a6ac2c4ed2b81695f92bc36afdf3b6f696e2f
33b6fdf2935cd49944ae7d16601cc58f6199cd49
refs/heads/v2
2023-06-18T23:10:45.637265
2020-09-30T09:14:56
2020-09-30T09:14:56
386,116,417
0
0
BSD-3-Clause
2021-07-15T00:45:56
2021-07-15T00:45:56
null
UTF-8
C++
false
false
1,363
h
#pragma once #include <numeric> #include <vector> #include <utility> #include <type_traits> namespace trtlab { template <typename T> std::vector<std::pair<T, T>> find_ranges(const std::vector<T>& values) { static_assert(std::is_integral<T>::value, "only integral types allowed"); auto copy = values; sort(copy.begin(), copy.end()); std::vector<std::pair<T, T>> ranges; auto it = copy.cbegin(); auto end = copy.cend(); while (it != end) { auto low = *it; auto high = *it; for (T i = 0; it != end && low + i == *it; it++, i++) { high = *it; } ranges.push_back(std::make_pair(low, high)); } return ranges; } template <typename T> std::string print_ranges(const std::vector<std::pair<T, T>>& ranges) { return std::accumulate(std::begin(ranges), std::end(ranges), std::string(), [](std::string r, std::pair<T, T> p) { if (p.first == p.second) { return r + (r.empty() ? "" : ",") + std::to_string(p.first); } else { return r + (r.empty() ? "" : ",") + std::to_string(p.first) + "-" + std::to_string(p.second); } }); } } // namespace trtlab
[ "rmolson@gmail.com" ]
rmolson@gmail.com
16c224113df64854240b1bfffecb97d53c82d8f2
abc86252fff1a18c1615ac4a35de407be6a9cb88
/IOI/ioi01p1.cpp
4c61df70f9eb8ecf57e77706bf86b397a2eac7ab
[]
no_license
ApoapsisAlpha/Competitive-Programming
56a97dd666a240c4e12b7d314a21c0759683eb82
83d82a3d5d5ee85f481c437f1b5e9c8ac199f6f6
refs/heads/master
2021-07-12T11:02:40.410131
2020-07-10T17:54:33
2020-07-10T17:54:33
174,010,075
0
0
null
null
null
null
UTF-8
C++
false
false
1,275
cpp
#include <bits/stdc++.h> using namespace std; int n, s; int tree[1026][1026]; void update(int x, int y, int v) { int y1; while (x <= s) { y1 = y; while (y1 <= s) { tree[x][y1] += v; y1 += (y1 & -y1); } x += (x & -x); } } int query(int x, int y) { int sum = 0; int y1; while (x > 0) { y1 = y; while (y1 > 0) { sum += tree[x][y1]; y1 -= (y1 & -y1); } x -= (x & -x); } return sum; } int main() { for (int i = 0; i < 1025; i++) { for (int j = 0; j < 1025; j++) { tree[i][j] = 0; } } scanf("%d", &n); while (n != 3) { switch(n) { case 0: scanf("%d", &s); break; case 1: int x, y, v; scanf("%d %d %d", &x, &y, &v); update(x+1, y+1, v); break; case 2: int x1, y1, x2, y2; scanf("%d %d %d %d", &x1, &y1, &x2, &y2); x1++; y1++; x2++; y2++; printf("%d\n", query(x2, y2)-query(x1-1, y2)-query(x2, y1-1)+query(x1-1, y1-1)); break; } scanf("%d", &n); } }
[ "david.tsuki@gmail.com" ]
david.tsuki@gmail.com
a4b9d26fb8b72f3455847250b3a9fb4640ed5035
84b4d4b1e2705b070fcf96e01f3e64665dc0c636
/google_apis/gcm/engine/connection_factory_impl.cc
7ae40be111b7785107aae5bb950d14da444652b9
[ "BSD-3-Clause" ]
permissive
qjia7/chromium-crosswalk
08f62bb9e7ba33b4c9e1b3d381faf05791866fff
655d52b83f4179b85de287ced66a72d9d7995e32
refs/heads/master
2021-01-09T05:23:10.553155
2014-02-21T16:28:51
2014-02-21T16:28:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,916
cc
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "google_apis/gcm/engine/connection_factory_impl.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram.h" #include "base/metrics/sparse_histogram.h" #include "google_apis/gcm/engine/connection_handler_impl.h" #include "google_apis/gcm/protocol/mcs.pb.h" #include "net/base/net_errors.h" #include "net/http/http_network_session.h" #include "net/http/http_request_headers.h" #include "net/proxy/proxy_info.h" #include "net/socket/client_socket_handle.h" #include "net/socket/client_socket_pool_manager.h" #include "net/ssl/ssl_config_service.h" namespace gcm { namespace { // The amount of time a Socket read should wait before timing out. const int kReadTimeoutMs = 30000; // 30 seconds. // If a connection is reset after succeeding within this window of time, // the previous backoff entry is restored (and the connection success is treated // as if it was transient). const int kConnectionResetWindowSecs = 10; // 10 seconds. // Backoff policy. const net::BackoffEntry::Policy kConnectionBackoffPolicy = { // Number of initial errors (in sequence) to ignore before applying // exponential back-off rules. 0, // Initial delay for exponential back-off in ms. 10000, // 10 seconds. // Factor by which the waiting time will be multiplied. 2, // Fuzzing percentage. ex: 10% will spread requests randomly // between 90%-100% of the calculated time. 0.5, // 50%. // Maximum amount of time we are willing to delay our request in ms. 1000 * 60 * 5, // 5 minutes. // Time to keep an entry from being discarded even when it // has no significant state, -1 to never discard. -1, // Don't use initial delay unless the last request was an error. false, }; } // namespace ConnectionFactoryImpl::ConnectionFactoryImpl( const GURL& mcs_endpoint, scoped_refptr<net::HttpNetworkSession> network_session, net::NetLog* net_log) : mcs_endpoint_(mcs_endpoint), network_session_(network_session), net_log_(net_log), connecting_(false), weak_ptr_factory_(this) { } ConnectionFactoryImpl::~ConnectionFactoryImpl() { } void ConnectionFactoryImpl::Initialize( const BuildLoginRequestCallback& request_builder, const ConnectionHandler::ProtoReceivedCallback& read_callback, const ConnectionHandler::ProtoSentCallback& write_callback) { DCHECK(!connection_handler_); previous_backoff_ = CreateBackoffEntry(&kConnectionBackoffPolicy); backoff_entry_ = CreateBackoffEntry(&kConnectionBackoffPolicy); request_builder_ = request_builder; net::NetworkChangeNotifier::AddIPAddressObserver(this); net::NetworkChangeNotifier::AddConnectionTypeObserver(this); connection_handler_.reset( new ConnectionHandlerImpl( base::TimeDelta::FromMilliseconds(kReadTimeoutMs), read_callback, write_callback, base::Bind(&ConnectionFactoryImpl::ConnectionHandlerCallback, weak_ptr_factory_.GetWeakPtr()))); } ConnectionHandler* ConnectionFactoryImpl::GetConnectionHandler() const { return connection_handler_.get(); } void ConnectionFactoryImpl::Connect() { DCHECK(connection_handler_); connecting_ = true; if (backoff_entry_->ShouldRejectRequest()) { DVLOG(1) << "Delaying MCS endpoint connection for " << backoff_entry_->GetTimeUntilRelease().InMilliseconds() << " milliseconds."; base::MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&ConnectionFactoryImpl::Connect, weak_ptr_factory_.GetWeakPtr()), backoff_entry_->GetTimeUntilRelease()); return; } DVLOG(1) << "Attempting connection to MCS endpoint."; ConnectImpl(); } bool ConnectionFactoryImpl::IsEndpointReachable() const { return connection_handler_ && connection_handler_->CanSendMessage() && !connecting_; } void ConnectionFactoryImpl::SignalConnectionReset() { if (connecting_) return; // Already attempting to reconnect. if (!backoff_reset_time_.is_null() && NowTicks() - backoff_reset_time_ <= base::TimeDelta::FromSeconds(kConnectionResetWindowSecs)) { backoff_entry_.swap(previous_backoff_); backoff_entry_->InformOfRequest(false); } backoff_reset_time_ = base::TimeTicks(); previous_backoff_->Reset(); Connect(); } base::TimeTicks ConnectionFactoryImpl::NextRetryAttempt() const { if (!backoff_entry_) return base::TimeTicks(); return backoff_entry_->GetReleaseTime(); } void ConnectionFactoryImpl::OnConnectionTypeChanged( net::NetworkChangeNotifier::ConnectionType type) { if (type == net::NetworkChangeNotifier::CONNECTION_NONE) return; // TODO(zea): implement different backoff/retry policies based on connection // type. DVLOG(1) << "Connection type changed to " << type << ", resetting backoff."; backoff_entry_->Reset(); // Connect(..) should be retrying with backoff already if a connection is // necessary, so no need to call again. } void ConnectionFactoryImpl::OnIPAddressChanged() { DVLOG(1) << "IP Address changed, resetting backoff."; backoff_entry_->Reset(); // Connect(..) should be retrying with backoff already if a connection is // necessary, so no need to call again. } void ConnectionFactoryImpl::ConnectImpl() { if (socket_handle_.socket() && socket_handle_.socket()->IsConnected()) socket_handle_.socket()->Disconnect(); socket_handle_.Reset(); // TODO(zea): resolve proxies. net::ProxyInfo proxy_info; proxy_info.UseDirect(); net::SSLConfig ssl_config; network_session_->ssl_config_service()->GetSSLConfig(&ssl_config); int status = net::InitSocketHandleForTlsConnect( net::HostPortPair::FromURL(mcs_endpoint_), network_session_.get(), proxy_info, ssl_config, ssl_config, net::kPrivacyModeDisabled, net::BoundNetLog::Make(net_log_, net::NetLog::SOURCE_SOCKET), &socket_handle_, base::Bind(&ConnectionFactoryImpl::OnConnectDone, weak_ptr_factory_.GetWeakPtr())); if (status != net::ERR_IO_PENDING) OnConnectDone(status); } void ConnectionFactoryImpl::InitHandler() { // May be null in tests. mcs_proto::LoginRequest login_request; if (!request_builder_.is_null()) { request_builder_.Run(&login_request); DCHECK(login_request.IsInitialized()); } connection_handler_->Init(login_request, socket_handle_.socket()); } scoped_ptr<net::BackoffEntry> ConnectionFactoryImpl::CreateBackoffEntry( const net::BackoffEntry::Policy* const policy) { return scoped_ptr<net::BackoffEntry>(new net::BackoffEntry(policy)); } base::TimeTicks ConnectionFactoryImpl::NowTicks() { return base::TimeTicks::Now(); } void ConnectionFactoryImpl::OnConnectDone(int result) { if (result != net::OK) { LOG(ERROR) << "Failed to connect to MCS endpoint with error " << result; backoff_entry_->InformOfRequest(false); UMA_HISTOGRAM_SPARSE_SLOWLY("GCM.ConnectionFailureErrorCode", result); Connect(); return; } DVLOG(1) << "MCS endpoint socket connection success, starting handshake."; InitHandler(); } void ConnectionFactoryImpl::ConnectionHandlerCallback(int result) { if (result == net::OK) { // Handshake succeeded, reset the backoff. connecting_ = false; backoff_reset_time_ = NowTicks(); previous_backoff_.swap(backoff_entry_); backoff_entry_->Reset(); return; } if (!connecting_) UMA_HISTOGRAM_SPARSE_SLOWLY("GCM.ConnectionDisconnectErrorCode", result); // TODO(zea): Consider how to handle errors that may require some sort of // user intervention (login page, etc.). LOG(ERROR) << "Connection reset with error " << result; backoff_entry_->InformOfRequest(false); Connect(); } } // namespace gcm
[ "zea@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98" ]
zea@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98
ae0603bb840ef3897f00f5706f81c8155d7241cc
08d4cddaf2febfdfeb74895b7fc2d78bad933bb0
/Pacman_Test/Intermediate/Build/Win64/UE4Editor/Inc/Pacman_Test/LevelLoad.gen.cpp
451aefc4f059e133cac3a6eda46f29ca52813b45
[]
no_license
EpicCrisis/PacmanTest
86c5dfb4de4c464c4bf0a5dd1e9fa894a4c566e4
b3799de918b840dcf5706259e1a3afa47d3ee087
refs/heads/master
2020-04-15T04:48:18.813056
2019-01-11T14:26:23
2019-01-11T14:26:23
164,397,083
0
0
null
null
null
null
UTF-8
C++
false
false
3,439
cpp
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "GeneratedCppIncludes.h" #include "LevelLoad.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeLevelLoad() {} // Cross Module References PACMAN_TEST_API UClass* Z_Construct_UClass_ALevelLoad_NoRegister(); PACMAN_TEST_API UClass* Z_Construct_UClass_ALevelLoad(); ENGINE_API UClass* Z_Construct_UClass_AActor(); UPackage* Z_Construct_UPackage__Script_Pacman_Test(); // End Cross Module References void ALevelLoad::StaticRegisterNativesALevelLoad() { } UClass* Z_Construct_UClass_ALevelLoad_NoRegister() { return ALevelLoad::StaticClass(); } UClass* Z_Construct_UClass_ALevelLoad() { static UClass* OuterClass = nullptr; if (!OuterClass) { static UObject* (*const DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AActor, (UObject* (*)())Z_Construct_UPackage__Script_Pacman_Test, }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[] = { { "IncludePath", "LevelLoad.h" }, { "ModuleRelativePath", "LevelLoad.h" }, }; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MapArray_MetaData[] = { { "Category", "MapArray" }, { "ModuleRelativePath", "LevelLoad.h" }, }; #endif static const UE4CodeGen_Private::FArrayPropertyParams NewProp_MapArray = { UE4CodeGen_Private::EPropertyClass::Array, "MapArray", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000020005, 1, nullptr, STRUCT_OFFSET(ALevelLoad, MapArray), METADATA_PARAMS(NewProp_MapArray_MetaData, ARRAY_COUNT(NewProp_MapArray_MetaData)) }; static const UE4CodeGen_Private::FUnsizedIntPropertyParams NewProp_MapArray_Inner = { UE4CodeGen_Private::EPropertyClass::Int, "MapArray", RF_Public|RF_Transient|RF_MarkAsNative, 0x0000000000020000, 1, nullptr, 0, METADATA_PARAMS(nullptr, 0) }; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_MapArray, (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_MapArray_Inner, }; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo = { TCppClassTypeTraits<ALevelLoad>::IsAbstract, }; static const UE4CodeGen_Private::FClassParams ClassParams = { &ALevelLoad::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x00900080u, nullptr, 0, PropPointers, ARRAY_COUNT(PropPointers), nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Class_MetaDataParams, ARRAY_COUNT(Class_MetaDataParams)) }; UE4CodeGen_Private::ConstructUClass(OuterClass, ClassParams); } return OuterClass; } IMPLEMENT_CLASS(ALevelLoad, 1620885938); static FCompiledInDefer Z_CompiledInDefer_UClass_ALevelLoad(Z_Construct_UClass_ALevelLoad, &ALevelLoad::StaticClass, TEXT("/Script/Pacman_Test"), TEXT("ALevelLoad"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(ALevelLoad); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
[ "roxes2112@yahoo.com" ]
roxes2112@yahoo.com
1ee0491e7d4a169454d3602878532352555b3bf2
1742cd526f243de44a84769c07266c473648ecd6
/uri/1182.cpp
33ee4ca5a4d80ebf6f85ffd4f6f5cd640e91263f
[]
no_license
filipeabelha/gym-solutions
0d555f124fdb32508f6406f269a67eed5044d9c6
4eb8ad60643d7923780124cba3d002c5383a66a4
refs/heads/master
2021-01-23T05:09:38.962238
2020-11-29T07:14:31
2020-11-29T07:14:31
86,275,942
2
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
#include <bits/stdc++.h> int main () { int n; scanf("%d", &n); char c; scanf(" %c", &c); double matrix[12][12]; for (int i = 0; i < 12; i++) for (int j = 0; j < 12; j++) scanf("%lf", &matrix[i][j]); double sum = 0; for (int i = 0; i < 12; i++) sum += matrix[i][n]; if (c == 'M') sum /= 12; printf("%.1lf\n", sum); return 0; }
[ "me@filipeabelha.com" ]
me@filipeabelha.com
2ea1bc261b29b29c290c486f5e6c91340a14b57b
5870bb19b53c61508c2e57499ab6f10252200dee
/linking_cuda/particle.h
1994cea42331f3efc63606dda2b743b659b92664
[]
no_license
blockspacer/test-cpp
40371c04864fd632e78e9e4da2dea6c80b307d2f
d70e8f77d1d8129266afd7e9a2c4c4c051068af1
refs/heads/master
2020-07-05T20:02:09.661427
2019-08-02T07:50:39
2019-08-02T07:50:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
197
h
#include "v3.h" class particle { public: v3 position, velocity, totalDistance; public: particle(); __host__ __device__ void advance(float); v3 const& getTotalDistance() const; };
[ "vdkhristenko1991@gmail.com" ]
vdkhristenko1991@gmail.com
cf4de3b248113030bbf3f430eff9fd3fdcadc654
c699171546a86547c3a069d0598d632756b6b9fc
/scene.cpp
57493e9f54afd110d406bbf230a55c7efea240ce
[]
no_license
neurocase/GLDrive2
f58323c9ed6647b4f2610aef2027912f7c16ca72
0b3bfaf229960f0bb61bf0011f4c7e633b3f1edc
refs/heads/master
2020-04-23T08:28:35.710546
2014-05-18T07:41:57
2014-05-18T07:41:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
85
cpp
#include "include.h" #include "scene.h" Scene::Scene() { } Scene::~Scene(){ }
[ "neuroc453@gmail.com" ]
neuroc453@gmail.com
bff6e31938a14bf2ea59928ffa2d7548c0156381
9d270e601aed32c8bb86102ea1fa1590653375c0
/math/atmel/Arduino Nano Math/src/main.cpp
688b4615870737ee4d5d0eb15ac24e6b9cab44e4
[]
no_license
thalesmaoa/microprocessor
29a5dea52b8f44242cc20577310ba2e08f2bfd5e
2a06866e51ae9225855eb1632b59c2f1ba612945
refs/heads/master
2022-09-10T22:15:14.446257
2020-05-27T16:46:24
2020-05-27T16:46:24
260,018,866
0
0
null
null
null
null
UTF-8
C++
false
false
2,117
cpp
#include <Arduino.h> // Define pin to measure speed uint8_t pin_out = 12; // Test math speeds uint8_t x_i8 = 12; uint8_t y_i8 = 3; uint8_t z_i8 = 0; uint16_t x_i16 = 123; uint16_t y_i16 = 456; uint16_t z_i16 = 0; uint32_t x_i32 = 1234; uint32_t y_i32 = 5678; uint32_t z_i32 = 0; uint64_t x_i64 = 10234; uint64_t y_i64 = 56789; uint64_t z_i64 = 0; float x_f = 1.0234; float y_f = 5.6789; float z_f = 0; int math_ciompute = 100; void setup() { // Adjust pin as output pinMode(pin_out, OUTPUT); } void loop() { delay(1); // Int multiply digitalWrite(pin_out, HIGH); for(int i = 0; i < math_ciompute; i++) z_i8 = x_i8 * y_i8; digitalWrite(pin_out, LOW); delayMicroseconds(1); digitalWrite(pin_out, HIGH); for(int i = 0; i < math_ciompute; i++) z_i16 = x_i16 * y_i16; digitalWrite(pin_out, LOW); delayMicroseconds(1); digitalWrite(pin_out, HIGH); for(int i = 0; i < math_ciompute; i++) z_i32 = x_i32 * y_i32; digitalWrite(pin_out, LOW); delayMicroseconds(1); digitalWrite(pin_out, HIGH); for(int i = 0; i < math_ciompute; i++) z_i64 = x_i64 * y_i64; digitalWrite(pin_out, LOW); delayMicroseconds(1.5); // Float multiply digitalWrite(pin_out, HIGH); for(int i = 0; i < math_ciompute; i++) z_f = x_f * y_f; digitalWrite(pin_out, LOW); delayMicroseconds(1.5); // Int division digitalWrite(pin_out, HIGH); for(int i = 0; i < math_ciompute; i++) z_i8 = x_i8 / y_i8; digitalWrite(pin_out, LOW); delayMicroseconds(1); digitalWrite(pin_out, HIGH); for(int i = 0; i < math_ciompute; i++) z_i16 = x_i16 / y_i16; digitalWrite(pin_out, LOW); delayMicroseconds(1); digitalWrite(pin_out, HIGH); for(int i = 0; i < math_ciompute; i++) z_i32 = x_i32 / y_i32; digitalWrite(pin_out, LOW); delayMicroseconds(1); digitalWrite(pin_out, HIGH); for(int i = 0; i < math_ciompute; i++) z_i64 = x_i64 / y_i64; digitalWrite(pin_out, LOW); delayMicroseconds(1.5); // Float divison digitalWrite(pin_out, HIGH); for(int i = 0; i < math_ciompute; i++) z_f = x_f / y_f; digitalWrite(pin_out, LOW); }
[ "thalesmaia@gmail.com" ]
thalesmaia@gmail.com
272714a645ce5539c8de0d9edd24903c645196cd
9f7847aa35788304e26b7b9a50a73d6cf37976f3
/zjazd2/zadanie4.cpp
209cb6727b1fe0dab334e878c9f689a9cd786586
[]
no_license
s20685-pj/prg1
c98111da15a5c8b284fdcb5c5cf634047d76fdab
c174416fbf8bc9c07bc7f7b459be9f7f4eafd4d8
refs/heads/master
2020-08-22T10:01:07.541568
2020-01-11T18:39:38
2020-01-11T18:39:38
216,370,819
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
#include <iostream> using namespace std; int main(){ int i, j; cin >> i; cout << "Zgadnij liczbe" << endl; do { cin >> j; if (i < j) { cout << " Liczba jest zbyt duża"<< endl; } if (i > j) { cout << "Liczba jest zbyt mała" << endl; } if (j == 0) { cout << "Liczba prawidłowa to: "; cout << i << endl; return 0; } }while(i != j); cout << "Brawo, wygrałeś!" << endl; return 0; }
[ "s20685@pjwstk.edu.pl" ]
s20685@pjwstk.edu.pl
50d679309d4403a53ff2c4a4609178abfc27e3bd
00001d3da9f9bbb3aae9c3a3bb8e209064d73407
/1_TwoSum/1_v2.cpp
e6b1cfefb3471dd1289d0668df1b51ecba1f5e90
[]
no_license
miksin/LeetCode-Practice
3f19fc03d75252a98bab0494f2d2fa5bd57cc290
dc9604c33ba489a52acea082c61317212b4d820e
refs/heads/master
2021-05-04T01:12:57.699908
2021-01-13T06:33:18
2021-01-13T06:33:18
71,148,915
1
0
null
null
null
null
UTF-8
C++
false
false
431
cpp
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> hashTable; for (int i = 0; i < nums.size(); i++){ int x = nums[i]; auto iter = hashTable.find(target - x); if (iter != hashTable.end()){ return {iter->second, i}; } hashTable[x] = i; } return vector<int>(); } };
[ "ppy951@gmail.com" ]
ppy951@gmail.com
e33ebd59d6d5ab0b3c53b096a34d3eca9535d8ee
45d214a2a09b919e97d8b0f6ad6e5fde38a8739b
/Lista2/zad6.cpp
74d5c5416e8cd42ac193d18cc7b78885103813bf
[]
no_license
ziomas3/Algorytmy---cpp
9832f0c304ddf9d04900822967dd75d2b8b07810
c26e57a297eed5e5680e9af03431020cec059dbb
refs/heads/master
2021-02-11T02:04:42.437108
2020-03-02T18:15:56
2020-03-02T18:15:56
244,440,633
0
0
null
null
null
null
UTF-8
C++
false
false
1,355
cpp
#include <iostream> struct lnode { int x; lnode* next; lnode(int x0, lnode* n=nullptr) :x(x0), next(n) {} }; void insert(lnode *& t, int x) // wstawianie { lnode **t1=&t; while(*t1) t1 = &((*t1)->next); *t1=new lnode(x); } void inorder(lnode *t) // wypisanie kluczy w porządku "in order" { if(t) { inorder(t->next); std::cout<<t->x<<" "; } } int licznik = 0; lnode* merge (lnode *L1, lnode *L2) { if (!L1) { licznik++; return L2; } else if (!L2) { licznik++; return L1; } if (L1->x < L2->x) { licznik++; L1->next = merge(L1->next, L2); return L1; } else { licznik++; L2->next = merge(L1, L2->next); return L2; } } void zadanie6() { lnode *L1 = nullptr; lnode *L2 = nullptr; lnode *result = nullptr; for (auto i=0; i<10; i++) { insert(L1, i); insert(L2, i*3); } std::cout << "Lista 1: " << std::endl; inorder(L1); std::cout << "\nLista 2: " << std::endl; inorder(L2); result = merge(L1, L2); std::cout << "\n Złączone listy : " << std::endl; inorder(result); std::cout << "\nIlość porównań: " << licznik << std::endl; } int main() { zadanie6(); return 0; }
[ "you@example.com" ]
you@example.com
e137f6600196462630fc9244632985e72fc632de
7c9d761f4dc5c1971e20aa83c402820108ecdaa0
/D3DEngineLib/cColliderComponent.h
48b8c46aa9b12e78e42bbfaa4331d743cdfef90b
[]
no_license
ljhx2/DirectX9RenderingEngine
4abc5b4f69ced54729bb4ce2ed0a53a9666d9a66
29d20f37c798180afe2d6c146df740c63c874855
refs/heads/master
2020-05-30T07:38:15.234486
2019-05-31T15:53:40
2019-05-31T15:53:40
189,601,711
1
0
null
null
null
null
UHC
C++
false
false
2,513
h
#pragma once #include "IComponent.h" #include "cCollisionSphere.h" #include "cCollisionBox.h" namespace ENGINE { enum ECOLLISION_TYPE { eMOVABLE_COLLISION = 0, eSTATIC_COLLISION }; struct COLLISION_SPHERE { D3DXVECTOR3 center; float radius; COLLISION_SPHERE(){ center = D3DXVECTOR3(0, 0, 0); radius = 0.0f; }; COLLISION_SPHERE(D3DXVECTOR3 _center, float _radius) { center = _center; radius = _radius; } }; class GameObject; class cColliderComponent : public IComponent { public: virtual void Update(float deltaTime, D3DXMATRIXA16* matWorld); virtual void Render(); COLLISION_SPHERE GetBoundingSphere() { return COLLISION_SPHERE(m_vecBoundingCenter, m_fBoundingRadius); } void SetRenderCollisionSphere(bool b) { m_isRenderBoundingSphere = b; } bool GetRenderCOllisionSphere() { return m_isRenderBoundingSphere; } COLLISION_SPHERE GetCollisionSphere(std::string name); //collisionSphere bool AddCollisionSphere(std::string name); cCollisionSphere* GetClassCollisionSphere(std::string name); //collisionBox bool AddCollisionBox(std::string name); cCollisionBox* GetCollisionBox(std::string name); void DelCollision(std::string name); cCollisionShape* GetCollisionShape(std::string name); cColliderComponent(); cColliderComponent(GameObject* pOwnerObject); virtual ~cColliderComponent(); ///------------------------------------------ void ColliderCollision(cColliderComponent& collider); void ColliderCollision(cColliderComponent* collider) { ColliderCollision(*collider); } void ClearCollisionList(); ECOLLISION_TYPE GetCollisionTYPE() { return m_colliderType; } void SetCollisionTYPE(ECOLLISION_TYPE type); //---------------------------------------------- public: //Tool을 위해 제공되는 함수 std::map<std::string, cCollisionShape*>* GetMapCollision() { return &m_mapCollision; } private: bool m_isRenderBoundingSphere; //Origin변수들은 콜리젼스피어를 그리는 Mesh를 만들때만 사용하고 //실제 중점과 반지름은 m_vecBoundingCenter와 m_fBoundingRadius이다 D3DXVECTOR3 m_vMax, m_vMin; D3DXVECTOR3 m_vOriginMax, m_vOriginMin; D3DXVECTOR3 m_vecBoundingCenter, m_vOriginBoundingCenter; float m_fBoundingRadius; ID3DXMesh* m_pBoundingSphereMesh; D3DXMATRIXA16 m_matWorld; std::map<std::string, cCollisionShape*> m_mapCollision; std::map<std::string, cCollisionShape*>::iterator m_mapIter; ECOLLISION_TYPE m_colliderType; }; }
[ "ljhx2@daum.net" ]
ljhx2@daum.net
6d7513378a59cad1ad8c7f6def87ee10588c4728
ba76ff053e4ad23b3ecd7e41d42be8b805743e66
/src/mge/graphics/shader.cpp
8bf6b794e73e7ef54f5a752d4d3a842fd2cc6762
[ "MIT" ]
permissive
mge-engine/mge
c6b45216fe327d279c6b86b3764abcda74a7f7d4
36ce18d0602d14e216405d00e2debe0dd117f7fb
refs/heads/main
2023-09-03T15:28:34.874064
2023-08-16T15:30:00
2023-08-16T10:28:45
174,581,225
0
0
MIT
2023-03-11T14:46:07
2019-03-08T17:34:06
C++
UTF-8
C++
false
false
688
cpp
// mge - Modern Game Engine // Copyright (c) 2017-2023 by Alexander Schroeder // All rights reserved. #include "mge/graphics/shader.hpp" namespace mge { shader::shader(render_context& context, shader_type t) : context_object(context) , m_type(t) , m_initialized(false) {} void shader::compile(std::string_view source) { on_compile(source); m_initialized = true; } void shader::set_code(const mge::buffer& code) { on_set_code(code); m_initialized = true; } shader_type shader::type() const { return m_type; } bool shader::initialized() const { return m_initialized; } } // namespace mge
[ "schroeder.alexander@googlemail.com" ]
schroeder.alexander@googlemail.com
12c14c87357fb84bfc1f94a93f1d1d6299d73f45
f3efdf8c4466a8e1dffa40282979d68958d2cb14
/atcoder.jp/arc097/arc097_a/Main.cpp
a9bee5ff867e0155a863c916fcab57a5bd25edf1
[]
no_license
bokusunny/atcoder-archive
be1abd03a59ef753837e3bada6c489a990dd4ee5
248aca070960ee5519df5d4432595298864fa0f9
refs/heads/master
2023-08-20T03:37:14.215842
2021-10-20T04:19:15
2021-10-20T04:19:15
355,762,924
2
0
null
null
null
null
UTF-8
C++
false
false
692
cpp
#include <bits/stdc++.h> using namespace std; string S; int K; void solve() { cin >> S >> K; using T = tuple<string, int, int>; priority_queue<T, vector<T>, greater<T>> pq; for (int i = 0; i < (int)S.size(); i++) { pq.emplace(S.substr(i, 1), i, i + 1); } set<string> seen; while (1) { auto [str, l, r] = pq.top(); pq.pop(); if (r + 1 <= (int)S.size()) pq.emplace(S.substr(l, r + 1 - l), l, r + 1); if (seen.count(str)) continue; K--; if (K == 0) { cout << str << endl; return; } seen.insert(str); } } void setcin() { ios::sync_with_stdio(false); cin.tie(nullptr); } int main() { setcin(); solve(); return 0; }
[ "abovillage1407@gmail.com" ]
abovillage1407@gmail.com
781deec794ab75381b8388e6407e9db9a11fdc37
31685d49dfb649955fe7091f02ba657bd8e53518
/animation.hpp
8968bb561ae07a713fcef48c1cee092ade63c243
[]
no_license
mylestunglee/ego
60ff1822daa64168a8b23e46ed8f0b9d220f84ee
ef6a7d8e5adde8ad282612c40230e4b00d19b5d5
refs/heads/master
2020-04-27T08:40:20.287571
2019-03-27T23:53:31
2019-03-27T23:53:31
174,180,252
0
0
null
null
null
null
UTF-8
C++
false
false
204
hpp
#include <string> using namespace std; void animation_start(string animation_message, size_t initial, size_t animation_maximum); void animation_step(); void animation_finish(); void animation_print();
[ "mtl115@ic.ac.uk" ]
mtl115@ic.ac.uk
f32aa9e876511b82b54688fa4565da60f9aa0099
72226039c9c04a5c5a520a41e984cb2a3adf7ede
/sources/gsdm/include/protocols/urlcode.h
eba74a0f1fade2773005c1e2e0ddd22d53de11a9
[]
no_license
evansun922/gsdm2.0
3a33c4bec1b40cec2b08df61d27645e13df9ceaf
1f7d660f94543d0fe3d588ff7c07253849e6aa86
refs/heads/main
2023-02-22T17:39:40.494428
2021-01-25T03:10:03
2021-01-25T03:10:03
303,964,024
1
2
null
null
null
null
UTF-8
C++
false
false
436
h
/* * Copyright (c) 2016, * It complete websocket protocol on server from [RFC6455] * sunlei (sswin0922@163.com) */ #ifndef _GSDMURLCODE_H_ #define _GSDMURLCODE_H_ #include "platform/linuxplatform.h" namespace gsdm { std::string encodeURIComponent(const std::string &value); std::string decodeURIComponent(const std::string &value); void decodeURIComponent(const std::string &value, char *rs, int rs_len); } #endif
[ "sunlei@bogon.localdomain" ]
sunlei@bogon.localdomain
96237535a5c655c2e6d1510bf38e14f8bc35e0fc
ceed8ee18ab314b40b3e5b170dceb9adedc39b1e
/android/external/vixl/src/vixl/a64/simulator-a64.cc
69a664baf25a7db9ca1c473d595a068032446677
[]
no_license
BPI-SINOVOIP/BPI-H3-New-Android7
c9906db06010ed6b86df53afb6e25f506ad3917c
111cb59a0770d080de7b30eb8b6398a545497080
refs/heads/master
2023-02-28T20:15:21.191551
2018-10-08T06:51:44
2018-10-08T06:51:44
132,708,249
1
1
null
null
null
null
UTF-8
C++
false
false
138,611
cc
// Copyright 2015, ARM Limited // 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 ARM Limited 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 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. #ifdef VIXL_INCLUDE_SIMULATOR #include <string.h> #include <cmath> #include "vixl/a64/simulator-a64.h" namespace vixl { const Instruction* Simulator::kEndOfSimAddress = NULL; void SimSystemRegister::SetBits(int msb, int lsb, uint32_t bits) { int width = msb - lsb + 1; VIXL_ASSERT(is_uintn(width, bits) || is_intn(width, bits)); bits <<= lsb; uint32_t mask = ((1 << width) - 1) << lsb; VIXL_ASSERT((mask & write_ignore_mask_) == 0); value_ = (value_ & ~mask) | (bits & mask); } SimSystemRegister SimSystemRegister::DefaultValueFor(SystemRegister id) { switch (id) { case NZCV: return SimSystemRegister(0x00000000, NZCVWriteIgnoreMask); case FPCR: return SimSystemRegister(0x00000000, FPCRWriteIgnoreMask); default: VIXL_UNREACHABLE(); return SimSystemRegister(); } } Simulator::Simulator(Decoder* decoder, FILE* stream) { // Ensure that shift operations act as the simulator expects. VIXL_ASSERT((static_cast<int32_t>(-1) >> 1) == -1); VIXL_ASSERT((static_cast<uint32_t>(-1) >> 1) == 0x7fffffff); instruction_stats_ = false; // Set up the decoder. decoder_ = decoder; decoder_->AppendVisitor(this); stream_ = stream; print_disasm_ = new PrintDisassembler(stream_); set_coloured_trace(false); trace_parameters_ = LOG_NONE; ResetState(); // Allocate and set up the simulator stack. stack_ = new byte[stack_size_]; stack_limit_ = stack_ + stack_protection_size_; // Configure the starting stack pointer. // - Find the top of the stack. byte * tos = stack_ + stack_size_; // - There's a protection region at both ends of the stack. tos -= stack_protection_size_; // - The stack pointer must be 16-byte aligned. tos = AlignDown(tos, 16); set_sp(tos); // Set the sample period to 10, as the VIXL examples and tests are short. instrumentation_ = new Instrument("vixl_stats.csv", 10); // Print a warning about exclusive-access instructions, but only the first // time they are encountered. This warning can be silenced using // SilenceExclusiveAccessWarning(). print_exclusive_access_warning_ = true; } void Simulator::ResetState() { // Reset the system registers. nzcv_ = SimSystemRegister::DefaultValueFor(NZCV); fpcr_ = SimSystemRegister::DefaultValueFor(FPCR); // Reset registers to 0. pc_ = NULL; pc_modified_ = false; for (unsigned i = 0; i < kNumberOfRegisters; i++) { set_xreg(i, 0xbadbeef); } // Set FP registers to a value that is a NaN in both 32-bit and 64-bit FP. uint64_t nan_bits = UINT64_C(0x7ff0dead7f8beef1); VIXL_ASSERT(IsSignallingNaN(rawbits_to_double(nan_bits & kDRegMask))); VIXL_ASSERT(IsSignallingNaN(rawbits_to_float(nan_bits & kSRegMask))); for (unsigned i = 0; i < kNumberOfFPRegisters; i++) { set_dreg_bits(i, nan_bits); } // Returning to address 0 exits the Simulator. set_lr(kEndOfSimAddress); } Simulator::~Simulator() { delete[] stack_; // The decoder may outlive the simulator. decoder_->RemoveVisitor(print_disasm_); delete print_disasm_; decoder_->RemoveVisitor(instrumentation_); delete instrumentation_; } void Simulator::Run() { pc_modified_ = false; while (pc_ != kEndOfSimAddress) { ExecuteInstruction(); LogAllWrittenRegisters(); } } void Simulator::RunFrom(const Instruction* first) { set_pc(first); Run(); } const char* Simulator::xreg_names[] = { "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x29", "lr", "xzr", "sp"}; const char* Simulator::wreg_names[] = { "w0", "w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8", "w9", "w10", "w11", "w12", "w13", "w14", "w15", "w16", "w17", "w18", "w19", "w20", "w21", "w22", "w23", "w24", "w25", "w26", "w27", "w28", "w29", "w30", "wzr", "wsp"}; const char* Simulator::sreg_names[] = { "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31"}; const char* Simulator::dreg_names[] = { "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15", "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23", "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31"}; const char* Simulator::vreg_names[] = { "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"}; const char* Simulator::WRegNameForCode(unsigned code, Reg31Mode mode) { VIXL_ASSERT(code < kNumberOfRegisters); // If the code represents the stack pointer, index the name after zr. if ((code == kZeroRegCode) && (mode == Reg31IsStackPointer)) { code = kZeroRegCode + 1; } return wreg_names[code]; } const char* Simulator::XRegNameForCode(unsigned code, Reg31Mode mode) { VIXL_ASSERT(code < kNumberOfRegisters); // If the code represents the stack pointer, index the name after zr. if ((code == kZeroRegCode) && (mode == Reg31IsStackPointer)) { code = kZeroRegCode + 1; } return xreg_names[code]; } const char* Simulator::SRegNameForCode(unsigned code) { VIXL_ASSERT(code < kNumberOfFPRegisters); return sreg_names[code]; } const char* Simulator::DRegNameForCode(unsigned code) { VIXL_ASSERT(code < kNumberOfFPRegisters); return dreg_names[code]; } const char* Simulator::VRegNameForCode(unsigned code) { VIXL_ASSERT(code < kNumberOfVRegisters); return vreg_names[code]; } #define COLOUR(colour_code) "\033[0;" colour_code "m" #define COLOUR_BOLD(colour_code) "\033[1;" colour_code "m" #define NORMAL "" #define GREY "30" #define RED "31" #define GREEN "32" #define YELLOW "33" #define BLUE "34" #define MAGENTA "35" #define CYAN "36" #define WHITE "37" void Simulator::set_coloured_trace(bool value) { coloured_trace_ = value; clr_normal = value ? COLOUR(NORMAL) : ""; clr_flag_name = value ? COLOUR_BOLD(WHITE) : ""; clr_flag_value = value ? COLOUR(NORMAL) : ""; clr_reg_name = value ? COLOUR_BOLD(CYAN) : ""; clr_reg_value = value ? COLOUR(CYAN) : ""; clr_vreg_name = value ? COLOUR_BOLD(MAGENTA) : ""; clr_vreg_value = value ? COLOUR(MAGENTA) : ""; clr_memory_address = value ? COLOUR_BOLD(BLUE) : ""; clr_warning = value ? COLOUR_BOLD(YELLOW) : ""; clr_warning_message = value ? COLOUR(YELLOW) : ""; clr_printf = value ? COLOUR(GREEN) : ""; } void Simulator::set_trace_parameters(int parameters) { bool disasm_before = trace_parameters_ & LOG_DISASM; trace_parameters_ = parameters; bool disasm_after = trace_parameters_ & LOG_DISASM; if (disasm_before != disasm_after) { if (disasm_after) { decoder_->InsertVisitorBefore(print_disasm_, this); } else { decoder_->RemoveVisitor(print_disasm_); } } } void Simulator::set_instruction_stats(bool value) { if (value != instruction_stats_) { if (value) { decoder_->AppendVisitor(instrumentation_); } else { decoder_->RemoveVisitor(instrumentation_); } instruction_stats_ = value; } } // Helpers --------------------------------------------------------------------- uint64_t Simulator::AddWithCarry(unsigned reg_size, bool set_flags, uint64_t left, uint64_t right, int carry_in) { VIXL_ASSERT((carry_in == 0) || (carry_in == 1)); VIXL_ASSERT((reg_size == kXRegSize) || (reg_size == kWRegSize)); uint64_t max_uint = (reg_size == kWRegSize) ? kWMaxUInt : kXMaxUInt; uint64_t reg_mask = (reg_size == kWRegSize) ? kWRegMask : kXRegMask; uint64_t sign_mask = (reg_size == kWRegSize) ? kWSignMask : kXSignMask; left &= reg_mask; right &= reg_mask; uint64_t result = (left + right + carry_in) & reg_mask; if (set_flags) { nzcv().SetN(CalcNFlag(result, reg_size)); nzcv().SetZ(CalcZFlag(result)); // Compute the C flag by comparing the result to the max unsigned integer. uint64_t max_uint_2op = max_uint - carry_in; bool C = (left > max_uint_2op) || ((max_uint_2op - left) < right); nzcv().SetC(C ? 1 : 0); // Overflow iff the sign bit is the same for the two inputs and different // for the result. uint64_t left_sign = left & sign_mask; uint64_t right_sign = right & sign_mask; uint64_t result_sign = result & sign_mask; bool V = (left_sign == right_sign) && (left_sign != result_sign); nzcv().SetV(V ? 1 : 0); LogSystemRegister(NZCV); } return result; } int64_t Simulator::ShiftOperand(unsigned reg_size, int64_t value, Shift shift_type, unsigned amount) { if (amount == 0) { return value; } int64_t mask = reg_size == kXRegSize ? kXRegMask : kWRegMask; switch (shift_type) { case LSL: return (value << amount) & mask; case LSR: return static_cast<uint64_t>(value) >> amount; case ASR: { // Shift used to restore the sign. unsigned s_shift = kXRegSize - reg_size; // Value with its sign restored. int64_t s_value = (value << s_shift) >> s_shift; return (s_value >> amount) & mask; } case ROR: { if (reg_size == kWRegSize) { value &= kWRegMask; } return (static_cast<uint64_t>(value) >> amount) | ((value & ((INT64_C(1) << amount) - 1)) << (reg_size - amount)); } default: VIXL_UNIMPLEMENTED(); return 0; } } int64_t Simulator::ExtendValue(unsigned reg_size, int64_t value, Extend extend_type, unsigned left_shift) { switch (extend_type) { case UXTB: value &= kByteMask; break; case UXTH: value &= kHalfWordMask; break; case UXTW: value &= kWordMask; break; case SXTB: value = (value << 56) >> 56; break; case SXTH: value = (value << 48) >> 48; break; case SXTW: value = (value << 32) >> 32; break; case UXTX: case SXTX: break; default: VIXL_UNREACHABLE(); } int64_t mask = (reg_size == kXRegSize) ? kXRegMask : kWRegMask; return (value << left_shift) & mask; } void Simulator::FPCompare(double val0, double val1, FPTrapFlags trap) { AssertSupportedFPCR(); // TODO: This assumes that the C++ implementation handles comparisons in the // way that we expect (as per AssertSupportedFPCR()). bool process_exception = false; if ((std::isnan(val0) != 0) || (std::isnan(val1) != 0)) { nzcv().SetRawValue(FPUnorderedFlag); if (IsSignallingNaN(val0) || IsSignallingNaN(val1) || (trap == EnableTrap)) { process_exception = true; } } else if (val0 < val1) { nzcv().SetRawValue(FPLessThanFlag); } else if (val0 > val1) { nzcv().SetRawValue(FPGreaterThanFlag); } else if (val0 == val1) { nzcv().SetRawValue(FPEqualFlag); } else { VIXL_UNREACHABLE(); } LogSystemRegister(NZCV); if (process_exception) FPProcessException(); } Simulator::PrintRegisterFormat Simulator::GetPrintRegisterFormatForSize( unsigned reg_size, unsigned lane_size) { VIXL_ASSERT(reg_size >= lane_size); uint32_t format = 0; if (reg_size != lane_size) { switch (reg_size) { default: VIXL_UNREACHABLE(); break; case kQRegSizeInBytes: format = kPrintRegAsQVector; break; case kDRegSizeInBytes: format = kPrintRegAsDVector; break; } } switch (lane_size) { default: VIXL_UNREACHABLE(); break; case kQRegSizeInBytes: format |= kPrintReg1Q; break; case kDRegSizeInBytes: format |= kPrintReg1D; break; case kSRegSizeInBytes: format |= kPrintReg1S; break; case kHRegSizeInBytes: format |= kPrintReg1H; break; case kBRegSizeInBytes: format |= kPrintReg1B; break; } // These sizes would be duplicate case labels. VIXL_STATIC_ASSERT(kXRegSizeInBytes == kDRegSizeInBytes); VIXL_STATIC_ASSERT(kWRegSizeInBytes == kSRegSizeInBytes); VIXL_STATIC_ASSERT(kPrintXReg == kPrintReg1D); VIXL_STATIC_ASSERT(kPrintWReg == kPrintReg1S); return static_cast<PrintRegisterFormat>(format); } Simulator::PrintRegisterFormat Simulator::GetPrintRegisterFormat( VectorFormat vform) { switch (vform) { default: VIXL_UNREACHABLE(); return kPrintReg16B; case kFormat16B: return kPrintReg16B; case kFormat8B: return kPrintReg8B; case kFormat8H: return kPrintReg8H; case kFormat4H: return kPrintReg4H; case kFormat4S: return kPrintReg4S; case kFormat2S: return kPrintReg2S; case kFormat2D: return kPrintReg2D; case kFormat1D: return kPrintReg1D; } } void Simulator::PrintWrittenRegisters() { for (unsigned i = 0; i < kNumberOfRegisters; i++) { if (registers_[i].WrittenSinceLastLog()) PrintRegister(i); } } void Simulator::PrintWrittenVRegisters() { for (unsigned i = 0; i < kNumberOfVRegisters; i++) { // At this point there is no type information, so print as a raw 1Q. if (vregisters_[i].WrittenSinceLastLog()) PrintVRegister(i, kPrintReg1Q); } } void Simulator::PrintSystemRegisters() { PrintSystemRegister(NZCV); PrintSystemRegister(FPCR); } void Simulator::PrintRegisters() { for (unsigned i = 0; i < kNumberOfRegisters; i++) { PrintRegister(i); } } void Simulator::PrintVRegisters() { for (unsigned i = 0; i < kNumberOfVRegisters; i++) { // At this point there is no type information, so print as a raw 1Q. PrintVRegister(i, kPrintReg1Q); } } // Print a register's name and raw value. // // Only the least-significant `size_in_bytes` bytes of the register are printed, // but the value is aligned as if the whole register had been printed. // // For typical register updates, size_in_bytes should be set to kXRegSizeInBytes // -- the default -- so that the whole register is printed. Other values of // size_in_bytes are intended for use when the register hasn't actually been // updated (such as in PrintWrite). // // No newline is printed. This allows the caller to print more details (such as // a memory access annotation). void Simulator::PrintRegisterRawHelper(unsigned code, Reg31Mode r31mode, int size_in_bytes) { // The template for all supported sizes. // "# x{code}: 0xffeeddccbbaa9988" // "# w{code}: 0xbbaa9988" // "# w{code}<15:0>: 0x9988" // "# w{code}<7:0>: 0x88" unsigned padding_chars = (kXRegSizeInBytes - size_in_bytes) * 2; const char * name = ""; const char * suffix = ""; switch (size_in_bytes) { case kXRegSizeInBytes: name = XRegNameForCode(code, r31mode); break; case kWRegSizeInBytes: name = WRegNameForCode(code, r31mode); break; case 2: name = WRegNameForCode(code, r31mode); suffix = "<15:0>"; padding_chars -= strlen(suffix); break; case 1: name = WRegNameForCode(code, r31mode); suffix = "<7:0>"; padding_chars -= strlen(suffix); break; default: VIXL_UNREACHABLE(); } fprintf(stream_, "# %s%5s%s: ", clr_reg_name, name, suffix); // Print leading padding spaces. VIXL_ASSERT(padding_chars < (kXRegSizeInBytes * 2)); for (unsigned i = 0; i < padding_chars; i++) { putc(' ', stream_); } // Print the specified bits in hexadecimal format. uint64_t bits = reg<uint64_t>(code, r31mode); bits &= kXRegMask >> ((kXRegSizeInBytes - size_in_bytes) * 8); VIXL_STATIC_ASSERT(sizeof(bits) == kXRegSizeInBytes); int chars = size_in_bytes * 2; fprintf(stream_, "%s0x%0*" PRIx64 "%s", clr_reg_value, chars, bits, clr_normal); } void Simulator::PrintRegister(unsigned code, Reg31Mode r31mode) { registers_[code].NotifyRegisterLogged(); // Don't print writes into xzr. if ((code == kZeroRegCode) && (r31mode == Reg31IsZeroRegister)) { return; } // The template for all x and w registers: // "# x{code}: 0x{value}" // "# w{code}: 0x{value}" PrintRegisterRawHelper(code, r31mode); fprintf(stream_, "\n"); } // Print a register's name and raw value. // // The `bytes` and `lsb` arguments can be used to limit the bytes that are // printed. These arguments are intended for use in cases where register hasn't // actually been updated (such as in PrintVWrite). // // No newline is printed. This allows the caller to print more details (such as // a floating-point interpretation or a memory access annotation). void Simulator::PrintVRegisterRawHelper(unsigned code, int bytes, int lsb) { // The template for vector types: // "# v{code}: 0xffeeddccbbaa99887766554433221100". // An example with bytes=4 and lsb=8: // "# v{code}: 0xbbaa9988 ". fprintf(stream_, "# %s%5s: %s", clr_vreg_name, VRegNameForCode(code), clr_vreg_value); int msb = lsb + bytes - 1; int byte = kQRegSizeInBytes - 1; // Print leading padding spaces. (Two spaces per byte.) while (byte > msb) { fprintf(stream_, " "); byte--; } // Print the specified part of the value, byte by byte. qreg_t rawbits = qreg(code); fprintf(stream_, "0x"); while (byte >= lsb) { fprintf(stream_, "%02x", rawbits.val[byte]); byte--; } // Print trailing padding spaces. while (byte >= 0) { fprintf(stream_, " "); byte--; } fprintf(stream_, "%s", clr_normal); } // Print each of the specified lanes of a register as a float or double value. // // The `lane_count` and `lslane` arguments can be used to limit the lanes that // are printed. These arguments are intended for use in cases where register // hasn't actually been updated (such as in PrintVWrite). // // No newline is printed. This allows the caller to print more details (such as // a memory access annotation). void Simulator::PrintVRegisterFPHelper(unsigned code, unsigned lane_size_in_bytes, int lane_count, int rightmost_lane) { VIXL_ASSERT((lane_size_in_bytes == kSRegSizeInBytes) || (lane_size_in_bytes == kDRegSizeInBytes)); unsigned msb = ((lane_count + rightmost_lane) * lane_size_in_bytes); VIXL_ASSERT(msb <= kQRegSizeInBytes); // For scalar types ((lane_count == 1) && (rightmost_lane == 0)), a register // name is used: // " (s{code}: {value})" // " (d{code}: {value})" // For vector types, "..." is used to represent one or more omitted lanes. // " (..., {value}, {value}, ...)" if ((lane_count == 1) && (rightmost_lane == 0)) { const char * name = (lane_size_in_bytes == kSRegSizeInBytes) ? SRegNameForCode(code) : DRegNameForCode(code); fprintf(stream_, " (%s%s: ", clr_vreg_name, name); } else { if (msb < (kQRegSizeInBytes - 1)) { fprintf(stream_, " (..., "); } else { fprintf(stream_, " ("); } } // Print the list of values. const char * separator = ""; int leftmost_lane = rightmost_lane + lane_count - 1; for (int lane = leftmost_lane; lane >= rightmost_lane; lane--) { double value = (lane_size_in_bytes == kSRegSizeInBytes) ? vreg(code).Get<float>(lane) : vreg(code).Get<double>(lane); fprintf(stream_, "%s%s%#g%s", separator, clr_vreg_value, value, clr_normal); separator = ", "; } if (rightmost_lane > 0) { fprintf(stream_, ", ..."); } fprintf(stream_, ")"); } void Simulator::PrintVRegister(unsigned code, PrintRegisterFormat format) { vregisters_[code].NotifyRegisterLogged(); int lane_size_log2 = format & kPrintRegLaneSizeMask; int reg_size_log2; if (format & kPrintRegAsQVector) { reg_size_log2 = kQRegSizeInBytesLog2; } else if (format & kPrintRegAsDVector) { reg_size_log2 = kDRegSizeInBytesLog2; } else { // Scalar types. reg_size_log2 = lane_size_log2; } int lane_count = 1 << (reg_size_log2 - lane_size_log2); int lane_size = 1 << lane_size_log2; // The template for vector types: // "# v{code}: 0x{rawbits} (..., {value}, ...)". // The template for scalar types: // "# v{code}: 0x{rawbits} ({reg}:{value})". // The values in parentheses after the bit representations are floating-point // interpretations. They are displayed only if the kPrintVRegAsFP bit is set. PrintVRegisterRawHelper(code); if (format & kPrintRegAsFP) { PrintVRegisterFPHelper(code, lane_size, lane_count); } fprintf(stream_, "\n"); } void Simulator::PrintSystemRegister(SystemRegister id) { switch (id) { case NZCV: fprintf(stream_, "# %sNZCV: %sN:%d Z:%d C:%d V:%d%s\n", clr_flag_name, clr_flag_value, nzcv().N(), nzcv().Z(), nzcv().C(), nzcv().V(), clr_normal); break; case FPCR: { static const char * rmode[] = { "0b00 (Round to Nearest)", "0b01 (Round towards Plus Infinity)", "0b10 (Round towards Minus Infinity)", "0b11 (Round towards Zero)" }; VIXL_ASSERT(fpcr().RMode() < (sizeof(rmode) / sizeof(rmode[0]))); fprintf(stream_, "# %sFPCR: %sAHP:%d DN:%d FZ:%d RMode:%s%s\n", clr_flag_name, clr_flag_value, fpcr().AHP(), fpcr().DN(), fpcr().FZ(), rmode[fpcr().RMode()], clr_normal); break; } default: VIXL_UNREACHABLE(); } } void Simulator::PrintRead(uintptr_t address, unsigned reg_code, PrintRegisterFormat format) { registers_[reg_code].NotifyRegisterLogged(); USE(format); // The template is "# {reg}: 0x{value} <- {address}". PrintRegisterRawHelper(reg_code, Reg31IsZeroRegister); fprintf(stream_, " <- %s0x%016" PRIxPTR "%s\n", clr_memory_address, address, clr_normal); } void Simulator::PrintVRead(uintptr_t address, unsigned reg_code, PrintRegisterFormat format, unsigned lane) { vregisters_[reg_code].NotifyRegisterLogged(); // The template is "# v{code}: 0x{rawbits} <- address". PrintVRegisterRawHelper(reg_code); if (format & kPrintRegAsFP) { PrintVRegisterFPHelper(reg_code, GetPrintRegLaneSizeInBytes(format), GetPrintRegLaneCount(format), lane); } fprintf(stream_, " <- %s0x%016" PRIxPTR "%s\n", clr_memory_address, address, clr_normal); } void Simulator::PrintWrite(uintptr_t address, unsigned reg_code, PrintRegisterFormat format) { VIXL_ASSERT(GetPrintRegLaneCount(format) == 1); // The template is "# v{code}: 0x{value} -> {address}". To keep the trace tidy // and readable, the value is aligned with the values in the register trace. PrintRegisterRawHelper(reg_code, Reg31IsZeroRegister, GetPrintRegSizeInBytes(format)); fprintf(stream_, " -> %s0x%016" PRIxPTR "%s\n", clr_memory_address, address, clr_normal); } void Simulator::PrintVWrite(uintptr_t address, unsigned reg_code, PrintRegisterFormat format, unsigned lane) { // The templates: // "# v{code}: 0x{rawbits} -> {address}" // "# v{code}: 0x{rawbits} (..., {value}, ...) -> {address}". // "# v{code}: 0x{rawbits} ({reg}:{value}) -> {address}" // Because this trace doesn't represent a change to the source register's // value, only the relevant part of the value is printed. To keep the trace // tidy and readable, the raw value is aligned with the other values in the // register trace. int lane_count = GetPrintRegLaneCount(format); int lane_size = GetPrintRegLaneSizeInBytes(format); int reg_size = GetPrintRegSizeInBytes(format); PrintVRegisterRawHelper(reg_code, reg_size, lane_size * lane); if (format & kPrintRegAsFP) { PrintVRegisterFPHelper(reg_code, lane_size, lane_count, lane); } fprintf(stream_, " -> %s0x%016" PRIxPTR "%s\n", clr_memory_address, address, clr_normal); } // Visitors--------------------------------------------------------------------- void Simulator::VisitUnimplemented(const Instruction* instr) { printf("Unimplemented instruction at %p: 0x%08" PRIx32 "\n", reinterpret_cast<const void*>(instr), instr->InstructionBits()); VIXL_UNIMPLEMENTED(); } void Simulator::VisitUnallocated(const Instruction* instr) { printf("Unallocated instruction at %p: 0x%08" PRIx32 "\n", reinterpret_cast<const void*>(instr), instr->InstructionBits()); VIXL_UNIMPLEMENTED(); } void Simulator::VisitPCRelAddressing(const Instruction* instr) { VIXL_ASSERT((instr->Mask(PCRelAddressingMask) == ADR) || (instr->Mask(PCRelAddressingMask) == ADRP)); set_reg(instr->Rd(), instr->ImmPCOffsetTarget()); } void Simulator::VisitUnconditionalBranch(const Instruction* instr) { switch (instr->Mask(UnconditionalBranchMask)) { case BL: set_lr(instr->NextInstruction()); VIXL_FALLTHROUGH(); case B: set_pc(instr->ImmPCOffsetTarget()); break; default: VIXL_UNREACHABLE(); } } void Simulator::VisitConditionalBranch(const Instruction* instr) { VIXL_ASSERT(instr->Mask(ConditionalBranchMask) == B_cond); if (ConditionPassed(instr->ConditionBranch())) { set_pc(instr->ImmPCOffsetTarget()); } } void Simulator::VisitUnconditionalBranchToRegister(const Instruction* instr) { const Instruction* target = Instruction::Cast(xreg(instr->Rn())); switch (instr->Mask(UnconditionalBranchToRegisterMask)) { case BLR: set_lr(instr->NextInstruction()); VIXL_FALLTHROUGH(); case BR: case RET: set_pc(target); break; default: VIXL_UNREACHABLE(); } } void Simulator::VisitTestBranch(const Instruction* instr) { unsigned bit_pos = (instr->ImmTestBranchBit5() << 5) | instr->ImmTestBranchBit40(); bool bit_zero = ((xreg(instr->Rt()) >> bit_pos) & 1) == 0; bool take_branch = false; switch (instr->Mask(TestBranchMask)) { case TBZ: take_branch = bit_zero; break; case TBNZ: take_branch = !bit_zero; break; default: VIXL_UNIMPLEMENTED(); } if (take_branch) { set_pc(instr->ImmPCOffsetTarget()); } } void Simulator::VisitCompareBranch(const Instruction* instr) { unsigned rt = instr->Rt(); bool take_branch = false; switch (instr->Mask(CompareBranchMask)) { case CBZ_w: take_branch = (wreg(rt) == 0); break; case CBZ_x: take_branch = (xreg(rt) == 0); break; case CBNZ_w: take_branch = (wreg(rt) != 0); break; case CBNZ_x: take_branch = (xreg(rt) != 0); break; default: VIXL_UNIMPLEMENTED(); } if (take_branch) { set_pc(instr->ImmPCOffsetTarget()); } } void Simulator::AddSubHelper(const Instruction* instr, int64_t op2) { unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; bool set_flags = instr->FlagsUpdate(); int64_t new_val = 0; Instr operation = instr->Mask(AddSubOpMask); switch (operation) { case ADD: case ADDS: { new_val = AddWithCarry(reg_size, set_flags, reg(reg_size, instr->Rn(), instr->RnMode()), op2); break; } case SUB: case SUBS: { new_val = AddWithCarry(reg_size, set_flags, reg(reg_size, instr->Rn(), instr->RnMode()), ~op2, 1); break; } default: VIXL_UNREACHABLE(); } set_reg(reg_size, instr->Rd(), new_val, LogRegWrites, instr->RdMode()); } void Simulator::VisitAddSubShifted(const Instruction* instr) { unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; int64_t op2 = ShiftOperand(reg_size, reg(reg_size, instr->Rm()), static_cast<Shift>(instr->ShiftDP()), instr->ImmDPShift()); AddSubHelper(instr, op2); } void Simulator::VisitAddSubImmediate(const Instruction* instr) { int64_t op2 = instr->ImmAddSub() << ((instr->ShiftAddSub() == 1) ? 12 : 0); AddSubHelper(instr, op2); } void Simulator::VisitAddSubExtended(const Instruction* instr) { unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; int64_t op2 = ExtendValue(reg_size, reg(reg_size, instr->Rm()), static_cast<Extend>(instr->ExtendMode()), instr->ImmExtendShift()); AddSubHelper(instr, op2); } void Simulator::VisitAddSubWithCarry(const Instruction* instr) { unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; int64_t op2 = reg(reg_size, instr->Rm()); int64_t new_val; if ((instr->Mask(AddSubOpMask) == SUB) || instr->Mask(AddSubOpMask) == SUBS) { op2 = ~op2; } new_val = AddWithCarry(reg_size, instr->FlagsUpdate(), reg(reg_size, instr->Rn()), op2, C()); set_reg(reg_size, instr->Rd(), new_val); } void Simulator::VisitLogicalShifted(const Instruction* instr) { unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; Shift shift_type = static_cast<Shift>(instr->ShiftDP()); unsigned shift_amount = instr->ImmDPShift(); int64_t op2 = ShiftOperand(reg_size, reg(reg_size, instr->Rm()), shift_type, shift_amount); if (instr->Mask(NOT) == NOT) { op2 = ~op2; } LogicalHelper(instr, op2); } void Simulator::VisitLogicalImmediate(const Instruction* instr) { LogicalHelper(instr, instr->ImmLogical()); } void Simulator::LogicalHelper(const Instruction* instr, int64_t op2) { unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; int64_t op1 = reg(reg_size, instr->Rn()); int64_t result = 0; bool update_flags = false; // Switch on the logical operation, stripping out the NOT bit, as it has a // different meaning for logical immediate instructions. switch (instr->Mask(LogicalOpMask & ~NOT)) { case ANDS: update_flags = true; VIXL_FALLTHROUGH(); case AND: result = op1 & op2; break; case ORR: result = op1 | op2; break; case EOR: result = op1 ^ op2; break; default: VIXL_UNIMPLEMENTED(); } if (update_flags) { nzcv().SetN(CalcNFlag(result, reg_size)); nzcv().SetZ(CalcZFlag(result)); nzcv().SetC(0); nzcv().SetV(0); LogSystemRegister(NZCV); } set_reg(reg_size, instr->Rd(), result, LogRegWrites, instr->RdMode()); } void Simulator::VisitConditionalCompareRegister(const Instruction* instr) { unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; ConditionalCompareHelper(instr, reg(reg_size, instr->Rm())); } void Simulator::VisitConditionalCompareImmediate(const Instruction* instr) { ConditionalCompareHelper(instr, instr->ImmCondCmp()); } void Simulator::ConditionalCompareHelper(const Instruction* instr, int64_t op2) { unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; int64_t op1 = reg(reg_size, instr->Rn()); if (ConditionPassed(instr->Condition())) { // If the condition passes, set the status flags to the result of comparing // the operands. if (instr->Mask(ConditionalCompareMask) == CCMP) { AddWithCarry(reg_size, true, op1, ~op2, 1); } else { VIXL_ASSERT(instr->Mask(ConditionalCompareMask) == CCMN); AddWithCarry(reg_size, true, op1, op2, 0); } } else { // If the condition fails, set the status flags to the nzcv immediate. nzcv().SetFlags(instr->Nzcv()); LogSystemRegister(NZCV); } } void Simulator::VisitLoadStoreUnsignedOffset(const Instruction* instr) { int offset = instr->ImmLSUnsigned() << instr->SizeLS(); LoadStoreHelper(instr, offset, Offset); } void Simulator::VisitLoadStoreUnscaledOffset(const Instruction* instr) { LoadStoreHelper(instr, instr->ImmLS(), Offset); } void Simulator::VisitLoadStorePreIndex(const Instruction* instr) { LoadStoreHelper(instr, instr->ImmLS(), PreIndex); } void Simulator::VisitLoadStorePostIndex(const Instruction* instr) { LoadStoreHelper(instr, instr->ImmLS(), PostIndex); } void Simulator::VisitLoadStoreRegisterOffset(const Instruction* instr) { Extend ext = static_cast<Extend>(instr->ExtendMode()); VIXL_ASSERT((ext == UXTW) || (ext == UXTX) || (ext == SXTW) || (ext == SXTX)); unsigned shift_amount = instr->ImmShiftLS() * instr->SizeLS(); int64_t offset = ExtendValue(kXRegSize, xreg(instr->Rm()), ext, shift_amount); LoadStoreHelper(instr, offset, Offset); } void Simulator::LoadStoreHelper(const Instruction* instr, int64_t offset, AddrMode addrmode) { unsigned srcdst = instr->Rt(); uintptr_t address = AddressModeHelper(instr->Rn(), offset, addrmode); LoadStoreOp op = static_cast<LoadStoreOp>(instr->Mask(LoadStoreMask)); switch (op) { case LDRB_w: set_wreg(srcdst, Memory::Read<uint8_t>(address), NoRegLog); break; case LDRH_w: set_wreg(srcdst, Memory::Read<uint16_t>(address), NoRegLog); break; case LDR_w: set_wreg(srcdst, Memory::Read<uint32_t>(address), NoRegLog); break; case LDR_x: set_xreg(srcdst, Memory::Read<uint64_t>(address), NoRegLog); break; case LDRSB_w: set_wreg(srcdst, Memory::Read<int8_t>(address), NoRegLog); break; case LDRSH_w: set_wreg(srcdst, Memory::Read<int16_t>(address), NoRegLog); break; case LDRSB_x: set_xreg(srcdst, Memory::Read<int8_t>(address), NoRegLog); break; case LDRSH_x: set_xreg(srcdst, Memory::Read<int16_t>(address), NoRegLog); break; case LDRSW_x: set_xreg(srcdst, Memory::Read<int32_t>(address), NoRegLog); break; case LDR_b: set_breg(srcdst, Memory::Read<uint8_t>(address), NoRegLog); break; case LDR_h: set_hreg(srcdst, Memory::Read<uint16_t>(address), NoRegLog); break; case LDR_s: set_sreg(srcdst, Memory::Read<float>(address), NoRegLog); break; case LDR_d: set_dreg(srcdst, Memory::Read<double>(address), NoRegLog); break; case LDR_q: set_qreg(srcdst, Memory::Read<qreg_t>(address), NoRegLog); break; case STRB_w: Memory::Write<uint8_t>(address, wreg(srcdst)); break; case STRH_w: Memory::Write<uint16_t>(address, wreg(srcdst)); break; case STR_w: Memory::Write<uint32_t>(address, wreg(srcdst)); break; case STR_x: Memory::Write<uint64_t>(address, xreg(srcdst)); break; case STR_b: Memory::Write<uint8_t>(address, breg(srcdst)); break; case STR_h: Memory::Write<uint16_t>(address, hreg(srcdst)); break; case STR_s: Memory::Write<float>(address, sreg(srcdst)); break; case STR_d: Memory::Write<double>(address, dreg(srcdst)); break; case STR_q: Memory::Write<qreg_t>(address, qreg(srcdst)); break; // Ignore prfm hint instructions. case PRFM: break; default: VIXL_UNIMPLEMENTED(); } unsigned access_size = 1 << instr->SizeLS(); if (instr->IsLoad()) { if ((op == LDR_s) || (op == LDR_d)) { LogVRead(address, srcdst, GetPrintRegisterFormatForSizeFP(access_size)); } else if ((op == LDR_b) || (op == LDR_h) || (op == LDR_q)) { LogVRead(address, srcdst, GetPrintRegisterFormatForSize(access_size)); } else { LogRead(address, srcdst, GetPrintRegisterFormatForSize(access_size)); } } else { if ((op == STR_s) || (op == STR_d)) { LogVWrite(address, srcdst, GetPrintRegisterFormatForSizeFP(access_size)); } else if ((op == STR_b) || (op == STR_h) || (op == STR_q)) { LogVWrite(address, srcdst, GetPrintRegisterFormatForSize(access_size)); } else { LogWrite(address, srcdst, GetPrintRegisterFormatForSize(access_size)); } } local_monitor_.MaybeClear(); } void Simulator::VisitLoadStorePairOffset(const Instruction* instr) { LoadStorePairHelper(instr, Offset); } void Simulator::VisitLoadStorePairPreIndex(const Instruction* instr) { LoadStorePairHelper(instr, PreIndex); } void Simulator::VisitLoadStorePairPostIndex(const Instruction* instr) { LoadStorePairHelper(instr, PostIndex); } void Simulator::VisitLoadStorePairNonTemporal(const Instruction* instr) { LoadStorePairHelper(instr, Offset); } void Simulator::LoadStorePairHelper(const Instruction* instr, AddrMode addrmode) { unsigned rt = instr->Rt(); unsigned rt2 = instr->Rt2(); int element_size = 1 << instr->SizeLSPair(); int64_t offset = instr->ImmLSPair() * element_size; uintptr_t address = AddressModeHelper(instr->Rn(), offset, addrmode); uintptr_t address2 = address + element_size; LoadStorePairOp op = static_cast<LoadStorePairOp>(instr->Mask(LoadStorePairMask)); // 'rt' and 'rt2' can only be aliased for stores. VIXL_ASSERT(((op & LoadStorePairLBit) == 0) || (rt != rt2)); switch (op) { // Use NoRegLog to suppress the register trace (LOG_REGS, LOG_FP_REGS). We // will print a more detailed log. case LDP_w: { set_wreg(rt, Memory::Read<uint32_t>(address), NoRegLog); set_wreg(rt2, Memory::Read<uint32_t>(address2), NoRegLog); break; } case LDP_s: { set_sreg(rt, Memory::Read<float>(address), NoRegLog); set_sreg(rt2, Memory::Read<float>(address2), NoRegLog); break; } case LDP_x: { set_xreg(rt, Memory::Read<uint64_t>(address), NoRegLog); set_xreg(rt2, Memory::Read<uint64_t>(address2), NoRegLog); break; } case LDP_d: { set_dreg(rt, Memory::Read<double>(address), NoRegLog); set_dreg(rt2, Memory::Read<double>(address2), NoRegLog); break; } case LDP_q: { set_qreg(rt, Memory::Read<qreg_t>(address), NoRegLog); set_qreg(rt2, Memory::Read<qreg_t>(address2), NoRegLog); break; } case LDPSW_x: { set_xreg(rt, Memory::Read<int32_t>(address), NoRegLog); set_xreg(rt2, Memory::Read<int32_t>(address2), NoRegLog); break; } case STP_w: { Memory::Write<uint32_t>(address, wreg(rt)); Memory::Write<uint32_t>(address2, wreg(rt2)); break; } case STP_s: { Memory::Write<float>(address, sreg(rt)); Memory::Write<float>(address2, sreg(rt2)); break; } case STP_x: { Memory::Write<uint64_t>(address, xreg(rt)); Memory::Write<uint64_t>(address2, xreg(rt2)); break; } case STP_d: { Memory::Write<double>(address, dreg(rt)); Memory::Write<double>(address2, dreg(rt2)); break; } case STP_q: { Memory::Write<qreg_t>(address, qreg(rt)); Memory::Write<qreg_t>(address2, qreg(rt2)); break; } default: VIXL_UNREACHABLE(); } // Print a detailed trace (including the memory address) instead of the basic // register:value trace generated by set_*reg(). if (instr->IsLoad()) { if ((op == LDP_s) || (op == LDP_d)) { LogVRead(address, rt, GetPrintRegisterFormatForSizeFP(element_size)); LogVRead(address2, rt2, GetPrintRegisterFormatForSizeFP(element_size)); } else if (op == LDP_q) { LogVRead(address, rt, GetPrintRegisterFormatForSize(element_size)); LogVRead(address2, rt2, GetPrintRegisterFormatForSize(element_size)); } else { LogRead(address, rt, GetPrintRegisterFormatForSize(element_size)); LogRead(address2, rt2, GetPrintRegisterFormatForSize(element_size)); } } else { if ((op == STP_s) || (op == STP_d)) { LogVWrite(address, rt, GetPrintRegisterFormatForSizeFP(element_size)); LogVWrite(address2, rt2, GetPrintRegisterFormatForSizeFP(element_size)); } else if (op == STP_q) { LogVWrite(address, rt, GetPrintRegisterFormatForSize(element_size)); LogVWrite(address2, rt2, GetPrintRegisterFormatForSize(element_size)); } else { LogWrite(address, rt, GetPrintRegisterFormatForSize(element_size)); LogWrite(address2, rt2, GetPrintRegisterFormatForSize(element_size)); } } local_monitor_.MaybeClear(); } void Simulator::PrintExclusiveAccessWarning() { if (print_exclusive_access_warning_) { fprintf( stderr, "%sWARNING:%s VIXL simulator support for load-/store-/clear-exclusive " "instructions is limited. Refer to the README for details.%s\n", clr_warning, clr_warning_message, clr_normal); print_exclusive_access_warning_ = false; } } void Simulator::VisitLoadStoreExclusive(const Instruction* instr) { PrintExclusiveAccessWarning(); unsigned rs = instr->Rs(); unsigned rt = instr->Rt(); unsigned rt2 = instr->Rt2(); unsigned rn = instr->Rn(); LoadStoreExclusive op = static_cast<LoadStoreExclusive>(instr->Mask(LoadStoreExclusiveMask)); bool is_acquire_release = instr->LdStXAcquireRelease(); bool is_exclusive = !instr->LdStXNotExclusive(); bool is_load = instr->LdStXLoad(); bool is_pair = instr->LdStXPair(); unsigned element_size = 1 << instr->LdStXSizeLog2(); unsigned access_size = is_pair ? element_size * 2 : element_size; uint64_t address = reg<uint64_t>(rn, Reg31IsStackPointer); // Verify that the address is available to the host. VIXL_ASSERT(address == static_cast<uintptr_t>(address)); // Check the alignment of `address`. if (AlignDown(address, access_size) != address) { VIXL_ALIGNMENT_EXCEPTION(); } // The sp must be aligned to 16 bytes when it is accessed. if ((rn == 31) && (AlignDown(address, 16) != address)) { VIXL_ALIGNMENT_EXCEPTION(); } if (is_load) { if (is_exclusive) { local_monitor_.MarkExclusive(address, access_size); } else { // Any non-exclusive load can clear the local monitor as a side effect. We // don't need to do this, but it is useful to stress the simulated code. local_monitor_.Clear(); } // Use NoRegLog to suppress the register trace (LOG_REGS, LOG_FP_REGS). We // will print a more detailed log. switch (op) { case LDXRB_w: case LDAXRB_w: case LDARB_w: set_wreg(rt, Memory::Read<uint8_t>(address), NoRegLog); break; case LDXRH_w: case LDAXRH_w: case LDARH_w: set_wreg(rt, Memory::Read<uint16_t>(address), NoRegLog); break; case LDXR_w: case LDAXR_w: case LDAR_w: set_wreg(rt, Memory::Read<uint32_t>(address), NoRegLog); break; case LDXR_x: case LDAXR_x: case LDAR_x: set_xreg(rt, Memory::Read<uint64_t>(address), NoRegLog); break; case LDXP_w: case LDAXP_w: set_wreg(rt, Memory::Read<uint32_t>(address), NoRegLog); set_wreg(rt2, Memory::Read<uint32_t>(address + element_size), NoRegLog); break; case LDXP_x: case LDAXP_x: set_xreg(rt, Memory::Read<uint64_t>(address), NoRegLog); set_xreg(rt2, Memory::Read<uint64_t>(address + element_size), NoRegLog); break; default: VIXL_UNREACHABLE(); } if (is_acquire_release) { // Approximate load-acquire by issuing a full barrier after the load. __sync_synchronize(); } LogRead(address, rt, GetPrintRegisterFormatForSize(element_size)); if (is_pair) { LogRead(address + element_size, rt2, GetPrintRegisterFormatForSize(element_size)); } } else { if (is_acquire_release) { // Approximate store-release by issuing a full barrier before the store. __sync_synchronize(); } bool do_store = true; if (is_exclusive) { do_store = local_monitor_.IsExclusive(address, access_size) && global_monitor_.IsExclusive(address, access_size); set_wreg(rs, do_store ? 0 : 1); // - All exclusive stores explicitly clear the local monitor. local_monitor_.Clear(); } else { // - Any other store can clear the local monitor as a side effect. local_monitor_.MaybeClear(); } if (do_store) { switch (op) { case STXRB_w: case STLXRB_w: case STLRB_w: Memory::Write<uint8_t>(address, wreg(rt)); break; case STXRH_w: case STLXRH_w: case STLRH_w: Memory::Write<uint16_t>(address, wreg(rt)); break; case STXR_w: case STLXR_w: case STLR_w: Memory::Write<uint32_t>(address, wreg(rt)); break; case STXR_x: case STLXR_x: case STLR_x: Memory::Write<uint64_t>(address, xreg(rt)); break; case STXP_w: case STLXP_w: Memory::Write<uint32_t>(address, wreg(rt)); Memory::Write<uint32_t>(address + element_size, wreg(rt2)); break; case STXP_x: case STLXP_x: Memory::Write<uint64_t>(address, xreg(rt)); Memory::Write<uint64_t>(address + element_size, xreg(rt2)); break; default: VIXL_UNREACHABLE(); } LogWrite(address, rt, GetPrintRegisterFormatForSize(element_size)); if (is_pair) { LogWrite(address + element_size, rt2, GetPrintRegisterFormatForSize(element_size)); } } } } void Simulator::VisitLoadLiteral(const Instruction* instr) { unsigned rt = instr->Rt(); uint64_t address = instr->LiteralAddress<uint64_t>(); // Verify that the calculated address is available to the host. VIXL_ASSERT(address == static_cast<uintptr_t>(address)); switch (instr->Mask(LoadLiteralMask)) { // Use NoRegLog to suppress the register trace (LOG_REGS, LOG_VREGS), then // print a more detailed log. case LDR_w_lit: set_wreg(rt, Memory::Read<uint32_t>(address), NoRegLog); LogRead(address, rt, kPrintWReg); break; case LDR_x_lit: set_xreg(rt, Memory::Read<uint64_t>(address), NoRegLog); LogRead(address, rt, kPrintXReg); break; case LDR_s_lit: set_sreg(rt, Memory::Read<float>(address), NoRegLog); LogVRead(address, rt, kPrintSReg); break; case LDR_d_lit: set_dreg(rt, Memory::Read<double>(address), NoRegLog); LogVRead(address, rt, kPrintDReg); break; case LDR_q_lit: set_qreg(rt, Memory::Read<qreg_t>(address), NoRegLog); LogVRead(address, rt, kPrintReg1Q); break; case LDRSW_x_lit: set_xreg(rt, Memory::Read<int32_t>(address), NoRegLog); LogRead(address, rt, kPrintWReg); break; // Ignore prfm hint instructions. case PRFM_lit: break; default: VIXL_UNREACHABLE(); } local_monitor_.MaybeClear(); } uintptr_t Simulator::AddressModeHelper(unsigned addr_reg, int64_t offset, AddrMode addrmode) { uint64_t address = xreg(addr_reg, Reg31IsStackPointer); if ((addr_reg == 31) && ((address % 16) != 0)) { // When the base register is SP the stack pointer is required to be // quadword aligned prior to the address calculation and write-backs. // Misalignment will cause a stack alignment fault. VIXL_ALIGNMENT_EXCEPTION(); } if ((addrmode == PreIndex) || (addrmode == PostIndex)) { VIXL_ASSERT(offset != 0); // Only preindex should log the register update here. For Postindex, the // update will be printed automatically by LogWrittenRegisters _after_ the // memory access itself is logged. RegLogMode log_mode = (addrmode == PreIndex) ? LogRegWrites : NoRegLog; set_xreg(addr_reg, address + offset, log_mode, Reg31IsStackPointer); } if ((addrmode == Offset) || (addrmode == PreIndex)) { address += offset; } // Verify that the calculated address is available to the host. VIXL_ASSERT(address == static_cast<uintptr_t>(address)); return static_cast<uintptr_t>(address); } void Simulator::VisitMoveWideImmediate(const Instruction* instr) { MoveWideImmediateOp mov_op = static_cast<MoveWideImmediateOp>(instr->Mask(MoveWideImmediateMask)); int64_t new_xn_val = 0; bool is_64_bits = instr->SixtyFourBits() == 1; // Shift is limited for W operations. VIXL_ASSERT(is_64_bits || (instr->ShiftMoveWide() < 2)); // Get the shifted immediate. int64_t shift = instr->ShiftMoveWide() * 16; int64_t shifted_imm16 = static_cast<int64_t>(instr->ImmMoveWide()) << shift; // Compute the new value. switch (mov_op) { case MOVN_w: case MOVN_x: { new_xn_val = ~shifted_imm16; if (!is_64_bits) new_xn_val &= kWRegMask; break; } case MOVK_w: case MOVK_x: { unsigned reg_code = instr->Rd(); int64_t prev_xn_val = is_64_bits ? xreg(reg_code) : wreg(reg_code); new_xn_val = (prev_xn_val & ~(INT64_C(0xffff) << shift)) | shifted_imm16; break; } case MOVZ_w: case MOVZ_x: { new_xn_val = shifted_imm16; break; } default: VIXL_UNREACHABLE(); } // Update the destination register. set_xreg(instr->Rd(), new_xn_val); } void Simulator::VisitConditionalSelect(const Instruction* instr) { uint64_t new_val = xreg(instr->Rn()); if (ConditionFailed(static_cast<Condition>(instr->Condition()))) { new_val = xreg(instr->Rm()); switch (instr->Mask(ConditionalSelectMask)) { case CSEL_w: case CSEL_x: break; case CSINC_w: case CSINC_x: new_val++; break; case CSINV_w: case CSINV_x: new_val = ~new_val; break; case CSNEG_w: case CSNEG_x: new_val = -new_val; break; default: VIXL_UNIMPLEMENTED(); } } unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; set_reg(reg_size, instr->Rd(), new_val); } void Simulator::VisitDataProcessing1Source(const Instruction* instr) { unsigned dst = instr->Rd(); unsigned src = instr->Rn(); switch (instr->Mask(DataProcessing1SourceMask)) { case RBIT_w: set_wreg(dst, ReverseBits(wreg(src))); break; case RBIT_x: set_xreg(dst, ReverseBits(xreg(src))); break; case REV16_w: set_wreg(dst, ReverseBytes(wreg(src), 1)); break; case REV16_x: set_xreg(dst, ReverseBytes(xreg(src), 1)); break; case REV_w: set_wreg(dst, ReverseBytes(wreg(src), 2)); break; case REV32_x: set_xreg(dst, ReverseBytes(xreg(src), 2)); break; case REV_x: set_xreg(dst, ReverseBytes(xreg(src), 3)); break; case CLZ_w: set_wreg(dst, CountLeadingZeros(wreg(src))); break; case CLZ_x: set_xreg(dst, CountLeadingZeros(xreg(src))); break; case CLS_w: { set_wreg(dst, CountLeadingSignBits(wreg(src))); break; } case CLS_x: { set_xreg(dst, CountLeadingSignBits(xreg(src))); break; } default: VIXL_UNIMPLEMENTED(); } } uint32_t Simulator::Poly32Mod2(unsigned n, uint64_t data, uint32_t poly) { VIXL_ASSERT((n > 32) && (n <= 64)); for (unsigned i = (n - 1); i >= 32; i--) { if (((data >> i) & 1) != 0) { uint64_t polysh32 = (uint64_t)poly << (i - 32); uint64_t mask = (UINT64_C(1) << i) - 1; data = ((data & mask) ^ polysh32); } } return data & 0xffffffff; } template <typename T> uint32_t Simulator::Crc32Checksum(uint32_t acc, T val, uint32_t poly) { unsigned size = sizeof(val) * 8; // Number of bits in type T. VIXL_ASSERT((size == 8) || (size == 16) || (size == 32)); uint64_t tempacc = static_cast<uint64_t>(ReverseBits(acc)) << size; uint64_t tempval = static_cast<uint64_t>(ReverseBits(val)) << 32; return ReverseBits(Poly32Mod2(32 + size, tempacc ^ tempval, poly)); } uint32_t Simulator::Crc32Checksum(uint32_t acc, uint64_t val, uint32_t poly) { // Poly32Mod2 cannot handle inputs with more than 32 bits, so compute // the CRC of each 32-bit word sequentially. acc = Crc32Checksum(acc, (uint32_t)(val & 0xffffffff), poly); return Crc32Checksum(acc, (uint32_t)(val >> 32), poly); } void Simulator::VisitDataProcessing2Source(const Instruction* instr) { Shift shift_op = NO_SHIFT; int64_t result = 0; unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; switch (instr->Mask(DataProcessing2SourceMask)) { case SDIV_w: { int32_t rn = wreg(instr->Rn()); int32_t rm = wreg(instr->Rm()); if ((rn == kWMinInt) && (rm == -1)) { result = kWMinInt; } else if (rm == 0) { // Division by zero can be trapped, but not on A-class processors. result = 0; } else { result = rn / rm; } break; } case SDIV_x: { int64_t rn = xreg(instr->Rn()); int64_t rm = xreg(instr->Rm()); if ((rn == kXMinInt) && (rm == -1)) { result = kXMinInt; } else if (rm == 0) { // Division by zero can be trapped, but not on A-class processors. result = 0; } else { result = rn / rm; } break; } case UDIV_w: { uint32_t rn = static_cast<uint32_t>(wreg(instr->Rn())); uint32_t rm = static_cast<uint32_t>(wreg(instr->Rm())); if (rm == 0) { // Division by zero can be trapped, but not on A-class processors. result = 0; } else { result = rn / rm; } break; } case UDIV_x: { uint64_t rn = static_cast<uint64_t>(xreg(instr->Rn())); uint64_t rm = static_cast<uint64_t>(xreg(instr->Rm())); if (rm == 0) { // Division by zero can be trapped, but not on A-class processors. result = 0; } else { result = rn / rm; } break; } case LSLV_w: case LSLV_x: shift_op = LSL; break; case LSRV_w: case LSRV_x: shift_op = LSR; break; case ASRV_w: case ASRV_x: shift_op = ASR; break; case RORV_w: case RORV_x: shift_op = ROR; break; case CRC32B: { uint32_t acc = reg<uint32_t>(instr->Rn()); uint8_t val = reg<uint8_t>(instr->Rm()); result = Crc32Checksum(acc, val, CRC32_POLY); break; } case CRC32H: { uint32_t acc = reg<uint32_t>(instr->Rn()); uint16_t val = reg<uint16_t>(instr->Rm()); result = Crc32Checksum(acc, val, CRC32_POLY); break; } case CRC32W: { uint32_t acc = reg<uint32_t>(instr->Rn()); uint32_t val = reg<uint32_t>(instr->Rm()); result = Crc32Checksum(acc, val, CRC32_POLY); break; } case CRC32X: { uint32_t acc = reg<uint32_t>(instr->Rn()); uint64_t val = reg<uint64_t>(instr->Rm()); result = Crc32Checksum(acc, val, CRC32_POLY); reg_size = kWRegSize; break; } case CRC32CB: { uint32_t acc = reg<uint32_t>(instr->Rn()); uint8_t val = reg<uint8_t>(instr->Rm()); result = Crc32Checksum(acc, val, CRC32C_POLY); break; } case CRC32CH: { uint32_t acc = reg<uint32_t>(instr->Rn()); uint16_t val = reg<uint16_t>(instr->Rm()); result = Crc32Checksum(acc, val, CRC32C_POLY); break; } case CRC32CW: { uint32_t acc = reg<uint32_t>(instr->Rn()); uint32_t val = reg<uint32_t>(instr->Rm()); result = Crc32Checksum(acc, val, CRC32C_POLY); break; } case CRC32CX: { uint32_t acc = reg<uint32_t>(instr->Rn()); uint64_t val = reg<uint64_t>(instr->Rm()); result = Crc32Checksum(acc, val, CRC32C_POLY); reg_size = kWRegSize; break; } default: VIXL_UNIMPLEMENTED(); } if (shift_op != NO_SHIFT) { // Shift distance encoded in the least-significant five/six bits of the // register. int mask = (instr->SixtyFourBits() == 1) ? 0x3f : 0x1f; unsigned shift = wreg(instr->Rm()) & mask; result = ShiftOperand(reg_size, reg(reg_size, instr->Rn()), shift_op, shift); } set_reg(reg_size, instr->Rd(), result); } // The algorithm used is adapted from the one described in section 8.2 of // Hacker's Delight, by Henry S. Warren, Jr. // It assumes that a right shift on a signed integer is an arithmetic shift. // Type T must be either uint64_t or int64_t. template <typename T> static T MultiplyHigh(T u, T v) { uint64_t u0, v0, w0; T u1, v1, w1, w2, t; VIXL_ASSERT(sizeof(u) == sizeof(u0)); u0 = u & 0xffffffff; u1 = u >> 32; v0 = v & 0xffffffff; v1 = v >> 32; w0 = u0 * v0; t = u1 * v0 + (w0 >> 32); w1 = t & 0xffffffff; w2 = t >> 32; w1 = u0 * v1 + w1; return u1 * v1 + w2 + (w1 >> 32); } void Simulator::VisitDataProcessing3Source(const Instruction* instr) { unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; int64_t result = 0; // Extract and sign- or zero-extend 32-bit arguments for widening operations. uint64_t rn_u32 = reg<uint32_t>(instr->Rn()); uint64_t rm_u32 = reg<uint32_t>(instr->Rm()); int64_t rn_s32 = reg<int32_t>(instr->Rn()); int64_t rm_s32 = reg<int32_t>(instr->Rm()); switch (instr->Mask(DataProcessing3SourceMask)) { case MADD_w: case MADD_x: result = xreg(instr->Ra()) + (xreg(instr->Rn()) * xreg(instr->Rm())); break; case MSUB_w: case MSUB_x: result = xreg(instr->Ra()) - (xreg(instr->Rn()) * xreg(instr->Rm())); break; case SMADDL_x: result = xreg(instr->Ra()) + (rn_s32 * rm_s32); break; case SMSUBL_x: result = xreg(instr->Ra()) - (rn_s32 * rm_s32); break; case UMADDL_x: result = xreg(instr->Ra()) + (rn_u32 * rm_u32); break; case UMSUBL_x: result = xreg(instr->Ra()) - (rn_u32 * rm_u32); break; case UMULH_x: result = MultiplyHigh(reg<uint64_t>(instr->Rn()), reg<uint64_t>(instr->Rm())); break; case SMULH_x: result = MultiplyHigh(xreg(instr->Rn()), xreg(instr->Rm())); break; default: VIXL_UNIMPLEMENTED(); } set_reg(reg_size, instr->Rd(), result); } void Simulator::VisitBitfield(const Instruction* instr) { unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize; int64_t reg_mask = instr->SixtyFourBits() ? kXRegMask : kWRegMask; int64_t R = instr->ImmR(); int64_t S = instr->ImmS(); int64_t diff = S - R; int64_t mask; if (diff >= 0) { mask = (diff < (reg_size - 1)) ? (INT64_C(1) << (diff + 1)) - 1 : reg_mask; } else { mask = (INT64_C(1) << (S + 1)) - 1; mask = (static_cast<uint64_t>(mask) >> R) | (mask << (reg_size - R)); diff += reg_size; } // inzero indicates if the extracted bitfield is inserted into the // destination register value or in zero. // If extend is true, extend the sign of the extracted bitfield. bool inzero = false; bool extend = false; switch (instr->Mask(BitfieldMask)) { case BFM_x: case BFM_w: break; case SBFM_x: case SBFM_w: inzero = true; extend = true; break; case UBFM_x: case UBFM_w: inzero = true; break; default: VIXL_UNIMPLEMENTED(); } int64_t dst = inzero ? 0 : reg(reg_size, instr->Rd()); int64_t src = reg(reg_size, instr->Rn()); // Rotate source bitfield into place. int64_t result = (static_cast<uint64_t>(src) >> R) | (src << (reg_size - R)); // Determine the sign extension. int64_t topbits = ((INT64_C(1) << (reg_size - diff - 1)) - 1) << (diff + 1); int64_t signbits = extend && ((src >> S) & 1) ? topbits : 0; // Merge sign extension, dest/zero and bitfield. result = signbits | (result & mask) | (dst & ~mask); set_reg(reg_size, instr->Rd(), result); } void Simulator::VisitExtract(const Instruction* instr) { unsigned lsb = instr->ImmS(); unsigned reg_size = (instr->SixtyFourBits() == 1) ? kXRegSize : kWRegSize; uint64_t low_res = static_cast<uint64_t>(reg(reg_size, instr->Rm())) >> lsb; uint64_t high_res = (lsb == 0) ? 0 : reg(reg_size, instr->Rn()) << (reg_size - lsb); set_reg(reg_size, instr->Rd(), low_res | high_res); } void Simulator::VisitFPImmediate(const Instruction* instr) { AssertSupportedFPCR(); unsigned dest = instr->Rd(); switch (instr->Mask(FPImmediateMask)) { case FMOV_s_imm: set_sreg(dest, instr->ImmFP32()); break; case FMOV_d_imm: set_dreg(dest, instr->ImmFP64()); break; default: VIXL_UNREACHABLE(); } } void Simulator::VisitFPIntegerConvert(const Instruction* instr) { AssertSupportedFPCR(); unsigned dst = instr->Rd(); unsigned src = instr->Rn(); FPRounding round = RMode(); switch (instr->Mask(FPIntegerConvertMask)) { case FCVTAS_ws: set_wreg(dst, FPToInt32(sreg(src), FPTieAway)); break; case FCVTAS_xs: set_xreg(dst, FPToInt64(sreg(src), FPTieAway)); break; case FCVTAS_wd: set_wreg(dst, FPToInt32(dreg(src), FPTieAway)); break; case FCVTAS_xd: set_xreg(dst, FPToInt64(dreg(src), FPTieAway)); break; case FCVTAU_ws: set_wreg(dst, FPToUInt32(sreg(src), FPTieAway)); break; case FCVTAU_xs: set_xreg(dst, FPToUInt64(sreg(src), FPTieAway)); break; case FCVTAU_wd: set_wreg(dst, FPToUInt32(dreg(src), FPTieAway)); break; case FCVTAU_xd: set_xreg(dst, FPToUInt64(dreg(src), FPTieAway)); break; case FCVTMS_ws: set_wreg(dst, FPToInt32(sreg(src), FPNegativeInfinity)); break; case FCVTMS_xs: set_xreg(dst, FPToInt64(sreg(src), FPNegativeInfinity)); break; case FCVTMS_wd: set_wreg(dst, FPToInt32(dreg(src), FPNegativeInfinity)); break; case FCVTMS_xd: set_xreg(dst, FPToInt64(dreg(src), FPNegativeInfinity)); break; case FCVTMU_ws: set_wreg(dst, FPToUInt32(sreg(src), FPNegativeInfinity)); break; case FCVTMU_xs: set_xreg(dst, FPToUInt64(sreg(src), FPNegativeInfinity)); break; case FCVTMU_wd: set_wreg(dst, FPToUInt32(dreg(src), FPNegativeInfinity)); break; case FCVTMU_xd: set_xreg(dst, FPToUInt64(dreg(src), FPNegativeInfinity)); break; case FCVTPS_ws: set_wreg(dst, FPToInt32(sreg(src), FPPositiveInfinity)); break; case FCVTPS_xs: set_xreg(dst, FPToInt64(sreg(src), FPPositiveInfinity)); break; case FCVTPS_wd: set_wreg(dst, FPToInt32(dreg(src), FPPositiveInfinity)); break; case FCVTPS_xd: set_xreg(dst, FPToInt64(dreg(src), FPPositiveInfinity)); break; case FCVTPU_ws: set_wreg(dst, FPToUInt32(sreg(src), FPPositiveInfinity)); break; case FCVTPU_xs: set_xreg(dst, FPToUInt64(sreg(src), FPPositiveInfinity)); break; case FCVTPU_wd: set_wreg(dst, FPToUInt32(dreg(src), FPPositiveInfinity)); break; case FCVTPU_xd: set_xreg(dst, FPToUInt64(dreg(src), FPPositiveInfinity)); break; case FCVTNS_ws: set_wreg(dst, FPToInt32(sreg(src), FPTieEven)); break; case FCVTNS_xs: set_xreg(dst, FPToInt64(sreg(src), FPTieEven)); break; case FCVTNS_wd: set_wreg(dst, FPToInt32(dreg(src), FPTieEven)); break; case FCVTNS_xd: set_xreg(dst, FPToInt64(dreg(src), FPTieEven)); break; case FCVTNU_ws: set_wreg(dst, FPToUInt32(sreg(src), FPTieEven)); break; case FCVTNU_xs: set_xreg(dst, FPToUInt64(sreg(src), FPTieEven)); break; case FCVTNU_wd: set_wreg(dst, FPToUInt32(dreg(src), FPTieEven)); break; case FCVTNU_xd: set_xreg(dst, FPToUInt64(dreg(src), FPTieEven)); break; case FCVTZS_ws: set_wreg(dst, FPToInt32(sreg(src), FPZero)); break; case FCVTZS_xs: set_xreg(dst, FPToInt64(sreg(src), FPZero)); break; case FCVTZS_wd: set_wreg(dst, FPToInt32(dreg(src), FPZero)); break; case FCVTZS_xd: set_xreg(dst, FPToInt64(dreg(src), FPZero)); break; case FCVTZU_ws: set_wreg(dst, FPToUInt32(sreg(src), FPZero)); break; case FCVTZU_xs: set_xreg(dst, FPToUInt64(sreg(src), FPZero)); break; case FCVTZU_wd: set_wreg(dst, FPToUInt32(dreg(src), FPZero)); break; case FCVTZU_xd: set_xreg(dst, FPToUInt64(dreg(src), FPZero)); break; case FMOV_ws: set_wreg(dst, sreg_bits(src)); break; case FMOV_xd: set_xreg(dst, dreg_bits(src)); break; case FMOV_sw: set_sreg_bits(dst, wreg(src)); break; case FMOV_dx: set_dreg_bits(dst, xreg(src)); break; case FMOV_d1_x: LogicVRegister(vreg(dst)).SetUint(kFormatD, 1, xreg(src)); break; case FMOV_x_d1: set_xreg(dst, LogicVRegister(vreg(src)).Uint(kFormatD, 1)); break; // A 32-bit input can be handled in the same way as a 64-bit input, since // the sign- or zero-extension will not affect the conversion. case SCVTF_dx: set_dreg(dst, FixedToDouble(xreg(src), 0, round)); break; case SCVTF_dw: set_dreg(dst, FixedToDouble(wreg(src), 0, round)); break; case UCVTF_dx: set_dreg(dst, UFixedToDouble(xreg(src), 0, round)); break; case UCVTF_dw: { set_dreg(dst, UFixedToDouble(static_cast<uint32_t>(wreg(src)), 0, round)); break; } case SCVTF_sx: set_sreg(dst, FixedToFloat(xreg(src), 0, round)); break; case SCVTF_sw: set_sreg(dst, FixedToFloat(wreg(src), 0, round)); break; case UCVTF_sx: set_sreg(dst, UFixedToFloat(xreg(src), 0, round)); break; case UCVTF_sw: { set_sreg(dst, UFixedToFloat(static_cast<uint32_t>(wreg(src)), 0, round)); break; } default: VIXL_UNREACHABLE(); } } void Simulator::VisitFPFixedPointConvert(const Instruction* instr) { AssertSupportedFPCR(); unsigned dst = instr->Rd(); unsigned src = instr->Rn(); int fbits = 64 - instr->FPScale(); FPRounding round = RMode(); switch (instr->Mask(FPFixedPointConvertMask)) { // A 32-bit input can be handled in the same way as a 64-bit input, since // the sign- or zero-extension will not affect the conversion. case SCVTF_dx_fixed: set_dreg(dst, FixedToDouble(xreg(src), fbits, round)); break; case SCVTF_dw_fixed: set_dreg(dst, FixedToDouble(wreg(src), fbits, round)); break; case UCVTF_dx_fixed: set_dreg(dst, UFixedToDouble(xreg(src), fbits, round)); break; case UCVTF_dw_fixed: { set_dreg(dst, UFixedToDouble(static_cast<uint32_t>(wreg(src)), fbits, round)); break; } case SCVTF_sx_fixed: set_sreg(dst, FixedToFloat(xreg(src), fbits, round)); break; case SCVTF_sw_fixed: set_sreg(dst, FixedToFloat(wreg(src), fbits, round)); break; case UCVTF_sx_fixed: set_sreg(dst, UFixedToFloat(xreg(src), fbits, round)); break; case UCVTF_sw_fixed: { set_sreg(dst, UFixedToFloat(static_cast<uint32_t>(wreg(src)), fbits, round)); break; } case FCVTZS_xd_fixed: set_xreg(dst, FPToInt64(dreg(src) * std::pow(2.0, fbits), FPZero)); break; case FCVTZS_wd_fixed: set_wreg(dst, FPToInt32(dreg(src) * std::pow(2.0, fbits), FPZero)); break; case FCVTZU_xd_fixed: set_xreg(dst, FPToUInt64(dreg(src) * std::pow(2.0, fbits), FPZero)); break; case FCVTZU_wd_fixed: set_wreg(dst, FPToUInt32(dreg(src) * std::pow(2.0, fbits), FPZero)); break; case FCVTZS_xs_fixed: set_xreg(dst, FPToInt64(sreg(src) * std::pow(2.0f, fbits), FPZero)); break; case FCVTZS_ws_fixed: set_wreg(dst, FPToInt32(sreg(src) * std::pow(2.0f, fbits), FPZero)); break; case FCVTZU_xs_fixed: set_xreg(dst, FPToUInt64(sreg(src) * std::pow(2.0f, fbits), FPZero)); break; case FCVTZU_ws_fixed: set_wreg(dst, FPToUInt32(sreg(src) * std::pow(2.0f, fbits), FPZero)); break; default: VIXL_UNREACHABLE(); } } void Simulator::VisitFPCompare(const Instruction* instr) { AssertSupportedFPCR(); FPTrapFlags trap = DisableTrap; switch (instr->Mask(FPCompareMask)) { case FCMPE_s: trap = EnableTrap; VIXL_FALLTHROUGH(); case FCMP_s: FPCompare(sreg(instr->Rn()), sreg(instr->Rm()), trap); break; case FCMPE_d: trap = EnableTrap; VIXL_FALLTHROUGH(); case FCMP_d: FPCompare(dreg(instr->Rn()), dreg(instr->Rm()), trap); break; case FCMPE_s_zero: trap = EnableTrap; VIXL_FALLTHROUGH(); case FCMP_s_zero: FPCompare(sreg(instr->Rn()), 0.0f, trap); break; case FCMPE_d_zero: trap = EnableTrap; VIXL_FALLTHROUGH(); case FCMP_d_zero: FPCompare(dreg(instr->Rn()), 0.0, trap); break; default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitFPConditionalCompare(const Instruction* instr) { AssertSupportedFPCR(); FPTrapFlags trap = DisableTrap; switch (instr->Mask(FPConditionalCompareMask)) { case FCCMPE_s: trap = EnableTrap; VIXL_FALLTHROUGH(); case FCCMP_s: if (ConditionPassed(instr->Condition())) { FPCompare(sreg(instr->Rn()), sreg(instr->Rm()), trap); } else { nzcv().SetFlags(instr->Nzcv()); LogSystemRegister(NZCV); } break; case FCCMPE_d: trap = EnableTrap; VIXL_FALLTHROUGH(); case FCCMP_d: if (ConditionPassed(instr->Condition())) { FPCompare(dreg(instr->Rn()), dreg(instr->Rm()), trap); } else { nzcv().SetFlags(instr->Nzcv()); LogSystemRegister(NZCV); } break; default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitFPConditionalSelect(const Instruction* instr) { AssertSupportedFPCR(); Instr selected; if (ConditionPassed(instr->Condition())) { selected = instr->Rn(); } else { selected = instr->Rm(); } switch (instr->Mask(FPConditionalSelectMask)) { case FCSEL_s: set_sreg(instr->Rd(), sreg(selected)); break; case FCSEL_d: set_dreg(instr->Rd(), dreg(selected)); break; default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitFPDataProcessing1Source(const Instruction* instr) { AssertSupportedFPCR(); FPRounding fpcr_rounding = static_cast<FPRounding>(fpcr().RMode()); VectorFormat vform = (instr->Mask(FP64) == FP64) ? kFormatD : kFormatS; SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); bool inexact_exception = false; unsigned fd = instr->Rd(); unsigned fn = instr->Rn(); switch (instr->Mask(FPDataProcessing1SourceMask)) { case FMOV_s: set_sreg(fd, sreg(fn)); return; case FMOV_d: set_dreg(fd, dreg(fn)); return; case FABS_s: fabs_(kFormatS, vreg(fd), vreg(fn)); return; case FABS_d: fabs_(kFormatD, vreg(fd), vreg(fn)); return; case FNEG_s: fneg(kFormatS, vreg(fd), vreg(fn)); return; case FNEG_d: fneg(kFormatD, vreg(fd), vreg(fn)); return; case FCVT_ds: set_dreg(fd, FPToDouble(sreg(fn))); return; case FCVT_sd: set_sreg(fd, FPToFloat(dreg(fn), FPTieEven)); return; case FCVT_hs: set_hreg(fd, FPToFloat16(sreg(fn), FPTieEven)); return; case FCVT_sh: set_sreg(fd, FPToFloat(hreg(fn))); return; case FCVT_dh: set_dreg(fd, FPToDouble(FPToFloat(hreg(fn)))); return; case FCVT_hd: set_hreg(fd, FPToFloat16(dreg(fn), FPTieEven)); return; case FSQRT_s: case FSQRT_d: fsqrt(vform, rd, rn); return; case FRINTI_s: case FRINTI_d: break; // Use FPCR rounding mode. case FRINTX_s: case FRINTX_d: inexact_exception = true; break; case FRINTA_s: case FRINTA_d: fpcr_rounding = FPTieAway; break; case FRINTM_s: case FRINTM_d: fpcr_rounding = FPNegativeInfinity; break; case FRINTN_s: case FRINTN_d: fpcr_rounding = FPTieEven; break; case FRINTP_s: case FRINTP_d: fpcr_rounding = FPPositiveInfinity; break; case FRINTZ_s: case FRINTZ_d: fpcr_rounding = FPZero; break; default: VIXL_UNIMPLEMENTED(); } // Only FRINT* instructions fall through the switch above. frint(vform, rd, rn, fpcr_rounding, inexact_exception); } void Simulator::VisitFPDataProcessing2Source(const Instruction* instr) { AssertSupportedFPCR(); VectorFormat vform = (instr->Mask(FP64) == FP64) ? kFormatD : kFormatS; SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); switch (instr->Mask(FPDataProcessing2SourceMask)) { case FADD_s: case FADD_d: fadd(vform, rd, rn, rm); break; case FSUB_s: case FSUB_d: fsub(vform, rd, rn, rm); break; case FMUL_s: case FMUL_d: fmul(vform, rd, rn, rm); break; case FNMUL_s: case FNMUL_d: fnmul(vform, rd, rn, rm); break; case FDIV_s: case FDIV_d: fdiv(vform, rd, rn, rm); break; case FMAX_s: case FMAX_d: fmax(vform, rd, rn, rm); break; case FMIN_s: case FMIN_d: fmin(vform, rd, rn, rm); break; case FMAXNM_s: case FMAXNM_d: fmaxnm(vform, rd, rn, rm); break; case FMINNM_s: case FMINNM_d: fminnm(vform, rd, rn, rm); break; default: VIXL_UNREACHABLE(); } } void Simulator::VisitFPDataProcessing3Source(const Instruction* instr) { AssertSupportedFPCR(); unsigned fd = instr->Rd(); unsigned fn = instr->Rn(); unsigned fm = instr->Rm(); unsigned fa = instr->Ra(); switch (instr->Mask(FPDataProcessing3SourceMask)) { // fd = fa +/- (fn * fm) case FMADD_s: set_sreg(fd, FPMulAdd(sreg(fa), sreg(fn), sreg(fm))); break; case FMSUB_s: set_sreg(fd, FPMulAdd(sreg(fa), -sreg(fn), sreg(fm))); break; case FMADD_d: set_dreg(fd, FPMulAdd(dreg(fa), dreg(fn), dreg(fm))); break; case FMSUB_d: set_dreg(fd, FPMulAdd(dreg(fa), -dreg(fn), dreg(fm))); break; // Negated variants of the above. case FNMADD_s: set_sreg(fd, FPMulAdd(-sreg(fa), -sreg(fn), sreg(fm))); break; case FNMSUB_s: set_sreg(fd, FPMulAdd(-sreg(fa), sreg(fn), sreg(fm))); break; case FNMADD_d: set_dreg(fd, FPMulAdd(-dreg(fa), -dreg(fn), dreg(fm))); break; case FNMSUB_d: set_dreg(fd, FPMulAdd(-dreg(fa), dreg(fn), dreg(fm))); break; default: VIXL_UNIMPLEMENTED(); } } bool Simulator::FPProcessNaNs(const Instruction* instr) { unsigned fd = instr->Rd(); unsigned fn = instr->Rn(); unsigned fm = instr->Rm(); bool done = false; if (instr->Mask(FP64) == FP64) { double result = FPProcessNaNs(dreg(fn), dreg(fm)); if (std::isnan(result)) { set_dreg(fd, result); done = true; } } else { float result = FPProcessNaNs(sreg(fn), sreg(fm)); if (std::isnan(result)) { set_sreg(fd, result); done = true; } } return done; } void Simulator::SysOp_W(int op, int64_t val) { switch (op) { case IVAU: case CVAC: case CVAU: case CIVAC: { // Perform a dummy memory access to ensure that we have read access // to the specified address. volatile uint8_t y = Memory::Read<uint8_t>(val); USE(y); // TODO: Implement "case ZVA:". break; } default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitSystem(const Instruction* instr) { // Some system instructions hijack their Op and Cp fields to represent a // range of immediates instead of indicating a different instruction. This // makes the decoding tricky. if (instr->Mask(SystemExclusiveMonitorFMask) == SystemExclusiveMonitorFixed) { VIXL_ASSERT(instr->Mask(SystemExclusiveMonitorMask) == CLREX); switch (instr->Mask(SystemExclusiveMonitorMask)) { case CLREX: { PrintExclusiveAccessWarning(); ClearLocalMonitor(); break; } } } else if (instr->Mask(SystemSysRegFMask) == SystemSysRegFixed) { switch (instr->Mask(SystemSysRegMask)) { case MRS: { switch (instr->ImmSystemRegister()) { case NZCV: set_xreg(instr->Rt(), nzcv().RawValue()); break; case FPCR: set_xreg(instr->Rt(), fpcr().RawValue()); break; default: VIXL_UNIMPLEMENTED(); } break; } case MSR: { switch (instr->ImmSystemRegister()) { case NZCV: nzcv().SetRawValue(wreg(instr->Rt())); LogSystemRegister(NZCV); break; case FPCR: fpcr().SetRawValue(wreg(instr->Rt())); LogSystemRegister(FPCR); break; default: VIXL_UNIMPLEMENTED(); } break; } } } else if (instr->Mask(SystemHintFMask) == SystemHintFixed) { VIXL_ASSERT(instr->Mask(SystemHintMask) == HINT); switch (instr->ImmHint()) { case NOP: break; default: VIXL_UNIMPLEMENTED(); } } else if (instr->Mask(MemBarrierFMask) == MemBarrierFixed) { __sync_synchronize(); } else if ((instr->Mask(SystemSysFMask) == SystemSysFixed)) { switch (instr->Mask(SystemSysMask)) { case SYS: SysOp_W(instr->SysOp(), xreg(instr->Rt())); break; default: VIXL_UNIMPLEMENTED(); } } else { VIXL_UNIMPLEMENTED(); } } void Simulator::VisitException(const Instruction* instr) { switch (instr->Mask(ExceptionMask)) { case HLT: switch (instr->ImmException()) { case kUnreachableOpcode: DoUnreachable(instr); return; case kTraceOpcode: DoTrace(instr); return; case kLogOpcode: DoLog(instr); return; case kPrintfOpcode: DoPrintf(instr); return; default: HostBreakpoint(); return; } case BRK: HostBreakpoint(); return; default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitCrypto2RegSHA(const Instruction* instr) { VisitUnimplemented(instr); } void Simulator::VisitCrypto3RegSHA(const Instruction* instr) { VisitUnimplemented(instr); } void Simulator::VisitCryptoAES(const Instruction* instr) { VisitUnimplemented(instr); } void Simulator::VisitNEON2RegMisc(const Instruction* instr) { NEONFormatDecoder nfd(instr); VectorFormat vf = nfd.GetVectorFormat(); static const NEONFormatMap map_lp = { {23, 22, 30}, {NF_4H, NF_8H, NF_2S, NF_4S, NF_1D, NF_2D} }; VectorFormat vf_lp = nfd.GetVectorFormat(&map_lp); static const NEONFormatMap map_fcvtl = { {22}, {NF_4S, NF_2D} }; VectorFormat vf_fcvtl = nfd.GetVectorFormat(&map_fcvtl); static const NEONFormatMap map_fcvtn = { {22, 30}, {NF_4H, NF_8H, NF_2S, NF_4S} }; VectorFormat vf_fcvtn = nfd.GetVectorFormat(&map_fcvtn); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); if (instr->Mask(NEON2RegMiscOpcode) <= NEON_NEG_opcode) { // These instructions all use a two bit size field, except NOT and RBIT, // which use the field to encode the operation. switch (instr->Mask(NEON2RegMiscMask)) { case NEON_REV64: rev64(vf, rd, rn); break; case NEON_REV32: rev32(vf, rd, rn); break; case NEON_REV16: rev16(vf, rd, rn); break; case NEON_SUQADD: suqadd(vf, rd, rn); break; case NEON_USQADD: usqadd(vf, rd, rn); break; case NEON_CLS: cls(vf, rd, rn); break; case NEON_CLZ: clz(vf, rd, rn); break; case NEON_CNT: cnt(vf, rd, rn); break; case NEON_SQABS: abs(vf, rd, rn).SignedSaturate(vf); break; case NEON_SQNEG: neg(vf, rd, rn).SignedSaturate(vf); break; case NEON_CMGT_zero: cmp(vf, rd, rn, 0, gt); break; case NEON_CMGE_zero: cmp(vf, rd, rn, 0, ge); break; case NEON_CMEQ_zero: cmp(vf, rd, rn, 0, eq); break; case NEON_CMLE_zero: cmp(vf, rd, rn, 0, le); break; case NEON_CMLT_zero: cmp(vf, rd, rn, 0, lt); break; case NEON_ABS: abs(vf, rd, rn); break; case NEON_NEG: neg(vf, rd, rn); break; case NEON_SADDLP: saddlp(vf_lp, rd, rn); break; case NEON_UADDLP: uaddlp(vf_lp, rd, rn); break; case NEON_SADALP: sadalp(vf_lp, rd, rn); break; case NEON_UADALP: uadalp(vf_lp, rd, rn); break; case NEON_RBIT_NOT: vf = nfd.GetVectorFormat(nfd.LogicalFormatMap()); switch (instr->FPType()) { case 0: not_(vf, rd, rn); break; case 1: rbit(vf, rd, rn);; break; default: VIXL_UNIMPLEMENTED(); } break; } } else { VectorFormat fpf = nfd.GetVectorFormat(nfd.FPFormatMap()); FPRounding fpcr_rounding = static_cast<FPRounding>(fpcr().RMode()); bool inexact_exception = false; // These instructions all use a one bit size field, except XTN, SQXTUN, // SHLL, SQXTN and UQXTN, which use a two bit size field. switch (instr->Mask(NEON2RegMiscFPMask)) { case NEON_FABS: fabs_(fpf, rd, rn); return; case NEON_FNEG: fneg(fpf, rd, rn); return; case NEON_FSQRT: fsqrt(fpf, rd, rn); return; case NEON_FCVTL: if (instr->Mask(NEON_Q)) { fcvtl2(vf_fcvtl, rd, rn); } else { fcvtl(vf_fcvtl, rd, rn); } return; case NEON_FCVTN: if (instr->Mask(NEON_Q)) { fcvtn2(vf_fcvtn, rd, rn); } else { fcvtn(vf_fcvtn, rd, rn); } return; case NEON_FCVTXN: if (instr->Mask(NEON_Q)) { fcvtxn2(vf_fcvtn, rd, rn); } else { fcvtxn(vf_fcvtn, rd, rn); } return; // The following instructions break from the switch statement, rather // than return. case NEON_FRINTI: break; // Use FPCR rounding mode. case NEON_FRINTX: inexact_exception = true; break; case NEON_FRINTA: fpcr_rounding = FPTieAway; break; case NEON_FRINTM: fpcr_rounding = FPNegativeInfinity; break; case NEON_FRINTN: fpcr_rounding = FPTieEven; break; case NEON_FRINTP: fpcr_rounding = FPPositiveInfinity; break; case NEON_FRINTZ: fpcr_rounding = FPZero; break; case NEON_FCVTNS: fcvts(fpf, rd, rn, FPTieEven); return; case NEON_FCVTNU: fcvtu(fpf, rd, rn, FPTieEven); return; case NEON_FCVTPS: fcvts(fpf, rd, rn, FPPositiveInfinity); return; case NEON_FCVTPU: fcvtu(fpf, rd, rn, FPPositiveInfinity); return; case NEON_FCVTMS: fcvts(fpf, rd, rn, FPNegativeInfinity); return; case NEON_FCVTMU: fcvtu(fpf, rd, rn, FPNegativeInfinity); return; case NEON_FCVTZS: fcvts(fpf, rd, rn, FPZero); return; case NEON_FCVTZU: fcvtu(fpf, rd, rn, FPZero); return; case NEON_FCVTAS: fcvts(fpf, rd, rn, FPTieAway); return; case NEON_FCVTAU: fcvtu(fpf, rd, rn, FPTieAway); return; case NEON_SCVTF: scvtf(fpf, rd, rn, 0, fpcr_rounding); return; case NEON_UCVTF: ucvtf(fpf, rd, rn, 0, fpcr_rounding); return; case NEON_URSQRTE: ursqrte(fpf, rd, rn); return; case NEON_URECPE: urecpe(fpf, rd, rn); return; case NEON_FRSQRTE: frsqrte(fpf, rd, rn); return; case NEON_FRECPE: frecpe(fpf, rd, rn, fpcr_rounding); return; case NEON_FCMGT_zero: fcmp_zero(fpf, rd, rn, gt); return; case NEON_FCMGE_zero: fcmp_zero(fpf, rd, rn, ge); return; case NEON_FCMEQ_zero: fcmp_zero(fpf, rd, rn, eq); return; case NEON_FCMLE_zero: fcmp_zero(fpf, rd, rn, le); return; case NEON_FCMLT_zero: fcmp_zero(fpf, rd, rn, lt); return; default: if ((NEON_XTN_opcode <= instr->Mask(NEON2RegMiscOpcode)) && (instr->Mask(NEON2RegMiscOpcode) <= NEON_UQXTN_opcode)) { switch (instr->Mask(NEON2RegMiscMask)) { case NEON_XTN: xtn(vf, rd, rn); return; case NEON_SQXTN: sqxtn(vf, rd, rn); return; case NEON_UQXTN: uqxtn(vf, rd, rn); return; case NEON_SQXTUN: sqxtun(vf, rd, rn); return; case NEON_SHLL: vf = nfd.GetVectorFormat(nfd.LongIntegerFormatMap()); if (instr->Mask(NEON_Q)) { shll2(vf, rd, rn); } else { shll(vf, rd, rn); } return; default: VIXL_UNIMPLEMENTED(); } } else { VIXL_UNIMPLEMENTED(); } } // Only FRINT* instructions fall through the switch above. frint(fpf, rd, rn, fpcr_rounding, inexact_exception); } } void Simulator::VisitNEON3Same(const Instruction* instr) { NEONFormatDecoder nfd(instr); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); if (instr->Mask(NEON3SameLogicalFMask) == NEON3SameLogicalFixed) { VectorFormat vf = nfd.GetVectorFormat(nfd.LogicalFormatMap()); switch (instr->Mask(NEON3SameLogicalMask)) { case NEON_AND: and_(vf, rd, rn, rm); break; case NEON_ORR: orr(vf, rd, rn, rm); break; case NEON_ORN: orn(vf, rd, rn, rm); break; case NEON_EOR: eor(vf, rd, rn, rm); break; case NEON_BIC: bic(vf, rd, rn, rm); break; case NEON_BIF: bif(vf, rd, rn, rm); break; case NEON_BIT: bit(vf, rd, rn, rm); break; case NEON_BSL: bsl(vf, rd, rn, rm); break; default: VIXL_UNIMPLEMENTED(); } } else if (instr->Mask(NEON3SameFPFMask) == NEON3SameFPFixed) { VectorFormat vf = nfd.GetVectorFormat(nfd.FPFormatMap()); switch (instr->Mask(NEON3SameFPMask)) { case NEON_FADD: fadd(vf, rd, rn, rm); break; case NEON_FSUB: fsub(vf, rd, rn, rm); break; case NEON_FMUL: fmul(vf, rd, rn, rm); break; case NEON_FDIV: fdiv(vf, rd, rn, rm); break; case NEON_FMAX: fmax(vf, rd, rn, rm); break; case NEON_FMIN: fmin(vf, rd, rn, rm); break; case NEON_FMAXNM: fmaxnm(vf, rd, rn, rm); break; case NEON_FMINNM: fminnm(vf, rd, rn, rm); break; case NEON_FMLA: fmla(vf, rd, rn, rm); break; case NEON_FMLS: fmls(vf, rd, rn, rm); break; case NEON_FMULX: fmulx(vf, rd, rn, rm); break; case NEON_FACGE: fabscmp(vf, rd, rn, rm, ge); break; case NEON_FACGT: fabscmp(vf, rd, rn, rm, gt); break; case NEON_FCMEQ: fcmp(vf, rd, rn, rm, eq); break; case NEON_FCMGE: fcmp(vf, rd, rn, rm, ge); break; case NEON_FCMGT: fcmp(vf, rd, rn, rm, gt); break; case NEON_FRECPS: frecps(vf, rd, rn, rm); break; case NEON_FRSQRTS: frsqrts(vf, rd, rn, rm); break; case NEON_FABD: fabd(vf, rd, rn, rm); break; case NEON_FADDP: faddp(vf, rd, rn, rm); break; case NEON_FMAXP: fmaxp(vf, rd, rn, rm); break; case NEON_FMAXNMP: fmaxnmp(vf, rd, rn, rm); break; case NEON_FMINP: fminp(vf, rd, rn, rm); break; case NEON_FMINNMP: fminnmp(vf, rd, rn, rm); break; default: VIXL_UNIMPLEMENTED(); } } else { VectorFormat vf = nfd.GetVectorFormat(); switch (instr->Mask(NEON3SameMask)) { case NEON_ADD: add(vf, rd, rn, rm); break; case NEON_ADDP: addp(vf, rd, rn, rm); break; case NEON_CMEQ: cmp(vf, rd, rn, rm, eq); break; case NEON_CMGE: cmp(vf, rd, rn, rm, ge); break; case NEON_CMGT: cmp(vf, rd, rn, rm, gt); break; case NEON_CMHI: cmp(vf, rd, rn, rm, hi); break; case NEON_CMHS: cmp(vf, rd, rn, rm, hs); break; case NEON_CMTST: cmptst(vf, rd, rn, rm); break; case NEON_MLS: mls(vf, rd, rn, rm); break; case NEON_MLA: mla(vf, rd, rn, rm); break; case NEON_MUL: mul(vf, rd, rn, rm); break; case NEON_PMUL: pmul(vf, rd, rn, rm); break; case NEON_SMAX: smax(vf, rd, rn, rm); break; case NEON_SMAXP: smaxp(vf, rd, rn, rm); break; case NEON_SMIN: smin(vf, rd, rn, rm); break; case NEON_SMINP: sminp(vf, rd, rn, rm); break; case NEON_SUB: sub(vf, rd, rn, rm); break; case NEON_UMAX: umax(vf, rd, rn, rm); break; case NEON_UMAXP: umaxp(vf, rd, rn, rm); break; case NEON_UMIN: umin(vf, rd, rn, rm); break; case NEON_UMINP: uminp(vf, rd, rn, rm); break; case NEON_SSHL: sshl(vf, rd, rn, rm); break; case NEON_USHL: ushl(vf, rd, rn, rm); break; case NEON_SABD: absdiff(vf, rd, rn, rm, true); break; case NEON_UABD: absdiff(vf, rd, rn, rm, false); break; case NEON_SABA: saba(vf, rd, rn, rm); break; case NEON_UABA: uaba(vf, rd, rn, rm); break; case NEON_UQADD: add(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQADD: add(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_UQSUB: sub(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQSUB: sub(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_SQDMULH: sqdmulh(vf, rd, rn, rm); break; case NEON_SQRDMULH: sqrdmulh(vf, rd, rn, rm); break; case NEON_UQSHL: ushl(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQSHL: sshl(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_URSHL: ushl(vf, rd, rn, rm).Round(vf); break; case NEON_SRSHL: sshl(vf, rd, rn, rm).Round(vf); break; case NEON_UQRSHL: ushl(vf, rd, rn, rm).Round(vf).UnsignedSaturate(vf); break; case NEON_SQRSHL: sshl(vf, rd, rn, rm).Round(vf).SignedSaturate(vf); break; case NEON_UHADD: add(vf, rd, rn, rm).Uhalve(vf); break; case NEON_URHADD: add(vf, rd, rn, rm).Uhalve(vf).Round(vf); break; case NEON_SHADD: add(vf, rd, rn, rm).Halve(vf); break; case NEON_SRHADD: add(vf, rd, rn, rm).Halve(vf).Round(vf); break; case NEON_UHSUB: sub(vf, rd, rn, rm).Uhalve(vf); break; case NEON_SHSUB: sub(vf, rd, rn, rm).Halve(vf); break; default: VIXL_UNIMPLEMENTED(); } } } void Simulator::VisitNEON3Different(const Instruction* instr) { NEONFormatDecoder nfd(instr); VectorFormat vf = nfd.GetVectorFormat(); VectorFormat vf_l = nfd.GetVectorFormat(nfd.LongIntegerFormatMap()); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); switch (instr->Mask(NEON3DifferentMask)) { case NEON_PMULL: pmull(vf_l, rd, rn, rm); break; case NEON_PMULL2: pmull2(vf_l, rd, rn, rm); break; case NEON_UADDL: uaddl(vf_l, rd, rn, rm); break; case NEON_UADDL2: uaddl2(vf_l, rd, rn, rm); break; case NEON_SADDL: saddl(vf_l, rd, rn, rm); break; case NEON_SADDL2: saddl2(vf_l, rd, rn, rm); break; case NEON_USUBL: usubl(vf_l, rd, rn, rm); break; case NEON_USUBL2: usubl2(vf_l, rd, rn, rm); break; case NEON_SSUBL: ssubl(vf_l, rd, rn, rm); break; case NEON_SSUBL2: ssubl2(vf_l, rd, rn, rm); break; case NEON_SABAL: sabal(vf_l, rd, rn, rm); break; case NEON_SABAL2: sabal2(vf_l, rd, rn, rm); break; case NEON_UABAL: uabal(vf_l, rd, rn, rm); break; case NEON_UABAL2: uabal2(vf_l, rd, rn, rm); break; case NEON_SABDL: sabdl(vf_l, rd, rn, rm); break; case NEON_SABDL2: sabdl2(vf_l, rd, rn, rm); break; case NEON_UABDL: uabdl(vf_l, rd, rn, rm); break; case NEON_UABDL2: uabdl2(vf_l, rd, rn, rm); break; case NEON_SMLAL: smlal(vf_l, rd, rn, rm); break; case NEON_SMLAL2: smlal2(vf_l, rd, rn, rm); break; case NEON_UMLAL: umlal(vf_l, rd, rn, rm); break; case NEON_UMLAL2: umlal2(vf_l, rd, rn, rm); break; case NEON_SMLSL: smlsl(vf_l, rd, rn, rm); break; case NEON_SMLSL2: smlsl2(vf_l, rd, rn, rm); break; case NEON_UMLSL: umlsl(vf_l, rd, rn, rm); break; case NEON_UMLSL2: umlsl2(vf_l, rd, rn, rm); break; case NEON_SMULL: smull(vf_l, rd, rn, rm); break; case NEON_SMULL2: smull2(vf_l, rd, rn, rm); break; case NEON_UMULL: umull(vf_l, rd, rn, rm); break; case NEON_UMULL2: umull2(vf_l, rd, rn, rm); break; case NEON_SQDMLAL: sqdmlal(vf_l, rd, rn, rm); break; case NEON_SQDMLAL2: sqdmlal2(vf_l, rd, rn, rm); break; case NEON_SQDMLSL: sqdmlsl(vf_l, rd, rn, rm); break; case NEON_SQDMLSL2: sqdmlsl2(vf_l, rd, rn, rm); break; case NEON_SQDMULL: sqdmull(vf_l, rd, rn, rm); break; case NEON_SQDMULL2: sqdmull2(vf_l, rd, rn, rm); break; case NEON_UADDW: uaddw(vf_l, rd, rn, rm); break; case NEON_UADDW2: uaddw2(vf_l, rd, rn, rm); break; case NEON_SADDW: saddw(vf_l, rd, rn, rm); break; case NEON_SADDW2: saddw2(vf_l, rd, rn, rm); break; case NEON_USUBW: usubw(vf_l, rd, rn, rm); break; case NEON_USUBW2: usubw2(vf_l, rd, rn, rm); break; case NEON_SSUBW: ssubw(vf_l, rd, rn, rm); break; case NEON_SSUBW2: ssubw2(vf_l, rd, rn, rm); break; case NEON_ADDHN: addhn(vf, rd, rn, rm); break; case NEON_ADDHN2: addhn2(vf, rd, rn, rm); break; case NEON_RADDHN: raddhn(vf, rd, rn, rm); break; case NEON_RADDHN2: raddhn2(vf, rd, rn, rm); break; case NEON_SUBHN: subhn(vf, rd, rn, rm); break; case NEON_SUBHN2: subhn2(vf, rd, rn, rm); break; case NEON_RSUBHN: rsubhn(vf, rd, rn, rm); break; case NEON_RSUBHN2: rsubhn2(vf, rd, rn, rm); break; default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitNEONAcrossLanes(const Instruction* instr) { NEONFormatDecoder nfd(instr); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); // The input operand's VectorFormat is passed for these instructions. if (instr->Mask(NEONAcrossLanesFPFMask) == NEONAcrossLanesFPFixed) { VectorFormat vf = nfd.GetVectorFormat(nfd.FPFormatMap()); switch (instr->Mask(NEONAcrossLanesFPMask)) { case NEON_FMAXV: fmaxv(vf, rd, rn); break; case NEON_FMINV: fminv(vf, rd, rn); break; case NEON_FMAXNMV: fmaxnmv(vf, rd, rn); break; case NEON_FMINNMV: fminnmv(vf, rd, rn); break; default: VIXL_UNIMPLEMENTED(); } } else { VectorFormat vf = nfd.GetVectorFormat(); switch (instr->Mask(NEONAcrossLanesMask)) { case NEON_ADDV: addv(vf, rd, rn); break; case NEON_SMAXV: smaxv(vf, rd, rn); break; case NEON_SMINV: sminv(vf, rd, rn); break; case NEON_UMAXV: umaxv(vf, rd, rn); break; case NEON_UMINV: uminv(vf, rd, rn); break; case NEON_SADDLV: saddlv(vf, rd, rn); break; case NEON_UADDLV: uaddlv(vf, rd, rn); break; default: VIXL_UNIMPLEMENTED(); } } } void Simulator::VisitNEONByIndexedElement(const Instruction* instr) { NEONFormatDecoder nfd(instr); VectorFormat vf_r = nfd.GetVectorFormat(); VectorFormat vf = nfd.GetVectorFormat(nfd.LongIntegerFormatMap()); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); ByElementOp Op = NULL; int rm_reg = instr->Rm(); int index = (instr->NEONH() << 1) | instr->NEONL(); if (instr->NEONSize() == 1) { rm_reg &= 0xf; index = (index << 1) | instr->NEONM(); } switch (instr->Mask(NEONByIndexedElementMask)) { case NEON_MUL_byelement: Op = &Simulator::mul; vf = vf_r; break; case NEON_MLA_byelement: Op = &Simulator::mla; vf = vf_r; break; case NEON_MLS_byelement: Op = &Simulator::mls; vf = vf_r; break; case NEON_SQDMULH_byelement: Op = &Simulator::sqdmulh; vf = vf_r; break; case NEON_SQRDMULH_byelement: Op = &Simulator::sqrdmulh; vf = vf_r; break; case NEON_SMULL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::smull2; } else { Op = &Simulator::smull; } break; case NEON_UMULL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::umull2; } else { Op = &Simulator::umull; } break; case NEON_SMLAL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::smlal2; } else { Op = &Simulator::smlal; } break; case NEON_UMLAL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::umlal2; } else { Op = &Simulator::umlal; } break; case NEON_SMLSL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::smlsl2; } else { Op = &Simulator::smlsl; } break; case NEON_UMLSL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::umlsl2; } else { Op = &Simulator::umlsl; } break; case NEON_SQDMULL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::sqdmull2; } else { Op = &Simulator::sqdmull; } break; case NEON_SQDMLAL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::sqdmlal2; } else { Op = &Simulator::sqdmlal; } break; case NEON_SQDMLSL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::sqdmlsl2; } else { Op = &Simulator::sqdmlsl; } break; default: index = instr->NEONH(); if ((instr->FPType() & 1) == 0) { index = (index << 1) | instr->NEONL(); } vf = nfd.GetVectorFormat(nfd.FPFormatMap()); switch (instr->Mask(NEONByIndexedElementFPMask)) { case NEON_FMUL_byelement: Op = &Simulator::fmul; break; case NEON_FMLA_byelement: Op = &Simulator::fmla; break; case NEON_FMLS_byelement: Op = &Simulator::fmls; break; case NEON_FMULX_byelement: Op = &Simulator::fmulx; break; default: VIXL_UNIMPLEMENTED(); } } (this->*Op)(vf, rd, rn, vreg(rm_reg), index); } void Simulator::VisitNEONCopy(const Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::TriangularFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); int imm5 = instr->ImmNEON5(); int tz = CountTrailingZeros(imm5, 32); int reg_index = imm5 >> (tz + 1); if (instr->Mask(NEONCopyInsElementMask) == NEON_INS_ELEMENT) { int imm4 = instr->ImmNEON4(); int rn_index = imm4 >> tz; ins_element(vf, rd, reg_index, rn, rn_index); } else if (instr->Mask(NEONCopyInsGeneralMask) == NEON_INS_GENERAL) { ins_immediate(vf, rd, reg_index, xreg(instr->Rn())); } else if (instr->Mask(NEONCopyUmovMask) == NEON_UMOV) { uint64_t value = LogicVRegister(rn).Uint(vf, reg_index); value &= MaxUintFromFormat(vf); set_xreg(instr->Rd(), value); } else if (instr->Mask(NEONCopyUmovMask) == NEON_SMOV) { int64_t value = LogicVRegister(rn).Int(vf, reg_index); if (instr->NEONQ()) { set_xreg(instr->Rd(), value); } else { set_wreg(instr->Rd(), (int32_t)value); } } else if (instr->Mask(NEONCopyDupElementMask) == NEON_DUP_ELEMENT) { dup_element(vf, rd, rn, reg_index); } else if (instr->Mask(NEONCopyDupGeneralMask) == NEON_DUP_GENERAL) { dup_immediate(vf, rd, xreg(instr->Rn())); } else { VIXL_UNIMPLEMENTED(); } } void Simulator::VisitNEONExtract(const Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::LogicalFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); if (instr->Mask(NEONExtractMask) == NEON_EXT) { int index = instr->ImmNEONExt(); ext(vf, rd, rn, rm, index); } else { VIXL_UNIMPLEMENTED(); } } void Simulator::NEONLoadStoreMultiStructHelper(const Instruction* instr, AddrMode addr_mode) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::LoadStoreFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); uint64_t addr_base = xreg(instr->Rn(), Reg31IsStackPointer); int reg_size = RegisterSizeInBytesFromFormat(vf); int reg[4]; uint64_t addr[4]; for (int i = 0; i < 4; i++) { reg[i] = (instr->Rt() + i) % kNumberOfVRegisters; addr[i] = addr_base + (i * reg_size); } int count = 1; bool log_read = true; Instr itype = instr->Mask(NEONLoadStoreMultiStructMask); if (((itype == NEON_LD1_1v) || (itype == NEON_LD1_2v) || (itype == NEON_LD1_3v) || (itype == NEON_LD1_4v) || (itype == NEON_ST1_1v) || (itype == NEON_ST1_2v) || (itype == NEON_ST1_3v) || (itype == NEON_ST1_4v)) && (instr->Bits(20, 16) != 0)) { VIXL_UNREACHABLE(); } // We use the PostIndex mask here, as it works in this case for both Offset // and PostIndex addressing. switch (instr->Mask(NEONLoadStoreMultiStructPostIndexMask)) { case NEON_LD1_4v: case NEON_LD1_4v_post: ld1(vf, vreg(reg[3]), addr[3]); count++; VIXL_FALLTHROUGH(); case NEON_LD1_3v: case NEON_LD1_3v_post: ld1(vf, vreg(reg[2]), addr[2]); count++; VIXL_FALLTHROUGH(); case NEON_LD1_2v: case NEON_LD1_2v_post: ld1(vf, vreg(reg[1]), addr[1]); count++; VIXL_FALLTHROUGH(); case NEON_LD1_1v: case NEON_LD1_1v_post: ld1(vf, vreg(reg[0]), addr[0]); log_read = true; break; case NEON_ST1_4v: case NEON_ST1_4v_post: st1(vf, vreg(reg[3]), addr[3]); count++; VIXL_FALLTHROUGH(); case NEON_ST1_3v: case NEON_ST1_3v_post: st1(vf, vreg(reg[2]), addr[2]); count++; VIXL_FALLTHROUGH(); case NEON_ST1_2v: case NEON_ST1_2v_post: st1(vf, vreg(reg[1]), addr[1]); count++; VIXL_FALLTHROUGH(); case NEON_ST1_1v: case NEON_ST1_1v_post: st1(vf, vreg(reg[0]), addr[0]); log_read = false; break; case NEON_LD2_post: case NEON_LD2: ld2(vf, vreg(reg[0]), vreg(reg[1]), addr[0]); count = 2; break; case NEON_ST2: case NEON_ST2_post: st2(vf, vreg(reg[0]), vreg(reg[1]), addr[0]); count = 2; break; case NEON_LD3_post: case NEON_LD3: ld3(vf, vreg(reg[0]), vreg(reg[1]), vreg(reg[2]), addr[0]); count = 3; break; case NEON_ST3: case NEON_ST3_post: st3(vf, vreg(reg[0]), vreg(reg[1]), vreg(reg[2]), addr[0]); count = 3; break; case NEON_ST4: case NEON_ST4_post: st4(vf, vreg(reg[0]), vreg(reg[1]), vreg(reg[2]), vreg(reg[3]), addr[0]); count = 4; break; case NEON_LD4_post: case NEON_LD4: ld4(vf, vreg(reg[0]), vreg(reg[1]), vreg(reg[2]), vreg(reg[3]), addr[0]); count = 4; break; default: VIXL_UNIMPLEMENTED(); } // Explicitly log the register update whilst we have type information. for (int i = 0; i < count; i++) { // For de-interleaving loads, only print the base address. int lane_size = LaneSizeInBytesFromFormat(vf); PrintRegisterFormat format = GetPrintRegisterFormatTryFP( GetPrintRegisterFormatForSize(reg_size, lane_size)); if (log_read) { LogVRead(addr_base, reg[i], format); } else { LogVWrite(addr_base, reg[i], format); } } if (addr_mode == PostIndex) { int rm = instr->Rm(); // The immediate post index addressing mode is indicated by rm = 31. // The immediate is implied by the number of vector registers used. addr_base += (rm == 31) ? RegisterSizeInBytesFromFormat(vf) * count : xreg(rm); set_xreg(instr->Rn(), addr_base); } else { VIXL_ASSERT(addr_mode == Offset); } } void Simulator::VisitNEONLoadStoreMultiStruct(const Instruction* instr) { NEONLoadStoreMultiStructHelper(instr, Offset); } void Simulator::VisitNEONLoadStoreMultiStructPostIndex( const Instruction* instr) { NEONLoadStoreMultiStructHelper(instr, PostIndex); } void Simulator::NEONLoadStoreSingleStructHelper(const Instruction* instr, AddrMode addr_mode) { uint64_t addr = xreg(instr->Rn(), Reg31IsStackPointer); int rt = instr->Rt(); Instr itype = instr->Mask(NEONLoadStoreSingleStructMask); if (((itype == NEON_LD1_b) || (itype == NEON_LD1_h) || (itype == NEON_LD1_s) || (itype == NEON_LD1_d)) && (instr->Bits(20, 16) != 0)) { VIXL_UNREACHABLE(); } // We use the PostIndex mask here, as it works in this case for both Offset // and PostIndex addressing. bool do_load = false; NEONFormatDecoder nfd(instr, NEONFormatDecoder::LoadStoreFormatMap()); VectorFormat vf_t = nfd.GetVectorFormat(); VectorFormat vf = kFormat16B; switch (instr->Mask(NEONLoadStoreSingleStructPostIndexMask)) { case NEON_LD1_b: case NEON_LD1_b_post: case NEON_LD2_b: case NEON_LD2_b_post: case NEON_LD3_b: case NEON_LD3_b_post: case NEON_LD4_b: case NEON_LD4_b_post: do_load = true; VIXL_FALLTHROUGH(); case NEON_ST1_b: case NEON_ST1_b_post: case NEON_ST2_b: case NEON_ST2_b_post: case NEON_ST3_b: case NEON_ST3_b_post: case NEON_ST4_b: case NEON_ST4_b_post: break; case NEON_LD1_h: case NEON_LD1_h_post: case NEON_LD2_h: case NEON_LD2_h_post: case NEON_LD3_h: case NEON_LD3_h_post: case NEON_LD4_h: case NEON_LD4_h_post: do_load = true; VIXL_FALLTHROUGH(); case NEON_ST1_h: case NEON_ST1_h_post: case NEON_ST2_h: case NEON_ST2_h_post: case NEON_ST3_h: case NEON_ST3_h_post: case NEON_ST4_h: case NEON_ST4_h_post: vf = kFormat8H; break; case NEON_LD1_s: case NEON_LD1_s_post: case NEON_LD2_s: case NEON_LD2_s_post: case NEON_LD3_s: case NEON_LD3_s_post: case NEON_LD4_s: case NEON_LD4_s_post: do_load = true; VIXL_FALLTHROUGH(); case NEON_ST1_s: case NEON_ST1_s_post: case NEON_ST2_s: case NEON_ST2_s_post: case NEON_ST3_s: case NEON_ST3_s_post: case NEON_ST4_s: case NEON_ST4_s_post: { VIXL_STATIC_ASSERT((NEON_LD1_s | (1 << NEONLSSize_offset)) == NEON_LD1_d); VIXL_STATIC_ASSERT( (NEON_LD1_s_post | (1 << NEONLSSize_offset)) == NEON_LD1_d_post); VIXL_STATIC_ASSERT((NEON_ST1_s | (1 << NEONLSSize_offset)) == NEON_ST1_d); VIXL_STATIC_ASSERT( (NEON_ST1_s_post | (1 << NEONLSSize_offset)) == NEON_ST1_d_post); vf = ((instr->NEONLSSize() & 1) == 0) ? kFormat4S : kFormat2D; break; } case NEON_LD1R: case NEON_LD1R_post: { vf = vf_t; ld1r(vf, vreg(rt), addr); do_load = true; break; } case NEON_LD2R: case NEON_LD2R_post: { vf = vf_t; int rt2 = (rt + 1) % kNumberOfVRegisters; ld2r(vf, vreg(rt), vreg(rt2), addr); do_load = true; break; } case NEON_LD3R: case NEON_LD3R_post: { vf = vf_t; int rt2 = (rt + 1) % kNumberOfVRegisters; int rt3 = (rt2 + 1) % kNumberOfVRegisters; ld3r(vf, vreg(rt), vreg(rt2), vreg(rt3), addr); do_load = true; break; } case NEON_LD4R: case NEON_LD4R_post: { vf = vf_t; int rt2 = (rt + 1) % kNumberOfVRegisters; int rt3 = (rt2 + 1) % kNumberOfVRegisters; int rt4 = (rt3 + 1) % kNumberOfVRegisters; ld4r(vf, vreg(rt), vreg(rt2), vreg(rt3), vreg(rt4), addr); do_load = true; break; } default: VIXL_UNIMPLEMENTED(); } PrintRegisterFormat print_format = GetPrintRegisterFormatTryFP(GetPrintRegisterFormat(vf)); // Make sure that the print_format only includes a single lane. print_format = static_cast<PrintRegisterFormat>(print_format & ~kPrintRegAsVectorMask); int esize = LaneSizeInBytesFromFormat(vf); int index_shift = LaneSizeInBytesLog2FromFormat(vf); int lane = instr->NEONLSIndex(index_shift); int scale = 0; int rt2 = (rt + 1) % kNumberOfVRegisters; int rt3 = (rt2 + 1) % kNumberOfVRegisters; int rt4 = (rt3 + 1) % kNumberOfVRegisters; switch (instr->Mask(NEONLoadStoreSingleLenMask)) { case NEONLoadStoreSingle1: scale = 1; if (do_load) { ld1(vf, vreg(rt), lane, addr); LogVRead(addr, rt, print_format, lane); } else { st1(vf, vreg(rt), lane, addr); LogVWrite(addr, rt, print_format, lane); } break; case NEONLoadStoreSingle2: scale = 2; if (do_load) { ld2(vf, vreg(rt), vreg(rt2), lane, addr); LogVRead(addr, rt, print_format, lane); LogVRead(addr + esize, rt2, print_format, lane); } else { st2(vf, vreg(rt), vreg(rt2), lane, addr); LogVWrite(addr, rt, print_format, lane); LogVWrite(addr + esize, rt2, print_format, lane); } break; case NEONLoadStoreSingle3: scale = 3; if (do_load) { ld3(vf, vreg(rt), vreg(rt2), vreg(rt3), lane, addr); LogVRead(addr, rt, print_format, lane); LogVRead(addr + esize, rt2, print_format, lane); LogVRead(addr + (2 * esize), rt3, print_format, lane); } else { st3(vf, vreg(rt), vreg(rt2), vreg(rt3), lane, addr); LogVWrite(addr, rt, print_format, lane); LogVWrite(addr + esize, rt2, print_format, lane); LogVWrite(addr + (2 * esize), rt3, print_format, lane); } break; case NEONLoadStoreSingle4: scale = 4; if (do_load) { ld4(vf, vreg(rt), vreg(rt2), vreg(rt3), vreg(rt4), lane, addr); LogVRead(addr, rt, print_format, lane); LogVRead(addr + esize, rt2, print_format, lane); LogVRead(addr + (2 * esize), rt3, print_format, lane); LogVRead(addr + (3 * esize), rt4, print_format, lane); } else { st4(vf, vreg(rt), vreg(rt2), vreg(rt3), vreg(rt4), lane, addr); LogVWrite(addr, rt, print_format, lane); LogVWrite(addr + esize, rt2, print_format, lane); LogVWrite(addr + (2 * esize), rt3, print_format, lane); LogVWrite(addr + (3 * esize), rt4, print_format, lane); } break; default: VIXL_UNIMPLEMENTED(); } if (addr_mode == PostIndex) { int rm = instr->Rm(); int lane_size = LaneSizeInBytesFromFormat(vf); set_xreg(instr->Rn(), addr + ((rm == 31) ? (scale * lane_size) : xreg(rm))); } } void Simulator::VisitNEONLoadStoreSingleStruct(const Instruction* instr) { NEONLoadStoreSingleStructHelper(instr, Offset); } void Simulator::VisitNEONLoadStoreSingleStructPostIndex( const Instruction* instr) { NEONLoadStoreSingleStructHelper(instr, PostIndex); } void Simulator::VisitNEONModifiedImmediate(const Instruction* instr) { SimVRegister& rd = vreg(instr->Rd()); int cmode = instr->NEONCmode(); int cmode_3_1 = (cmode >> 1) & 7; int cmode_3 = (cmode >> 3) & 1; int cmode_2 = (cmode >> 2) & 1; int cmode_1 = (cmode >> 1) & 1; int cmode_0 = cmode & 1; int q = instr->NEONQ(); int op_bit = instr->NEONModImmOp(); uint64_t imm8 = instr->ImmNEONabcdefgh(); // Find the format and immediate value uint64_t imm = 0; VectorFormat vform = kFormatUndefined; switch (cmode_3_1) { case 0x0: case 0x1: case 0x2: case 0x3: vform = (q == 1) ? kFormat4S : kFormat2S; imm = imm8 << (8 * cmode_3_1); break; case 0x4: case 0x5: vform = (q == 1) ? kFormat8H : kFormat4H; imm = imm8 << (8 * cmode_1); break; case 0x6: vform = (q == 1) ? kFormat4S : kFormat2S; if (cmode_0 == 0) { imm = imm8 << 8 | 0x000000ff; } else { imm = imm8 << 16 | 0x0000ffff; } break; case 0x7: if (cmode_0 == 0 && op_bit == 0) { vform = q ? kFormat16B : kFormat8B; imm = imm8; } else if (cmode_0 == 0 && op_bit == 1) { vform = q ? kFormat2D : kFormat1D; imm = 0; for (int i = 0; i < 8; ++i) { if (imm8 & (1 << i)) { imm |= (UINT64_C(0xff) << (8 * i)); } } } else { // cmode_0 == 1, cmode == 0xf. if (op_bit == 0) { vform = q ? kFormat4S : kFormat2S; imm = float_to_rawbits(instr->ImmNEONFP32()); } else if (q == 1) { vform = kFormat2D; imm = double_to_rawbits(instr->ImmNEONFP64()); } else { VIXL_ASSERT((q == 0) && (op_bit == 1) && (cmode == 0xf)); VisitUnallocated(instr); } } break; default: VIXL_UNREACHABLE(); break; } // Find the operation NEONModifiedImmediateOp op; if (cmode_3 == 0) { if (cmode_0 == 0) { op = op_bit ? NEONModifiedImmediate_MVNI : NEONModifiedImmediate_MOVI; } else { // cmode<0> == '1' op = op_bit ? NEONModifiedImmediate_BIC : NEONModifiedImmediate_ORR; } } else { // cmode<3> == '1' if (cmode_2 == 0) { if (cmode_0 == 0) { op = op_bit ? NEONModifiedImmediate_MVNI : NEONModifiedImmediate_MOVI; } else { // cmode<0> == '1' op = op_bit ? NEONModifiedImmediate_BIC : NEONModifiedImmediate_ORR; } } else { // cmode<2> == '1' if (cmode_1 == 0) { op = op_bit ? NEONModifiedImmediate_MVNI : NEONModifiedImmediate_MOVI; } else { // cmode<1> == '1' if (cmode_0 == 0) { op = NEONModifiedImmediate_MOVI; } else { // cmode<0> == '1' op = NEONModifiedImmediate_MOVI; } } } } // Call the logic function if (op == NEONModifiedImmediate_ORR) { orr(vform, rd, rd, imm); } else if (op == NEONModifiedImmediate_BIC) { bic(vform, rd, rd, imm); } else if (op == NEONModifiedImmediate_MOVI) { movi(vform, rd, imm); } else if (op == NEONModifiedImmediate_MVNI) { mvni(vform, rd, imm); } else { VisitUnimplemented(instr); } } void Simulator::VisitNEONScalar2RegMisc(const Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::ScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); if (instr->Mask(NEON2RegMiscOpcode) <= NEON_NEG_scalar_opcode) { // These instructions all use a two bit size field, except NOT and RBIT, // which use the field to encode the operation. switch (instr->Mask(NEONScalar2RegMiscMask)) { case NEON_CMEQ_zero_scalar: cmp(vf, rd, rn, 0, eq); break; case NEON_CMGE_zero_scalar: cmp(vf, rd, rn, 0, ge); break; case NEON_CMGT_zero_scalar: cmp(vf, rd, rn, 0, gt); break; case NEON_CMLT_zero_scalar: cmp(vf, rd, rn, 0, lt); break; case NEON_CMLE_zero_scalar: cmp(vf, rd, rn, 0, le); break; case NEON_ABS_scalar: abs(vf, rd, rn); break; case NEON_SQABS_scalar: abs(vf, rd, rn).SignedSaturate(vf); break; case NEON_NEG_scalar: neg(vf, rd, rn); break; case NEON_SQNEG_scalar: neg(vf, rd, rn).SignedSaturate(vf); break; case NEON_SUQADD_scalar: suqadd(vf, rd, rn); break; case NEON_USQADD_scalar: usqadd(vf, rd, rn); break; default: VIXL_UNIMPLEMENTED(); break; } } else { VectorFormat fpf = nfd.GetVectorFormat(nfd.FPScalarFormatMap()); FPRounding fpcr_rounding = static_cast<FPRounding>(fpcr().RMode()); // These instructions all use a one bit size field, except SQXTUN, SQXTN // and UQXTN, which use a two bit size field. switch (instr->Mask(NEONScalar2RegMiscFPMask)) { case NEON_FRECPE_scalar: frecpe(fpf, rd, rn, fpcr_rounding); break; case NEON_FRECPX_scalar: frecpx(fpf, rd, rn); break; case NEON_FRSQRTE_scalar: frsqrte(fpf, rd, rn); break; case NEON_FCMGT_zero_scalar: fcmp_zero(fpf, rd, rn, gt); break; case NEON_FCMGE_zero_scalar: fcmp_zero(fpf, rd, rn, ge); break; case NEON_FCMEQ_zero_scalar: fcmp_zero(fpf, rd, rn, eq); break; case NEON_FCMLE_zero_scalar: fcmp_zero(fpf, rd, rn, le); break; case NEON_FCMLT_zero_scalar: fcmp_zero(fpf, rd, rn, lt); break; case NEON_SCVTF_scalar: scvtf(fpf, rd, rn, 0, fpcr_rounding); break; case NEON_UCVTF_scalar: ucvtf(fpf, rd, rn, 0, fpcr_rounding); break; case NEON_FCVTNS_scalar: fcvts(fpf, rd, rn, FPTieEven); break; case NEON_FCVTNU_scalar: fcvtu(fpf, rd, rn, FPTieEven); break; case NEON_FCVTPS_scalar: fcvts(fpf, rd, rn, FPPositiveInfinity); break; case NEON_FCVTPU_scalar: fcvtu(fpf, rd, rn, FPPositiveInfinity); break; case NEON_FCVTMS_scalar: fcvts(fpf, rd, rn, FPNegativeInfinity); break; case NEON_FCVTMU_scalar: fcvtu(fpf, rd, rn, FPNegativeInfinity); break; case NEON_FCVTZS_scalar: fcvts(fpf, rd, rn, FPZero); break; case NEON_FCVTZU_scalar: fcvtu(fpf, rd, rn, FPZero); break; case NEON_FCVTAS_scalar: fcvts(fpf, rd, rn, FPTieAway); break; case NEON_FCVTAU_scalar: fcvtu(fpf, rd, rn, FPTieAway); break; case NEON_FCVTXN_scalar: // Unlike all of the other FP instructions above, fcvtxn encodes dest // size S as size<0>=1. There's only one case, so we ignore the form. VIXL_ASSERT(instr->Bit(22) == 1); fcvtxn(kFormatS, rd, rn); break; default: switch (instr->Mask(NEONScalar2RegMiscMask)) { case NEON_SQXTN_scalar: sqxtn(vf, rd, rn); break; case NEON_UQXTN_scalar: uqxtn(vf, rd, rn); break; case NEON_SQXTUN_scalar: sqxtun(vf, rd, rn); break; default: VIXL_UNIMPLEMENTED(); } } } } void Simulator::VisitNEONScalar3Diff(const Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::LongScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); switch (instr->Mask(NEONScalar3DiffMask)) { case NEON_SQDMLAL_scalar: sqdmlal(vf, rd, rn, rm); break; case NEON_SQDMLSL_scalar: sqdmlsl(vf, rd, rn, rm); break; case NEON_SQDMULL_scalar: sqdmull(vf, rd, rn, rm); break; default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitNEONScalar3Same(const Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::ScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); if (instr->Mask(NEONScalar3SameFPFMask) == NEONScalar3SameFPFixed) { vf = nfd.GetVectorFormat(nfd.FPScalarFormatMap()); switch (instr->Mask(NEONScalar3SameFPMask)) { case NEON_FMULX_scalar: fmulx(vf, rd, rn, rm); break; case NEON_FACGE_scalar: fabscmp(vf, rd, rn, rm, ge); break; case NEON_FACGT_scalar: fabscmp(vf, rd, rn, rm, gt); break; case NEON_FCMEQ_scalar: fcmp(vf, rd, rn, rm, eq); break; case NEON_FCMGE_scalar: fcmp(vf, rd, rn, rm, ge); break; case NEON_FCMGT_scalar: fcmp(vf, rd, rn, rm, gt); break; case NEON_FRECPS_scalar: frecps(vf, rd, rn, rm); break; case NEON_FRSQRTS_scalar: frsqrts(vf, rd, rn, rm); break; case NEON_FABD_scalar: fabd(vf, rd, rn, rm); break; default: VIXL_UNIMPLEMENTED(); } } else { switch (instr->Mask(NEONScalar3SameMask)) { case NEON_ADD_scalar: add(vf, rd, rn, rm); break; case NEON_SUB_scalar: sub(vf, rd, rn, rm); break; case NEON_CMEQ_scalar: cmp(vf, rd, rn, rm, eq); break; case NEON_CMGE_scalar: cmp(vf, rd, rn, rm, ge); break; case NEON_CMGT_scalar: cmp(vf, rd, rn, rm, gt); break; case NEON_CMHI_scalar: cmp(vf, rd, rn, rm, hi); break; case NEON_CMHS_scalar: cmp(vf, rd, rn, rm, hs); break; case NEON_CMTST_scalar: cmptst(vf, rd, rn, rm); break; case NEON_USHL_scalar: ushl(vf, rd, rn, rm); break; case NEON_SSHL_scalar: sshl(vf, rd, rn, rm); break; case NEON_SQDMULH_scalar: sqdmulh(vf, rd, rn, rm); break; case NEON_SQRDMULH_scalar: sqrdmulh(vf, rd, rn, rm); break; case NEON_UQADD_scalar: add(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQADD_scalar: add(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_UQSUB_scalar: sub(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQSUB_scalar: sub(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_UQSHL_scalar: ushl(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQSHL_scalar: sshl(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_URSHL_scalar: ushl(vf, rd, rn, rm).Round(vf); break; case NEON_SRSHL_scalar: sshl(vf, rd, rn, rm).Round(vf); break; case NEON_UQRSHL_scalar: ushl(vf, rd, rn, rm).Round(vf).UnsignedSaturate(vf); break; case NEON_SQRSHL_scalar: sshl(vf, rd, rn, rm).Round(vf).SignedSaturate(vf); break; default: VIXL_UNIMPLEMENTED(); } } } void Simulator::VisitNEONScalarByIndexedElement(const Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::LongScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); VectorFormat vf_r = nfd.GetVectorFormat(nfd.ScalarFormatMap()); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); ByElementOp Op = NULL; int rm_reg = instr->Rm(); int index = (instr->NEONH() << 1) | instr->NEONL(); if (instr->NEONSize() == 1) { rm_reg &= 0xf; index = (index << 1) | instr->NEONM(); } switch (instr->Mask(NEONScalarByIndexedElementMask)) { case NEON_SQDMULL_byelement_scalar: Op = &Simulator::sqdmull; break; case NEON_SQDMLAL_byelement_scalar: Op = &Simulator::sqdmlal; break; case NEON_SQDMLSL_byelement_scalar: Op = &Simulator::sqdmlsl; break; case NEON_SQDMULH_byelement_scalar: Op = &Simulator::sqdmulh; vf = vf_r; break; case NEON_SQRDMULH_byelement_scalar: Op = &Simulator::sqrdmulh; vf = vf_r; break; default: vf = nfd.GetVectorFormat(nfd.FPScalarFormatMap()); index = instr->NEONH(); if ((instr->FPType() & 1) == 0) { index = (index << 1) | instr->NEONL(); } switch (instr->Mask(NEONScalarByIndexedElementFPMask)) { case NEON_FMUL_byelement_scalar: Op = &Simulator::fmul; break; case NEON_FMLA_byelement_scalar: Op = &Simulator::fmla; break; case NEON_FMLS_byelement_scalar: Op = &Simulator::fmls; break; case NEON_FMULX_byelement_scalar: Op = &Simulator::fmulx; break; default: VIXL_UNIMPLEMENTED(); } } (this->*Op)(vf, rd, rn, vreg(rm_reg), index); } void Simulator::VisitNEONScalarCopy(const Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::TriangularScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); if (instr->Mask(NEONScalarCopyMask) == NEON_DUP_ELEMENT_scalar) { int imm5 = instr->ImmNEON5(); int tz = CountTrailingZeros(imm5, 32); int rn_index = imm5 >> (tz + 1); dup_element(vf, rd, rn, rn_index); } else { VIXL_UNIMPLEMENTED(); } } void Simulator::VisitNEONScalarPairwise(const Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::FPScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); switch (instr->Mask(NEONScalarPairwiseMask)) { case NEON_ADDP_scalar: addp(vf, rd, rn); break; case NEON_FADDP_scalar: faddp(vf, rd, rn); break; case NEON_FMAXP_scalar: fmaxp(vf, rd, rn); break; case NEON_FMAXNMP_scalar: fmaxnmp(vf, rd, rn); break; case NEON_FMINP_scalar: fminp(vf, rd, rn); break; case NEON_FMINNMP_scalar: fminnmp(vf, rd, rn); break; default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitNEONScalarShiftImmediate(const Instruction* instr) { SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); FPRounding fpcr_rounding = static_cast<FPRounding>(fpcr().RMode()); static const NEONFormatMap map = { {22, 21, 20, 19}, {NF_UNDEF, NF_B, NF_H, NF_H, NF_S, NF_S, NF_S, NF_S, NF_D, NF_D, NF_D, NF_D, NF_D, NF_D, NF_D, NF_D} }; NEONFormatDecoder nfd(instr, &map); VectorFormat vf = nfd.GetVectorFormat(); int highestSetBit = HighestSetBitPosition(instr->ImmNEONImmh()); int immhimmb = instr->ImmNEONImmhImmb(); int right_shift = (16 << highestSetBit) - immhimmb; int left_shift = immhimmb - (8 << highestSetBit); switch (instr->Mask(NEONScalarShiftImmediateMask)) { case NEON_SHL_scalar: shl(vf, rd, rn, left_shift); break; case NEON_SLI_scalar: sli(vf, rd, rn, left_shift); break; case NEON_SQSHL_imm_scalar: sqshl(vf, rd, rn, left_shift); break; case NEON_UQSHL_imm_scalar: uqshl(vf, rd, rn, left_shift); break; case NEON_SQSHLU_scalar: sqshlu(vf, rd, rn, left_shift); break; case NEON_SRI_scalar: sri(vf, rd, rn, right_shift); break; case NEON_SSHR_scalar: sshr(vf, rd, rn, right_shift); break; case NEON_USHR_scalar: ushr(vf, rd, rn, right_shift); break; case NEON_SRSHR_scalar: sshr(vf, rd, rn, right_shift).Round(vf); break; case NEON_URSHR_scalar: ushr(vf, rd, rn, right_shift).Round(vf); break; case NEON_SSRA_scalar: ssra(vf, rd, rn, right_shift); break; case NEON_USRA_scalar: usra(vf, rd, rn, right_shift); break; case NEON_SRSRA_scalar: srsra(vf, rd, rn, right_shift); break; case NEON_URSRA_scalar: ursra(vf, rd, rn, right_shift); break; case NEON_UQSHRN_scalar: uqshrn(vf, rd, rn, right_shift); break; case NEON_UQRSHRN_scalar: uqrshrn(vf, rd, rn, right_shift); break; case NEON_SQSHRN_scalar: sqshrn(vf, rd, rn, right_shift); break; case NEON_SQRSHRN_scalar: sqrshrn(vf, rd, rn, right_shift); break; case NEON_SQSHRUN_scalar: sqshrun(vf, rd, rn, right_shift); break; case NEON_SQRSHRUN_scalar: sqrshrun(vf, rd, rn, right_shift); break; case NEON_FCVTZS_imm_scalar: fcvts(vf, rd, rn, FPZero, right_shift); break; case NEON_FCVTZU_imm_scalar: fcvtu(vf, rd, rn, FPZero, right_shift); break; case NEON_SCVTF_imm_scalar: scvtf(vf, rd, rn, right_shift, fpcr_rounding); break; case NEON_UCVTF_imm_scalar: ucvtf(vf, rd, rn, right_shift, fpcr_rounding); break; default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitNEONShiftImmediate(const Instruction* instr) { SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); FPRounding fpcr_rounding = static_cast<FPRounding>(fpcr().RMode()); // 00010->8B, 00011->16B, 001x0->4H, 001x1->8H, // 01xx0->2S, 01xx1->4S, 1xxx1->2D, all others undefined. static const NEONFormatMap map = { {22, 21, 20, 19, 30}, {NF_UNDEF, NF_UNDEF, NF_8B, NF_16B, NF_4H, NF_8H, NF_4H, NF_8H, NF_2S, NF_4S, NF_2S, NF_4S, NF_2S, NF_4S, NF_2S, NF_4S, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D} }; NEONFormatDecoder nfd(instr, &map); VectorFormat vf = nfd.GetVectorFormat(); // 0001->8H, 001x->4S, 01xx->2D, all others undefined. static const NEONFormatMap map_l = { {22, 21, 20, 19}, {NF_UNDEF, NF_8H, NF_4S, NF_4S, NF_2D, NF_2D, NF_2D, NF_2D} }; VectorFormat vf_l = nfd.GetVectorFormat(&map_l); int highestSetBit = HighestSetBitPosition(instr->ImmNEONImmh()); int immhimmb = instr->ImmNEONImmhImmb(); int right_shift = (16 << highestSetBit) - immhimmb; int left_shift = immhimmb - (8 << highestSetBit); switch (instr->Mask(NEONShiftImmediateMask)) { case NEON_SHL: shl(vf, rd, rn, left_shift); break; case NEON_SLI: sli(vf, rd, rn, left_shift); break; case NEON_SQSHLU: sqshlu(vf, rd, rn, left_shift); break; case NEON_SRI: sri(vf, rd, rn, right_shift); break; case NEON_SSHR: sshr(vf, rd, rn, right_shift); break; case NEON_USHR: ushr(vf, rd, rn, right_shift); break; case NEON_SRSHR: sshr(vf, rd, rn, right_shift).Round(vf); break; case NEON_URSHR: ushr(vf, rd, rn, right_shift).Round(vf); break; case NEON_SSRA: ssra(vf, rd, rn, right_shift); break; case NEON_USRA: usra(vf, rd, rn, right_shift); break; case NEON_SRSRA: srsra(vf, rd, rn, right_shift); break; case NEON_URSRA: ursra(vf, rd, rn, right_shift); break; case NEON_SQSHL_imm: sqshl(vf, rd, rn, left_shift); break; case NEON_UQSHL_imm: uqshl(vf, rd, rn, left_shift); break; case NEON_SCVTF_imm: scvtf(vf, rd, rn, right_shift, fpcr_rounding); break; case NEON_UCVTF_imm: ucvtf(vf, rd, rn, right_shift, fpcr_rounding); break; case NEON_FCVTZS_imm: fcvts(vf, rd, rn, FPZero, right_shift); break; case NEON_FCVTZU_imm: fcvtu(vf, rd, rn, FPZero, right_shift); break; case NEON_SSHLL: vf = vf_l; if (instr->Mask(NEON_Q)) { sshll2(vf, rd, rn, left_shift); } else { sshll(vf, rd, rn, left_shift); } break; case NEON_USHLL: vf = vf_l; if (instr->Mask(NEON_Q)) { ushll2(vf, rd, rn, left_shift); } else { ushll(vf, rd, rn, left_shift); } break; case NEON_SHRN: if (instr->Mask(NEON_Q)) { shrn2(vf, rd, rn, right_shift); } else { shrn(vf, rd, rn, right_shift); } break; case NEON_RSHRN: if (instr->Mask(NEON_Q)) { rshrn2(vf, rd, rn, right_shift); } else { rshrn(vf, rd, rn, right_shift); } break; case NEON_UQSHRN: if (instr->Mask(NEON_Q)) { uqshrn2(vf, rd, rn, right_shift); } else { uqshrn(vf, rd, rn, right_shift); } break; case NEON_UQRSHRN: if (instr->Mask(NEON_Q)) { uqrshrn2(vf, rd, rn, right_shift); } else { uqrshrn(vf, rd, rn, right_shift); } break; case NEON_SQSHRN: if (instr->Mask(NEON_Q)) { sqshrn2(vf, rd, rn, right_shift); } else { sqshrn(vf, rd, rn, right_shift); } break; case NEON_SQRSHRN: if (instr->Mask(NEON_Q)) { sqrshrn2(vf, rd, rn, right_shift); } else { sqrshrn(vf, rd, rn, right_shift); } break; case NEON_SQSHRUN: if (instr->Mask(NEON_Q)) { sqshrun2(vf, rd, rn, right_shift); } else { sqshrun(vf, rd, rn, right_shift); } break; case NEON_SQRSHRUN: if (instr->Mask(NEON_Q)) { sqrshrun2(vf, rd, rn, right_shift); } else { sqrshrun(vf, rd, rn, right_shift); } break; default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitNEONTable(const Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::LogicalFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rn2 = vreg((instr->Rn() + 1) % kNumberOfVRegisters); SimVRegister& rn3 = vreg((instr->Rn() + 2) % kNumberOfVRegisters); SimVRegister& rn4 = vreg((instr->Rn() + 3) % kNumberOfVRegisters); SimVRegister& rm = vreg(instr->Rm()); switch (instr->Mask(NEONTableMask)) { case NEON_TBL_1v: tbl(vf, rd, rn, rm); break; case NEON_TBL_2v: tbl(vf, rd, rn, rn2, rm); break; case NEON_TBL_3v: tbl(vf, rd, rn, rn2, rn3, rm); break; case NEON_TBL_4v: tbl(vf, rd, rn, rn2, rn3, rn4, rm); break; case NEON_TBX_1v: tbx(vf, rd, rn, rm); break; case NEON_TBX_2v: tbx(vf, rd, rn, rn2, rm); break; case NEON_TBX_3v: tbx(vf, rd, rn, rn2, rn3, rm); break; case NEON_TBX_4v: tbx(vf, rd, rn, rn2, rn3, rn4, rm); break; default: VIXL_UNIMPLEMENTED(); } } void Simulator::VisitNEONPerm(const Instruction* instr) { NEONFormatDecoder nfd(instr); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); switch (instr->Mask(NEONPermMask)) { case NEON_TRN1: trn1(vf, rd, rn, rm); break; case NEON_TRN2: trn2(vf, rd, rn, rm); break; case NEON_UZP1: uzp1(vf, rd, rn, rm); break; case NEON_UZP2: uzp2(vf, rd, rn, rm); break; case NEON_ZIP1: zip1(vf, rd, rn, rm); break; case NEON_ZIP2: zip2(vf, rd, rn, rm); break; default: VIXL_UNIMPLEMENTED(); } } void Simulator::DoUnreachable(const Instruction* instr) { VIXL_ASSERT((instr->Mask(ExceptionMask) == HLT) && (instr->ImmException() == kUnreachableOpcode)); fprintf(stream_, "Hit UNREACHABLE marker at pc=%p.\n", reinterpret_cast<const void*>(instr)); abort(); } void Simulator::DoTrace(const Instruction* instr) { VIXL_ASSERT((instr->Mask(ExceptionMask) == HLT) && (instr->ImmException() == kTraceOpcode)); // Read the arguments encoded inline in the instruction stream. uint32_t parameters; uint32_t command; VIXL_STATIC_ASSERT(sizeof(*instr) == 1); memcpy(&parameters, instr + kTraceParamsOffset, sizeof(parameters)); memcpy(&command, instr + kTraceCommandOffset, sizeof(command)); switch (command) { case TRACE_ENABLE: set_trace_parameters(trace_parameters() | parameters); break; case TRACE_DISABLE: set_trace_parameters(trace_parameters() & ~parameters); break; default: VIXL_UNREACHABLE(); } set_pc(instr->InstructionAtOffset(kTraceLength)); } void Simulator::DoLog(const Instruction* instr) { VIXL_ASSERT((instr->Mask(ExceptionMask) == HLT) && (instr->ImmException() == kLogOpcode)); // Read the arguments encoded inline in the instruction stream. uint32_t parameters; VIXL_STATIC_ASSERT(sizeof(*instr) == 1); memcpy(&parameters, instr + kTraceParamsOffset, sizeof(parameters)); // We don't support a one-shot LOG_DISASM. VIXL_ASSERT((parameters & LOG_DISASM) == 0); // Print the requested information. if (parameters & LOG_SYSREGS) PrintSystemRegisters(); if (parameters & LOG_REGS) PrintRegisters(); if (parameters & LOG_VREGS) PrintVRegisters(); set_pc(instr->InstructionAtOffset(kLogLength)); } void Simulator::DoPrintf(const Instruction* instr) { VIXL_ASSERT((instr->Mask(ExceptionMask) == HLT) && (instr->ImmException() == kPrintfOpcode)); // Read the arguments encoded inline in the instruction stream. uint32_t arg_count; uint32_t arg_pattern_list; VIXL_STATIC_ASSERT(sizeof(*instr) == 1); memcpy(&arg_count, instr + kPrintfArgCountOffset, sizeof(arg_count)); memcpy(&arg_pattern_list, instr + kPrintfArgPatternListOffset, sizeof(arg_pattern_list)); VIXL_ASSERT(arg_count <= kPrintfMaxArgCount); VIXL_ASSERT((arg_pattern_list >> (kPrintfArgPatternBits * arg_count)) == 0); // We need to call the host printf function with a set of arguments defined by // arg_pattern_list. Because we don't know the types and sizes of the // arguments, this is very difficult to do in a robust and portable way. To // work around the problem, we pick apart the format string, and print one // format placeholder at a time. // Allocate space for the format string. We take a copy, so we can modify it. // Leave enough space for one extra character per expected argument (plus the // '\0' termination). const char * format_base = reg<const char *>(0); VIXL_ASSERT(format_base != NULL); size_t length = strlen(format_base) + 1; char * const format = new char[length + arg_count]; // A list of chunks, each with exactly one format placeholder. const char * chunks[kPrintfMaxArgCount]; // Copy the format string and search for format placeholders. uint32_t placeholder_count = 0; char * format_scratch = format; for (size_t i = 0; i < length; i++) { if (format_base[i] != '%') { *format_scratch++ = format_base[i]; } else { if (format_base[i + 1] == '%') { // Ignore explicit "%%" sequences. *format_scratch++ = format_base[i]; i++; // Chunks after the first are passed as format strings to printf, so we // need to escape '%' characters in those chunks. if (placeholder_count > 0) *format_scratch++ = format_base[i]; } else { VIXL_CHECK(placeholder_count < arg_count); // Insert '\0' before placeholders, and store their locations. *format_scratch++ = '\0'; chunks[placeholder_count++] = format_scratch; *format_scratch++ = format_base[i]; } } } VIXL_CHECK(placeholder_count == arg_count); // Finally, call printf with each chunk, passing the appropriate register // argument. Normally, printf returns the number of bytes transmitted, so we // can emulate a single printf call by adding the result from each chunk. If // any call returns a negative (error) value, though, just return that value. printf("%s", clr_printf); // Because '\0' is inserted before each placeholder, the first string in // 'format' contains no format placeholders and should be printed literally. int result = printf("%s", format); int pcs_r = 1; // Start at x1. x0 holds the format string. int pcs_f = 0; // Start at d0. if (result >= 0) { for (uint32_t i = 0; i < placeholder_count; i++) { int part_result = -1; uint32_t arg_pattern = arg_pattern_list >> (i * kPrintfArgPatternBits); arg_pattern &= (1 << kPrintfArgPatternBits) - 1; switch (arg_pattern) { case kPrintfArgW: part_result = printf(chunks[i], wreg(pcs_r++)); break; case kPrintfArgX: part_result = printf(chunks[i], xreg(pcs_r++)); break; case kPrintfArgD: part_result = printf(chunks[i], dreg(pcs_f++)); break; default: VIXL_UNREACHABLE(); } if (part_result < 0) { // Handle error values. result = part_result; break; } result += part_result; } } printf("%s", clr_normal); // Printf returns its result in x0 (just like the C library's printf). set_xreg(0, result); // The printf parameters are inlined in the code, so skip them. set_pc(instr->InstructionAtOffset(kPrintfLength)); // Set LR as if we'd just called a native printf function. set_lr(pc()); delete[] format; } } // namespace vixl #endif // VIXL_INCLUDE_SIMULATOR
[ "Justin" ]
Justin
f811acdff3446d2094def392590e01da4209de87
2f8a6900b6ec50c3bacf14fae8cdbd6173335af0
/src/common.cpp
e98bf575e4356c057f697777a056152f333f5e07
[]
no_license
pinfort/curl-kuin-bridge
470a68eceef2471ca6646e9524a31347b7daf989
3fdc48c61a0c39cea5063ea416d56d80f9a39ab7
refs/heads/master
2021-07-25T13:12:58.989859
2020-12-16T14:04:37
2020-12-16T14:04:37
229,768,326
0
0
null
null
null
null
UTF-8
C++
false
false
1,057
cpp
#pragma once #include "common.h" #include <stdexcept> std::string WstrToStr(std::wstring wstr) { int len_str = wstr.length(); size_t len = (size_t)(WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), len_str, NULL, 0, NULL, NULL)); char* buf = (char*)malloc(sizeof(char) * (len + 1)); memset(buf, 0, sizeof(char) * (len + 1)); if (WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), len_str, buf, (int)len, NULL, NULL) != (int)len) { free(buf); std::runtime_error("wchar_t char convert failed\n"); } buf[len] = '\0'; std::string retVal(buf); return retVal; } std::wstring StrToWstr(std::string str) { int len_str = str.length(); size_t len = (size_t)MultiByteToWideChar(CP_UTF8, 0, str.c_str(), len_str, NULL, 0); wchar_t* buf = (wchar_t*)malloc(sizeof(wchar_t) * (len + 1)); memset(buf, 0, sizeof(wchar_t) * (len + 1)); if (MultiByteToWideChar(CP_UTF8, 0, str.c_str(), len_str, buf, (int)len) != (int)len) { free(buf); std::runtime_error("char wchar_t convert failed\n");; } buf[len] = '\0'; std::wstring retVal(buf); return retVal; }
[ "ptg@nijitei.com" ]
ptg@nijitei.com
249698d6313dcfb2bf115c9375449c58e97cbbd1
c6a859dfaf7516cca0fc4e94ad6e4401358ac4a0
/trianglesurface.h
525b4cd58f7069a1024d7887825d0560cd237e5e
[]
no_license
WaerjakSC/VSIMOblig
bdecc87646060b1d85f5b00af5e1e00f22cee697
f9b159c1733f8cedca4280f18b1290d1a4c9d7ec
refs/heads/master
2020-08-03T09:24:54.634330
2019-11-05T08:42:27
2019-11-05T08:42:27
211,699,838
0
4
null
2019-11-05T08:42:28
2019-09-29T17:28:06
C++
UTF-8
C++
false
false
525
h
#ifndef TRIANGLESURFACE_H #define TRIANGLESURFACE_H #include "visualobject.h" class TriangleSurface : public VisualObject { public: TriangleSurface(); TriangleSurface(std::string filename); ~TriangleSurface() override; virtual void init() override; virtual void draw() override; virtual void readFile(std::string filename); void writeFile(std::string filename); void construct(); void createSurface(); std::vector<gsl::Vector3D> getTrianglePoints(); }; #endif //TRIANGLESURFACE_H
[ "waerjaksc@gmail.com" ]
waerjaksc@gmail.com
2cc8cdd027103a1c42fc9d3385b2d14014ab0885
dd239ca86acad10971fb6d743464865e2eda18cd
/tracker/refiner/feature_refiner_klt.cc
5bc624505866d20ebe0e8ede38f6bcbf439cc837
[ "BSD-3-Clause" ]
permissive
ivankreso/stereo-vision
80bae794d0d78739df88ffefec0ff40bfcc4362e
2e2638c2f47e9c0d1c023598923d5c0ce85da200
refs/heads/master
2021-07-22T22:19:32.350972
2021-02-14T08:13:28
2021-02-14T08:13:28
55,307,848
55
26
NOASSERTION
2021-02-14T08:13:29
2016-04-02T17:40:56
C++
UTF-8
C++
false
false
17,046
cc
#include "feature_refiner_klt.h" #include <iostream> #include <iomanip> #include <sstream> #include <memory> #include <cassert> namespace{ ///////////////////////////////////////////////////////////// // image processing double interpolate( double x, double y, const core::Image& img) { assert(img.szPixel_==4); const int x_floor = (int)x; const int y_floor = (int)y; assert(x_floor>=0 && x_floor<img.cols_-1); assert(y_floor>=0 && y_floor<img.rows_-1); float const *psrc = (float const *) img.data_; float const *ppix0 = psrc + y_floor * img.cols_ + x_floor; float const *ppix1 = ppix0 + img.cols_; double dx = x - x_floor; double dy = y - y_floor; double dxdy = dx * dy; double result = dxdy * ppix1[1]; result += (dx - dxdy) * ppix0[1]; result += (dy - dxdy) * ppix1[0]; result += (1 -dx -dy +dxdy) * ppix0[0]; return result; } void getReferenceImages( const core::Image& src, /* source image */ track::refiner::FeatureData& fi) /* feature position, output */ { assert(src.szPixel_==4); const int hw=fi.width()/2; const int hh=fi.height()/2; float* pmagdst=(float*)fi.ref_.data_; for (int y=-hh; y<=hh; ++y){ for (int x=-hw ; x<=hw; ++x) *pmagdst++ = interpolate(fi.posx() + x, fi.posy() + y, src); } } // old without subpixel references //void getReferenceImages( // const core::Image& src, /* source image */ // track::refiner::FeatureData& fi) /* feature position, output */ //{ // assert(src.szPixel_==4); // const int x0 = std::round(fi.posx()); // assert(fi.posx() == x0); // const int y0 = std::round(fi.posy()); // assert(fi.posy() == y0); // const int hw=fi.width()/2; // assert(x0>hw && x0<src.cols_-hw); // const int hh=fi.height()/2; // assert(y0>hh && y0<src.rows_-hh); // float* pmagdst=(float*)fi.ref_.data_; // // for (int y=y0-hh; y<=y0+hh; ++y){ // float const* pmagsrc=src.pcbits<float>() + y*src.cols_ + x0-hw; // float const* pmagsrcEnd=pmagsrc+2*hw+1; // while (pmagsrc<pmagsrcEnd){ // *pmagdst++=*pmagsrc++; // } // } //} void computeWarpedGradient( const core::ImageSet& src, /* source images */ const track::refiner::FeatureData& fi, /* feature position */ const core::Image& gwgx, /* geometrically warped gradient x */ const core::Image& gwgy) /* geometrically warped gradient y */ { float* pgwgx =(float*)gwgx.data_; float* pgwgy =(float*)gwgy.data_; const int hw=fi.width()/2; const int hh=fi.height()/2; for (int y=-hh; y<=hh; ++y){ for (int x=-hw ; x<=hw; ++x){ double xsrc = fi.warpx(x,y); double ysrc = fi.warpy(x,y); *pgwgx++ = interpolate(xsrc,ysrc, src.gx_); *pgwgy++ = interpolate(xsrc,ysrc, src.gy_); } } } double computeError( const core::ImageSet& src, /* source images */ track::refiner::FeatureData& fi, /* feature position, some outputs */ core::Image& gwimg) /* geometrically warped image */ { double residue=0; float const* pref =(float const*)fi.ref_.data_; // reference float* pgwimg =(float*)gwimg.data_; // geometric warp float* pwarped =(float*)fi.warped_.data_; // geometric+photometric warp float* perror =(float*)fi.error_.data_; const int hw=fi.width()/2; const int hh=fi.height()/2; for (int y=-hh; y<=hh; ++y){ for (int x=-hw ; x<=hw; ++x){ double gw_smooth=interpolate(fi.warpx(x,y),fi.warpy(x,y), src.smooth_); double warped = fi.lambda() * gw_smooth + fi.delta(); double error = warped - *pref++; *pgwimg++ = gw_smooth; *pwarped++ = warped; *perror++ = error; residue+= error*error; } } return sqrt(residue/fi.width()/fi.height()); } ///////////////////////////////////////////////////////////// // linear system solving // taken (almost) verbatim from http://www.ces.clemson.edu/~stb/klt/ int _am_gauss_jordan_elimination(double **a, int n, double **b, int m) { /* re-implemented from Numerical Recipes in C */ int *indxc,*indxr,*ipiv; int i,j,k,l,ll; double big,dum,pivinv; int col = 0; int row = 0; assert(n > 0); indxc=(int *)malloc((size_t) (n*sizeof(int))); indxr=(int *)malloc((size_t) (n*sizeof(int))); ipiv=(int *)malloc((size_t) (n*sizeof(int))); for (j=0;j<n;j++) ipiv[j]=0; for (i=0;i<n;i++) { big=0.0; for (j=0;j<n;j++) if (ipiv[j] != 1) for (k=0;k<n;k++) { if (ipiv[k] == 0) { if (fabs(a[j][k]) >= big) { big=fabs(a[j][k]); row=j; col=k; } } else if (ipiv[k] > 1) return false; } ++(ipiv[col]); if (row != col) { for (l=0;l<n;l++) std::swap(a[row][l],a[col][l]); for (l=0;l<m;l++) std::swap(b[row][l],b[col][l]); } indxr[i]=row; indxc[i]=col; if (a[col][col] == 0.0) return false; pivinv=1.0f/a[col][col]; a[col][col]=1.0; for (l=0;l<n;l++) a[col][l] *= pivinv; for (l=0;l<m;l++) b[col][l] *= pivinv; for (ll=0;ll<n;ll++) if (ll != col) { dum=a[ll][col]; a[ll][col]=0.0; for (l=0;l<n;l++) a[ll][l] -= a[col][l]*dum; for (l=0;l<m;l++) b[ll][l] -= b[col][l]*dum; } } for (l=n-1;l>=0;l--) { if (indxr[l] != indxc[l]) for (k=0;k<n;k++) std::swap(a[k][indxr[l]],a[k][indxc[l]]); } free(ipiv); free(indxr); free(indxc); return true; } std::vector<double> solve( std::vector<std::vector<double> >& LS) { int n=LS.size()-1; double** a=(double**)malloc(n * sizeof(double*)); double** b=(double**)malloc(n * sizeof(double*)); for (int i=0; i<n; ++i){ a[i]=&LS[i][0]; b[i]=&LS[n][i]; } bool success=_am_gauss_jordan_elimination(a,n,b,1); std::vector<double> result; if (success){ result.resize(n); for (int i=0; i<n; ++i){ result[i] = -b[i][0]; // Ax+b=0 vs Ax=b } } free(a); free(b); return result; } int testSolver(){ try{throw 1;} catch (int){}; std::vector<std::vector<double> > LS(3); LS[0]={1,2}; LS[1]={2,2}; LS[2]={5,6}; std::vector<double> result=solve(LS); std::cerr <<"solution: "; for (auto q: result){ std::cerr <<q <<" "; } std::cerr <<"\n"; exit(0); return 0; } //bool success=testSolver(); ///////////////////////////////////////////////////////////////////////////////// // Various trackers class LKTracker{ protected: int hw_; int hh_; std::vector<std::vector<double> > LS_; std::vector<double> solution_; std::vector<double> g_; public: virtual std::vector<double> track( float const* pgwgx, float const* pgwgy, float const* perror, float const* pgwimg, double lambda); protected: virtual void constructSystem( float const* pgwgx, float const* pgwgy, float const* perror, float const* pgwimg, double lambda)=0; virtual void adjustSolution(){} protected: void updateLinearSystem(double diff); }; void LKTracker::updateLinearSystem(double diff) { for (size_t i=0; i<g_.size(); ++i){ for (size_t j=i+1; j<g_.size(); ++j){ LS_[i][j]+=g_[i]*g_[j]; LS_[j][i]+=g_[i]*g_[j]; } LS_[i][i]+=g_[i]*g_[i]; LS_[g_.size()][i]+=diff*g_[i]; } } std::vector<double> LKTracker::track( float const* pgwgx, float const* pgwgy, float const* perror, float const* pgwimg, double lambda) { constructSystem(pgwgx, pgwgy, perror, pgwimg, lambda); solution_=solve(LS_); if (solution_.size()!=0){ adjustSolution(); } return solution_; } class LKTracker2: public LKTracker{ public: LKTracker2(int hw, int hh){hw_=hw; hh_=hh;} virtual void constructSystem( float const* gwgx, float const* gwgy, float const* imgdiff, float const* gwimg, double lambda); }; void LKTracker2::constructSystem( float const* gwgx, float const* gwgy, float const* imgdiff, float const* , double ) { LS_.assign(3, std::vector<double>(2,0)); g_.resize(2); for (int y=-hh_; y<=hh_; ++y){ for (int x=-hw_; x<=hw_; ++x){ g_[0]=*gwgx++; g_[1]=*gwgy++; updateLinearSystem(*imgdiff++); } } } class LKTracker5: public LKTracker{ public: LKTracker5(int hw, int hh){hw_=hw; hh_=hh;} protected: virtual void constructSystem( float const* gwgx, float const* gwgy, float const* imgdiff, float const* gwimg, double lambda); virtual void adjustSolution(); }; void LKTracker5::constructSystem( float const* gwgx, float const* gwgy, float const* imgdiff, float const* gwimg, double lambda) { LS_.assign(6, std::vector<double>(5,0)); g_.resize(5); for (int y=-hh_; y<=hh_; ++y){ for (int x=-hw_; x<=hw_; ++x){ double gx = *gwgx++; double gy = *gwgy++; double diff = *imgdiff++; double i2 = *gwimg++; g_[0]=lambda*gx; g_[1]=lambda*gy; g_[2]=lambda*(x*gx+y*gy); g_[3]=i2; g_[4]=1; updateLinearSystem(diff); } } } void LKTracker5::adjustSolution(){ assert(solution_.size()==5); solution_.resize(8); solution_[7]=solution_[4]; solution_[6]=solution_[3]; solution_[5]=solution_[2]; solution_[4]=solution_[3]=0; } class LKTracker8: public LKTracker{ public: LKTracker8(int hw, int hh){hw_=hw; hh_=hh;} protected: virtual void constructSystem( float const* gwgx, float const* gwgy, float const* imgdiff, float const* gwimg, double lambda); }; void LKTracker8::constructSystem( float const* gwgx, float const* gwgy, float const* imgdiff, float const* gwimg, double lambda) { LS_.assign(9, std::vector<double>(8,0)); g_.resize(8); for (int y=-hh_; y<=hh_; ++y){ for (int x=-hw_; x<=hw_; ++x){ double gx = *gwgx++; double gy = *gwgy++; double i2 = *gwimg++; double diff = *imgdiff++; g_[0]=lambda*gx; g_[1]=lambda*gy; g_[2]=lambda*gx*x; g_[3]=lambda*gx*y; g_[4]=lambda*gy*x; g_[5]=lambda*gy*y; g_[6]=i2; g_[7]=1; updateLinearSystem(diff); } } } LKTracker* createLKTracker(int hw, int hh, int model){ switch (model){ case 2: return new LKTracker2(hw,hh); case 5: return new LKTracker5(hw,hh); case 8: return new LKTracker8(hw,hh); } assert(0); return nullptr; } ///////////////////////////////////////// // convergence tests bool testOutOfBoundary( const std::vector<core::Point>& bbox, int rows, int cols) { bool rv=false; for (const auto& bbox_i: bbox){ rv |= bbox_i.x_ < 0; rv |= bbox_i.x_ > cols-1; rv |= bbox_i.y_ < 0; rv |= bbox_i.y_ > rows-1; } return rv; } std::vector<core::Point> subtract( const std::vector<core::Point>& bbox1, const std::vector<core::Point>& bbox2) { std::vector<core::Point> diff(bbox1.size()); for (size_t i=0; i<bbox1.size(); ++i){ diff[i]=bbox1[i]-bbox2[i]; } return diff; } bool testConvergence( const std::vector<core::Point>& bboxCur, const std::vector<core::Point>& bboxPrev, double thConvergence) { std::vector<core::Point> diff(subtract(bboxCur, bboxPrev)); bool rv=true; for (const auto& diff_i: diff){ rv &= diff_i.l1() < thConvergence; } return rv; } bool testDivergence( const std::vector<core::Point>& bboxCur, const std::vector<core::Point>& bboxInitial, int thDivergence) { std::vector<core::Point> diff(subtract(bboxCur, bboxInitial)); bool rv=false; for (const auto& diff_i: diff){ rv |= diff_i.l1() >= thDivergence; } return rv; } ///////////////////////////////////////// // reporting void reportIteration(int fid, int iteration, const track::refiner::FeatureData& feature, const std::vector<double>& solution) { try{throw 1;} catch (int){}; // catch breakpoint std::ostringstream oss; oss <<"F" <<fid <<"#" <<std::setfill('0') <<std::setw(3) <<iteration; std::cerr <<oss.str() <<"@" <<feature.pt() <<"R" <<feature.residue_ <<"\n"; //core::savepgm(oss.str()+"gwgx.pgm", core::equalize(gwgx)); //track::refiner::savepgm(oss.str()+"gwgy.pgm", track::refiner::equalize(gwgy)); //track::refiner::savepgm(oss.str()+"gwimg.pgm", track::refiner::equalize(gwimg)); core::savepgm(oss.str()+"ref.pgm", core::equalize(feature.ref_, 0,255)); core::savepgm(oss.str()+"warped.pgm", core::equalize(feature.warped_, 0,255)); core::savepgm(oss.str()+"error.pgm", core::equalize(feature.error_,-255,255)); std::ostringstream ossw; ossw <<"warp: "; for (int i=0; i<8; ++i){ ossw <<feature.warp_[i] <<" "; } std::cerr <<" " <<ossw.str() <<"\n"; std::ostringstream ossdw; ossdw <<"delta warp: "; for (auto dw: solution){ ossdw <<dw <<" "; } std::cerr <<" " <<ossdw.str() <<"\n"; } } // unnamed namespace ends here ////////////////////////////////////////// // The interface class: FeatureRefinerKLT namespace track { namespace refiner { void FeatureRefinerKLT::config(const std::string& conf) { } void FeatureRefinerKLT::addFeatures( const core::ImageSet& src, const std::map<int, core::Point>& pts) { // TODO //#pragma omp parallel for for (auto q : pts){ //for (auto iter = pts.begin(); iter != pts.end(); iter++) { // TODO - replace or not to replace? //auto ret = map_.emplace(q.first, FeatureData(q.second.x_, q.second.y_)); map_[q.first] = FeatureData(q.second.x_, q.second.y_); //auto ret = map_.emplace(iter->first, FeatureData(iter->second.x_, iter->second.y_)); //std::cout << "index: " << q.first << "\n"; //assert(ret.second == true); FeatureData& feature = map_[q.first]; //FeatureData& feature = map_[iter->first]; //std::cout << feature.pt() << "\n"; getReferenceImages(src.smooth_, feature); } } void FeatureRefinerKLT::refineFeatures( const core::ImageSet& src, const std::map<int, core::Point>& pts) { if (verbose_){ core::savepgm("srcgx.pgm", core::equalize(src.gx_)); core::savepgm("srcgy.pgm", core::equalize(src.gy_)); core::savepgm("srcimg.pgm", core::equalize(src.smooth_, 0, 255)); } // local images const int fw=FeatureData::width(); const int fh=FeatureData::height(); core::Image gwgx(fw,fh, 4); // geometrically warped gradient x core::Image gwgy(fw,fh, 4); // geometrically warped gradient y core::Image gwimg(fw,fh, 4); // geometrically warped image std::unique_ptr<LKTracker> plk(createLKTracker(fw/2,fh/2, warpModel_)); // TODO this was removed coz of xeon phi gcc 4.7 //#pragma omp parallel for for (auto q : pts){ FeatureData& feature=map_[q.first]; feature.setpos(q.second.x_,q.second.y_); // check bounding box std::vector<core::Point> bboxInitial=feature.bbox(); if (testOutOfBoundary(bboxInitial, src.rows(),src.cols())){ feature.status_=FeatureData::OutOfBounds; continue; } // iterate until convergence or failure feature.status_=FeatureData::MaxIterations; std::vector<core::Point> bboxCur(bboxInitial); for (int iteration=0; iteration<thMaxIterations_; ++iteration){ // compute error computeWarpedGradient(src, feature, gwgx, gwgy); feature.residue_=computeError(src, feature, gwimg); if(iteration == 0) feature.first_residue_ = feature.residue_; // LK tracking std::vector<double> improvement = plk->track( gwgx.pcbits<float>(), gwgy.pcbits<float>(), feature.error_.pcbits<float>(), gwimg.pcbits<float>(), feature.lambda()); if (improvement.size()==0){ feature.status_=FeatureData::SmallDet; break; } if (verbose_){ reportIteration(q.first, iteration, feature, improvement); } for (size_t i=0; i<improvement.size(); ++i){ feature.warp_[i]+=improvement[i]*optimizationFactor_; } // check bounding box std::vector<core::Point> bboxPrev(std::move(bboxCur)); bboxCur=feature.bbox(); if (testOutOfBoundary(bboxCur, src.rows(),src.cols())){ feature.status_=FeatureData::OutOfBounds; break; } // check convergence if (testConvergence(bboxCur, bboxPrev, thDisplacementConvergence_) && feature.residue_ < thMaxResidue_) { feature.status_ = FeatureData::OK; break; } } if (feature.status_ == FeatureData::OK){ // check divergence if (testDivergence(bboxCur, bboxInitial, thDisplacementDivergence_)){ feature.status_=FeatureData::NotFound; } feature.residue_=computeError(src, feature, gwimg); // check residue if (feature.residue_>=thMaxResidue_){ feature.status_=FeatureData::LargeResidue; } } // TODO // check if the final residue is worse then initial //if (feature.status_ == FeatureData::OK){ // if(feature.residue_ > feature.first_residue_) // std::cout << "[FeatureRefinerKLT] First residue -> New residue: " << feature.first_residue_ // << " -> " << feature.residue_ << "\n"; //} if (verbose_){ std::ostringstream oss; oss <<"F" <<q.first <<"S" <<feature.status_ <<"@" <<feature.pt() <<"R" <<feature.residue_ <<"\n"; std::cerr <<oss.str() <<"\n"; } } return; } } }
[ "ivan.kreso@fer.hr" ]
ivan.kreso@fer.hr
b372f09712b287e7c3a2f160cb45280e1cc91c56
73b28acb36e116eaf6415f441f99d1cd7812fa5c
/semaphore.hpp
bf0a4f9fb4055dbc60a1565aba367b83ca8853aa
[]
no_license
adda25/MultithreadUtilities
275fc016df1fd711e3e9bf0e65f114e5a4323cba
6b3701e0226007687ba8d0f902d0491e5000c865
refs/heads/master
2020-06-21T11:35:17.771352
2016-11-25T21:53:10
2016-11-25T21:53:10
74,790,060
0
0
null
null
null
null
UTF-8
C++
false
false
3,315
hpp
/** * * The MIT License (MIT) * * Copyright (c) 2016 Amedeo Setti * * 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 NON INFRINGEMENT. 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 * */ #ifndef _SEMAPHORE_HPP_ #define _SEMAPHORE_HPP_ #ifdef __cplusplus #include <mutex> #include <condition_variable> namespace assm { /** * Original C implementation come from * "The Little Book of Semaphores" by * Allen B. Downey. * http://greenteapress.com/wp/semaphores/ * * Adapted to the C++11 standard. */ class Semaphore { public: Semaphore(int value = 1) : _value(value) {}; Semaphore(const Semaphore &S) : _mutex(), _cv() {}; Semaphore& operator=(Semaphore S) { return *this; } ~Semaphore() {}; void wait() { std::unique_lock<std::mutex> lock(_mutex); --_value; if (_value < 0) { do { _cv.wait(lock); } while (_wake_ups < 1); --_wake_ups; } } void signal() { std::unique_lock<std::mutex> lock(_mutex); ++_value; if (_value <= 0) { ++_wake_ups; _cv.notify_one(); } } private: int _value; int _wake_ups = 0; std::condition_variable _cv; std::mutex _mutex; }; // End class Semaphore }; // End assm #endif // __cplusplus #endif // _SEMAPHORE_HPP_
[ "amedeosetti@gmail.com" ]
amedeosetti@gmail.com
01b6f52b8efb05b496d3a7bca80eb31217e6d29b
24b4121d82bbf1367dd6d6e0a3658d40c523aa60
/main.cc
579c4256bf83f76bec128b376032e4ee0eee6e50
[]
no_license
Mequam/text-effect
311cbf2ba9c989c683c49d2e2e19be3c167acf18
34543065d8c8f990d569e62b3e9abcf1d2739640
refs/heads/master
2021-06-24T20:52:03.250251
2021-06-04T23:47:46
2021-06-04T23:47:46
181,961,461
1
0
null
null
null
null
UTF-8
C++
false
false
859
cc
#include <iostream> #include <string.h> #include <unistd.h> #include "Rng.h" using namespace std; string parse(int argc,char ** argv) { string ret_val = ""; for (int i = 1;i<argc;i++) { int j = 0; while (argv[i][j] != '\x00') { ret_val += argv[i][j]; j++; } ret_val += ' '; } return ret_val; } int main(int argc,char ** argv) { //set up our constants Rng dice = Rng(); string key = " // _=+-*/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,()[]!?#;\"\'\\*<>{}"; string found = ""; string parsed = parse(argc,argv); for (int i = 0;i<parsed.length();i++) { for (int j = 0; j < 200;j++) { if (i != parsed.length()-1) { cout << '\r' << found << key[dice.Range(0,key.length()-1)]; } else { cout << '\r' << found; } usleep(100); } found+=parsed[i]; } cout << endl; return 1; }
[ "blue9ja@gmail.com" ]
blue9ja@gmail.com
9d0a503ee045fc055cbbcf37c1961d3131063307
909ceeb751dc13e84b2e5450c16ca3cec0941359
/ハッカソン用フォルダ/プログラムデータ/完成版プログラム/HGSgame/pause.cpp
5e588cd5afa62a34c44bb6018c73f0d83ba94a8e
[]
no_license
reima22/game_3DteamC
d59d3736dd7585933d409e4653d1301ce7aea788
169f1dc9bac77a32e84cc6d20219759f58caeac4
refs/heads/master
2023-08-29T12:44:35.298230
2021-10-25T00:27:23
2021-10-25T00:27:23
314,099,927
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
12,231
cpp
//============================================================================== // // ポーズメニューの描画〔pause.cpp〕 // AUTHOR : MARE HORIAI // //============================================================================== #include "pause.h" #include "input.h" #include "sound.h" #include "gamepad.h" #include "fade.h" //============================================================================== // マクロ定義 //============================================================================== #define PAUSE_POLYGON (5) // ポーズ画面の使用するポリゴン数 #define PAUSETEXT (3) // ポーズ画面の選択肢数 #define PAUSE_WINDOWX (160) // ポーズメニューの幅 #define PAUSE_WINDOWY (160) // ポーズメニューの高さ #define PAUSE_SIZEX (140) // ポーズテキストの幅 #define PAUSE_SIZEY (40) // ポーズテキストの高さ #define PAUSETEXT_POSY (260) // ポーズテキスト1行目の高さ //============================================================================== // グローバル変数 //============================================================================== LPDIRECT3DTEXTURE9 g_pTexturePause[PAUSE_POLYGON] = {}; // ポーズテクスチャへのポインタ LPDIRECT3DVERTEXBUFFER9 g_pVtxBuffPause = NULL; // バッファへのポインタ D3DXVECTOR3 g_posBackScreen; // ポーズ背景の位置 D3DXVECTOR3 g_posWindow; // ポーズウィンドウの位置 D3DXVECTOR3 g_posText[PAUSETEXT]; // ポーズテキストの位置 float g_fContinue; // コンテニューテキストのテクスチャ位置 float g_fRetry; // リトライテキストのテクスチャ位置 float g_fQuit; // やり直しテキストのテクスチャ位置 PAUSE_MENU PauseMenu; // ポーズの状態 //============================================================================== // ポーズメニューの初期化処理 //============================================================================== HRESULT InitPause(void) { // ローカル変数宣言 VERTEX_2D *pVtx; LPDIRECT3DDEVICE9 pDevice; // デバイスの取得 pDevice = GetDevice(); // 背景テクスチャの読み込み D3DXCreateTextureFromFile( pDevice, "data/TEXTURE/pause_BS.png", &g_pTexturePause[0]); D3DXCreateTextureFromFile( pDevice, "data/TEXTURE/continue.png", &g_pTexturePause[1]); D3DXCreateTextureFromFile( pDevice, "data/TEXTURE/retry.png", &g_pTexturePause[2]); D3DXCreateTextureFromFile( pDevice, "data/TEXTURE/quit.png", &g_pTexturePause[3]); // 頂点バッファの生成 if (FAILED(pDevice->CreateVertexBuffer( sizeof(VERTEX_2D) * 4 * 5, // 確保するバッファサイズ D3DUSAGE_WRITEONLY, FVF_VERTEX_2D, // 頂点フォーマット D3DPOOL_MANAGED, &g_pVtxBuffPause, NULL))) { return E_FAIL; } // 変数の初期化 g_fContinue = 0.0f; g_fRetry = 0.5f; g_fQuit = 0.5f; PauseMenu = PAUSE_MENU_CONTINUE; // 頂点バッファをロックし、頂点情報へのポインタを取得 g_pVtxBuffPause->Lock(0, 0, (void**)&pVtx, 0); // ユーザーインターフェースの中心座標 g_posBackScreen = D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f); // ポリゴンの各頂点座標 pVtx[0].pos = D3DXVECTOR3(g_posBackScreen.x - (SCREEN_WIDTH / 2), g_posBackScreen.y + (SCREEN_HEIGHT / 2), 0.0f); pVtx[1].pos = D3DXVECTOR3(g_posBackScreen.x - (SCREEN_WIDTH / 2), g_posBackScreen.y - (SCREEN_HEIGHT / 2), 0.0f); pVtx[2].pos = D3DXVECTOR3(g_posBackScreen.x + (SCREEN_WIDTH / 2), g_posBackScreen.y + (SCREEN_HEIGHT / 2), 0.0f); pVtx[3].pos = D3DXVECTOR3(g_posBackScreen.x + (SCREEN_WIDTH / 2), g_posBackScreen.y - (SCREEN_HEIGHT / 2), 0.0f); // rhwの設定 pVtx[0].rhw = 1.0f; pVtx[1].rhw = 1.0f; pVtx[2].rhw = 1.0f; pVtx[3].rhw = 1.0f; // 各頂点カラーの設定 pVtx[0].col = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.5f); pVtx[1].col = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.5f); pVtx[2].col = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.5f); pVtx[3].col = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.5f); // 頂点座標の設定 pVtx[0].tex = D3DXVECTOR2(0.0, 1.0); pVtx[1].tex = D3DXVECTOR2(0.0, 0.0); pVtx[2].tex = D3DXVECTOR2(1.0, 1.0); pVtx[3].tex = D3DXVECTOR2(1.0, 0.0); // 頂点バッファをアンロックする g_pVtxBuffPause->Unlock(); // 頂点バッファをロックし、頂点情報へのポインタを取得 g_pVtxBuffPause->Lock(0, 0, (void**)&pVtx, 0); // ユーザーインターフェースの中心座標 g_posWindow = D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f); // ポリゴンの各頂点座標 pVtx[4].pos = D3DXVECTOR3(g_posWindow.x - PAUSE_WINDOWX, g_posWindow.y + PAUSE_WINDOWY, 0.0f); pVtx[5].pos = D3DXVECTOR3(g_posWindow.x - PAUSE_WINDOWX, g_posWindow.y - PAUSE_WINDOWY, 0.0f); pVtx[6].pos = D3DXVECTOR3(g_posWindow.x + PAUSE_WINDOWX, g_posWindow.y + PAUSE_WINDOWY, 0.0f); pVtx[7].pos = D3DXVECTOR3(g_posWindow.x + PAUSE_WINDOWX, g_posWindow.y - PAUSE_WINDOWY, 0.0f); // rhwの設定 pVtx[4].rhw = 1.0f; pVtx[5].rhw = 1.0f; pVtx[6].rhw = 1.0f; pVtx[7].rhw = 1.0f; // 各頂点カラーの設定 pVtx[4].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[5].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[6].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[7].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); // 頂点座標の設定 pVtx[4].tex = D3DXVECTOR2(0.0, 1.0); pVtx[5].tex = D3DXVECTOR2(0.0, 0.0); pVtx[6].tex = D3DXVECTOR2(1.0, 1.0); pVtx[7].tex = D3DXVECTOR2(1.0, 0.0); // 頂点バッファをアンロックする g_pVtxBuffPause->Unlock(); // 頂点バッファをロックし、頂点情報へのポインタを取得 g_pVtxBuffPause->Lock(0, 0, (void**)&pVtx, 0); for (int nCnt = 0; nCnt < 3; nCnt++, pVtx += 4) { // ユーザーインターフェースの中心座標 g_posText[nCnt] = D3DXVECTOR3(SCREEN_WIDTH / 2, PAUSETEXT_POSY + (nCnt * 100.0f), 0.0f); // ポリゴンの各頂点座標 pVtx[8].pos = D3DXVECTOR3(g_posText[nCnt].x - PAUSE_SIZEX, g_posText[nCnt].y + PAUSE_SIZEY, 0.0f); pVtx[9].pos = D3DXVECTOR3(g_posText[nCnt].x - PAUSE_SIZEX, g_posText[nCnt].y - PAUSE_SIZEY, 0.0f); pVtx[10].pos = D3DXVECTOR3(g_posText[nCnt].x + PAUSE_SIZEX, g_posText[nCnt].y + PAUSE_SIZEY, 0.0f); pVtx[11].pos = D3DXVECTOR3(g_posText[nCnt].x + PAUSE_SIZEX, g_posText[nCnt].y - PAUSE_SIZEY, 0.0f); // rhwの設定 pVtx[8].rhw = 1.0f; pVtx[9].rhw = 1.0f; pVtx[10].rhw = 1.0f; pVtx[11].rhw = 1.0f; // 各頂点カラーの設定 pVtx[8].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[9].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[10].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[11].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); // 頂点座標の設定 pVtx[8].tex = D3DXVECTOR2(0.0, 0.5); pVtx[9].tex = D3DXVECTOR2(0.0, 0.0); pVtx[10].tex = D3DXVECTOR2(1.0, 0.5); pVtx[11].tex = D3DXVECTOR2(1.0, 0.0); } // 頂点バッファをアンロックする g_pVtxBuffPause->Unlock(); return S_OK; } //============================================================================== // ポーズメニューの終了処理 //============================================================================== void UninitPause(void) { // 頂点バッファの開放 if (g_pVtxBuffPause != NULL) { g_pVtxBuffPause->Release(); g_pVtxBuffPause = NULL; } // テクスチャの開放 for (int nCnt = 0; nCnt < PAUSE_POLYGON; nCnt++) { if (g_pTexturePause[nCnt] != NULL) { g_pTexturePause[nCnt]->Release(); g_pTexturePause[nCnt] = NULL; } } } //============================================================================== // ポーズメニューの更新処理 //============================================================================== void UpdatePause(void) { // ローカル変数宣言 VERTEX_2D *pVtx; FADE fade = GetFade(); if (fade == FADE_NONE) { // ポーズからゲーム続行 if (GetKeyboardTrigger(KEYINFO_PAUSE) == true || IsButtonDown(KEYINFO::KEYINFO_PAUSE) == true) { if (PauseMenu != PAUSE_MENU_CONTINUE) { PauseMenu = PAUSE_MENU_CONTINUE; } } // 選択画面 if (GetKeyboardTrigger(KEYINFO_DOWN) == true || IsButtonDown(KEYINFO::KEYINFO_DOWN) == true) { // 音の再生 PlaySound(SOUND_LABEL_SE_SELECT); if (PauseMenu == PAUSE_MENU_CONTINUE) { // カーソルが「CONTINUE」の時 PauseMenu = PAUSE_MENU_RETRY; } else if (PauseMenu == PAUSE_MENU_RETRY) { // カーソルが「RETRY」の時 PauseMenu = PAUSE_MENU_QUIT; } else if (PauseMenu == PAUSE_MENU_QUIT) { // カーソルが「QUIT」の時 PauseMenu = PAUSE_MENU_CONTINUE; } } else if (GetKeyboardTrigger(KEYINFO_UP) == true || IsButtonDown(KEYINFO::KEYINFO_UP) == true) { // 音の再生 PlaySound(SOUND_LABEL_SE_SELECT); if (PauseMenu == PAUSE_MENU_CONTINUE) { // カーソルが「CONTINUE」の時 PauseMenu = PAUSE_MENU_QUIT; } else if (PauseMenu == PAUSE_MENU_RETRY) { // カーソルが「RETRY」の時 PauseMenu = PAUSE_MENU_CONTINUE; } else if (PauseMenu == PAUSE_MENU_QUIT) { // カーソルが「QUIT」の時 PauseMenu = PAUSE_MENU_RETRY; } } } // テクスチャの切り替え switch (PauseMenu) { case PAUSE_MENU_CONTINUE: // カーソルが「CONTINUE」の時 g_fContinue = 0.0f; g_fRetry = 0.5f; g_fQuit = 0.5f; break; case PAUSE_MENU_RETRY: // カーソルが「RETRY」の時 g_fContinue = 0.5f; g_fRetry = 0.0f; g_fQuit = 0.5f; break; case PAUSE_MENU_QUIT: // カーソルが「QUIT」の時 g_fContinue = 0.5f; g_fRetry = 0.5f; g_fQuit = 0.0f; break; default: break; } // 頂点バッファをロックし、頂点情報へのポインタを取得 g_pVtxBuffPause->Lock(0, 0, (void**)&pVtx, 0); // 各テクスチャの更新 pVtx[8].tex = D3DXVECTOR2(0.0f, 0.5f + g_fContinue); pVtx[9].tex = D3DXVECTOR2(0.0f, 0.0f + g_fContinue); pVtx[10].tex = D3DXVECTOR2(1.0f, 0.5f + g_fContinue); pVtx[11].tex = D3DXVECTOR2(1.0f, 0.0f + g_fContinue); pVtx[12].tex = D3DXVECTOR2(0.0f, 0.5f + g_fRetry); pVtx[13].tex = D3DXVECTOR2(0.0f, 0.0f + g_fRetry); pVtx[14].tex = D3DXVECTOR2(1.0f, 0.5f + g_fRetry); pVtx[15].tex = D3DXVECTOR2(1.0f, 0.0f + g_fRetry); pVtx[16].tex = D3DXVECTOR2(0.0f, 0.5f + g_fQuit); pVtx[17].tex = D3DXVECTOR2(0.0f, 0.0f + g_fQuit); pVtx[18].tex = D3DXVECTOR2(1.0f, 0.5f + g_fQuit); pVtx[19].tex = D3DXVECTOR2(1.0f, 0.0f + g_fQuit); // 頂点バッファをアンロックする g_pVtxBuffPause->Unlock(); } //============================================================================== // ポーズメニューの描画処理 //============================================================================== void DrawPause(void) { // ローカル変数宣言 LPDIRECT3DDEVICE9 pDevice; // デバイスの取得 pDevice = GetDevice(); // 頂点バッファをデータストリームに設定 pDevice->SetStreamSource( 0, g_pVtxBuffPause, 0, sizeof(VERTEX_2D)); // 頂点フォーマットの設定 pDevice->SetFVF(FVF_VERTEX_2D); // テクスチャの設定 for (int nCnt = 0; nCnt < 5; nCnt++) { if (nCnt == 0) { // 背景暗転のテクスチャ pDevice->SetTexture(0, NULL); } else { // ポーズメニューのテクスチャ pDevice->SetTexture(0, g_pTexturePause[nCnt - 1]); } // ポリゴンの描画 pDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, // プリミティブの種類 nCnt * 4, // 描画を開始する頂点インデックス 2); // 描画するプリミティブ数 } } //============================================================================== // ポーズの情報取得 //============================================================================== PAUSE_MENU GetPause(void) { return PauseMenu; }
[ "doraemonn.ww.22-gtr-xyz.2500@ezweb.ne.jp" ]
doraemonn.ww.22-gtr-xyz.2500@ezweb.ne.jp
7eb246846b0b1c93bb08ab14dfe54efa0112f3d0
5621fa1ad956aba95995c474f35c09c78a4f008b
/educational_dp_b.cpp
ca5f117d2e2388f54f989533d441a677399d0a55
[]
no_license
tasogare66/atcoder
ea3e6cdcdd28f2c6be816d85e0b521d0cb94d6a3
16bc66ab3f72788f1a940be921edc681763f86f1
refs/heads/master
2020-05-09T14:33:30.659718
2020-04-14T14:09:37
2020-04-14T14:09:37
181,196,939
0
0
null
null
null
null
UTF-8
C++
false
false
1,057
cpp
//https://atcoder.jp/contests/dp/tasks/dp_b //B - Frog 2 #include <bits/stdc++.h> #if LOCAL #include "dump.hpp" #else #define dump(...) #endif using namespace std; using ll=long long; #define FOR(i,a,b) for(ll i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) template<class T>bool chmax(T &a, const T &b) {if (a<b) { a=b; return 1; } return 0;} template<class T>bool chmin(T &a, const T &b) {if (b<a) { a=b; return 1; } return 0;} int main() { #if LOCAL&01 std::ifstream in("./test/sample-1.in"); //input.txt std::cin.rdbuf(in.rdbuf()); #else cin.tie(0); ios::sync_with_stdio(false); #endif ll N, K; cin>>N>>K; vector<ll> hn(N+1,0); FOR(i,1,N+1){ cin>>hn.at(i); } vector<ll> ans(N+1,INT64_MAX); ans[1]=0; auto get_val = [&](ll p,ll ofs)->ll{ if(p-ofs<=0) return INT64_MAX; ll a=abs(hn[p]-hn[p-ofs]); return a+ans[p-ofs]; }; FOR(i,2,N+1){ FOR(j,1,K+1){ ll v=get_val(i,j); chmin(ans[i],v); } } cout<<ans[N]<<endl; return 0; }
[ "tasogare66@gmai.com" ]
tasogare66@gmai.com
fb39870083566c4916f17a10d44101db64c3adae
08b9ae84a01d11be758127fb9746189647525ce0
/AlgorithmicToolbox/week2/C++/LastDigitSumRange.cpp
f40af7e486355eb146f5247e2c7d313766047d9a
[]
no_license
taingocbui/Coursera
c652f71d988cfa0fd328629ceaac3d0e180bd216
a81525e090a0dd9f847f753b41d821e0d56227de
refs/heads/master
2020-06-20T22:56:30.245661
2019-09-28T02:25:39
2019-09-28T02:25:39
197,278,905
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
//Task. Given two non-negative integers m and n, where m ≤ n, find the last digit of the sum F m + F m+1 + //· · · + F n . //Input Format. The input consists of two non-negative integers m and n separated by a space. //Constraints. 0 ≤ m ≤ n ≤ 10 18 . //Output Format. Output the last digit of F m + F m+1 + · · · + F n . #include <iostream> #include <vector> using namespace std; int Pisano(const int m){ int a = 0; int b = 1; int c,i; for(i=0; i<m*m+1; i++){ c = (a+b)%m; a = b; b = c; if(a==0 && b==1) break; } return i+1; } long long Fibonacci(const long long n){ long long list[n+2]; list[0] = 0; list[1] = 1; for(int i=2; i<=n; i++){ list[i] = list[i-1] + list[i-2]; } return list[n]; } int main(){ vector<int> list(2); for(int i=0; i<2; i++){ cin>>list[i]; } int p = Pisano(10); int m = (list[0]+1)%p; int n = (list[1]+2)%p; int answer = (Fibonacci(n)%10 - Fibonacci(m)%10 + 10)%10; cout<<answer<<"\n"; }
[ "taingocbui@gmail.com" ]
taingocbui@gmail.com
cedfe78b32599dbd28fa301142ac3dd2e1537178
dce0a22a899c20b85070a6f117b169bab3be848e
/Classes/Entity/Weapon/Ammo/PitchForkAmmo.cpp
90d6962c3092b8fac3dec06075a7606f21dad068
[]
no_license
Ryougi-Shio/CHEN
3d8d24717bf34551c85f898181267f2c325a1ea6
398555f129f4b6401b3d8abb78f8f5824b32ddfc
refs/heads/main
2023-06-03T18:52:45.569102
2021-06-19T14:00:39
2021-06-19T14:00:39
363,114,561
5
6
null
2021-06-19T14:00:40
2021-04-30T11:06:40
C++
UTF-8
C++
false
false
467
cpp
#include"PitchForkAmmo.h" #include<ctime> USING_NS_CC; bool PitchForkAmmo::init() { bindSprite(Sprite::create("Weapon/Ammo/spear_action1.png")); Animation* animation = Animation::create(); for (int i = 1; i <= 5; i++) { char s[50]; sprintf(s, "Weapon/Ammo/spear_action%d.png", i); animation->addSpriteFrameWithFile(s); } animation->setDelayPerUnit(0.1f); auto* action = Animate::create(animation); this->getSprite()->runAction(action); return 1; }
[ "1060696988@qq.com" ]
1060696988@qq.com
e1ebc29a94f4ddc5d61f5d8e44c4fbbd5081cbfc
405468add1e96aacfd4a96351f23a74525126d31
/run_Rm_sf_0p9.cpp
b3cbd92d9b00ec8442a7f3e52507f94e5433fec5
[]
no_license
zhchenseven/Computational_Physics_Traffic_Equation
03a8e3ab1029351ee7ec6d056cca42e2d02352e4
8b41330828b6d28726c2cd5b79c106c4dda41ab4
refs/heads/master
2021-08-26T09:12:53.561212
2017-11-22T19:45:53
2017-11-22T19:45:53
107,586,764
2
1
null
null
null
null
UTF-8
C++
false
false
849
cpp
# include <iostream> # include <armadillo> # include "Data_process.h" using namespace std; using namespace arma; //int main(int argv, char ** argc) int Rm(int argv, char ** argc) { Data_process Project; int N = 32; double x_low = -2000; double x_sup = 4000; double dx = 50; double rhom = 0.1; double vm = 50; double T = 60; double safe_fac = 0.9; int M = 1000; Project.set_para(x_low, x_sup, dx, T, vm, rhom,safe_fac); string ini_type = "TL"; string bnd_type = "DN"; Project.set_IBC(ini_type, bnd_type); string flux_type = "Rm"; Project.set_flux(flux_type); string vis_name = "Rm_T_20_sf_0p9"; int index = 0; string data_type = "dat"; string size_sufx = "size"; Project.set_process_ctrl(vis_name, index, data_type, size_sufx); Project.exe_cetr(); Project.process(); Project.write_log(); system("pause"); return 0; }
[ "32938765+zhchenseven@users.noreply.github.com" ]
32938765+zhchenseven@users.noreply.github.com
8965b2b37343a4e14cc7dd14f1586dc0e38db6c7
ddfd3663319095361aedfdd1e2f106f59a89093e
/msf_localization_core/src/include/msf_localization_core/free_model_robot_state_core.h
960afc6fa218a87581b768ed4b9af14309a87284
[ "BSD-3-Clause" ]
permissive
Ahrovan/msf_localization
483be22f098d006d0c7d33b05e06c50206f90254
a78ba2473115234910789617e9b45262ebf1d13d
refs/heads/master
2020-03-07T02:01:25.421494
2018-02-15T15:27:32
2018-02-15T15:27:32
127,198,975
1
0
null
null
null
null
UTF-8
C++
false
false
2,269
h
#ifndef _FREE_MODEL_ROBOT_STATE_CORE_H #define _FREE_MODEL_ROBOT_STATE_CORE_H #include <Eigen/Dense> #include <Eigen/Sparse> #include "msf_localization_core/robot_state_core.h" #include "quaternion_algebra/quaternion_algebra.h" class FreeModelRobotStateCore : public RobotStateCore { public: FreeModelRobotStateCore(); FreeModelRobotStateCore(const std::weak_ptr<MsfElementCore> msf_element_core_ptr); ~FreeModelRobotStateCore(); protected: int init(); // State: xR=[pos (3/3), lin_speed (3/3), lin_accel (3/3), attit (4/3), ang_vel (3/3), ang_acc (3/3)]' protected: public: Eigen::Vector3d position_robot_wrt_world_; public: Eigen::Vector3d getPositionRobotWrtWorld() const; int setPositionRobotWrtWorld(const Eigen::Vector3d& position); protected: public: Eigen::Vector3d linear_speed_robot_wrt_world_; public: Eigen::Vector3d getLinearSpeedRobotWrtWorld() const; int setLinearSpeedRobotWrtWorld(const Eigen::Vector3d &linear_speed); protected: public: Eigen::Vector3d linear_acceleration_robot_wrt_world_; public: Eigen::Vector3d getLinearAccelerationRobotWrtWorld() const; int setLinearAccelerationRobotWrtWorld(const Eigen::Vector3d& linear_acceleration); protected: public: Eigen::Vector4d attitude_robot_wrt_world_; public: Eigen::Vector4d getAttitudeRobotWrtWorld() const; int setAttitudeRobotWrtWorld(const Eigen::Vector4d &attitude); protected: public: Eigen::Vector3d angular_velocity_robot_wrt_world_; public: Eigen::Vector3d getAngularVelocityRobotWrtWorld() const; int setAngularVelocityRobotWrtWorld(const Eigen::Vector3d& angular_velocity); protected: public: Eigen::Vector3d angular_acceleration_robot_wrt_world_; public: Eigen::Vector3d getAngularAccelerationRobotWrtWorld() const; int setAngularAccelerationRobotWrtWorld(const Eigen::Vector3d &angular_acceleration); // Jacobian Error State (18 x 18) -> 54 non-zero elements // Fx_robot linear (9 x 9) -> 18 non-zero elements // Fx_robot angular (9 x 9) -> 36 non-zero elements // Jacobian Error State Noise (18 x 6) -> 6 non-zero elements public: int updateStateFromIncrementErrorState(const Eigen::VectorXd& increment_error_state); }; #endif
[ "jl.sanchez@upm.es" ]
jl.sanchez@upm.es
65fde08a0bafb65b92d34eb2c6e662adca6ebd11
2909872aceb1ba30a1f5bf8a913d3e8c8203ddbe
/tests/route.cpp
eba9b37d877413ea40f890ff7712facc0e722b1d
[]
no_license
kolodziej/Speditor
c0a863e335d5ba173aedfe15f79d9a27f64dcb2c
370b726db1669942f367a054f752b65e7f8fee39
refs/heads/master
2021-01-20T10:48:01.410826
2015-04-29T20:10:40
2015-04-29T20:10:40
30,795,084
0
0
null
null
null
null
UTF-8
C++
false
false
1,418
cpp
#include "gtest/gtest.h" #include "map.hpp" #include "route.hpp" #include "road.hpp" #include "city.hpp" #include <vector> #include <memory> #include "tools/logger.hpp" using namespace speditor; speditor::tools::Logger global_logger(std::cerr, speditor::tools::Logger::ShowTime | speditor::tools::Logger::ShowType); class RouteTest : public ::testing::Test { protected: virtual void SetUp() { cities = { std::make_shared<City>("One"), std::make_shared<City>("Two"), std::make_shared<City>("Three"), std::make_shared<City>("Four") }; for (auto city : cities) { for (auto in_city : cities) { if (city == in_city) continue; city->addRoad(std::make_shared<Road>(in_city, 100)); } } } std::vector<NodePtr> cities; }; TEST_F(RouteTest, Continuous) { Route route(cities[0], { cities[0]->roads()[0], cities[1]->roads()[2], cities[3]->roads()[2] }); ASSERT_EQ(route.startNode(), cities[0]); ASSERT_EQ(route.endNode(), cities[2]); ASSERT_TRUE(route.continuous()); } TEST_F(RouteTest, NotContinuous) { Route route(cities[0], { cities[0]->roads()[0], cities[1]->roads()[2], cities[3]->roads()[2], cities[1]->roads()[0] }); ASSERT_EQ(route.startNode(), cities[0]); ASSERT_EQ(route.endNode(), cities[0]); ASSERT_FALSE(route.continuous()); }
[ "kacper@kolodziej.in" ]
kacper@kolodziej.in
9bad4fa41b3a3340ed471485f6d240d7e5ece097
363f00150ba6f78d6a12fce60bd52d18dfa46fc9
/src/boost/boost/fusion/support/config.hpp
72ba4f2364be30ede726c89f6e3ec023b710c627
[ "BSL-1.0" ]
permissive
chasemc/mzR
0bf9df51ed70aab5a9ed46e480a5e9e5ab1dd0dc
eef4b69a16096174ef86bdb9d7b4011376a9d3fa
refs/heads/master
2021-04-06T01:46:28.264357
2018-03-13T15:46:42
2018-03-13T15:46:42
125,068,531
1
0
null
2018-03-13T14:56:15
2018-03-13T14:56:15
null
UTF-8
C++
false
false
3,332
hpp
/*============================================================================= Copyright (c) 2014 Eric Niebler Copyright (c) 2014 Kohei Takahashi Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(FUSION_SUPPORT_CONFIG_01092014_1718) #define FUSION_SUPPORT_CONFIG_01092014_1718 #include <boost/config.hpp> #include <boost/detail/workaround.hpp> #ifndef BOOST_FUSION_GPU_ENABLED #define BOOST_FUSION_GPU_ENABLED BOOST_GPU_ENABLED #endif // Enclose with inline namespace because unqualified lookup of GCC < 4.5 is broken. // // namespace detail { // struct foo; // struct X { }; // } // // template <typename T> void foo(T) { } // // int main() // { // foo(detail::X()); // // prog.cc: In function 'int main()': // // prog.cc:2: error: 'struct detail::foo' is not a function, // // prog.cc:6: error: conflict with 'template<class T> void foo(T)' // // prog.cc:10: error: in call to 'foo' // } namespace boost { namespace fusion { namespace detail { namespace barrier { } using namespace barrier; }}} #define BOOST_FUSION_BARRIER_BEGIN namespace barrier { #define BOOST_FUSION_BARRIER_END } #if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1900)) // All of rvalue-reference ready MSVC don't perform implicit conversion from // fundamental type to rvalue-reference of another fundamental type [1]. // // Following example doesn't compile // // int i; // long &&l = i; // sigh..., std::forward<long&&>(i) also fail. // // however, following one will work. // // int i; // long &&l = static_cast<long &&>(i); // // OK, now can we replace all usage of std::forward to static_cast? -- I say NO! // All of rvalue-reference ready Clang doesn't compile above static_cast usage [2], sigh... // // References: // 1. https://connect.microsoft.com/VisualStudio/feedback/details/1037806/implicit-conversion-doesnt-perform-for-fund // 2. http://llvm.org/bugs/show_bug.cgi?id=19917 // // Tentatively, we use static_cast to forward if run under MSVC. # define BOOST_FUSION_FWD_ELEM(type, value) static_cast<type&&>(value) #else # define BOOST_FUSION_FWD_ELEM(type, value) std::forward<type>(value) #endif // Workaround for LWG 2408: C++17 SFINAE-friendly std::iterator_traits. // http://cplusplus.github.io/LWG/lwg-defects.html#2408 // // - GCC 4.5 enables the feature under C++11. // https://gcc.gnu.org/ml/gcc-patches/2014-11/msg01105.html // // - MSVC 10.0 implements iterator intrinsics; MSVC 13.0 implements LWG2408. #if (defined(BOOST_LIBSTDCXX_VERSION) && (BOOST_LIBSTDCXX_VERSION < 40500) && \ defined(BOOST_LIBSTDCXX11)) || \ (defined(BOOST_MSVC) && (1600 <= BOOST_MSVC || BOOST_MSVC < 1900)) # define BOOST_FUSION_WORKAROUND_FOR_LWG_2408 namespace std { template <typename> struct iterator_traits; } #endif // Workaround for older GCC that doesn't accept `this` in constexpr. // https://github.com/boostorg/fusion/pull/96/files #if BOOST_WORKAROUND(BOOST_GCC, < 40700) #define BOOST_FUSION_CONSTEXPR_THIS #else #define BOOST_FUSION_CONSTEXPR_THIS BOOST_CONSTEXPR #endif #endif
[ "l.gatto@bc3139a8-67e5-0310-9ffc-ced21a209358" ]
l.gatto@bc3139a8-67e5-0310-9ffc-ced21a209358
c9b118699bfc315fc89a392a60241c0daab8fcd8
06867f299f556a1ca65e9852e8da4c6edba07cde
/common/utility/math/range.h
868f1f662ac75a9c352ed77f53d38b0397f690e7
[]
no_license
vito-trianni/more
1f895360424e57af50d0eedc35e6918af71c955c
8ac894e0dc5b18c68da0f69baff51864d07f0b09
refs/heads/master
2021-01-10T02:05:17.452659
2015-03-30T16:52:55
2015-03-30T16:52:55
33,126,563
0
0
null
null
null
null
UTF-8
C++
false
false
6,550
h
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef CRANGE_H #define CRANGE_H #include <argos2/common/utility/datatypes/datatypes.h> #include <argos2/common/utility/string_utilities.h> #include <argos2/common/utility/configuration/argos_exception.h> #include <iostream> namespace argos { template<typename T> class CRange { public: CRange(const T& t_min, const T& t_max) : m_tMin(t_min), m_tMax(t_max), m_tSpan(m_tMax - m_tMin) { ARGOS_ASSERT(t_min < t_max, "Error initializing CRange(" << t_min << ", " << t_max << "): " << t_min << " is not < " << t_max); } inline T GetMin() const { return m_tMin; } inline void SetMin(const T& t_min) { ARGOS_ASSERT(t_min < m_tMax, "Error setting min CRange bound (" << t_min << "): " << t_min << " is not < " << m_tMax); m_tMin = t_min; /* Same as, but faster than m_tSpan = m_tMax - m_tMin; */ m_tSpan = m_tMax; m_tSpan -= m_tMin; } inline T GetMax() const { return m_tMax; } inline void SetMax(const T& t_max) { ARGOS_ASSERT(m_tMin < t_max, "Error setting max CRange bound (" << t_max << "): " << m_tMin << " is not < " << t_max); m_tMax = t_max; /* Same as, but faster than m_tSpan = m_tMax - m_tMin; */ m_tSpan = m_tMax; m_tSpan -= m_tMin; } inline T GetSpan() const { return m_tSpan; } inline void Set(const T& t_min, const T& t_max) { ARGOS_ASSERT(t_min < t_max, "Error setting CRange bounds (" << t_min << ", " << t_max << "): " << t_min << " is not < " << t_max); m_tMin = t_min; m_tMax = t_max; /* Same as, but faster than m_tSpan = m_tMax - m_tMin; */ m_tSpan = m_tMax; m_tSpan -= m_tMin; } inline bool WithinMinBoundIncludedMaxBoundIncluded(const T& t_value) const { return t_value >= m_tMin && t_value <= m_tMax; } inline bool WithinMinBoundIncludedMaxBoundExcluded(const T& t_value) const { return t_value >= m_tMin && t_value < m_tMax; } inline bool WithinMinBoundExcludedMaxBoundIncluded(const T& t_value) const { return t_value > m_tMin && t_value <= m_tMax; } inline bool WithinMinBoundExcludedMaxBoundExcluded(const T& t_value) const { return t_value > m_tMin && t_value < m_tMax; } inline void TruncValue(T& t_value) const { if (t_value > m_tMax) t_value = m_tMax; if (t_value < m_tMin) t_value = m_tMin; } inline Real NormalizeValue(const T& t_value) const { T tTmpValue(t_value); TruncValue(tTmpValue); return static_cast<Real>(tTmpValue - m_tMin) / static_cast<Real>(m_tSpan); } template <typename U> void MapValueIntoRange(U& t_output_value, const T& t_input_value, const CRange<U>& c_range) const { t_output_value = (NormalizeValue(t_input_value) * c_range.GetSpan()) + c_range.GetMin(); } inline void WrapValue(T& t_value) const { /* * To wrap a value inside this range, we need two while loops. * The first one is necessary for t_value greater than the max bound; * the second one for t_value smaller than the min bound. * In the first one, we keep subtracting the span until t_value * falls into the range; in the second one, the span is summed. * It could happen that one calls this function with a t_value that is * too large or too small wrt the span. Due to the implementation of * floating-point values, a small value summed to or subtracted from * a much larger one could result in no change for the large value. * Thus, the while loop would be infinite. * To prevent this from happening, we first check if summing or subtracting * the span from t_value changes t_value's value. If so, we continue with * the loop. Otherwise, we bomb out and blame the caller for feeding a * value that cannot be wrapped. */ T tBuffer; if(t_value > m_tMax) { tBuffer = t_value; t_value -= m_tSpan; if(tBuffer > t_value) { while(t_value > m_tMax) t_value -= m_tSpan; } else { THROW_ARGOSEXCEPTION("[BUG] The value " << t_value << " cannot be wrapped in range [" << *this << "]"); } } if(t_value < m_tMin) { tBuffer = t_value; t_value += m_tSpan; if(tBuffer < t_value) { while(t_value < m_tMin) t_value += m_tSpan; } else { THROW_ARGOSEXCEPTION("[BUG] The value " << t_value << " cannot be wrapped in range [" << *this << "]"); } } } inline friend std::ostream& operator<<(std::ostream& os, const CRange& c_range) { os << c_range.m_tMin << ":" << c_range.m_tMax; return os; } inline friend std::istream& operator>>(std::istream& is, CRange& c_range) { T tValues[2]; ParseValues<T> (is, 2, tValues, ':'); c_range.Set(tValues[0], tValues[1]); return is; } private: T m_tMin; T m_tMax; T m_tSpan; }; } #endif
[ "vtrianni@ulb.ac.be" ]
vtrianni@ulb.ac.be
6ee9c26a1347f6c8382be0111342b3c08c996327
39e4ce41335361dac60b4cd3789c2444e92f06e4
/devel/include/msgs_demo/MoveBaseActionFeedback.h
23bc9282bc2c23c01c392fe9441976f42ed72901
[]
no_license
Symphony-in-Icecity/simulation_of_robot_ws
a3569b72feb5e44e9c99db29020d2df647066a48
1c5735c84cc72d8a96dbf8db6cf7d6cb979b201a
refs/heads/master
2020-04-14T19:18:20.608845
2019-01-04T03:26:58
2019-01-04T03:26:58
164,052,878
1
0
null
null
null
null
UTF-8
C++
false
false
10,755
h
// Generated by gencpp from file msgs_demo/MoveBaseActionFeedback.msg // DO NOT EDIT! #ifndef MSGS_DEMO_MESSAGE_MOVEBASEACTIONFEEDBACK_H #define MSGS_DEMO_MESSAGE_MOVEBASEACTIONFEEDBACK_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> #include <actionlib_msgs/GoalStatus.h> #include <msgs_demo/MoveBaseFeedback.h> namespace msgs_demo { template <class ContainerAllocator> struct MoveBaseActionFeedback_ { typedef MoveBaseActionFeedback_<ContainerAllocator> Type; MoveBaseActionFeedback_() : header() , status() , feedback() { } MoveBaseActionFeedback_(const ContainerAllocator& _alloc) : header(_alloc) , status(_alloc) , feedback(_alloc) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef ::actionlib_msgs::GoalStatus_<ContainerAllocator> _status_type; _status_type status; typedef ::msgs_demo::MoveBaseFeedback_<ContainerAllocator> _feedback_type; _feedback_type feedback; typedef boost::shared_ptr< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> const> ConstPtr; }; // struct MoveBaseActionFeedback_ typedef ::msgs_demo::MoveBaseActionFeedback_<std::allocator<void> > MoveBaseActionFeedback; typedef boost::shared_ptr< ::msgs_demo::MoveBaseActionFeedback > MoveBaseActionFeedbackPtr; typedef boost::shared_ptr< ::msgs_demo::MoveBaseActionFeedback const> MoveBaseActionFeedbackConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> & v) { ros::message_operations::Printer< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace msgs_demo namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'nav_msgs': ['/opt/ros/kinetic/share/nav_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'msgs_demo': ['/home/flsong/simulation_of_robot_ws/src/ROS-Academy-for-Beginners/msgs_demo/msg', '/home/flsong/simulation_of_robot_ws/devel/share/msgs_demo/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> > { static const char* value() { return "7d1870ff6e0decea702b943b5af0b42e"; } static const char* value(const ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x7d1870ff6e0deceaULL; static const uint64_t static_value2 = 0x702b943b5af0b42eULL; }; template<class ContainerAllocator> struct DataType< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> > { static const char* value() { return "msgs_demo/MoveBaseActionFeedback"; } static const char* value(const ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> > { static const char* value() { return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ \n\ Header header\n\ actionlib_msgs/GoalStatus status\n\ MoveBaseFeedback feedback\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ \n\ ================================================================================\n\ MSG: actionlib_msgs/GoalStatus\n\ GoalID goal_id\n\ uint8 status\n\ uint8 PENDING = 0 # The goal has yet to be processed by the action server\n\ uint8 ACTIVE = 1 # The goal is currently being processed by the action server\n\ uint8 PREEMPTED = 2 # The goal received a cancel request after it started executing\n\ # and has since completed its execution (Terminal State)\n\ uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server (Terminal State)\n\ uint8 ABORTED = 4 # The goal was aborted during execution by the action server due\n\ # to some failure (Terminal State)\n\ uint8 REJECTED = 5 # The goal was rejected by the action server without being processed,\n\ # because the goal was unattainable or invalid (Terminal State)\n\ uint8 PREEMPTING = 6 # The goal received a cancel request after it started executing\n\ # and has not yet completed execution\n\ uint8 RECALLING = 7 # The goal received a cancel request before it started executing,\n\ # but the action server has not yet confirmed that the goal is canceled\n\ uint8 RECALLED = 8 # The goal received a cancel request before it started executing\n\ # and was successfully cancelled (Terminal State)\n\ uint8 LOST = 9 # An action client can determine that a goal is LOST. This should not be\n\ # sent over the wire by an action server\n\ \n\ #Allow for the user to associate a string with GoalStatus for debugging\n\ string text\n\ \n\ \n\ ================================================================================\n\ MSG: actionlib_msgs/GoalID\n\ # The stamp should store the time at which this goal was requested.\n\ # It is used by an action server when it tries to preempt all\n\ # goals that were requested before a certain time\n\ time stamp\n\ \n\ # The id provides a way to associate feedback and\n\ # result message with specific goal requests. The id\n\ # specified must be unique.\n\ string id\n\ \n\ \n\ ================================================================================\n\ MSG: msgs_demo/MoveBaseFeedback\n\ # ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ geometry_msgs/PoseStamped base_position\n\ \n\ \n\ ================================================================================\n\ MSG: geometry_msgs/PoseStamped\n\ # A Pose with reference coordinate frame and timestamp\n\ Header header\n\ Pose pose\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Pose\n\ # A representation of pose in free space, composed of position and orientation. \n\ Point position\n\ Quaternion orientation\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Point\n\ # This contains the position of a point in free space\n\ float64 x\n\ float64 y\n\ float64 z\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Quaternion\n\ # This represents an orientation in free space in quaternion form.\n\ \n\ float64 x\n\ float64 y\n\ float64 z\n\ float64 w\n\ "; } static const char* value(const ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.status); stream.next(m.feedback); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct MoveBaseActionFeedback_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::msgs_demo::MoveBaseActionFeedback_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "status: "; s << std::endl; Printer< ::actionlib_msgs::GoalStatus_<ContainerAllocator> >::stream(s, indent + " ", v.status); s << indent << "feedback: "; s << std::endl; Printer< ::msgs_demo::MoveBaseFeedback_<ContainerAllocator> >::stream(s, indent + " ", v.feedback); } }; } // namespace message_operations } // namespace ros #endif // MSGS_DEMO_MESSAGE_MOVEBASEACTIONFEEDBACK_H
[ "songfulin1996@outlook.com" ]
songfulin1996@outlook.com
857056044ff3ce22ab03b83a821b4e572c258d77
3c60f2d3623f587b247bd1620013c3b7a6d528da
/tests/catch.hpp
b1485cdd1f4af6eec1406ca97be5defa9bb5ec89
[]
no_license
thimovandermeer/ft_containers
ba4e9228679a848ea17e5beb1e0b727dcf6aaa42
7e9c8f5c98948765be6485d59336a0db40c9ac06
refs/heads/main
2023-07-16T16:43:57.132931
2021-09-02T13:14:07
2021-09-02T13:14:07
364,879,401
0
0
null
null
null
null
UTF-8
C++
false
false
365,726
hpp
// Copyright Catch2 Authors // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // SPDX-License-Identifier: BSL-1.0 // Catch v3.0.0-preview.3 // Generated: 2020-10-08 13:59:26.309308 // ---------------------------------------------------------- // This file is an amalgamation of multiple different files. // You probably shouldn't edit it directly. // ---------------------------------------------------------- #ifndef CATCH_AMALGAMATED_HPP_INCLUDED #define CATCH_AMALGAMATED_HPP_INCLUDED /** \file * This is a convenience header for Catch2. It includes **all** of Catch2 headers. * * Generally the Catch2 users should use specific includes they need, * but this header can be used instead for ease-of-experimentation, or * just plain convenience, at the cost of (significantly) increased * compilation times. * * When a new header is added to either the top level folder, or to the * corresponding internal subfolder, it should be added here. Headers * added to the various subparts (e.g. matchers, generators, etc...), * should go their respective catch-all headers. */ #ifndef CATCH_ALL_HPP_INCLUDED #define CATCH_ALL_HPP_INCLUDED /** \file * This is a convenience header for Catch2's benchmarking. It includes * **all** of Catch2 headers related to benchmarking. * * Generally the Catch2 users should use specific includes they need, * but this header can be used instead for ease-of-experimentation, or * just plain convenience, at the cost of (significantly) increased * compilation times. * * When a new header is added to either the `benchmark` folder, or to * the corresponding internal (detail) subfolder, it should be added here. */ #ifndef CATCH_BENCHMARK_ALL_HPP_INCLUDED #define CATCH_BENCHMARK_ALL_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_BENCHMARK_HPP_INCLUDED #define CATCH_BENCHMARK_HPP_INCLUDED #ifndef CATCH_INTERFACES_CONFIG_HPP_INCLUDED #define CATCH_INTERFACES_CONFIG_HPP_INCLUDED #ifndef CATCH_NONCOPYABLE_HPP_INCLUDED #define CATCH_NONCOPYABLE_HPP_INCLUDED namespace Catch { namespace Detail { //! Deriving classes become noncopyable and nonmovable class NonCopyable { NonCopyable( NonCopyable const& ) = delete; NonCopyable( NonCopyable&& ) = delete; NonCopyable& operator=( NonCopyable const& ) = delete; NonCopyable& operator=( NonCopyable&& ) = delete; protected: NonCopyable() noexcept = default; }; } // namespace Detail } // namespace Catch #endif // CATCH_NONCOPYABLE_HPP_INCLUDED #include <chrono> #include <iosfwd> #include <string> #include <vector> namespace Catch { enum class Verbosity { Quiet = 0, Normal, High }; struct WarnAbout { enum What { Nothing = 0x00, NoAssertions = 0x01, NoTests = 0x02 }; }; enum class ShowDurations { DefaultForReporter, Always, Never }; enum class TestRunOrder { Declared, LexicographicallySorted, Randomized }; enum class UseColour { Auto, Yes, No }; struct WaitForKeypress { enum When { Never, BeforeStart = 1, BeforeExit = 2, BeforeStartAndExit = BeforeStart | BeforeExit }; }; class TestSpec; struct IConfig : Detail::NonCopyable { virtual ~IConfig(); virtual bool allowThrows() const = 0; virtual std::ostream& stream() const = 0; virtual std::string name() const = 0; virtual bool includeSuccessfulResults() const = 0; virtual bool shouldDebugBreak() const = 0; virtual bool warnAboutMissingAssertions() const = 0; virtual bool warnAboutNoTests() const = 0; virtual int abortAfter() const = 0; virtual bool showInvisibles() const = 0; virtual ShowDurations showDurations() const = 0; virtual double minDuration() const = 0; virtual TestSpec const& testSpec() const = 0; virtual bool hasTestFilters() const = 0; virtual std::vector<std::string> const& getTestsOrTags() const = 0; virtual TestRunOrder runOrder() const = 0; virtual unsigned int rngSeed() const = 0; virtual UseColour useColour() const = 0; virtual std::vector<std::string> const& getSectionsToRun() const = 0; virtual Verbosity verbosity() const = 0; virtual bool benchmarkNoAnalysis() const = 0; virtual int benchmarkSamples() const = 0; virtual double benchmarkConfidenceInterval() const = 0; virtual unsigned int benchmarkResamples() const = 0; virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0; }; } #endif // CATCH_INTERFACES_CONFIG_HPP_INCLUDED #ifndef CATCH_CONTEXT_HPP_INCLUDED #define CATCH_CONTEXT_HPP_INCLUDED namespace Catch { struct IResultCapture; struct IRunner; struct IConfig; struct IContext { virtual ~IContext(); virtual IResultCapture* getResultCapture() = 0; virtual IRunner* getRunner() = 0; virtual IConfig const* getConfig() const = 0; }; struct IMutableContext : IContext { virtual ~IMutableContext(); virtual void setResultCapture( IResultCapture* resultCapture ) = 0; virtual void setRunner( IRunner* runner ) = 0; virtual void setConfig( IConfig const* config ) = 0; private: static IMutableContext *currentContext; friend IMutableContext& getCurrentMutableContext(); friend void cleanUpContext(); static void createContext(); }; inline IMutableContext& getCurrentMutableContext() { if( !IMutableContext::currentContext ) IMutableContext::createContext(); // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn) return *IMutableContext::currentContext; } inline IContext& getCurrentContext() { return getCurrentMutableContext(); } void cleanUpContext(); class SimplePcg32; SimplePcg32& rng(); } #endif // CATCH_CONTEXT_HPP_INCLUDED #ifndef CATCH_INTERFACES_REPORTER_HPP_INCLUDED #define CATCH_INTERFACES_REPORTER_HPP_INCLUDED #ifndef CATCH_SECTION_INFO_HPP_INCLUDED #define CATCH_SECTION_INFO_HPP_INCLUDED #ifndef CATCH_COMMON_HPP_INCLUDED #define CATCH_COMMON_HPP_INCLUDED #ifndef CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED #define CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED // Detect a number of compiler features - by compiler // The following features are defined: // // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled? // **************** // Note to maintainers: if new toggles are added please document them // in configuration.md, too // **************** // In general each macro has a _NO_<feature name> form // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. // Many features, at point of detection, define an _INTERNAL_ macro, so they // can be combined, en-mass, with the _NO_ forms later. #ifndef CATCH_PLATFORM_HPP_INCLUDED #define CATCH_PLATFORM_HPP_INCLUDED #ifdef __APPLE__ # include <TargetConditionals.h> # if TARGET_OS_OSX == 1 # define CATCH_PLATFORM_MAC # elif TARGET_OS_IPHONE == 1 # define CATCH_PLATFORM_IPHONE # endif #elif defined(linux) || defined(__linux) || defined(__linux__) # define CATCH_PLATFORM_LINUX #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) # define CATCH_PLATFORM_WINDOWS #endif #endif // CATCH_PLATFORM_HPP_INCLUDED #ifdef __cplusplus # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) # define CATCH_CPP14_OR_GREATER # endif # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) # define CATCH_CPP17_OR_GREATER # endif #endif // We have to avoid both ICC and Clang, because they try to mask themselves // as gcc, and we want only GCC in this block #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) // This only works on GCC 9+. so we have to also add a global suppression of Wparentheses // for older versions of GCC. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ _Pragma( "GCC diagnostic ignored \"-Wparentheses\"" ) # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ _Pragma( "GCC diagnostic ignored \"-Wunused-variable\"" ) # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) #endif #if defined(__clang__) # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) // As of this writing, IBM XL's implementation of __builtin_constant_p has a bug // which results in calls to destructors being emitted for each temporary, // without a matching initialization. In practice, this can result in something // like `std::string::~string` being called on an uninitialized value. // // For example, this code will likely segfault under IBM XL: // ``` // REQUIRE(std::string("12") + "34" == "1234") // ``` // // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. # if !defined(__ibmxl__) && !defined(__CUDACC__) # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */ # endif # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) #endif // __clang__ //////////////////////////////////////////////////////////////////////////////// // Assume that non-Windows platforms support posix signals by default #if !defined(CATCH_PLATFORM_WINDOWS) #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS #endif //////////////////////////////////////////////////////////////////////////////// // We know some environments not to support full POSIX signals #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS #endif #ifdef __OS400__ # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS # define CATCH_CONFIG_COLOUR_NONE #endif //////////////////////////////////////////////////////////////////////////////// // Android somehow still does not support std::to_string #if defined(__ANDROID__) # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE #endif //////////////////////////////////////////////////////////////////////////////// // Not all Windows environments support SEH properly #if defined(__MINGW32__) # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH #endif //////////////////////////////////////////////////////////////////////////////// // PS4 #if defined(__ORBIS__) # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE #endif //////////////////////////////////////////////////////////////////////////////// // Cygwin #ifdef __CYGWIN__ // Required for some versions of Cygwin to declare gettimeofday // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin # define _BSD_SOURCE // some versions of cygwin (most) do not support std::to_string. Use the libstd check. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING # endif #endif // __CYGWIN__ //////////////////////////////////////////////////////////////////////////////// // Visual C++ #if defined(_MSC_VER) # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) // Universal Windows platform does not support SEH // Or console colours (or console at all...) # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) # define CATCH_CONFIG_COLOUR_NONE # else # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH # endif // MSVC traditional preprocessor needs some workaround for __VA_ARGS__ // _MSVC_TRADITIONAL == 0 means new conformant preprocessor // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor # if !defined(__clang__) // Handle Clang masquerading for msvc # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR # endif // MSVC_TRADITIONAL # endif // __clang__ #endif // _MSC_VER #if defined(_REENTRANT) || defined(_MSC_VER) // Enable async processing, as -pthread is specified or no additional linking is required # define CATCH_INTERNAL_CONFIG_USE_ASYNC #endif // _MSC_VER //////////////////////////////////////////////////////////////////////////////// // Check if we are compiled with -fno-exceptions or equivalent #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED #endif //////////////////////////////////////////////////////////////////////////////// // DJGPP #ifdef __DJGPP__ # define CATCH_INTERNAL_CONFIG_NO_WCHAR #endif // __DJGPP__ //////////////////////////////////////////////////////////////////////////////// // Embarcadero C++Build #if defined(__BORLANDC__) #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN #endif //////////////////////////////////////////////////////////////////////////////// // Use of __COUNTER__ is suppressed during code analysis in // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly // handled by it. // Otherwise all supported compilers support COUNTER macro, // but user still might want to turn it off #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) #define CATCH_INTERNAL_CONFIG_COUNTER #endif //////////////////////////////////////////////////////////////////////////////// // RTX is a special version of Windows that is real time. // This means that it is detected as Windows, but does not provide // the same set of capabilities as real Windows does. #if defined(UNDER_RTSS) || defined(RTX64_BUILD) #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH #define CATCH_INTERNAL_CONFIG_NO_ASYNC #define CATCH_CONFIG_COLOUR_NONE #endif #if !defined(_GLIBCXX_USE_C99_MATH_TR1) #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER #endif // Various stdlib support checks that require __has_include #if defined(__has_include) // Check if string_view is available and usable #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER) # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW #endif // Check if optional is available and usable # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) // Check if byte is available and usable # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) # include <cstddef> # if __cpp_lib_byte > 0 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE # endif # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) // Check if variant is available and usable # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) # if defined(__clang__) && (__clang_major__ < 8) // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 // fix should be in clang 8, workaround in libstdc++ 8.2 # include <ciso646> # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) # define CATCH_CONFIG_NO_CPP17_VARIANT # else # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) # else # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT # endif // defined(__clang__) && (__clang_major__ < 8) # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) #endif // defined(__has_include) #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) # define CATCH_CONFIG_COUNTER #endif #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) # define CATCH_CONFIG_WINDOWS_SEH #endif // This is set by default, because we assume that unix compilers are posix-signal-compatible by default. #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) # define CATCH_CONFIG_POSIX_SIGNALS #endif // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) # define CATCH_CONFIG_WCHAR #endif #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) # define CATCH_CONFIG_CPP11_TO_STRING #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) # define CATCH_CONFIG_CPP17_OPTIONAL #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) # define CATCH_CONFIG_CPP17_STRING_VIEW #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) # define CATCH_CONFIG_CPP17_VARIANT #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) # define CATCH_CONFIG_CPP17_BYTE #endif #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE #endif #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) # define CATCH_CONFIG_NEW_CAPTURE #endif #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) # define CATCH_CONFIG_DISABLE_EXCEPTIONS #endif #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) # define CATCH_CONFIG_POLYFILL_ISNAN #endif #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) # define CATCH_CONFIG_USE_ASYNC #endif #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) # define CATCH_CONFIG_ANDROID_LOGWRITE #endif #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) # define CATCH_CONFIG_GLOBAL_NEXTAFTER #endif // Even if we do not think the compiler has that warning, we still have // to provide a macro that can be used by the code. #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION #endif #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION #endif #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS #endif // The goal of this macro is to avoid evaluation of the arguments, but // still have the compiler warn on problems inside... #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) #endif #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS #elif defined(__clang__) && (__clang_major__ < 5) # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS #endif #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) #define CATCH_TRY if ((true)) #define CATCH_CATCH_ALL if ((false)) #define CATCH_CATCH_ANON(type) if ((false)) #else #define CATCH_TRY try #define CATCH_CATCH_ALL catch (...) #define CATCH_CATCH_ANON(type) catch (type) #endif #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #endif #endif // CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED #ifndef CATCH_STRINGREF_HPP_INCLUDED #define CATCH_STRINGREF_HPP_INCLUDED #include <cstddef> #include <string> #include <iosfwd> #include <cassert> namespace Catch { /// A non-owning string class (similar to the forthcoming std::string_view) /// Note that, because a StringRef may be a substring of another string, /// it may not be null terminated. class StringRef { public: using size_type = std::size_t; using const_iterator = const char*; private: static constexpr char const* const s_empty = ""; char const* m_start = s_empty; size_type m_size = 0; public: // construction constexpr StringRef() noexcept = default; StringRef( char const* rawChars ) noexcept; constexpr StringRef( char const* rawChars, size_type size ) noexcept : m_start( rawChars ), m_size( size ) {} StringRef( std::string const& stdString ) noexcept : m_start( stdString.c_str() ), m_size( stdString.size() ) {} explicit operator std::string() const { return std::string(m_start, m_size); } public: // operators auto operator == ( StringRef const& other ) const noexcept -> bool; auto operator != (StringRef const& other) const noexcept -> bool { return !(*this == other); } constexpr auto operator[] ( size_type index ) const noexcept -> char { assert(index < m_size); return m_start[index]; } bool operator<(StringRef const& rhs) const noexcept; public: // named queries constexpr auto empty() const noexcept -> bool { return m_size == 0; } constexpr auto size() const noexcept -> size_type { return m_size; } // Returns the current start pointer. If the StringRef is not // null-terminated, throws std::domain_exception auto c_str() const -> char const*; public: // substrings and searches // Returns a substring of [start, start + length). // If start + length > size(), then the substring is [start, start + size()). // If start > size(), then the substring is empty. constexpr StringRef substr(size_type start, size_type length) const noexcept { if (start < m_size) { const auto shortened_size = m_size - start; return StringRef(m_start + start, (shortened_size < length) ? shortened_size : length); } else { return StringRef(); } } // Returns the current start pointer. May not be null-terminated. constexpr char const* data() const noexcept { return m_start; } constexpr auto isNullTerminated() const noexcept -> bool { return m_start[m_size] == '\0'; } public: // iterators constexpr const_iterator begin() const { return m_start; } constexpr const_iterator end() const { return m_start + m_size; } friend std::string& operator += (std::string& lhs, StringRef const& sr); friend std::ostream& operator << (std::ostream& os, StringRef const& sr); friend std::string operator+(StringRef lhs, StringRef rhs); }; constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { return StringRef( rawChars, size ); } } // namespace Catch constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { return Catch::StringRef( rawChars, size ); } #endif // CATCH_STRINGREF_HPP_INCLUDED #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) #ifdef CATCH_CONFIG_COUNTER # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) #else # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) #endif #include <iosfwd> // We need a dummy global operator<< so we can bring it into Catch namespace later struct Catch_global_namespace_dummy {}; std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); namespace Catch { struct SourceLineInfo { SourceLineInfo() = delete; constexpr SourceLineInfo( char const* _file, std::size_t _line ) noexcept: file( _file ), line( _line ) {} bool operator == ( SourceLineInfo const& other ) const noexcept; bool operator < ( SourceLineInfo const& other ) const noexcept; char const* file; std::size_t line; friend std::ostream& operator << (std::ostream& os, SourceLineInfo const& info); }; // Bring in operator<< from global namespace into Catch namespace // This is necessary because the overload of operator<< above makes // lookup stop at namespace Catch using ::operator<<; // Use this in variadic streaming macros to allow // >> +StreamEndStop // as well as // >> stuff +StreamEndStop struct StreamEndStop { StringRef operator+() const { return StringRef(); } template<typename T> friend T const& operator + ( T const& value, StreamEndStop ) { return value; } }; } #define CATCH_INTERNAL_LINEINFO \ ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) ) #endif // CATCH_COMMON_HPP_INCLUDED #ifndef CATCH_TOTALS_HPP_INCLUDED #define CATCH_TOTALS_HPP_INCLUDED #include <cstddef> namespace Catch { struct Counts { Counts operator - ( Counts const& other ) const; Counts& operator += ( Counts const& other ); std::size_t total() const; bool allPassed() const; bool allOk() const; std::size_t passed = 0; std::size_t failed = 0; std::size_t failedButOk = 0; }; struct Totals { Totals operator - ( Totals const& other ) const; Totals& operator += ( Totals const& other ); Totals delta( Totals const& prevTotals ) const; int error = 0; Counts assertions; Counts testCases; }; } #endif // CATCH_TOTALS_HPP_INCLUDED #include <string> namespace Catch { struct SectionInfo { // The last argument is ignored, so that people can write // SECTION("ShortName", "Proper description that is long") and // still use the `-c` flag comfortably. SectionInfo( SourceLineInfo const& _lineInfo, std::string _name, const char* const = nullptr ): name(std::move(_name)), lineInfo(_lineInfo) {} std::string name; SourceLineInfo lineInfo; }; struct SectionEndInfo { SectionInfo sectionInfo; Counts prevAssertions; double durationInSeconds; }; } // end namespace Catch #endif // CATCH_SECTION_INFO_HPP_INCLUDED #ifndef CATCH_ASSERTION_RESULT_HPP_INCLUDED #define CATCH_ASSERTION_RESULT_HPP_INCLUDED #include <string> #ifndef CATCH_ASSERTION_INFO_HPP_INCLUDED #define CATCH_ASSERTION_INFO_HPP_INCLUDED #ifndef CATCH_RESULT_TYPE_HPP_INCLUDED #define CATCH_RESULT_TYPE_HPP_INCLUDED namespace Catch { // ResultWas::OfType enum struct ResultWas { enum OfType { Unknown = -1, Ok = 0, Info = 1, Warning = 2, FailureBit = 0x10, ExpressionFailed = FailureBit | 1, ExplicitFailure = FailureBit | 2, Exception = 0x100 | FailureBit, ThrewException = Exception | 1, DidntThrowException = Exception | 2, FatalErrorCondition = 0x200 | FailureBit }; }; bool isOk( ResultWas::OfType resultType ); bool isJustInfo( int flags ); // ResultDisposition::Flags enum struct ResultDisposition { enum Flags { Normal = 0x01, ContinueOnFailure = 0x02, // Failures fail test, but execution continues FalseTest = 0x04, // Prefix expression with ! SuppressFail = 0x08 // Failures are reported but do not fail the test }; }; ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ); bool shouldContinueOnFailure( int flags ); inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } bool shouldSuppressFailure( int flags ); } // end namespace Catch #endif // CATCH_RESULT_TYPE_HPP_INCLUDED namespace Catch { struct AssertionInfo { // AssertionInfo() = delete; StringRef macroName; SourceLineInfo lineInfo; StringRef capturedExpression; ResultDisposition::Flags resultDisposition; }; } // end namespace Catch #endif // CATCH_ASSERTION_INFO_HPP_INCLUDED #ifndef CATCH_LAZY_EXPR_HPP_INCLUDED #define CATCH_LAZY_EXPR_HPP_INCLUDED #include <iosfwd> namespace Catch { struct ITransientExpression; class LazyExpression { friend class AssertionHandler; friend struct AssertionStats; friend class RunContext; ITransientExpression const* m_transientExpression = nullptr; bool m_isNegated; public: LazyExpression( bool isNegated ): m_isNegated(isNegated) {} LazyExpression(LazyExpression const& other) = default; LazyExpression& operator = ( LazyExpression const& ) = delete; explicit operator bool() const { return m_transientExpression != nullptr; } friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&; }; } // namespace Catch #endif // CATCH_LAZY_EXPR_HPP_INCLUDED namespace Catch { struct AssertionResultData { AssertionResultData() = delete; AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression ); std::string message; mutable std::string reconstructedExpression; LazyExpression lazyExpression; ResultWas::OfType resultType; std::string reconstructExpression() const; }; class AssertionResult { public: AssertionResult() = delete; AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); bool isOk() const; bool succeeded() const; ResultWas::OfType getResultType() const; bool hasExpression() const; bool hasMessage() const; std::string getExpression() const; std::string getExpressionInMacro() const; bool hasExpandedExpression() const; std::string getExpandedExpression() const; std::string getMessage() const; SourceLineInfo getSourceInfo() const; StringRef getTestMacroName() const; //protected: AssertionInfo m_info; AssertionResultData m_resultData; }; } // end namespace Catch #endif // CATCH_ASSERTION_RESULT_HPP_INCLUDED #ifndef CATCH_MESSAGE_INFO_HPP_INCLUDED #define CATCH_MESSAGE_INFO_HPP_INCLUDED #ifndef CATCH_INTERFACES_CAPTURE_HPP_INCLUDED #define CATCH_INTERFACES_CAPTURE_HPP_INCLUDED #include <string> #include <chrono> namespace Catch { class AssertionResult; struct AssertionInfo; struct SectionInfo; struct SectionEndInfo; struct MessageInfo; struct MessageBuilder; struct Counts; struct AssertionReaction; struct SourceLineInfo; struct ITransientExpression; struct IGeneratorTracker; struct BenchmarkInfo; template <typename Duration = std::chrono::duration<double, std::nano>> struct BenchmarkStats; struct IResultCapture { virtual ~IResultCapture(); virtual bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) = 0; virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0; virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0; virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0; virtual void benchmarkPreparing( std::string const& name ) = 0; virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0; virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0; virtual void benchmarkFailed( std::string const& error ) = 0; virtual void pushScopedMessage( MessageInfo const& message ) = 0; virtual void popScopedMessage( MessageInfo const& message ) = 0; virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0; virtual void handleFatalErrorCondition( StringRef message ) = 0; virtual void handleExpr ( AssertionInfo const& info, ITransientExpression const& expr, AssertionReaction& reaction ) = 0; virtual void handleMessage ( AssertionInfo const& info, ResultWas::OfType resultType, StringRef const& message, AssertionReaction& reaction ) = 0; virtual void handleUnexpectedExceptionNotThrown ( AssertionInfo const& info, AssertionReaction& reaction ) = 0; virtual void handleUnexpectedInflightException ( AssertionInfo const& info, std::string const& message, AssertionReaction& reaction ) = 0; virtual void handleIncomplete ( AssertionInfo const& info ) = 0; virtual void handleNonExpr ( AssertionInfo const &info, ResultWas::OfType resultType, AssertionReaction &reaction ) = 0; virtual bool lastAssertionPassed() = 0; virtual void assertionPassed() = 0; // Deprecated, do not use: virtual std::string getCurrentTestName() const = 0; virtual const AssertionResult* getLastResult() const = 0; virtual void exceptionEarlyReported() = 0; }; IResultCapture& getResultCapture(); } #endif // CATCH_INTERFACES_CAPTURE_HPP_INCLUDED #include <string> namespace Catch { struct MessageInfo { MessageInfo( StringRef const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ); StringRef macroName; std::string message; SourceLineInfo lineInfo; ResultWas::OfType type; unsigned int sequence; bool operator == (MessageInfo const& other) const { return sequence == other.sequence; } bool operator < (MessageInfo const& other) const { return sequence < other.sequence; } private: static unsigned int globalCount; }; } // end namespace Catch #endif // CATCH_MESSAGE_INFO_HPP_INCLUDED #ifndef CATCH_UNIQUE_PTR_HPP_INCLUDED #define CATCH_UNIQUE_PTR_HPP_INCLUDED #include <cassert> #include <type_traits> namespace Catch { namespace Detail { // reimplementation of unique_ptr for improved compilation times // Does not support custom deleters (and thus does not require EBO) // Does not support arrays template <typename T> class unique_ptr { T* m_ptr; public: constexpr unique_ptr(std::nullptr_t = nullptr): m_ptr{} {} explicit constexpr unique_ptr(T* ptr): m_ptr(ptr) {} template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>> unique_ptr(unique_ptr<U>&& from): m_ptr(from.release()) {} template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>> unique_ptr& operator=(unique_ptr<U>&& from) { reset(from.release()); return *this; } unique_ptr(unique_ptr const&) = delete; unique_ptr& operator=(unique_ptr const&) = delete; unique_ptr(unique_ptr&& rhs) noexcept: m_ptr(rhs.m_ptr) { rhs.m_ptr = nullptr; } unique_ptr& operator=(unique_ptr&& rhs) noexcept { reset(rhs.release()); return *this; } ~unique_ptr() { delete m_ptr; } T& operator*() { assert(m_ptr); return *m_ptr; } T const& operator*() const { assert(m_ptr); return *m_ptr; } T* operator->() const noexcept { assert(m_ptr); return m_ptr; } T* get() { return m_ptr; } T const* get() const { return m_ptr; } void reset(T* ptr = nullptr) { delete m_ptr; m_ptr = ptr; } T* release() { auto temp = m_ptr; m_ptr = nullptr; return temp; } explicit operator bool() const { return m_ptr; } friend void swap(unique_ptr& lhs, unique_ptr& rhs) { auto temp = lhs.m_ptr; lhs.m_ptr = rhs.m_ptr; rhs.m_ptr = temp; } }; // Purposefully doesn't exist // We could also rely on compiler warning + werror for calling plain delete // on a T[], but this seems better. // Maybe add definition and a static assert? template <typename T> class unique_ptr<T[]>; template <typename T, typename... Args> unique_ptr<T> make_unique(Args&&... args) { // static_cast<Args&&> does the same thing as std::forward in // this case, but does not require including big header (<utility>) // and compiles faster thanks to not requiring template instantiation // and overload resolution return unique_ptr<T>(new T(static_cast<Args&&>(args)...)); } } // end namespace Detail } // end namespace Catch #endif // CATCH_UNIQUE_PTR_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_ESTIMATE_HPP_INCLUDED #define CATCH_ESTIMATE_HPP_INCLUDED namespace Catch { namespace Benchmark { template <typename Duration> struct Estimate { Duration point; Duration lower_bound; Duration upper_bound; double confidence_interval; template <typename Duration2> operator Estimate<Duration2>() const { return { point, lower_bound, upper_bound, confidence_interval }; } }; } // namespace Benchmark } // namespace Catch #endif // CATCH_ESTIMATE_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_OUTLIER_CLASSIFICATION_HPP_INCLUDED #define CATCH_OUTLIER_CLASSIFICATION_HPP_INCLUDED namespace Catch { namespace Benchmark { struct OutlierClassification { int samples_seen = 0; int low_severe = 0; // more than 3 times IQR below Q1 int low_mild = 0; // 1.5 to 3 times IQR below Q1 int high_mild = 0; // 1.5 to 3 times IQR above Q3 int high_severe = 0; // more than 3 times IQR above Q3 int total() const { return low_severe + low_mild + high_mild + high_severe; } }; } // namespace Benchmark } // namespace Catch #endif // CATCH_OUTLIERS_CLASSIFICATION_HPP_INCLUDED #include <string> #include <vector> #include <iosfwd> namespace Catch { struct ReporterDescription; struct TagInfo; struct TestCaseInfo; class TestCaseHandle; struct IConfig; struct ReporterConfig { explicit ReporterConfig( IConfig const* _fullConfig ); ReporterConfig( IConfig const* _fullConfig, std::ostream& _stream ); std::ostream& stream() const; IConfig const* fullConfig() const; private: std::ostream* m_stream; IConfig const* m_fullConfig; }; struct TestRunInfo { TestRunInfo( std::string const& _name ); std::string name; }; struct GroupInfo { GroupInfo( std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount ); std::string name; std::size_t groupIndex; std::size_t groupsCounts; }; struct AssertionStats { AssertionStats( AssertionResult const& _assertionResult, std::vector<MessageInfo> const& _infoMessages, Totals const& _totals ); AssertionStats( AssertionStats const& ) = default; AssertionStats( AssertionStats && ) = default; AssertionStats& operator = ( AssertionStats const& ) = delete; AssertionStats& operator = ( AssertionStats && ) = delete; AssertionResult assertionResult; std::vector<MessageInfo> infoMessages; Totals totals; }; struct SectionStats { SectionStats( SectionInfo const& _sectionInfo, Counts const& _assertions, double _durationInSeconds, bool _missingAssertions ); SectionInfo sectionInfo; Counts assertions; double durationInSeconds; bool missingAssertions; }; struct TestCaseStats { TestCaseStats( TestCaseInfo const& _testInfo, Totals const& _totals, std::string const& _stdOut, std::string const& _stdErr, bool _aborting ); TestCaseInfo const * testInfo; Totals totals; std::string stdOut; std::string stdErr; bool aborting; }; struct TestGroupStats { TestGroupStats( GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting ); TestGroupStats( GroupInfo const& _groupInfo ); GroupInfo groupInfo; Totals totals; bool aborting; }; struct TestRunStats { TestRunStats( TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting ); TestRunInfo runInfo; Totals totals; bool aborting; }; struct BenchmarkInfo { std::string name; double estimatedDuration; int iterations; int samples; unsigned int resamples; double clockResolution; double clockCost; }; template <class Duration> struct BenchmarkStats { BenchmarkInfo info; std::vector<Duration> samples; Benchmark::Estimate<Duration> mean; Benchmark::Estimate<Duration> standardDeviation; Benchmark::OutlierClassification outliers; double outlierVariance; template <typename Duration2> operator BenchmarkStats<Duration2>() const { std::vector<Duration2> samples2; samples2.reserve(samples.size()); for (auto const& sample : samples) { samples2.push_back(Duration2(sample)); } return { info, std::move(samples2), mean, standardDeviation, outliers, outlierVariance, }; } }; //! By setting up its preferences, a reporter can modify Catch2's behaviour //! in some regards, e.g. it can request Catch2 to capture writes to //! stdout/stderr during test execution, and pass them to the reporter. struct ReporterPreferences { //! Catch2 should redirect writes to stdout and pass them to the //! reporter bool shouldRedirectStdOut = false; //! Catch2 should call `Reporter::assertionEnded` even for passing //! assertions bool shouldReportAllAssertions = false; }; struct IStreamingReporter { protected: //! Derived classes can set up their preferences here ReporterPreferences m_preferences; public: virtual ~IStreamingReporter() = default; // Implementing class must also provide the following static methods: // static std::string getDescription(); ReporterPreferences const& getPreferences() const { return m_preferences; } virtual void noMatchingTestCases( std::string const& spec ) = 0; virtual void reportInvalidArguments(std::string const&) {} virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; virtual void benchmarkPreparing( std::string const& ) {} virtual void benchmarkStarting( BenchmarkInfo const& ) {} virtual void benchmarkEnded( BenchmarkStats<> const& ) {} virtual void benchmarkFailed( std::string const& ) {} virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; // The return value indicates if the messages buffer should be cleared: virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; virtual void sectionEnded( SectionStats const& sectionStats ) = 0; virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; virtual void skipTest( TestCaseInfo const& testInfo ) = 0; // Default empty implementation provided virtual void fatalErrorEncountered( StringRef name ); //! Writes out information about provided reporters using reporter-specific format virtual void listReporters(std::vector<ReporterDescription> const& descriptions, IConfig const& config); //! Writes out information about provided tests using reporter-specific format virtual void listTests(std::vector<TestCaseHandle> const& tests, IConfig const& config); //! Writes out information about the provided tags using reporter-specific format virtual void listTags(std::vector<TagInfo> const& tags, IConfig const& config); }; using IStreamingReporterPtr = Detail::unique_ptr<IStreamingReporter>; } // end namespace Catch #endif // CATCH_INTERFACES_REPORTER_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_CHRONOMETER_HPP_INCLUDED #define CATCH_CHRONOMETER_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_CLOCK_HPP_INCLUDED #define CATCH_CLOCK_HPP_INCLUDED #include <chrono> #include <ratio> namespace Catch { namespace Benchmark { template <typename Clock> using ClockDuration = typename Clock::duration; template <typename Clock> using FloatDuration = std::chrono::duration<double, typename Clock::period>; template <typename Clock> using TimePoint = typename Clock::time_point; using default_clock = std::chrono::steady_clock; template <typename Clock> struct now { TimePoint<Clock> operator()() const { return Clock::now(); } }; using fp_seconds = std::chrono::duration<double, std::ratio<1>>; } // namespace Benchmark } // namespace Catch #endif // CATCH_CLOCK_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_OPTIMIZER_HPP_INCLUDED #define CATCH_OPTIMIZER_HPP_INCLUDED #if defined(_MSC_VER) # include <atomic> // atomic_thread_fence #endif #include <type_traits> #include <utility> namespace Catch { namespace Benchmark { #if defined(__GNUC__) || defined(__clang__) template <typename T> inline void keep_memory(T* p) { asm volatile("" : : "g"(p) : "memory"); } inline void keep_memory() { asm volatile("" : : : "memory"); } namespace Detail { inline void optimizer_barrier() { keep_memory(); } } // namespace Detail #elif defined(_MSC_VER) #pragma optimize("", off) template <typename T> inline void keep_memory(T* p) { // thanks @milleniumbug *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p); } // TODO equivalent keep_memory() #pragma optimize("", on) namespace Detail { inline void optimizer_barrier() { std::atomic_thread_fence(std::memory_order_seq_cst); } } // namespace Detail #endif template <typename T> inline void deoptimize_value(T&& x) { keep_memory(&x); } template <typename Fn, typename... Args> inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type { deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...))); } template <typename Fn, typename... Args> inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type { std::forward<Fn>(fn) (std::forward<Args...>(args...)); } } // namespace Benchmark } // namespace Catch #endif // CATCH_OPTIMIZER_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_COMPLETE_INVOKE_HPP_INCLUDED #define CATCH_COMPLETE_INVOKE_HPP_INCLUDED #ifndef CATCH_ENFORCE_HPP_INCLUDED #define CATCH_ENFORCE_HPP_INCLUDED #ifndef CATCH_STREAM_HPP_INCLUDED #define CATCH_STREAM_HPP_INCLUDED #include <iosfwd> #include <cstddef> #include <ostream> namespace Catch { std::ostream& cout(); std::ostream& cerr(); std::ostream& clog(); class StringRef; struct IStream { virtual ~IStream(); virtual std::ostream& stream() const = 0; }; auto makeStream( StringRef const &filename ) -> IStream const*; class ReusableStringStream : Detail::NonCopyable { std::size_t m_index; std::ostream* m_oss; public: ReusableStringStream(); ~ReusableStringStream(); //! Returns the serialized state std::string str() const; //! Sets internal state to `str` void str(std::string const& str); #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic push // Old versions of GCC do not understand -Wnonnull-compare #pragma GCC diagnostic ignored "-Wpragmas" // Streaming a function pointer triggers Waddress and Wnonnull-compare // on GCC, because it implicitly converts it to bool and then decides // that the check it uses (a? true : false) is tautological and cannot // be null... #pragma GCC diagnostic ignored "-Waddress" #pragma GCC diagnostic ignored "-Wnonnull-compare" #endif template<typename T> auto operator << ( T const& value ) -> ReusableStringStream& { *m_oss << value; return *this; } #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic pop #endif auto get() -> std::ostream& { return *m_oss; } }; } #endif // CATCH_STREAM_HPP_INCLUDED #include <exception> namespace Catch { #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) template <typename Ex> [[noreturn]] void throw_exception(Ex const& e) { throw e; } #else // ^^ Exceptions are enabled // Exceptions are disabled vv [[noreturn]] void throw_exception(std::exception const& e); #endif [[noreturn]] void throw_logic_error(std::string const& msg); [[noreturn]] void throw_domain_error(std::string const& msg); [[noreturn]] void throw_runtime_error(std::string const& msg); } // namespace Catch; #define CATCH_MAKE_MSG(...) \ (Catch::ReusableStringStream() << __VA_ARGS__).str() #define CATCH_INTERNAL_ERROR(...) \ Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__)) #define CATCH_ERROR(...) \ Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ )) #define CATCH_RUNTIME_ERROR(...) \ Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ )) #define CATCH_ENFORCE( condition, ... ) \ do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false) #endif // CATCH_ENFORCE_HPP_INCLUDED #ifndef CATCH_META_HPP_INCLUDED #define CATCH_META_HPP_INCLUDED #include <type_traits> namespace Catch { template<typename T> struct always_false : std::false_type {}; template <typename> struct true_given : std::true_type {}; struct is_callable_tester { template <typename Fun, typename... Args> true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int); template <typename...> std::false_type static test(...); }; template <typename T> struct is_callable; template <typename Fun, typename... Args> struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {}; #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is // replaced with std::invoke_result here. template <typename Func, typename... U> using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>; #else template <typename Func, typename... U> using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::result_of_t<Func(U...)>>>; #endif } // namespace Catch namespace mpl_{ struct na; } #endif // CATCH_META_HPP_INCLUDED #ifndef CATCH_INTERFACES_REGISTRY_HUB_HPP_INCLUDED #define CATCH_INTERFACES_REGISTRY_HUB_HPP_INCLUDED #include <string> namespace Catch { class TestCaseHandle; struct TestCaseInfo; struct ITestCaseRegistry; struct IExceptionTranslatorRegistry; struct IExceptionTranslator; struct IReporterRegistry; struct IReporterFactory; struct ITagAliasRegistry; struct ITestInvoker; struct IMutableEnumValuesRegistry; struct SourceLineInfo; class StartupExceptionRegistry; using IReporterFactoryPtr = Detail::unique_ptr<IReporterFactory>; struct IRegistryHub { virtual ~IRegistryHub(); virtual IReporterRegistry const& getReporterRegistry() const = 0; virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0; virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0; virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0; }; struct IMutableRegistryHub { virtual ~IMutableRegistryHub(); virtual void registerReporter( std::string const& name, IReporterFactoryPtr factory ) = 0; virtual void registerListener( IReporterFactoryPtr factory ) = 0; virtual void registerTest(Detail::unique_ptr<TestCaseInfo>&& testInfo, Detail::unique_ptr<ITestInvoker>&& invoker) = 0; virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0; virtual void registerStartupException() noexcept = 0; virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0; }; IRegistryHub const& getRegistryHub(); IMutableRegistryHub& getMutableRegistryHub(); void cleanUp(); std::string translateActiveException(); } #endif // CATCH_INTERFACES_REGISTRY_HUB_HPP_INCLUDED #include <type_traits> #include <utility> namespace Catch { namespace Benchmark { namespace Detail { template <typename T> struct CompleteType { using type = T; }; template <> struct CompleteType<void> { struct type {}; }; template <typename T> using CompleteType_t = typename CompleteType<T>::type; template <typename Result> struct CompleteInvoker { template <typename Fun, typename... Args> static Result invoke(Fun&& fun, Args&&... args) { return std::forward<Fun>(fun)(std::forward<Args>(args)...); } }; template <> struct CompleteInvoker<void> { template <typename Fun, typename... Args> static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) { std::forward<Fun>(fun)(std::forward<Args>(args)...); return {}; } }; // invoke and not return void :( template <typename Fun, typename... Args> CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) { return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...); } extern const std::string benchmarkErrorMsg; } // namespace Detail template <typename Fun> Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) { CATCH_TRY{ return Detail::complete_invoke(std::forward<Fun>(fun)); } CATCH_CATCH_ALL{ getResultCapture().benchmarkFailed(translateActiveException()); CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg); } } } // namespace Benchmark } // namespace Catch #endif // CATCH_COMPLETE_INVOKE_HPP_INCLUDED namespace Catch { namespace Benchmark { namespace Detail { struct ChronometerConcept { virtual void start() = 0; virtual void finish() = 0; virtual ~ChronometerConcept(); // = default; ChronometerConcept() = default; ChronometerConcept(ChronometerConcept const&) = default; ChronometerConcept& operator=(ChronometerConcept const&) = default; }; template <typename Clock> struct ChronometerModel final : public ChronometerConcept { void start() override { started = Clock::now(); } void finish() override { finished = Clock::now(); } ClockDuration<Clock> elapsed() const { return finished - started; } TimePoint<Clock> started; TimePoint<Clock> finished; }; } // namespace Detail struct Chronometer { public: template <typename Fun> void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); } int runs() const { return repeats; } Chronometer(Detail::ChronometerConcept& meter, int repeats_) : impl(&meter) , repeats(repeats_) {} private: template <typename Fun> void measure(Fun&& fun, std::false_type) { measure([&fun](int) { return fun(); }, std::true_type()); } template <typename Fun> void measure(Fun&& fun, std::true_type) { Detail::optimizer_barrier(); impl->start(); for (int i = 0; i < repeats; ++i) invoke_deoptimized(fun, i); impl->finish(); Detail::optimizer_barrier(); } Detail::ChronometerConcept* impl; int repeats; }; } // namespace Benchmark } // namespace Catch #endif // CATCH_CHRONOMETER_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_ENVIRONMENT_HPP_INCLUDED #define CATCH_ENVIRONMENT_HPP_INCLUDED namespace Catch { namespace Benchmark { template <typename Duration> struct EnvironmentEstimate { Duration mean; OutlierClassification outliers; template <typename Duration2> operator EnvironmentEstimate<Duration2>() const { return { mean, outliers }; } }; template <typename Clock> struct Environment { using clock_type = Clock; EnvironmentEstimate<FloatDuration<Clock>> clock_resolution; EnvironmentEstimate<FloatDuration<Clock>> clock_cost; }; } // namespace Benchmark } // namespace Catch #endif // CATCH_ENVIRONMENT_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_EXECUTION_PLAN_HPP_INCLUDED #define CATCH_EXECUTION_PLAN_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_BENCHMARK_FUNCTION_HPP_INCLUDED #define CATCH_BENCHMARK_FUNCTION_HPP_INCLUDED #include <cassert> #include <type_traits> #include <utility> namespace Catch { namespace Benchmark { namespace Detail { template <typename T> using Decay = typename std::decay<T>::type; template <typename T, typename U> struct is_related : std::is_same<Decay<T>, Decay<U>> {}; /// We need to reinvent std::function because every piece of code that might add overhead /// in a measurement context needs to have consistent performance characteristics so that we /// can account for it in the measurement. /// Implementations of std::function with optimizations that aren't always applicable, like /// small buffer optimizations, are not uncommon. /// This is effectively an implementation of std::function without any such optimizations; /// it may be slow, but it is consistently slow. struct BenchmarkFunction { private: struct callable { virtual void call(Chronometer meter) const = 0; virtual callable* clone() const = 0; virtual ~callable(); // = default; callable() = default; callable(callable const&) = default; callable& operator=(callable const&) = default; }; template <typename Fun> struct model : public callable { model(Fun&& fun_) : fun(std::move(fun_)) {} model(Fun const& fun_) : fun(fun_) {} model<Fun>* clone() const override { return new model<Fun>(*this); } void call(Chronometer meter) const override { call(meter, is_callable<Fun(Chronometer)>()); } void call(Chronometer meter, std::true_type) const { fun(meter); } void call(Chronometer meter, std::false_type) const { meter.measure(fun); } Fun fun; }; struct do_nothing { void operator()() const {} }; template <typename T> BenchmarkFunction(model<T>* c) : f(c) {} public: BenchmarkFunction() : f(new model<do_nothing>{ {} }) {} template <typename Fun, typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0> BenchmarkFunction(Fun&& fun) : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {} BenchmarkFunction( BenchmarkFunction&& that ) noexcept: f( std::move( that.f ) ) {} BenchmarkFunction(BenchmarkFunction const& that) : f(that.f->clone()) {} BenchmarkFunction& operator=( BenchmarkFunction&& that ) noexcept { f = std::move( that.f ); return *this; } BenchmarkFunction& operator=(BenchmarkFunction const& that) { f.reset(that.f->clone()); return *this; } void operator()(Chronometer meter) const { f->call(meter); } private: Catch::Detail::unique_ptr<callable> f; }; } // namespace Detail } // namespace Benchmark } // namespace Catch #endif // CATCH_BENCHMARK_FUNCTION_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_REPEAT_HPP_INCLUDED #define CATCH_REPEAT_HPP_INCLUDED #include <type_traits> #include <utility> namespace Catch { namespace Benchmark { namespace Detail { template <typename Fun> struct repeater { void operator()(int k) const { for (int i = 0; i < k; ++i) { fun(); } } Fun fun; }; template <typename Fun> repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) { return { std::forward<Fun>(fun) }; } } // namespace Detail } // namespace Benchmark } // namespace Catch #endif // CATCH_REPEAT_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_RUN_FOR_AT_LEAST_HPP_INCLUDED #define CATCH_RUN_FOR_AT_LEAST_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_MEASURE_HPP_INCLUDED #define CATCH_MEASURE_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_TIMING_HPP_INCLUDED #define CATCH_TIMING_HPP_INCLUDED #include <type_traits> namespace Catch { namespace Benchmark { template <typename Duration, typename Result> struct Timing { Duration elapsed; Result result; int iterations; }; template <typename Clock, typename Func, typename... Args> using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>; } // namespace Benchmark } // namespace Catch #endif // CATCH_TIMING_HPP_INCLUDED #include <utility> namespace Catch { namespace Benchmark { namespace Detail { template <typename Clock, typename Fun, typename... Args> TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) { auto start = Clock::now(); auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...); auto end = Clock::now(); auto delta = end - start; return { delta, std::forward<decltype(r)>(r), 1 }; } } // namespace Detail } // namespace Benchmark } // namespace Catch #endif // CATCH_MEASURE_HPP_INCLUDED #include <utility> #include <type_traits> namespace Catch { namespace Benchmark { namespace Detail { template <typename Clock, typename Fun> TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) { return Detail::measure<Clock>(fun, iters); } template <typename Clock, typename Fun> TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) { Detail::ChronometerModel<Clock> meter; auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters)); return { meter.elapsed(), std::move(result), iters }; } template <typename Clock, typename Fun> using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type; [[noreturn]] void throw_optimized_away_error(); template <typename Clock, typename Fun> TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) { auto iters = seed; while (iters < (1 << 30)) { auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>()); if (Timing.elapsed >= how_long) { return { Timing.elapsed, std::move(Timing.result), iters }; } iters *= 2; } throw_optimized_away_error(); } } // namespace Detail } // namespace Benchmark } // namespace Catch #endif // CATCH_RUN_FOR_AT_LEAST_HPP_INCLUDED #include <algorithm> namespace Catch { namespace Benchmark { template <typename Duration> struct ExecutionPlan { int iterations_per_sample; Duration estimated_duration; Detail::BenchmarkFunction benchmark; Duration warmup_time; int warmup_iterations; template <typename Duration2> operator ExecutionPlan<Duration2>() const { return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations }; } template <typename Clock> std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const { // warmup a bit Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{})); std::vector<FloatDuration<Clock>> times; times.reserve(cfg.benchmarkSamples()); std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] { Detail::ChronometerModel<Clock> model; this->benchmark(Chronometer(model, iterations_per_sample)); auto sample_time = model.elapsed() - env.clock_cost.mean; if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero(); return sample_time / iterations_per_sample; }); return times; } }; } // namespace Benchmark } // namespace Catch #endif // CATCH_EXECUTION_PLAN_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_ESTIMATE_CLOCK_HPP_INCLUDED #define CATCH_ESTIMATE_CLOCK_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_STATS_HPP_INCLUDED #define CATCH_STATS_HPP_INCLUDED #include <algorithm> #include <vector> #include <numeric> #include <tuple> #include <cmath> #include <utility> namespace Catch { namespace Benchmark { namespace Detail { using sample = std::vector<double>; double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last); template <typename Iterator> OutlierClassification classify_outliers(Iterator first, Iterator last) { std::vector<double> copy(first, last); auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end()); auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end()); auto iqr = q3 - q1; auto los = q1 - (iqr * 3.); auto lom = q1 - (iqr * 1.5); auto him = q3 + (iqr * 1.5); auto his = q3 + (iqr * 3.); OutlierClassification o; for (; first != last; ++first) { auto&& t = *first; if (t < los) ++o.low_severe; else if (t < lom) ++o.low_mild; else if (t > his) ++o.high_severe; else if (t > him) ++o.high_mild; ++o.samples_seen; } return o; } template <typename Iterator> double mean(Iterator first, Iterator last) { auto count = last - first; double sum = std::accumulate(first, last, 0.); return sum / count; } template <typename Estimator, typename Iterator> sample jackknife(Estimator&& estimator, Iterator first, Iterator last) { auto n = last - first; auto second = first; ++second; sample results; results.reserve(n); for (auto it = first; it != last; ++it) { std::iter_swap(it, first); results.push_back(estimator(second, last)); } return results; } inline double normal_cdf(double x) { return std::erfc(-x / std::sqrt(2.0)) / 2.0; } double erfc_inv(double x); double normal_quantile(double p); template <typename Iterator, typename Estimator> Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) { auto n_samples = last - first; double point = estimator(first, last); // Degenerate case with a single sample if (n_samples == 1) return { point, point, point, confidence_level }; sample jack = jackknife(estimator, first, last); double jack_mean = mean(jack.begin(), jack.end()); double sum_squares, sum_cubes; std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> { auto d = jack_mean - x; auto d2 = d * d; auto d3 = d2 * d; return { sqcb.first + d2, sqcb.second + d3 }; }); double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5)); int n = static_cast<int>(resample.size()); double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n; // degenerate case with uniform samples if (prob_n == 0) return { point, point, point, confidence_level }; double bias = normal_quantile(prob_n); double z1 = normal_quantile((1. - confidence_level) / 2.); auto cumn = [n](double x) -> int { return std::lround(normal_cdf(x) * n); }; auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); }; double b1 = bias + z1; double b2 = bias - z1; double a1 = a(b1); double a2 = a(b2); auto lo = std::max(cumn(a1), 0); auto hi = std::min(cumn(a2), n - 1); return { point, resample[lo], resample[hi], confidence_level }; } double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n); struct bootstrap_analysis { Estimate<double> mean; Estimate<double> standard_deviation; double outlier_variance; }; bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last); } // namespace Detail } // namespace Benchmark } // namespace Catch #endif // CATCH_STATS_HPP_INCLUDED #include <algorithm> #include <iterator> #include <vector> #include <cmath> namespace Catch { namespace Benchmark { namespace Detail { template <typename Clock> std::vector<double> resolution(int k) { std::vector<TimePoint<Clock>> times; times.reserve(k + 1); std::generate_n(std::back_inserter(times), k + 1, now<Clock>{}); std::vector<double> deltas; deltas.reserve(k); std::transform(std::next(times.begin()), times.end(), times.begin(), std::back_inserter(deltas), [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); }); return deltas; } const auto warmup_iterations = 10000; const auto warmup_time = std::chrono::milliseconds(100); const auto minimum_ticks = 1000; const auto warmup_seed = 10000; const auto clock_resolution_estimation_time = std::chrono::milliseconds(500); const auto clock_cost_estimation_time_limit = std::chrono::seconds(1); const auto clock_cost_estimation_tick_limit = 100000; const auto clock_cost_estimation_time = std::chrono::milliseconds(10); const auto clock_cost_estimation_iterations = 10000; template <typename Clock> int warmup() { return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>) .iterations; } template <typename Clock> EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) { auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>) .result; return { FloatDuration<Clock>(mean(r.begin(), r.end())), classify_outliers(r.begin(), r.end()), }; } template <typename Clock> EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) { auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit)); auto time_clock = [](int k) { return Detail::measure<Clock>([k] { for (int i = 0; i < k; ++i) { volatile auto ignored = Clock::now(); (void)ignored; } }).elapsed; }; time_clock(1); int iters = clock_cost_estimation_iterations; auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock); std::vector<double> times; int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed)); times.reserve(nsamples); std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] { return static_cast<double>((time_clock(r.iterations) / r.iterations).count()); }); return { FloatDuration<Clock>(mean(times.begin(), times.end())), classify_outliers(times.begin(), times.end()), }; } template <typename Clock> Environment<FloatDuration<Clock>> measure_environment() { static Environment<FloatDuration<Clock>>* env = nullptr; if (env) { return *env; } auto iters = Detail::warmup<Clock>(); auto resolution = Detail::estimate_clock_resolution<Clock>(iters); auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean); env = new Environment<FloatDuration<Clock>>{ resolution, cost }; return *env; } } // namespace Detail } // namespace Benchmark } // namespace Catch #endif // CATCH_ESTIMATE_CLOCK_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_ANALYSE_HPP_INCLUDED #define CATCH_ANALYSE_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_SAMPLE_ANALYSIS_HPP_INCLUDED #define CATCH_SAMPLE_ANALYSIS_HPP_INCLUDED #include <algorithm> #include <vector> #include <string> #include <iterator> namespace Catch { namespace Benchmark { template <typename Duration> struct SampleAnalysis { std::vector<Duration> samples; Estimate<Duration> mean; Estimate<Duration> standard_deviation; OutlierClassification outliers; double outlier_variance; template <typename Duration2> operator SampleAnalysis<Duration2>() const { std::vector<Duration2> samples2; samples2.reserve(samples.size()); std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); }); return { std::move(samples2), mean, standard_deviation, outliers, outlier_variance, }; } }; } // namespace Benchmark } // namespace Catch #endif // CATCH_SAMPLE_ANALYSIS_HPP_INCLUDED #include <algorithm> #include <iterator> #include <vector> namespace Catch { namespace Benchmark { namespace Detail { template <typename Duration, typename Iterator> SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) { if (!cfg.benchmarkNoAnalysis()) { std::vector<double> samples; samples.reserve(last - first); std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); }); auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end()); auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end()); auto wrap_estimate = [](Estimate<double> e) { return Estimate<Duration> { Duration(e.point), Duration(e.lower_bound), Duration(e.upper_bound), e.confidence_interval, }; }; std::vector<Duration> samples2; samples2.reserve(samples.size()); std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); }); return { std::move(samples2), wrap_estimate(analysis.mean), wrap_estimate(analysis.standard_deviation), outliers, analysis.outlier_variance, }; } else { std::vector<Duration> samples; samples.reserve(last - first); Duration mean = Duration(0); int i = 0; for (auto it = first; it < last; ++it, ++i) { samples.push_back(Duration(*it)); mean += Duration(*it); } mean /= i; return { std::move(samples), Estimate<Duration>{mean, mean, mean, 0.0}, Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0}, OutlierClassification{}, 0.0 }; } } } // namespace Detail } // namespace Benchmark } // namespace Catch #endif // CATCH_ANALYSE_HPP_INCLUDED #include <algorithm> #include <functional> #include <string> #include <vector> #include <cmath> namespace Catch { namespace Benchmark { struct Benchmark { Benchmark(std::string&& benchmarkName) : name(std::move(benchmarkName)) {} template <class FUN> Benchmark(std::string&& benchmarkName , FUN &&func) : fun(std::move(func)), name(std::move(benchmarkName)) {} template <typename Clock> ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const { auto min_time = env.clock_resolution.mean * Detail::minimum_ticks; auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime())); auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun); int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed)); return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations }; } template <typename Clock = default_clock> void run() { auto const* cfg = getCurrentContext().getConfig(); auto env = Detail::measure_environment<Clock>(); getResultCapture().benchmarkPreparing(name); CATCH_TRY{ auto plan = user_code([&] { return prepare<Clock>(*cfg, env); }); BenchmarkInfo info { name, plan.estimated_duration.count(), plan.iterations_per_sample, cfg->benchmarkSamples(), cfg->benchmarkResamples(), env.clock_resolution.mean.count(), env.clock_cost.mean.count() }; getResultCapture().benchmarkStarting(info); auto samples = user_code([&] { return plan.template run<Clock>(*cfg, env); }); auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end()); BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance }; getResultCapture().benchmarkEnded(stats); } CATCH_CATCH_ALL{ if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow. std::rethrow_exception(std::current_exception()); } } // sets lambda to be used in fun *and* executes benchmark! template <typename Fun, typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0> Benchmark & operator=(Fun func) { fun = Detail::BenchmarkFunction(func); run(); return *this; } explicit operator bool() { return true; } private: Detail::BenchmarkFunction fun; std::string name; }; } } // namespace Catch #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\ if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ BenchmarkName = [&](int benchmarkIndex) #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\ if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ BenchmarkName = [&] #if defined(CATCH_CONFIG_PREFIX_ALL) #define CATCH_BENCHMARK(...) \ INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,)) #define CATCH_BENCHMARK_ADVANCED(name) \ INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) #else #define BENCHMARK(...) \ INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,)) #define BENCHMARK_ADVANCED(name) \ INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) #endif #endif // CATCH_BENCHMARK_HPP_INCLUDED // Adapted from donated nonius code. #ifndef CATCH_CONSTRUCTOR_HPP_INCLUDED #define CATCH_CONSTRUCTOR_HPP_INCLUDED #include <type_traits> namespace Catch { namespace Benchmark { namespace Detail { template <typename T, bool Destruct> struct ObjectStorage { using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type; ObjectStorage() : data() {} ObjectStorage(const ObjectStorage& other) { new(&data) T(other.stored_object()); } ObjectStorage(ObjectStorage&& other) { new(&data) T(std::move(other.stored_object())); } ~ObjectStorage() { destruct_on_exit<T>(); } template <typename... Args> void construct(Args&&... args) { new (&data) T(std::forward<Args>(args)...); } template <bool AllowManualDestruction = !Destruct> typename std::enable_if<AllowManualDestruction>::type destruct() { stored_object().~T(); } private: // If this is a constructor benchmark, destruct the underlying object template <typename U> void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); } // Otherwise, don't template <typename U> void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { } T& stored_object() { return *static_cast<T*>(static_cast<void*>(&data)); } T const& stored_object() const { return *static_cast<T*>(static_cast<void*>(&data)); } TStorage data; }; } // namespace Detail template <typename T> using storage_for = Detail::ObjectStorage<T, true>; template <typename T> using destructable_object = Detail::ObjectStorage<T, false>; } // namespace Benchmark } // namespace Catch #endif // CATCH_CONSTRUCTOR_HPP_INCLUDED #endif // CATCH_BENCHMARK_ALL_HPP_INCLUDED #ifndef CATCH_APPROX_HPP_INCLUDED #define CATCH_APPROX_HPP_INCLUDED #ifndef CATCH_TOSTRING_HPP_INCLUDED #define CATCH_TOSTRING_HPP_INCLUDED #include <vector> #include <cstddef> #include <type_traits> #include <string> #ifndef CATCH_INTERFACES_ENUM_VALUES_REGISTRY_HPP_INCLUDED #define CATCH_INTERFACES_ENUM_VALUES_REGISTRY_HPP_INCLUDED #include <vector> namespace Catch { namespace Detail { struct EnumInfo { StringRef m_name; std::vector<std::pair<int, StringRef>> m_values; ~EnumInfo(); StringRef lookup( int value ) const; }; } // namespace Detail struct IMutableEnumValuesRegistry { virtual ~IMutableEnumValuesRegistry(); virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0; template<typename E> Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) { static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int"); std::vector<int> intValues; intValues.reserve( values.size() ); for( auto enumValue : values ) intValues.push_back( static_cast<int>( enumValue ) ); return registerEnum( enumName, allEnums, intValues ); } }; } // Catch #endif // CATCH_INTERFACES_ENUM_VALUES_REGISTRY_HPP_INCLUDED #ifdef CATCH_CONFIG_CPP17_STRING_VIEW #include <string_view> #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless #endif namespace Catch { namespace Detail { extern const std::string unprintableString; std::string rawMemoryToString( const void *object, std::size_t size ); template<typename T> std::string rawMemoryToString( const T& object ) { return rawMemoryToString( &object, sizeof(object) ); } template<typename T> class IsStreamInsertable { template<typename Stream, typename U> static auto test(int) -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type()); template<typename, typename> static auto test(...)->std::false_type; public: static const bool value = decltype(test<std::ostream, const T&>(0))::value; }; template<typename E> std::string convertUnknownEnumToString( E e ); template<typename T> std::enable_if_t< !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value, std::string> convertUnstreamable( T const& ) { return Detail::unprintableString; } template<typename T> std::enable_if_t< !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value, std::string> convertUnstreamable(T const& ex) { return ex.what(); } template<typename T> std::enable_if_t< std::is_enum<T>::value, std::string> convertUnstreamable( T const& value ) { return convertUnknownEnumToString( value ); } #if defined(_MANAGED) //! Convert a CLR string to a utf8 std::string template<typename T> std::string clrReferenceToString( T^ ref ) { if (ref == nullptr) return std::string("null"); auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString()); cli::pin_ptr<System::Byte> p = &bytes[0]; return std::string(reinterpret_cast<char const *>(p), bytes->Length); } #endif } // namespace Detail // If we decide for C++14, change these to enable_if_ts template <typename T, typename = void> struct StringMaker { template <typename Fake = T> static std::enable_if_t<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string> convert(const Fake& value) { ReusableStringStream rss; // NB: call using the function-like syntax to avoid ambiguity with // user-defined templated operator<< under clang. rss.operator<<(value); return rss.str(); } template <typename Fake = T> static std::enable_if_t<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string> convert( const Fake& value ) { #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER) return Detail::convertUnstreamable(value); #else return CATCH_CONFIG_FALLBACK_STRINGIFIER(value); #endif } }; namespace Detail { // This function dispatches all stringification requests inside of Catch. // Should be preferably called fully qualified, like ::Catch::Detail::stringify template <typename T> std::string stringify(const T& e) { return ::Catch::StringMaker<std::remove_cv_t<std::remove_reference_t<T>>>::convert(e); } template<typename E> std::string convertUnknownEnumToString( E e ) { return ::Catch::Detail::stringify(static_cast<std::underlying_type_t<E>>(e)); } #if defined(_MANAGED) template <typename T> std::string stringify( T^ e ) { return ::Catch::StringMaker<T^>::convert(e); } #endif } // namespace Detail // Some predefined specializations template<> struct StringMaker<std::string> { static std::string convert(const std::string& str); }; #ifdef CATCH_CONFIG_CPP17_STRING_VIEW template<> struct StringMaker<std::string_view> { static std::string convert(std::string_view str); }; #endif template<> struct StringMaker<char const *> { static std::string convert(char const * str); }; template<> struct StringMaker<char *> { static std::string convert(char * str); }; #ifdef CATCH_CONFIG_WCHAR template<> struct StringMaker<std::wstring> { static std::string convert(const std::wstring& wstr); }; # ifdef CATCH_CONFIG_CPP17_STRING_VIEW template<> struct StringMaker<std::wstring_view> { static std::string convert(std::wstring_view str); }; # endif template<> struct StringMaker<wchar_t const *> { static std::string convert(wchar_t const * str); }; template<> struct StringMaker<wchar_t *> { static std::string convert(wchar_t * str); }; #endif // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer, // while keeping string semantics? template<int SZ> struct StringMaker<char[SZ]> { static std::string convert(char const* str) { return ::Catch::Detail::stringify(std::string{ str }); } }; template<int SZ> struct StringMaker<signed char[SZ]> { static std::string convert(signed char const* str) { return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) }); } }; template<int SZ> struct StringMaker<unsigned char[SZ]> { static std::string convert(unsigned char const* str) { return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) }); } }; #if defined(CATCH_CONFIG_CPP17_BYTE) template<> struct StringMaker<std::byte> { static std::string convert(std::byte value); }; #endif // defined(CATCH_CONFIG_CPP17_BYTE) template<> struct StringMaker<int> { static std::string convert(int value); }; template<> struct StringMaker<long> { static std::string convert(long value); }; template<> struct StringMaker<long long> { static std::string convert(long long value); }; template<> struct StringMaker<unsigned int> { static std::string convert(unsigned int value); }; template<> struct StringMaker<unsigned long> { static std::string convert(unsigned long value); }; template<> struct StringMaker<unsigned long long> { static std::string convert(unsigned long long value); }; template<> struct StringMaker<bool> { static std::string convert(bool b) { using namespace std::string_literals; return b ? "true"s : "false"s; } }; template<> struct StringMaker<char> { static std::string convert(char c); }; template<> struct StringMaker<signed char> { static std::string convert(signed char c); }; template<> struct StringMaker<unsigned char> { static std::string convert(unsigned char c); }; template<> struct StringMaker<std::nullptr_t> { static std::string convert(std::nullptr_t) { using namespace std::string_literals; return "nullptr"s; } }; template<> struct StringMaker<float> { static std::string convert(float value); static int precision; }; template<> struct StringMaker<double> { static std::string convert(double value); static int precision; }; template <typename T> struct StringMaker<T*> { template <typename U> static std::string convert(U* p) { if (p) { return ::Catch::Detail::rawMemoryToString(p); } else { return "nullptr"; } } }; template <typename R, typename C> struct StringMaker<R C::*> { static std::string convert(R C::* p) { if (p) { return ::Catch::Detail::rawMemoryToString(p); } else { return "nullptr"; } } }; #if defined(_MANAGED) template <typename T> struct StringMaker<T^> { static std::string convert( T^ ref ) { return ::Catch::Detail::clrReferenceToString(ref); } }; #endif namespace Detail { template<typename InputIterator, typename Sentinel = InputIterator> std::string rangeToString(InputIterator first, Sentinel last) { ReusableStringStream rss; rss << "{ "; if (first != last) { rss << ::Catch::Detail::stringify(*first); for (++first; first != last; ++first) rss << ", " << ::Catch::Detail::stringify(*first); } rss << " }"; return rss.str(); } } } // namespace Catch ////////////////////////////////////////////////////// // Separate std-lib types stringification, so it can be selectively enabled // This means that we do not bring in their headers #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS) # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER #endif // Separate std::pair specialization #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER) #include <utility> namespace Catch { template<typename T1, typename T2> struct StringMaker<std::pair<T1, T2> > { static std::string convert(const std::pair<T1, T2>& pair) { ReusableStringStream rss; rss << "{ " << ::Catch::Detail::stringify(pair.first) << ", " << ::Catch::Detail::stringify(pair.second) << " }"; return rss.str(); } }; } #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL) #include <optional> namespace Catch { template<typename T> struct StringMaker<std::optional<T> > { static std::string convert(const std::optional<T>& optional) { ReusableStringStream rss; if (optional.has_value()) { rss << ::Catch::Detail::stringify(*optional); } else { rss << "{ }"; } return rss.str(); } }; } #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER // Separate std::tuple specialization #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER) #include <tuple> namespace Catch { namespace Detail { template< typename Tuple, std::size_t N = 0, bool = (N < std::tuple_size<Tuple>::value) > struct TupleElementPrinter { static void print(const Tuple& tuple, std::ostream& os) { os << (N ? ", " : " ") << ::Catch::Detail::stringify(std::get<N>(tuple)); TupleElementPrinter<Tuple, N + 1>::print(tuple, os); } }; template< typename Tuple, std::size_t N > struct TupleElementPrinter<Tuple, N, false> { static void print(const Tuple&, std::ostream&) {} }; } template<typename ...Types> struct StringMaker<std::tuple<Types...>> { static std::string convert(const std::tuple<Types...>& tuple) { ReusableStringStream rss; rss << '{'; Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get()); rss << " }"; return rss.str(); } }; } #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT) #include <variant> namespace Catch { template<> struct StringMaker<std::monostate> { static std::string convert(const std::monostate&) { return "{ }"; } }; template<typename... Elements> struct StringMaker<std::variant<Elements...>> { static std::string convert(const std::variant<Elements...>& variant) { if (variant.valueless_by_exception()) { return "{valueless variant}"; } else { return std::visit( [](const auto& value) { return ::Catch::Detail::stringify(value); }, variant ); } } }; } #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER namespace Catch { // Import begin/ end from std here using std::begin; using std::end; namespace detail { template <typename...> struct void_type { using type = void; }; template <typename T, typename = void> struct is_range_impl : std::false_type { }; template <typename T> struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type> : std::true_type { }; } // namespace detail template <typename T> struct is_range : detail::is_range_impl<T> { }; #if defined(_MANAGED) // Managed types are never ranges template <typename T> struct is_range<T^> { static const bool value = false; }; #endif template<typename Range> std::string rangeToString( Range const& range ) { return ::Catch::Detail::rangeToString( begin( range ), end( range ) ); } // Handle vector<bool> specially template<typename Allocator> std::string rangeToString( std::vector<bool, Allocator> const& v ) { ReusableStringStream rss; rss << "{ "; bool first = true; for( bool b : v ) { if( first ) first = false; else rss << ", "; rss << ::Catch::Detail::stringify( b ); } rss << " }"; return rss.str(); } template<typename R> struct StringMaker<R, std::enable_if_t<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>> { static std::string convert( R const& range ) { return rangeToString( range ); } }; template <typename T, int SZ> struct StringMaker<T[SZ]> { static std::string convert(T const(&arr)[SZ]) { return rangeToString(arr); } }; } // namespace Catch // Separate std::chrono::duration specialization #include <ctime> #include <ratio> #include <chrono> namespace Catch { template <class Ratio> struct ratio_string { static std::string symbol() { Catch::ReusableStringStream rss; rss << '[' << Ratio::num << '/' << Ratio::den << ']'; return rss.str(); } }; template <> struct ratio_string<std::atto> { static std::string symbol() { return "a"; } }; template <> struct ratio_string<std::femto> { static std::string symbol() { return "f"; } }; template <> struct ratio_string<std::pico> { static std::string symbol() { return "p"; } }; template <> struct ratio_string<std::nano> { static std::string symbol() { return "n"; } }; template <> struct ratio_string<std::micro> { static std::string symbol() { return "u"; } }; template <> struct ratio_string<std::milli> { static std::string symbol() { return "m"; } }; //////////// // std::chrono::duration specializations template<typename Value, typename Ratio> struct StringMaker<std::chrono::duration<Value, Ratio>> { static std::string convert(std::chrono::duration<Value, Ratio> const& duration) { ReusableStringStream rss; rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's'; return rss.str(); } }; template<typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> { static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) { ReusableStringStream rss; rss << duration.count() << " s"; return rss.str(); } }; template<typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> { static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) { ReusableStringStream rss; rss << duration.count() << " m"; return rss.str(); } }; template<typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> { static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) { ReusableStringStream rss; rss << duration.count() << " h"; return rss.str(); } }; //////////// // std::chrono::time_point specialization // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock> template<typename Clock, typename Duration> struct StringMaker<std::chrono::time_point<Clock, Duration>> { static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) { return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch"; } }; // std::chrono::time_point<system_clock> specialization template<typename Duration> struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> { static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) { auto converted = std::chrono::system_clock::to_time_t(time_point); #ifdef _MSC_VER std::tm timeInfo = {}; gmtime_s(&timeInfo, &converted); #else std::tm* timeInfo = std::gmtime(&converted); #endif auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); char timeStamp[timeStampSize]; const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; #ifdef _MSC_VER std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); #else std::strftime(timeStamp, timeStampSize, fmt, timeInfo); #endif return std::string(timeStamp); } }; } #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \ namespace Catch { \ template<> struct StringMaker<enumName> { \ static std::string convert( enumName value ) { \ static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \ return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \ } \ }; \ } #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ ) #ifdef _MSC_VER #pragma warning(pop) #endif #endif // CATCH_TOSTRING_HPP_INCLUDED #include <type_traits> namespace Catch { class Approx { private: bool equalityComparisonImpl(double other) const; // Sets and validates the new margin (margin >= 0) void setMargin(double margin); // Sets and validates the new epsilon (0 < epsilon < 1) void setEpsilon(double epsilon); public: explicit Approx ( double value ); static Approx custom(); Approx operator-() const; template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> Approx operator()( T const& value ) { Approx approx( static_cast<double>(value) ); approx.m_epsilon = m_epsilon; approx.m_margin = m_margin; approx.m_scale = m_scale; return approx; } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> explicit Approx( T const& value ): Approx(static_cast<double>(value)) {} template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> friend bool operator == ( const T& lhs, Approx const& rhs ) { auto lhs_v = static_cast<double>(lhs); return rhs.equalityComparisonImpl(lhs_v); } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> friend bool operator == ( Approx const& lhs, const T& rhs ) { return operator==( rhs, lhs ); } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> friend bool operator != ( T const& lhs, Approx const& rhs ) { return !operator==( lhs, rhs ); } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> friend bool operator != ( Approx const& lhs, T const& rhs ) { return !operator==( rhs, lhs ); } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> friend bool operator <= ( T const& lhs, Approx const& rhs ) { return static_cast<double>(lhs) < rhs.m_value || lhs == rhs; } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> friend bool operator <= ( Approx const& lhs, T const& rhs ) { return lhs.m_value < static_cast<double>(rhs) || lhs == rhs; } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> friend bool operator >= ( T const& lhs, Approx const& rhs ) { return static_cast<double>(lhs) > rhs.m_value || lhs == rhs; } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> friend bool operator >= ( Approx const& lhs, T const& rhs ) { return lhs.m_value > static_cast<double>(rhs) || lhs == rhs; } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> Approx& epsilon( T const& newEpsilon ) { double epsilonAsDouble = static_cast<double>(newEpsilon); setEpsilon(epsilonAsDouble); return *this; } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> Approx& margin( T const& newMargin ) { double marginAsDouble = static_cast<double>(newMargin); setMargin(marginAsDouble); return *this; } template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>> Approx& scale( T const& newScale ) { m_scale = static_cast<double>(newScale); return *this; } std::string toString() const; private: double m_epsilon; double m_margin; double m_scale; double m_value; }; namespace literals { Approx operator "" _a(long double val); Approx operator "" _a(unsigned long long val); } // end namespace literals template<> struct StringMaker<Catch::Approx> { static std::string convert(Catch::Approx const& value); }; } // end namespace Catch #endif // CATCH_APPROX_HPP_INCLUDED #ifndef CATCH_CONFIG_HPP_INCLUDED #define CATCH_CONFIG_HPP_INCLUDED #ifndef CATCH_TEST_SPEC_HPP_INCLUDED #define CATCH_TEST_SPEC_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif #ifndef CATCH_WILDCARD_PATTERN_HPP_INCLUDED #define CATCH_WILDCARD_PATTERN_HPP_INCLUDED #ifndef CATCH_CASE_SENSITIVE_HPP_INCLUDED #define CATCH_CASE_SENSITIVE_HPP_INCLUDED namespace Catch { enum class CaseSensitive { Yes, No }; } // namespace Catch #endif // CATCH_CASE_SENSITIVE_HPP_INCLUDED #include <string> namespace Catch { class WildcardPattern { enum WildcardPosition { NoWildcard = 0, WildcardAtStart = 1, WildcardAtEnd = 2, WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd }; public: WildcardPattern( std::string const& pattern, CaseSensitive caseSensitivity ); virtual ~WildcardPattern() = default; virtual bool matches( std::string const& str ) const; private: std::string normaliseString( std::string const& str ) const; CaseSensitive m_caseSensitivity; WildcardPosition m_wildcard = NoWildcard; std::string m_pattern; }; } #endif // CATCH_WILDCARD_PATTERN_HPP_INCLUDED #include <string> #include <vector> namespace Catch { struct IConfig; struct TestCaseInfo; class TestCaseHandle; class TestSpec { class Pattern { public: explicit Pattern( std::string const& name ); virtual ~Pattern(); virtual bool matches( TestCaseInfo const& testCase ) const = 0; std::string const& name() const; private: std::string const m_name; }; class NamePattern : public Pattern { public: explicit NamePattern( std::string const& name, std::string const& filterString ); bool matches( TestCaseInfo const& testCase ) const override; private: WildcardPattern m_wildcardPattern; }; class TagPattern : public Pattern { public: explicit TagPattern( std::string const& tag, std::string const& filterString ); bool matches( TestCaseInfo const& testCase ) const override; private: std::string m_tag; }; struct Filter { std::vector<Detail::unique_ptr<Pattern>> m_required; std::vector<Detail::unique_ptr<Pattern>> m_forbidden; bool matches( TestCaseInfo const& testCase ) const; std::string name() const; }; public: struct FilterMatch { std::string name; std::vector<TestCaseHandle const*> tests; }; using Matches = std::vector<FilterMatch>; using vectorStrings = std::vector<std::string>; bool hasFilters() const; bool matches( TestCaseInfo const& testCase ) const; Matches matchesByFilter( std::vector<TestCaseHandle> const& testCases, IConfig const& config ) const; const vectorStrings & getInvalidArgs() const; private: std::vector<Filter> m_filters; std::vector<std::string> m_invalidArgs; friend class TestSpecParser; }; } #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CATCH_TEST_SPEC_HPP_INCLUDED #include <vector> #include <string> namespace Catch { struct IStream; struct ConfigData { bool listTests = false; bool listTags = false; bool listReporters = false; bool showSuccessfulTests = false; bool shouldDebugBreak = false; bool noThrow = false; bool showHelp = false; bool showInvisibles = false; bool filenamesAsTags = false; bool libIdentify = false; int abortAfter = -1; unsigned int rngSeed = 0; bool benchmarkNoAnalysis = false; unsigned int benchmarkSamples = 100; double benchmarkConfidenceInterval = 0.95; unsigned int benchmarkResamples = 100000; std::chrono::milliseconds::rep benchmarkWarmupTime = 100; Verbosity verbosity = Verbosity::Normal; WarnAbout::What warnings = WarnAbout::Nothing; ShowDurations showDurations = ShowDurations::DefaultForReporter; double minDuration = -1; TestRunOrder runOrder = TestRunOrder::Declared; UseColour useColour = UseColour::Auto; WaitForKeypress::When waitForKeypress = WaitForKeypress::Never; std::string outputFilename; std::string name; std::string processName; #ifndef CATCH_CONFIG_DEFAULT_REPORTER #define CATCH_CONFIG_DEFAULT_REPORTER "console" #endif std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER; #undef CATCH_CONFIG_DEFAULT_REPORTER std::vector<std::string> testsOrTags; std::vector<std::string> sectionsToRun; }; class Config : public IConfig { public: Config() = default; Config( ConfigData const& data ); ~Config() override; // = default in the cpp file std::string const& getFilename() const; bool listTests() const; bool listTags() const; bool listReporters() const; std::string getProcessName() const; std::string const& getReporterName() const; std::vector<std::string> const& getTestsOrTags() const override; std::vector<std::string> const& getSectionsToRun() const override; TestSpec const& testSpec() const override; bool hasTestFilters() const override; bool showHelp() const; // IConfig interface bool allowThrows() const override; std::ostream& stream() const override; std::string name() const override; bool includeSuccessfulResults() const override; bool warnAboutMissingAssertions() const override; bool warnAboutNoTests() const override; ShowDurations showDurations() const override; double minDuration() const override; TestRunOrder runOrder() const override; unsigned int rngSeed() const override; UseColour useColour() const override; bool shouldDebugBreak() const override; int abortAfter() const override; bool showInvisibles() const override; Verbosity verbosity() const override; bool benchmarkNoAnalysis() const override; int benchmarkSamples() const override; double benchmarkConfidenceInterval() const override; unsigned int benchmarkResamples() const override; std::chrono::milliseconds benchmarkWarmupTime() const override; private: IStream const* openStream(); ConfigData m_data; Detail::unique_ptr<IStream const> m_stream; TestSpec m_testSpec; bool m_hasTestFilters = false; }; } // end namespace Catch #endif // CATCH_CONFIG_HPP_INCLUDED #ifndef CATCH_MESSAGE_HPP_INCLUDED #define CATCH_MESSAGE_HPP_INCLUDED #include <string> #include <vector> namespace Catch { struct MessageStream { template<typename T> MessageStream& operator << ( T const& value ) { m_stream << value; return *this; } ReusableStringStream m_stream; }; struct MessageBuilder : MessageStream { MessageBuilder( StringRef const& macroName, SourceLineInfo const& lineInfo, ResultWas::OfType type ); template<typename T> MessageBuilder& operator << ( T const& value ) { m_stream << value; return *this; } MessageInfo m_info; }; class ScopedMessage { public: explicit ScopedMessage( MessageBuilder const& builder ); ScopedMessage( ScopedMessage& duplicate ) = delete; ScopedMessage( ScopedMessage&& old ) noexcept; ~ScopedMessage(); MessageInfo m_info; bool m_moved = false; }; class Capturer { std::vector<MessageInfo> m_messages; IResultCapture& m_resultCapture = getResultCapture(); size_t m_captured = 0; public: Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ); Capturer(Capturer const&) = delete; Capturer& operator=(Capturer const&) = delete; ~Capturer(); void captureValue( size_t index, std::string const& value ); template<typename T> void captureValues( size_t index, T const& value ) { captureValue( index, Catch::Detail::stringify( value ) ); } template<typename T, typename... Ts> void captureValues( size_t index, T const& value, Ts const&... values ) { captureValue( index, Catch::Detail::stringify(value) ); captureValues( index+1, values... ); } }; } // end namespace Catch /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \ catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \ Catch::Capturer varName( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \ varName.captureValues( 0, __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_INFO( macroName, log ) \ Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \ Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ) #if defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE) #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg ) #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE", __VA_ARGS__ ) #elif defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE) #define CATCH_INFO( msg ) (void)(0) #define CATCH_UNSCOPED_INFO( msg ) (void)(0) #define CATCH_WARN( msg ) (void)(0) #define CATCH_CAPTURE( ... ) (void)(0) #elif !defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE) #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg ) #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE", __VA_ARGS__ ) #elif !defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE) #define INFO( msg ) (void)(0) #define UNSCOPED_INFO( msg ) (void)(0) #define WARN( msg ) (void)(0) #define CAPTURE( ... ) (void)(0) #endif // end of user facing macro declarations #endif // CATCH_MESSAGE_HPP_INCLUDED #ifndef CATCH_REPORTER_REGISTRARS_HPP_INCLUDED #define CATCH_REPORTER_REGISTRARS_HPP_INCLUDED #ifndef CATCH_INTERFACES_REPORTER_FACTORY_HPP_INCLUDED #define CATCH_INTERFACES_REPORTER_FACTORY_HPP_INCLUDED namespace Catch { struct ReporterConfig; struct IReporterFactory { virtual ~IReporterFactory(); // = default virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0; virtual std::string getDescription() const = 0; }; using IReporterFactoryPtr = Detail::unique_ptr<IReporterFactory>; } // namespace Catch #endif // CATCH_INTERFACES_REPORTER_FACTORY_HPP_INCLUDED namespace Catch { template <typename T> class ReporterFactory : public IReporterFactory { IStreamingReporterPtr create( ReporterConfig const& config ) const override { return Detail::make_unique<T>( config ); } std::string getDescription() const override { return T::getDescription(); } }; template<typename T> class ReporterRegistrar { public: explicit ReporterRegistrar( std::string const& name ) { getMutableRegistryHub().registerReporter( name, Detail::make_unique<ReporterFactory<T>>() ); } }; template<typename T> class ListenerRegistrar { class ListenerFactory : public IReporterFactory { IStreamingReporterPtr create( ReporterConfig const& config ) const override { return Detail::make_unique<T>(config); } std::string getDescription() const override { return std::string(); } }; public: ListenerRegistrar() { getMutableRegistryHub().registerListener( Detail::make_unique<ListenerFactory>() ); } }; } #if !defined(CATCH_CONFIG_DISABLE) #define CATCH_REGISTER_REPORTER( name, reporterType ) \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION #define CATCH_REGISTER_LISTENER( listenerType ) \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION #else // CATCH_CONFIG_DISABLE #define CATCH_REGISTER_REPORTER(name, reporterType) #define CATCH_REGISTER_LISTENER(listenerType) #endif // CATCH_CONFIG_DISABLE #endif // CATCH_REPORTER_REGISTRARS_HPP_INCLUDED #ifndef CATCH_SESSION_HPP_INCLUDED #define CATCH_SESSION_HPP_INCLUDED #ifndef CATCH_COMMANDLINE_HPP_INCLUDED #define CATCH_COMMANDLINE_HPP_INCLUDED #ifndef CATCH_CLARA_HPP_INCLUDED #define CATCH_CLARA_HPP_INCLUDED #if defined( __clang__ ) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wweak-vtables" # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wdeprecated" #endif #if defined( __GNUC__ ) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wsign-conversion" #endif #ifndef CLARA_CONFIG_OPTIONAL_TYPE # ifdef __has_include # if __has_include( <optional>) && __cplusplus >= 201703L # include <optional> # define CLARA_CONFIG_OPTIONAL_TYPE std::optional # endif # endif #endif #include <cassert> #include <cctype> #include <memory> #include <ostream> #include <sstream> #include <string> #include <vector> namespace Catch { namespace Clara { class Args; class Parser; // enum of result types from a parse enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame }; namespace Detail { // Traits for extracting arg and return type of lambdas (for single // argument lambdas) template <typename L> struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {}; template <typename ClassT, typename ReturnT, typename... Args> struct UnaryLambdaTraits<ReturnT ( ClassT::* )( Args... ) const> { static const bool isValid = false; }; template <typename ClassT, typename ReturnT, typename ArgT> struct UnaryLambdaTraits<ReturnT ( ClassT::* )( ArgT ) const> { static const bool isValid = true; using ArgType = typename std::remove_const< typename std::remove_reference<ArgT>::type>::type; using ReturnType = ReturnT; }; class TokenStream; // Wraps a token coming from a token stream. These may not directly // correspond to strings as a single string may encode an option + // its argument if the : or = form is used enum class TokenType { Option, Argument }; struct Token { TokenType type; std::string token; }; // Abstracts iterators into args as a stream of tokens, with option // arguments uniformly handled class TokenStream { using Iterator = std::vector<std::string>::const_iterator; Iterator it; Iterator itEnd; std::vector<Token> m_tokenBuffer; void loadBuffer(); public: explicit TokenStream( Args const& args ); TokenStream( Iterator it, Iterator itEnd ); explicit operator bool() const { return !m_tokenBuffer.empty() || it != itEnd; } size_t count() const { return m_tokenBuffer.size() + ( itEnd - it ); } Token operator*() const { assert( !m_tokenBuffer.empty() ); return m_tokenBuffer.front(); } Token const* operator->() const { assert( !m_tokenBuffer.empty() ); return &m_tokenBuffer.front(); } TokenStream& operator++(); }; //! Denotes type of a parsing result enum class ResultType { Ok, ///< No errors LogicError, ///< Error in user-specified arguments for ///< construction RuntimeError ///< Error in parsing inputs }; class ResultBase { protected: ResultBase( ResultType type ): m_type( type ) {} virtual ~ResultBase(); // = default; ResultBase(ResultBase const&) = default; ResultBase& operator=(ResultBase const&) = default; ResultBase(ResultBase&&) = default; ResultBase& operator=(ResultBase&&) = default; virtual void enforceOk() const = 0; ResultType m_type; }; template <typename T> class ResultValueBase : public ResultBase { public: auto value() const -> T const& { enforceOk(); return m_value; } protected: ResultValueBase( ResultType type ): ResultBase( type ) {} ResultValueBase( ResultValueBase const& other ): ResultBase( other ) { if ( m_type == ResultType::Ok ) new ( &m_value ) T( other.m_value ); } ResultValueBase( ResultType, T const& value ): ResultBase( ResultType::Ok ) { new ( &m_value ) T( value ); } auto operator=( ResultValueBase const& other ) -> ResultValueBase& { if ( m_type == ResultType::Ok ) m_value.~T(); ResultBase::operator=( other ); if ( m_type == ResultType::Ok ) new ( &m_value ) T( other.m_value ); return *this; } ~ResultValueBase() override { if ( m_type == ResultType::Ok ) m_value.~T(); } union { T m_value; }; }; template <> class ResultValueBase<void> : public ResultBase { protected: using ResultBase::ResultBase; }; template <typename T = void> class BasicResult : public ResultValueBase<T> { public: template <typename U> explicit BasicResult( BasicResult<U> const& other ): ResultValueBase<T>( other.type() ), m_errorMessage( other.errorMessage() ) { assert( type() != ResultType::Ok ); } template <typename U> static auto ok( U const& value ) -> BasicResult { return { ResultType::Ok, value }; } static auto ok() -> BasicResult { return { ResultType::Ok }; } static auto logicError( std::string const& message ) -> BasicResult { return { ResultType::LogicError, message }; } static auto runtimeError( std::string const& message ) -> BasicResult { return { ResultType::RuntimeError, message }; } explicit operator bool() const { return m_type == ResultType::Ok; } auto type() const -> ResultType { return m_type; } auto errorMessage() const -> std::string { return m_errorMessage; } protected: void enforceOk() const override { // Errors shouldn't reach this point, but if they do // the actual error message will be in m_errorMessage assert( m_type != ResultType::LogicError ); assert( m_type != ResultType::RuntimeError ); if ( m_type != ResultType::Ok ) std::abort(); } std::string m_errorMessage; // Only populated if resultType is an error BasicResult( ResultType type, std::string const& message ): ResultValueBase<T>( type ), m_errorMessage( message ) { assert( m_type != ResultType::Ok ); } using ResultValueBase<T>::ResultValueBase; using ResultBase::m_type; }; class ParseState { public: ParseState( ParseResultType type, TokenStream const& remainingTokens ); ParseResultType type() const { return m_type; } TokenStream const& remainingTokens() const { return m_remainingTokens; } private: ParseResultType m_type; TokenStream m_remainingTokens; }; using Result = BasicResult<void>; using ParserResult = BasicResult<ParseResultType>; using InternalParseResult = BasicResult<ParseState>; struct HelpColumns { std::string left; std::string right; }; template <typename T> ParserResult convertInto( std::string const& source, T& target ) { std::stringstream ss( source ); ss >> target; if ( ss.fail() ) { return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" ); } else { return ParserResult::ok( ParseResultType::Matched ); } } ParserResult convertInto( std::string const& source, std::string& target ); ParserResult convertInto( std::string const& source, bool& target ); #ifdef CLARA_CONFIG_OPTIONAL_TYPE template <typename T> auto convertInto( std::string const& source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult { T temp; auto result = convertInto( source, temp ); if ( result ) target = std::move( temp ); return result; } #endif // CLARA_CONFIG_OPTIONAL_TYPE struct BoundRef : Catch::Detail::NonCopyable { virtual ~BoundRef() = default; virtual bool isContainer() const; virtual bool isFlag() const; }; struct BoundValueRefBase : BoundRef { virtual auto setValue( std::string const& arg ) -> ParserResult = 0; }; struct BoundFlagRefBase : BoundRef { virtual auto setFlag( bool flag ) -> ParserResult = 0; bool isFlag() const override; }; template <typename T> struct BoundValueRef : BoundValueRefBase { T& m_ref; explicit BoundValueRef( T& ref ): m_ref( ref ) {} ParserResult setValue( std::string const& arg ) override { return convertInto( arg, m_ref ); } }; template <typename T> struct BoundValueRef<std::vector<T>> : BoundValueRefBase { std::vector<T>& m_ref; explicit BoundValueRef( std::vector<T>& ref ): m_ref( ref ) {} auto isContainer() const -> bool override { return true; } auto setValue( std::string const& arg ) -> ParserResult override { T temp; auto result = convertInto( arg, temp ); if ( result ) m_ref.push_back( temp ); return result; } }; struct BoundFlagRef : BoundFlagRefBase { bool& m_ref; explicit BoundFlagRef( bool& ref ): m_ref( ref ) {} ParserResult setFlag( bool flag ) override; }; template <typename ReturnType> struct LambdaInvoker { static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" ); template <typename L, typename ArgType> static auto invoke( L const& lambda, ArgType const& arg ) -> ParserResult { return lambda( arg ); } }; template <> struct LambdaInvoker<void> { template <typename L, typename ArgType> static auto invoke( L const& lambda, ArgType const& arg ) -> ParserResult { lambda( arg ); return ParserResult::ok( ParseResultType::Matched ); } }; template <typename ArgType, typename L> auto invokeLambda( L const& lambda, std::string const& arg ) -> ParserResult { ArgType temp{}; auto result = convertInto( arg, temp ); return !result ? result : LambdaInvoker<typename UnaryLambdaTraits< L>::ReturnType>::invoke( lambda, temp ); } template <typename L> struct BoundLambda : BoundValueRefBase { L m_lambda; static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" ); explicit BoundLambda( L const& lambda ): m_lambda( lambda ) {} auto setValue( std::string const& arg ) -> ParserResult override { return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg ); } }; template <typename L> struct BoundFlagLambda : BoundFlagRefBase { L m_lambda; static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" ); static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" ); explicit BoundFlagLambda( L const& lambda ): m_lambda( lambda ) {} auto setFlag( bool flag ) -> ParserResult override { return LambdaInvoker<typename UnaryLambdaTraits< L>::ReturnType>::invoke( m_lambda, flag ); } }; enum class Optionality { Optional, Required }; class ParserBase { public: virtual ~ParserBase() = default; virtual auto validate() const -> Result { return Result::ok(); } virtual auto parse( std::string const& exeName, TokenStream const& tokens ) const -> InternalParseResult = 0; virtual size_t cardinality() const; InternalParseResult parse( Args const& args ) const; }; template <typename DerivedT> class ComposableParserImpl : public ParserBase { public: template <typename T> auto operator|( T const& other ) const -> Parser; }; // Common code and state for Args and Opts template <typename DerivedT> class ParserRefImpl : public ComposableParserImpl<DerivedT> { protected: Optionality m_optionality = Optionality::Optional; std::shared_ptr<BoundRef> m_ref; std::string m_hint; std::string m_description; explicit ParserRefImpl( std::shared_ptr<BoundRef> const& ref ): m_ref( ref ) {} public: template <typename T> ParserRefImpl( T& ref, std::string const& hint ): m_ref( std::make_shared<BoundValueRef<T>>( ref ) ), m_hint( hint ) {} template <typename LambdaT> ParserRefImpl( LambdaT const& ref, std::string const& hint ): m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ), m_hint( hint ) {} auto operator()( std::string const& description ) -> DerivedT& { m_description = description; return static_cast<DerivedT&>( *this ); } auto optional() -> DerivedT& { m_optionality = Optionality::Optional; return static_cast<DerivedT&>( *this ); } auto required() -> DerivedT& { m_optionality = Optionality::Required; return static_cast<DerivedT&>( *this ); } auto isOptional() const -> bool { return m_optionality == Optionality::Optional; } auto cardinality() const -> size_t override { if ( m_ref->isContainer() ) return 0; else return 1; } std::string const& hint() const { return m_hint; } }; } // namespace detail // A parser for arguments class Arg : public Detail::ParserRefImpl<Arg> { public: using ParserRefImpl::ParserRefImpl; Detail::InternalParseResult parse(std::string const&, Detail::TokenStream const& tokens) const override; }; // A parser for options class Opt : public Detail::ParserRefImpl<Opt> { protected: std::vector<std::string> m_optNames; public: template <typename LambdaT> explicit Opt(LambdaT const& ref) : ParserRefImpl( std::make_shared<Detail::BoundFlagLambda<LambdaT>>(ref)) {} explicit Opt(bool& ref); template <typename LambdaT> Opt(LambdaT const& ref, std::string const& hint) : ParserRefImpl(ref, hint) {} template <typename T> Opt(T& ref, std::string const& hint) : ParserRefImpl(ref, hint) {} auto operator[](std::string const& optName) -> Opt& { m_optNames.push_back(optName); return *this; } std::vector<Detail::HelpColumns> getHelpColumns() const; bool isMatch(std::string const& optToken) const; using ParserBase::parse; Detail::InternalParseResult parse(std::string const&, Detail::TokenStream const& tokens) const override; Detail::Result validate() const override; }; // Specifies the name of the executable class ExeName : public Detail::ComposableParserImpl<ExeName> { std::shared_ptr<std::string> m_name; std::shared_ptr<Detail::BoundValueRefBase> m_ref; template <typename LambdaT> static auto makeRef(LambdaT const& lambda) -> std::shared_ptr<Detail::BoundValueRefBase> { return std::make_shared<Detail::BoundLambda<LambdaT>>(lambda); } public: ExeName(); explicit ExeName(std::string& ref); template <typename LambdaT> explicit ExeName(LambdaT const& lambda) : ExeName() { m_ref = std::make_shared<Detail::BoundLambda<LambdaT>>(lambda); } // The exe name is not parsed out of the normal tokens, but is // handled specially Detail::InternalParseResult parse(std::string const&, Detail::TokenStream const& tokens) const override; std::string const& name() const { return *m_name; } Detail::ParserResult set(std::string const& newName); }; // A Combined parser class Parser : Detail::ParserBase { mutable ExeName m_exeName; std::vector<Opt> m_options; std::vector<Arg> m_args; public: auto operator|=(ExeName const& exeName) -> Parser& { m_exeName = exeName; return *this; } auto operator|=(Arg const& arg) -> Parser& { m_args.push_back(arg); return *this; } auto operator|=(Opt const& opt) -> Parser& { m_options.push_back(opt); return *this; } Parser& operator|=(Parser const& other); template <typename T> auto operator|(T const& other) const -> Parser { return Parser(*this) |= other; } std::vector<Detail::HelpColumns> getHelpColumns() const; void writeToStream(std::ostream& os) const; friend auto operator<<(std::ostream& os, Parser const& parser) -> std::ostream& { parser.writeToStream(os); return os; } Detail::Result validate() const override; using ParserBase::parse; Detail::InternalParseResult parse(std::string const& exeName, Detail::TokenStream const& tokens) const override; }; // Transport for raw args (copied from main args, or supplied via // init list for testing) class Args { friend Detail::TokenStream; std::string m_exeName; std::vector<std::string> m_args; public: Args(int argc, char const* const* argv); Args(std::initializer_list<std::string> args); std::string const& exeName() const { return m_exeName; } }; // Convenience wrapper for option parser that specifies the help option struct Help : Opt { Help(bool& showHelpFlag); }; // Result type for parser operation using Detail::ParserResult; namespace Detail { template <typename DerivedT> template <typename T> Parser ComposableParserImpl<DerivedT>::operator|(T const& other) const { return Parser() | static_cast<DerivedT const&>(*this) | other; } } } // namespace Clara } // namespace Catch #if defined( __clang__ ) # pragma clang diagnostic pop #endif #if defined( __GNUC__ ) # pragma GCC diagnostic pop #endif #endif // CATCH_CLARA_HPP_INCLUDED namespace Catch { struct ConfigData; Clara::Parser makeCommandLineParser( ConfigData& config ); } // end namespace Catch #endif // CATCH_COMMANDLINE_HPP_INCLUDED namespace Catch { class Session : Detail::NonCopyable { public: Session(); ~Session(); void showHelp() const; void libIdentify(); int applyCommandLine( int argc, char const * const * argv ); #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) int applyCommandLine( int argc, wchar_t const * const * argv ); #endif void useConfigData( ConfigData const& configData ); template<typename CharT> int run(int argc, CharT const * const argv[]) { if (m_startupExceptions) return 1; int returnCode = applyCommandLine(argc, argv); if (returnCode == 0) returnCode = run(); return returnCode; } int run(); Clara::Parser const& cli() const; void cli( Clara::Parser const& newParser ); ConfigData& configData(); Config& config(); private: int runInternal(); Clara::Parser m_cli; ConfigData m_configData; Detail::unique_ptr<Config> m_config; bool m_startupExceptions = false; }; } // end namespace Catch #endif // CATCH_SESSION_HPP_INCLUDED #ifndef CATCH_TAG_ALIAS_HPP_INCLUDED #define CATCH_TAG_ALIAS_HPP_INCLUDED #include <string> namespace Catch { struct TagAlias { TagAlias(std::string const& _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {} std::string tag; SourceLineInfo lineInfo; }; } // end namespace Catch #endif // CATCH_TAG_ALIAS_HPP_INCLUDED #ifndef CATCH_TAG_ALIAS_AUTOREGISTRAR_HPP_INCLUDED #define CATCH_TAG_ALIAS_AUTOREGISTRAR_HPP_INCLUDED namespace Catch { struct RegistrarForTagAliases { RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); }; } // end namespace Catch #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION #endif // CATCH_TAG_ALIAS_AUTOREGISTRAR_HPP_INCLUDED #ifndef CATCH_TEMPLATE_TEST_MACROS_HPP_INCLUDED #define CATCH_TEMPLATE_TEST_MACROS_HPP_INCLUDED // We need this suppression to leak, because it took until GCC 10 // for the front end to handle local suppression via _Pragma properly // inside templates (so `TEMPLATE_TEST_CASE` and co). // **THIS IS DIFFERENT FOR STANDARD TESTS, WHERE GCC 9 IS SUFFICIENT** #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && __GNUC__ < 10 #pragma GCC diagnostic ignored "-Wparentheses" #endif #ifndef CATCH_TEST_MACROS_HPP_INCLUDED #define CATCH_TEST_MACROS_HPP_INCLUDED #ifndef CATCH_TEST_MACRO_IMPL_HPP_INCLUDED #define CATCH_TEST_MACRO_IMPL_HPP_INCLUDED #ifndef CATCH_ASSERTION_HANDLER_HPP_INCLUDED #define CATCH_ASSERTION_HANDLER_HPP_INCLUDED #ifndef CATCH_DECOMPOSER_HPP_INCLUDED #define CATCH_DECOMPOSER_HPP_INCLUDED #include <iosfwd> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4389) // '==' : signed/unsigned mismatch #pragma warning(disable:4018) // more "signed/unsigned mismatch" #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) #pragma warning(disable:4180) // qualifier applied to function type has no meaning #pragma warning(disable:4800) // Forcing result to true or false #endif #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wsign-compare" #elif defined __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wsign-compare" #endif namespace Catch { struct ITransientExpression { auto isBinaryExpression() const -> bool { return m_isBinaryExpression; } auto getResult() const -> bool { return m_result; } virtual void streamReconstructedExpression( std::ostream &os ) const = 0; ITransientExpression( bool isBinaryExpression, bool result ) : m_isBinaryExpression( isBinaryExpression ), m_result( result ) {} ITransientExpression() = default; ITransientExpression(ITransientExpression const&) = default; ITransientExpression& operator=(ITransientExpression const&) = default; // We don't actually need a virtual destructor, but many static analysers // complain if it's not here :-( virtual ~ITransientExpression(); // = default; bool m_isBinaryExpression; bool m_result; friend std::ostream& operator<<(std::ostream& out, ITransientExpression const& expr) { expr.streamReconstructedExpression(out); return out; } }; void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ); template<typename LhsT, typename RhsT> class BinaryExpr : public ITransientExpression { LhsT m_lhs; StringRef m_op; RhsT m_rhs; void streamReconstructedExpression( std::ostream &os ) const override { formatReconstructedExpression ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) ); } public: BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs ) : ITransientExpression{ true, comparisonResult }, m_lhs( lhs ), m_op( op ), m_rhs( rhs ) {} template<typename T> auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename T> auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<T>::value, "chained comparisons are not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } }; template<typename LhsT> class UnaryExpr : public ITransientExpression { LhsT m_lhs; void streamReconstructedExpression( std::ostream &os ) const override { os << Catch::Detail::stringify( m_lhs ); } public: explicit UnaryExpr( LhsT lhs ) : ITransientExpression{ false, static_cast<bool>(lhs) }, m_lhs( lhs ) {} }; // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int) template<typename LhsT, typename RhsT> auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); } template<typename T> auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); } template<typename T> auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); } template<typename T> auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; } template<typename T> auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; } template<typename LhsT, typename RhsT> auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); } template<typename T> auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); } template<typename T> auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); } template<typename T> auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; } template<typename T> auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; } template<typename LhsT> class ExprLhs { LhsT m_lhs; public: explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {} template<typename RhsT> auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { compareEqual( m_lhs, rhs ), m_lhs, "=="_sr, rhs }; } auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const { return { m_lhs == rhs, m_lhs, "=="_sr, rhs }; } template<typename RhsT> auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { compareNotEqual( m_lhs, rhs ), m_lhs, "!="_sr, rhs }; } auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const { return { m_lhs != rhs, m_lhs, "!="_sr, rhs }; } template<typename RhsT> auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs > rhs), m_lhs, ">"_sr, rhs }; } template<typename RhsT> auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs < rhs), m_lhs, "<"_sr, rhs }; } template<typename RhsT> auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">="_sr, rhs }; } template<typename RhsT> auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<="_sr, rhs }; } template <typename RhsT> auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs | rhs), m_lhs, "|"_sr, rhs }; } template <typename RhsT> auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs & rhs), m_lhs, "&"_sr, rhs }; } template <typename RhsT> auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^"_sr, rhs }; } template<typename RhsT> auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<RhsT>::value, "operator&& is not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } template<typename RhsT> auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const { static_assert(always_false<RhsT>::value, "operator|| is not supported inside assertions, " "wrap the expression inside parentheses, or decompose it"); } auto makeUnaryExpr() const -> UnaryExpr<LhsT> { return UnaryExpr<LhsT>{ m_lhs }; } }; void handleExpression( ITransientExpression const& expr ); template<typename T> void handleExpression( ExprLhs<T> const& expr ) { handleExpression( expr.makeUnaryExpr() ); } struct Decomposer { template<typename T> auto operator <= ( T const& lhs ) -> ExprLhs<T const&> { return ExprLhs<T const&>{ lhs }; } auto operator <=( bool value ) -> ExprLhs<bool> { return ExprLhs<bool>{ value }; } }; } // end namespace Catch #ifdef _MSC_VER #pragma warning(pop) #endif #ifdef __clang__ # pragma clang diagnostic pop #elif defined __GNUC__ # pragma GCC diagnostic pop #endif #endif // CATCH_DECOMPOSER_HPP_INCLUDED namespace Catch { struct TestFailureException{}; struct AssertionResultData; struct IResultCapture; class RunContext; struct AssertionReaction { bool shouldDebugBreak = false; bool shouldThrow = false; }; class AssertionHandler { AssertionInfo m_assertionInfo; AssertionReaction m_reaction; bool m_completed = false; IResultCapture& m_resultCapture; public: AssertionHandler ( StringRef const& macroName, SourceLineInfo const& lineInfo, StringRef capturedExpression, ResultDisposition::Flags resultDisposition ); ~AssertionHandler() { if ( !m_completed ) { m_resultCapture.handleIncomplete( m_assertionInfo ); } } template<typename T> void handleExpr( ExprLhs<T> const& expr ) { handleExpr( expr.makeUnaryExpr() ); } void handleExpr( ITransientExpression const& expr ); void handleMessage(ResultWas::OfType resultType, StringRef const& message); void handleExceptionThrownAsExpected(); void handleUnexpectedExceptionNotThrown(); void handleExceptionNotThrownAsExpected(); void handleThrowingCallSkipped(); void handleUnexpectedInflightException(); void complete(); void setCompleted(); // query auto allowThrows() const -> bool; }; void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ); } // namespace Catch #endif // CATCH_ASSERTION_HANDLER_HPP_INCLUDED // We need this suppression to leak, because it took until GCC 9 // for the front end to handle local suppression via _Pragma properly #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && __GNUC__ < 9 #pragma GCC diagnostic ignored "-Wparentheses" #endif #if !defined(CATCH_CONFIG_DISABLE) #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION) #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__ #else #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" #endif #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) /////////////////////////////////////////////////////////////////////////////// // Another way to speed-up compilation is to omit local try-catch for REQUIRE* // macros. #define INTERNAL_CATCH_TRY #define INTERNAL_CATCH_CATCH( capturer ) #else // CATCH_CONFIG_FAST_COMPILE #define INTERNAL_CATCH_TRY try #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); } #endif #define INTERNAL_CATCH_REACT( handler ) handler.complete(); /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \ do { \ /* The expression should not be evaluated, but warnings should hopefully be checked */ \ CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ INTERNAL_CATCH_TRY { \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \ INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ if( Catch::getResultCapture().lastAssertionPassed() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \ INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ if( !Catch::getResultCapture().lastAssertionPassed() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ try { \ static_cast<void>(__VA_ARGS__); \ catchAssertionHandler.handleExceptionNotThrownAsExpected(); \ } \ catch( ... ) { \ catchAssertionHandler.handleUnexpectedInflightException(); \ } \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \ if( catchAssertionHandler.allowThrows() ) \ try { \ static_cast<void>(__VA_ARGS__); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch( ... ) { \ catchAssertionHandler.handleExceptionThrownAsExpected(); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \ if( catchAssertionHandler.allowThrows() ) \ try { \ static_cast<void>(expr); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch( exceptionType const& ) { \ catchAssertionHandler.handleExceptionThrownAsExpected(); \ } \ catch( ... ) { \ catchAssertionHandler.handleUnexpectedInflightException(); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) /////////////////////////////////////////////////////////////////////////////// // Although this is matcher-based, it can be used with just a string #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ if( catchAssertionHandler.allowThrows() ) \ try { \ static_cast<void>(__VA_ARGS__); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch( ... ) { \ Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) #endif // CATCH_CONFIG_DISABLE #endif // CATCH_TEST_MACRO_IMPL_HPP_INCLUDED #ifndef CATCH_PREPROCESSOR_HPP_INCLUDED #define CATCH_PREPROCESSOR_HPP_INCLUDED #if defined(__GNUC__) // We need to silence "empty __VA_ARGS__ warning", and using just _Pragma does not work #pragma GCC system_header #endif #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ // MSVC needs more evaluations #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) #else #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) #endif #define CATCH_REC_END(...) #define CATCH_REC_OUT #define CATCH_EMPTY() #define CATCH_DEFER(id) id CATCH_EMPTY() #define CATCH_REC_GET_END2() 0, CATCH_REC_END #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results, // and passes userdata as the first parameter to each invocation, // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c) #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) #else // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) #endif #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()) #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) #else #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())) #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) #endif #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N #define INTERNAL_CATCH_TYPE_GEN\ template<typename...> struct TypeList {};\ template<typename...Ts>\ constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\ template<template<typename...> class...> struct TemplateTypeList{};\ template<template<typename...> class...Cs>\ constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\ template<typename...>\ struct append;\ template<typename...>\ struct rewrap;\ template<template<typename...> class, typename...>\ struct create;\ template<template<typename...> class, typename>\ struct convert;\ \ template<typename T> \ struct append<T> { using type = T; };\ template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\ struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\ template< template<typename...> class L1, typename...E1, typename...Rest>\ struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\ \ template< template<typename...> class Container, template<typename...> class List, typename...elems>\ struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\ template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\ struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\ \ template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\ struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\ template<template <typename...> class Final, template <typename...> class List, typename...Ts>\ struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; }; #define INTERNAL_CATCH_NTTP_1(signature, ...)\ template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\ template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \ template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\ template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\ constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \ \ template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\ struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\ template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\ struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\ template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\ struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; }; #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName) #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\ template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ static void TestName() #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\ template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ static void TestName() #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName) #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\ template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ static void TestName() #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\ template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ static void TestName() #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\ template<typename Type>\ void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\ {\ Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ } #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\ template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\ {\ Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ } #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\ template<typename Type>\ void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ {\ Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ } #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\ template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ {\ Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ } #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName) #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\ template<typename TestType> \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \ void test();\ } #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\ template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \ void test();\ } #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName) #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\ template<typename TestType> \ void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test() #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\ template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_NTTP_0 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0) #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__) #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__) #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__) #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__) #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__) #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__) #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__) #else #define INTERNAL_CATCH_NTTP_0(signature) #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__)) #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)) #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)) #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)) #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)) #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)) #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)) #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)) #endif #endif // CATCH_PREPROCESSOR_HPP_INCLUDED #ifndef CATCH_SECTION_HPP_INCLUDED #define CATCH_SECTION_HPP_INCLUDED #ifndef CATCH_TIMER_HPP_INCLUDED #define CATCH_TIMER_HPP_INCLUDED #include <cstdint> namespace Catch { auto getCurrentNanosecondsSinceEpoch() -> uint64_t; auto getEstimatedClockResolution() -> uint64_t; class Timer { uint64_t m_nanoseconds = 0; public: void start(); auto getElapsedNanoseconds() const -> uint64_t; auto getElapsedMicroseconds() const -> uint64_t; auto getElapsedMilliseconds() const -> unsigned int; auto getElapsedSeconds() const -> double; }; } // namespace Catch #endif // CATCH_TIMER_HPP_INCLUDED #include <string> namespace Catch { class Section : Detail::NonCopyable { public: Section( SectionInfo&& info ); ~Section(); // This indicates whether the section should be executed or not explicit operator bool() const; private: SectionInfo m_info; Counts m_assertions; bool m_sectionIncluded; Timer m_timer; }; } // end namespace Catch #define INTERNAL_CATCH_SECTION( ... ) \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION #endif // CATCH_SECTION_HPP_INCLUDED #ifndef CATCH_TEST_REGISTRY_HPP_INCLUDED #define CATCH_TEST_REGISTRY_HPP_INCLUDED #ifndef CATCH_INTERFACES_TESTCASE_HPP_INCLUDED #define CATCH_INTERFACES_TESTCASE_HPP_INCLUDED #include <vector> namespace Catch { class TestSpec; struct TestCaseInfo; struct ITestInvoker { virtual void invoke () const = 0; virtual ~ITestInvoker(); }; class TestCaseHandle; struct IConfig; struct ITestCaseRegistry { virtual ~ITestCaseRegistry(); // TODO: this exists only for adding filenames to test cases -- let's expose this in a saner way later virtual std::vector<TestCaseInfo* > const& getAllInfos() const = 0; virtual std::vector<TestCaseHandle> const& getAllTests() const = 0; virtual std::vector<TestCaseHandle> const& getAllTestsSorted( IConfig const& config ) const = 0; }; bool isThrowSafe( TestCaseHandle const& testCase, IConfig const& config ); bool matchTest( TestCaseHandle const& testCase, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCaseHandle> filterTests( std::vector<TestCaseHandle> const& testCases, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCaseHandle> const& getAllTestCasesSorted( IConfig const& config ); } #endif // CATCH_INTERFACES_TESTCASE_HPP_INCLUDED // GCC 5 and older do not properly handle disabling unused-variable warning // with a _Pragma. This means that we have to leak the suppression to the // user code as well :-( #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ <= 5 #pragma GCC diagnostic ignored "-Wunused-variable" #endif namespace Catch { template<typename C> class TestInvokerAsMethod : public ITestInvoker { void (C::*m_testAsMethod)(); public: TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {} void invoke() const override { C obj; (obj.*m_testAsMethod)(); } }; Detail::unique_ptr<ITestInvoker> makeTestInvoker( void(*testAsFunction)() ); template<typename C> Detail::unique_ptr<ITestInvoker> makeTestInvoker( void (C::*testAsMethod)() ) { return Detail::unique_ptr<ITestInvoker>( new TestInvokerAsMethod<C>(testAsMethod) ); } struct NameAndTags { NameAndTags(StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef()) noexcept: name(name_), tags(tags_) {} StringRef name; StringRef tags; }; struct AutoReg : Detail::NonCopyable { AutoReg( Detail::unique_ptr<ITestInvoker> invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept; }; } // end namespace Catch #if defined(CATCH_CONFIG_DISABLE) #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \ static inline void TestName() #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ namespace{ \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ void test(); \ }; \ } \ void TestName::test() #endif /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ static void TestName(); \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ static void TestName() #define INTERNAL_CATCH_TESTCASE( ... ) \ INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ void test(); \ }; \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \ } \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ void TestName::test() #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ do { \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ } while(false) #endif // CATCH_TEST_REGISTRY_HPP_INCLUDED // All of our user-facing macros support configuration toggle, that // forces them to be defined prefixed with CATCH_. We also like to // support another toggle that can minimize (disable) their implementation. // Given this, we have 4 different configuration options below #if defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE) #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ ) #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ ) #else #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ ) #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ ) #endif // "BDD-style" convenience wrappers #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) #elif defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE) // ^^ prefixed, implemented | vv prefixed, disabled #define CATCH_REQUIRE( ... ) (void)(0) #define CATCH_REQUIRE_FALSE( ... ) (void)(0) #define CATCH_REQUIRE_THROWS( ... ) (void)(0) #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0) #define CATCH_CHECK( ... ) (void)(0) #define CATCH_CHECK_FALSE( ... ) (void)(0) #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__) #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) #define CATCH_CHECK_NOFAIL( ... ) (void)(0) #define CATCH_CHECK_THROWS( ... ) (void)(0) #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0) #define CATCH_CHECK_NOTHROW( ... ) (void)(0) #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0) #define CATCH_SECTION( ... ) #define CATCH_DYNAMIC_SECTION( ... ) #define CATCH_FAIL( ... ) (void)(0) #define CATCH_FAIL_CHECK( ... ) (void)(0) #define CATCH_SUCCEED( ... ) (void)(0) #define CATCH_STATIC_REQUIRE( ... ) (void)(0) #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0) // "BDD-style" convenience wrappers #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) #define CATCH_GIVEN( desc ) #define CATCH_AND_GIVEN( desc ) #define CATCH_WHEN( desc ) #define CATCH_AND_WHEN( desc ) #define CATCH_THEN( desc ) #define CATCH_AND_THEN( desc ) #elif !defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE) // ^^ prefixed, disabled | vv unprefixed, implemented #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ ) #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" ) #else #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ ) #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ ) #endif // "BDD-style" convenience wrappers #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) #elif !defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE) // ^^ unprefixed, implemented | vv unprefixed, disabled #define REQUIRE( ... ) (void)(0) #define REQUIRE_FALSE( ... ) (void)(0) #define REQUIRE_THROWS( ... ) (void)(0) #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) #define REQUIRE_NOTHROW( ... ) (void)(0) #define CHECK( ... ) (void)(0) #define CHECK_FALSE( ... ) (void)(0) #define CHECKED_IF( ... ) if (__VA_ARGS__) #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) #define CHECK_NOFAIL( ... ) (void)(0) #define CHECK_THROWS( ... ) (void)(0) #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0) #define CHECK_NOTHROW( ... ) (void)(0) #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__) #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) #define METHOD_AS_TEST_CASE( method, ... ) #define REGISTER_TEST_CASE( Function, ... ) (void)(0) #define SECTION( ... ) #define DYNAMIC_SECTION( ... ) #define FAIL( ... ) (void)(0) #define FAIL_CHECK( ... ) (void)(0) #define SUCCEED( ... ) (void)(0) #define STATIC_REQUIRE( ... ) (void)(0) #define STATIC_REQUIRE_FALSE( ... ) (void)(0) // "BDD-style" convenience wrappers #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) #define GIVEN( desc ) #define AND_GIVEN( desc ) #define WHEN( desc ) #define AND_WHEN( desc ) #define THEN( desc ) #define AND_THEN( desc ) #endif // ^^ unprefixed, disabled // end of user facing macros #endif // CATCH_TEST_MACROS_HPP_INCLUDED #ifndef CATCH_TEMPLATE_TEST_REGISTRY_HPP_INCLUDED #define CATCH_TEMPLATE_TEST_REGISTRY_HPP_INCLUDED // GCC 5 and older do not properly handle disabling unused-variable warning // with a _Pragma. This means that we have to leak the suppression to the // user code as well :-( #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ <= 5 #pragma GCC diagnostic ignored "-Wunused-variable" #endif #if defined(CATCH_CONFIG_DISABLE) #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \ INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ namespace{ \ namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ } \ } \ INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) #endif #endif /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ namespace {\ namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ INTERNAL_CATCH_TYPE_GEN\ INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\ template<typename...Types> \ struct TestName{\ TestName(){\ int index = 0; \ constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ using expander = int[];\ (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \ }\ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ return 0;\ }();\ }\ }\ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature)) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ template<typename TestType> static void TestFuncName(); \ namespace {\ namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ INTERNAL_CATCH_TYPE_GEN \ INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ template<typename... Types> \ struct TestName { \ void reg_tests() { \ int index = 0; \ using expander = int[]; \ constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */\ } \ }; \ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \ TestInit t; \ t.reg_tests(); \ return 0; \ }(); \ } \ } \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ template<typename TestType> \ static void TestFuncName() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__) #else #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__) #else #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ template<typename TestType> static void TestFunc(); \ namespace {\ namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ INTERNAL_CATCH_TYPE_GEN\ template<typename... Types> \ struct TestName { \ void reg_tests() { \ int index = 0; \ using expander = int[]; \ (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */\ } \ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ using TestInit = typename convert<TestName, TmplList>::type; \ TestInit t; \ t.reg_tests(); \ return 0; \ }(); \ }}\ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ template<typename TestType> \ static void TestFunc() #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \ INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList ) #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ namespace {\ namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ INTERNAL_CATCH_TYPE_GEN\ INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\ template<typename...Types> \ struct TestNameClass{\ TestNameClass(){\ int index = 0; \ constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ using expander = int[];\ (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \ }\ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ return 0;\ }();\ }\ }\ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ template<typename TestType> \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ void test();\ };\ namespace {\ namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\ INTERNAL_CATCH_TYPE_GEN \ INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ template<typename...Types>\ struct TestNameClass{\ void reg_tests(){\ int index = 0;\ using expander = int[];\ constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */ \ }\ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\ TestInit t;\ t.reg_tests();\ return 0;\ }(); \ }\ }\ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ template<typename TestType> \ void TestName<TestType>::test() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ template<typename TestType> \ struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ void test();\ };\ namespace {\ namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ INTERNAL_CATCH_TYPE_GEN\ template<typename...Types>\ struct TestNameClass{\ void reg_tests(){\ int index = 0;\ using expander = int[];\ (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */ \ }\ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ using TestInit = typename convert<TestNameClass, TmplList>::type;\ TestInit t;\ t.reg_tests();\ return 0;\ }(); \ }}\ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ template<typename TestType> \ void TestName<TestType>::test() #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \ INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList ) #endif // CATCH_TEMPLATE_TEST_REGISTRY_HPP_INCLUDED #if defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) #define CATCH_TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__) #define CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) #else #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) #define CATCH_TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) ) #define CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) #endif #elif defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) #else #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) #endif // When disabled, these can be shared between proper preprocessor and MSVC preprocessor #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_TEMPLATE_LIST_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__) #define CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #elif !defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__) #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) #else #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) ) #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) #endif #elif !defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) #else #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) #endif // When disabled, these can be shared between proper preprocessor and MSVC preprocessor #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define TEMPLATE_LIST_TEST_CASE( ... ) TEMPLATE_TEST_CASE(__VA_ARGS__) #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) #endif // end of user facing macro declarations #endif // CATCH_TEMPLATE_TEST_MACROS_HPP_INCLUDED #ifndef CATCH_TEST_CASE_INFO_HPP_INCLUDED #define CATCH_TEST_CASE_INFO_HPP_INCLUDED #include <string> #include <vector> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif namespace Catch { struct Tag { Tag(StringRef original_, StringRef lowerCased_): original(original_), lowerCased(lowerCased_) {} StringRef original, lowerCased; }; struct ITestInvoker; enum class TestCaseProperties : uint8_t { None = 0, IsHidden = 1 << 1, ShouldFail = 1 << 2, MayFail = 1 << 3, Throws = 1 << 4, NonPortable = 1 << 5, Benchmark = 1 << 6 }; struct TestCaseInfo : Detail::NonCopyable { TestCaseInfo(std::string const& _className, NameAndTags const& _tags, SourceLineInfo const& _lineInfo); bool isHidden() const; bool throws() const; bool okToFail() const; bool expectedToFail() const; // Adds the tag(s) with test's filename (for the -# flag) void addFilenameTag(); std::string tagsAsString() const; std::string name; std::string className; private: std::string backingTags, backingLCaseTags; // Internally we copy tags to the backing storage and then add // refs to this storage to the tags vector. void internalAppendTag(StringRef tagString); public: std::vector<Tag> tags; SourceLineInfo lineInfo; TestCaseProperties properties = TestCaseProperties::None; }; class TestCaseHandle { TestCaseInfo* m_info; ITestInvoker* m_invoker; public: TestCaseHandle(TestCaseInfo* info, ITestInvoker* invoker) : m_info(info), m_invoker(invoker) {} void invoke() const { m_invoker->invoke(); } TestCaseInfo const& getTestCaseInfo() const; bool operator== ( TestCaseHandle const& rhs ) const; bool operator < ( TestCaseHandle const& rhs ) const; }; Detail::unique_ptr<TestCaseInfo> makeTestCaseInfo( std::string const& className, NameAndTags const& nameAndTags, SourceLineInfo const& lineInfo ); } #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CATCH_TEST_CASE_INFO_HPP_INCLUDED #ifndef CATCH_TRANSLATE_EXCEPTION_HPP_INCLUDED #define CATCH_TRANSLATE_EXCEPTION_HPP_INCLUDED #ifndef CATCH_INTERFACES_EXCEPTION_HPP_INCLUDED #define CATCH_INTERFACES_EXCEPTION_HPP_INCLUDED #include <string> #include <vector> namespace Catch { using exceptionTranslateFunction = std::string(*)(); struct IExceptionTranslator; using ExceptionTranslators = std::vector<Detail::unique_ptr<IExceptionTranslator const>>; struct IExceptionTranslator { virtual ~IExceptionTranslator(); virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; }; struct IExceptionTranslatorRegistry { virtual ~IExceptionTranslatorRegistry(); virtual std::string translateActiveException() const = 0; }; } // namespace Catch #endif // CATCH_INTERFACES_EXCEPTION_HPP_INCLUDED #include <exception> namespace Catch { class ExceptionTranslatorRegistrar { template<typename T> class ExceptionTranslator : public IExceptionTranslator { public: ExceptionTranslator( std::string(*translateFunction)( T const& ) ) : m_translateFunction( translateFunction ) {} std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override { #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) try { if( it == itEnd ) std::rethrow_exception(std::current_exception()); else return (*it)->translate( it+1, itEnd ); } catch( T const& ex ) { return m_translateFunction( ex ); } #else return "You should never get here!"; #endif } protected: std::string(*m_translateFunction)( T const& ); }; public: template<typename T> ExceptionTranslatorRegistrar( std::string(*translateFunction)( T const& ) ) { getMutableRegistryHub().registerTranslator ( new ExceptionTranslator<T>( translateFunction ) ); } }; } // namespace Catch /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ static std::string translatorName( signature ); \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ static std::string translatorName( signature ) #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) #if defined(CATCH_CONFIG_DISABLE) #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \ static std::string translatorName( signature ) #endif // This macro is always prefixed #if !defined(CATCH_CONFIG_DISABLE) #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) #else #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) #endif #endif // CATCH_TRANSLATE_EXCEPTION_HPP_INCLUDED #ifndef CATCH_VERSION_HPP_INCLUDED #define CATCH_VERSION_HPP_INCLUDED #include <iosfwd> namespace Catch { // Versioning information struct Version { Version( Version const& ) = delete; Version& operator=( Version const& ) = delete; Version( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, char const * const _branchName, unsigned int _buildNumber ); unsigned int const majorVersion; unsigned int const minorVersion; unsigned int const patchNumber; // buildNumber is only used if branchName is not null char const * const branchName; unsigned int const buildNumber; friend std::ostream& operator << ( std::ostream& os, Version const& version ); }; Version const& libraryVersion(); } #endif // CATCH_VERSION_HPP_INCLUDED #ifndef CATCH_VERSION_MACROS_HPP_INCLUDED #define CATCH_VERSION_MACROS_HPP_INCLUDED #define CATCH_VERSION_MAJOR 3 #define CATCH_VERSION_MINOR 0 #define CATCH_VERSION_PATCH 0 #endif // CATCH_VERSION_MACROS_HPP_INCLUDED /** \file * This is a convenience header for Catch2's Generator support. It includes * **all** of Catch2 headers related to generators. * * Generally the Catch2 users should use specific includes they need, * but this header can be used instead for ease-of-experimentation, or * just plain convenience, at the cost of (significantly) increased * compilation times. * * When a new header is added to either the `generators` folder, * or to the corresponding internal subfolder, it should be added here. */ #ifndef CATCH_GENERATORS_ALL_HPP_INCLUDED #define CATCH_GENERATORS_ALL_HPP_INCLUDED #ifndef CATCH_GENERATOR_EXCEPTION_HPP_INCLUDED #define CATCH_GENERATOR_EXCEPTION_HPP_INCLUDED #include <exception> namespace Catch { // Exception type to be thrown when a Generator runs into an error, // e.g. it cannot initialize the first return value based on // runtime information class GeneratorException : public std::exception { const char* const m_msg = ""; public: GeneratorException(const char* msg): m_msg(msg) {} const char* what() const noexcept override final; }; } // end namespace Catch #endif // CATCH_GENERATOR_EXCEPTION_HPP_INCLUDED #ifndef CATCH_GENERATORS_HPP_INCLUDED #define CATCH_GENERATORS_HPP_INCLUDED #ifndef CATCH_INTERFACES_GENERATORTRACKER_HPP_INCLUDED #define CATCH_INTERFACES_GENERATORTRACKER_HPP_INCLUDED namespace Catch { namespace Generators { class GeneratorUntypedBase { public: GeneratorUntypedBase() = default; // Generation of copy ops is deprecated (and Clang will complain) // if there is a user destructor defined GeneratorUntypedBase(GeneratorUntypedBase const&) = default; GeneratorUntypedBase& operator=(GeneratorUntypedBase const&) = default; virtual ~GeneratorUntypedBase(); // = default; // Attempts to move the generator to the next element // // Returns true iff the move succeeded (and a valid element // can be retrieved). virtual bool next() = 0; }; using GeneratorBasePtr = Catch::Detail::unique_ptr<GeneratorUntypedBase>; } // namespace Generators struct IGeneratorTracker { virtual ~IGeneratorTracker(); // = default; virtual auto hasGenerator() const -> bool = 0; virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0; virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0; }; } // namespace Catch #endif // CATCH_INTERFACES_GENERATORTRACKER_HPP_INCLUDED #include <vector> #include <tuple> #include <utility> namespace Catch { namespace Generators { namespace Detail { //! Throws GeneratorException with the provided message [[noreturn]] void throw_generator_exception(char const * msg); } // end namespace detail template<typename T> struct IGenerator : GeneratorUntypedBase { ~IGenerator() override = default; IGenerator() = default; IGenerator(IGenerator const&) = default; IGenerator& operator=(IGenerator const&) = default; // Returns the current element of the generator // // \Precondition The generator is either freshly constructed, // or the last call to `next()` returned true virtual T const& get() const = 0; using type = T; }; template <typename T> using GeneratorPtr = Catch::Detail::unique_ptr<IGenerator<T>>; template <typename T> class GeneratorWrapper final { GeneratorPtr<T> m_generator; public: //! Takes ownership of the passed pointer. GeneratorWrapper(IGenerator<T>* generator): m_generator(generator) {} GeneratorWrapper(GeneratorPtr<T> generator): m_generator(std::move(generator)) {} T const& get() const { return m_generator->get(); } bool next() { return m_generator->next(); } }; template<typename T> class SingleValueGenerator final : public IGenerator<T> { T m_value; public: SingleValueGenerator(T&& value): m_value(std::forward<T>(value)) {} T const& get() const override { return m_value; } bool next() override { return false; } }; template<typename T> class FixedValuesGenerator final : public IGenerator<T> { static_assert(!std::is_same<T, bool>::value, "FixedValuesGenerator does not support bools because of std::vector<bool>" "specialization, use SingleValue Generator instead."); std::vector<T> m_values; size_t m_idx = 0; public: FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {} T const& get() const override { return m_values[m_idx]; } bool next() override { ++m_idx; return m_idx < m_values.size(); } }; template <typename T> GeneratorWrapper<T> value(T&& value) { return GeneratorWrapper<T>(Catch::Detail::make_unique<SingleValueGenerator<T>>(std::forward<T>(value))); } template <typename T> GeneratorWrapper<T> values(std::initializer_list<T> values) { return GeneratorWrapper<T>(Catch::Detail::make_unique<FixedValuesGenerator<T>>(values)); } template<typename T> class Generators : public IGenerator<T> { std::vector<GeneratorWrapper<T>> m_generators; size_t m_current = 0; void populate(GeneratorWrapper<T>&& generator) { m_generators.emplace_back(std::move(generator)); } void populate(T&& val) { m_generators.emplace_back(value(std::forward<T>(val))); } template<typename U> void populate(U&& val) { populate(T(std::forward<U>(val))); } template<typename U, typename... Gs> void populate(U&& valueOrGenerator, Gs &&... moreGenerators) { populate(std::forward<U>(valueOrGenerator)); populate(std::forward<Gs>(moreGenerators)...); } public: template <typename... Gs> Generators(Gs &&... moreGenerators) { m_generators.reserve(sizeof...(Gs)); populate(std::forward<Gs>(moreGenerators)...); } T const& get() const override { return m_generators[m_current].get(); } bool next() override { if (m_current >= m_generators.size()) { return false; } const bool current_status = m_generators[m_current].next(); if (!current_status) { ++m_current; } return m_current < m_generators.size(); } }; template<typename... Ts> GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<std::decay_t<Ts>...>> tuples ) { return values<std::tuple<Ts...>>( tuples ); } // Tag type to signal that a generator sequence should convert arguments to a specific type template <typename T> struct as {}; template<typename T, typename... Gs> auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> { return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...); } template<typename T> auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> { return Generators<T>(std::move(generator)); } template<typename T, typename... Gs> auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> { return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... ); } template<typename T, typename U, typename... Gs> auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> { return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... ); } auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&; template<typename L> // Note: The type after -> is weird, because VS2015 cannot parse // the expression used in the typedef inside, when it is in // return type. Yeah. auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) { using UnderlyingType = typename decltype(generatorExpression())::type; IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo ); if (!tracker.hasGenerator()) { tracker.setGenerator(Catch::Detail::make_unique<Generators<UnderlyingType>>(generatorExpression())); } auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() ); return generator.get(); } } // namespace Generators } // namespace Catch #define GENERATE( ... ) \ Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ CATCH_INTERNAL_LINEINFO, \ [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) #define GENERATE_COPY( ... ) \ Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ CATCH_INTERNAL_LINEINFO, \ [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) #define GENERATE_REF( ... ) \ Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ CATCH_INTERNAL_LINEINFO, \ [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) #endif // CATCH_GENERATORS_HPP_INCLUDED #ifndef CATCH_GENERATORS_ADAPTERS_HPP_INCLUDED #define CATCH_GENERATORS_ADAPTERS_HPP_INCLUDED namespace Catch { namespace Generators { template <typename T> class TakeGenerator final : public IGenerator<T> { GeneratorWrapper<T> m_generator; size_t m_returned = 0; size_t m_target; public: TakeGenerator(size_t target, GeneratorWrapper<T>&& generator): m_generator(std::move(generator)), m_target(target) { assert(target != 0 && "Empty generators are not allowed"); } T const& get() const override { return m_generator.get(); } bool next() override { ++m_returned; if (m_returned >= m_target) { return false; } const auto success = m_generator.next(); // If the underlying generator does not contain enough values // then we cut short as well if (!success) { m_returned = m_target; } return success; } }; template <typename T> GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) { return GeneratorWrapper<T>(Catch::Detail::make_unique<TakeGenerator<T>>(target, std::move(generator))); } template <typename T, typename Predicate> class FilterGenerator final : public IGenerator<T> { GeneratorWrapper<T> m_generator; Predicate m_predicate; public: template <typename P = Predicate> FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator): m_generator(std::move(generator)), m_predicate(std::forward<P>(pred)) { if (!m_predicate(m_generator.get())) { // It might happen that there are no values that pass the // filter. In that case we throw an exception. auto has_initial_value = next(); if (!has_initial_value) { Detail::throw_generator_exception("No valid value found in filtered generator"); } } } T const& get() const override { return m_generator.get(); } bool next() override { bool success = m_generator.next(); if (!success) { return false; } while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true); return success; } }; template <typename T, typename Predicate> GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) { return GeneratorWrapper<T>(Catch::Detail::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))); } template <typename T> class RepeatGenerator final : public IGenerator<T> { static_assert(!std::is_same<T, bool>::value, "RepeatGenerator currently does not support bools" "because of std::vector<bool> specialization"); GeneratorWrapper<T> m_generator; mutable std::vector<T> m_returned; size_t m_target_repeats; size_t m_current_repeat = 0; size_t m_repeat_index = 0; public: RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator): m_generator(std::move(generator)), m_target_repeats(repeats) { assert(m_target_repeats > 0 && "Repeat generator must repeat at least once"); } T const& get() const override { if (m_current_repeat == 0) { m_returned.push_back(m_generator.get()); return m_returned.back(); } return m_returned[m_repeat_index]; } bool next() override { // There are 2 basic cases: // 1) We are still reading the generator // 2) We are reading our own cache // In the first case, we need to poke the underlying generator. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache if (m_current_repeat == 0) { const auto success = m_generator.next(); if (!success) { ++m_current_repeat; } return m_current_repeat < m_target_repeats; } // In the second case, we need to move indices forward and check that we haven't run up against the end ++m_repeat_index; if (m_repeat_index == m_returned.size()) { m_repeat_index = 0; ++m_current_repeat; } return m_current_repeat < m_target_repeats; } }; template <typename T> GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) { return GeneratorWrapper<T>(Catch::Detail::make_unique<RepeatGenerator<T>>(repeats, std::move(generator))); } template <typename T, typename U, typename Func> class MapGenerator final : public IGenerator<T> { // TBD: provide static assert for mapping function, for friendly error message GeneratorWrapper<U> m_generator; Func m_function; // To avoid returning dangling reference, we have to save the values T m_cache; public: template <typename F2 = Func> MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) : m_generator(std::move(generator)), m_function(std::forward<F2>(function)), m_cache(m_function(m_generator.get())) {} T const& get() const override { return m_cache; } bool next() override { const auto success = m_generator.next(); if (success) { m_cache = m_function(m_generator.get()); } return success; } }; template <typename Func, typename U, typename T = FunctionReturnType<Func, U>> GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) { return GeneratorWrapper<T>( Catch::Detail::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator)) ); } template <typename T, typename U, typename Func> GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) { return GeneratorWrapper<T>( Catch::Detail::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator)) ); } template <typename T> class ChunkGenerator final : public IGenerator<std::vector<T>> { std::vector<T> m_chunk; size_t m_chunk_size; GeneratorWrapper<T> m_generator; bool m_used_up = false; public: ChunkGenerator(size_t size, GeneratorWrapper<T> generator) : m_chunk_size(size), m_generator(std::move(generator)) { m_chunk.reserve(m_chunk_size); if (m_chunk_size != 0) { m_chunk.push_back(m_generator.get()); for (size_t i = 1; i < m_chunk_size; ++i) { if (!m_generator.next()) { Detail::throw_generator_exception("Not enough values to initialize the first chunk"); } m_chunk.push_back(m_generator.get()); } } } std::vector<T> const& get() const override { return m_chunk; } bool next() override { m_chunk.clear(); for (size_t idx = 0; idx < m_chunk_size; ++idx) { if (!m_generator.next()) { return false; } m_chunk.push_back(m_generator.get()); } return true; } }; template <typename T> GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) { return GeneratorWrapper<std::vector<T>>( Catch::Detail::make_unique<ChunkGenerator<T>>(size, std::move(generator)) ); } } // namespace Generators } // namespace Catch #endif // CATCH_GENERATORS_ADAPTERS_HPP_INCLUDED #ifndef CATCH_GENERATORS_RANDOM_HPP_INCLUDED #define CATCH_GENERATORS_RANDOM_HPP_INCLUDED #ifndef CATCH_RANDOM_NUMBER_GENERATOR_HPP_INCLUDED #define CATCH_RANDOM_NUMBER_GENERATOR_HPP_INCLUDED #include <cstdint> namespace Catch { // This is a simple implementation of C++11 Uniform Random Number // Generator. It does not provide all operators, because Catch2 // does not use it, but it should behave as expected inside stdlib's // distributions. // The implementation is based on the PCG family (http://pcg-random.org) class SimplePcg32 { using state_type = std::uint64_t; public: using result_type = std::uint32_t; static constexpr result_type (min)() { return 0; } static constexpr result_type (max)() { return static_cast<result_type>(-1); } // Provide some default initial state for the default constructor SimplePcg32():SimplePcg32(0xed743cc4U) {} explicit SimplePcg32(result_type seed_); void seed(result_type seed_); void discard(uint64_t skip); result_type operator()(); private: friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs); friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs); // In theory we also need operator<< and operator>> // In practice we do not use them, so we will skip them for now std::uint64_t m_state; // This part of the state determines which "stream" of the numbers // is chosen -- we take it as a constant for Catch2, so we only // need to deal with seeding the main state. // Picked by reading 8 bytes from `/dev/random` :-) static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL; }; } // end namespace Catch #endif // CATCH_RANDOM_NUMBER_GENERATOR_HPP_INCLUDED #include <random> namespace Catch { namespace Generators { template <typename Float> class RandomFloatingGenerator final : public IGenerator<Float> { Catch::SimplePcg32& m_rng; std::uniform_real_distribution<Float> m_dist; Float m_current_number; public: RandomFloatingGenerator(Float a, Float b): m_rng(rng()), m_dist(a, b) { static_cast<void>(next()); } Float const& get() const override { return m_current_number; } bool next() override { m_current_number = m_dist(m_rng); return true; } }; template <typename Integer> class RandomIntegerGenerator final : public IGenerator<Integer> { Catch::SimplePcg32& m_rng; std::uniform_int_distribution<Integer> m_dist; Integer m_current_number; public: RandomIntegerGenerator(Integer a, Integer b): m_rng(rng()), m_dist(a, b) { static_cast<void>(next()); } Integer const& get() const override { return m_current_number; } bool next() override { m_current_number = m_dist(m_rng); return true; } }; // TODO: Ideally this would be also constrained against the various char types, // but I don't expect users to run into that in practice. template <typename T> std::enable_if_t<std::is_integral<T>::value && !std::is_same<T, bool>::value, GeneratorWrapper<T>> random(T a, T b) { return GeneratorWrapper<T>( Catch::Detail::make_unique<RandomIntegerGenerator<T>>(a, b) ); } template <typename T> std::enable_if_t<std::is_floating_point<T>::value, GeneratorWrapper<T>> random(T a, T b) { return GeneratorWrapper<T>( Catch::Detail::make_unique<RandomFloatingGenerator<T>>(a, b) ); } } // namespace Generators } // namespace Catch #endif // CATCH_GENERATORS_RANDOM_HPP_INCLUDED #ifndef CATCH_GENERATORS_RANGE_HPP_INCLUDED #define CATCH_GENERATORS_RANGE_HPP_INCLUDED #include <iterator> #include <type_traits> namespace Catch { namespace Generators { template <typename T> class RangeGenerator final : public IGenerator<T> { T m_current; T m_end; T m_step; bool m_positive; public: RangeGenerator(T const& start, T const& end, T const& step): m_current(start), m_end(end), m_step(step), m_positive(m_step > T(0)) { assert(m_current != m_end && "Range start and end cannot be equal"); assert(m_step != T(0) && "Step size cannot be zero"); assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end"); } RangeGenerator(T const& start, T const& end): RangeGenerator(start, end, (start < end) ? T(1) : T(-1)) {} T const& get() const override { return m_current; } bool next() override { m_current += m_step; return (m_positive) ? (m_current < m_end) : (m_current > m_end); } }; template <typename T> GeneratorWrapper<T> range(T const& start, T const& end, T const& step) { static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric"); return GeneratorWrapper<T>(Catch::Detail::make_unique<RangeGenerator<T>>(start, end, step)); } template <typename T> GeneratorWrapper<T> range(T const& start, T const& end) { static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer"); return GeneratorWrapper<T>(Catch::Detail::make_unique<RangeGenerator<T>>(start, end)); } template <typename T> class IteratorGenerator final : public IGenerator<T> { static_assert(!std::is_same<T, bool>::value, "IteratorGenerator currently does not support bools" "because of std::vector<bool> specialization"); std::vector<T> m_elems; size_t m_current = 0; public: template <typename InputIterator, typename InputSentinel> IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) { if (m_elems.empty()) { Detail::throw_generator_exception("IteratorGenerator received no valid values"); } } T const& get() const override { return m_elems[m_current]; } bool next() override { ++m_current; return m_current != m_elems.size(); } }; template <typename InputIterator, typename InputSentinel, typename ResultType = typename std::iterator_traits<InputIterator>::value_type> GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) { return GeneratorWrapper<ResultType>(Catch::Detail::make_unique<IteratorGenerator<ResultType>>(from, to)); } template <typename Container, typename ResultType = typename Container::value_type> GeneratorWrapper<ResultType> from_range(Container const& cnt) { return GeneratorWrapper<ResultType>(Catch::Detail::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end())); } } // namespace Generators } // namespace Catch #endif // CATCH_GENERATORS_RANGE_HPP_INCLUDED #endif // CATCH_GENERATORS_ALL_HPP_INCLUDED /** \file * This is a convenience header for Catch2's interfaces. It includes * **all** of Catch2 headers related to interfaces. * * Generally the Catch2 users should use specific includes they need, * but this header can be used instead for ease-of-experimentation, or * just plain convenience, at the cost of somewhat increased compilation * times. * * When a new header is added to either the `interfaces` folder, or to * the corresponding internal subfolder, it should be added here. */ #ifndef CATCH_INTERFACES_ALL_HPP_INCLUDED #define CATCH_INTERFACES_ALL_HPP_INCLUDED #ifndef CATCH_INTERFACES_REPORTER_REGISTRY_HPP_INCLUDED #define CATCH_INTERFACES_REPORTER_REGISTRY_HPP_INCLUDED #include <string> #include <vector> #include <map> namespace Catch { struct IConfig; struct IStreamingReporter; using IStreamingReporterPtr = Detail::unique_ptr<IStreamingReporter>; struct IReporterFactory; using IReporterFactoryPtr = Detail::unique_ptr<IReporterFactory>; struct IReporterRegistry { using FactoryMap = std::map<std::string, IReporterFactoryPtr>; using Listeners = std::vector<IReporterFactoryPtr>; virtual ~IReporterRegistry(); virtual IStreamingReporterPtr create( std::string const& name, IConfig const* config ) const = 0; virtual FactoryMap const& getFactories() const = 0; virtual Listeners const& getListeners() const = 0; }; } // end namespace Catch #endif // CATCH_INTERFACES_REPORTER_REGISTRY_HPP_INCLUDED #ifndef CATCH_INTERFACES_RUNNER_HPP_INCLUDED #define CATCH_INTERFACES_RUNNER_HPP_INCLUDED namespace Catch { struct IRunner { virtual ~IRunner(); virtual bool aborting() const = 0; }; } #endif // CATCH_INTERFACES_RUNNER_HPP_INCLUDED #ifndef CATCH_INTERFACES_TAG_ALIAS_REGISTRY_HPP_INCLUDED #define CATCH_INTERFACES_TAG_ALIAS_REGISTRY_HPP_INCLUDED #include <string> namespace Catch { struct TagAlias; struct ITagAliasRegistry { virtual ~ITagAliasRegistry(); // Nullptr if not present virtual TagAlias const* find( std::string const& alias ) const = 0; virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; static ITagAliasRegistry const& get(); }; } // end namespace Catch #endif // CATCH_INTERFACES_TAG_ALIAS_REGISTRY_HPP_INCLUDED #endif // CATCH_INTERFACES_ALL_HPP_INCLUDED /** \file * Wrapper for UNCAUGHT_EXCEPTIONS configuration option * * For some functionality, Catch2 requires to know whether there is * an active exception. Because `std::uncaught_exception` is deprecated * in C++17, we want to use `std::uncaught_exceptions` if possible. */ #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP #if defined(_MSC_VER) # if _MSC_VER >= 1900 // Visual Studio 2015 or newer # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS # endif #endif #include <exception> #if defined(__cpp_lib_uncaught_exceptions) \ && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif // __cpp_lib_uncaught_exceptions #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \ && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \ && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP #ifndef CATCH_CONSOLE_COLOUR_HPP_INCLUDED #define CATCH_CONSOLE_COLOUR_HPP_INCLUDED namespace Catch { struct Colour { enum Code { None = 0, White, Red, Green, Blue, Cyan, Yellow, Grey, Bright = 0x10, BrightRed = Bright | Red, BrightGreen = Bright | Green, LightGrey = Bright | Grey, BrightWhite = Bright | White, BrightYellow = Bright | Yellow, // By intention FileName = LightGrey, Warning = BrightYellow, ResultError = BrightRed, ResultSuccess = BrightGreen, ResultExpectedFailure = Warning, Error = BrightRed, Success = Green, OriginalExpression = Cyan, ReconstructedExpression = BrightYellow, SecondaryText = LightGrey, Headers = White }; // Use constructed object for RAII guard Colour( Code _colourCode ); Colour( Colour&& other ) noexcept; Colour& operator=( Colour&& other ) noexcept; ~Colour(); // Use static method for one-shot changes static void use( Code _colourCode ); private: bool m_moved = false; friend std::ostream& operator << (std::ostream& os, Colour const&); }; } // end namespace Catch #endif // CATCH_CONSOLE_COLOUR_HPP_INCLUDED #ifndef CATCH_CONSOLE_WIDTH_HPP_INCLUDED #define CATCH_CONSOLE_WIDTH_HPP_INCLUDED #ifndef CATCH_CONFIG_CONSOLE_WIDTH #define CATCH_CONFIG_CONSOLE_WIDTH 80 #endif #endif // CATCH_CONSOLE_WIDTH_HPP_INCLUDED #ifndef CATCH_CONTAINER_NONMEMBERS_HPP_INCLUDED #define CATCH_CONTAINER_NONMEMBERS_HPP_INCLUDED // We want a simple polyfill over `std::empty`, `std::size` and so on // for C++14 or C++ libraries with incomplete support. // We also have to handle that MSVC std lib will happily provide these // under older standards. #if defined(CATCH_CPP17_OR_GREATER) || defined(_MSC_VER) // We are already using this header either way, so there shouldn't // be much additional overhead in including it to get the feature // test macros #include <string> # if !defined(__cpp_lib_nonmember_container_access) # define CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS # endif #else #define CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS #endif namespace Catch { namespace Detail { #if defined(CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS) template <typename Container> constexpr auto empty(Container const& cont) -> decltype(cont.empty()) { return cont.empty(); } template <typename T, std::size_t N> constexpr bool empty(const T (&)[N]) noexcept { // GCC < 7 does not support the const T(&)[] parameter syntax // so we have to ignore the length explicitly (void)N; return false; } template <typename T> constexpr bool empty(std::initializer_list<T> list) noexcept { return list.size() > 0; } template <typename Container> constexpr auto size(Container const& cont) -> decltype(cont.size()) { return cont.size(); } template <typename T, std::size_t N> constexpr std::size_t size(const T(&)[N]) noexcept { return N; } #endif // CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS } // end namespace Detail } // end namespace Catch #endif // CATCH_CONTAINER_NONMEMBERS_HPP_INCLUDED #ifndef CATCH_DEBUG_CONSOLE_HPP_INCLUDED #define CATCH_DEBUG_CONSOLE_HPP_INCLUDED #include <string> namespace Catch { void writeToDebugConsole( std::string const& text ); } #endif // CATCH_DEBUG_CONSOLE_HPP_INCLUDED #ifndef CATCH_DEBUGGER_HPP_INCLUDED #define CATCH_DEBUGGER_HPP_INCLUDED namespace Catch { bool isDebuggerActive(); } #ifdef CATCH_PLATFORM_MAC #if defined(__i386__) || defined(__x86_64__) #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */ #elif defined(__aarch64__) #define CATCH_TRAP() __asm__(".inst 0xd4200000") #endif #elif defined(CATCH_PLATFORM_IPHONE) // use inline assembler #if defined(__i386__) || defined(__x86_64__) #define CATCH_TRAP() __asm__("int $3") #elif defined(__aarch64__) #define CATCH_TRAP() __asm__(".inst 0xd4200000") #elif defined(__arm__) && !defined(__thumb__) #define CATCH_TRAP() __asm__(".inst 0xe7f001f0") #elif defined(__arm__) && defined(__thumb__) #define CATCH_TRAP() __asm__(".inst 0xde01") #endif #elif defined(CATCH_PLATFORM_LINUX) // If we can use inline assembler, do it because this allows us to break // directly at the location of the failing check instead of breaking inside // raise() called from it, i.e. one stack frame below. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */ #else // Fall back to the generic way. #include <signal.h> #define CATCH_TRAP() raise(SIGTRAP) #endif #elif defined(_MSC_VER) #define CATCH_TRAP() __debugbreak() #elif defined(__MINGW32__) extern "C" __declspec(dllimport) void __stdcall DebugBreak(); #define CATCH_TRAP() DebugBreak() #endif #ifndef CATCH_BREAK_INTO_DEBUGGER #ifdef CATCH_TRAP #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }() #else #define CATCH_BREAK_INTO_DEBUGGER() []{}() #endif #endif #endif // CATCH_DEBUGGER_HPP_INCLUDED #ifndef CATCH_ENUM_VALUES_REGISTRY_HPP_INCLUDED #define CATCH_ENUM_VALUES_REGISTRY_HPP_INCLUDED #include <vector> namespace Catch { namespace Detail { Catch::Detail::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ); class EnumValuesRegistry : public IMutableEnumValuesRegistry { std::vector<Catch::Detail::unique_ptr<EnumInfo>> m_enumInfos; EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override; }; std::vector<StringRef> parseEnums( StringRef enums ); } // Detail } // Catch #endif // CATCH_ENUM_VALUES_REGISTRY_HPP_INCLUDED #ifndef CATCH_ERRNO_GUARD_HPP_INCLUDED #define CATCH_ERRNO_GUARD_HPP_INCLUDED namespace Catch { //! Simple RAII class that stores the value of `errno` //! at construction and restores it at destruction. class ErrnoGuard { public: // Keep these outlined to avoid dragging in macros from <cerrno> ErrnoGuard(); ~ErrnoGuard(); private: int m_oldErrno; }; } #endif // CATCH_ERRNO_GUARD_HPP_INCLUDED #ifndef CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED #define CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED #include <vector> #include <string> namespace Catch { class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { public: ~ExceptionTranslatorRegistry(); virtual void registerTranslator( const IExceptionTranslator* translator ); std::string translateActiveException() const override; std::string tryTranslators() const; private: ExceptionTranslators m_translators; }; } #endif // CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED #ifndef CATCH_FATAL_CONDITION_HANDLER_HPP_INCLUDED #define CATCH_FATAL_CONDITION_HANDLER_HPP_INCLUDED #ifndef CATCH_WINDOWS_H_PROXY_HPP_INCLUDED #define CATCH_WINDOWS_H_PROXY_HPP_INCLUDED #if defined(CATCH_PLATFORM_WINDOWS) #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) # define CATCH_DEFINED_NOMINMAX # define NOMINMAX #endif #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN #endif #ifdef __AFXDLL #include <AfxWin.h> #else #include <windows.h> #endif #ifdef CATCH_DEFINED_NOMINMAX # undef NOMINMAX #endif #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN # undef WIN32_LEAN_AND_MEAN #endif #endif // defined(CATCH_PLATFORM_WINDOWS) #endif // CATCH_WINDOWS_H_PROXY_HPP_INCLUDED #if defined( CATCH_CONFIG_WINDOWS_SEH ) namespace Catch { struct FatalConditionHandler { static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo); FatalConditionHandler(); static void reset(); ~FatalConditionHandler() { reset(); } private: static bool isSet; static ULONG guaranteeSize; static PVOID exceptionHandlerHandle; }; } // namespace Catch #elif defined ( CATCH_CONFIG_POSIX_SIGNALS ) #include <signal.h> namespace Catch { struct FatalConditionHandler { static bool isSet; static struct sigaction oldSigActions[]; static stack_t oldSigStack; static char altStackMem[]; static void handleSignal( int sig ); FatalConditionHandler(); ~FatalConditionHandler() { reset(); } static void reset(); }; } // namespace Catch #else namespace Catch { struct FatalConditionHandler {}; } #endif #endif // CATCH_FATAL_CONDITION_HANDLER_HPP_INCLUDED #ifndef CATCH_LEAK_DETECTOR_HPP_INCLUDED #define CATCH_LEAK_DETECTOR_HPP_INCLUDED namespace Catch { struct LeakDetector { LeakDetector(); ~LeakDetector(); }; } #endif // CATCH_LEAK_DETECTOR_HPP_INCLUDED #ifndef CATCH_LIST_HPP_INCLUDED #define CATCH_LIST_HPP_INCLUDED #include <set> #include <string> namespace Catch { struct IStreamingReporter; class Config; struct ReporterDescription { std::string name, description; }; struct TagInfo { void add(StringRef spelling); std::string all() const; std::set<StringRef> spellings; std::size_t count = 0; }; bool list( IStreamingReporter& reporter, Config const& config ); } // end namespace Catch #endif // CATCH_LIST_HPP_INCLUDED #ifndef CATCH_OPTION_HPP_INCLUDED #define CATCH_OPTION_HPP_INCLUDED namespace Catch { // An optional type template<typename T> class Option { public: Option() : nullableValue( nullptr ) {} Option( T const& _value ) : nullableValue( new( storage ) T( _value ) ) {} Option( Option const& _other ) : nullableValue( _other ? new( storage ) T( *_other ) : nullptr ) {} ~Option() { reset(); } Option& operator= ( Option const& _other ) { if( &_other != this ) { reset(); if( _other ) nullableValue = new( storage ) T( *_other ); } return *this; } Option& operator = ( T const& _value ) { reset(); nullableValue = new( storage ) T( _value ); return *this; } void reset() { if( nullableValue ) nullableValue->~T(); nullableValue = nullptr; } T& operator*() { return *nullableValue; } T const& operator*() const { return *nullableValue; } T* operator->() { return nullableValue; } const T* operator->() const { return nullableValue; } T valueOr( T const& defaultValue ) const { return nullableValue ? *nullableValue : defaultValue; } bool some() const { return nullableValue != nullptr; } bool none() const { return nullableValue == nullptr; } bool operator !() const { return nullableValue == nullptr; } explicit operator bool() const { return some(); } private: T *nullableValue; alignas(alignof(T)) char storage[sizeof(T)]; }; } // end namespace Catch #endif // CATCH_OPTION_HPP_INCLUDED #ifndef CATCH_OUTPUT_REDIRECT_HPP_INCLUDED #define CATCH_OUTPUT_REDIRECT_HPP_INCLUDED #include <cstdio> #include <iosfwd> #include <string> namespace Catch { class RedirectedStream { std::ostream& m_originalStream; std::ostream& m_redirectionStream; std::streambuf* m_prevBuf; public: RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream ); ~RedirectedStream(); }; class RedirectedStdOut { ReusableStringStream m_rss; RedirectedStream m_cout; public: RedirectedStdOut(); auto str() const -> std::string; }; // StdErr has two constituent streams in C++, std::cerr and std::clog // This means that we need to redirect 2 streams into 1 to keep proper // order of writes class RedirectedStdErr { ReusableStringStream m_rss; RedirectedStream m_cerr; RedirectedStream m_clog; public: RedirectedStdErr(); auto str() const -> std::string; }; class RedirectedStreams { public: RedirectedStreams(RedirectedStreams const&) = delete; RedirectedStreams& operator=(RedirectedStreams const&) = delete; RedirectedStreams(RedirectedStreams&&) = delete; RedirectedStreams& operator=(RedirectedStreams&&) = delete; RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr); ~RedirectedStreams(); private: std::string& m_redirectedCout; std::string& m_redirectedCerr; RedirectedStdOut m_redirectedStdOut; RedirectedStdErr m_redirectedStdErr; }; #if defined(CATCH_CONFIG_NEW_CAPTURE) // Windows's implementation of std::tmpfile is terrible (it tries // to create a file inside system folder, thus requiring elevated // privileges for the binary), so we have to use tmpnam(_s) and // create the file ourselves there. class TempFile { public: TempFile(TempFile const&) = delete; TempFile& operator=(TempFile const&) = delete; TempFile(TempFile&&) = delete; TempFile& operator=(TempFile&&) = delete; TempFile(); ~TempFile(); std::FILE* getFile(); std::string getContents(); private: std::FILE* m_file = nullptr; #if defined(_MSC_VER) char m_buffer[L_tmpnam] = { 0 }; #endif }; class OutputRedirect { public: OutputRedirect(OutputRedirect const&) = delete; OutputRedirect& operator=(OutputRedirect const&) = delete; OutputRedirect(OutputRedirect&&) = delete; OutputRedirect& operator=(OutputRedirect&&) = delete; OutputRedirect(std::string& stdout_dest, std::string& stderr_dest); ~OutputRedirect(); private: int m_originalStdout = -1; int m_originalStderr = -1; TempFile m_stdoutFile; TempFile m_stderrFile; std::string& m_stdoutDest; std::string& m_stderrDest; }; #endif } // end namespace Catch #endif // CATCH_OUTPUT_REDIRECT_HPP_INCLUDED #ifndef CATCH_POLYFILLS_HPP_INCLUDED #define CATCH_POLYFILLS_HPP_INCLUDED namespace Catch { bool isnan(float f); bool isnan(double d); } #endif // CATCH_POLYFILLS_HPP_INCLUDED #ifndef CATCH_REPORTER_REGISTRY_HPP_INCLUDED #define CATCH_REPORTER_REGISTRY_HPP_INCLUDED #include <map> namespace Catch { class ReporterRegistry : public IReporterRegistry { public: ReporterRegistry(); ~ReporterRegistry() override; // = default, out of line to allow fwd decl IStreamingReporterPtr create( std::string const& name, IConfig const* config ) const override; void registerReporter( std::string const& name, IReporterFactoryPtr factory ); void registerListener( IReporterFactoryPtr factory ); FactoryMap const& getFactories() const override; Listeners const& getListeners() const override; private: FactoryMap m_factories; Listeners m_listeners; }; } #endif // CATCH_REPORTER_REGISTRY_HPP_INCLUDED #ifndef CATCH_RUN_CONTEXT_HPP_INCLUDED #define CATCH_RUN_CONTEXT_HPP_INCLUDED #ifndef CATCH_TEST_CASE_TRACKER_HPP_INCLUDED #define CATCH_TEST_CASE_TRACKER_HPP_INCLUDED #include <string> #include <vector> #include <memory> namespace Catch { namespace TestCaseTracking { struct NameAndLocation { std::string name; SourceLineInfo location; NameAndLocation( std::string const& _name, SourceLineInfo const& _location ); friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) { return lhs.name == rhs.name && lhs.location == rhs.location; } }; class ITracker; using ITrackerPtr = std::shared_ptr<ITracker>; class ITracker { NameAndLocation m_nameAndLocation; using Children = std::vector<ITrackerPtr>; protected: Children m_children; public: ITracker(NameAndLocation const& nameAndLoc) : m_nameAndLocation(nameAndLoc) {} // static queries NameAndLocation const& nameAndLocation() const { return m_nameAndLocation; } virtual ~ITracker(); // dynamic queries virtual bool isComplete() const = 0; // Successfully completed or failed virtual bool isSuccessfullyCompleted() const = 0; virtual bool isOpen() const = 0; // Started but not complete virtual bool hasStarted() const = 0; virtual ITracker& parent() = 0; // actions virtual void close() = 0; // Successfully complete virtual void fail() = 0; virtual void markAsNeedingAnotherRun() = 0; //! Register a nested ITracker void addChild( ITrackerPtr const& child ); /** * Returns ptr to specific child if register with this tracker. * * Returns nullptr if not found. */ ITrackerPtr findChild( NameAndLocation const& nameAndLocation ); //! Have any children been added? bool hasChildren() const { return !m_children.empty(); } virtual void openChild() = 0; // Debug/ checking virtual bool isSectionTracker() const = 0; virtual bool isGeneratorTracker() const = 0; }; class TrackerContext { enum RunState { NotStarted, Executing, CompletedCycle }; ITrackerPtr m_rootTracker; ITracker* m_currentTracker = nullptr; RunState m_runState = NotStarted; public: ITracker& startRun(); void endRun(); void startCycle(); void completeCycle(); bool completedCycle() const; ITracker& currentTracker(); void setCurrentTracker( ITracker* tracker ); }; class TrackerBase : public ITracker { protected: enum CycleState { NotStarted, Executing, ExecutingChildren, NeedsAnotherRun, CompletedSuccessfully, Failed }; TrackerContext& m_ctx; ITracker* m_parent; CycleState m_runState = NotStarted; public: TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ); bool isComplete() const override; bool isSuccessfullyCompleted() const override; bool isOpen() const override; bool hasStarted() const override { return m_runState != NotStarted; } ITracker& parent() override; void openChild() override; bool isSectionTracker() const override; bool isGeneratorTracker() const override; void open(); void close() override; void fail() override; void markAsNeedingAnotherRun() override; private: void moveToParent(); void moveToThis(); }; class SectionTracker : public TrackerBase { std::vector<std::string> m_filters; std::string m_trimmed_name; public: SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ); bool isSectionTracker() const override; bool isComplete() const override; static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ); void tryOpen(); void addInitialFilters( std::vector<std::string> const& filters ); void addNextFilters( std::vector<std::string> const& filters ); }; } // namespace TestCaseTracking using TestCaseTracking::ITracker; using TestCaseTracking::TrackerContext; using TestCaseTracking::SectionTracker; } // namespace Catch #endif // CATCH_TEST_CASE_TRACKER_HPP_INCLUDED #include <string> namespace Catch { struct IMutableContext; struct IGeneratorTracker; struct IConfig; /////////////////////////////////////////////////////////////////////////// class RunContext : public IResultCapture, public IRunner { public: RunContext( RunContext const& ) = delete; RunContext& operator =( RunContext const& ) = delete; explicit RunContext( IConfig const* _config, IStreamingReporterPtr&& reporter ); ~RunContext() override; void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ); void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ); Totals runTest(TestCaseHandle const& testCase); public: // IResultCapture // Assertion handlers void handleExpr ( AssertionInfo const& info, ITransientExpression const& expr, AssertionReaction& reaction ) override; void handleMessage ( AssertionInfo const& info, ResultWas::OfType resultType, StringRef const& message, AssertionReaction& reaction ) override; void handleUnexpectedExceptionNotThrown ( AssertionInfo const& info, AssertionReaction& reaction ) override; void handleUnexpectedInflightException ( AssertionInfo const& info, std::string const& message, AssertionReaction& reaction ) override; void handleIncomplete ( AssertionInfo const& info ) override; void handleNonExpr ( AssertionInfo const &info, ResultWas::OfType resultType, AssertionReaction &reaction ) override; bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override; void sectionEnded( SectionEndInfo const& endInfo ) override; void sectionEndedEarly( SectionEndInfo const& endInfo ) override; auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override; void benchmarkPreparing( std::string const& name ) override; void benchmarkStarting( BenchmarkInfo const& info ) override; void benchmarkEnded( BenchmarkStats<> const& stats ) override; void benchmarkFailed( std::string const& error ) override; void pushScopedMessage( MessageInfo const& message ) override; void popScopedMessage( MessageInfo const& message ) override; void emplaceUnscopedMessage( MessageBuilder const& builder ) override; std::string getCurrentTestName() const override; const AssertionResult* getLastResult() const override; void exceptionEarlyReported() override; void handleFatalErrorCondition( StringRef message ) override; bool lastAssertionPassed() override; void assertionPassed() override; public: // !TBD We need to do this another way! bool aborting() const override; private: void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ); void invokeActiveTestCase(); void resetAssertionInfo(); bool testForMissingAssertions( Counts& assertions ); void assertionEnded( AssertionResult const& result ); void reportExpr ( AssertionInfo const &info, ResultWas::OfType resultType, ITransientExpression const *expr, bool negated ); void populateReaction( AssertionReaction& reaction ); private: void handleUnfinishedSections(); TestRunInfo m_runInfo; IMutableContext& m_context; TestCaseHandle const* m_activeTestCase = nullptr; ITracker* m_testCaseTracker = nullptr; Option<AssertionResult> m_lastResult; IConfig const* m_config; Totals m_totals; IStreamingReporterPtr m_reporter; std::vector<MessageInfo> m_messages; std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */ AssertionInfo m_lastAssertionInfo; std::vector<SectionEndInfo> m_unfinishedSections; std::vector<ITracker*> m_activeSections; TrackerContext m_trackerContext; bool m_lastAssertionPassed = false; bool m_shouldReportUnexpected = true; bool m_includeSuccessfulResults; }; void seedRng(IConfig const& config); unsigned int rngSeed(); } // end namespace Catch #endif // CATCH_RUN_CONTEXT_HPP_INCLUDED #ifndef CATCH_SINGLETONS_HPP_INCLUDED #define CATCH_SINGLETONS_HPP_INCLUDED namespace Catch { struct ISingleton { virtual ~ISingleton(); }; void addSingleton( ISingleton* singleton ); void cleanupSingletons(); template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT> class Singleton : SingletonImplT, public ISingleton { static auto getInternal() -> Singleton* { static Singleton* s_instance = nullptr; if( !s_instance ) { s_instance = new Singleton; addSingleton( s_instance ); } return s_instance; } public: static auto get() -> InterfaceT const& { return *getInternal(); } static auto getMutable() -> MutableInterfaceT& { return *getInternal(); } }; } // namespace Catch #endif // CATCH_SINGLETONS_HPP_INCLUDED #ifndef CATCH_STARTUP_EXCEPTION_REGISTRY_HPP_INCLUDED #define CATCH_STARTUP_EXCEPTION_REGISTRY_HPP_INCLUDED #include <vector> #include <exception> namespace Catch { class StartupExceptionRegistry { #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) public: void add(std::exception_ptr const& exception) noexcept; std::vector<std::exception_ptr> const& getExceptions() const noexcept; private: std::vector<std::exception_ptr> m_exceptions; #endif }; } // end namespace Catch #endif // CATCH_STARTUP_EXCEPTION_REGISTRY_HPP_INCLUDED #ifndef CATCH_STRING_MANIP_HPP_INCLUDED #define CATCH_STRING_MANIP_HPP_INCLUDED #include <string> #include <iosfwd> #include <vector> namespace Catch { bool startsWith( std::string const& s, std::string const& prefix ); bool startsWith( std::string const& s, char prefix ); bool endsWith( std::string const& s, std::string const& suffix ); bool endsWith( std::string const& s, char suffix ); bool contains( std::string const& s, std::string const& infix ); void toLowerInPlace( std::string& s ); std::string toLower( std::string const& s ); //! Returns a new string without whitespace at the start/end std::string trim( std::string const& str ); //! Returns a substring of the original ref without whitespace. Beware lifetimes! StringRef trim(StringRef ref); // !!! Be aware, returns refs into original string - make sure original string outlives them std::vector<StringRef> splitStringRef( StringRef str, char delimiter ); bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); struct pluralise { pluralise( std::size_t count, std::string const& label ); friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); std::size_t m_count; std::string m_label; }; } #endif // CATCH_STRING_MANIP_HPP_INCLUDED #ifndef CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED #define CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED #include <map> #include <string> namespace Catch { class TagAliasRegistry : public ITagAliasRegistry { public: ~TagAliasRegistry() override; TagAlias const* find( std::string const& alias ) const override; std::string expandAliases( std::string const& unexpandedTestSpec ) const override; void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ); private: std::map<std::string, TagAlias> m_registry; }; } // end namespace Catch #endif // CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED #ifndef CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED #define CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED #include <vector> namespace Catch { class TestCaseHandle; struct IConfig; class TestSpec; std::vector<TestCaseHandle> sortTests( IConfig const& config, std::vector<TestCaseHandle> const& unsortedTestCases ); bool isThrowSafe( TestCaseHandle const& testCase, IConfig const& config ); bool matchTest( TestCaseHandle const& testCase, TestSpec const& testSpec, IConfig const& config ); void enforceNoDuplicateTestCases( std::vector<TestCaseHandle> const& functions ); std::vector<TestCaseHandle> filterTests( std::vector<TestCaseHandle> const& testCases, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCaseHandle> const& getAllTestCasesSorted( IConfig const& config ); class TestRegistry : public ITestCaseRegistry { public: ~TestRegistry() override = default; void registerTest( Detail::unique_ptr<TestCaseInfo> testInfo, Detail::unique_ptr<ITestInvoker> testInvoker ); std::vector<TestCaseInfo*> const& getAllInfos() const override; std::vector<TestCaseHandle> const& getAllTests() const override; std::vector<TestCaseHandle> const& getAllTestsSorted( IConfig const& config ) const override; private: std::vector<Detail::unique_ptr<TestCaseInfo>> m_owned_test_infos; // Keeps a materialized vector for `getAllInfos`. // We should get rid of that eventually (see interface note) std::vector<TestCaseInfo*> m_viewed_test_infos; std::vector<Detail::unique_ptr<ITestInvoker>> m_invokers; std::vector<TestCaseHandle> m_handles; mutable TestRunOrder m_currentSortOrder = TestRunOrder::Declared; mutable std::vector<TestCaseHandle> m_sortedFunctions; }; /////////////////////////////////////////////////////////////////////////// class TestInvokerAsFunction final : public ITestInvoker { using TestType = void(*)(); TestType m_testAsFunction; public: TestInvokerAsFunction(TestType testAsFunction) noexcept: m_testAsFunction(testAsFunction) {} void invoke() const override; }; std::string extractClassName( StringRef const& classOrQualifiedMethodName ); /////////////////////////////////////////////////////////////////////////// } // end namespace Catch #endif // CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED #ifndef CATCH_TEST_SPEC_PARSER_HPP_INCLUDED #define CATCH_TEST_SPEC_PARSER_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif #include <vector> #include <string> namespace Catch { struct ITagAliasRegistry; class TestSpecParser { enum Mode{ None, Name, QuotedName, Tag, EscapedName }; Mode m_mode = None; Mode lastMode = None; bool m_exclusion = false; std::size_t m_pos = 0; std::size_t m_realPatternPos = 0; std::string m_arg; std::string m_substring; std::string m_patternName; std::vector<std::size_t> m_escapeChars; TestSpec::Filter m_currentFilter; TestSpec m_testSpec; ITagAliasRegistry const* m_tagAliases = nullptr; public: TestSpecParser( ITagAliasRegistry const& tagAliases ); TestSpecParser& parse( std::string const& arg ); TestSpec testSpec(); private: bool visitChar( char c ); void startNewMode( Mode mode ); bool processNoneChar( char c ); void processNameChar( char c ); bool processOtherChar( char c ); void endMode(); void escape(); bool isControlChar( char c ) const; void saveLastMode(); void revertBackToLastMode(); void addFilter(); bool separate(); // Handles common preprocessing of the pattern for name/tag patterns std::string preprocessPattern(); // Adds the current pattern as a test name void addNamePattern(); // Adds the current pattern as a tag void addTagPattern(); inline void addCharToPattern(char c) { m_substring += c; m_patternName += c; m_realPatternPos++; } }; TestSpec parseTestSpec( std::string const& arg ); } // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CATCH_TEST_SPEC_PARSER_HPP_INCLUDED #ifndef CATCH_TEXTFLOW_HPP_INCLUDED #define CATCH_TEXTFLOW_HPP_INCLUDED #include <cassert> #include <string> #include <vector> namespace Catch { namespace TextFlow { class Columns; class Column { std::string m_string; size_t m_width = CATCH_CONFIG_CONSOLE_WIDTH - 1; size_t m_indent = 0; size_t m_initialIndent = std::string::npos; public: class iterator { friend Column; struct EndTag {}; Column const& m_column; size_t m_pos = 0; size_t m_len = 0; size_t m_end = 0; bool m_suffix = false; iterator( Column const& column, EndTag ): m_column( column ), m_pos( m_column.m_string.size() ) {} void calcLength(); // Returns current indention width size_t indent() const; // Creates an indented and (optionally) suffixed string from // current iterator position, indentation and length. std::string addIndentAndSuffix( size_t position, size_t length ) const; public: using difference_type = std::ptrdiff_t; using value_type = std::string; using pointer = value_type*; using reference = value_type&; using iterator_category = std::forward_iterator_tag; explicit iterator( Column const& column ); std::string operator*() const; iterator& operator++(); iterator operator++( int ); bool operator==( iterator const& other ) const { return m_pos == other.m_pos && &m_column == &other.m_column; } bool operator!=( iterator const& other ) const { return !operator==( other ); } }; using const_iterator = iterator; explicit Column( std::string const& text ): m_string( text ) {} Column& width( size_t newWidth ) { assert( newWidth > 0 ); m_width = newWidth; return *this; } Column& indent( size_t newIndent ) { m_indent = newIndent; return *this; } Column& initialIndent( size_t newIndent ) { m_initialIndent = newIndent; return *this; } size_t width() const { return m_width; } iterator begin() const { return iterator( *this ); } iterator end() const { return { *this, iterator::EndTag{} }; } friend std::ostream& operator<<( std::ostream& os, Column const& col ); Columns operator+( Column const& other ); }; //! Creates a column that serves as an empty space of specific width Column Spacer( size_t spaceWidth ); class Columns { std::vector<Column> m_columns; public: class iterator { friend Columns; struct EndTag {}; std::vector<Column> const& m_columns; std::vector<Column::iterator> m_iterators; size_t m_activeIterators; iterator( Columns const& columns, EndTag ); public: using difference_type = std::ptrdiff_t; using value_type = std::string; using pointer = value_type*; using reference = value_type&; using iterator_category = std::forward_iterator_tag; explicit iterator( Columns const& columns ); auto operator==( iterator const& other ) const -> bool { return m_iterators == other.m_iterators; } auto operator!=( iterator const& other ) const -> bool { return m_iterators != other.m_iterators; } std::string operator*() const; iterator& operator++(); iterator operator++( int ); }; using const_iterator = iterator; iterator begin() const { return iterator( *this ); } iterator end() const { return { *this, iterator::EndTag() }; } Columns& operator+=( Column const& col ); Columns operator+( Column const& col ); friend std::ostream& operator<<( std::ostream& os, Columns const& cols ); }; } // namespace TextFlow } // namespace Catch #endif // CATCH_TEXTFLOW_HPP_INCLUDED #ifndef CATCH_TO_STRING_HPP_INCLUDED #define CATCH_TO_STRING_HPP_INCLUDED #include <string> namespace Catch { template <typename T> std::string to_string(T const& t) { #if defined(CATCH_CONFIG_CPP11_TO_STRING) return std::to_string(t); #else ReusableStringStream rss; rss << t; return rss.str(); #endif } } // end namespace Catch #endif // CATCH_TO_STRING_HPP_INCLUDED #ifndef CATCH_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED #define CATCH_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED namespace Catch { bool uncaught_exceptions(); } // end namespace Catch #endif // CATCH_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED #ifndef CATCH_XMLWRITER_HPP_INCLUDED #define CATCH_XMLWRITER_HPP_INCLUDED // FixMe: Without this include (and something inside it), MSVC goes crazy // and reports that calls to XmlEncode's op << are ambiguous between // the declaration and definition. // It also has to be in the header. #include <vector> namespace Catch { enum class XmlFormatting { None = 0x00, Indent = 0x01, Newline = 0x02, }; XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs); XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs); class XmlEncode { public: enum ForWhat { ForTextNodes, ForAttributes }; XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); void encodeTo( std::ostream& os ) const; friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ); private: std::string m_str; ForWhat m_forWhat; }; class XmlWriter { public: class ScopedElement { public: ScopedElement( XmlWriter* writer, XmlFormatting fmt ); ScopedElement( ScopedElement&& other ) noexcept; ScopedElement& operator=( ScopedElement&& other ) noexcept; ~ScopedElement(); ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent ); template<typename T> ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { m_writer->writeAttribute( name, attribute ); return *this; } private: mutable XmlWriter* m_writer = nullptr; XmlFormatting m_fmt; }; XmlWriter( std::ostream& os = Catch::cout() ); ~XmlWriter(); XmlWriter( XmlWriter const& ) = delete; XmlWriter& operator=( XmlWriter const& ) = delete; XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent); ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent); XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent); XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ); XmlWriter& writeAttribute( std::string const& name, bool attribute ); template<typename T> XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { ReusableStringStream rss; rss << attribute; return writeAttribute( name, rss.str() ); } XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent); XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent); void writeStylesheetRef( std::string const& url ); XmlWriter& writeBlankLine(); void ensureTagClosed(); private: void applyFormatting(XmlFormatting fmt); void writeDeclaration(); void newlineIfNecessary(); bool m_tagIsOpen = false; bool m_needsNewline = false; std::vector<std::string> m_tags; std::string m_indent; std::ostream& m_os; }; } #endif // CATCH_XMLWRITER_HPP_INCLUDED /** \file * This is a convenience header for Catch2's Matcher support. It includes * **all** of Catch2 headers related to matchers. * * Generally the Catch2 users should use specific includes they need, * but this header can be used instead for ease-of-experimentation, or * just plain convenience, at the cost of increased compilation times. * * When a new header is added to either the `matchers` folder, or to * the corresponding internal subfolder, it should be added here. */ #ifndef CATCH_MATCHERS_ALL_HPP_INCLUDED #define CATCH_MATCHERS_ALL_HPP_INCLUDED #ifndef CATCH_MATCHERS_HPP_INCLUDED #define CATCH_MATCHERS_HPP_INCLUDED #ifndef CATCH_MATCHERS_IMPL_HPP_INCLUDED #define CATCH_MATCHERS_IMPL_HPP_INCLUDED namespace Catch { template<typename ArgT, typename MatcherT> class MatchExpr : public ITransientExpression { ArgT && m_arg; MatcherT const& m_matcher; StringRef m_matcherString; public: MatchExpr( ArgT && arg, MatcherT const& matcher, StringRef const& matcherString ) : ITransientExpression{ true, matcher.match( arg ) }, // not forwarding arg here on purpose m_arg( std::forward<ArgT>(arg) ), m_matcher( matcher ), m_matcherString( matcherString ) {} void streamReconstructedExpression( std::ostream &os ) const override { auto matcherAsString = m_matcher.toString(); os << Catch::Detail::stringify( m_arg ) << ' '; if( matcherAsString == Detail::unprintableString ) os << m_matcherString; else os << matcherAsString; } }; namespace Matchers { template <typename ArgT> struct MatcherBase; } using StringMatcher = Matchers::MatcherBase<std::string>; void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ); template<typename ArgT, typename MatcherT> auto makeMatchExpr( ArgT && arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> { return MatchExpr<ArgT, MatcherT>( std::forward<ArgT>(arg), matcher, matcherString ); } } // namespace Catch /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ INTERNAL_CATCH_TRY { \ catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \ } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \ do { \ Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ if( catchAssertionHandler.allowThrows() ) \ try { \ static_cast<void>(__VA_ARGS__ ); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch( exceptionType const& ex ) { \ catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \ } \ catch( ... ) { \ catchAssertionHandler.handleUnexpectedInflightException(); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while( false ) #endif // CATCH_MATCHERS_IMPL_HPP_INCLUDED #include <string> #include <vector> namespace Catch { namespace Matchers { class MatcherUntypedBase { public: MatcherUntypedBase() = default; MatcherUntypedBase(MatcherUntypedBase const&) = default; MatcherUntypedBase(MatcherUntypedBase&&) = default; MatcherUntypedBase& operator = (MatcherUntypedBase const&) = delete; MatcherUntypedBase& operator = (MatcherUntypedBase&&) = delete; std::string toString() const; protected: virtual ~MatcherUntypedBase(); // = default; virtual std::string describe() const = 0; mutable std::string m_cachedToString; }; #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wnon-virtual-dtor" #endif template<typename ObjectT> struct MatcherMethod { virtual bool match(ObjectT const& arg) const = 0; }; #ifdef __clang__ # pragma clang diagnostic pop #endif template<typename T> struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {}; namespace Detail { template<typename ArgT> struct MatchAllOf final : MatcherBase<ArgT> { MatchAllOf() = default; MatchAllOf(MatchAllOf const&) = delete; MatchAllOf& operator=(MatchAllOf const&) = delete; MatchAllOf(MatchAllOf&&) = default; MatchAllOf& operator=(MatchAllOf&&) = default; bool match( ArgT const& arg ) const override { for( auto matcher : m_matchers ) { if (!matcher->match(arg)) return false; } return true; } std::string describe() const override { std::string description; description.reserve( 4 + m_matchers.size()*32 ); description += "( "; bool first = true; for( auto matcher : m_matchers ) { if( first ) first = false; else description += " and "; description += matcher->toString(); } description += " )"; return description; } friend MatchAllOf operator&& (MatchAllOf&& lhs, MatcherBase<ArgT> const& rhs) { lhs.m_matchers.push_back(&rhs); return std::move(lhs); } friend MatchAllOf operator&& (MatcherBase<ArgT> const& lhs, MatchAllOf&& rhs) { rhs.m_matchers.insert(rhs.m_matchers.begin(), &lhs); return std::move(rhs); } private: std::vector<MatcherBase<ArgT> const*> m_matchers; }; //! lvalue overload is intentionally deleted, users should //! not be trying to compose stored composition matchers template<typename ArgT> MatchAllOf<ArgT> operator&& (MatchAllOf<ArgT> const& lhs, MatcherBase<ArgT> const& rhs) = delete; //! lvalue overload is intentionally deleted, users should //! not be trying to compose stored composition matchers template<typename ArgT> MatchAllOf<ArgT> operator&& (MatcherBase<ArgT> const& lhs, MatchAllOf<ArgT> const& rhs) = delete; template<typename ArgT> struct MatchAnyOf final : MatcherBase<ArgT> { MatchAnyOf() = default; MatchAnyOf(MatchAnyOf const&) = delete; MatchAnyOf& operator=(MatchAnyOf const&) = delete; MatchAnyOf(MatchAnyOf&&) = default; MatchAnyOf& operator=(MatchAnyOf&&) = default; bool match( ArgT const& arg ) const override { for( auto matcher : m_matchers ) { if (matcher->match(arg)) return true; } return false; } std::string describe() const override { std::string description; description.reserve( 4 + m_matchers.size()*32 ); description += "( "; bool first = true; for( auto matcher : m_matchers ) { if( first ) first = false; else description += " or "; description += matcher->toString(); } description += " )"; return description; } friend MatchAnyOf operator|| (MatchAnyOf&& lhs, MatcherBase<ArgT> const& rhs) { lhs.m_matchers.push_back(&rhs); return std::move(lhs); } friend MatchAnyOf operator|| (MatcherBase<ArgT> const& lhs, MatchAnyOf&& rhs) { rhs.m_matchers.insert(rhs.m_matchers.begin(), &lhs); return std::move(rhs); } private: std::vector<MatcherBase<ArgT> const*> m_matchers; }; //! lvalue overload is intentionally deleted, users should //! not be trying to compose stored composition matchers template<typename ArgT> MatchAnyOf<ArgT> operator|| (MatchAnyOf<ArgT> const& lhs, MatcherBase<ArgT> const& rhs) = delete; //! lvalue overload is intentionally deleted, users should //! not be trying to compose stored composition matchers template<typename ArgT> MatchAnyOf<ArgT> operator|| (MatcherBase<ArgT> const& lhs, MatchAnyOf<ArgT> const& rhs) = delete; template<typename ArgT> struct MatchNotOf final : MatcherBase<ArgT> { explicit MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ): m_underlyingMatcher( underlyingMatcher ) {} bool match( ArgT const& arg ) const override { return !m_underlyingMatcher.match( arg ); } std::string describe() const override { return "not " + m_underlyingMatcher.toString(); } private: MatcherBase<ArgT> const& m_underlyingMatcher; }; } // namespace Detail template <typename T> Detail::MatchAllOf<T> operator&& (MatcherBase<T> const& lhs, MatcherBase<T> const& rhs) { return Detail::MatchAllOf<T>{} && lhs && rhs; } template <typename T> Detail::MatchAnyOf<T> operator|| (MatcherBase<T> const& lhs, MatcherBase<T> const& rhs) { return Detail::MatchAnyOf<T>{} || lhs || rhs; } template <typename T> Detail::MatchNotOf<T> operator! (MatcherBase<T> const& matcher) { return Detail::MatchNotOf<T>{ matcher }; } } // namespace Matchers } // namespace Catch #if defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE) #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) #elif defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE) #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0) #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) #define CATCH_CHECK_THAT( arg, matcher ) (void)(0) #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0) #elif !defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE) #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) #elif !defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE) #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) #define CHECK_THROWS_WITH( expr, matcher ) (void)(0) #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) #define CHECK_THAT( arg, matcher ) (void)(0) #define REQUIRE_THAT( arg, matcher ) (void)(0) #endif // end of user facing macro declarations #endif // CATCH_MATCHERS_HPP_INCLUDED #ifndef CATCH_MATCHERS_CONTAINER_PROPERTIES_HPP_INCLUDED #define CATCH_MATCHERS_CONTAINER_PROPERTIES_HPP_INCLUDED #ifndef CATCH_MATCHERS_TEMPLATED_HPP_INCLUDED #define CATCH_MATCHERS_TEMPLATED_HPP_INCLUDED #include <array> #include <algorithm> #include <string> #include <type_traits> #include <utility> namespace Catch { namespace Matchers { struct MatcherGenericBase : MatcherUntypedBase { MatcherGenericBase() = default; virtual ~MatcherGenericBase(); // = default; MatcherGenericBase(MatcherGenericBase&) = default; MatcherGenericBase(MatcherGenericBase&&) = default; MatcherGenericBase& operator=(MatcherGenericBase const&) = delete; MatcherGenericBase& operator=(MatcherGenericBase&&) = delete; }; namespace Detail { template<std::size_t N, std::size_t M> std::array<void const*, N + M> array_cat(std::array<void const*, N> && lhs, std::array<void const*, M> && rhs) { std::array<void const*, N + M> arr{}; std::copy_n(lhs.begin(), N, arr.begin()); std::copy_n(rhs.begin(), M, arr.begin() + N); return arr; } template<std::size_t N> std::array<void const*, N+1> array_cat(std::array<void const*, N> && lhs, void const* rhs) { std::array<void const*, N+1> arr{}; std::copy_n(lhs.begin(), N, arr.begin()); arr[N] = rhs; return arr; } template<std::size_t N> std::array<void const*, N+1> array_cat(void const* lhs, std::array<void const*, N> && rhs) { std::array<void const*, N + 1> arr{ {lhs} }; std::copy_n(rhs.begin(), N, arr.begin() + 1); return arr; } #ifdef CATCH_CPP17_OR_GREATER using std::conjunction; #else // CATCH_CPP17_OR_GREATER template<typename... Cond> struct conjunction : std::true_type {}; template<typename Cond, typename... Rest> struct conjunction<Cond, Rest...> : std::integral_constant<bool, Cond::value && conjunction<Rest...>::value> {}; #endif // CATCH_CPP17_OR_GREATER template<typename T> using is_generic_matcher = std::is_base_of< Catch::Matchers::MatcherGenericBase, std::remove_cv_t<std::remove_reference_t<T>> >; template<typename... Ts> using are_generic_matchers = conjunction<is_generic_matcher<Ts>...>; template<typename T> using is_matcher = std::is_base_of< Catch::Matchers::MatcherUntypedBase, std::remove_cv_t<std::remove_reference_t<T>> >; template<std::size_t N, typename Arg> bool match_all_of(Arg&&, std::array<void const*, N> const&, std::index_sequence<>) { return true; } template<typename T, typename... MatcherTs, std::size_t N, typename Arg, std::size_t Idx, std::size_t... Indices> bool match_all_of(Arg&& arg, std::array<void const*, N> const& matchers, std::index_sequence<Idx, Indices...>) { return static_cast<T const*>(matchers[Idx])->match(arg) && match_all_of<MatcherTs...>(arg, matchers, std::index_sequence<Indices...>{}); } template<std::size_t N, typename Arg> bool match_any_of(Arg&&, std::array<void const*, N> const&, std::index_sequence<>) { return false; } template<typename T, typename... MatcherTs, std::size_t N, typename Arg, std::size_t Idx, std::size_t... Indices> bool match_any_of(Arg&& arg, std::array<void const*, N> const& matchers, std::index_sequence<Idx, Indices...>) { return static_cast<T const*>(matchers[Idx])->match(arg) || match_any_of<MatcherTs...>(arg, matchers, std::index_sequence<Indices...>{}); } std::string describe_multi_matcher(StringRef combine, std::string const* descriptions_begin, std::string const* descriptions_end); template<typename... MatcherTs, std::size_t... Idx> std::string describe_multi_matcher(StringRef combine, std::array<void const*, sizeof...(MatcherTs)> const& matchers, std::index_sequence<Idx...>) { std::array<std::string, sizeof...(MatcherTs)> descriptions {{ static_cast<MatcherTs const*>(matchers[Idx])->toString()... }}; return describe_multi_matcher(combine, descriptions.data(), descriptions.data() + descriptions.size()); } template<typename... MatcherTs> struct MatchAllOfGeneric final : MatcherGenericBase { MatchAllOfGeneric(MatchAllOfGeneric const&) = delete; MatchAllOfGeneric& operator=(MatchAllOfGeneric const&) = delete; MatchAllOfGeneric(MatchAllOfGeneric&&) = default; MatchAllOfGeneric& operator=(MatchAllOfGeneric&&) = default; MatchAllOfGeneric(MatcherTs const&... matchers) : m_matchers{ {std::addressof(matchers)...} } {} explicit MatchAllOfGeneric(std::array<void const*, sizeof...(MatcherTs)> matchers) : m_matchers{matchers} {} template<typename Arg> bool match(Arg&& arg) const { return match_all_of<MatcherTs...>(arg, m_matchers, std::index_sequence_for<MatcherTs...>{}); } std::string describe() const override { return describe_multi_matcher<MatcherTs...>(" and "_sr, m_matchers, std::index_sequence_for<MatcherTs...>{}); } std::array<void const*, sizeof...(MatcherTs)> m_matchers; //! Avoids type nesting for `GenericAllOf && GenericAllOf` case template<typename... MatchersRHS> friend MatchAllOfGeneric<MatcherTs..., MatchersRHS...> operator && ( MatchAllOfGeneric<MatcherTs...>&& lhs, MatchAllOfGeneric<MatchersRHS...>&& rhs) { return MatchAllOfGeneric<MatcherTs..., MatchersRHS...>{array_cat(std::move(lhs.m_matchers), std::move(rhs.m_matchers))}; } //! Avoids type nesting for `GenericAllOf && some matcher` case template<typename MatcherRHS> friend std::enable_if_t<is_matcher<MatcherRHS>::value, MatchAllOfGeneric<MatcherTs..., MatcherRHS>> operator && ( MatchAllOfGeneric<MatcherTs...>&& lhs, MatcherRHS const& rhs) { return MatchAllOfGeneric<MatcherTs..., MatcherRHS>{array_cat(std::move(lhs.m_matchers), static_cast<void const*>(&rhs))}; } //! Avoids type nesting for `some matcher && GenericAllOf` case template<typename MatcherLHS> friend std::enable_if_t<is_matcher<MatcherLHS>::value, MatchAllOfGeneric<MatcherLHS, MatcherTs...>> operator && ( MatcherLHS const& lhs, MatchAllOfGeneric<MatcherTs...>&& rhs) { return MatchAllOfGeneric<MatcherLHS, MatcherTs...>{array_cat(static_cast<void const*>(std::addressof(lhs)), std::move(rhs.m_matchers))}; } }; template<typename... MatcherTs> struct MatchAnyOfGeneric final : MatcherGenericBase { MatchAnyOfGeneric(MatchAnyOfGeneric const&) = delete; MatchAnyOfGeneric& operator=(MatchAnyOfGeneric const&) = delete; MatchAnyOfGeneric(MatchAnyOfGeneric&&) = default; MatchAnyOfGeneric& operator=(MatchAnyOfGeneric&&) = default; MatchAnyOfGeneric(MatcherTs const&... matchers) : m_matchers{ {std::addressof(matchers)...} } {} explicit MatchAnyOfGeneric(std::array<void const*, sizeof...(MatcherTs)> matchers) : m_matchers{matchers} {} template<typename Arg> bool match(Arg&& arg) const { return match_any_of<MatcherTs...>(arg, m_matchers, std::index_sequence_for<MatcherTs...>{}); } std::string describe() const override { return describe_multi_matcher<MatcherTs...>(" or "_sr, m_matchers, std::index_sequence_for<MatcherTs...>{}); } std::array<void const*, sizeof...(MatcherTs)> m_matchers; //! Avoids type nesting for `GenericAnyOf || GenericAnyOf` case template<typename... MatchersRHS> friend MatchAnyOfGeneric<MatcherTs..., MatchersRHS...> operator || ( MatchAnyOfGeneric<MatcherTs...>&& lhs, MatchAnyOfGeneric<MatchersRHS...>&& rhs) { return MatchAnyOfGeneric<MatcherTs..., MatchersRHS...>{array_cat(std::move(lhs.m_matchers), std::move(rhs.m_matchers))}; } //! Avoids type nesting for `GenericAnyOf || some matcher` case template<typename MatcherRHS> friend std::enable_if_t<is_matcher<MatcherRHS>::value, MatchAnyOfGeneric<MatcherTs..., MatcherRHS>> operator || ( MatchAnyOfGeneric<MatcherTs...>&& lhs, MatcherRHS const& rhs) { return MatchAnyOfGeneric<MatcherTs..., MatcherRHS>{array_cat(std::move(lhs.m_matchers), static_cast<void const*>(std::addressof(rhs)))}; } //! Avoids type nesting for `some matcher || GenericAnyOf` case template<typename MatcherLHS> friend std::enable_if_t<is_matcher<MatcherLHS>::value, MatchAnyOfGeneric<MatcherLHS, MatcherTs...>> operator || ( MatcherLHS const& lhs, MatchAnyOfGeneric<MatcherTs...>&& rhs) { return MatchAnyOfGeneric<MatcherLHS, MatcherTs...>{array_cat(static_cast<void const*>(std::addressof(lhs)), std::move(rhs.m_matchers))}; } }; template<typename MatcherT> struct MatchNotOfGeneric final : MatcherGenericBase { MatchNotOfGeneric(MatchNotOfGeneric const&) = delete; MatchNotOfGeneric& operator=(MatchNotOfGeneric const&) = delete; MatchNotOfGeneric(MatchNotOfGeneric&&) = default; MatchNotOfGeneric& operator=(MatchNotOfGeneric&&) = default; explicit MatchNotOfGeneric(MatcherT const& matcher) : m_matcher{matcher} {} template<typename Arg> bool match(Arg&& arg) const { return !m_matcher.match(arg); } std::string describe() const override { return "not " + m_matcher.toString(); } //! Negating negation can just unwrap and return underlying matcher friend MatcherT const& operator ! (MatchNotOfGeneric<MatcherT> const& matcher) { return matcher.m_matcher; } private: MatcherT const& m_matcher; }; } // namespace Detail // compose only generic matchers template<typename MatcherLHS, typename MatcherRHS> std::enable_if_t<Detail::are_generic_matchers<MatcherLHS, MatcherRHS>::value, Detail::MatchAllOfGeneric<MatcherLHS, MatcherRHS>> operator && (MatcherLHS const& lhs, MatcherRHS const& rhs) { return { lhs, rhs }; } template<typename MatcherLHS, typename MatcherRHS> std::enable_if_t<Detail::are_generic_matchers<MatcherLHS, MatcherRHS>::value, Detail::MatchAnyOfGeneric<MatcherLHS, MatcherRHS>> operator || (MatcherLHS const& lhs, MatcherRHS const& rhs) { return { lhs, rhs }; } //! Wrap provided generic matcher in generic negator template<typename MatcherT> std::enable_if_t<Detail::is_generic_matcher<MatcherT>::value, Detail::MatchNotOfGeneric<MatcherT>> operator ! (MatcherT const& matcher) { return Detail::MatchNotOfGeneric<MatcherT>{matcher}; } // compose mixed generic and non-generic matchers template<typename MatcherLHS, typename ArgRHS> std::enable_if_t<Detail::is_generic_matcher<MatcherLHS>::value, Detail::MatchAllOfGeneric<MatcherLHS, MatcherBase<ArgRHS>>> operator && (MatcherLHS const& lhs, MatcherBase<ArgRHS> const& rhs) { return { lhs, rhs }; } template<typename ArgLHS, typename MatcherRHS> std::enable_if_t<Detail::is_generic_matcher<MatcherRHS>::value, Detail::MatchAllOfGeneric<MatcherBase<ArgLHS>, MatcherRHS>> operator && (MatcherBase<ArgLHS> const& lhs, MatcherRHS const& rhs) { return { lhs, rhs }; } template<typename MatcherLHS, typename ArgRHS> std::enable_if_t<Detail::is_generic_matcher<MatcherLHS>::value, Detail::MatchAnyOfGeneric<MatcherLHS, MatcherBase<ArgRHS>>> operator || (MatcherLHS const& lhs, MatcherBase<ArgRHS> const& rhs) { return { lhs, rhs }; } template<typename ArgLHS, typename MatcherRHS> std::enable_if_t<Detail::is_generic_matcher<MatcherRHS>::value, Detail::MatchAnyOfGeneric<MatcherBase<ArgLHS>, MatcherRHS>> operator || (MatcherBase<ArgLHS> const& lhs, MatcherRHS const& rhs) { return { lhs, rhs }; } } // namespace Matchers } // namespace Catch #endif // CATCH_MATCHERS_TEMPLATED_HPP_INCLUDED namespace Catch { namespace Matchers { class IsEmptyMatcher final : public MatcherGenericBase { public: // todo: Use polyfills template <typename RangeLike> bool match(RangeLike&& rng) const { #if defined(CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS) using Catch::Detail::empty; #else using std::empty; #endif return empty(rng); } std::string describe() const override; }; class HasSizeMatcher final : public MatcherGenericBase { std::size_t m_target_size; public: explicit HasSizeMatcher(std::size_t target_size): m_target_size(target_size) {} template <typename RangeLike> bool match(RangeLike&& rng) const { #if defined(CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS) using Catch::Detail::size; #else using std::size; #endif return size(rng) == m_target_size; } std::string describe() const override; }; template <typename Matcher> class SizeMatchesMatcher final : public MatcherGenericBase { Matcher m_matcher; public: explicit SizeMatchesMatcher(Matcher m): m_matcher(std::move(m)) {} template <typename RangeLike> bool match(RangeLike&& rng) const { #if defined(CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS) using Catch::Detail::size; #else using std::size; #endif return m_matcher.match(size(rng)); } std::string describe() const override { return "size matches " + m_matcher.describe(); } }; //! Creates a matcher that accepts empty ranges/containers IsEmptyMatcher IsEmpty(); //! Creates a matcher that accepts ranges/containers with specific size HasSizeMatcher SizeIs(std::size_t sz); template <typename Matcher> std::enable_if_t<Detail::is_matcher<Matcher>::value, SizeMatchesMatcher<Matcher>> SizeIs(Matcher&& m) { return SizeMatchesMatcher<Matcher>{std::forward<Matcher>(m)}; } } // end namespace Matchers } // end namespace Catch #endif // CATCH_MATCHERS_CONTAINER_PROPERTIES_HPP_INCLUDED #ifndef CATCH_MATCHERS_CONTAINS_HPP_INCLUDED #define CATCH_MATCHERS_CONTAINS_HPP_INCLUDED #include <algorithm> #include <functional> #include <utility> namespace Catch { namespace Matchers { //! Matcher for checking that an element in range is equal to specific element template <typename T, typename Equality> class ContainsElementMatcher final : public MatcherGenericBase { T m_desired; Equality m_eq; public: template <typename T2, typename Equality2> ContainsElementMatcher(T2&& target, Equality2&& predicate): m_desired(std::forward<T2>(target)), m_eq(std::forward<Equality2>(predicate)) {} std::string describe() const override { return "contains element " + Catch::Detail::stringify(m_desired); } template <typename RangeLike> bool match(RangeLike&& rng) const { using std::begin; using std::end; return end(rng) != std::find_if(begin(rng), end(rng), [&](auto const& elem) { return m_eq(elem, m_desired); }); } }; //! Meta-matcher for checking that an element in a range matches a specific matcher template <typename Matcher> class ContainsMatcherMatcher final : public MatcherGenericBase { Matcher m_matcher; public: // Note that we do a copy+move to avoid having to SFINAE this // constructor (and also avoid some perfect forwarding failure // cases) ContainsMatcherMatcher(Matcher matcher): m_matcher(std::move(matcher)) {} template <typename RangeLike> bool match(RangeLike&& rng) const { using std::begin; using std::endl; for (auto&& elem : rng) { if (m_matcher.match(elem)) { return true; } } return false; } std::string describe() const override { return "contains element matching " + m_matcher.describe(); } }; /** * Creates a matcher that checks whether a range contains a specific element. * * Uses `std::equal_to` to do the comparison */ template <typename T> std::enable_if_t<!Detail::is_matcher<T>::value, ContainsElementMatcher<T, std::equal_to<>>> Contains(T&& elem) { return { std::forward<T>(elem), std::equal_to<>{} }; } //! Creates a matcher that checks whether a range contains element matching a matcher template <typename Matcher> std::enable_if_t<Detail::is_matcher<Matcher>::value, ContainsMatcherMatcher<Matcher>> Contains(Matcher&& matcher) { return { std::forward<Matcher>(matcher) }; } /** * Creates a matcher that checks whether a range contains a specific element. * * Uses `eq` to do the comparisons */ template <typename T, typename Equality> ContainsElementMatcher<T, Equality> Contains(T&& elem, Equality&& eq) { return { std::forward<T>(elem), std::forward<Equality>(eq) }; } } } #endif // CATCH_MATCHERS_CONTAINS_HPP_INCLUDED #ifndef CATCH_MATCHERS_EXCEPTION_HPP_INCLUDED #define CATCH_MATCHERS_EXCEPTION_HPP_INCLUDED namespace Catch { namespace Matchers { class ExceptionMessageMatcher final : public MatcherBase<std::exception> { std::string m_message; public: ExceptionMessageMatcher(std::string const& message): m_message(message) {} bool match(std::exception const& ex) const override; std::string describe() const override; }; //! Creates a matcher that checks whether a std derived exception has the provided message ExceptionMessageMatcher Message(std::string const& message); } // namespace Matchers } // namespace Catch #endif // CATCH_MATCHERS_EXCEPTION_HPP_INCLUDED #ifndef CATCH_MATCHERS_FLOATING_HPP_INCLUDED #define CATCH_MATCHERS_FLOATING_HPP_INCLUDED namespace Catch { namespace Matchers { namespace Detail { enum class FloatingPointKind : uint8_t; } struct WithinAbsMatcher final : MatcherBase<double> { WithinAbsMatcher(double target, double margin); bool match(double const& matchee) const override; std::string describe() const override; private: double m_target; double m_margin; }; struct WithinUlpsMatcher final : MatcherBase<double> { WithinUlpsMatcher(double target, uint64_t ulps, Detail::FloatingPointKind baseType); bool match(double const& matchee) const override; std::string describe() const override; private: double m_target; uint64_t m_ulps; Detail::FloatingPointKind m_type; }; // Given IEEE-754 format for floats and doubles, we can assume // that float -> double promotion is lossless. Given this, we can // assume that if we do the standard relative comparison of // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get // the same result if we do this for floats, as if we do this for // doubles that were promoted from floats. struct WithinRelMatcher final : MatcherBase<double> { WithinRelMatcher(double target, double epsilon); bool match(double const& matchee) const override; std::string describe() const override; private: double m_target; double m_epsilon; }; //! Creates a matcher that accepts doubles within certain ULP range of target WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff); //! Creates a matcher that accepts floats within certain ULP range of target WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff); //! Creates a matcher that accepts numbers within certain range of target WithinAbsMatcher WithinAbs(double target, double margin); //! Creates a matcher that accepts doubles within certain relative range of target WithinRelMatcher WithinRel(double target, double eps); //! Creates a matcher that accepts doubles within 100*DBL_EPS relative range of target WithinRelMatcher WithinRel(double target); //! Creates a matcher that accepts doubles within certain relative range of target WithinRelMatcher WithinRel(float target, float eps); //! Creates a matcher that accepts floats within 100*FLT_EPS relative range of target WithinRelMatcher WithinRel(float target); } // namespace Matchers } // namespace Catch #endif // CATCH_MATCHERS_FLOATING_HPP_INCLUDED #ifndef CATCH_MATCHERS_PREDICATE_HPP_INCLUDED #define CATCH_MATCHERS_PREDICATE_HPP_INCLUDED #include <string> #include <utility> namespace Catch { namespace Matchers { namespace Detail { std::string finalizeDescription(const std::string& desc); } // namespace Detail template <typename T, typename Predicate> class PredicateMatcher final : public MatcherBase<T> { Predicate m_predicate; std::string m_description; public: PredicateMatcher(Predicate&& elem, std::string const& descr) :m_predicate(std::forward<Predicate>(elem)), m_description(Detail::finalizeDescription(descr)) {} bool match( T const& item ) const override { return m_predicate(item); } std::string describe() const override { return m_description; } }; /** * Creates a matcher that calls delegates `match` to the provided predicate. * * The user has to explicitly specify the argument type to the matcher */ template<typename T, typename Pred> PredicateMatcher<T, Pred> Predicate(Pred&& predicate, std::string const& description = "") { static_assert(is_callable<Pred(T)>::value, "Predicate not callable with argument T"); static_assert(std::is_same<bool, FunctionReturnType<Pred, T>>::value, "Predicate does not return bool"); return PredicateMatcher<T, Pred>(std::forward<Pred>(predicate), description); } } // namespace Matchers } // namespace Catch #endif // CATCH_MATCHERS_PREDICATE_HPP_INCLUDED #ifndef CATCH_MATCHERS_STRING_HPP_INCLUDED #define CATCH_MATCHERS_STRING_HPP_INCLUDED #include <string> namespace Catch { namespace Matchers { struct CasedString { CasedString( std::string const& str, CaseSensitive caseSensitivity ); std::string adjustString( std::string const& str ) const; StringRef caseSensitivitySuffix() const; CaseSensitive m_caseSensitivity; std::string m_str; }; struct StringMatcherBase : MatcherBase<std::string> { StringMatcherBase( std::string const& operation, CasedString const& comparator ); std::string describe() const override; CasedString m_comparator; std::string m_operation; }; struct StringEqualsMatcher final : StringMatcherBase { StringEqualsMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct StringContainsMatcher final : StringMatcherBase { StringContainsMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct StartsWithMatcher final : StringMatcherBase { StartsWithMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct EndsWithMatcher final : StringMatcherBase { EndsWithMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct RegexMatcher final : MatcherBase<std::string> { RegexMatcher( std::string regex, CaseSensitive caseSensitivity ); bool match( std::string const& matchee ) const override; std::string describe() const override; private: std::string m_regex; CaseSensitive m_caseSensitivity; }; //! Creates matcher that accepts strings that are exactly equal to `str` StringEqualsMatcher Equals( std::string const& str, CaseSensitive caseSensitivity = CaseSensitive::Yes ); //! Creates matcher that accepts strings that contain `str` StringContainsMatcher Contains( std::string const& str, CaseSensitive caseSensitivity = CaseSensitive::Yes ); //! Creates matcher that accepts strings that _end_ with `str` EndsWithMatcher EndsWith( std::string const& str, CaseSensitive caseSensitivity = CaseSensitive::Yes ); //! Creates matcher that accepts strings that _start_ with `str` StartsWithMatcher StartsWith( std::string const& str, CaseSensitive caseSensitivity = CaseSensitive::Yes ); //! Creates matcher that accepts strings matching `regex` RegexMatcher Matches( std::string const& regex, CaseSensitive caseSensitivity = CaseSensitive::Yes ); } // namespace Matchers } // namespace Catch #endif // CATCH_MATCHERS_STRING_HPP_INCLUDED #ifndef CATCH_MATCHERS_VECTOR_HPP_INCLUDED #define CATCH_MATCHERS_VECTOR_HPP_INCLUDED #include <algorithm> namespace Catch { namespace Matchers { template<typename T, typename Alloc> struct VectorContainsElementMatcher final : MatcherBase<std::vector<T, Alloc>> { VectorContainsElementMatcher(T const& comparator): m_comparator(comparator) {} bool match(std::vector<T, Alloc> const& v) const override { for (auto const& el : v) { if (el == m_comparator) { return true; } } return false; } std::string describe() const override { return "Contains: " + ::Catch::Detail::stringify( m_comparator ); } T const& m_comparator; }; template<typename T, typename AllocComp, typename AllocMatch> struct ContainsMatcher final : MatcherBase<std::vector<T, AllocMatch>> { ContainsMatcher(std::vector<T, AllocComp> const& comparator): m_comparator( comparator ) {} bool match(std::vector<T, AllocMatch> const& v) const override { // !TBD: see note in EqualsMatcher if (m_comparator.size() > v.size()) return false; for (auto const& comparator : m_comparator) { auto present = false; for (const auto& el : v) { if (el == comparator) { present = true; break; } } if (!present) { return false; } } return true; } std::string describe() const override { return "Contains: " + ::Catch::Detail::stringify( m_comparator ); } std::vector<T, AllocComp> const& m_comparator; }; template<typename T, typename AllocComp, typename AllocMatch> struct EqualsMatcher final : MatcherBase<std::vector<T, AllocMatch>> { EqualsMatcher(std::vector<T, AllocComp> const& comparator): m_comparator( comparator ) {} bool match(std::vector<T, AllocMatch> const& v) const override { // !TBD: This currently works if all elements can be compared using != // - a more general approach would be via a compare template that defaults // to using !=. but could be specialised for, e.g. std::vector<T> etc // - then just call that directly if (m_comparator.size() != v.size()) return false; for (std::size_t i = 0; i < v.size(); ++i) if (m_comparator[i] != v[i]) return false; return true; } std::string describe() const override { return "Equals: " + ::Catch::Detail::stringify( m_comparator ); } std::vector<T, AllocComp> const& m_comparator; }; template<typename T, typename AllocComp, typename AllocMatch> struct ApproxMatcher final : MatcherBase<std::vector<T, AllocMatch>> { ApproxMatcher(std::vector<T, AllocComp> const& comparator): m_comparator( comparator ) {} bool match(std::vector<T, AllocMatch> const& v) const override { if (m_comparator.size() != v.size()) return false; for (std::size_t i = 0; i < v.size(); ++i) if (m_comparator[i] != approx(v[i])) return false; return true; } std::string describe() const override { return "is approx: " + ::Catch::Detail::stringify( m_comparator ); } template <typename = std::enable_if_t<std::is_constructible<double, T>::value>> ApproxMatcher& epsilon( T const& newEpsilon ) { approx.epsilon(static_cast<double>(newEpsilon)); return *this; } template <typename = std::enable_if_t<std::is_constructible<double, T>::value>> ApproxMatcher& margin( T const& newMargin ) { approx.margin(static_cast<double>(newMargin)); return *this; } template <typename = std::enable_if_t<std::is_constructible<double, T>::value>> ApproxMatcher& scale( T const& newScale ) { approx.scale(static_cast<double>(newScale)); return *this; } std::vector<T, AllocComp> const& m_comparator; mutable Catch::Approx approx = Catch::Approx::custom(); }; template<typename T, typename AllocComp, typename AllocMatch> struct UnorderedEqualsMatcher final : MatcherBase<std::vector<T, AllocMatch>> { UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target): m_target(target) {} bool match(std::vector<T, AllocMatch> const& vec) const override { if (m_target.size() != vec.size()) { return false; } return std::is_permutation(m_target.begin(), m_target.end(), vec.begin()); } std::string describe() const override { return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target); } private: std::vector<T, AllocComp> const& m_target; }; // The following functions create the actual matcher objects. // This allows the types to be inferred //! Creates a matcher that matches vectors that contain all elements in `comparator` template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp> ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) { return ContainsMatcher<T, AllocComp, AllocMatch>(comparator); } //! Creates a matcher that matches vectors that contain `comparator` as an element template<typename T, typename Alloc = std::allocator<T>> VectorContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) { return VectorContainsElementMatcher<T, Alloc>(comparator); } //! Creates a matcher that matches vectors that are exactly equal to `comparator` template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp> EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) { return EqualsMatcher<T, AllocComp, AllocMatch>(comparator); } //! Creates a matcher that matches vectors that `comparator` as an element template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp> ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) { return ApproxMatcher<T, AllocComp, AllocMatch>(comparator); } //! Creates a matcher that matches vectors that is equal to `target` modulo permutation template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp> UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) { return UnorderedEqualsMatcher<T, AllocComp, AllocMatch>(target); } } // namespace Matchers } // namespace Catch #endif // CATCH_MATCHERS_VECTOR_HPP_INCLUDED #endif // CATCH_MATCHERS_ALL_HPP_INCLUDED /** \file * This is a convenience header for Catch2's Reporter support. It includes * **all** of Catch2 headers related to reporters, including all reporters. * * Generally the Catch2 users should use specific includes they need, * but this header can be used instead for ease-of-experimentation, or * just plain convenience, at the cost of (significantly) increased * compilation times. * * When a new header (reporter) is added to either the `reporter` folder, * or to the corresponding internal subfolder, it should be added here. */ #ifndef CATCH_REPORTERS_ALL_HPP_INCLUDED #define CATCH_REPORTERS_ALL_HPP_INCLUDED #ifndef CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED #define CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED #ifndef CATCH_REPORTER_STREAMING_BASE_HPP_INCLUDED #define CATCH_REPORTER_STREAMING_BASE_HPP_INCLUDED #include <iosfwd> #include <string> #include <vector> namespace Catch { template<typename T> struct LazyStat : Option<T> { LazyStat& operator=(T const& _value) { Option<T>::operator=(_value); used = false; return *this; } void reset() { Option<T>::reset(); used = false; } bool used = false; }; struct StreamingReporterBase : IStreamingReporter { StreamingReporterBase( ReporterConfig const& _config ): m_config( _config.fullConfig() ), stream( _config.stream() ) { } ~StreamingReporterBase() override; void noMatchingTestCases(std::string const&) override {} void reportInvalidArguments(std::string const&) override {} void testRunStarting( TestRunInfo const& _testRunInfo ) override; void testGroupStarting( GroupInfo const& _groupInfo ) override; void testCaseStarting(TestCaseInfo const& _testInfo) override { currentTestCaseInfo = &_testInfo; } void sectionStarting(SectionInfo const& _sectionInfo) override { m_sectionStack.push_back(_sectionInfo); } void sectionEnded(SectionStats const& /* _sectionStats */) override { m_sectionStack.pop_back(); } void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override { currentTestCaseInfo = nullptr; } void testGroupEnded( TestGroupStats const& ) override; void testRunEnded( TestRunStats const& /* _testRunStats */ ) override; void skipTest(TestCaseInfo const&) override { // Don't do anything with this by default. // It can optionally be overridden in the derived class. } IConfig const* m_config; std::ostream& stream; LazyStat<TestRunInfo> currentTestRunInfo; LazyStat<GroupInfo> currentGroupInfo; TestCaseInfo const* currentTestCaseInfo = nullptr; std::vector<SectionInfo> m_sectionStack; }; } // end namespace Catch #endif // CATCH_REPORTER_STREAMING_BASE_HPP_INCLUDED namespace Catch { struct AutomakeReporter : StreamingReporterBase { AutomakeReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ) {} ~AutomakeReporter() override; static std::string getDescription() { using namespace std::string_literals; return "Reports test results in the format of Automake .trs files"s; } void assertionStarting( AssertionInfo const& ) override {} bool assertionEnded( AssertionStats const& /*_assertionStats*/ ) override { return true; } void testCaseEnded(TestCaseStats const& _testCaseStats) override; void skipTest(TestCaseInfo const& testInfo) override; }; } // end namespace Catch #endif // CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED #ifndef CATCH_REPORTER_COMPACT_HPP_INCLUDED #define CATCH_REPORTER_COMPACT_HPP_INCLUDED namespace Catch { struct CompactReporter : StreamingReporterBase { using StreamingReporterBase::StreamingReporterBase; ~CompactReporter() override; static std::string getDescription(); void noMatchingTestCases(std::string const& spec) override; void assertionStarting(AssertionInfo const&) override; bool assertionEnded(AssertionStats const& _assertionStats) override; void sectionEnded(SectionStats const& _sectionStats) override; void testRunEnded(TestRunStats const& _testRunStats) override; }; } // end namespace Catch #endif // CATCH_REPORTER_COMPACT_HPP_INCLUDED #ifndef CATCH_REPORTER_CONSOLE_HPP_INCLUDED #define CATCH_REPORTER_CONSOLE_HPP_INCLUDED #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch // Note that 4062 (not all labels are handled // and default is missing) is enabled #endif namespace Catch { // Fwd decls struct SummaryColumn; class TablePrinter; struct ConsoleReporter : StreamingReporterBase { Detail::unique_ptr<TablePrinter> m_tablePrinter; ConsoleReporter(ReporterConfig const& config); ~ConsoleReporter() override; static std::string getDescription(); void noMatchingTestCases(std::string const& spec) override; void reportInvalidArguments(std::string const&arg) override; void assertionStarting(AssertionInfo const&) override; bool assertionEnded(AssertionStats const& _assertionStats) override; void sectionStarting(SectionInfo const& _sectionInfo) override; void sectionEnded(SectionStats const& _sectionStats) override; void benchmarkPreparing(std::string const& name) override; void benchmarkStarting(BenchmarkInfo const& info) override; void benchmarkEnded(BenchmarkStats<> const& stats) override; void benchmarkFailed(std::string const& error) override; void testCaseEnded(TestCaseStats const& _testCaseStats) override; void testGroupEnded(TestGroupStats const& _testGroupStats) override; void testRunEnded(TestRunStats const& _testRunStats) override; void testRunStarting(TestRunInfo const& _testRunInfo) override; private: void lazyPrint(); void lazyPrintWithoutClosingBenchmarkTable(); void lazyPrintRunInfo(); void lazyPrintGroupInfo(); void printTestCaseAndSectionHeader(); void printClosedHeader(std::string const& _name); void printOpenHeader(std::string const& _name); // if string has a : in first line will set indent to follow it on // subsequent lines void printHeaderString(std::string const& _string, std::size_t indent = 0); void printTotals(Totals const& totals); void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row); void printTotalsDivider(Totals const& totals); void printSummaryDivider(); void printTestFilters(); private: bool m_headerPrinted = false; }; } // end namespace Catch #if defined(_MSC_VER) #pragma warning(pop) #endif #endif // CATCH_REPORTER_CONSOLE_HPP_INCLUDED #ifndef CATCH_REPORTER_CUMULATIVE_BASE_HPP_INCLUDED #define CATCH_REPORTER_CUMULATIVE_BASE_HPP_INCLUDED #include <iosfwd> #include <memory> #include <string> #include <vector> namespace Catch { struct CumulativeReporterBase : IStreamingReporter { template<typename T, typename ChildNodeT> struct Node { explicit Node( T const& _value ) : value( _value ) {} virtual ~Node() {} using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>; T value; ChildNodes children; }; struct SectionNode { explicit SectionNode(SectionStats const& _stats) : stats(_stats) {} bool operator == (SectionNode const& other) const { return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; } SectionStats stats; using ChildSections = std::vector<std::shared_ptr<SectionNode>>; using Assertions = std::vector<AssertionStats>; ChildSections childSections; Assertions assertions; std::string stdOut; std::string stdErr; }; using TestCaseNode = Node<TestCaseStats, SectionNode>; using TestGroupNode = Node<TestGroupStats, TestCaseNode>; using TestRunNode = Node<TestRunStats, TestGroupNode>; CumulativeReporterBase( ReporterConfig const& _config ): m_config( _config.fullConfig() ), stream( _config.stream() ) {} ~CumulativeReporterBase() override; void testRunStarting( TestRunInfo const& ) override {} void testGroupStarting( GroupInfo const& ) override {} void testCaseStarting( TestCaseInfo const& ) override {} void sectionStarting( SectionInfo const& sectionInfo ) override; void assertionStarting( AssertionInfo const& ) override {} bool assertionEnded( AssertionStats const& assertionStats ) override; void sectionEnded( SectionStats const& sectionStats ) override; void testCaseEnded( TestCaseStats const& testCaseStats ) override; void testGroupEnded( TestGroupStats const& testGroupStats ) override; void testRunEnded( TestRunStats const& testRunStats ) override; virtual void testRunEndedCumulative() = 0; void skipTest(TestCaseInfo const&) override {} IConfig const* m_config; std::ostream& stream; std::vector<AssertionStats> m_assertions; std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections; std::vector<std::shared_ptr<TestCaseNode>> m_testCases; std::vector<std::shared_ptr<TestGroupNode>> m_testGroups; std::vector<std::shared_ptr<TestRunNode>> m_testRuns; std::shared_ptr<SectionNode> m_rootSection; std::shared_ptr<SectionNode> m_deepestSection; std::vector<std::shared_ptr<SectionNode>> m_sectionStack; }; } // end namespace Catch #endif // CATCH_REPORTER_CUMULATIVE_BASE_HPP_INCLUDED #ifndef CATCH_REPORTER_EVENT_LISTENER_HPP_INCLUDED #define CATCH_REPORTER_EVENT_LISTENER_HPP_INCLUDED namespace Catch { /** * Base class identifying listeners. * * Provides default implementation for all IStreamingReporter member * functions, so that listeners implementations can pick which * member functions it actually cares about. */ class EventListenerBase : public IStreamingReporter { IConfig const* m_config; public: EventListenerBase( ReporterConfig const& config ): m_config( config.fullConfig() ) {} void assertionStarting( AssertionInfo const& assertionInfo ) override; bool assertionEnded( AssertionStats const& assertionStats ) override; void listReporters( std::vector<ReporterDescription> const& descriptions, IConfig const& config ) override; void listTests( std::vector<TestCaseHandle> const& tests, IConfig const& config ) override; void listTags( std::vector<TagInfo> const& tagInfos, IConfig const& config ) override; void noMatchingTestCases( std::string const& spec ) override; void testRunStarting( TestRunInfo const& testRunInfo ) override; void testGroupStarting( GroupInfo const& groupInfo ) override; void testCaseStarting( TestCaseInfo const& testInfo ) override; void sectionStarting( SectionInfo const& sectionInfo ) override; void sectionEnded( SectionStats const& sectionStats ) override; void testCaseEnded( TestCaseStats const& testCaseStats ) override; void testGroupEnded( TestGroupStats const& testGroupStats ) override; void testRunEnded( TestRunStats const& testRunStats ) override; void skipTest( TestCaseInfo const& testInfo ) override; }; } // end namespace Catch #endif // CATCH_REPORTER_EVENT_LISTENER_HPP_INCLUDED #ifndef CATCH_REPORTER_HELPERS_HPP_INCLUDED #define CATCH_REPORTER_HELPERS_HPP_INCLUDED #include <iosfwd> #include <string> #include <vector> namespace Catch { struct IConfig; // Returns double formatted as %.3f (format expected on output) std::string getFormattedDuration( double duration ); //! Should the reporter show duration of test given current configuration? bool shouldShowDuration( IConfig const& config, double duration ); std::string serializeFilters( std::vector<std::string> const& filters ); struct lineOfChars { char c; constexpr lineOfChars( char c_ ): c( c_ ) {} friend std::ostream& operator<<( std::ostream& out, lineOfChars value ); }; } // end namespace Catch #endif // CATCH_REPORTER_HELPERS_HPP_INCLUDED #ifndef CATCH_REPORTER_JUNIT_HPP_INCLUDED #define CATCH_REPORTER_JUNIT_HPP_INCLUDED namespace Catch { class JunitReporter : public CumulativeReporterBase { public: JunitReporter(ReporterConfig const& _config); ~JunitReporter() override; static std::string getDescription(); void noMatchingTestCases(std::string const& /*spec*/) override; void testRunStarting(TestRunInfo const& runInfo) override; void testGroupStarting(GroupInfo const& groupInfo) override; void testCaseStarting(TestCaseInfo const& testCaseInfo) override; bool assertionEnded(AssertionStats const& assertionStats) override; void testCaseEnded(TestCaseStats const& testCaseStats) override; void testGroupEnded(TestGroupStats const& testGroupStats) override; void testRunEndedCumulative() override; void writeGroup(TestGroupNode const& groupNode, double suiteTime); void writeTestCase(TestCaseNode const& testCaseNode); void writeSection(std::string const& className, std::string const& rootName, SectionNode const& sectionNode); void writeAssertions(SectionNode const& sectionNode); void writeAssertion(AssertionStats const& stats); XmlWriter xml; Timer suiteTimer; std::string stdOutForSuite; std::string stdErrForSuite; unsigned int unexpectedExceptions = 0; bool m_okToFail = false; }; } // end namespace Catch #endif // CATCH_REPORTER_JUNIT_HPP_INCLUDED #ifndef CATCH_REPORTER_LISTENING_HPP_INCLUDED #define CATCH_REPORTER_LISTENING_HPP_INCLUDED namespace Catch { class ListeningReporter final : public IStreamingReporter { using Reporters = std::vector<IStreamingReporterPtr>; Reporters m_listeners; IStreamingReporterPtr m_reporter = nullptr; public: ListeningReporter(); void addListener( IStreamingReporterPtr&& listener ); void addReporter( IStreamingReporterPtr&& reporter ); public: // IStreamingReporter void noMatchingTestCases( std::string const& spec ) override; void reportInvalidArguments(std::string const&arg) override; void benchmarkPreparing(std::string const& name) override; void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override; void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override; void benchmarkFailed(std::string const&) override; void testRunStarting( TestRunInfo const& testRunInfo ) override; void testGroupStarting( GroupInfo const& groupInfo ) override; void testCaseStarting( TestCaseInfo const& testInfo ) override; void sectionStarting( SectionInfo const& sectionInfo ) override; void assertionStarting( AssertionInfo const& assertionInfo ) override; // The return value indicates if the messages buffer should be cleared: bool assertionEnded( AssertionStats const& assertionStats ) override; void sectionEnded( SectionStats const& sectionStats ) override; void testCaseEnded( TestCaseStats const& testCaseStats ) override; void testGroupEnded( TestGroupStats const& testGroupStats ) override; void testRunEnded( TestRunStats const& testRunStats ) override; void skipTest( TestCaseInfo const& testInfo ) override; void listReporters(std::vector<ReporterDescription> const& descriptions, IConfig const& config) override; void listTests(std::vector<TestCaseHandle> const& tests, IConfig const& config) override; void listTags(std::vector<TagInfo> const& tags, IConfig const& config) override; }; } // end namespace Catch #endif // CATCH_REPORTER_LISTENING_HPP_INCLUDED #ifndef CATCH_REPORTER_SONARQUBE_HPP_INCLUDED #define CATCH_REPORTER_SONARQUBE_HPP_INCLUDED namespace Catch { struct SonarQubeReporter : CumulativeReporterBase { SonarQubeReporter(ReporterConfig const& config) : CumulativeReporterBase(config) , xml(config.stream()) { m_preferences.shouldRedirectStdOut = true; m_preferences.shouldReportAllAssertions = true; } ~SonarQubeReporter() override; static std::string getDescription() { using namespace std::string_literals; return "Reports test results in the Generic Test Data SonarQube XML format"s; } void noMatchingTestCases(std::string const& /*spec*/) override {} void testRunStarting(TestRunInfo const& testRunInfo) override; void testGroupEnded(TestGroupStats const& testGroupStats) override; void testRunEndedCumulative() override { xml.endElement(); } void writeGroup(TestGroupNode const& groupNode); void writeTestFile(std::string const& filename, TestGroupNode::ChildNodes const& testCaseNodes); void writeTestCase(TestCaseNode const& testCaseNode); void writeSection(std::string const& rootName, SectionNode const& sectionNode, bool okToFail); void writeAssertions(SectionNode const& sectionNode, bool okToFail); void writeAssertion(AssertionStats const& stats, bool okToFail); private: XmlWriter xml; }; } // end namespace Catch #endif // CATCH_REPORTER_SONARQUBE_HPP_INCLUDED #ifndef CATCH_REPORTER_TAP_HPP_INCLUDED #define CATCH_REPORTER_TAP_HPP_INCLUDED namespace Catch { struct TAPReporter : StreamingReporterBase { TAPReporter( ReporterConfig const& config ): StreamingReporterBase( config ) { m_preferences.shouldReportAllAssertions = true; } ~TAPReporter() override; static std::string getDescription() { using namespace std::string_literals; return "Reports test results in TAP format, suitable for test harnesses"s; } void noMatchingTestCases(std::string const& spec) override; void assertionStarting( AssertionInfo const& ) override {} bool assertionEnded(AssertionStats const& _assertionStats) override; void testRunEnded(TestRunStats const& _testRunStats) override; private: std::size_t counter = 0; }; } // end namespace Catch #endif // CATCH_REPORTER_TAP_HPP_INCLUDED #ifndef CATCH_REPORTER_TEAMCITY_HPP_INCLUDED #define CATCH_REPORTER_TEAMCITY_HPP_INCLUDED #include <cstring> #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wpadded" #endif namespace Catch { struct TeamCityReporter : StreamingReporterBase { TeamCityReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ) { m_preferences.shouldRedirectStdOut = true; } ~TeamCityReporter() override; static std::string getDescription() { using namespace std::string_literals; return "Reports test results as TeamCity service messages"s; } void skipTest( TestCaseInfo const& /* testInfo */ ) override {} void noMatchingTestCases( std::string const& /* spec */ ) override {} void testGroupStarting(GroupInfo const& groupInfo) override; void testGroupEnded(TestGroupStats const& testGroupStats) override; void assertionStarting(AssertionInfo const&) override {} bool assertionEnded(AssertionStats const& assertionStats) override; void sectionStarting(SectionInfo const& sectionInfo) override { m_headerPrintedForThisSection = false; StreamingReporterBase::sectionStarting( sectionInfo ); } void testCaseStarting(TestCaseInfo const& testInfo) override; void testCaseEnded(TestCaseStats const& testCaseStats) override; private: void printSectionHeader(std::ostream& os); private: bool m_headerPrintedForThisSection = false; Timer m_testTimer; }; } // end namespace Catch #ifdef __clang__ # pragma clang diagnostic pop #endif #endif // CATCH_REPORTER_TEAMCITY_HPP_INCLUDED #ifndef CATCH_REPORTER_XML_HPP_INCLUDED #define CATCH_REPORTER_XML_HPP_INCLUDED namespace Catch { class XmlReporter : public StreamingReporterBase { public: XmlReporter(ReporterConfig const& _config); ~XmlReporter() override; static std::string getDescription(); virtual std::string getStylesheetRef() const; void writeSourceInfo(SourceLineInfo const& sourceInfo); public: // StreamingReporterBase void noMatchingTestCases(std::string const& s) override; void testRunStarting(TestRunInfo const& testInfo) override; void testGroupStarting(GroupInfo const& groupInfo) override; void testCaseStarting(TestCaseInfo const& testInfo) override; void sectionStarting(SectionInfo const& sectionInfo) override; void assertionStarting(AssertionInfo const&) override; bool assertionEnded(AssertionStats const& assertionStats) override; void sectionEnded(SectionStats const& sectionStats) override; void testCaseEnded(TestCaseStats const& testCaseStats) override; void testGroupEnded(TestGroupStats const& testGroupStats) override; void testRunEnded(TestRunStats const& testRunStats) override; void benchmarkPreparing(std::string const& name) override; void benchmarkStarting(BenchmarkInfo const&) override; void benchmarkEnded(BenchmarkStats<> const&) override; void benchmarkFailed(std::string const&) override; void listReporters(std::vector<ReporterDescription> const& descriptions, IConfig const& config) override; void listTests(std::vector<TestCaseHandle> const& tests, IConfig const& config) override; void listTags(std::vector<TagInfo> const& tags, IConfig const& config) override; private: Timer m_testCaseTimer; XmlWriter m_xml; int m_sectionDepth = 0; }; } // end namespace Catch #endif // CATCH_REPORTER_XML_HPP_INCLUDED #endif // CATCH_REPORTERS_ALL_HPP_INCLUDED #endif // CATCH_ALL_HPP_INCLUDED #endif // CATCH_AMALGAMATED_HPP_INCLUDED
[ "thimovandermeer@gmail.com" ]
thimovandermeer@gmail.com
6119b04067b23b9de9db70e7cca8838b4f6835ab
215111e92a3dfc535ce1c1ce25a35fb6003ab575
/cf/german_2017/e.cpp
c6f6f31593fdecfbf61beab45b676e33c01075a5
[]
no_license
emanueljuliano/Competitive_Programming
6e65aa696fb2bb0e2251e5a68657f4c79cd8f803
86fefe4d0e3ee09b5766acddc8c78ed8b60402d6
refs/heads/master
2023-06-23T04:52:43.910062
2021-06-26T11:34:42
2021-06-26T11:34:42
299,115,304
0
0
null
null
null
null
UTF-8
C++
false
false
1,421
cpp
#include <bits/stdc++.h> using namespace std; #define _ ios_base::sync_with_stdio(0);cin.tie(0); //#define endl '\n' #define f first #define s second #define pb push_back typedef long long ll; typedef double ld; typedef pair<int, int> ii; const int INF = 0x3f3f3f3f; const ll LINF = 0x3f3f3f3f3f3f3f3fll; bool show; int sz; typedef vector<vector<ld> > mat; mat idty() { mat id(sz, vector<ld>(sz,0)); for(int i=0; i<sz; i++) id[i][i] = 1; return id; } mat z; void mmul(mat &x, mat &y) { for(int i=0; i<sz; i++) for(int j=0; j<sz; j++) z[i][j] = 0; for(int i=0; i < sz; i++) for(int j=0; j < sz; j++) for(int k=0; k < sz; k++) z[i][j] += x[i][k]*y[k][j]; for(int i=0;i <sz; i++) for(int j=0;j <sz; j++) x[i][j] = z[i][j]; } mat z2(sz,vector<ld>(sz)); void mfexp(mat &x, ll y) { z2 = idty(); while (y) { if (y & 1) mmul(z2,x); y >>= 1; mmul(x,x); } for(int i=0;i <sz; i++) for(int j=0;j <sz; j++) x[i][j] = z2[i][j]; } int main(){ _ int n, m; cin >> n >> m; sz = n; z = mat(sz, vector<ld>(sz,0)); vector M(n, vector<ld> (n)); for(int i=0;i <m; i++){ int a, b; ld c; cin >> a >> b >> c; a--, b--; M[a][b] = c; } show = true; mfexp(M, 800); // cout << "DIAG: "; for(int i=0;i <n; i++){ // cout << M[i][i] << " "; if(M[i][i] >= 1.1) show = false; } // cout << endl; if(show) cout << "admissible" << endl; else cout << "inadmissible" << endl; exit(0); }
[ "emanueljulianoms@gmail.com" ]
emanueljulianoms@gmail.com
aa4e36bf61f4cb04c90c0bd56c98ebdd6f8f7d32
7c64360b6e32f8576344048db7b9938ea722dedd
/npy/tests/NSceneMeshTest.cc
2010c03804ff62bb209787ed25a0804f88cef6f4
[ "Apache-2.0" ]
permissive
recepkandemir/opticks
4be08a9243c3e0abe82eca77be70178e6384e555
523387f7593676bab58de22d22049e650de3f5c3
refs/heads/master
2023-01-24T16:55:04.131498
2020-12-04T20:25:09
2020-12-04T20:25:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,967
cc
/* * Copyright (c) 2019 Opticks Team. All Rights Reserved. * * This file is part of Opticks * (see https://bitbucket.org/simoncblyth/opticks). * * 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 "SSys.hh" #include "BOpticksResource.hh" #include "NGLTF.hpp" #include "NScene.hpp" #include "NSceneConfig.hpp" #include "NPY.hpp" #include "OPTICKS_LOG.hh" int main(int argc, char** argv) { OPTICKS_LOG(argc, argv); BOpticksResource okr ; // no Opticks at this level const char* dbgmesh = SSys::getenvvar("DBGMESH"); int dbgnode = SSys::getenvint("DBGNODE", -1) ; const char* gltfbase = argc > 1 ? argv[1] : okr.getDebuggingIDFOLD() ; const char* gltfname = "g4_00.gltf" ; const char* gltfconfig = "check_surf_containment=0,check_aabb_containment=0" ; LOG(info) << argv[0] << " gltfbase " << gltfbase << " gltfname " << gltfname << " gltfconfig " << gltfconfig ; if(!NGLTF::Exists(gltfbase, gltfname)) { LOG(warning) << "no such scene at" << " base " << gltfbase << " name " << gltfname ; return 0 ; } const char* idfold = NULL ; NSceneConfig* config = new NSceneConfig(gltfconfig); NScene* scene = NScene::Load( gltfbase, gltfname, idfold, config, dbgnode ); assert(scene); scene->dumpCSG(dbgmesh); return 0 ; }
[ "simoncblyth@gmail.com" ]
simoncblyth@gmail.com
b82a316a815dfc90ce178de7caa5541ad0ab5d12
cdd8ff6d49072f51492ecc98219ac54a5e30ac4a
/Urho2DSprite.cpp
ed9df4a9a5582b874d2e44e6679ed3eed1d94357
[]
no_license
Ribis84/MyFirstProgrammUrho3d
c72b85931384f372268ded58ea2ea60b679f61a1
602881ee9d4b2be4ff47a6253c9918c73ea83b33
refs/heads/master
2022-11-22T11:19:37.426621
2020-07-21T09:13:29
2020-07-21T09:13:29
281,345,160
0
0
null
null
null
null
UTF-8
C++
false
false
8,480
cpp
// // Copyright (c) 2008-2020 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include <Urho3D/Core/CoreEvents.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/Graphics/Camera.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/Octree.h> #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Graphics/Zone.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/UI/Font.h> #include <Urho3D/UI/Text.h> #include <Urho3D/Urho2D/AnimatedSprite2D.h> #include <Urho3D/Urho2D/AnimationSet2D.h> #include <Urho3D/Urho2D/Sprite2D.h> #include "Urho2DSprite.h" #include <Urho3D/DebugNew.h> // Number of static sprites to draw static const unsigned NUM_SPRITES = 200; static const StringHash VAR_MOVESPEED("MoveSpeed"); static const StringHash VAR_ROTATESPEED("RotateSpeed"); URHO3D_DEFINE_APPLICATION_MAIN(Urho2DSprite) Urho2DSprite::Urho2DSprite(Context* context) : Sample(context) { } void Urho2DSprite::Start() { // Execute base class startup Sample::Start(); // Create the scene content CreateScene(); // Create the UI content CreateInstructions(); // Setup the viewport for displaying the scene SetupViewport(); // Hook up to the frame update events SubscribeToEvents(); // Set the mouse mode to use in the sample Sample::InitMouseMode(MM_FREE); } void Urho2DSprite::CreateScene() { scene_ = new Scene(context_); scene_->CreateComponent<Octree>(); // Create camera node cameraNode_ = scene_->CreateChild("Camera"); // Set camera's position cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -10.0f)); auto* camera = cameraNode_->CreateComponent<Camera>(); camera->SetOrthographic(true); auto* graphics = GetSubsystem<Graphics>(); camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE); auto* cache = GetSubsystem<ResourceCache>(); // Get sprite auto* sprite = cache->GetResource<Sprite2D>("Urho2D/Aster.png"); if (!sprite) return; float halfWidth = graphics->GetWidth() * 0.5f * PIXEL_SIZE; float halfHeight = graphics->GetHeight() * 0.5f * PIXEL_SIZE; for (unsigned i = 0; i < NUM_SPRITES; ++i) { SharedPtr<Node> spriteNode(scene_->CreateChild("StaticSprite2D")); spriteNode->SetPosition(Vector3(Random(-halfWidth, halfWidth), Random(-halfHeight, halfHeight), 0.0f)); auto* staticSprite = spriteNode->CreateComponent<StaticSprite2D>(); // Set random color staticSprite->SetColor(Color(Random(1.0f), Random(1.0f), Random(1.0f), 1.0f)); // Set blend mode staticSprite->SetBlendMode(BLEND_ALPHA); // Set sprite staticSprite->SetSprite(sprite); // Set move speed spriteNode->SetVar(VAR_MOVESPEED, Vector3(Random(-2.0f, 2.0f), Random(-2.0f, 2.0f), 0.0f)); // Set rotate speed spriteNode->SetVar(VAR_ROTATESPEED, Random(-90.0f, 90.0f)); // Add to sprite node vector spriteNodes_.Push(spriteNode); } // Get animation set auto* animationSet = cache->GetResource<AnimationSet2D>("Urho2D/GoldIcon.scml"); if (!animationSet) return; SharedPtr<Node> spriteNode(scene_->CreateChild("AnimatedSprite2D")); spriteNode->SetPosition(Vector3(0.0f, 0.0f, -1.0f)); auto* animatedSprite = spriteNode->CreateComponent<AnimatedSprite2D>(); // Set animation animatedSprite->SetAnimationSet(animationSet); animatedSprite->SetAnimation("idle"); } void Urho2DSprite::CreateInstructions() { auto* cache = GetSubsystem<ResourceCache>(); auto* ui = GetSubsystem<UI>(); // Construct new Text object, set string to display and font to use auto* instructionText = ui->GetRoot()->CreateChild<Text>(); instructionText->SetText("Use WASD keys to move, use PageUp PageDown keys to zoom."); instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15); // Position the text relative to the screen center instructionText->SetHorizontalAlignment(HA_CENTER); instructionText->SetVerticalAlignment(VA_CENTER); instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4); } void Urho2DSprite::SetupViewport() { auto* renderer = GetSubsystem<Renderer>(); // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>())); renderer->SetViewport(0, viewport); } void Urho2DSprite::MoveCamera(float timeStep) { // Do not move if the UI has a focused element (the console) if (GetSubsystem<UI>()->GetFocusElement()) return; auto* input = GetSubsystem<Input>(); // Movement speed as world units per second const float MOVE_SPEED = 4.0f; // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if (input->GetKeyDown(KEY_W)) cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep); if (input->GetKeyDown(KEY_S)) cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep); if (input->GetKeyDown(KEY_A)) cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep); if (input->GetKeyDown(KEY_D)) cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep); if (input->GetKeyDown(KEY_PAGEUP)) { auto* camera = cameraNode_->GetComponent<Camera>(); camera->SetZoom(camera->GetZoom() * 1.01f); } if (input->GetKeyDown(KEY_PAGEDOWN)) { auto* camera = cameraNode_->GetComponent<Camera>(); camera->SetZoom(camera->GetZoom() * 0.99f); } } void Urho2DSprite::SubscribeToEvents() { // Subscribe HandleUpdate() function for processing update events SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Urho2DSprite, HandleUpdate)); // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample UnsubscribeFromEvent(E_SCENEUPDATE); } void Urho2DSprite::HandleUpdate(StringHash eventType, VariantMap& eventData) { using namespace Update; // Take the frame time step, which is stored as a float float timeStep = eventData[P_TIMESTEP].GetFloat(); // Move the camera, scale movement with time step MoveCamera(timeStep); auto* graphics = GetSubsystem<Graphics>(); float halfWidth = (float)graphics->GetWidth() * 0.5f * PIXEL_SIZE; float halfHeight = (float)graphics->GetHeight() * 0.5f * PIXEL_SIZE; for (unsigned i = 0; i < spriteNodes_.Size(); ++i) { SharedPtr<Node> node = spriteNodes_[i]; Vector3 position = node->GetPosition(); Vector3 moveSpeed = node->GetVar(VAR_MOVESPEED).GetVector3(); Vector3 newPosition = position + moveSpeed * timeStep; if (newPosition.x_ < -halfWidth || newPosition.x_ > halfWidth) { newPosition.x_ = position.x_; moveSpeed.x_ = -moveSpeed.x_; node->SetVar(VAR_MOVESPEED, moveSpeed); } if (newPosition.y_ < -halfHeight || newPosition.y_ > halfHeight) { newPosition.y_ = position.y_; moveSpeed.y_ = -moveSpeed.y_; node->SetVar(VAR_MOVESPEED, moveSpeed); } node->SetPosition(newPosition); float rotateSpeed = node->GetVar(VAR_ROTATESPEED).GetFloat(); node->Roll(rotateSpeed * timeStep); } }
[ "ivanmik80@gmail.com" ]
ivanmik80@gmail.com
76f45b9d5ad38bf0a7236222bed25c4b40977b79
973422e8a0ea40474b46082bbb5a146fa762e19c
/★winApi/ShapeGame/ShapeGame/stdafx.h
98b09b821666ae3f34f68aad895f9989c4ef9dc6
[]
no_license
YunHoseon/InhaStudy
45e0e7671dc09b313a1b3b4281dead93d8f33633
edde0627d335a2cf83dd369b6a3b0b96d6aa4461
refs/heads/master
2022-12-08T16:03:25.194855
2020-09-14T19:19:10
2020-09-14T19:19:10
273,371,294
0
0
null
null
null
null
UTF-8
C++
false
false
624
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> // C RunTime Header Files #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include <iostream> #include <vector> #include <time.h> // TODO: reference additional headers your program requires here #include "Shape.h" #define PI 3.14159187 POINT point[10];
[ "hosun2776@gmail.com" ]
hosun2776@gmail.com
d53323eb44c7655755db5b0495523b03a7750a39
0fa0c8e456d4e4c2bc60543d47ae331feaebfeac
/src/OmniDrive.cpp
f84b13041ccc6f70903da167ba1975e0b7692e8b
[]
no_license
SkyeOfBreeze/ArduinoOmniBot
2baef2f1a58620b80e18537e4cf081a16243cead
c474bb648dd0dd4845df5e643ce9234c2a59a910
refs/heads/main
2023-06-11T08:54:25.519080
2020-09-21T01:31:01
2020-09-21T01:31:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,168
cpp
#include "math.h" #include <Arduino.h> struct OmniDrive { /* data */ private: float wheel[10]; float wheelCount; float xJoy, yJoy; float thetaJoy, rJoy; float speed; public: float maxSpeed = .6f; float b = 1; //TODO this is a constant defined to scale based on https://robotics.stackexchange.com/questions/7829 void supplyJoy(float x, float y){ xJoy = x; yJoy = y; thetaJoy = atan2(xJoy, yJoy); rJoy = sqrt(yJoy*yJoy + xJoy*xJoy); speed = maxSpeed*rJoy/b; } void supplyDirectional(float theta, float r){ thetaJoy = theta; rJoy = r; speed = maxSpeed*rJoy/b; } void registerWheels(float wheelAngles[], int size){ OmniDrive::wheelCount = size; for(int i = 0; i < size; i++){ wheel[i] = wheelAngles[i]; } } float getWheelSpeed(int wheelPos){ float theta = wheel[wheelPos] - thetaJoy; return speed*sin(theta); } void zero(){ xJoy = 0; yJoy = 0; thetaJoy = atan2(xJoy, yJoy); rJoy = sqrt(yJoy*yJoy + xJoy*xJoy); speed = 0; } };
[ "b.telman01@gmail.com" ]
b.telman01@gmail.com
2ac7ec8aa55cb83035640003efeca488a676cf61
2fc80489d3955389495a3820beb61b28c9a408b0
/sdizo2/sdizo2/source/structures/utilities/matrixGraph/MatrixGraph.h
1781303e1d2a8d1ed0867a66b04b283969ebedd6
[]
no_license
krzemien888/sdizo2
cfcec596751e5ca3d9c452425656096a54290221
db725e90ac7282b52f7bce6d50cd82a7d849977a
refs/heads/master
2021-01-23T01:12:45.741930
2018-06-18T14:00:09
2018-06-18T14:00:09
92,856,763
0
0
null
null
null
null
UTF-8
C++
false
false
1,018
h
#pragma once #include "structures\utilities\graph\Graph.h" #include "structures\matrix\Matrix.h" #include "structures\utilities\point\Point.h" class MatrixGraph : public Graph { public: MatrixGraph(); MatrixGraph::MatrixGraph(MatrixGraph& m); void clear(); void addEdge(const Edge &e) override; void addPoint(const Point &p) override; shared_ptr<Edge> getEdge(int a, int b) override; List<Edge> getEdges() override; PriorityQueue<Edge> getEdgesSorted() override; void addNeighboursSorted(int a, PriorityQueue<Edge> &queue) override; PriorityQueue<Edge> getConnections(List<int> &source) override; List<Edge> getNeighbours(int p)const override; void print(); MatrixGraph* getBlanck() override; int getEdgeValue(int a, int b) override; void setEdgeValue(int a, int b, int value) override; void increaseEdgeValue(int a, int b, int value) override; void decreaseEdgeValue(int a, int b, int value) override; void resize(int newSize) override; virtual ~MatrixGraph(); private: Matrix m_matrix; };
[ "krzeminski.k@outlook.com" ]
krzeminski.k@outlook.com
96ce29dc602183d3784cef018d7ccddf20d13383
73a64b3ada20930f2aeece2bb8631ef7f37d5b23
/src/Scene/PolyRenderer.cpp
8d626587953e38ecbe1fefc3422c051828b89122
[]
no_license
aWilson41/GLEngine
75d96ff1bfb2d6dd86abff16c4504e5a4225dd94
ebe1479856099f2d8376f3b2e8609e1a1fa1fe40
refs/heads/master
2021-08-11T06:16:18.055909
2021-08-05T04:32:46
2021-08-05T04:32:46
76,613,921
0
1
null
null
null
null
UTF-8
C++
false
false
479
cpp
#include "PolyRenderer.h" #include "PolyData.h" #include "PolyDataMapper.h" #include "SceneObject.h" PolyRenderer::PolyRenderer() { mapper = polyMapper = std::make_shared<PolyDataMapper>(); } void PolyRenderer::setInput(std::shared_ptr<PolyData> polyData) { polyMapper->setInput(polyData); polyMapper->update(); } void PolyRenderer::setTransform(const glm::mat4& transform) { polyMapper->setModelMatrix(transform); } void PolyRenderer::update() { polyMapper->update(); }
[ "andx_roo@live.com" ]
andx_roo@live.com
a5c626e014dbcf3fc1d7a2bc6f280b89ac0a2962
bd0a45d9898d3b131bebc38603b48e2fce0ced2c
/stock/GeneratedFiles/Debug/moc_xmlutils.cpp
f21caad01b4be71bbdbba6105e295197843019cb
[]
no_license
qxyjw2008/Stock
d42892cb212dcd706366d8ccce287222b2c83d52
cb54080147c8d1273cb934db2b184b0d7ada6347
refs/heads/master
2021-01-22T00:03:29.940643
2014-10-11T09:25:06
2014-10-11T09:25:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,754
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'xmlutils.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "StdAfx.h" #include "../../xmlutils.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'xmlutils.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_XmlUtils[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 7, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 50, 41, 10, 9, 0x0a, 86, 72, 67, 9, 0x0a, 148, 41, 135, 9, 0x0a, 165, 72, 67, 9, 0x0a, 224, 196, 67, 9, 0x0a, 285, 267, 67, 9, 0x0a, 356, 330, 9, 9, 0x0a, 0 // eod }; static const char qt_meta_stringdata_XmlUtils[] = { "XmlUtils\0\0QList<QHash<QString,QString> >\0" "fileName\0readXml(QString)\0bool\0" "fileName,list\0" "writeXml(QString,QList<QHash<QString,QString> >)\0" "QVariantList\0ReadXml(QString)\0" "WriteXml(QString,QVariantList)\0" "fileName,tagName,tagContent\0" "isElementExist(QString&,QString&,QString&)\0" "fileName,listItem\0" "appendItem(QString&,QHash<QString,QString>&)\0" "fileName,tagName,tagValue\0" "removeItem(QString&,QString&,QString&)\0" }; void XmlUtils::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); XmlUtils *_t = static_cast<XmlUtils *>(_o); switch (_id) { case 0: { QList<QHash<QString,QString> > _r = _t->readXml((*reinterpret_cast< QString(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QList<QHash<QString,QString> >*>(_a[0]) = _r; } break; case 1: { bool _r = _t->writeXml((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QList<QHash<QString,QString> >(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 2: { QVariantList _r = _t->ReadXml((*reinterpret_cast< QString(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QVariantList*>(_a[0]) = _r; } break; case 3: { bool _r = _t->WriteXml((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QVariantList(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 4: { bool _r = _t->isElementExist((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 5: { bool _r = _t->appendItem((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QHash<QString,QString>(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 6: _t->removeItem((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3]))); break; default: ; } } } const QMetaObjectExtraData XmlUtils::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject XmlUtils::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_XmlUtils, qt_meta_data_XmlUtils, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &XmlUtils::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *XmlUtils::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *XmlUtils::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_XmlUtils)) return static_cast<void*>(const_cast< XmlUtils*>(this)); return QObject::qt_metacast(_clname); } int XmlUtils::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 7) qt_static_metacall(this, _c, _id, _a); _id -= 7; } return _id; } QT_END_MOC_NAMESPACE
[ "766058573@qq.com" ]
766058573@qq.com
df45e2f76ce667d5e788bc827c80a48b72a88c6e
f85cfed4ae3c54b5d31b43e10435bb4fc4875d7e
/sc-virt/src/projects/compiler-rt/test/msan/allocator_mapping.cc
f47d9a63e09f80af5ad38955be76d3acd0489e09
[ "NCSA", "MIT" ]
permissive
archercreat/dta-vs-osc
2f495f74e0a67d3672c1fc11ecb812d3bc116210
b39f4d4eb6ffea501025fc3e07622251c2118fe0
refs/heads/main
2023-08-01T01:54:05.925289
2021-09-05T21:00:35
2021-09-05T21:00:35
438,047,267
1
1
MIT
2021-12-13T22:45:20
2021-12-13T22:45:19
null
UTF-8
C++
false
false
1,105
cc
// Test that a module constructor can not map memory over the MSan heap // (without MAP_FIXED, of course). Current implementation ensures this by // mapping the heap early, in __msan_init. // // RUN: %clangxx_msan -O0 %s -o %t_1 // RUN: %clangxx_msan -O0 -DHEAP_ADDRESS=$(%run %t_1) %s -o %t_2 && %run %t_2 // // This test only makes sense for the 64-bit allocator. The 32-bit allocator // does not have a fixed mapping. Exclude platforms that use the 32-bit // allocator. // UNSUPPORTED: mips64,aarch64 #include <assert.h> #include <stdio.h> #include <sys/mman.h> #include <stdlib.h> #ifdef HEAP_ADDRESS struct A { A() { void *const hint = reinterpret_cast<void *>(HEAP_ADDRESS); void *p = mmap(hint, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); // This address must be already mapped. Check that mmap() succeeds, but at a // different address. assert(p != reinterpret_cast<void *>(-1)); assert(p != hint); } } a; #endif int main() { void *p = malloc(10); printf("0x%zx\n", reinterpret_cast<size_t>(p) & (~0xfff)); free(p); }
[ "sebi@quantstamp.com" ]
sebi@quantstamp.com
7223c7f0c1ad6781ff4a3cdb0bb872251938862e
528376452dfa7d679d966f3560677179cd78c834
/TankBattle1.1.1/TankBattle1.1.1/Props.h
3f38378c7819a8bbc74103014a77f6cc9ef24e52
[]
no_license
cxm1150806259/TankBattle
4d4cbef36273c783c35bd56ffcd23d04219c757a
d042602f294a89863fea525af929b0cfb7bb576f
refs/heads/master
2021-01-13T01:54:26.707281
2014-03-30T11:36:40
2014-03-30T11:36:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
622
h
// // Props.h // Tank // // Created by cstlab on 14-3-10. // // #ifndef __Tank__Props__ #define __Tank__Props__ #include <iostream> #include "cocos2d.h" #include "TileMapInfo.h" using namespace cocos2d; class Props:public CCSprite { public: Props(); ~Props(); static Props* createPropsWithPropsType(TileMapInfo* tileMapInfo); void initPropsWithPropsType(TileMapInfo* tileMapInfo); //virtual void update(float dt); void removeProps(); CREATE_FUNC(Props); private: TileMapInfo* mTileMapInfo; CCPoint bornPoint[3]; CCSprite* moneySprit; }; #endif /* defined(__Tank__Props__) */
[ "1150806259@qq.com" ]
1150806259@qq.com
f6bc9903185f715d0eef0c120222bdc156420dfd
dfc99c33d245b408e77e2d86d7fdb9c88574bee3
/The Technate/Prototype/menustate.cpp
4d3ce33c40afdc9ace510d5181e4714bbaa8f172
[]
no_license
deezy135/The-Technate
3b835629dda2145ea15cf189dc40b031a2453dd7
c8c2b55e27a3e6d61df1307f46620489a0b48e99
refs/heads/master
2021-01-21T04:19:17.223215
2016-06-22T13:49:29
2016-06-22T13:49:29
55,894,527
1
0
null
null
null
null
UTF-8
C++
false
false
269
cpp
#include "menustate.h" bool MenuState::init(Engine * engine) { this->input = input; return true; } State::StateEvent MenuState::update() { if (input->getQuit()) { return StateEvent::Quit; } return StateEvent::Run; } void MenuState::close() { input = NULL; }
[ "deezy@DZ-PC" ]
deezy@DZ-PC
b44dbda83fe5678a90de7fb2433bb6815873d36a
ba0cbdae81c171bd4be7b12c0594de72bd6d625a
/MyToontown/Panda3D-1.9.0/include/cConstrainTransformInterval.h
6c09c96987ed9063360727665b0a7d18d0ad3cd0
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
sweep41/Toontown-2016
65985f198fa32a832e762fa9c59e59606d6a40a3
7732fb2c27001264e6dd652c057b3dc41f9c8a7d
refs/heads/master
2021-01-23T16:04:45.264205
2017-06-04T02:47:34
2017-06-04T02:47:34
93,279,679
0
0
null
null
null
null
UTF-8
C++
false
false
2,061
h
// Filename: cConstrainTransformInterval.h // Created by: pratt (29Sep06) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #ifndef CCONSTRAINTRANSFORMINTERVAL_H #define CCONSTRAINTRANSFORMINTERVAL_H #include "directbase.h" #include "cConstraintInterval.h" #include "nodePath.h" //////////////////////////////////////////////////////////////////// // Class : CConstrainTransformInterval // Description : A constraint interval that will constrain the // transform of one node to the transform of another. //////////////////////////////////////////////////////////////////// class EXPCL_DIRECT CConstrainTransformInterval : public CConstraintInterval { PUBLISHED: CConstrainTransformInterval(const string &name, double duration, const NodePath &node, const NodePath &target, bool wrt); INLINE const NodePath &get_node() const; INLINE const NodePath &get_target() const; virtual void priv_step(double t); virtual void output(ostream &out) const; private: NodePath _node; NodePath _target; bool _wrt; public: static TypeHandle get_class_type() { return _type_handle; } static void init_type() { CConstraintInterval::init_type(); register_type(_type_handle, "CConstrainTransformInterval", CConstraintInterval::get_class_type()); } virtual TypeHandle get_type() const { return get_class_type(); } virtual TypeHandle force_init_type() {init_type(); return get_class_type();} private: static TypeHandle _type_handle; }; #include "cConstrainTransformInterval.I" #endif
[ "sweep14@gmail.com" ]
sweep14@gmail.com
143f2ec89db860ed1b40a5367a31c6a59d6979b3
13e1e38318d6c832347b75cd76f1d342dfec3f64
/3rdParty/V8-4.3.61/src/hydrogen.cc
4389bfe78ab391c44a24a8ab36874e57968046cf
[ "bzip2-1.0.6", "BSD-3-Clause", "Apache-2.0", "GPL-1.0-or-later", "ICU", "MIT" ]
permissive
msand/arangodb
f1e2c2208258261e6a081897746c247a0aec6bdf
7c43164bb989e185f9c68a5275cebdf15548c2d6
refs/heads/devel
2023-04-07T00:35:40.506103
2015-07-20T08:59:22
2015-07-20T08:59:22
39,376,414
0
0
Apache-2.0
2023-04-04T00:08:22
2015-07-20T09:58:42
C++
UTF-8
C++
false
false
481,471
cc
// Copyright 2013 the V8 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. #include "src/hydrogen.h" #include <sstream> #include "src/v8.h" #include "src/allocation-site-scopes.h" #include "src/ast-numbering.h" #include "src/full-codegen.h" #include "src/hydrogen-bce.h" #include "src/hydrogen-bch.h" #include "src/hydrogen-canonicalize.h" #include "src/hydrogen-check-elimination.h" #include "src/hydrogen-dce.h" #include "src/hydrogen-dehoist.h" #include "src/hydrogen-environment-liveness.h" #include "src/hydrogen-escape-analysis.h" #include "src/hydrogen-gvn.h" #include "src/hydrogen-infer-representation.h" #include "src/hydrogen-infer-types.h" #include "src/hydrogen-load-elimination.h" #include "src/hydrogen-mark-deoptimize.h" #include "src/hydrogen-mark-unreachable.h" #include "src/hydrogen-osr.h" #include "src/hydrogen-range-analysis.h" #include "src/hydrogen-redundant-phi.h" #include "src/hydrogen-removable-simulates.h" #include "src/hydrogen-representation-changes.h" #include "src/hydrogen-sce.h" #include "src/hydrogen-store-elimination.h" #include "src/hydrogen-uint32-analysis.h" #include "src/ic/call-optimization.h" #include "src/ic/ic.h" // GetRootConstructor #include "src/ic/ic-inl.h" #include "src/lithium-allocator.h" #include "src/parser.h" #include "src/runtime/runtime.h" #include "src/scopeinfo.h" #include "src/typing.h" #if V8_TARGET_ARCH_IA32 #include "src/ia32/lithium-codegen-ia32.h" // NOLINT #elif V8_TARGET_ARCH_X64 #include "src/x64/lithium-codegen-x64.h" // NOLINT #elif V8_TARGET_ARCH_ARM64 #include "src/arm64/lithium-codegen-arm64.h" // NOLINT #elif V8_TARGET_ARCH_ARM #include "src/arm/lithium-codegen-arm.h" // NOLINT #elif V8_TARGET_ARCH_PPC #include "src/ppc/lithium-codegen-ppc.h" // NOLINT #elif V8_TARGET_ARCH_MIPS #include "src/mips/lithium-codegen-mips.h" // NOLINT #elif V8_TARGET_ARCH_MIPS64 #include "src/mips64/lithium-codegen-mips64.h" // NOLINT #elif V8_TARGET_ARCH_X87 #include "src/x87/lithium-codegen-x87.h" // NOLINT #else #error Unsupported target architecture. #endif namespace v8 { namespace internal { HBasicBlock::HBasicBlock(HGraph* graph) : block_id_(graph->GetNextBlockID()), graph_(graph), phis_(4, graph->zone()), first_(NULL), last_(NULL), end_(NULL), loop_information_(NULL), predecessors_(2, graph->zone()), dominator_(NULL), dominated_blocks_(4, graph->zone()), last_environment_(NULL), argument_count_(-1), first_instruction_index_(-1), last_instruction_index_(-1), deleted_phis_(4, graph->zone()), parent_loop_header_(NULL), inlined_entry_block_(NULL), is_inline_return_target_(false), is_reachable_(true), dominates_loop_successors_(false), is_osr_entry_(false), is_ordered_(false) { } Isolate* HBasicBlock::isolate() const { return graph_->isolate(); } void HBasicBlock::MarkUnreachable() { is_reachable_ = false; } void HBasicBlock::AttachLoopInformation() { DCHECK(!IsLoopHeader()); loop_information_ = new(zone()) HLoopInformation(this, zone()); } void HBasicBlock::DetachLoopInformation() { DCHECK(IsLoopHeader()); loop_information_ = NULL; } void HBasicBlock::AddPhi(HPhi* phi) { DCHECK(!IsStartBlock()); phis_.Add(phi, zone()); phi->SetBlock(this); } void HBasicBlock::RemovePhi(HPhi* phi) { DCHECK(phi->block() == this); DCHECK(phis_.Contains(phi)); phi->Kill(); phis_.RemoveElement(phi); phi->SetBlock(NULL); } void HBasicBlock::AddInstruction(HInstruction* instr, SourcePosition position) { DCHECK(!IsStartBlock() || !IsFinished()); DCHECK(!instr->IsLinked()); DCHECK(!IsFinished()); if (!position.IsUnknown()) { instr->set_position(position); } if (first_ == NULL) { DCHECK(last_environment() != NULL); DCHECK(!last_environment()->ast_id().IsNone()); HBlockEntry* entry = new(zone()) HBlockEntry(); entry->InitializeAsFirst(this); if (!position.IsUnknown()) { entry->set_position(position); } else { DCHECK(!FLAG_hydrogen_track_positions || !graph()->info()->IsOptimizing() || instr->IsAbnormalExit()); } first_ = last_ = entry; } instr->InsertAfter(last_); } HPhi* HBasicBlock::AddNewPhi(int merged_index) { if (graph()->IsInsideNoSideEffectsScope()) { merged_index = HPhi::kInvalidMergedIndex; } HPhi* phi = new(zone()) HPhi(merged_index, zone()); AddPhi(phi); return phi; } HSimulate* HBasicBlock::CreateSimulate(BailoutId ast_id, RemovableSimulate removable) { DCHECK(HasEnvironment()); HEnvironment* environment = last_environment(); DCHECK(ast_id.IsNone() || ast_id == BailoutId::StubEntry() || environment->closure()->shared()->VerifyBailoutId(ast_id)); int push_count = environment->push_count(); int pop_count = environment->pop_count(); HSimulate* instr = new(zone()) HSimulate(ast_id, pop_count, zone(), removable); #ifdef DEBUG instr->set_closure(environment->closure()); #endif // Order of pushed values: newest (top of stack) first. This allows // HSimulate::MergeWith() to easily append additional pushed values // that are older (from further down the stack). for (int i = 0; i < push_count; ++i) { instr->AddPushedValue(environment->ExpressionStackAt(i)); } for (GrowableBitVector::Iterator it(environment->assigned_variables(), zone()); !it.Done(); it.Advance()) { int index = it.Current(); instr->AddAssignedValue(index, environment->Lookup(index)); } environment->ClearHistory(); return instr; } void HBasicBlock::Finish(HControlInstruction* end, SourcePosition position) { DCHECK(!IsFinished()); AddInstruction(end, position); end_ = end; for (HSuccessorIterator it(end); !it.Done(); it.Advance()) { it.Current()->RegisterPredecessor(this); } } void HBasicBlock::Goto(HBasicBlock* block, SourcePosition position, FunctionState* state, bool add_simulate) { bool drop_extra = state != NULL && state->inlining_kind() == NORMAL_RETURN; if (block->IsInlineReturnTarget()) { HEnvironment* env = last_environment(); int argument_count = env->arguments_environment()->parameter_count(); AddInstruction(new(zone()) HLeaveInlined(state->entry(), argument_count), position); UpdateEnvironment(last_environment()->DiscardInlined(drop_extra)); } if (add_simulate) AddNewSimulate(BailoutId::None(), position); HGoto* instr = new(zone()) HGoto(block); Finish(instr, position); } void HBasicBlock::AddLeaveInlined(HValue* return_value, FunctionState* state, SourcePosition position) { HBasicBlock* target = state->function_return(); bool drop_extra = state->inlining_kind() == NORMAL_RETURN; DCHECK(target->IsInlineReturnTarget()); DCHECK(return_value != NULL); HEnvironment* env = last_environment(); int argument_count = env->arguments_environment()->parameter_count(); AddInstruction(new(zone()) HLeaveInlined(state->entry(), argument_count), position); UpdateEnvironment(last_environment()->DiscardInlined(drop_extra)); last_environment()->Push(return_value); AddNewSimulate(BailoutId::None(), position); HGoto* instr = new(zone()) HGoto(target); Finish(instr, position); } void HBasicBlock::SetInitialEnvironment(HEnvironment* env) { DCHECK(!HasEnvironment()); DCHECK(first() == NULL); UpdateEnvironment(env); } void HBasicBlock::UpdateEnvironment(HEnvironment* env) { last_environment_ = env; graph()->update_maximum_environment_size(env->first_expression_index()); } void HBasicBlock::SetJoinId(BailoutId ast_id) { int length = predecessors_.length(); DCHECK(length > 0); for (int i = 0; i < length; i++) { HBasicBlock* predecessor = predecessors_[i]; DCHECK(predecessor->end()->IsGoto()); HSimulate* simulate = HSimulate::cast(predecessor->end()->previous()); DCHECK(i != 0 || (predecessor->last_environment()->closure().is_null() || predecessor->last_environment()->closure()->shared() ->VerifyBailoutId(ast_id))); simulate->set_ast_id(ast_id); predecessor->last_environment()->set_ast_id(ast_id); } } bool HBasicBlock::Dominates(HBasicBlock* other) const { HBasicBlock* current = other->dominator(); while (current != NULL) { if (current == this) return true; current = current->dominator(); } return false; } bool HBasicBlock::EqualToOrDominates(HBasicBlock* other) const { if (this == other) return true; return Dominates(other); } int HBasicBlock::LoopNestingDepth() const { const HBasicBlock* current = this; int result = (current->IsLoopHeader()) ? 1 : 0; while (current->parent_loop_header() != NULL) { current = current->parent_loop_header(); result++; } return result; } void HBasicBlock::PostProcessLoopHeader(IterationStatement* stmt) { DCHECK(IsLoopHeader()); SetJoinId(stmt->EntryId()); if (predecessors()->length() == 1) { // This is a degenerated loop. DetachLoopInformation(); return; } // Only the first entry into the loop is from outside the loop. All other // entries must be back edges. for (int i = 1; i < predecessors()->length(); ++i) { loop_information()->RegisterBackEdge(predecessors()->at(i)); } } void HBasicBlock::MarkSuccEdgeUnreachable(int succ) { DCHECK(IsFinished()); HBasicBlock* succ_block = end()->SuccessorAt(succ); DCHECK(succ_block->predecessors()->length() == 1); succ_block->MarkUnreachable(); } void HBasicBlock::RegisterPredecessor(HBasicBlock* pred) { if (HasPredecessor()) { // Only loop header blocks can have a predecessor added after // instructions have been added to the block (they have phis for all // values in the environment, these phis may be eliminated later). DCHECK(IsLoopHeader() || first_ == NULL); HEnvironment* incoming_env = pred->last_environment(); if (IsLoopHeader()) { DCHECK(phis()->length() == incoming_env->length()); for (int i = 0; i < phis_.length(); ++i) { phis_[i]->AddInput(incoming_env->values()->at(i)); } } else { last_environment()->AddIncomingEdge(this, pred->last_environment()); } } else if (!HasEnvironment() && !IsFinished()) { DCHECK(!IsLoopHeader()); SetInitialEnvironment(pred->last_environment()->Copy()); } predecessors_.Add(pred, zone()); } void HBasicBlock::AddDominatedBlock(HBasicBlock* block) { DCHECK(!dominated_blocks_.Contains(block)); // Keep the list of dominated blocks sorted such that if there is two // succeeding block in this list, the predecessor is before the successor. int index = 0; while (index < dominated_blocks_.length() && dominated_blocks_[index]->block_id() < block->block_id()) { ++index; } dominated_blocks_.InsertAt(index, block, zone()); } void HBasicBlock::AssignCommonDominator(HBasicBlock* other) { if (dominator_ == NULL) { dominator_ = other; other->AddDominatedBlock(this); } else if (other->dominator() != NULL) { HBasicBlock* first = dominator_; HBasicBlock* second = other; while (first != second) { if (first->block_id() > second->block_id()) { first = first->dominator(); } else { second = second->dominator(); } DCHECK(first != NULL && second != NULL); } if (dominator_ != first) { DCHECK(dominator_->dominated_blocks_.Contains(this)); dominator_->dominated_blocks_.RemoveElement(this); dominator_ = first; first->AddDominatedBlock(this); } } } void HBasicBlock::AssignLoopSuccessorDominators() { // Mark blocks that dominate all subsequent reachable blocks inside their // loop. Exploit the fact that blocks are sorted in reverse post order. When // the loop is visited in increasing block id order, if the number of // non-loop-exiting successor edges at the dominator_candidate block doesn't // exceed the number of previously encountered predecessor edges, there is no // path from the loop header to any block with higher id that doesn't go // through the dominator_candidate block. In this case, the // dominator_candidate block is guaranteed to dominate all blocks reachable // from it with higher ids. HBasicBlock* last = loop_information()->GetLastBackEdge(); int outstanding_successors = 1; // one edge from the pre-header // Header always dominates everything. MarkAsLoopSuccessorDominator(); for (int j = block_id(); j <= last->block_id(); ++j) { HBasicBlock* dominator_candidate = graph_->blocks()->at(j); for (HPredecessorIterator it(dominator_candidate); !it.Done(); it.Advance()) { HBasicBlock* predecessor = it.Current(); // Don't count back edges. if (predecessor->block_id() < dominator_candidate->block_id()) { outstanding_successors--; } } // If more successors than predecessors have been seen in the loop up to // now, it's not possible to guarantee that the current block dominates // all of the blocks with higher IDs. In this case, assume conservatively // that those paths through loop that don't go through the current block // contain all of the loop's dependencies. Also be careful to record // dominator information about the current loop that's being processed, // and not nested loops, which will be processed when // AssignLoopSuccessorDominators gets called on their header. DCHECK(outstanding_successors >= 0); HBasicBlock* parent_loop_header = dominator_candidate->parent_loop_header(); if (outstanding_successors == 0 && (parent_loop_header == this && !dominator_candidate->IsLoopHeader())) { dominator_candidate->MarkAsLoopSuccessorDominator(); } HControlInstruction* end = dominator_candidate->end(); for (HSuccessorIterator it(end); !it.Done(); it.Advance()) { HBasicBlock* successor = it.Current(); // Only count successors that remain inside the loop and don't loop back // to a loop header. if (successor->block_id() > dominator_candidate->block_id() && successor->block_id() <= last->block_id()) { // Backwards edges must land on loop headers. DCHECK(successor->block_id() > dominator_candidate->block_id() || successor->IsLoopHeader()); outstanding_successors++; } } } } int HBasicBlock::PredecessorIndexOf(HBasicBlock* predecessor) const { for (int i = 0; i < predecessors_.length(); ++i) { if (predecessors_[i] == predecessor) return i; } UNREACHABLE(); return -1; } #ifdef DEBUG void HBasicBlock::Verify() { // Check that every block is finished. DCHECK(IsFinished()); DCHECK(block_id() >= 0); // Check that the incoming edges are in edge split form. if (predecessors_.length() > 1) { for (int i = 0; i < predecessors_.length(); ++i) { DCHECK(predecessors_[i]->end()->SecondSuccessor() == NULL); } } } #endif void HLoopInformation::RegisterBackEdge(HBasicBlock* block) { this->back_edges_.Add(block, block->zone()); AddBlock(block); } HBasicBlock* HLoopInformation::GetLastBackEdge() const { int max_id = -1; HBasicBlock* result = NULL; for (int i = 0; i < back_edges_.length(); ++i) { HBasicBlock* cur = back_edges_[i]; if (cur->block_id() > max_id) { max_id = cur->block_id(); result = cur; } } return result; } void HLoopInformation::AddBlock(HBasicBlock* block) { if (block == loop_header()) return; if (block->parent_loop_header() == loop_header()) return; if (block->parent_loop_header() != NULL) { AddBlock(block->parent_loop_header()); } else { block->set_parent_loop_header(loop_header()); blocks_.Add(block, block->zone()); for (int i = 0; i < block->predecessors()->length(); ++i) { AddBlock(block->predecessors()->at(i)); } } } #ifdef DEBUG // Checks reachability of the blocks in this graph and stores a bit in // the BitVector "reachable()" for every block that can be reached // from the start block of the graph. If "dont_visit" is non-null, the given // block is treated as if it would not be part of the graph. "visited_count()" // returns the number of reachable blocks. class ReachabilityAnalyzer BASE_EMBEDDED { public: ReachabilityAnalyzer(HBasicBlock* entry_block, int block_count, HBasicBlock* dont_visit) : visited_count_(0), stack_(16, entry_block->zone()), reachable_(block_count, entry_block->zone()), dont_visit_(dont_visit) { PushBlock(entry_block); Analyze(); } int visited_count() const { return visited_count_; } const BitVector* reachable() const { return &reachable_; } private: void PushBlock(HBasicBlock* block) { if (block != NULL && block != dont_visit_ && !reachable_.Contains(block->block_id())) { reachable_.Add(block->block_id()); stack_.Add(block, block->zone()); visited_count_++; } } void Analyze() { while (!stack_.is_empty()) { HControlInstruction* end = stack_.RemoveLast()->end(); for (HSuccessorIterator it(end); !it.Done(); it.Advance()) { PushBlock(it.Current()); } } } int visited_count_; ZoneList<HBasicBlock*> stack_; BitVector reachable_; HBasicBlock* dont_visit_; }; void HGraph::Verify(bool do_full_verify) const { Heap::RelocationLock relocation_lock(isolate()->heap()); AllowHandleDereference allow_deref; AllowDeferredHandleDereference allow_deferred_deref; for (int i = 0; i < blocks_.length(); i++) { HBasicBlock* block = blocks_.at(i); block->Verify(); // Check that every block contains at least one node and that only the last // node is a control instruction. HInstruction* current = block->first(); DCHECK(current != NULL && current->IsBlockEntry()); while (current != NULL) { DCHECK((current->next() == NULL) == current->IsControlInstruction()); DCHECK(current->block() == block); current->Verify(); current = current->next(); } // Check that successors are correctly set. HBasicBlock* first = block->end()->FirstSuccessor(); HBasicBlock* second = block->end()->SecondSuccessor(); DCHECK(second == NULL || first != NULL); // Check that the predecessor array is correct. if (first != NULL) { DCHECK(first->predecessors()->Contains(block)); if (second != NULL) { DCHECK(second->predecessors()->Contains(block)); } } // Check that phis have correct arguments. for (int j = 0; j < block->phis()->length(); j++) { HPhi* phi = block->phis()->at(j); phi->Verify(); } // Check that all join blocks have predecessors that end with an // unconditional goto and agree on their environment node id. if (block->predecessors()->length() >= 2) { BailoutId id = block->predecessors()->first()->last_environment()->ast_id(); for (int k = 0; k < block->predecessors()->length(); k++) { HBasicBlock* predecessor = block->predecessors()->at(k); DCHECK(predecessor->end()->IsGoto() || predecessor->end()->IsDeoptimize()); DCHECK(predecessor->last_environment()->ast_id() == id); } } } // Check special property of first block to have no predecessors. DCHECK(blocks_.at(0)->predecessors()->is_empty()); if (do_full_verify) { // Check that the graph is fully connected. ReachabilityAnalyzer analyzer(entry_block_, blocks_.length(), NULL); DCHECK(analyzer.visited_count() == blocks_.length()); // Check that entry block dominator is NULL. DCHECK(entry_block_->dominator() == NULL); // Check dominators. for (int i = 0; i < blocks_.length(); ++i) { HBasicBlock* block = blocks_.at(i); if (block->dominator() == NULL) { // Only start block may have no dominator assigned to. DCHECK(i == 0); } else { // Assert that block is unreachable if dominator must not be visited. ReachabilityAnalyzer dominator_analyzer(entry_block_, blocks_.length(), block->dominator()); DCHECK(!dominator_analyzer.reachable()->Contains(block->block_id())); } } } } #endif HConstant* HGraph::GetConstant(SetOncePointer<HConstant>* pointer, int32_t value) { if (!pointer->is_set()) { // Can't pass GetInvalidContext() to HConstant::New, because that will // recursively call GetConstant HConstant* constant = HConstant::New(isolate(), zone(), NULL, value); constant->InsertAfter(entry_block()->first()); pointer->set(constant); return constant; } return ReinsertConstantIfNecessary(pointer->get()); } HConstant* HGraph::ReinsertConstantIfNecessary(HConstant* constant) { if (!constant->IsLinked()) { // The constant was removed from the graph. Reinsert. constant->ClearFlag(HValue::kIsDead); constant->InsertAfter(entry_block()->first()); } return constant; } HConstant* HGraph::GetConstant0() { return GetConstant(&constant_0_, 0); } HConstant* HGraph::GetConstant1() { return GetConstant(&constant_1_, 1); } HConstant* HGraph::GetConstantMinus1() { return GetConstant(&constant_minus1_, -1); } #define DEFINE_GET_CONSTANT(Name, name, type, htype, boolean_value) \ HConstant* HGraph::GetConstant##Name() { \ if (!constant_##name##_.is_set()) { \ HConstant* constant = new(zone()) HConstant( \ Unique<Object>::CreateImmovable(isolate()->factory()->name##_value()), \ Unique<Map>::CreateImmovable(isolate()->factory()->type##_map()), \ false, \ Representation::Tagged(), \ htype, \ true, \ boolean_value, \ false, \ ODDBALL_TYPE); \ constant->InsertAfter(entry_block()->first()); \ constant_##name##_.set(constant); \ } \ return ReinsertConstantIfNecessary(constant_##name##_.get()); \ } DEFINE_GET_CONSTANT(Undefined, undefined, undefined, HType::Undefined(), false) DEFINE_GET_CONSTANT(True, true, boolean, HType::Boolean(), true) DEFINE_GET_CONSTANT(False, false, boolean, HType::Boolean(), false) DEFINE_GET_CONSTANT(Hole, the_hole, the_hole, HType::None(), false) DEFINE_GET_CONSTANT(Null, null, null, HType::Null(), false) #undef DEFINE_GET_CONSTANT #define DEFINE_IS_CONSTANT(Name, name) \ bool HGraph::IsConstant##Name(HConstant* constant) { \ return constant_##name##_.is_set() && constant == constant_##name##_.get(); \ } DEFINE_IS_CONSTANT(Undefined, undefined) DEFINE_IS_CONSTANT(0, 0) DEFINE_IS_CONSTANT(1, 1) DEFINE_IS_CONSTANT(Minus1, minus1) DEFINE_IS_CONSTANT(True, true) DEFINE_IS_CONSTANT(False, false) DEFINE_IS_CONSTANT(Hole, the_hole) DEFINE_IS_CONSTANT(Null, null) #undef DEFINE_IS_CONSTANT HConstant* HGraph::GetInvalidContext() { return GetConstant(&constant_invalid_context_, 0xFFFFC0C7); } bool HGraph::IsStandardConstant(HConstant* constant) { if (IsConstantUndefined(constant)) return true; if (IsConstant0(constant)) return true; if (IsConstant1(constant)) return true; if (IsConstantMinus1(constant)) return true; if (IsConstantTrue(constant)) return true; if (IsConstantFalse(constant)) return true; if (IsConstantHole(constant)) return true; if (IsConstantNull(constant)) return true; return false; } HGraphBuilder::IfBuilder::IfBuilder() : builder_(NULL), needs_compare_(true) {} HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder) : needs_compare_(true) { Initialize(builder); } HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder, HIfContinuation* continuation) : needs_compare_(false), first_true_block_(NULL), first_false_block_(NULL) { InitializeDontCreateBlocks(builder); continuation->Continue(&first_true_block_, &first_false_block_); } void HGraphBuilder::IfBuilder::InitializeDontCreateBlocks( HGraphBuilder* builder) { builder_ = builder; finished_ = false; did_then_ = false; did_else_ = false; did_else_if_ = false; did_and_ = false; did_or_ = false; captured_ = false; pending_merge_block_ = false; split_edge_merge_block_ = NULL; merge_at_join_blocks_ = NULL; normal_merge_at_join_block_count_ = 0; deopt_merge_at_join_block_count_ = 0; } void HGraphBuilder::IfBuilder::Initialize(HGraphBuilder* builder) { InitializeDontCreateBlocks(builder); HEnvironment* env = builder->environment(); first_true_block_ = builder->CreateBasicBlock(env->Copy()); first_false_block_ = builder->CreateBasicBlock(env->Copy()); } HControlInstruction* HGraphBuilder::IfBuilder::AddCompare( HControlInstruction* compare) { DCHECK(did_then_ == did_else_); if (did_else_) { // Handle if-then-elseif did_else_if_ = true; did_else_ = false; did_then_ = false; did_and_ = false; did_or_ = false; pending_merge_block_ = false; split_edge_merge_block_ = NULL; HEnvironment* env = builder()->environment(); first_true_block_ = builder()->CreateBasicBlock(env->Copy()); first_false_block_ = builder()->CreateBasicBlock(env->Copy()); } if (split_edge_merge_block_ != NULL) { HEnvironment* env = first_false_block_->last_environment(); HBasicBlock* split_edge = builder()->CreateBasicBlock(env->Copy()); if (did_or_) { compare->SetSuccessorAt(0, split_edge); compare->SetSuccessorAt(1, first_false_block_); } else { compare->SetSuccessorAt(0, first_true_block_); compare->SetSuccessorAt(1, split_edge); } builder()->GotoNoSimulate(split_edge, split_edge_merge_block_); } else { compare->SetSuccessorAt(0, first_true_block_); compare->SetSuccessorAt(1, first_false_block_); } builder()->FinishCurrentBlock(compare); needs_compare_ = false; return compare; } void HGraphBuilder::IfBuilder::Or() { DCHECK(!needs_compare_); DCHECK(!did_and_); did_or_ = true; HEnvironment* env = first_false_block_->last_environment(); if (split_edge_merge_block_ == NULL) { split_edge_merge_block_ = builder()->CreateBasicBlock(env->Copy()); builder()->GotoNoSimulate(first_true_block_, split_edge_merge_block_); first_true_block_ = split_edge_merge_block_; } builder()->set_current_block(first_false_block_); first_false_block_ = builder()->CreateBasicBlock(env->Copy()); } void HGraphBuilder::IfBuilder::And() { DCHECK(!needs_compare_); DCHECK(!did_or_); did_and_ = true; HEnvironment* env = first_false_block_->last_environment(); if (split_edge_merge_block_ == NULL) { split_edge_merge_block_ = builder()->CreateBasicBlock(env->Copy()); builder()->GotoNoSimulate(first_false_block_, split_edge_merge_block_); first_false_block_ = split_edge_merge_block_; } builder()->set_current_block(first_true_block_); first_true_block_ = builder()->CreateBasicBlock(env->Copy()); } void HGraphBuilder::IfBuilder::CaptureContinuation( HIfContinuation* continuation) { DCHECK(!did_else_if_); DCHECK(!finished_); DCHECK(!captured_); HBasicBlock* true_block = NULL; HBasicBlock* false_block = NULL; Finish(&true_block, &false_block); DCHECK(true_block != NULL); DCHECK(false_block != NULL); continuation->Capture(true_block, false_block); captured_ = true; builder()->set_current_block(NULL); End(); } void HGraphBuilder::IfBuilder::JoinContinuation(HIfContinuation* continuation) { DCHECK(!did_else_if_); DCHECK(!finished_); DCHECK(!captured_); HBasicBlock* true_block = NULL; HBasicBlock* false_block = NULL; Finish(&true_block, &false_block); merge_at_join_blocks_ = NULL; if (true_block != NULL && !true_block->IsFinished()) { DCHECK(continuation->IsTrueReachable()); builder()->GotoNoSimulate(true_block, continuation->true_branch()); } if (false_block != NULL && !false_block->IsFinished()) { DCHECK(continuation->IsFalseReachable()); builder()->GotoNoSimulate(false_block, continuation->false_branch()); } captured_ = true; End(); } void HGraphBuilder::IfBuilder::Then() { DCHECK(!captured_); DCHECK(!finished_); did_then_ = true; if (needs_compare_) { // Handle if's without any expressions, they jump directly to the "else" // branch. However, we must pretend that the "then" branch is reachable, // so that the graph builder visits it and sees any live range extending // constructs within it. HConstant* constant_false = builder()->graph()->GetConstantFalse(); ToBooleanStub::Types boolean_type = ToBooleanStub::Types(); boolean_type.Add(ToBooleanStub::BOOLEAN); HBranch* branch = builder()->New<HBranch>( constant_false, boolean_type, first_true_block_, first_false_block_); builder()->FinishCurrentBlock(branch); } builder()->set_current_block(first_true_block_); pending_merge_block_ = true; } void HGraphBuilder::IfBuilder::Else() { DCHECK(did_then_); DCHECK(!captured_); DCHECK(!finished_); AddMergeAtJoinBlock(false); builder()->set_current_block(first_false_block_); pending_merge_block_ = true; did_else_ = true; } void HGraphBuilder::IfBuilder::Deopt(Deoptimizer::DeoptReason reason) { DCHECK(did_then_); builder()->Add<HDeoptimize>(reason, Deoptimizer::EAGER); AddMergeAtJoinBlock(true); } void HGraphBuilder::IfBuilder::Return(HValue* value) { HValue* parameter_count = builder()->graph()->GetConstantMinus1(); builder()->FinishExitCurrentBlock( builder()->New<HReturn>(value, parameter_count)); AddMergeAtJoinBlock(false); } void HGraphBuilder::IfBuilder::AddMergeAtJoinBlock(bool deopt) { if (!pending_merge_block_) return; HBasicBlock* block = builder()->current_block(); DCHECK(block == NULL || !block->IsFinished()); MergeAtJoinBlock* record = new (builder()->zone()) MergeAtJoinBlock(block, deopt, merge_at_join_blocks_); merge_at_join_blocks_ = record; if (block != NULL) { DCHECK(block->end() == NULL); if (deopt) { normal_merge_at_join_block_count_++; } else { deopt_merge_at_join_block_count_++; } } builder()->set_current_block(NULL); pending_merge_block_ = false; } void HGraphBuilder::IfBuilder::Finish() { DCHECK(!finished_); if (!did_then_) { Then(); } AddMergeAtJoinBlock(false); if (!did_else_) { Else(); AddMergeAtJoinBlock(false); } finished_ = true; } void HGraphBuilder::IfBuilder::Finish(HBasicBlock** then_continuation, HBasicBlock** else_continuation) { Finish(); MergeAtJoinBlock* else_record = merge_at_join_blocks_; if (else_continuation != NULL) { *else_continuation = else_record->block_; } MergeAtJoinBlock* then_record = else_record->next_; if (then_continuation != NULL) { *then_continuation = then_record->block_; } DCHECK(then_record->next_ == NULL); } void HGraphBuilder::IfBuilder::End() { if (captured_) return; Finish(); int total_merged_blocks = normal_merge_at_join_block_count_ + deopt_merge_at_join_block_count_; DCHECK(total_merged_blocks >= 1); HBasicBlock* merge_block = total_merged_blocks == 1 ? NULL : builder()->graph()->CreateBasicBlock(); // Merge non-deopt blocks first to ensure environment has right size for // padding. MergeAtJoinBlock* current = merge_at_join_blocks_; while (current != NULL) { if (!current->deopt_ && current->block_ != NULL) { // If there is only one block that makes it through to the end of the // if, then just set it as the current block and continue rather then // creating an unnecessary merge block. if (total_merged_blocks == 1) { builder()->set_current_block(current->block_); return; } builder()->GotoNoSimulate(current->block_, merge_block); } current = current->next_; } // Merge deopt blocks, padding when necessary. current = merge_at_join_blocks_; while (current != NULL) { if (current->deopt_ && current->block_ != NULL) { current->block_->FinishExit( HAbnormalExit::New(builder()->isolate(), builder()->zone(), NULL), SourcePosition::Unknown()); } current = current->next_; } builder()->set_current_block(merge_block); } HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder) { Initialize(builder, NULL, kWhileTrue, NULL); } HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context, LoopBuilder::Direction direction) { Initialize(builder, context, direction, builder->graph()->GetConstant1()); } HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context, LoopBuilder::Direction direction, HValue* increment_amount) { Initialize(builder, context, direction, increment_amount); increment_amount_ = increment_amount; } void HGraphBuilder::LoopBuilder::Initialize(HGraphBuilder* builder, HValue* context, Direction direction, HValue* increment_amount) { builder_ = builder; context_ = context; direction_ = direction; increment_amount_ = increment_amount; finished_ = false; header_block_ = builder->CreateLoopHeaderBlock(); body_block_ = NULL; exit_block_ = NULL; exit_trampoline_block_ = NULL; } HValue* HGraphBuilder::LoopBuilder::BeginBody( HValue* initial, HValue* terminating, Token::Value token) { DCHECK(direction_ != kWhileTrue); HEnvironment* env = builder_->environment(); phi_ = header_block_->AddNewPhi(env->values()->length()); phi_->AddInput(initial); env->Push(initial); builder_->GotoNoSimulate(header_block_); HEnvironment* body_env = env->Copy(); HEnvironment* exit_env = env->Copy(); // Remove the phi from the expression stack body_env->Pop(); exit_env->Pop(); body_block_ = builder_->CreateBasicBlock(body_env); exit_block_ = builder_->CreateBasicBlock(exit_env); builder_->set_current_block(header_block_); env->Pop(); builder_->FinishCurrentBlock(builder_->New<HCompareNumericAndBranch>( phi_, terminating, token, body_block_, exit_block_)); builder_->set_current_block(body_block_); if (direction_ == kPreIncrement || direction_ == kPreDecrement) { Isolate* isolate = builder_->isolate(); HValue* one = builder_->graph()->GetConstant1(); if (direction_ == kPreIncrement) { increment_ = HAdd::New(isolate, zone(), context_, phi_, one); } else { increment_ = HSub::New(isolate, zone(), context_, phi_, one); } increment_->ClearFlag(HValue::kCanOverflow); builder_->AddInstruction(increment_); return increment_; } else { return phi_; } } void HGraphBuilder::LoopBuilder::BeginBody(int drop_count) { DCHECK(direction_ == kWhileTrue); HEnvironment* env = builder_->environment(); builder_->GotoNoSimulate(header_block_); builder_->set_current_block(header_block_); env->Drop(drop_count); } void HGraphBuilder::LoopBuilder::Break() { if (exit_trampoline_block_ == NULL) { // Its the first time we saw a break. if (direction_ == kWhileTrue) { HEnvironment* env = builder_->environment()->Copy(); exit_trampoline_block_ = builder_->CreateBasicBlock(env); } else { HEnvironment* env = exit_block_->last_environment()->Copy(); exit_trampoline_block_ = builder_->CreateBasicBlock(env); builder_->GotoNoSimulate(exit_block_, exit_trampoline_block_); } } builder_->GotoNoSimulate(exit_trampoline_block_); builder_->set_current_block(NULL); } void HGraphBuilder::LoopBuilder::EndBody() { DCHECK(!finished_); if (direction_ == kPostIncrement || direction_ == kPostDecrement) { Isolate* isolate = builder_->isolate(); if (direction_ == kPostIncrement) { increment_ = HAdd::New(isolate, zone(), context_, phi_, increment_amount_); } else { increment_ = HSub::New(isolate, zone(), context_, phi_, increment_amount_); } increment_->ClearFlag(HValue::kCanOverflow); builder_->AddInstruction(increment_); } if (direction_ != kWhileTrue) { // Push the new increment value on the expression stack to merge into // the phi. builder_->environment()->Push(increment_); } HBasicBlock* last_block = builder_->current_block(); builder_->GotoNoSimulate(last_block, header_block_); header_block_->loop_information()->RegisterBackEdge(last_block); if (exit_trampoline_block_ != NULL) { builder_->set_current_block(exit_trampoline_block_); } else { builder_->set_current_block(exit_block_); } finished_ = true; } HGraph* HGraphBuilder::CreateGraph() { graph_ = new(zone()) HGraph(info_); if (FLAG_hydrogen_stats) isolate()->GetHStatistics()->Initialize(info_); CompilationPhase phase("H_Block building", info_); set_current_block(graph()->entry_block()); if (!BuildGraph()) return NULL; graph()->FinalizeUniqueness(); return graph_; } HInstruction* HGraphBuilder::AddInstruction(HInstruction* instr) { DCHECK(current_block() != NULL); DCHECK(!FLAG_hydrogen_track_positions || !position_.IsUnknown() || !info_->IsOptimizing()); current_block()->AddInstruction(instr, source_position()); if (graph()->IsInsideNoSideEffectsScope()) { instr->SetFlag(HValue::kHasNoObservableSideEffects); } return instr; } void HGraphBuilder::FinishCurrentBlock(HControlInstruction* last) { DCHECK(!FLAG_hydrogen_track_positions || !info_->IsOptimizing() || !position_.IsUnknown()); current_block()->Finish(last, source_position()); if (last->IsReturn() || last->IsAbnormalExit()) { set_current_block(NULL); } } void HGraphBuilder::FinishExitCurrentBlock(HControlInstruction* instruction) { DCHECK(!FLAG_hydrogen_track_positions || !info_->IsOptimizing() || !position_.IsUnknown()); current_block()->FinishExit(instruction, source_position()); if (instruction->IsReturn() || instruction->IsAbnormalExit()) { set_current_block(NULL); } } void HGraphBuilder::AddIncrementCounter(StatsCounter* counter) { if (FLAG_native_code_counters && counter->Enabled()) { HValue* reference = Add<HConstant>(ExternalReference(counter)); HValue* old_value = Add<HLoadNamedField>(reference, nullptr, HObjectAccess::ForCounter()); HValue* new_value = AddUncasted<HAdd>(old_value, graph()->GetConstant1()); new_value->ClearFlag(HValue::kCanOverflow); // Ignore counter overflow Add<HStoreNamedField>(reference, HObjectAccess::ForCounter(), new_value, STORE_TO_INITIALIZED_ENTRY); } } void HGraphBuilder::AddSimulate(BailoutId id, RemovableSimulate removable) { DCHECK(current_block() != NULL); DCHECK(!graph()->IsInsideNoSideEffectsScope()); current_block()->AddNewSimulate(id, source_position(), removable); } HBasicBlock* HGraphBuilder::CreateBasicBlock(HEnvironment* env) { HBasicBlock* b = graph()->CreateBasicBlock(); b->SetInitialEnvironment(env); return b; } HBasicBlock* HGraphBuilder::CreateLoopHeaderBlock() { HBasicBlock* header = graph()->CreateBasicBlock(); HEnvironment* entry_env = environment()->CopyAsLoopHeader(header); header->SetInitialEnvironment(entry_env); header->AttachLoopInformation(); return header; } HValue* HGraphBuilder::BuildGetElementsKind(HValue* object) { HValue* map = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMap()); HValue* bit_field2 = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField2()); return BuildDecodeField<Map::ElementsKindBits>(bit_field2); } HValue* HGraphBuilder::BuildCheckHeapObject(HValue* obj) { if (obj->type().IsHeapObject()) return obj; return Add<HCheckHeapObject>(obj); } void HGraphBuilder::FinishExitWithHardDeoptimization( Deoptimizer::DeoptReason reason) { Add<HDeoptimize>(reason, Deoptimizer::EAGER); FinishExitCurrentBlock(New<HAbnormalExit>()); } HValue* HGraphBuilder::BuildCheckString(HValue* string) { if (!string->type().IsString()) { DCHECK(!string->IsConstant() || !HConstant::cast(string)->HasStringValue()); BuildCheckHeapObject(string); return Add<HCheckInstanceType>(string, HCheckInstanceType::IS_STRING); } return string; } HValue* HGraphBuilder::BuildWrapReceiver(HValue* object, HValue* function) { if (object->type().IsJSObject()) return object; if (function->IsConstant() && HConstant::cast(function)->handle(isolate())->IsJSFunction()) { Handle<JSFunction> f = Handle<JSFunction>::cast( HConstant::cast(function)->handle(isolate())); SharedFunctionInfo* shared = f->shared(); if (is_strict(shared->language_mode()) || shared->native()) return object; } return Add<HWrapReceiver>(object, function); } HValue* HGraphBuilder::BuildCheckForCapacityGrow( HValue* object, HValue* elements, ElementsKind kind, HValue* length, HValue* key, bool is_js_array, PropertyAccessType access_type) { IfBuilder length_checker(this); Token::Value token = IsHoleyElementsKind(kind) ? Token::GTE : Token::EQ; length_checker.If<HCompareNumericAndBranch>(key, length, token); length_checker.Then(); HValue* current_capacity = AddLoadFixedArrayLength(elements); IfBuilder capacity_checker(this); capacity_checker.If<HCompareNumericAndBranch>(key, current_capacity, Token::GTE); capacity_checker.Then(); HValue* max_gap = Add<HConstant>(static_cast<int32_t>(JSObject::kMaxGap)); HValue* max_capacity = AddUncasted<HAdd>(current_capacity, max_gap); Add<HBoundsCheck>(key, max_capacity); HValue* new_capacity = BuildNewElementsCapacity(key); HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind, kind, length, new_capacity); environment()->Push(new_elements); capacity_checker.Else(); environment()->Push(elements); capacity_checker.End(); if (is_js_array) { HValue* new_length = AddUncasted<HAdd>(key, graph_->GetConstant1()); new_length->ClearFlag(HValue::kCanOverflow); Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(kind), new_length); } if (access_type == STORE && kind == FAST_SMI_ELEMENTS) { HValue* checked_elements = environment()->Top(); // Write zero to ensure that the new element is initialized with some smi. Add<HStoreKeyed>(checked_elements, key, graph()->GetConstant0(), kind); } length_checker.Else(); Add<HBoundsCheck>(key, length); environment()->Push(elements); length_checker.End(); return environment()->Pop(); } HValue* HGraphBuilder::BuildCopyElementsOnWrite(HValue* object, HValue* elements, ElementsKind kind, HValue* length) { Factory* factory = isolate()->factory(); IfBuilder cow_checker(this); cow_checker.If<HCompareMap>(elements, factory->fixed_cow_array_map()); cow_checker.Then(); HValue* capacity = AddLoadFixedArrayLength(elements); HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind, kind, length, capacity); environment()->Push(new_elements); cow_checker.Else(); environment()->Push(elements); cow_checker.End(); return environment()->Pop(); } void HGraphBuilder::BuildTransitionElementsKind(HValue* object, HValue* map, ElementsKind from_kind, ElementsKind to_kind, bool is_jsarray) { DCHECK(!IsFastHoleyElementsKind(from_kind) || IsFastHoleyElementsKind(to_kind)); if (AllocationSite::GetMode(from_kind, to_kind) == TRACK_ALLOCATION_SITE) { Add<HTrapAllocationMemento>(object); } if (!IsSimpleMapChangeTransition(from_kind, to_kind)) { HInstruction* elements = AddLoadElements(object); HInstruction* empty_fixed_array = Add<HConstant>( isolate()->factory()->empty_fixed_array()); IfBuilder if_builder(this); if_builder.IfNot<HCompareObjectEqAndBranch>(elements, empty_fixed_array); if_builder.Then(); HInstruction* elements_length = AddLoadFixedArrayLength(elements); HInstruction* array_length = is_jsarray ? Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForArrayLength(from_kind)) : elements_length; BuildGrowElementsCapacity(object, elements, from_kind, to_kind, array_length, elements_length); if_builder.End(); } Add<HStoreNamedField>(object, HObjectAccess::ForMap(), map); } void HGraphBuilder::BuildJSObjectCheck(HValue* receiver, int bit_field_mask) { // Check that the object isn't a smi. Add<HCheckHeapObject>(receiver); // Get the map of the receiver. HValue* map = Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForMap()); // Check the instance type and if an access check is needed, this can be // done with a single load, since both bytes are adjacent in the map. HObjectAccess access(HObjectAccess::ForMapInstanceTypeAndBitField()); HValue* instance_type_and_bit_field = Add<HLoadNamedField>(map, nullptr, access); HValue* mask = Add<HConstant>(0x00FF | (bit_field_mask << 8)); HValue* and_result = AddUncasted<HBitwise>(Token::BIT_AND, instance_type_and_bit_field, mask); HValue* sub_result = AddUncasted<HSub>(and_result, Add<HConstant>(JS_OBJECT_TYPE)); Add<HBoundsCheck>(sub_result, Add<HConstant>(LAST_JS_OBJECT_TYPE + 1 - JS_OBJECT_TYPE)); } void HGraphBuilder::BuildKeyedIndexCheck(HValue* key, HIfContinuation* join_continuation) { // The sometimes unintuitively backward ordering of the ifs below is // convoluted, but necessary. All of the paths must guarantee that the // if-true of the continuation returns a smi element index and the if-false of // the continuation returns either a symbol or a unique string key. All other // object types cause a deopt to fall back to the runtime. IfBuilder key_smi_if(this); key_smi_if.If<HIsSmiAndBranch>(key); key_smi_if.Then(); { Push(key); // Nothing to do, just continue to true of continuation. } key_smi_if.Else(); { HValue* map = Add<HLoadNamedField>(key, nullptr, HObjectAccess::ForMap()); HValue* instance_type = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType()); // Non-unique string, check for a string with a hash code that is actually // an index. STATIC_ASSERT(LAST_UNIQUE_NAME_TYPE == FIRST_NONSTRING_TYPE); IfBuilder not_string_or_name_if(this); not_string_or_name_if.If<HCompareNumericAndBranch>( instance_type, Add<HConstant>(LAST_UNIQUE_NAME_TYPE), Token::GT); not_string_or_name_if.Then(); { // Non-smi, non-Name, non-String: Try to convert to smi in case of // HeapNumber. // TODO(danno): This could call some variant of ToString Push(AddUncasted<HForceRepresentation>(key, Representation::Smi())); } not_string_or_name_if.Else(); { // String or Name: check explicitly for Name, they can short-circuit // directly to unique non-index key path. IfBuilder not_symbol_if(this); not_symbol_if.If<HCompareNumericAndBranch>( instance_type, Add<HConstant>(SYMBOL_TYPE), Token::NE); not_symbol_if.Then(); { // String: check whether the String is a String of an index. If it is, // extract the index value from the hash. HValue* hash = Add<HLoadNamedField>(key, nullptr, HObjectAccess::ForNameHashField()); HValue* not_index_mask = Add<HConstant>(static_cast<int>( String::kContainsCachedArrayIndexMask)); HValue* not_index_test = AddUncasted<HBitwise>( Token::BIT_AND, hash, not_index_mask); IfBuilder string_index_if(this); string_index_if.If<HCompareNumericAndBranch>(not_index_test, graph()->GetConstant0(), Token::EQ); string_index_if.Then(); { // String with index in hash: extract string and merge to index path. Push(BuildDecodeField<String::ArrayIndexValueBits>(hash)); } string_index_if.Else(); { // Key is a non-index String, check for uniqueness/internalization. // If it's not internalized yet, internalize it now. HValue* not_internalized_bit = AddUncasted<HBitwise>( Token::BIT_AND, instance_type, Add<HConstant>(static_cast<int>(kIsNotInternalizedMask))); IfBuilder internalized(this); internalized.If<HCompareNumericAndBranch>(not_internalized_bit, graph()->GetConstant0(), Token::EQ); internalized.Then(); Push(key); internalized.Else(); Add<HPushArguments>(key); HValue* intern_key = Add<HCallRuntime>( isolate()->factory()->empty_string(), Runtime::FunctionForId(Runtime::kInternalizeString), 1); Push(intern_key); internalized.End(); // Key guaranteed to be a unique string } string_index_if.JoinContinuation(join_continuation); } not_symbol_if.Else(); { Push(key); // Key is symbol } not_symbol_if.JoinContinuation(join_continuation); } not_string_or_name_if.JoinContinuation(join_continuation); } key_smi_if.JoinContinuation(join_continuation); } void HGraphBuilder::BuildNonGlobalObjectCheck(HValue* receiver) { // Get the the instance type of the receiver, and make sure that it is // not one of the global object types. HValue* map = Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForMap()); HValue* instance_type = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType()); STATIC_ASSERT(JS_BUILTINS_OBJECT_TYPE == JS_GLOBAL_OBJECT_TYPE + 1); HValue* min_global_type = Add<HConstant>(JS_GLOBAL_OBJECT_TYPE); HValue* max_global_type = Add<HConstant>(JS_BUILTINS_OBJECT_TYPE); IfBuilder if_global_object(this); if_global_object.If<HCompareNumericAndBranch>(instance_type, max_global_type, Token::LTE); if_global_object.And(); if_global_object.If<HCompareNumericAndBranch>(instance_type, min_global_type, Token::GTE); if_global_object.ThenDeopt(Deoptimizer::kReceiverWasAGlobalObject); if_global_object.End(); } void HGraphBuilder::BuildTestForDictionaryProperties( HValue* object, HIfContinuation* continuation) { HValue* properties = Add<HLoadNamedField>( object, nullptr, HObjectAccess::ForPropertiesPointer()); HValue* properties_map = Add<HLoadNamedField>(properties, nullptr, HObjectAccess::ForMap()); HValue* hash_map = Add<HLoadRoot>(Heap::kHashTableMapRootIndex); IfBuilder builder(this); builder.If<HCompareObjectEqAndBranch>(properties_map, hash_map); builder.CaptureContinuation(continuation); } HValue* HGraphBuilder::BuildKeyedLookupCacheHash(HValue* object, HValue* key) { // Load the map of the receiver, compute the keyed lookup cache hash // based on 32 bits of the map pointer and the string hash. HValue* object_map = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMapAsInteger32()); HValue* shifted_map = AddUncasted<HShr>( object_map, Add<HConstant>(KeyedLookupCache::kMapHashShift)); HValue* string_hash = Add<HLoadNamedField>(key, nullptr, HObjectAccess::ForStringHashField()); HValue* shifted_hash = AddUncasted<HShr>( string_hash, Add<HConstant>(String::kHashShift)); HValue* xor_result = AddUncasted<HBitwise>(Token::BIT_XOR, shifted_map, shifted_hash); int mask = (KeyedLookupCache::kCapacityMask & KeyedLookupCache::kHashMask); return AddUncasted<HBitwise>(Token::BIT_AND, xor_result, Add<HConstant>(mask)); } HValue* HGraphBuilder::BuildElementIndexHash(HValue* index) { int32_t seed_value = static_cast<uint32_t>(isolate()->heap()->HashSeed()); HValue* seed = Add<HConstant>(seed_value); HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, index, seed); // hash = ~hash + (hash << 15); HValue* shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(15)); HValue* not_hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, graph()->GetConstantMinus1()); hash = AddUncasted<HAdd>(shifted_hash, not_hash); // hash = hash ^ (hash >> 12); shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(12)); hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash); // hash = hash + (hash << 2); shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(2)); hash = AddUncasted<HAdd>(hash, shifted_hash); // hash = hash ^ (hash >> 4); shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(4)); hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash); // hash = hash * 2057; hash = AddUncasted<HMul>(hash, Add<HConstant>(2057)); hash->ClearFlag(HValue::kCanOverflow); // hash = hash ^ (hash >> 16); shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(16)); return AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash); } HValue* HGraphBuilder::BuildUncheckedDictionaryElementLoad(HValue* receiver, HValue* elements, HValue* key, HValue* hash) { HValue* capacity = Add<HLoadKeyed>(elements, Add<HConstant>(NameDictionary::kCapacityIndex), nullptr, FAST_ELEMENTS); HValue* mask = AddUncasted<HSub>(capacity, graph()->GetConstant1()); mask->ChangeRepresentation(Representation::Integer32()); mask->ClearFlag(HValue::kCanOverflow); HValue* entry = hash; HValue* count = graph()->GetConstant1(); Push(entry); Push(count); HIfContinuation return_or_loop_continuation(graph()->CreateBasicBlock(), graph()->CreateBasicBlock()); HIfContinuation found_key_match_continuation(graph()->CreateBasicBlock(), graph()->CreateBasicBlock()); LoopBuilder probe_loop(this); probe_loop.BeginBody(2); // Drop entry, count from last environment to // appease live range building without simulates. count = Pop(); entry = Pop(); entry = AddUncasted<HBitwise>(Token::BIT_AND, entry, mask); int entry_size = SeededNumberDictionary::kEntrySize; HValue* base_index = AddUncasted<HMul>(entry, Add<HConstant>(entry_size)); base_index->ClearFlag(HValue::kCanOverflow); int start_offset = SeededNumberDictionary::kElementsStartIndex; HValue* key_index = AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset)); key_index->ClearFlag(HValue::kCanOverflow); HValue* candidate_key = Add<HLoadKeyed>(elements, key_index, nullptr, FAST_ELEMENTS); IfBuilder if_undefined(this); if_undefined.If<HCompareObjectEqAndBranch>(candidate_key, graph()->GetConstantUndefined()); if_undefined.Then(); { // element == undefined means "not found". Call the runtime. // TODO(jkummerow): walk the prototype chain instead. Add<HPushArguments>(receiver, key); Push(Add<HCallRuntime>(isolate()->factory()->empty_string(), Runtime::FunctionForId(Runtime::kKeyedGetProperty), 2)); } if_undefined.Else(); { IfBuilder if_match(this); if_match.If<HCompareObjectEqAndBranch>(candidate_key, key); if_match.Then(); if_match.Else(); // Update non-internalized string in the dictionary with internalized key? IfBuilder if_update_with_internalized(this); HValue* smi_check = if_update_with_internalized.IfNot<HIsSmiAndBranch>(candidate_key); if_update_with_internalized.And(); HValue* map = AddLoadMap(candidate_key, smi_check); HValue* instance_type = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType()); HValue* not_internalized_bit = AddUncasted<HBitwise>( Token::BIT_AND, instance_type, Add<HConstant>(static_cast<int>(kIsNotInternalizedMask))); if_update_with_internalized.If<HCompareNumericAndBranch>( not_internalized_bit, graph()->GetConstant0(), Token::NE); if_update_with_internalized.And(); if_update_with_internalized.IfNot<HCompareObjectEqAndBranch>( candidate_key, graph()->GetConstantHole()); if_update_with_internalized.AndIf<HStringCompareAndBranch>(candidate_key, key, Token::EQ); if_update_with_internalized.Then(); // Replace a key that is a non-internalized string by the equivalent // internalized string for faster further lookups. Add<HStoreKeyed>(elements, key_index, key, FAST_ELEMENTS); if_update_with_internalized.Else(); if_update_with_internalized.JoinContinuation(&found_key_match_continuation); if_match.JoinContinuation(&found_key_match_continuation); IfBuilder found_key_match(this, &found_key_match_continuation); found_key_match.Then(); // Key at current probe matches. Relevant bits in the |details| field must // be zero, otherwise the dictionary element requires special handling. HValue* details_index = AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset + 2)); details_index->ClearFlag(HValue::kCanOverflow); HValue* details = Add<HLoadKeyed>(elements, details_index, nullptr, FAST_ELEMENTS); int details_mask = PropertyDetails::TypeField::kMask; details = AddUncasted<HBitwise>(Token::BIT_AND, details, Add<HConstant>(details_mask)); IfBuilder details_compare(this); details_compare.If<HCompareNumericAndBranch>( details, graph()->GetConstant0(), Token::EQ); details_compare.Then(); HValue* result_index = AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset + 1)); result_index->ClearFlag(HValue::kCanOverflow); Push(Add<HLoadKeyed>(elements, result_index, nullptr, FAST_ELEMENTS)); details_compare.Else(); Add<HPushArguments>(receiver, key); Push(Add<HCallRuntime>(isolate()->factory()->empty_string(), Runtime::FunctionForId(Runtime::kKeyedGetProperty), 2)); details_compare.End(); found_key_match.Else(); found_key_match.JoinContinuation(&return_or_loop_continuation); } if_undefined.JoinContinuation(&return_or_loop_continuation); IfBuilder return_or_loop(this, &return_or_loop_continuation); return_or_loop.Then(); probe_loop.Break(); return_or_loop.Else(); entry = AddUncasted<HAdd>(entry, count); entry->ClearFlag(HValue::kCanOverflow); count = AddUncasted<HAdd>(count, graph()->GetConstant1()); count->ClearFlag(HValue::kCanOverflow); Push(entry); Push(count); probe_loop.EndBody(); return_or_loop.End(); return Pop(); } HValue* HGraphBuilder::BuildRegExpConstructResult(HValue* length, HValue* index, HValue* input) { NoObservableSideEffectsScope scope(this); HConstant* max_length = Add<HConstant>(JSObject::kInitialMaxFastElementArray); Add<HBoundsCheck>(length, max_length); // Generate size calculation code here in order to make it dominate // the JSRegExpResult allocation. ElementsKind elements_kind = FAST_ELEMENTS; HValue* size = BuildCalculateElementsSize(elements_kind, length); // Allocate the JSRegExpResult and the FixedArray in one step. HValue* result = Add<HAllocate>( Add<HConstant>(JSRegExpResult::kSize), HType::JSArray(), NOT_TENURED, JS_ARRAY_TYPE); // Initialize the JSRegExpResult header. HValue* global_object = Add<HLoadNamedField>( context(), nullptr, HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); HValue* native_context = Add<HLoadNamedField>( global_object, nullptr, HObjectAccess::ForGlobalObjectNativeContext()); Add<HStoreNamedField>( result, HObjectAccess::ForMap(), Add<HLoadNamedField>( native_context, nullptr, HObjectAccess::ForContextSlot(Context::REGEXP_RESULT_MAP_INDEX))); HConstant* empty_fixed_array = Add<HConstant>(isolate()->factory()->empty_fixed_array()); Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSArray::kPropertiesOffset), empty_fixed_array); Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset), empty_fixed_array); Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSArray::kLengthOffset), length); // Initialize the additional fields. Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kIndexOffset), index); Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kInputOffset), input); // Allocate and initialize the elements header. HAllocate* elements = BuildAllocateElements(elements_kind, size); BuildInitializeElementsHeader(elements, elements_kind, length); if (!elements->has_size_upper_bound()) { HConstant* size_in_bytes_upper_bound = EstablishElementsAllocationSize( elements_kind, max_length->Integer32Value()); elements->set_size_upper_bound(size_in_bytes_upper_bound); } Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset), elements); // Initialize the elements contents with undefined. BuildFillElementsWithValue( elements, elements_kind, graph()->GetConstant0(), length, graph()->GetConstantUndefined()); return result; } HValue* HGraphBuilder::BuildNumberToString(HValue* object, Type* type) { NoObservableSideEffectsScope scope(this); // Convert constant numbers at compile time. if (object->IsConstant() && HConstant::cast(object)->HasNumberValue()) { Handle<Object> number = HConstant::cast(object)->handle(isolate()); Handle<String> result = isolate()->factory()->NumberToString(number); return Add<HConstant>(result); } // Create a joinable continuation. HIfContinuation found(graph()->CreateBasicBlock(), graph()->CreateBasicBlock()); // Load the number string cache. HValue* number_string_cache = Add<HLoadRoot>(Heap::kNumberStringCacheRootIndex); // Make the hash mask from the length of the number string cache. It // contains two elements (number and string) for each cache entry. HValue* mask = AddLoadFixedArrayLength(number_string_cache); mask->set_type(HType::Smi()); mask = AddUncasted<HSar>(mask, graph()->GetConstant1()); mask = AddUncasted<HSub>(mask, graph()->GetConstant1()); // Check whether object is a smi. IfBuilder if_objectissmi(this); if_objectissmi.If<HIsSmiAndBranch>(object); if_objectissmi.Then(); { // Compute hash for smi similar to smi_get_hash(). HValue* hash = AddUncasted<HBitwise>(Token::BIT_AND, object, mask); // Load the key. HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1()); HValue* key = Add<HLoadKeyed>(number_string_cache, key_index, nullptr, FAST_ELEMENTS, ALLOW_RETURN_HOLE); // Check if object == key. IfBuilder if_objectiskey(this); if_objectiskey.If<HCompareObjectEqAndBranch>(object, key); if_objectiskey.Then(); { // Make the key_index available. Push(key_index); } if_objectiskey.JoinContinuation(&found); } if_objectissmi.Else(); { if (type->Is(Type::SignedSmall())) { if_objectissmi.Deopt(Deoptimizer::kExpectedSmi); } else { // Check if the object is a heap number. IfBuilder if_objectisnumber(this); HValue* objectisnumber = if_objectisnumber.If<HCompareMap>( object, isolate()->factory()->heap_number_map()); if_objectisnumber.Then(); { // Compute hash for heap number similar to double_get_hash(). HValue* low = Add<HLoadNamedField>( object, objectisnumber, HObjectAccess::ForHeapNumberValueLowestBits()); HValue* high = Add<HLoadNamedField>( object, objectisnumber, HObjectAccess::ForHeapNumberValueHighestBits()); HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, low, high); hash = AddUncasted<HBitwise>(Token::BIT_AND, hash, mask); // Load the key. HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1()); HValue* key = Add<HLoadKeyed>(number_string_cache, key_index, nullptr, FAST_ELEMENTS, ALLOW_RETURN_HOLE); // Check if the key is a heap number and compare it with the object. IfBuilder if_keyisnotsmi(this); HValue* keyisnotsmi = if_keyisnotsmi.IfNot<HIsSmiAndBranch>(key); if_keyisnotsmi.Then(); { IfBuilder if_keyisheapnumber(this); if_keyisheapnumber.If<HCompareMap>( key, isolate()->factory()->heap_number_map()); if_keyisheapnumber.Then(); { // Check if values of key and object match. IfBuilder if_keyeqobject(this); if_keyeqobject.If<HCompareNumericAndBranch>( Add<HLoadNamedField>(key, keyisnotsmi, HObjectAccess::ForHeapNumberValue()), Add<HLoadNamedField>(object, objectisnumber, HObjectAccess::ForHeapNumberValue()), Token::EQ); if_keyeqobject.Then(); { // Make the key_index available. Push(key_index); } if_keyeqobject.JoinContinuation(&found); } if_keyisheapnumber.JoinContinuation(&found); } if_keyisnotsmi.JoinContinuation(&found); } if_objectisnumber.Else(); { if (type->Is(Type::Number())) { if_objectisnumber.Deopt(Deoptimizer::kExpectedHeapNumber); } } if_objectisnumber.JoinContinuation(&found); } } if_objectissmi.JoinContinuation(&found); // Check for cache hit. IfBuilder if_found(this, &found); if_found.Then(); { // Count number to string operation in native code. AddIncrementCounter(isolate()->counters()->number_to_string_native()); // Load the value in case of cache hit. HValue* key_index = Pop(); HValue* value_index = AddUncasted<HAdd>(key_index, graph()->GetConstant1()); Push(Add<HLoadKeyed>(number_string_cache, value_index, nullptr, FAST_ELEMENTS, ALLOW_RETURN_HOLE)); } if_found.Else(); { // Cache miss, fallback to runtime. Add<HPushArguments>(object); Push(Add<HCallRuntime>( isolate()->factory()->empty_string(), Runtime::FunctionForId(Runtime::kNumberToStringSkipCache), 1)); } if_found.End(); return Pop(); } HAllocate* HGraphBuilder::BuildAllocate( HValue* object_size, HType type, InstanceType instance_type, HAllocationMode allocation_mode) { // Compute the effective allocation size. HValue* size = object_size; if (allocation_mode.CreateAllocationMementos()) { size = AddUncasted<HAdd>(size, Add<HConstant>(AllocationMemento::kSize)); size->ClearFlag(HValue::kCanOverflow); } // Perform the actual allocation. HAllocate* object = Add<HAllocate>( size, type, allocation_mode.GetPretenureMode(), instance_type, allocation_mode.feedback_site()); // Setup the allocation memento. if (allocation_mode.CreateAllocationMementos()) { BuildCreateAllocationMemento( object, object_size, allocation_mode.current_site()); } return object; } HValue* HGraphBuilder::BuildAddStringLengths(HValue* left_length, HValue* right_length) { // Compute the combined string length and check against max string length. HValue* length = AddUncasted<HAdd>(left_length, right_length); // Check that length <= kMaxLength <=> length < MaxLength + 1. HValue* max_length = Add<HConstant>(String::kMaxLength + 1); Add<HBoundsCheck>(length, max_length); return length; } HValue* HGraphBuilder::BuildCreateConsString( HValue* length, HValue* left, HValue* right, HAllocationMode allocation_mode) { // Determine the string instance types. HInstruction* left_instance_type = AddLoadStringInstanceType(left); HInstruction* right_instance_type = AddLoadStringInstanceType(right); // Allocate the cons string object. HAllocate does not care whether we // pass CONS_STRING_TYPE or CONS_ONE_BYTE_STRING_TYPE here, so we just use // CONS_STRING_TYPE here. Below we decide whether the cons string is // one-byte or two-byte and set the appropriate map. DCHECK(HAllocate::CompatibleInstanceTypes(CONS_STRING_TYPE, CONS_ONE_BYTE_STRING_TYPE)); HAllocate* result = BuildAllocate(Add<HConstant>(ConsString::kSize), HType::String(), CONS_STRING_TYPE, allocation_mode); // Compute intersection and difference of instance types. HValue* anded_instance_types = AddUncasted<HBitwise>( Token::BIT_AND, left_instance_type, right_instance_type); HValue* xored_instance_types = AddUncasted<HBitwise>( Token::BIT_XOR, left_instance_type, right_instance_type); // We create a one-byte cons string if // 1. both strings are one-byte, or // 2. at least one of the strings is two-byte, but happens to contain only // one-byte characters. // To do this, we check // 1. if both strings are one-byte, or if the one-byte data hint is set in // both strings, or // 2. if one of the strings has the one-byte data hint set and the other // string is one-byte. IfBuilder if_onebyte(this); STATIC_ASSERT(kOneByteStringTag != 0); STATIC_ASSERT(kOneByteDataHintMask != 0); if_onebyte.If<HCompareNumericAndBranch>( AddUncasted<HBitwise>( Token::BIT_AND, anded_instance_types, Add<HConstant>(static_cast<int32_t>( kStringEncodingMask | kOneByteDataHintMask))), graph()->GetConstant0(), Token::NE); if_onebyte.Or(); STATIC_ASSERT(kOneByteStringTag != 0 && kOneByteDataHintTag != 0 && kOneByteDataHintTag != kOneByteStringTag); if_onebyte.If<HCompareNumericAndBranch>( AddUncasted<HBitwise>( Token::BIT_AND, xored_instance_types, Add<HConstant>(static_cast<int32_t>( kOneByteStringTag | kOneByteDataHintTag))), Add<HConstant>(static_cast<int32_t>( kOneByteStringTag | kOneByteDataHintTag)), Token::EQ); if_onebyte.Then(); { // We can safely skip the write barrier for storing the map here. Add<HStoreNamedField>( result, HObjectAccess::ForMap(), Add<HConstant>(isolate()->factory()->cons_one_byte_string_map())); } if_onebyte.Else(); { // We can safely skip the write barrier for storing the map here. Add<HStoreNamedField>( result, HObjectAccess::ForMap(), Add<HConstant>(isolate()->factory()->cons_string_map())); } if_onebyte.End(); // Initialize the cons string fields. Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(), Add<HConstant>(String::kEmptyHashField)); Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length); Add<HStoreNamedField>(result, HObjectAccess::ForConsStringFirst(), left); Add<HStoreNamedField>(result, HObjectAccess::ForConsStringSecond(), right); // Count the native string addition. AddIncrementCounter(isolate()->counters()->string_add_native()); return result; } void HGraphBuilder::BuildCopySeqStringChars(HValue* src, HValue* src_offset, String::Encoding src_encoding, HValue* dst, HValue* dst_offset, String::Encoding dst_encoding, HValue* length) { DCHECK(dst_encoding != String::ONE_BYTE_ENCODING || src_encoding == String::ONE_BYTE_ENCODING); LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement); HValue* index = loop.BeginBody(graph()->GetConstant0(), length, Token::LT); { HValue* src_index = AddUncasted<HAdd>(src_offset, index); HValue* value = AddUncasted<HSeqStringGetChar>(src_encoding, src, src_index); HValue* dst_index = AddUncasted<HAdd>(dst_offset, index); Add<HSeqStringSetChar>(dst_encoding, dst, dst_index, value); } loop.EndBody(); } HValue* HGraphBuilder::BuildObjectSizeAlignment( HValue* unaligned_size, int header_size) { DCHECK((header_size & kObjectAlignmentMask) == 0); HValue* size = AddUncasted<HAdd>( unaligned_size, Add<HConstant>(static_cast<int32_t>( header_size + kObjectAlignmentMask))); size->ClearFlag(HValue::kCanOverflow); return AddUncasted<HBitwise>( Token::BIT_AND, size, Add<HConstant>(static_cast<int32_t>( ~kObjectAlignmentMask))); } HValue* HGraphBuilder::BuildUncheckedStringAdd( HValue* left, HValue* right, HAllocationMode allocation_mode) { // Determine the string lengths. HValue* left_length = AddLoadStringLength(left); HValue* right_length = AddLoadStringLength(right); // Compute the combined string length. HValue* length = BuildAddStringLengths(left_length, right_length); // Do some manual constant folding here. if (left_length->IsConstant()) { HConstant* c_left_length = HConstant::cast(left_length); DCHECK_NE(0, c_left_length->Integer32Value()); if (c_left_length->Integer32Value() + 1 >= ConsString::kMinLength) { // The right string contains at least one character. return BuildCreateConsString(length, left, right, allocation_mode); } } else if (right_length->IsConstant()) { HConstant* c_right_length = HConstant::cast(right_length); DCHECK_NE(0, c_right_length->Integer32Value()); if (c_right_length->Integer32Value() + 1 >= ConsString::kMinLength) { // The left string contains at least one character. return BuildCreateConsString(length, left, right, allocation_mode); } } // Check if we should create a cons string. IfBuilder if_createcons(this); if_createcons.If<HCompareNumericAndBranch>( length, Add<HConstant>(ConsString::kMinLength), Token::GTE); if_createcons.Then(); { // Create a cons string. Push(BuildCreateConsString(length, left, right, allocation_mode)); } if_createcons.Else(); { // Determine the string instance types. HValue* left_instance_type = AddLoadStringInstanceType(left); HValue* right_instance_type = AddLoadStringInstanceType(right); // Compute union and difference of instance types. HValue* ored_instance_types = AddUncasted<HBitwise>( Token::BIT_OR, left_instance_type, right_instance_type); HValue* xored_instance_types = AddUncasted<HBitwise>( Token::BIT_XOR, left_instance_type, right_instance_type); // Check if both strings have the same encoding and both are // sequential. IfBuilder if_sameencodingandsequential(this); if_sameencodingandsequential.If<HCompareNumericAndBranch>( AddUncasted<HBitwise>( Token::BIT_AND, xored_instance_types, Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))), graph()->GetConstant0(), Token::EQ); if_sameencodingandsequential.And(); STATIC_ASSERT(kSeqStringTag == 0); if_sameencodingandsequential.If<HCompareNumericAndBranch>( AddUncasted<HBitwise>( Token::BIT_AND, ored_instance_types, Add<HConstant>(static_cast<int32_t>(kStringRepresentationMask))), graph()->GetConstant0(), Token::EQ); if_sameencodingandsequential.Then(); { HConstant* string_map = Add<HConstant>(isolate()->factory()->string_map()); HConstant* one_byte_string_map = Add<HConstant>(isolate()->factory()->one_byte_string_map()); // Determine map and size depending on whether result is one-byte string. IfBuilder if_onebyte(this); STATIC_ASSERT(kOneByteStringTag != 0); if_onebyte.If<HCompareNumericAndBranch>( AddUncasted<HBitwise>( Token::BIT_AND, ored_instance_types, Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))), graph()->GetConstant0(), Token::NE); if_onebyte.Then(); { // Allocate sequential one-byte string object. Push(length); Push(one_byte_string_map); } if_onebyte.Else(); { // Allocate sequential two-byte string object. HValue* size = AddUncasted<HShl>(length, graph()->GetConstant1()); size->ClearFlag(HValue::kCanOverflow); size->SetFlag(HValue::kUint32); Push(size); Push(string_map); } if_onebyte.End(); HValue* map = Pop(); // Calculate the number of bytes needed for the characters in the // string while observing object alignment. STATIC_ASSERT((SeqString::kHeaderSize & kObjectAlignmentMask) == 0); HValue* size = BuildObjectSizeAlignment(Pop(), SeqString::kHeaderSize); // Allocate the string object. HAllocate does not care whether we pass // STRING_TYPE or ONE_BYTE_STRING_TYPE here, so we just use STRING_TYPE. HAllocate* result = BuildAllocate( size, HType::String(), STRING_TYPE, allocation_mode); Add<HStoreNamedField>(result, HObjectAccess::ForMap(), map); // Initialize the string fields. Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(), Add<HConstant>(String::kEmptyHashField)); Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length); // Copy characters to the result string. IfBuilder if_twobyte(this); if_twobyte.If<HCompareObjectEqAndBranch>(map, string_map); if_twobyte.Then(); { // Copy characters from the left string. BuildCopySeqStringChars( left, graph()->GetConstant0(), String::TWO_BYTE_ENCODING, result, graph()->GetConstant0(), String::TWO_BYTE_ENCODING, left_length); // Copy characters from the right string. BuildCopySeqStringChars( right, graph()->GetConstant0(), String::TWO_BYTE_ENCODING, result, left_length, String::TWO_BYTE_ENCODING, right_length); } if_twobyte.Else(); { // Copy characters from the left string. BuildCopySeqStringChars( left, graph()->GetConstant0(), String::ONE_BYTE_ENCODING, result, graph()->GetConstant0(), String::ONE_BYTE_ENCODING, left_length); // Copy characters from the right string. BuildCopySeqStringChars( right, graph()->GetConstant0(), String::ONE_BYTE_ENCODING, result, left_length, String::ONE_BYTE_ENCODING, right_length); } if_twobyte.End(); // Count the native string addition. AddIncrementCounter(isolate()->counters()->string_add_native()); // Return the sequential string. Push(result); } if_sameencodingandsequential.Else(); { // Fallback to the runtime to add the two strings. Add<HPushArguments>(left, right); Push(Add<HCallRuntime>(isolate()->factory()->empty_string(), Runtime::FunctionForId(Runtime::kStringAddRT), 2)); } if_sameencodingandsequential.End(); } if_createcons.End(); return Pop(); } HValue* HGraphBuilder::BuildStringAdd( HValue* left, HValue* right, HAllocationMode allocation_mode) { NoObservableSideEffectsScope no_effects(this); // Determine string lengths. HValue* left_length = AddLoadStringLength(left); HValue* right_length = AddLoadStringLength(right); // Check if left string is empty. IfBuilder if_leftempty(this); if_leftempty.If<HCompareNumericAndBranch>( left_length, graph()->GetConstant0(), Token::EQ); if_leftempty.Then(); { // Count the native string addition. AddIncrementCounter(isolate()->counters()->string_add_native()); // Just return the right string. Push(right); } if_leftempty.Else(); { // Check if right string is empty. IfBuilder if_rightempty(this); if_rightempty.If<HCompareNumericAndBranch>( right_length, graph()->GetConstant0(), Token::EQ); if_rightempty.Then(); { // Count the native string addition. AddIncrementCounter(isolate()->counters()->string_add_native()); // Just return the left string. Push(left); } if_rightempty.Else(); { // Add the two non-empty strings. Push(BuildUncheckedStringAdd(left, right, allocation_mode)); } if_rightempty.End(); } if_leftempty.End(); return Pop(); } HInstruction* HGraphBuilder::BuildUncheckedMonomorphicElementAccess( HValue* checked_object, HValue* key, HValue* val, bool is_js_array, ElementsKind elements_kind, PropertyAccessType access_type, LoadKeyedHoleMode load_mode, KeyedAccessStoreMode store_mode) { DCHECK((!IsExternalArrayElementsKind(elements_kind) && !IsFixedTypedArrayElementsKind(elements_kind)) || !is_js_array); // No GVNFlag is necessary for ElementsKind if there is an explicit dependency // on a HElementsTransition instruction. The flag can also be removed if the // map to check has FAST_HOLEY_ELEMENTS, since there can be no further // ElementsKind transitions. Finally, the dependency can be removed for stores // for FAST_ELEMENTS, since a transition to HOLEY elements won't change the // generated store code. if ((elements_kind == FAST_HOLEY_ELEMENTS) || (elements_kind == FAST_ELEMENTS && access_type == STORE)) { checked_object->ClearDependsOnFlag(kElementsKind); } bool fast_smi_only_elements = IsFastSmiElementsKind(elements_kind); bool fast_elements = IsFastObjectElementsKind(elements_kind); HValue* elements = AddLoadElements(checked_object); if (access_type == STORE && (fast_elements || fast_smi_only_elements) && store_mode != STORE_NO_TRANSITION_HANDLE_COW) { HCheckMaps* check_cow_map = Add<HCheckMaps>( elements, isolate()->factory()->fixed_array_map()); check_cow_map->ClearDependsOnFlag(kElementsKind); } HInstruction* length = NULL; if (is_js_array) { length = Add<HLoadNamedField>( checked_object->ActualValue(), checked_object, HObjectAccess::ForArrayLength(elements_kind)); } else { length = AddLoadFixedArrayLength(elements); } length->set_type(HType::Smi()); HValue* checked_key = NULL; if (IsExternalArrayElementsKind(elements_kind) || IsFixedTypedArrayElementsKind(elements_kind)) { HValue* backing_store; if (IsExternalArrayElementsKind(elements_kind)) { backing_store = Add<HLoadNamedField>( elements, nullptr, HObjectAccess::ForExternalArrayExternalPointer()); } else { backing_store = elements; } if (store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) { NoObservableSideEffectsScope no_effects(this); IfBuilder length_checker(this); length_checker.If<HCompareNumericAndBranch>(key, length, Token::LT); length_checker.Then(); IfBuilder negative_checker(this); HValue* bounds_check = negative_checker.If<HCompareNumericAndBranch>( key, graph()->GetConstant0(), Token::GTE); negative_checker.Then(); HInstruction* result = AddElementAccess( backing_store, key, val, bounds_check, elements_kind, access_type); negative_checker.ElseDeopt(Deoptimizer::kNegativeKeyEncountered); negative_checker.End(); length_checker.End(); return result; } else { DCHECK(store_mode == STANDARD_STORE); checked_key = Add<HBoundsCheck>(key, length); return AddElementAccess( backing_store, checked_key, val, checked_object, elements_kind, access_type); } } DCHECK(fast_smi_only_elements || fast_elements || IsFastDoubleElementsKind(elements_kind)); // In case val is stored into a fast smi array, assure that the value is a smi // before manipulating the backing store. Otherwise the actual store may // deopt, leaving the backing store in an invalid state. if (access_type == STORE && IsFastSmiElementsKind(elements_kind) && !val->type().IsSmi()) { val = AddUncasted<HForceRepresentation>(val, Representation::Smi()); } if (IsGrowStoreMode(store_mode)) { NoObservableSideEffectsScope no_effects(this); Representation representation = HStoreKeyed::RequiredValueRepresentation( elements_kind, STORE_TO_INITIALIZED_ENTRY); val = AddUncasted<HForceRepresentation>(val, representation); elements = BuildCheckForCapacityGrow(checked_object, elements, elements_kind, length, key, is_js_array, access_type); checked_key = key; } else { checked_key = Add<HBoundsCheck>(key, length); if (access_type == STORE && (fast_elements || fast_smi_only_elements)) { if (store_mode == STORE_NO_TRANSITION_HANDLE_COW) { NoObservableSideEffectsScope no_effects(this); elements = BuildCopyElementsOnWrite(checked_object, elements, elements_kind, length); } else { HCheckMaps* check_cow_map = Add<HCheckMaps>( elements, isolate()->factory()->fixed_array_map()); check_cow_map->ClearDependsOnFlag(kElementsKind); } } } return AddElementAccess(elements, checked_key, val, checked_object, elements_kind, access_type, load_mode); } HValue* HGraphBuilder::BuildAllocateArrayFromLength( JSArrayBuilder* array_builder, HValue* length_argument) { if (length_argument->IsConstant() && HConstant::cast(length_argument)->HasSmiValue()) { int array_length = HConstant::cast(length_argument)->Integer32Value(); if (array_length == 0) { return array_builder->AllocateEmptyArray(); } else { return array_builder->AllocateArray(length_argument, array_length, length_argument); } } HValue* constant_zero = graph()->GetConstant0(); HConstant* max_alloc_length = Add<HConstant>(JSObject::kInitialMaxFastElementArray); HInstruction* checked_length = Add<HBoundsCheck>(length_argument, max_alloc_length); IfBuilder if_builder(this); if_builder.If<HCompareNumericAndBranch>(checked_length, constant_zero, Token::EQ); if_builder.Then(); const int initial_capacity = JSArray::kPreallocatedArrayElements; HConstant* initial_capacity_node = Add<HConstant>(initial_capacity); Push(initial_capacity_node); // capacity Push(constant_zero); // length if_builder.Else(); if (!(top_info()->IsStub()) && IsFastPackedElementsKind(array_builder->kind())) { // We'll come back later with better (holey) feedback. if_builder.Deopt( Deoptimizer::kHoleyArrayDespitePackedElements_kindFeedback); } else { Push(checked_length); // capacity Push(checked_length); // length } if_builder.End(); // Figure out total size HValue* length = Pop(); HValue* capacity = Pop(); return array_builder->AllocateArray(capacity, max_alloc_length, length); } HValue* HGraphBuilder::BuildCalculateElementsSize(ElementsKind kind, HValue* capacity) { int elements_size = IsFastDoubleElementsKind(kind) ? kDoubleSize : kPointerSize; HConstant* elements_size_value = Add<HConstant>(elements_size); HInstruction* mul = HMul::NewImul(isolate(), zone(), context(), capacity->ActualValue(), elements_size_value); AddInstruction(mul); mul->ClearFlag(HValue::kCanOverflow); STATIC_ASSERT(FixedDoubleArray::kHeaderSize == FixedArray::kHeaderSize); HConstant* header_size = Add<HConstant>(FixedArray::kHeaderSize); HValue* total_size = AddUncasted<HAdd>(mul, header_size); total_size->ClearFlag(HValue::kCanOverflow); return total_size; } HAllocate* HGraphBuilder::AllocateJSArrayObject(AllocationSiteMode mode) { int base_size = JSArray::kSize; if (mode == TRACK_ALLOCATION_SITE) { base_size += AllocationMemento::kSize; } HConstant* size_in_bytes = Add<HConstant>(base_size); return Add<HAllocate>( size_in_bytes, HType::JSArray(), NOT_TENURED, JS_OBJECT_TYPE); } HConstant* HGraphBuilder::EstablishElementsAllocationSize( ElementsKind kind, int capacity) { int base_size = IsFastDoubleElementsKind(kind) ? FixedDoubleArray::SizeFor(capacity) : FixedArray::SizeFor(capacity); return Add<HConstant>(base_size); } HAllocate* HGraphBuilder::BuildAllocateElements(ElementsKind kind, HValue* size_in_bytes) { InstanceType instance_type = IsFastDoubleElementsKind(kind) ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE; return Add<HAllocate>(size_in_bytes, HType::HeapObject(), NOT_TENURED, instance_type); } void HGraphBuilder::BuildInitializeElementsHeader(HValue* elements, ElementsKind kind, HValue* capacity) { Factory* factory = isolate()->factory(); Handle<Map> map = IsFastDoubleElementsKind(kind) ? factory->fixed_double_array_map() : factory->fixed_array_map(); Add<HStoreNamedField>(elements, HObjectAccess::ForMap(), Add<HConstant>(map)); Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(), capacity); } HValue* HGraphBuilder::BuildAllocateAndInitializeArray(ElementsKind kind, HValue* capacity) { // The HForceRepresentation is to prevent possible deopt on int-smi // conversion after allocation but before the new object fields are set. capacity = AddUncasted<HForceRepresentation>(capacity, Representation::Smi()); HValue* size_in_bytes = BuildCalculateElementsSize(kind, capacity); HValue* new_array = BuildAllocateElements(kind, size_in_bytes); BuildInitializeElementsHeader(new_array, kind, capacity); return new_array; } void HGraphBuilder::BuildJSArrayHeader(HValue* array, HValue* array_map, HValue* elements, AllocationSiteMode mode, ElementsKind elements_kind, HValue* allocation_site_payload, HValue* length_field) { Add<HStoreNamedField>(array, HObjectAccess::ForMap(), array_map); HConstant* empty_fixed_array = Add<HConstant>(isolate()->factory()->empty_fixed_array()); Add<HStoreNamedField>( array, HObjectAccess::ForPropertiesPointer(), empty_fixed_array); Add<HStoreNamedField>( array, HObjectAccess::ForElementsPointer(), elements != NULL ? elements : empty_fixed_array); Add<HStoreNamedField>( array, HObjectAccess::ForArrayLength(elements_kind), length_field); if (mode == TRACK_ALLOCATION_SITE) { BuildCreateAllocationMemento( array, Add<HConstant>(JSArray::kSize), allocation_site_payload); } } HInstruction* HGraphBuilder::AddElementAccess( HValue* elements, HValue* checked_key, HValue* val, HValue* dependency, ElementsKind elements_kind, PropertyAccessType access_type, LoadKeyedHoleMode load_mode) { if (access_type == STORE) { DCHECK(val != NULL); if (elements_kind == EXTERNAL_UINT8_CLAMPED_ELEMENTS || elements_kind == UINT8_CLAMPED_ELEMENTS) { val = Add<HClampToUint8>(val); } return Add<HStoreKeyed>(elements, checked_key, val, elements_kind, STORE_TO_INITIALIZED_ENTRY); } DCHECK(access_type == LOAD); DCHECK(val == NULL); HLoadKeyed* load = Add<HLoadKeyed>( elements, checked_key, dependency, elements_kind, load_mode); if (elements_kind == EXTERNAL_UINT32_ELEMENTS || elements_kind == UINT32_ELEMENTS) { graph()->RecordUint32Instruction(load); } return load; } HLoadNamedField* HGraphBuilder::AddLoadMap(HValue* object, HValue* dependency) { return Add<HLoadNamedField>(object, dependency, HObjectAccess::ForMap()); } HLoadNamedField* HGraphBuilder::AddLoadElements(HValue* object, HValue* dependency) { return Add<HLoadNamedField>( object, dependency, HObjectAccess::ForElementsPointer()); } HLoadNamedField* HGraphBuilder::AddLoadFixedArrayLength( HValue* array, HValue* dependency) { return Add<HLoadNamedField>( array, dependency, HObjectAccess::ForFixedArrayLength()); } HLoadNamedField* HGraphBuilder::AddLoadArrayLength(HValue* array, ElementsKind kind, HValue* dependency) { return Add<HLoadNamedField>( array, dependency, HObjectAccess::ForArrayLength(kind)); } HValue* HGraphBuilder::BuildNewElementsCapacity(HValue* old_capacity) { HValue* half_old_capacity = AddUncasted<HShr>(old_capacity, graph_->GetConstant1()); HValue* new_capacity = AddUncasted<HAdd>(half_old_capacity, old_capacity); new_capacity->ClearFlag(HValue::kCanOverflow); HValue* min_growth = Add<HConstant>(16); new_capacity = AddUncasted<HAdd>(new_capacity, min_growth); new_capacity->ClearFlag(HValue::kCanOverflow); return new_capacity; } HValue* HGraphBuilder::BuildGrowElementsCapacity(HValue* object, HValue* elements, ElementsKind kind, ElementsKind new_kind, HValue* length, HValue* new_capacity) { Add<HBoundsCheck>(new_capacity, Add<HConstant>( (Page::kMaxRegularHeapObjectSize - FixedArray::kHeaderSize) >> ElementsKindToShiftSize(new_kind))); HValue* new_elements = BuildAllocateAndInitializeArray(new_kind, new_capacity); BuildCopyElements(elements, kind, new_elements, new_kind, length, new_capacity); Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(), new_elements); return new_elements; } void HGraphBuilder::BuildFillElementsWithValue(HValue* elements, ElementsKind elements_kind, HValue* from, HValue* to, HValue* value) { if (to == NULL) { to = AddLoadFixedArrayLength(elements); } // Special loop unfolding case STATIC_ASSERT(JSArray::kPreallocatedArrayElements <= kElementLoopUnrollThreshold); int initial_capacity = -1; if (from->IsInteger32Constant() && to->IsInteger32Constant()) { int constant_from = from->GetInteger32Constant(); int constant_to = to->GetInteger32Constant(); if (constant_from == 0 && constant_to <= kElementLoopUnrollThreshold) { initial_capacity = constant_to; } } if (initial_capacity >= 0) { for (int i = 0; i < initial_capacity; i++) { HInstruction* key = Add<HConstant>(i); Add<HStoreKeyed>(elements, key, value, elements_kind); } } else { // Carefully loop backwards so that the "from" remains live through the loop // rather than the to. This often corresponds to keeping length live rather // then capacity, which helps register allocation, since length is used more // other than capacity after filling with holes. LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement); HValue* key = builder.BeginBody(to, from, Token::GT); HValue* adjusted_key = AddUncasted<HSub>(key, graph()->GetConstant1()); adjusted_key->ClearFlag(HValue::kCanOverflow); Add<HStoreKeyed>(elements, adjusted_key, value, elements_kind); builder.EndBody(); } } void HGraphBuilder::BuildFillElementsWithHole(HValue* elements, ElementsKind elements_kind, HValue* from, HValue* to) { // Fast elements kinds need to be initialized in case statements below cause a // garbage collection. HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind) ? graph()->GetConstantHole() : Add<HConstant>(HConstant::kHoleNaN); // Since we're about to store a hole value, the store instruction below must // assume an elements kind that supports heap object values. if (IsFastSmiOrObjectElementsKind(elements_kind)) { elements_kind = FAST_HOLEY_ELEMENTS; } BuildFillElementsWithValue(elements, elements_kind, from, to, hole); } void HGraphBuilder::BuildCopyProperties(HValue* from_properties, HValue* to_properties, HValue* length, HValue* capacity) { ElementsKind kind = FAST_ELEMENTS; BuildFillElementsWithValue(to_properties, kind, length, capacity, graph()->GetConstantUndefined()); LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement); HValue* key = builder.BeginBody(length, graph()->GetConstant0(), Token::GT); key = AddUncasted<HSub>(key, graph()->GetConstant1()); key->ClearFlag(HValue::kCanOverflow); HValue* element = Add<HLoadKeyed>(from_properties, key, nullptr, kind); Add<HStoreKeyed>(to_properties, key, element, kind); builder.EndBody(); } void HGraphBuilder::BuildCopyElements(HValue* from_elements, ElementsKind from_elements_kind, HValue* to_elements, ElementsKind to_elements_kind, HValue* length, HValue* capacity) { int constant_capacity = -1; if (capacity != NULL && capacity->IsConstant() && HConstant::cast(capacity)->HasInteger32Value()) { int constant_candidate = HConstant::cast(capacity)->Integer32Value(); if (constant_candidate <= kElementLoopUnrollThreshold) { constant_capacity = constant_candidate; } } bool pre_fill_with_holes = IsFastDoubleElementsKind(from_elements_kind) && IsFastObjectElementsKind(to_elements_kind); if (pre_fill_with_holes) { // If the copy might trigger a GC, make sure that the FixedArray is // pre-initialized with holes to make sure that it's always in a // consistent state. BuildFillElementsWithHole(to_elements, to_elements_kind, graph()->GetConstant0(), NULL); } if (constant_capacity != -1) { // Unroll the loop for small elements kinds. for (int i = 0; i < constant_capacity; i++) { HValue* key_constant = Add<HConstant>(i); HInstruction* value = Add<HLoadKeyed>(from_elements, key_constant, nullptr, from_elements_kind); Add<HStoreKeyed>(to_elements, key_constant, value, to_elements_kind); } } else { if (!pre_fill_with_holes && (capacity == NULL || !length->Equals(capacity))) { BuildFillElementsWithHole(to_elements, to_elements_kind, length, NULL); } LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement); HValue* key = builder.BeginBody(length, graph()->GetConstant0(), Token::GT); key = AddUncasted<HSub>(key, graph()->GetConstant1()); key->ClearFlag(HValue::kCanOverflow); HValue* element = Add<HLoadKeyed>(from_elements, key, nullptr, from_elements_kind, ALLOW_RETURN_HOLE); ElementsKind kind = (IsHoleyElementsKind(from_elements_kind) && IsFastSmiElementsKind(to_elements_kind)) ? FAST_HOLEY_ELEMENTS : to_elements_kind; if (IsHoleyElementsKind(from_elements_kind) && from_elements_kind != to_elements_kind) { IfBuilder if_hole(this); if_hole.If<HCompareHoleAndBranch>(element); if_hole.Then(); HConstant* hole_constant = IsFastDoubleElementsKind(to_elements_kind) ? Add<HConstant>(HConstant::kHoleNaN) : graph()->GetConstantHole(); Add<HStoreKeyed>(to_elements, key, hole_constant, kind); if_hole.Else(); HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind); store->SetFlag(HValue::kAllowUndefinedAsNaN); if_hole.End(); } else { HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind); store->SetFlag(HValue::kAllowUndefinedAsNaN); } builder.EndBody(); } Counters* counters = isolate()->counters(); AddIncrementCounter(counters->inlined_copied_elements()); } HValue* HGraphBuilder::BuildCloneShallowArrayCow(HValue* boilerplate, HValue* allocation_site, AllocationSiteMode mode, ElementsKind kind) { HAllocate* array = AllocateJSArrayObject(mode); HValue* map = AddLoadMap(boilerplate); HValue* elements = AddLoadElements(boilerplate); HValue* length = AddLoadArrayLength(boilerplate, kind); BuildJSArrayHeader(array, map, elements, mode, FAST_ELEMENTS, allocation_site, length); return array; } HValue* HGraphBuilder::BuildCloneShallowArrayEmpty(HValue* boilerplate, HValue* allocation_site, AllocationSiteMode mode) { HAllocate* array = AllocateJSArrayObject(mode); HValue* map = AddLoadMap(boilerplate); BuildJSArrayHeader(array, map, NULL, // set elements to empty fixed array mode, FAST_ELEMENTS, allocation_site, graph()->GetConstant0()); return array; } HValue* HGraphBuilder::BuildCloneShallowArrayNonEmpty(HValue* boilerplate, HValue* allocation_site, AllocationSiteMode mode, ElementsKind kind) { HValue* boilerplate_elements = AddLoadElements(boilerplate); HValue* capacity = AddLoadFixedArrayLength(boilerplate_elements); // Generate size calculation code here in order to make it dominate // the JSArray allocation. HValue* elements_size = BuildCalculateElementsSize(kind, capacity); // Create empty JSArray object for now, store elimination should remove // redundant initialization of elements and length fields and at the same // time the object will be fully prepared for GC if it happens during // elements allocation. HValue* result = BuildCloneShallowArrayEmpty( boilerplate, allocation_site, mode); HAllocate* elements = BuildAllocateElements(kind, elements_size); // This function implicitly relies on the fact that the // FastCloneShallowArrayStub is called only for literals shorter than // JSObject::kInitialMaxFastElementArray. // Can't add HBoundsCheck here because otherwise the stub will eager a frame. HConstant* size_upper_bound = EstablishElementsAllocationSize( kind, JSObject::kInitialMaxFastElementArray); elements->set_size_upper_bound(size_upper_bound); Add<HStoreNamedField>(result, HObjectAccess::ForElementsPointer(), elements); // The allocation for the cloned array above causes register pressure on // machines with low register counts. Force a reload of the boilerplate // elements here to free up a register for the allocation to avoid unnecessary // spillage. boilerplate_elements = AddLoadElements(boilerplate); boilerplate_elements->SetFlag(HValue::kCantBeReplaced); // Copy the elements array header. for (int i = 0; i < FixedArrayBase::kHeaderSize; i += kPointerSize) { HObjectAccess access = HObjectAccess::ForFixedArrayHeader(i); Add<HStoreNamedField>( elements, access, Add<HLoadNamedField>(boilerplate_elements, nullptr, access)); } // And the result of the length HValue* length = AddLoadArrayLength(boilerplate, kind); Add<HStoreNamedField>(result, HObjectAccess::ForArrayLength(kind), length); BuildCopyElements(boilerplate_elements, kind, elements, kind, length, NULL); return result; } void HGraphBuilder::BuildCompareNil(HValue* value, Type* type, HIfContinuation* continuation, MapEmbedding map_embedding) { IfBuilder if_nil(this); bool some_case_handled = false; bool some_case_missing = false; if (type->Maybe(Type::Null())) { if (some_case_handled) if_nil.Or(); if_nil.If<HCompareObjectEqAndBranch>(value, graph()->GetConstantNull()); some_case_handled = true; } else { some_case_missing = true; } if (type->Maybe(Type::Undefined())) { if (some_case_handled) if_nil.Or(); if_nil.If<HCompareObjectEqAndBranch>(value, graph()->GetConstantUndefined()); some_case_handled = true; } else { some_case_missing = true; } if (type->Maybe(Type::Undetectable())) { if (some_case_handled) if_nil.Or(); if_nil.If<HIsUndetectableAndBranch>(value); some_case_handled = true; } else { some_case_missing = true; } if (some_case_missing) { if_nil.Then(); if_nil.Else(); if (type->NumClasses() == 1) { BuildCheckHeapObject(value); // For ICs, the map checked below is a sentinel map that gets replaced by // the monomorphic map when the code is used as a template to generate a // new IC. For optimized functions, there is no sentinel map, the map // emitted below is the actual monomorphic map. if (map_embedding == kEmbedMapsViaWeakCells) { HValue* cell = Add<HConstant>(Map::WeakCellForMap(type->Classes().Current())); HValue* expected_map = Add<HLoadNamedField>( cell, nullptr, HObjectAccess::ForWeakCellValue()); HValue* map = Add<HLoadNamedField>(value, nullptr, HObjectAccess::ForMap()); IfBuilder map_check(this); map_check.IfNot<HCompareObjectEqAndBranch>(expected_map, map); map_check.ThenDeopt(Deoptimizer::kUnknownMap); map_check.End(); } else { DCHECK(map_embedding == kEmbedMapsDirectly); Add<HCheckMaps>(value, type->Classes().Current()); } } else { if_nil.Deopt(Deoptimizer::kTooManyUndetectableTypes); } } if_nil.CaptureContinuation(continuation); } void HGraphBuilder::BuildCreateAllocationMemento( HValue* previous_object, HValue* previous_object_size, HValue* allocation_site) { DCHECK(allocation_site != NULL); HInnerAllocatedObject* allocation_memento = Add<HInnerAllocatedObject>( previous_object, previous_object_size, HType::HeapObject()); AddStoreMapConstant( allocation_memento, isolate()->factory()->allocation_memento_map()); Add<HStoreNamedField>( allocation_memento, HObjectAccess::ForAllocationMementoSite(), allocation_site); if (FLAG_allocation_site_pretenuring) { HValue* memento_create_count = Add<HLoadNamedField>(allocation_site, nullptr, HObjectAccess::ForAllocationSiteOffset( AllocationSite::kPretenureCreateCountOffset)); memento_create_count = AddUncasted<HAdd>( memento_create_count, graph()->GetConstant1()); // This smi value is reset to zero after every gc, overflow isn't a problem // since the counter is bounded by the new space size. memento_create_count->ClearFlag(HValue::kCanOverflow); Add<HStoreNamedField>( allocation_site, HObjectAccess::ForAllocationSiteOffset( AllocationSite::kPretenureCreateCountOffset), memento_create_count); } } HInstruction* HGraphBuilder::BuildGetNativeContext(HValue* closure) { // Get the global object, then the native context HInstruction* context = Add<HLoadNamedField>( closure, nullptr, HObjectAccess::ForFunctionContextPointer()); HInstruction* global_object = Add<HLoadNamedField>( context, nullptr, HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset( GlobalObject::kNativeContextOffset); return Add<HLoadNamedField>(global_object, nullptr, access); } HInstruction* HGraphBuilder::BuildGetScriptContext(int context_index) { HValue* native_context = BuildGetNativeContext(); HValue* script_context_table = Add<HLoadNamedField>( native_context, nullptr, HObjectAccess::ForContextSlot(Context::SCRIPT_CONTEXT_TABLE_INDEX)); return Add<HLoadNamedField>(script_context_table, nullptr, HObjectAccess::ForScriptContext(context_index)); } HInstruction* HGraphBuilder::BuildGetNativeContext() { // Get the global object, then the native context HValue* global_object = Add<HLoadNamedField>( context(), nullptr, HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); return Add<HLoadNamedField>(global_object, nullptr, HObjectAccess::ForObservableJSObjectOffset( GlobalObject::kNativeContextOffset)); } HInstruction* HGraphBuilder::BuildGetArrayFunction() { HInstruction* native_context = BuildGetNativeContext(); HInstruction* index = Add<HConstant>(static_cast<int32_t>(Context::ARRAY_FUNCTION_INDEX)); return Add<HLoadKeyed>(native_context, index, nullptr, FAST_ELEMENTS); } HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder, ElementsKind kind, HValue* allocation_site_payload, HValue* constructor_function, AllocationSiteOverrideMode override_mode) : builder_(builder), kind_(kind), allocation_site_payload_(allocation_site_payload), constructor_function_(constructor_function) { DCHECK(!allocation_site_payload->IsConstant() || HConstant::cast(allocation_site_payload)->handle( builder_->isolate())->IsAllocationSite()); mode_ = override_mode == DISABLE_ALLOCATION_SITES ? DONT_TRACK_ALLOCATION_SITE : AllocationSite::GetMode(kind); } HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder, ElementsKind kind, HValue* constructor_function) : builder_(builder), kind_(kind), mode_(DONT_TRACK_ALLOCATION_SITE), allocation_site_payload_(NULL), constructor_function_(constructor_function) { } HValue* HGraphBuilder::JSArrayBuilder::EmitMapCode() { if (!builder()->top_info()->IsStub()) { // A constant map is fine. Handle<Map> map(builder()->isolate()->get_initial_js_array_map(kind_), builder()->isolate()); return builder()->Add<HConstant>(map); } if (constructor_function_ != NULL && kind_ == GetInitialFastElementsKind()) { // No need for a context lookup if the kind_ matches the initial // map, because we can just load the map in that case. HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap(); return builder()->Add<HLoadNamedField>(constructor_function_, nullptr, access); } // TODO(mvstanton): we should always have a constructor function if we // are creating a stub. HInstruction* native_context = constructor_function_ != NULL ? builder()->BuildGetNativeContext(constructor_function_) : builder()->BuildGetNativeContext(); HInstruction* index = builder()->Add<HConstant>( static_cast<int32_t>(Context::JS_ARRAY_MAPS_INDEX)); HInstruction* map_array = builder()->Add<HLoadKeyed>(native_context, index, nullptr, FAST_ELEMENTS); HInstruction* kind_index = builder()->Add<HConstant>(kind_); return builder()->Add<HLoadKeyed>(map_array, kind_index, nullptr, FAST_ELEMENTS); } HValue* HGraphBuilder::JSArrayBuilder::EmitInternalMapCode() { // Find the map near the constructor function HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap(); return builder()->Add<HLoadNamedField>(constructor_function_, nullptr, access); } HAllocate* HGraphBuilder::JSArrayBuilder::AllocateEmptyArray() { HConstant* capacity = builder()->Add<HConstant>(initial_capacity()); return AllocateArray(capacity, capacity, builder()->graph()->GetConstant0()); } HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray( HValue* capacity, HConstant* capacity_upper_bound, HValue* length_field, FillMode fill_mode) { return AllocateArray(capacity, capacity_upper_bound->GetInteger32Constant(), length_field, fill_mode); } HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray( HValue* capacity, int capacity_upper_bound, HValue* length_field, FillMode fill_mode) { HConstant* elememts_size_upper_bound = capacity->IsInteger32Constant() ? HConstant::cast(capacity) : builder()->EstablishElementsAllocationSize(kind_, capacity_upper_bound); HAllocate* array = AllocateArray(capacity, length_field, fill_mode); if (!elements_location_->has_size_upper_bound()) { elements_location_->set_size_upper_bound(elememts_size_upper_bound); } return array; } HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray( HValue* capacity, HValue* length_field, FillMode fill_mode) { // These HForceRepresentations are because we store these as fields in the // objects we construct, and an int32-to-smi HChange could deopt. Accept // the deopt possibility now, before allocation occurs. capacity = builder()->AddUncasted<HForceRepresentation>(capacity, Representation::Smi()); length_field = builder()->AddUncasted<HForceRepresentation>(length_field, Representation::Smi()); // Generate size calculation code here in order to make it dominate // the JSArray allocation. HValue* elements_size = builder()->BuildCalculateElementsSize(kind_, capacity); // Allocate (dealing with failure appropriately) HAllocate* array_object = builder()->AllocateJSArrayObject(mode_); // Fill in the fields: map, properties, length HValue* map; if (allocation_site_payload_ == NULL) { map = EmitInternalMapCode(); } else { map = EmitMapCode(); } builder()->BuildJSArrayHeader(array_object, map, NULL, // set elements to empty fixed array mode_, kind_, allocation_site_payload_, length_field); // Allocate and initialize the elements elements_location_ = builder()->BuildAllocateElements(kind_, elements_size); builder()->BuildInitializeElementsHeader(elements_location_, kind_, capacity); // Set the elements builder()->Add<HStoreNamedField>( array_object, HObjectAccess::ForElementsPointer(), elements_location_); if (fill_mode == FILL_WITH_HOLE) { builder()->BuildFillElementsWithHole(elements_location_, kind_, graph()->GetConstant0(), capacity); } return array_object; } HValue* HGraphBuilder::AddLoadJSBuiltin(Builtins::JavaScript builtin) { HValue* global_object = Add<HLoadNamedField>( context(), nullptr, HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset( GlobalObject::kBuiltinsOffset); HValue* builtins = Add<HLoadNamedField>(global_object, nullptr, access); HObjectAccess function_access = HObjectAccess::ForObservableJSObjectOffset( JSBuiltinsObject::OffsetOfFunctionWithId(builtin)); return Add<HLoadNamedField>(builtins, nullptr, function_access); } HOptimizedGraphBuilder::HOptimizedGraphBuilder(CompilationInfo* info) : HGraphBuilder(info), function_state_(NULL), initial_function_state_(this, info, NORMAL_RETURN, 0), ast_context_(NULL), break_scope_(NULL), inlined_count_(0), globals_(10, info->zone()), osr_(new(info->zone()) HOsrBuilder(this)) { // This is not initialized in the initializer list because the // constructor for the initial state relies on function_state_ == NULL // to know it's the initial state. function_state_ = &initial_function_state_; InitializeAstVisitor(info->isolate(), info->zone()); if (top_info()->is_tracking_positions()) { SetSourcePosition(info->shared_info()->start_position()); } } HBasicBlock* HOptimizedGraphBuilder::CreateJoin(HBasicBlock* first, HBasicBlock* second, BailoutId join_id) { if (first == NULL) { return second; } else if (second == NULL) { return first; } else { HBasicBlock* join_block = graph()->CreateBasicBlock(); Goto(first, join_block); Goto(second, join_block); join_block->SetJoinId(join_id); return join_block; } } HBasicBlock* HOptimizedGraphBuilder::JoinContinue(IterationStatement* statement, HBasicBlock* exit_block, HBasicBlock* continue_block) { if (continue_block != NULL) { if (exit_block != NULL) Goto(exit_block, continue_block); continue_block->SetJoinId(statement->ContinueId()); return continue_block; } return exit_block; } HBasicBlock* HOptimizedGraphBuilder::CreateLoop(IterationStatement* statement, HBasicBlock* loop_entry, HBasicBlock* body_exit, HBasicBlock* loop_successor, HBasicBlock* break_block) { if (body_exit != NULL) Goto(body_exit, loop_entry); loop_entry->PostProcessLoopHeader(statement); if (break_block != NULL) { if (loop_successor != NULL) Goto(loop_successor, break_block); break_block->SetJoinId(statement->ExitId()); return break_block; } return loop_successor; } // Build a new loop header block and set it as the current block. HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry() { HBasicBlock* loop_entry = CreateLoopHeaderBlock(); Goto(loop_entry); set_current_block(loop_entry); return loop_entry; } HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry( IterationStatement* statement) { HBasicBlock* loop_entry = osr()->HasOsrEntryAt(statement) ? osr()->BuildOsrLoopEntry(statement) : BuildLoopEntry(); return loop_entry; } void HBasicBlock::FinishExit(HControlInstruction* instruction, SourcePosition position) { Finish(instruction, position); ClearEnvironment(); } std::ostream& operator<<(std::ostream& os, const HBasicBlock& b) { return os << "B" << b.block_id(); } HGraph::HGraph(CompilationInfo* info) : isolate_(info->isolate()), next_block_id_(0), entry_block_(NULL), blocks_(8, info->zone()), values_(16, info->zone()), phi_list_(NULL), uint32_instructions_(NULL), osr_(NULL), info_(info), zone_(info->zone()), is_recursive_(false), this_has_uses_(false), use_optimistic_licm_(false), depends_on_empty_array_proto_elements_(false), type_change_checksum_(0), maximum_environment_size_(0), no_side_effects_scope_count_(0), disallow_adding_new_values_(false) { if (info->IsStub()) { CallInterfaceDescriptor descriptor = info->code_stub()->GetCallInterfaceDescriptor(); start_environment_ = new (zone_) HEnvironment(zone_, descriptor.GetEnvironmentParameterCount()); } else { if (info->is_tracking_positions()) { info->TraceInlinedFunction(info->shared_info(), SourcePosition::Unknown(), InlinedFunctionInfo::kNoParentId); } start_environment_ = new(zone_) HEnvironment(NULL, info->scope(), info->closure(), zone_); } start_environment_->set_ast_id(BailoutId::FunctionEntry()); entry_block_ = CreateBasicBlock(); entry_block_->SetInitialEnvironment(start_environment_); } HBasicBlock* HGraph::CreateBasicBlock() { HBasicBlock* result = new(zone()) HBasicBlock(this); blocks_.Add(result, zone()); return result; } void HGraph::FinalizeUniqueness() { DisallowHeapAllocation no_gc; DCHECK(!OptimizingCompilerThread::IsOptimizerThread(isolate())); for (int i = 0; i < blocks()->length(); ++i) { for (HInstructionIterator it(blocks()->at(i)); !it.Done(); it.Advance()) { it.Current()->FinalizeUniqueness(); } } } int HGraph::SourcePositionToScriptPosition(SourcePosition pos) { return (FLAG_hydrogen_track_positions && !pos.IsUnknown()) ? info()->start_position_for(pos.inlining_id()) + pos.position() : pos.raw(); } // Block ordering was implemented with two mutually recursive methods, // HGraph::Postorder and HGraph::PostorderLoopBlocks. // The recursion could lead to stack overflow so the algorithm has been // implemented iteratively. // At a high level the algorithm looks like this: // // Postorder(block, loop_header) : { // if (block has already been visited or is of another loop) return; // mark block as visited; // if (block is a loop header) { // VisitLoopMembers(block, loop_header); // VisitSuccessorsOfLoopHeader(block); // } else { // VisitSuccessors(block) // } // put block in result list; // } // // VisitLoopMembers(block, outer_loop_header) { // foreach (block b in block loop members) { // VisitSuccessorsOfLoopMember(b, outer_loop_header); // if (b is loop header) VisitLoopMembers(b); // } // } // // VisitSuccessorsOfLoopMember(block, outer_loop_header) { // foreach (block b in block successors) Postorder(b, outer_loop_header) // } // // VisitSuccessorsOfLoopHeader(block) { // foreach (block b in block successors) Postorder(b, block) // } // // VisitSuccessors(block, loop_header) { // foreach (block b in block successors) Postorder(b, loop_header) // } // // The ordering is started calling Postorder(entry, NULL). // // Each instance of PostorderProcessor represents the "stack frame" of the // recursion, and particularly keeps the state of the loop (iteration) of the // "Visit..." function it represents. // To recycle memory we keep all the frames in a double linked list but // this means that we cannot use constructors to initialize the frames. // class PostorderProcessor : public ZoneObject { public: // Back link (towards the stack bottom). PostorderProcessor* parent() {return father_; } // Forward link (towards the stack top). PostorderProcessor* child() {return child_; } HBasicBlock* block() { return block_; } HLoopInformation* loop() { return loop_; } HBasicBlock* loop_header() { return loop_header_; } static PostorderProcessor* CreateEntryProcessor(Zone* zone, HBasicBlock* block) { PostorderProcessor* result = new(zone) PostorderProcessor(NULL); return result->SetupSuccessors(zone, block, NULL); } PostorderProcessor* PerformStep(Zone* zone, ZoneList<HBasicBlock*>* order) { PostorderProcessor* next = PerformNonBacktrackingStep(zone, order); if (next != NULL) { return next; } else { return Backtrack(zone, order); } } private: explicit PostorderProcessor(PostorderProcessor* father) : father_(father), child_(NULL), successor_iterator(NULL) { } // Each enum value states the cycle whose state is kept by this instance. enum LoopKind { NONE, SUCCESSORS, SUCCESSORS_OF_LOOP_HEADER, LOOP_MEMBERS, SUCCESSORS_OF_LOOP_MEMBER }; // Each "Setup..." method is like a constructor for a cycle state. PostorderProcessor* SetupSuccessors(Zone* zone, HBasicBlock* block, HBasicBlock* loop_header) { if (block == NULL || block->IsOrdered() || block->parent_loop_header() != loop_header) { kind_ = NONE; block_ = NULL; loop_ = NULL; loop_header_ = NULL; return this; } else { block_ = block; loop_ = NULL; block->MarkAsOrdered(); if (block->IsLoopHeader()) { kind_ = SUCCESSORS_OF_LOOP_HEADER; loop_header_ = block; InitializeSuccessors(); PostorderProcessor* result = Push(zone); return result->SetupLoopMembers(zone, block, block->loop_information(), loop_header); } else { DCHECK(block->IsFinished()); kind_ = SUCCESSORS; loop_header_ = loop_header; InitializeSuccessors(); return this; } } } PostorderProcessor* SetupLoopMembers(Zone* zone, HBasicBlock* block, HLoopInformation* loop, HBasicBlock* loop_header) { kind_ = LOOP_MEMBERS; block_ = block; loop_ = loop; loop_header_ = loop_header; InitializeLoopMembers(); return this; } PostorderProcessor* SetupSuccessorsOfLoopMember( HBasicBlock* block, HLoopInformation* loop, HBasicBlock* loop_header) { kind_ = SUCCESSORS_OF_LOOP_MEMBER; block_ = block; loop_ = loop; loop_header_ = loop_header; InitializeSuccessors(); return this; } // This method "allocates" a new stack frame. PostorderProcessor* Push(Zone* zone) { if (child_ == NULL) { child_ = new(zone) PostorderProcessor(this); } return child_; } void ClosePostorder(ZoneList<HBasicBlock*>* order, Zone* zone) { DCHECK(block_->end()->FirstSuccessor() == NULL || order->Contains(block_->end()->FirstSuccessor()) || block_->end()->FirstSuccessor()->IsLoopHeader()); DCHECK(block_->end()->SecondSuccessor() == NULL || order->Contains(block_->end()->SecondSuccessor()) || block_->end()->SecondSuccessor()->IsLoopHeader()); order->Add(block_, zone); } // This method is the basic block to walk up the stack. PostorderProcessor* Pop(Zone* zone, ZoneList<HBasicBlock*>* order) { switch (kind_) { case SUCCESSORS: case SUCCESSORS_OF_LOOP_HEADER: ClosePostorder(order, zone); return father_; case LOOP_MEMBERS: return father_; case SUCCESSORS_OF_LOOP_MEMBER: if (block()->IsLoopHeader() && block() != loop_->loop_header()) { // In this case we need to perform a LOOP_MEMBERS cycle so we // initialize it and return this instead of father. return SetupLoopMembers(zone, block(), block()->loop_information(), loop_header_); } else { return father_; } case NONE: return father_; } UNREACHABLE(); return NULL; } // Walks up the stack. PostorderProcessor* Backtrack(Zone* zone, ZoneList<HBasicBlock*>* order) { PostorderProcessor* parent = Pop(zone, order); while (parent != NULL) { PostorderProcessor* next = parent->PerformNonBacktrackingStep(zone, order); if (next != NULL) { return next; } else { parent = parent->Pop(zone, order); } } return NULL; } PostorderProcessor* PerformNonBacktrackingStep( Zone* zone, ZoneList<HBasicBlock*>* order) { HBasicBlock* next_block; switch (kind_) { case SUCCESSORS: next_block = AdvanceSuccessors(); if (next_block != NULL) { PostorderProcessor* result = Push(zone); return result->SetupSuccessors(zone, next_block, loop_header_); } break; case SUCCESSORS_OF_LOOP_HEADER: next_block = AdvanceSuccessors(); if (next_block != NULL) { PostorderProcessor* result = Push(zone); return result->SetupSuccessors(zone, next_block, block()); } break; case LOOP_MEMBERS: next_block = AdvanceLoopMembers(); if (next_block != NULL) { PostorderProcessor* result = Push(zone); return result->SetupSuccessorsOfLoopMember(next_block, loop_, loop_header_); } break; case SUCCESSORS_OF_LOOP_MEMBER: next_block = AdvanceSuccessors(); if (next_block != NULL) { PostorderProcessor* result = Push(zone); return result->SetupSuccessors(zone, next_block, loop_header_); } break; case NONE: return NULL; } return NULL; } // The following two methods implement a "foreach b in successors" cycle. void InitializeSuccessors() { loop_index = 0; loop_length = 0; successor_iterator = HSuccessorIterator(block_->end()); } HBasicBlock* AdvanceSuccessors() { if (!successor_iterator.Done()) { HBasicBlock* result = successor_iterator.Current(); successor_iterator.Advance(); return result; } return NULL; } // The following two methods implement a "foreach b in loop members" cycle. void InitializeLoopMembers() { loop_index = 0; loop_length = loop_->blocks()->length(); } HBasicBlock* AdvanceLoopMembers() { if (loop_index < loop_length) { HBasicBlock* result = loop_->blocks()->at(loop_index); loop_index++; return result; } else { return NULL; } } LoopKind kind_; PostorderProcessor* father_; PostorderProcessor* child_; HLoopInformation* loop_; HBasicBlock* block_; HBasicBlock* loop_header_; int loop_index; int loop_length; HSuccessorIterator successor_iterator; }; void HGraph::OrderBlocks() { CompilationPhase phase("H_Block ordering", info()); #ifdef DEBUG // Initially the blocks must not be ordered. for (int i = 0; i < blocks_.length(); ++i) { DCHECK(!blocks_[i]->IsOrdered()); } #endif PostorderProcessor* postorder = PostorderProcessor::CreateEntryProcessor(zone(), blocks_[0]); blocks_.Rewind(0); while (postorder) { postorder = postorder->PerformStep(zone(), &blocks_); } #ifdef DEBUG // Now all blocks must be marked as ordered. for (int i = 0; i < blocks_.length(); ++i) { DCHECK(blocks_[i]->IsOrdered()); } #endif // Reverse block list and assign block IDs. for (int i = 0, j = blocks_.length(); --j >= i; ++i) { HBasicBlock* bi = blocks_[i]; HBasicBlock* bj = blocks_[j]; bi->set_block_id(j); bj->set_block_id(i); blocks_[i] = bj; blocks_[j] = bi; } } void HGraph::AssignDominators() { HPhase phase("H_Assign dominators", this); for (int i = 0; i < blocks_.length(); ++i) { HBasicBlock* block = blocks_[i]; if (block->IsLoopHeader()) { // Only the first predecessor of a loop header is from outside the loop. // All others are back edges, and thus cannot dominate the loop header. block->AssignCommonDominator(block->predecessors()->first()); block->AssignLoopSuccessorDominators(); } else { for (int j = blocks_[i]->predecessors()->length() - 1; j >= 0; --j) { blocks_[i]->AssignCommonDominator(blocks_[i]->predecessors()->at(j)); } } } } bool HGraph::CheckArgumentsPhiUses() { int block_count = blocks_.length(); for (int i = 0; i < block_count; ++i) { for (int j = 0; j < blocks_[i]->phis()->length(); ++j) { HPhi* phi = blocks_[i]->phis()->at(j); // We don't support phi uses of arguments for now. if (phi->CheckFlag(HValue::kIsArguments)) return false; } } return true; } bool HGraph::CheckConstPhiUses() { int block_count = blocks_.length(); for (int i = 0; i < block_count; ++i) { for (int j = 0; j < blocks_[i]->phis()->length(); ++j) { HPhi* phi = blocks_[i]->phis()->at(j); // Check for the hole value (from an uninitialized const). for (int k = 0; k < phi->OperandCount(); k++) { if (phi->OperandAt(k) == GetConstantHole()) return false; } } } return true; } void HGraph::CollectPhis() { int block_count = blocks_.length(); phi_list_ = new(zone()) ZoneList<HPhi*>(block_count, zone()); for (int i = 0; i < block_count; ++i) { for (int j = 0; j < blocks_[i]->phis()->length(); ++j) { HPhi* phi = blocks_[i]->phis()->at(j); phi_list_->Add(phi, zone()); } } } // Implementation of utility class to encapsulate the translation state for // a (possibly inlined) function. FunctionState::FunctionState(HOptimizedGraphBuilder* owner, CompilationInfo* info, InliningKind inlining_kind, int inlining_id) : owner_(owner), compilation_info_(info), call_context_(NULL), inlining_kind_(inlining_kind), function_return_(NULL), test_context_(NULL), entry_(NULL), arguments_object_(NULL), arguments_elements_(NULL), inlining_id_(inlining_id), outer_source_position_(SourcePosition::Unknown()), outer_(owner->function_state()) { if (outer_ != NULL) { // State for an inline function. if (owner->ast_context()->IsTest()) { HBasicBlock* if_true = owner->graph()->CreateBasicBlock(); HBasicBlock* if_false = owner->graph()->CreateBasicBlock(); if_true->MarkAsInlineReturnTarget(owner->current_block()); if_false->MarkAsInlineReturnTarget(owner->current_block()); TestContext* outer_test_context = TestContext::cast(owner->ast_context()); Expression* cond = outer_test_context->condition(); // The AstContext constructor pushed on the context stack. This newed // instance is the reason that AstContext can't be BASE_EMBEDDED. test_context_ = new TestContext(owner, cond, if_true, if_false); } else { function_return_ = owner->graph()->CreateBasicBlock(); function_return()->MarkAsInlineReturnTarget(owner->current_block()); } // Set this after possibly allocating a new TestContext above. call_context_ = owner->ast_context(); } // Push on the state stack. owner->set_function_state(this); if (compilation_info_->is_tracking_positions()) { outer_source_position_ = owner->source_position(); owner->EnterInlinedSource( info->shared_info()->start_position(), inlining_id); owner->SetSourcePosition(info->shared_info()->start_position()); } } FunctionState::~FunctionState() { delete test_context_; owner_->set_function_state(outer_); if (compilation_info_->is_tracking_positions()) { owner_->set_source_position(outer_source_position_); owner_->EnterInlinedSource( outer_->compilation_info()->shared_info()->start_position(), outer_->inlining_id()); } } // Implementation of utility classes to represent an expression's context in // the AST. AstContext::AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind) : owner_(owner), kind_(kind), outer_(owner->ast_context()), for_typeof_(false) { owner->set_ast_context(this); // Push. #ifdef DEBUG DCHECK(owner->environment()->frame_type() == JS_FUNCTION); original_length_ = owner->environment()->length(); #endif } AstContext::~AstContext() { owner_->set_ast_context(outer_); // Pop. } EffectContext::~EffectContext() { DCHECK(owner()->HasStackOverflow() || owner()->current_block() == NULL || (owner()->environment()->length() == original_length_ && owner()->environment()->frame_type() == JS_FUNCTION)); } ValueContext::~ValueContext() { DCHECK(owner()->HasStackOverflow() || owner()->current_block() == NULL || (owner()->environment()->length() == original_length_ + 1 && owner()->environment()->frame_type() == JS_FUNCTION)); } void EffectContext::ReturnValue(HValue* value) { // The value is simply ignored. } void ValueContext::ReturnValue(HValue* value) { // The value is tracked in the bailout environment, and communicated // through the environment as the result of the expression. if (value->CheckFlag(HValue::kIsArguments)) { if (flag_ == ARGUMENTS_FAKED) { value = owner()->graph()->GetConstantUndefined(); } else if (!arguments_allowed()) { owner()->Bailout(kBadValueContextForArgumentsValue); } } owner()->Push(value); } void TestContext::ReturnValue(HValue* value) { BuildBranch(value); } void EffectContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) { DCHECK(!instr->IsControlInstruction()); owner()->AddInstruction(instr); if (instr->HasObservableSideEffects()) { owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } } void EffectContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) { DCHECK(!instr->HasObservableSideEffects()); HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock(); HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock(); instr->SetSuccessorAt(0, empty_true); instr->SetSuccessorAt(1, empty_false); owner()->FinishCurrentBlock(instr); HBasicBlock* join = owner()->CreateJoin(empty_true, empty_false, ast_id); owner()->set_current_block(join); } void EffectContext::ReturnContinuation(HIfContinuation* continuation, BailoutId ast_id) { HBasicBlock* true_branch = NULL; HBasicBlock* false_branch = NULL; continuation->Continue(&true_branch, &false_branch); if (!continuation->IsTrueReachable()) { owner()->set_current_block(false_branch); } else if (!continuation->IsFalseReachable()) { owner()->set_current_block(true_branch); } else { HBasicBlock* join = owner()->CreateJoin(true_branch, false_branch, ast_id); owner()->set_current_block(join); } } void ValueContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) { DCHECK(!instr->IsControlInstruction()); if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) { return owner()->Bailout(kBadValueContextForArgumentsObjectValue); } owner()->AddInstruction(instr); owner()->Push(instr); if (instr->HasObservableSideEffects()) { owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } } void ValueContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) { DCHECK(!instr->HasObservableSideEffects()); if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) { return owner()->Bailout(kBadValueContextForArgumentsObjectValue); } HBasicBlock* materialize_false = owner()->graph()->CreateBasicBlock(); HBasicBlock* materialize_true = owner()->graph()->CreateBasicBlock(); instr->SetSuccessorAt(0, materialize_true); instr->SetSuccessorAt(1, materialize_false); owner()->FinishCurrentBlock(instr); owner()->set_current_block(materialize_true); owner()->Push(owner()->graph()->GetConstantTrue()); owner()->set_current_block(materialize_false); owner()->Push(owner()->graph()->GetConstantFalse()); HBasicBlock* join = owner()->CreateJoin(materialize_true, materialize_false, ast_id); owner()->set_current_block(join); } void ValueContext::ReturnContinuation(HIfContinuation* continuation, BailoutId ast_id) { HBasicBlock* materialize_true = NULL; HBasicBlock* materialize_false = NULL; continuation->Continue(&materialize_true, &materialize_false); if (continuation->IsTrueReachable()) { owner()->set_current_block(materialize_true); owner()->Push(owner()->graph()->GetConstantTrue()); owner()->set_current_block(materialize_true); } if (continuation->IsFalseReachable()) { owner()->set_current_block(materialize_false); owner()->Push(owner()->graph()->GetConstantFalse()); owner()->set_current_block(materialize_false); } if (continuation->TrueAndFalseReachable()) { HBasicBlock* join = owner()->CreateJoin(materialize_true, materialize_false, ast_id); owner()->set_current_block(join); } } void TestContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) { DCHECK(!instr->IsControlInstruction()); HOptimizedGraphBuilder* builder = owner(); builder->AddInstruction(instr); // We expect a simulate after every expression with side effects, though // this one isn't actually needed (and wouldn't work if it were targeted). if (instr->HasObservableSideEffects()) { builder->Push(instr); builder->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); builder->Pop(); } BuildBranch(instr); } void TestContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) { DCHECK(!instr->HasObservableSideEffects()); HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock(); HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock(); instr->SetSuccessorAt(0, empty_true); instr->SetSuccessorAt(1, empty_false); owner()->FinishCurrentBlock(instr); owner()->Goto(empty_true, if_true(), owner()->function_state()); owner()->Goto(empty_false, if_false(), owner()->function_state()); owner()->set_current_block(NULL); } void TestContext::ReturnContinuation(HIfContinuation* continuation, BailoutId ast_id) { HBasicBlock* true_branch = NULL; HBasicBlock* false_branch = NULL; continuation->Continue(&true_branch, &false_branch); if (continuation->IsTrueReachable()) { owner()->Goto(true_branch, if_true(), owner()->function_state()); } if (continuation->IsFalseReachable()) { owner()->Goto(false_branch, if_false(), owner()->function_state()); } owner()->set_current_block(NULL); } void TestContext::BuildBranch(HValue* value) { // We expect the graph to be in edge-split form: there is no edge that // connects a branch node to a join node. We conservatively ensure that // property by always adding an empty block on the outgoing edges of this // branch. HOptimizedGraphBuilder* builder = owner(); if (value != NULL && value->CheckFlag(HValue::kIsArguments)) { builder->Bailout(kArgumentsObjectValueInATestContext); } ToBooleanStub::Types expected(condition()->to_boolean_types()); ReturnControl(owner()->New<HBranch>(value, expected), BailoutId::None()); } // HOptimizedGraphBuilder infrastructure for bailing out and checking bailouts. #define CHECK_BAILOUT(call) \ do { \ call; \ if (HasStackOverflow()) return; \ } while (false) #define CHECK_ALIVE(call) \ do { \ call; \ if (HasStackOverflow() || current_block() == NULL) return; \ } while (false) #define CHECK_ALIVE_OR_RETURN(call, value) \ do { \ call; \ if (HasStackOverflow() || current_block() == NULL) return value; \ } while (false) void HOptimizedGraphBuilder::Bailout(BailoutReason reason) { current_info()->AbortOptimization(reason); SetStackOverflow(); } void HOptimizedGraphBuilder::VisitForEffect(Expression* expr) { EffectContext for_effect(this); Visit(expr); } void HOptimizedGraphBuilder::VisitForValue(Expression* expr, ArgumentsAllowedFlag flag) { ValueContext for_value(this, flag); Visit(expr); } void HOptimizedGraphBuilder::VisitForTypeOf(Expression* expr) { ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED); for_value.set_for_typeof(true); Visit(expr); } void HOptimizedGraphBuilder::VisitForControl(Expression* expr, HBasicBlock* true_block, HBasicBlock* false_block) { TestContext for_test(this, expr, true_block, false_block); Visit(expr); } void HOptimizedGraphBuilder::VisitExpressions( ZoneList<Expression*>* exprs) { for (int i = 0; i < exprs->length(); ++i) { CHECK_ALIVE(VisitForValue(exprs->at(i))); } } void HOptimizedGraphBuilder::VisitExpressions(ZoneList<Expression*>* exprs, ArgumentsAllowedFlag flag) { for (int i = 0; i < exprs->length(); ++i) { CHECK_ALIVE(VisitForValue(exprs->at(i), flag)); } } bool HOptimizedGraphBuilder::BuildGraph() { if (IsSubclassConstructor(current_info()->function()->kind())) { Bailout(kSuperReference); return false; } Scope* scope = current_info()->scope(); SetUpScope(scope); // Add an edge to the body entry. This is warty: the graph's start // environment will be used by the Lithium translation as the initial // environment on graph entry, but it has now been mutated by the // Hydrogen translation of the instructions in the start block. This // environment uses values which have not been defined yet. These // Hydrogen instructions will then be replayed by the Lithium // translation, so they cannot have an environment effect. The edge to // the body's entry block (along with some special logic for the start // block in HInstruction::InsertAfter) seals the start block from // getting unwanted instructions inserted. // // TODO(kmillikin): Fix this. Stop mutating the initial environment. // Make the Hydrogen instructions in the initial block into Hydrogen // values (but not instructions), present in the initial environment and // not replayed by the Lithium translation. HEnvironment* initial_env = environment()->CopyWithoutHistory(); HBasicBlock* body_entry = CreateBasicBlock(initial_env); Goto(body_entry); body_entry->SetJoinId(BailoutId::FunctionEntry()); set_current_block(body_entry); // Handle implicit declaration of the function name in named function // expressions before other declarations. if (scope->is_function_scope() && scope->function() != NULL) { VisitVariableDeclaration(scope->function()); } VisitDeclarations(scope->declarations()); Add<HSimulate>(BailoutId::Declarations()); Add<HStackCheck>(HStackCheck::kFunctionEntry); VisitStatements(current_info()->function()->body()); if (HasStackOverflow()) return false; if (current_block() != NULL) { Add<HReturn>(graph()->GetConstantUndefined()); set_current_block(NULL); } // If the checksum of the number of type info changes is the same as the // last time this function was compiled, then this recompile is likely not // due to missing/inadequate type feedback, but rather too aggressive // optimization. Disable optimistic LICM in that case. Handle<Code> unoptimized_code(current_info()->shared_info()->code()); DCHECK(unoptimized_code->kind() == Code::FUNCTION); Handle<TypeFeedbackInfo> type_info( TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info())); int checksum = type_info->own_type_change_checksum(); int composite_checksum = graph()->update_type_change_checksum(checksum); graph()->set_use_optimistic_licm( !type_info->matches_inlined_type_change_checksum(composite_checksum)); type_info->set_inlined_type_change_checksum(composite_checksum); // Perform any necessary OSR-specific cleanups or changes to the graph. osr()->FinishGraph(); return true; } bool HGraph::Optimize(BailoutReason* bailout_reason) { OrderBlocks(); AssignDominators(); // We need to create a HConstant "zero" now so that GVN will fold every // zero-valued constant in the graph together. // The constant is needed to make idef-based bounds check work: the pass // evaluates relations with "zero" and that zero cannot be created after GVN. GetConstant0(); #ifdef DEBUG // Do a full verify after building the graph and computing dominators. Verify(true); #endif if (FLAG_analyze_environment_liveness && maximum_environment_size() != 0) { Run<HEnvironmentLivenessAnalysisPhase>(); } if (!CheckConstPhiUses()) { *bailout_reason = kUnsupportedPhiUseOfConstVariable; return false; } Run<HRedundantPhiEliminationPhase>(); if (!CheckArgumentsPhiUses()) { *bailout_reason = kUnsupportedPhiUseOfArguments; return false; } // Find and mark unreachable code to simplify optimizations, especially gvn, // where unreachable code could unnecessarily defeat LICM. Run<HMarkUnreachableBlocksPhase>(); if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>(); if (FLAG_use_escape_analysis) Run<HEscapeAnalysisPhase>(); if (FLAG_load_elimination) Run<HLoadEliminationPhase>(); CollectPhis(); if (has_osr()) osr()->FinishOsrValues(); Run<HInferRepresentationPhase>(); // Remove HSimulate instructions that have turned out not to be needed // after all by folding them into the following HSimulate. // This must happen after inferring representations. Run<HMergeRemovableSimulatesPhase>(); Run<HMarkDeoptimizeOnUndefinedPhase>(); Run<HRepresentationChangesPhase>(); Run<HInferTypesPhase>(); // Must be performed before canonicalization to ensure that Canonicalize // will not remove semantically meaningful ToInt32 operations e.g. BIT_OR with // zero. Run<HUint32AnalysisPhase>(); if (FLAG_use_canonicalizing) Run<HCanonicalizePhase>(); if (FLAG_use_gvn) Run<HGlobalValueNumberingPhase>(); if (FLAG_check_elimination) Run<HCheckEliminationPhase>(); if (FLAG_store_elimination) Run<HStoreEliminationPhase>(); Run<HRangeAnalysisPhase>(); Run<HComputeChangeUndefinedToNaN>(); // Eliminate redundant stack checks on backwards branches. Run<HStackCheckEliminationPhase>(); if (FLAG_array_bounds_checks_elimination) Run<HBoundsCheckEliminationPhase>(); if (FLAG_array_bounds_checks_hoisting) Run<HBoundsCheckHoistingPhase>(); if (FLAG_array_index_dehoisting) Run<HDehoistIndexComputationsPhase>(); if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>(); RestoreActualValues(); // Find unreachable code a second time, GVN and other optimizations may have // made blocks unreachable that were previously reachable. Run<HMarkUnreachableBlocksPhase>(); return true; } void HGraph::RestoreActualValues() { HPhase phase("H_Restore actual values", this); for (int block_index = 0; block_index < blocks()->length(); block_index++) { HBasicBlock* block = blocks()->at(block_index); #ifdef DEBUG for (int i = 0; i < block->phis()->length(); i++) { HPhi* phi = block->phis()->at(i); DCHECK(phi->ActualValue() == phi); } #endif for (HInstructionIterator it(block); !it.Done(); it.Advance()) { HInstruction* instruction = it.Current(); if (instruction->ActualValue() == instruction) continue; if (instruction->CheckFlag(HValue::kIsDead)) { // The instruction was marked as deleted but left in the graph // as a control flow dependency point for subsequent // instructions. instruction->DeleteAndReplaceWith(instruction->ActualValue()); } else { DCHECK(instruction->IsInformativeDefinition()); if (instruction->IsPurelyInformativeDefinition()) { instruction->DeleteAndReplaceWith(instruction->RedefinedOperand()); } else { instruction->ReplaceAllUsesWith(instruction->ActualValue()); } } } } } void HOptimizedGraphBuilder::PushArgumentsFromEnvironment(int count) { ZoneList<HValue*> arguments(count, zone()); for (int i = 0; i < count; ++i) { arguments.Add(Pop(), zone()); } HPushArguments* push_args = New<HPushArguments>(); while (!arguments.is_empty()) { push_args->AddInput(arguments.RemoveLast()); } AddInstruction(push_args); } template <class Instruction> HInstruction* HOptimizedGraphBuilder::PreProcessCall(Instruction* call) { PushArgumentsFromEnvironment(call->argument_count()); return call; } void HOptimizedGraphBuilder::SetUpScope(Scope* scope) { // First special is HContext. HInstruction* context = Add<HContext>(); environment()->BindContext(context); // Create an arguments object containing the initial parameters. Set the // initial values of parameters including "this" having parameter index 0. DCHECK_EQ(scope->num_parameters() + 1, environment()->parameter_count()); HArgumentsObject* arguments_object = New<HArgumentsObject>(environment()->parameter_count()); for (int i = 0; i < environment()->parameter_count(); ++i) { HInstruction* parameter = Add<HParameter>(i); arguments_object->AddArgument(parameter, zone()); environment()->Bind(i, parameter); } AddInstruction(arguments_object); graph()->SetArgumentsObject(arguments_object); HConstant* undefined_constant = graph()->GetConstantUndefined(); // Initialize specials and locals to undefined. for (int i = environment()->parameter_count() + 1; i < environment()->length(); ++i) { environment()->Bind(i, undefined_constant); } // Handle the arguments and arguments shadow variables specially (they do // not have declarations). if (scope->arguments() != NULL) { environment()->Bind(scope->arguments(), graph()->GetArgumentsObject()); } int rest_index; Variable* rest = scope->rest_parameter(&rest_index); if (rest) { return Bailout(kRestParameter); } } void HOptimizedGraphBuilder::VisitStatements(ZoneList<Statement*>* statements) { for (int i = 0; i < statements->length(); i++) { Statement* stmt = statements->at(i); CHECK_ALIVE(Visit(stmt)); if (stmt->IsJump()) break; } } void HOptimizedGraphBuilder::VisitBlock(Block* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); Scope* outer_scope = scope(); Scope* scope = stmt->scope(); BreakAndContinueInfo break_info(stmt, outer_scope); { BreakAndContinueScope push(&break_info, this); if (scope != NULL) { // Load the function object. Scope* declaration_scope = scope->DeclarationScope(); HInstruction* function; HValue* outer_context = environment()->context(); if (declaration_scope->is_script_scope() || declaration_scope->is_eval_scope()) { function = new(zone()) HLoadContextSlot( outer_context, Context::CLOSURE_INDEX, HLoadContextSlot::kNoCheck); } else { function = New<HThisFunction>(); } AddInstruction(function); // Allocate a block context and store it to the stack frame. HInstruction* inner_context = Add<HAllocateBlockContext>( outer_context, function, scope->GetScopeInfo(isolate())); HInstruction* instr = Add<HStoreFrameContext>(inner_context); set_scope(scope); environment()->BindContext(inner_context); if (instr->HasObservableSideEffects()) { AddSimulate(stmt->EntryId(), REMOVABLE_SIMULATE); } VisitDeclarations(scope->declarations()); AddSimulate(stmt->DeclsId(), REMOVABLE_SIMULATE); } CHECK_BAILOUT(VisitStatements(stmt->statements())); } set_scope(outer_scope); if (scope != NULL && current_block() != NULL) { HValue* inner_context = environment()->context(); HValue* outer_context = Add<HLoadNamedField>( inner_context, nullptr, HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX)); HInstruction* instr = Add<HStoreFrameContext>(outer_context); environment()->BindContext(outer_context); if (instr->HasObservableSideEffects()) { AddSimulate(stmt->ExitId(), REMOVABLE_SIMULATE); } } HBasicBlock* break_block = break_info.break_block(); if (break_block != NULL) { if (current_block() != NULL) Goto(break_block); break_block->SetJoinId(stmt->ExitId()); set_current_block(break_block); } } void HOptimizedGraphBuilder::VisitExpressionStatement( ExpressionStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); VisitForEffect(stmt->expression()); } void HOptimizedGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); } void HOptimizedGraphBuilder::VisitIfStatement(IfStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); if (stmt->condition()->ToBooleanIsTrue()) { Add<HSimulate>(stmt->ThenId()); Visit(stmt->then_statement()); } else if (stmt->condition()->ToBooleanIsFalse()) { Add<HSimulate>(stmt->ElseId()); Visit(stmt->else_statement()); } else { HBasicBlock* cond_true = graph()->CreateBasicBlock(); HBasicBlock* cond_false = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(stmt->condition(), cond_true, cond_false)); if (cond_true->HasPredecessor()) { cond_true->SetJoinId(stmt->ThenId()); set_current_block(cond_true); CHECK_BAILOUT(Visit(stmt->then_statement())); cond_true = current_block(); } else { cond_true = NULL; } if (cond_false->HasPredecessor()) { cond_false->SetJoinId(stmt->ElseId()); set_current_block(cond_false); CHECK_BAILOUT(Visit(stmt->else_statement())); cond_false = current_block(); } else { cond_false = NULL; } HBasicBlock* join = CreateJoin(cond_true, cond_false, stmt->IfId()); set_current_block(join); } } HBasicBlock* HOptimizedGraphBuilder::BreakAndContinueScope::Get( BreakableStatement* stmt, BreakType type, Scope** scope, int* drop_extra) { *drop_extra = 0; BreakAndContinueScope* current = this; while (current != NULL && current->info()->target() != stmt) { *drop_extra += current->info()->drop_extra(); current = current->next(); } DCHECK(current != NULL); // Always found (unless stack is malformed). *scope = current->info()->scope(); if (type == BREAK) { *drop_extra += current->info()->drop_extra(); } HBasicBlock* block = NULL; switch (type) { case BREAK: block = current->info()->break_block(); if (block == NULL) { block = current->owner()->graph()->CreateBasicBlock(); current->info()->set_break_block(block); } break; case CONTINUE: block = current->info()->continue_block(); if (block == NULL) { block = current->owner()->graph()->CreateBasicBlock(); current->info()->set_continue_block(block); } break; } return block; } void HOptimizedGraphBuilder::VisitContinueStatement( ContinueStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); Scope* outer_scope = NULL; Scope* inner_scope = scope(); int drop_extra = 0; HBasicBlock* continue_block = break_scope()->Get( stmt->target(), BreakAndContinueScope::CONTINUE, &outer_scope, &drop_extra); HValue* context = environment()->context(); Drop(drop_extra); int context_pop_count = inner_scope->ContextChainLength(outer_scope); if (context_pop_count > 0) { while (context_pop_count-- > 0) { HInstruction* context_instruction = Add<HLoadNamedField>( context, nullptr, HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX)); context = context_instruction; } HInstruction* instr = Add<HStoreFrameContext>(context); if (instr->HasObservableSideEffects()) { AddSimulate(stmt->target()->EntryId(), REMOVABLE_SIMULATE); } environment()->BindContext(context); } Goto(continue_block); set_current_block(NULL); } void HOptimizedGraphBuilder::VisitBreakStatement(BreakStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); Scope* outer_scope = NULL; Scope* inner_scope = scope(); int drop_extra = 0; HBasicBlock* break_block = break_scope()->Get( stmt->target(), BreakAndContinueScope::BREAK, &outer_scope, &drop_extra); HValue* context = environment()->context(); Drop(drop_extra); int context_pop_count = inner_scope->ContextChainLength(outer_scope); if (context_pop_count > 0) { while (context_pop_count-- > 0) { HInstruction* context_instruction = Add<HLoadNamedField>( context, nullptr, HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX)); context = context_instruction; } HInstruction* instr = Add<HStoreFrameContext>(context); if (instr->HasObservableSideEffects()) { AddSimulate(stmt->target()->ExitId(), REMOVABLE_SIMULATE); } environment()->BindContext(context); } Goto(break_block); set_current_block(NULL); } void HOptimizedGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); FunctionState* state = function_state(); AstContext* context = call_context(); if (context == NULL) { // Not an inlined return, so an actual one. CHECK_ALIVE(VisitForValue(stmt->expression())); HValue* result = environment()->Pop(); Add<HReturn>(result); } else if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) { // Return from an inlined construct call. In a test context the return value // will always evaluate to true, in a value context the return value needs // to be a JSObject. if (context->IsTest()) { TestContext* test = TestContext::cast(context); CHECK_ALIVE(VisitForEffect(stmt->expression())); Goto(test->if_true(), state); } else if (context->IsEffect()) { CHECK_ALIVE(VisitForEffect(stmt->expression())); Goto(function_return(), state); } else { DCHECK(context->IsValue()); CHECK_ALIVE(VisitForValue(stmt->expression())); HValue* return_value = Pop(); HValue* receiver = environment()->arguments_environment()->Lookup(0); HHasInstanceTypeAndBranch* typecheck = New<HHasInstanceTypeAndBranch>(return_value, FIRST_SPEC_OBJECT_TYPE, LAST_SPEC_OBJECT_TYPE); HBasicBlock* if_spec_object = graph()->CreateBasicBlock(); HBasicBlock* not_spec_object = graph()->CreateBasicBlock(); typecheck->SetSuccessorAt(0, if_spec_object); typecheck->SetSuccessorAt(1, not_spec_object); FinishCurrentBlock(typecheck); AddLeaveInlined(if_spec_object, return_value, state); AddLeaveInlined(not_spec_object, receiver, state); } } else if (state->inlining_kind() == SETTER_CALL_RETURN) { // Return from an inlined setter call. The returned value is never used, the // value of an assignment is always the value of the RHS of the assignment. CHECK_ALIVE(VisitForEffect(stmt->expression())); if (context->IsTest()) { HValue* rhs = environment()->arguments_environment()->Lookup(1); context->ReturnValue(rhs); } else if (context->IsEffect()) { Goto(function_return(), state); } else { DCHECK(context->IsValue()); HValue* rhs = environment()->arguments_environment()->Lookup(1); AddLeaveInlined(rhs, state); } } else { // Return from a normal inlined function. Visit the subexpression in the // expression context of the call. if (context->IsTest()) { TestContext* test = TestContext::cast(context); VisitForControl(stmt->expression(), test->if_true(), test->if_false()); } else if (context->IsEffect()) { // Visit in value context and ignore the result. This is needed to keep // environment in sync with full-codegen since some visitors (e.g. // VisitCountOperation) use the operand stack differently depending on // context. CHECK_ALIVE(VisitForValue(stmt->expression())); Pop(); Goto(function_return(), state); } else { DCHECK(context->IsValue()); CHECK_ALIVE(VisitForValue(stmt->expression())); AddLeaveInlined(Pop(), state); } } set_current_block(NULL); } void HOptimizedGraphBuilder::VisitWithStatement(WithStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); return Bailout(kWithStatement); } void HOptimizedGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); ZoneList<CaseClause*>* clauses = stmt->cases(); int clause_count = clauses->length(); ZoneList<HBasicBlock*> body_blocks(clause_count, zone()); CHECK_ALIVE(VisitForValue(stmt->tag())); Add<HSimulate>(stmt->EntryId()); HValue* tag_value = Top(); Type* tag_type = stmt->tag()->bounds().lower; // 1. Build all the tests, with dangling true branches BailoutId default_id = BailoutId::None(); for (int i = 0; i < clause_count; ++i) { CaseClause* clause = clauses->at(i); if (clause->is_default()) { body_blocks.Add(NULL, zone()); if (default_id.IsNone()) default_id = clause->EntryId(); continue; } // Generate a compare and branch. CHECK_ALIVE(VisitForValue(clause->label())); HValue* label_value = Pop(); Type* label_type = clause->label()->bounds().lower; Type* combined_type = clause->compare_type(); HControlInstruction* compare = BuildCompareInstruction( Token::EQ_STRICT, tag_value, label_value, tag_type, label_type, combined_type, ScriptPositionToSourcePosition(stmt->tag()->position()), ScriptPositionToSourcePosition(clause->label()->position()), PUSH_BEFORE_SIMULATE, clause->id()); HBasicBlock* next_test_block = graph()->CreateBasicBlock(); HBasicBlock* body_block = graph()->CreateBasicBlock(); body_blocks.Add(body_block, zone()); compare->SetSuccessorAt(0, body_block); compare->SetSuccessorAt(1, next_test_block); FinishCurrentBlock(compare); set_current_block(body_block); Drop(1); // tag_value set_current_block(next_test_block); } // Save the current block to use for the default or to join with the // exit. HBasicBlock* last_block = current_block(); Drop(1); // tag_value // 2. Loop over the clauses and the linked list of tests in lockstep, // translating the clause bodies. HBasicBlock* fall_through_block = NULL; BreakAndContinueInfo break_info(stmt, scope()); { BreakAndContinueScope push(&break_info, this); for (int i = 0; i < clause_count; ++i) { CaseClause* clause = clauses->at(i); // Identify the block where normal (non-fall-through) control flow // goes to. HBasicBlock* normal_block = NULL; if (clause->is_default()) { if (last_block == NULL) continue; normal_block = last_block; last_block = NULL; // Cleared to indicate we've handled it. } else { normal_block = body_blocks[i]; } if (fall_through_block == NULL) { set_current_block(normal_block); } else { HBasicBlock* join = CreateJoin(fall_through_block, normal_block, clause->EntryId()); set_current_block(join); } CHECK_BAILOUT(VisitStatements(clause->statements())); fall_through_block = current_block(); } } // Create an up-to-3-way join. Use the break block if it exists since // it's already a join block. HBasicBlock* break_block = break_info.break_block(); if (break_block == NULL) { set_current_block(CreateJoin(fall_through_block, last_block, stmt->ExitId())); } else { if (fall_through_block != NULL) Goto(fall_through_block, break_block); if (last_block != NULL) Goto(last_block, break_block); break_block->SetJoinId(stmt->ExitId()); set_current_block(break_block); } } void HOptimizedGraphBuilder::VisitLoopBody(IterationStatement* stmt, HBasicBlock* loop_entry) { Add<HSimulate>(stmt->StackCheckId()); HStackCheck* stack_check = HStackCheck::cast(Add<HStackCheck>(HStackCheck::kBackwardsBranch)); DCHECK(loop_entry->IsLoopHeader()); loop_entry->loop_information()->set_stack_check(stack_check); CHECK_BAILOUT(Visit(stmt->body())); } void HOptimizedGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); DCHECK(current_block() != NULL); HBasicBlock* loop_entry = BuildLoopEntry(stmt); BreakAndContinueInfo break_info(stmt, scope()); { BreakAndContinueScope push(&break_info, this); CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry)); } HBasicBlock* body_exit = JoinContinue(stmt, current_block(), break_info.continue_block()); HBasicBlock* loop_successor = NULL; if (body_exit != NULL && !stmt->cond()->ToBooleanIsTrue()) { set_current_block(body_exit); loop_successor = graph()->CreateBasicBlock(); if (stmt->cond()->ToBooleanIsFalse()) { loop_entry->loop_information()->stack_check()->Eliminate(); Goto(loop_successor); body_exit = NULL; } else { // The block for a true condition, the actual predecessor block of the // back edge. body_exit = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(stmt->cond(), body_exit, loop_successor)); } if (body_exit != NULL && body_exit->HasPredecessor()) { body_exit->SetJoinId(stmt->BackEdgeId()); } else { body_exit = NULL; } if (loop_successor->HasPredecessor()) { loop_successor->SetJoinId(stmt->ExitId()); } else { loop_successor = NULL; } } HBasicBlock* loop_exit = CreateLoop(stmt, loop_entry, body_exit, loop_successor, break_info.break_block()); set_current_block(loop_exit); } void HOptimizedGraphBuilder::VisitWhileStatement(WhileStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); DCHECK(current_block() != NULL); HBasicBlock* loop_entry = BuildLoopEntry(stmt); // If the condition is constant true, do not generate a branch. HBasicBlock* loop_successor = NULL; if (!stmt->cond()->ToBooleanIsTrue()) { HBasicBlock* body_entry = graph()->CreateBasicBlock(); loop_successor = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor)); if (body_entry->HasPredecessor()) { body_entry->SetJoinId(stmt->BodyId()); set_current_block(body_entry); } if (loop_successor->HasPredecessor()) { loop_successor->SetJoinId(stmt->ExitId()); } else { loop_successor = NULL; } } BreakAndContinueInfo break_info(stmt, scope()); if (current_block() != NULL) { BreakAndContinueScope push(&break_info, this); CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry)); } HBasicBlock* body_exit = JoinContinue(stmt, current_block(), break_info.continue_block()); HBasicBlock* loop_exit = CreateLoop(stmt, loop_entry, body_exit, loop_successor, break_info.break_block()); set_current_block(loop_exit); } void HOptimizedGraphBuilder::VisitForStatement(ForStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); if (stmt->init() != NULL) { CHECK_ALIVE(Visit(stmt->init())); } DCHECK(current_block() != NULL); HBasicBlock* loop_entry = BuildLoopEntry(stmt); HBasicBlock* loop_successor = NULL; if (stmt->cond() != NULL) { HBasicBlock* body_entry = graph()->CreateBasicBlock(); loop_successor = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor)); if (body_entry->HasPredecessor()) { body_entry->SetJoinId(stmt->BodyId()); set_current_block(body_entry); } if (loop_successor->HasPredecessor()) { loop_successor->SetJoinId(stmt->ExitId()); } else { loop_successor = NULL; } } BreakAndContinueInfo break_info(stmt, scope()); if (current_block() != NULL) { BreakAndContinueScope push(&break_info, this); CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry)); } HBasicBlock* body_exit = JoinContinue(stmt, current_block(), break_info.continue_block()); if (stmt->next() != NULL && body_exit != NULL) { set_current_block(body_exit); CHECK_BAILOUT(Visit(stmt->next())); body_exit = current_block(); } HBasicBlock* loop_exit = CreateLoop(stmt, loop_entry, body_exit, loop_successor, break_info.break_block()); set_current_block(loop_exit); } void HOptimizedGraphBuilder::VisitForInStatement(ForInStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); if (!FLAG_optimize_for_in) { return Bailout(kForInStatementOptimizationIsDisabled); } if (stmt->for_in_type() != ForInStatement::FAST_FOR_IN) { return Bailout(kForInStatementIsNotFastCase); } if (!stmt->each()->IsVariableProxy() || !stmt->each()->AsVariableProxy()->var()->IsStackLocal()) { return Bailout(kForInStatementWithNonLocalEachVariable); } Variable* each_var = stmt->each()->AsVariableProxy()->var(); CHECK_ALIVE(VisitForValue(stmt->enumerable())); HValue* enumerable = Top(); // Leave enumerable at the top. HInstruction* map = Add<HForInPrepareMap>(enumerable); Add<HSimulate>(stmt->PrepareId()); HInstruction* array = Add<HForInCacheArray>( enumerable, map, DescriptorArray::kEnumCacheBridgeCacheIndex); HInstruction* enum_length = Add<HMapEnumLength>(map); HInstruction* start_index = Add<HConstant>(0); Push(map); Push(array); Push(enum_length); Push(start_index); HInstruction* index_cache = Add<HForInCacheArray>( enumerable, map, DescriptorArray::kEnumCacheBridgeIndicesCacheIndex); HForInCacheArray::cast(array)->set_index_cache( HForInCacheArray::cast(index_cache)); HBasicBlock* loop_entry = BuildLoopEntry(stmt); HValue* index = environment()->ExpressionStackAt(0); HValue* limit = environment()->ExpressionStackAt(1); // Check that we still have more keys. HCompareNumericAndBranch* compare_index = New<HCompareNumericAndBranch>(index, limit, Token::LT); compare_index->set_observed_input_representation( Representation::Smi(), Representation::Smi()); HBasicBlock* loop_body = graph()->CreateBasicBlock(); HBasicBlock* loop_successor = graph()->CreateBasicBlock(); compare_index->SetSuccessorAt(0, loop_body); compare_index->SetSuccessorAt(1, loop_successor); FinishCurrentBlock(compare_index); set_current_block(loop_successor); Drop(5); set_current_block(loop_body); HValue* key = Add<HLoadKeyed>( environment()->ExpressionStackAt(2), // Enum cache. environment()->ExpressionStackAt(0), // Iteration index. environment()->ExpressionStackAt(0), FAST_ELEMENTS); // Check if the expected map still matches that of the enumerable. // If not just deoptimize. Add<HCheckMapValue>(environment()->ExpressionStackAt(4), environment()->ExpressionStackAt(3)); Bind(each_var, key); BreakAndContinueInfo break_info(stmt, scope(), 5); { BreakAndContinueScope push(&break_info, this); CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry)); } HBasicBlock* body_exit = JoinContinue(stmt, current_block(), break_info.continue_block()); if (body_exit != NULL) { set_current_block(body_exit); HValue* current_index = Pop(); Push(AddUncasted<HAdd>(current_index, graph()->GetConstant1())); body_exit = current_block(); } HBasicBlock* loop_exit = CreateLoop(stmt, loop_entry, body_exit, loop_successor, break_info.break_block()); set_current_block(loop_exit); } void HOptimizedGraphBuilder::VisitForOfStatement(ForOfStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); return Bailout(kForOfStatement); } void HOptimizedGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); return Bailout(kTryCatchStatement); } void HOptimizedGraphBuilder::VisitTryFinallyStatement( TryFinallyStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); return Bailout(kTryFinallyStatement); } void HOptimizedGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); return Bailout(kDebuggerStatement); } void HOptimizedGraphBuilder::VisitCaseClause(CaseClause* clause) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); Handle<SharedFunctionInfo> shared_info = expr->shared_info(); if (shared_info.is_null()) { shared_info = Compiler::BuildFunctionInfo(expr, current_info()->script(), top_info()); } // We also have a stack overflow if the recursive compilation did. if (HasStackOverflow()) return; HFunctionLiteral* instr = New<HFunctionLiteral>(shared_info, expr->pretenure()); return ast_context()->ReturnInstruction(instr, expr->id()); } void HOptimizedGraphBuilder::VisitClassLiteral(ClassLiteral* lit) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); return Bailout(kClassLiteral); } void HOptimizedGraphBuilder::VisitNativeFunctionLiteral( NativeFunctionLiteral* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); return Bailout(kNativeFunctionLiteral); } void HOptimizedGraphBuilder::VisitConditional(Conditional* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); HBasicBlock* cond_true = graph()->CreateBasicBlock(); HBasicBlock* cond_false = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(expr->condition(), cond_true, cond_false)); // Visit the true and false subexpressions in the same AST context as the // whole expression. if (cond_true->HasPredecessor()) { cond_true->SetJoinId(expr->ThenId()); set_current_block(cond_true); CHECK_BAILOUT(Visit(expr->then_expression())); cond_true = current_block(); } else { cond_true = NULL; } if (cond_false->HasPredecessor()) { cond_false->SetJoinId(expr->ElseId()); set_current_block(cond_false); CHECK_BAILOUT(Visit(expr->else_expression())); cond_false = current_block(); } else { cond_false = NULL; } if (!ast_context()->IsTest()) { HBasicBlock* join = CreateJoin(cond_true, cond_false, expr->id()); set_current_block(join); if (join != NULL && !ast_context()->IsEffect()) { return ast_context()->ReturnValue(Pop()); } } } HOptimizedGraphBuilder::GlobalPropertyAccess HOptimizedGraphBuilder::LookupGlobalProperty(Variable* var, LookupIterator* it, PropertyAccessType access_type) { if (var->is_this() || !current_info()->has_global_object()) { return kUseGeneric; } switch (it->state()) { case LookupIterator::ACCESSOR: case LookupIterator::ACCESS_CHECK: case LookupIterator::INTERCEPTOR: case LookupIterator::INTEGER_INDEXED_EXOTIC: case LookupIterator::NOT_FOUND: return kUseGeneric; case LookupIterator::DATA: if (access_type == STORE && it->IsReadOnly()) return kUseGeneric; return kUseCell; case LookupIterator::JSPROXY: case LookupIterator::TRANSITION: UNREACHABLE(); } UNREACHABLE(); return kUseGeneric; } HValue* HOptimizedGraphBuilder::BuildContextChainWalk(Variable* var) { DCHECK(var->IsContextSlot()); HValue* context = environment()->context(); int length = scope()->ContextChainLength(var->scope()); while (length-- > 0) { context = Add<HLoadNamedField>( context, nullptr, HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX)); } return context; } void HOptimizedGraphBuilder::VisitVariableProxy(VariableProxy* expr) { if (expr->is_this()) { graph()->MarkThisHasUses(); } DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); Variable* variable = expr->var(); switch (variable->location()) { case Variable::UNALLOCATED: { if (IsLexicalVariableMode(variable->mode())) { // TODO(rossberg): should this be an DCHECK? return Bailout(kReferenceToGlobalLexicalVariable); } // Handle known global constants like 'undefined' specially to avoid a // load from a global cell for them. Handle<Object> constant_value = isolate()->factory()->GlobalConstantFor(variable->name()); if (!constant_value.is_null()) { HConstant* instr = New<HConstant>(constant_value); return ast_context()->ReturnInstruction(instr, expr->id()); } Handle<GlobalObject> global(current_info()->global_object()); // Lookup in script contexts. { Handle<ScriptContextTable> script_contexts( global->native_context()->script_context_table()); ScriptContextTable::LookupResult lookup; if (ScriptContextTable::Lookup(script_contexts, variable->name(), &lookup)) { Handle<Context> script_context = ScriptContextTable::GetContext( script_contexts, lookup.context_index); Handle<Object> current_value = FixedArray::get(script_context, lookup.slot_index); // If the values is not the hole, it will stay initialized, // so no need to generate a check. if (*current_value == *isolate()->factory()->the_hole_value()) { return Bailout(kReferenceToUninitializedVariable); } HInstruction* result = New<HLoadNamedField>( Add<HConstant>(script_context), nullptr, HObjectAccess::ForContextSlot(lookup.slot_index)); return ast_context()->ReturnInstruction(result, expr->id()); } } LookupIterator it(global, variable->name(), LookupIterator::OWN_SKIP_INTERCEPTOR); GlobalPropertyAccess type = LookupGlobalProperty(variable, &it, LOAD); if (type == kUseCell) { Handle<PropertyCell> cell = it.GetPropertyCell(); PropertyCell::AddDependentCompilationInfo(cell, top_info()); if (it.property_details().cell_type() == PropertyCellType::kConstant) { Handle<Object> constant_object(cell->value(), isolate()); if (constant_object->IsConsString()) { constant_object = String::Flatten(Handle<String>::cast(constant_object)); } HConstant* constant = New<HConstant>(constant_object); return ast_context()->ReturnInstruction(constant, expr->id()); } else { HConstant* cell_constant = Add<HConstant>(cell); HLoadNamedField* instr = New<HLoadNamedField>( cell_constant, nullptr, HObjectAccess::ForPropertyCellValue()); instr->ClearDependsOnFlag(kInobjectFields); instr->SetDependsOnFlag(kGlobalVars); return ast_context()->ReturnInstruction(instr, expr->id()); } } else { HValue* global_object = Add<HLoadNamedField>( context(), nullptr, HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); HLoadGlobalGeneric* instr = New<HLoadGlobalGeneric>(global_object, variable->name(), ast_context()->is_for_typeof()); if (FLAG_vector_ics) { Handle<SharedFunctionInfo> current_shared = function_state()->compilation_info()->shared_info(); instr->SetVectorAndSlot( handle(current_shared->feedback_vector(), isolate()), expr->VariableFeedbackSlot()); } return ast_context()->ReturnInstruction(instr, expr->id()); } } case Variable::PARAMETER: case Variable::LOCAL: { HValue* value = LookupAndMakeLive(variable); if (value == graph()->GetConstantHole()) { DCHECK(IsDeclaredVariableMode(variable->mode()) && variable->mode() != VAR); return Bailout(kReferenceToUninitializedVariable); } return ast_context()->ReturnValue(value); } case Variable::CONTEXT: { HValue* context = BuildContextChainWalk(variable); HLoadContextSlot::Mode mode; switch (variable->mode()) { case LET: case CONST: mode = HLoadContextSlot::kCheckDeoptimize; break; case CONST_LEGACY: mode = HLoadContextSlot::kCheckReturnUndefined; break; default: mode = HLoadContextSlot::kNoCheck; break; } HLoadContextSlot* instr = new(zone()) HLoadContextSlot(context, variable->index(), mode); return ast_context()->ReturnInstruction(instr, expr->id()); } case Variable::LOOKUP: return Bailout(kReferenceToAVariableWhichRequiresDynamicLookup); } } void HOptimizedGraphBuilder::VisitLiteral(Literal* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); HConstant* instr = New<HConstant>(expr->value()); return ast_context()->ReturnInstruction(instr, expr->id()); } void HOptimizedGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); Handle<JSFunction> closure = function_state()->compilation_info()->closure(); Handle<FixedArray> literals(closure->literals()); HRegExpLiteral* instr = New<HRegExpLiteral>(literals, expr->pattern(), expr->flags(), expr->literal_index()); return ast_context()->ReturnInstruction(instr, expr->id()); } static bool CanInlinePropertyAccess(Handle<Map> map) { if (map->instance_type() == HEAP_NUMBER_TYPE) return true; if (map->instance_type() < FIRST_NONSTRING_TYPE) return true; return map->IsJSObjectMap() && !map->is_dictionary_map() && !map->has_named_interceptor() && // TODO(verwaest): Whitelist contexts to which we have access. !map->is_access_check_needed(); } // Determines whether the given array or object literal boilerplate satisfies // all limits to be considered for fast deep-copying and computes the total // size of all objects that are part of the graph. static bool IsFastLiteral(Handle<JSObject> boilerplate, int max_depth, int* max_properties) { if (boilerplate->map()->is_deprecated() && !JSObject::TryMigrateInstance(boilerplate)) { return false; } DCHECK(max_depth >= 0 && *max_properties >= 0); if (max_depth == 0) return false; Isolate* isolate = boilerplate->GetIsolate(); Handle<FixedArrayBase> elements(boilerplate->elements()); if (elements->length() > 0 && elements->map() != isolate->heap()->fixed_cow_array_map()) { if (boilerplate->HasFastSmiOrObjectElements()) { Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements); int length = elements->length(); for (int i = 0; i < length; i++) { if ((*max_properties)-- == 0) return false; Handle<Object> value(fast_elements->get(i), isolate); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); if (!IsFastLiteral(value_object, max_depth - 1, max_properties)) { return false; } } } } else if (!boilerplate->HasFastDoubleElements()) { return false; } } Handle<FixedArray> properties(boilerplate->properties()); if (properties->length() > 0) { return false; } else { Handle<DescriptorArray> descriptors( boilerplate->map()->instance_descriptors()); int limit = boilerplate->map()->NumberOfOwnDescriptors(); for (int i = 0; i < limit; i++) { PropertyDetails details = descriptors->GetDetails(i); if (details.type() != DATA) continue; if ((*max_properties)-- == 0) return false; FieldIndex field_index = FieldIndex::ForDescriptor(boilerplate->map(), i); if (boilerplate->IsUnboxedDoubleField(field_index)) continue; Handle<Object> value(boilerplate->RawFastPropertyAt(field_index), isolate); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); if (!IsFastLiteral(value_object, max_depth - 1, max_properties)) { return false; } } } } return true; } void HOptimizedGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); expr->BuildConstantProperties(isolate()); Handle<JSFunction> closure = function_state()->compilation_info()->closure(); HInstruction* literal; // Check whether to use fast or slow deep-copying for boilerplate. int max_properties = kMaxFastLiteralProperties; Handle<Object> literals_cell(closure->literals()->get(expr->literal_index()), isolate()); Handle<AllocationSite> site; Handle<JSObject> boilerplate; if (!literals_cell->IsUndefined()) { // Retrieve the boilerplate site = Handle<AllocationSite>::cast(literals_cell); boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()), isolate()); } if (!boilerplate.is_null() && IsFastLiteral(boilerplate, kMaxFastLiteralDepth, &max_properties)) { AllocationSiteUsageContext usage_context(isolate(), site, false); usage_context.EnterNewScope(); literal = BuildFastLiteral(boilerplate, &usage_context); usage_context.ExitScope(site, boilerplate); } else { NoObservableSideEffectsScope no_effects(this); Handle<FixedArray> closure_literals(closure->literals(), isolate()); Handle<FixedArray> constant_properties = expr->constant_properties(); int literal_index = expr->literal_index(); int flags = expr->fast_elements() ? ObjectLiteral::kFastElements : ObjectLiteral::kNoFlags; flags |= expr->has_function() ? ObjectLiteral::kHasFunction : ObjectLiteral::kNoFlags; Add<HPushArguments>(Add<HConstant>(closure_literals), Add<HConstant>(literal_index), Add<HConstant>(constant_properties), Add<HConstant>(flags)); // TODO(mvstanton): Add a flag to turn off creation of any // AllocationMementos for this call: we are in crankshaft and should have // learned enough about transition behavior to stop emitting mementos. Runtime::FunctionId function_id = Runtime::kCreateObjectLiteral; literal = Add<HCallRuntime>(isolate()->factory()->empty_string(), Runtime::FunctionForId(function_id), 4); } // The object is expected in the bailout environment during computation // of the property values and is the value of the entire expression. Push(literal); expr->CalculateEmitStore(zone()); for (int i = 0; i < expr->properties()->length(); i++) { ObjectLiteral::Property* property = expr->properties()->at(i); if (property->is_computed_name()) return Bailout(kComputedPropertyName); if (property->IsCompileTimeValue()) continue; Literal* key = property->key()->AsLiteral(); Expression* value = property->value(); switch (property->kind()) { case ObjectLiteral::Property::MATERIALIZED_LITERAL: DCHECK(!CompileTimeValue::IsCompileTimeValue(value)); // Fall through. case ObjectLiteral::Property::COMPUTED: // It is safe to use [[Put]] here because the boilerplate already // contains computed properties with an uninitialized value. if (key->value()->IsInternalizedString()) { if (property->emit_store()) { CHECK_ALIVE(VisitForValue(value)); HValue* value = Pop(); // Add [[HomeObject]] to function literals. if (FunctionLiteral::NeedsHomeObject(property->value())) { Handle<Symbol> sym = isolate()->factory()->home_object_symbol(); HInstruction* store_home = BuildKeyedGeneric( STORE, NULL, value, Add<HConstant>(sym), literal); AddInstruction(store_home); DCHECK(store_home->HasObservableSideEffects()); Add<HSimulate>(property->value()->id(), REMOVABLE_SIMULATE); } Handle<Map> map = property->GetReceiverType(); Handle<String> name = key->AsPropertyName(); HInstruction* store; if (map.is_null()) { // If we don't know the monomorphic type, do a generic store. CHECK_ALIVE(store = BuildNamedGeneric( STORE, NULL, literal, name, value)); } else { PropertyAccessInfo info(this, STORE, map, name); if (info.CanAccessMonomorphic()) { HValue* checked_literal = Add<HCheckMaps>(literal, map); DCHECK(!info.IsAccessorConstant()); store = BuildMonomorphicAccess( &info, literal, checked_literal, value, BailoutId::None(), BailoutId::None()); } else { CHECK_ALIVE(store = BuildNamedGeneric( STORE, NULL, literal, name, value)); } } AddInstruction(store); DCHECK(store->HasObservableSideEffects()); Add<HSimulate>(key->id(), REMOVABLE_SIMULATE); } else { CHECK_ALIVE(VisitForEffect(value)); } break; } // Fall through. case ObjectLiteral::Property::PROTOTYPE: case ObjectLiteral::Property::SETTER: case ObjectLiteral::Property::GETTER: return Bailout(kObjectLiteralWithComplexProperty); default: UNREACHABLE(); } } if (expr->has_function()) { // Return the result of the transformation to fast properties // instead of the original since this operation changes the map // of the object. This makes sure that the original object won't // be used by other optimized code before it is transformed // (e.g. because of code motion). HToFastProperties* result = Add<HToFastProperties>(Pop()); return ast_context()->ReturnValue(result); } else { return ast_context()->ReturnValue(Pop()); } } void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); expr->BuildConstantElements(isolate()); ZoneList<Expression*>* subexprs = expr->values(); int length = subexprs->length(); HInstruction* literal; Handle<AllocationSite> site; Handle<FixedArray> literals(environment()->closure()->literals(), isolate()); bool uninitialized = false; Handle<Object> literals_cell(literals->get(expr->literal_index()), isolate()); Handle<JSObject> boilerplate_object; if (literals_cell->IsUndefined()) { uninitialized = true; Handle<Object> raw_boilerplate; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate(), raw_boilerplate, Runtime::CreateArrayLiteralBoilerplate( isolate(), literals, expr->constant_elements()), Bailout(kArrayBoilerplateCreationFailed)); boilerplate_object = Handle<JSObject>::cast(raw_boilerplate); AllocationSiteCreationContext creation_context(isolate()); site = creation_context.EnterNewScope(); if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) { return Bailout(kArrayBoilerplateCreationFailed); } creation_context.ExitScope(site, boilerplate_object); literals->set(expr->literal_index(), *site); if (boilerplate_object->elements()->map() == isolate()->heap()->fixed_cow_array_map()) { isolate()->counters()->cow_arrays_created_runtime()->Increment(); } } else { DCHECK(literals_cell->IsAllocationSite()); site = Handle<AllocationSite>::cast(literals_cell); boilerplate_object = Handle<JSObject>( JSObject::cast(site->transition_info()), isolate()); } DCHECK(!boilerplate_object.is_null()); DCHECK(site->SitePointsToLiteral()); ElementsKind boilerplate_elements_kind = boilerplate_object->GetElementsKind(); // Check whether to use fast or slow deep-copying for boilerplate. int max_properties = kMaxFastLiteralProperties; if (IsFastLiteral(boilerplate_object, kMaxFastLiteralDepth, &max_properties)) { AllocationSiteUsageContext usage_context(isolate(), site, false); usage_context.EnterNewScope(); literal = BuildFastLiteral(boilerplate_object, &usage_context); usage_context.ExitScope(site, boilerplate_object); } else { NoObservableSideEffectsScope no_effects(this); // Boilerplate already exists and constant elements are never accessed, // pass an empty fixed array to the runtime function instead. Handle<FixedArray> constants = isolate()->factory()->empty_fixed_array(); int literal_index = expr->literal_index(); int flags = expr->depth() == 1 ? ArrayLiteral::kShallowElements : ArrayLiteral::kNoFlags; flags |= ArrayLiteral::kDisableMementos; Add<HPushArguments>(Add<HConstant>(literals), Add<HConstant>(literal_index), Add<HConstant>(constants), Add<HConstant>(flags)); Runtime::FunctionId function_id = Runtime::kCreateArrayLiteral; literal = Add<HCallRuntime>(isolate()->factory()->empty_string(), Runtime::FunctionForId(function_id), 4); // Register to deopt if the boilerplate ElementsKind changes. AllocationSite::RegisterForDeoptOnTransitionChange(site, top_info()); } // The array is expected in the bailout environment during computation // of the property values and is the value of the entire expression. Push(literal); // The literal index is on the stack, too. Push(Add<HConstant>(expr->literal_index())); HInstruction* elements = NULL; for (int i = 0; i < length; i++) { Expression* subexpr = subexprs->at(i); // If the subexpression is a literal or a simple materialized literal it // is already set in the cloned array. if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue; CHECK_ALIVE(VisitForValue(subexpr)); HValue* value = Pop(); if (!Smi::IsValid(i)) return Bailout(kNonSmiKeyInArrayLiteral); elements = AddLoadElements(literal); HValue* key = Add<HConstant>(i); switch (boilerplate_elements_kind) { case FAST_SMI_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_ELEMENTS: case FAST_HOLEY_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: { HStoreKeyed* instr = Add<HStoreKeyed>(elements, key, value, boilerplate_elements_kind); instr->SetUninitialized(uninitialized); break; } default: UNREACHABLE(); break; } Add<HSimulate>(expr->GetIdForElement(i)); } Drop(1); // array literal index return ast_context()->ReturnValue(Pop()); } HCheckMaps* HOptimizedGraphBuilder::AddCheckMap(HValue* object, Handle<Map> map) { BuildCheckHeapObject(object); return Add<HCheckMaps>(object, map); } HInstruction* HOptimizedGraphBuilder::BuildLoadNamedField( PropertyAccessInfo* info, HValue* checked_object) { // See if this is a load for an immutable property if (checked_object->ActualValue()->IsConstant()) { Handle<Object> object( HConstant::cast(checked_object->ActualValue())->handle(isolate())); if (object->IsJSObject()) { LookupIterator it(object, info->name(), LookupIterator::OWN_SKIP_INTERCEPTOR); Handle<Object> value = JSObject::GetDataProperty(&it); if (it.IsFound() && it.IsReadOnly() && !it.IsConfigurable()) { return New<HConstant>(value); } } } HObjectAccess access = info->access(); if (access.representation().IsDouble() && (!FLAG_unbox_double_fields || !access.IsInobject())) { // Load the heap number. checked_object = Add<HLoadNamedField>( checked_object, nullptr, access.WithRepresentation(Representation::Tagged())); // Load the double value from it. access = HObjectAccess::ForHeapNumberValue(); } SmallMapList* map_list = info->field_maps(); if (map_list->length() == 0) { return New<HLoadNamedField>(checked_object, checked_object, access); } UniqueSet<Map>* maps = new(zone()) UniqueSet<Map>(map_list->length(), zone()); for (int i = 0; i < map_list->length(); ++i) { maps->Add(Unique<Map>::CreateImmovable(map_list->at(i)), zone()); } return New<HLoadNamedField>( checked_object, checked_object, access, maps, info->field_type()); } HInstruction* HOptimizedGraphBuilder::BuildStoreNamedField( PropertyAccessInfo* info, HValue* checked_object, HValue* value) { bool transition_to_field = info->IsTransition(); // TODO(verwaest): Move this logic into PropertyAccessInfo. HObjectAccess field_access = info->access(); HStoreNamedField *instr; if (field_access.representation().IsDouble() && (!FLAG_unbox_double_fields || !field_access.IsInobject())) { HObjectAccess heap_number_access = field_access.WithRepresentation(Representation::Tagged()); if (transition_to_field) { // The store requires a mutable HeapNumber to be allocated. NoObservableSideEffectsScope no_side_effects(this); HInstruction* heap_number_size = Add<HConstant>(HeapNumber::kSize); // TODO(hpayer): Allocation site pretenuring support. HInstruction* heap_number = Add<HAllocate>(heap_number_size, HType::HeapObject(), NOT_TENURED, MUTABLE_HEAP_NUMBER_TYPE); AddStoreMapConstant( heap_number, isolate()->factory()->mutable_heap_number_map()); Add<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(), value); instr = New<HStoreNamedField>(checked_object->ActualValue(), heap_number_access, heap_number); } else { // Already holds a HeapNumber; load the box and write its value field. HInstruction* heap_number = Add<HLoadNamedField>(checked_object, nullptr, heap_number_access); instr = New<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(), value, STORE_TO_INITIALIZED_ENTRY); } } else { if (field_access.representation().IsHeapObject()) { BuildCheckHeapObject(value); } if (!info->field_maps()->is_empty()) { DCHECK(field_access.representation().IsHeapObject()); value = Add<HCheckMaps>(value, info->field_maps()); } // This is a normal store. instr = New<HStoreNamedField>( checked_object->ActualValue(), field_access, value, transition_to_field ? INITIALIZING_STORE : STORE_TO_INITIALIZED_ENTRY); } if (transition_to_field) { Handle<Map> transition(info->transition()); DCHECK(!transition->is_deprecated()); instr->SetTransition(Add<HConstant>(transition)); } return instr; } bool HOptimizedGraphBuilder::PropertyAccessInfo::IsCompatible( PropertyAccessInfo* info) { if (!CanInlinePropertyAccess(map_)) return false; // Currently only handle Type::Number as a polymorphic case. // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber // instruction. if (IsNumberType()) return false; // Values are only compatible for monomorphic load if they all behave the same // regarding value wrappers. if (IsValueWrapped() != info->IsValueWrapped()) return false; if (!LookupDescriptor()) return false; if (!IsFound()) { return (!info->IsFound() || info->has_holder()) && map()->prototype() == info->map()->prototype(); } // Mismatch if the other access info found the property in the prototype // chain. if (info->has_holder()) return false; if (IsAccessorConstant()) { return accessor_.is_identical_to(info->accessor_) && api_holder_.is_identical_to(info->api_holder_); } if (IsDataConstant()) { return constant_.is_identical_to(info->constant_); } DCHECK(IsData()); if (!info->IsData()) return false; Representation r = access_.representation(); if (IsLoad()) { if (!info->access_.representation().IsCompatibleForLoad(r)) return false; } else { if (!info->access_.representation().IsCompatibleForStore(r)) return false; } if (info->access_.offset() != access_.offset()) return false; if (info->access_.IsInobject() != access_.IsInobject()) return false; if (IsLoad()) { if (field_maps_.is_empty()) { info->field_maps_.Clear(); } else if (!info->field_maps_.is_empty()) { for (int i = 0; i < field_maps_.length(); ++i) { info->field_maps_.AddMapIfMissing(field_maps_.at(i), info->zone()); } info->field_maps_.Sort(); } } else { // We can only merge stores that agree on their field maps. The comparison // below is safe, since we keep the field maps sorted. if (field_maps_.length() != info->field_maps_.length()) return false; for (int i = 0; i < field_maps_.length(); ++i) { if (!field_maps_.at(i).is_identical_to(info->field_maps_.at(i))) { return false; } } } info->GeneralizeRepresentation(r); info->field_type_ = info->field_type_.Combine(field_type_); return true; } bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupDescriptor() { if (!map_->IsJSObjectMap()) return true; LookupDescriptor(*map_, *name_); return LoadResult(map_); } bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadResult(Handle<Map> map) { if (!IsLoad() && IsProperty() && IsReadOnly()) { return false; } if (IsData()) { // Construct the object field access. int index = GetLocalFieldIndexFromMap(map); access_ = HObjectAccess::ForField(map, index, representation(), name_); // Load field map for heap objects. LoadFieldMaps(map); } else if (IsAccessorConstant()) { Handle<Object> accessors = GetAccessorsFromMap(map); if (!accessors->IsAccessorPair()) return false; Object* raw_accessor = IsLoad() ? Handle<AccessorPair>::cast(accessors)->getter() : Handle<AccessorPair>::cast(accessors)->setter(); if (!raw_accessor->IsJSFunction()) return false; Handle<JSFunction> accessor = handle(JSFunction::cast(raw_accessor)); if (accessor->shared()->IsApiFunction()) { CallOptimization call_optimization(accessor); if (call_optimization.is_simple_api_call()) { CallOptimization::HolderLookup holder_lookup; api_holder_ = call_optimization.LookupHolderOfExpectedType(map_, &holder_lookup); } } accessor_ = accessor; } else if (IsDataConstant()) { constant_ = GetConstantFromMap(map); } return true; } void HOptimizedGraphBuilder::PropertyAccessInfo::LoadFieldMaps( Handle<Map> map) { // Clear any previously collected field maps/type. field_maps_.Clear(); field_type_ = HType::Tagged(); // Figure out the field type from the accessor map. Handle<HeapType> field_type = GetFieldTypeFromMap(map); // Collect the (stable) maps from the field type. int num_field_maps = field_type->NumClasses(); if (num_field_maps == 0) return; DCHECK(access_.representation().IsHeapObject()); field_maps_.Reserve(num_field_maps, zone()); HeapType::Iterator<Map> it = field_type->Classes(); while (!it.Done()) { Handle<Map> field_map = it.Current(); if (!field_map->is_stable()) { field_maps_.Clear(); return; } field_maps_.Add(field_map, zone()); it.Advance(); } field_maps_.Sort(); DCHECK_EQ(num_field_maps, field_maps_.length()); // Determine field HType from field HeapType. field_type_ = HType::FromType<HeapType>(field_type); DCHECK(field_type_.IsHeapObject()); // Add dependency on the map that introduced the field. Map::AddDependentCompilationInfo(GetFieldOwnerFromMap(map), DependentCode::kFieldTypeGroup, top_info()); } bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupInPrototypes() { Handle<Map> map = this->map(); while (map->prototype()->IsJSObject()) { holder_ = handle(JSObject::cast(map->prototype())); if (holder_->map()->is_deprecated()) { JSObject::TryMigrateInstance(holder_); } map = Handle<Map>(holder_->map()); if (!CanInlinePropertyAccess(map)) { NotFound(); return false; } LookupDescriptor(*map, *name_); if (IsFound()) return LoadResult(map); } NotFound(); return true; } bool HOptimizedGraphBuilder::PropertyAccessInfo::IsIntegerIndexedExotic() { InstanceType instance_type = map_->instance_type(); return instance_type == JS_TYPED_ARRAY_TYPE && IsNonArrayIndexInteger(*name_); } bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessMonomorphic() { if (!CanInlinePropertyAccess(map_)) return false; if (IsJSObjectFieldAccessor()) return IsLoad(); if (map_->function_with_prototype() && !map_->has_non_instance_prototype() && name_.is_identical_to(isolate()->factory()->prototype_string())) { return IsLoad(); } if (!LookupDescriptor()) return false; if (IsFound()) return IsLoad() || !IsReadOnly(); if (IsIntegerIndexedExotic()) return false; if (!LookupInPrototypes()) return false; if (IsLoad()) return true; if (IsAccessorConstant()) return true; LookupTransition(*map_, *name_, NONE); if (IsTransitionToData() && map_->unused_property_fields() > 0) { // Construct the object field access. int descriptor = transition()->LastAdded(); int index = transition()->instance_descriptors()->GetFieldIndex(descriptor) - map_->inobject_properties(); PropertyDetails details = transition()->instance_descriptors()->GetDetails(descriptor); Representation representation = details.representation(); access_ = HObjectAccess::ForField(map_, index, representation, name_); // Load field map for heap objects. LoadFieldMaps(transition()); return true; } return false; } bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessAsMonomorphic( SmallMapList* maps) { DCHECK(map_.is_identical_to(maps->first())); if (!CanAccessMonomorphic()) return false; STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism); if (maps->length() > kMaxLoadPolymorphism) return false; HObjectAccess access = HObjectAccess::ForMap(); // bogus default if (GetJSObjectFieldAccess(&access)) { for (int i = 1; i < maps->length(); ++i) { PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_); HObjectAccess test_access = HObjectAccess::ForMap(); // bogus default if (!test_info.GetJSObjectFieldAccess(&test_access)) return false; if (!access.Equals(test_access)) return false; } return true; } // Currently only handle numbers as a polymorphic case. // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber // instruction. if (IsNumberType()) return false; // Multiple maps cannot transition to the same target map. DCHECK(!IsLoad() || !IsTransition()); if (IsTransition() && maps->length() > 1) return false; for (int i = 1; i < maps->length(); ++i) { PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_); if (!test_info.IsCompatible(this)) return false; } return true; } Handle<Map> HOptimizedGraphBuilder::PropertyAccessInfo::map() { JSFunction* ctor = IC::GetRootConstructor( *map_, current_info()->closure()->context()->native_context()); if (ctor != NULL) return handle(ctor->initial_map()); return map_; } static bool NeedsWrapping(Handle<Map> map, Handle<JSFunction> target) { return !map->IsJSObjectMap() && is_sloppy(target->shared()->language_mode()) && !target->shared()->native(); } bool HOptimizedGraphBuilder::PropertyAccessInfo::NeedsWrappingFor( Handle<JSFunction> target) const { return NeedsWrapping(map_, target); } HInstruction* HOptimizedGraphBuilder::BuildMonomorphicAccess( PropertyAccessInfo* info, HValue* object, HValue* checked_object, HValue* value, BailoutId ast_id, BailoutId return_id, bool can_inline_accessor) { HObjectAccess access = HObjectAccess::ForMap(); // bogus default if (info->GetJSObjectFieldAccess(&access)) { DCHECK(info->IsLoad()); return New<HLoadNamedField>(object, checked_object, access); } if (info->name().is_identical_to(isolate()->factory()->prototype_string()) && info->map()->function_with_prototype()) { DCHECK(!info->map()->has_non_instance_prototype()); return New<HLoadFunctionPrototype>(checked_object); } HValue* checked_holder = checked_object; if (info->has_holder()) { Handle<JSObject> prototype(JSObject::cast(info->map()->prototype())); checked_holder = BuildCheckPrototypeMaps(prototype, info->holder()); } if (!info->IsFound()) { DCHECK(info->IsLoad()); return graph()->GetConstantUndefined(); } if (info->IsData()) { if (info->IsLoad()) { return BuildLoadNamedField(info, checked_holder); } else { return BuildStoreNamedField(info, checked_object, value); } } if (info->IsTransition()) { DCHECK(!info->IsLoad()); return BuildStoreNamedField(info, checked_object, value); } if (info->IsAccessorConstant()) { Push(checked_object); int argument_count = 1; if (!info->IsLoad()) { argument_count = 2; Push(value); } if (info->NeedsWrappingFor(info->accessor())) { HValue* function = Add<HConstant>(info->accessor()); PushArgumentsFromEnvironment(argument_count); return New<HCallFunction>(function, argument_count, WRAP_AND_CALL); } else if (FLAG_inline_accessors && can_inline_accessor) { bool success = info->IsLoad() ? TryInlineGetter(info->accessor(), info->map(), ast_id, return_id) : TryInlineSetter( info->accessor(), info->map(), ast_id, return_id, value); if (success || HasStackOverflow()) return NULL; } PushArgumentsFromEnvironment(argument_count); return BuildCallConstantFunction(info->accessor(), argument_count); } DCHECK(info->IsDataConstant()); if (info->IsLoad()) { return New<HConstant>(info->constant()); } else { return New<HCheckValue>(value, Handle<JSFunction>::cast(info->constant())); } } void HOptimizedGraphBuilder::HandlePolymorphicNamedFieldAccess( PropertyAccessType access_type, Expression* expr, BailoutId ast_id, BailoutId return_id, HValue* object, HValue* value, SmallMapList* maps, Handle<String> name) { // Something did not match; must use a polymorphic load. int count = 0; HBasicBlock* join = NULL; HBasicBlock* number_block = NULL; bool handled_string = false; bool handle_smi = false; STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism); int i; for (i = 0; i < maps->length() && count < kMaxLoadPolymorphism; ++i) { PropertyAccessInfo info(this, access_type, maps->at(i), name); if (info.IsStringType()) { if (handled_string) continue; handled_string = true; } if (info.CanAccessMonomorphic()) { count++; if (info.IsNumberType()) { handle_smi = true; break; } } } if (i < maps->length()) { count = -1; maps->Clear(); } else { count = 0; } HControlInstruction* smi_check = NULL; handled_string = false; for (i = 0; i < maps->length() && count < kMaxLoadPolymorphism; ++i) { PropertyAccessInfo info(this, access_type, maps->at(i), name); if (info.IsStringType()) { if (handled_string) continue; handled_string = true; } if (!info.CanAccessMonomorphic()) continue; if (count == 0) { join = graph()->CreateBasicBlock(); if (handle_smi) { HBasicBlock* empty_smi_block = graph()->CreateBasicBlock(); HBasicBlock* not_smi_block = graph()->CreateBasicBlock(); number_block = graph()->CreateBasicBlock(); smi_check = New<HIsSmiAndBranch>( object, empty_smi_block, not_smi_block); FinishCurrentBlock(smi_check); GotoNoSimulate(empty_smi_block, number_block); set_current_block(not_smi_block); } else { BuildCheckHeapObject(object); } } ++count; HBasicBlock* if_true = graph()->CreateBasicBlock(); HBasicBlock* if_false = graph()->CreateBasicBlock(); HUnaryControlInstruction* compare; HValue* dependency; if (info.IsNumberType()) { Handle<Map> heap_number_map = isolate()->factory()->heap_number_map(); compare = New<HCompareMap>(object, heap_number_map, if_true, if_false); dependency = smi_check; } else if (info.IsStringType()) { compare = New<HIsStringAndBranch>(object, if_true, if_false); dependency = compare; } else { compare = New<HCompareMap>(object, info.map(), if_true, if_false); dependency = compare; } FinishCurrentBlock(compare); if (info.IsNumberType()) { GotoNoSimulate(if_true, number_block); if_true = number_block; } set_current_block(if_true); HInstruction* access = BuildMonomorphicAccess( &info, object, dependency, value, ast_id, return_id, FLAG_polymorphic_inlining); HValue* result = NULL; switch (access_type) { case LOAD: result = access; break; case STORE: result = value; break; } if (access == NULL) { if (HasStackOverflow()) return; } else { if (!access->IsLinked()) AddInstruction(access); if (!ast_context()->IsEffect()) Push(result); } if (current_block() != NULL) Goto(join); set_current_block(if_false); } // Finish up. Unconditionally deoptimize if we've handled all the maps we // know about and do not want to handle ones we've never seen. Otherwise // use a generic IC. if (count == maps->length() && FLAG_deoptimize_uncommon_cases) { FinishExitWithHardDeoptimization( Deoptimizer::kUnknownMapInPolymorphicAccess); } else { HInstruction* instr = BuildNamedGeneric(access_type, expr, object, name, value); AddInstruction(instr); if (!ast_context()->IsEffect()) Push(access_type == LOAD ? instr : value); if (join != NULL) { Goto(join); } else { Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop()); return; } } DCHECK(join != NULL); if (join->HasPredecessor()) { join->SetJoinId(ast_id); set_current_block(join); if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop()); } else { set_current_block(NULL); } } static bool ComputeReceiverTypes(Expression* expr, HValue* receiver, SmallMapList** t, Zone* zone) { SmallMapList* maps = expr->GetReceiverTypes(); *t = maps; bool monomorphic = expr->IsMonomorphic(); if (maps != NULL && receiver->HasMonomorphicJSObjectType()) { Map* root_map = receiver->GetMonomorphicJSObjectMap()->FindRootMap(); maps->FilterForPossibleTransitions(root_map); monomorphic = maps->length() == 1; } return monomorphic && CanInlinePropertyAccess(maps->first()); } static bool AreStringTypes(SmallMapList* maps) { for (int i = 0; i < maps->length(); i++) { if (maps->at(i)->instance_type() >= FIRST_NONSTRING_TYPE) return false; } return true; } void HOptimizedGraphBuilder::BuildStore(Expression* expr, Property* prop, BailoutId ast_id, BailoutId return_id, bool is_uninitialized) { if (!prop->key()->IsPropertyName()) { // Keyed store. HValue* value = Pop(); HValue* key = Pop(); HValue* object = Pop(); bool has_side_effects = false; HValue* result = HandleKeyedElementAccess( object, key, value, expr, ast_id, return_id, STORE, &has_side_effects); if (has_side_effects) { if (!ast_context()->IsEffect()) Push(value); Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) Drop(1); } if (result == NULL) return; return ast_context()->ReturnValue(value); } // Named store. HValue* value = Pop(); HValue* object = Pop(); Literal* key = prop->key()->AsLiteral(); Handle<String> name = Handle<String>::cast(key->value()); DCHECK(!name.is_null()); HInstruction* instr = BuildNamedAccess(STORE, ast_id, return_id, expr, object, name, value, is_uninitialized); if (instr == NULL) return; if (!ast_context()->IsEffect()) Push(value); AddInstruction(instr); if (instr->HasObservableSideEffects()) { Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } if (!ast_context()->IsEffect()) Drop(1); return ast_context()->ReturnValue(value); } void HOptimizedGraphBuilder::HandlePropertyAssignment(Assignment* expr) { Property* prop = expr->target()->AsProperty(); DCHECK(prop != NULL); CHECK_ALIVE(VisitForValue(prop->obj())); if (!prop->key()->IsPropertyName()) { CHECK_ALIVE(VisitForValue(prop->key())); } CHECK_ALIVE(VisitForValue(expr->value())); BuildStore(expr, prop, expr->id(), expr->AssignmentId(), expr->IsUninitialized()); } // Because not every expression has a position and there is not common // superclass of Assignment and CountOperation, we cannot just pass the // owning expression instead of position and ast_id separately. void HOptimizedGraphBuilder::HandleGlobalVariableAssignment( Variable* var, HValue* value, BailoutId ast_id) { Handle<GlobalObject> global(current_info()->global_object()); // Lookup in script contexts. { Handle<ScriptContextTable> script_contexts( global->native_context()->script_context_table()); ScriptContextTable::LookupResult lookup; if (ScriptContextTable::Lookup(script_contexts, var->name(), &lookup)) { if (lookup.mode == CONST) { return Bailout(kNonInitializerAssignmentToConst); } Handle<Context> script_context = ScriptContextTable::GetContext(script_contexts, lookup.context_index); Handle<Object> current_value = FixedArray::get(script_context, lookup.slot_index); // If the values is not the hole, it will stay initialized, // so no need to generate a check. if (*current_value == *isolate()->factory()->the_hole_value()) { return Bailout(kReferenceToUninitializedVariable); } HStoreNamedField* instr = Add<HStoreNamedField>( Add<HConstant>(script_context), HObjectAccess::ForContextSlot(lookup.slot_index), value); USE(instr); DCHECK(instr->HasObservableSideEffects()); Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); return; } } LookupIterator it(global, var->name(), LookupIterator::OWN_SKIP_INTERCEPTOR); GlobalPropertyAccess type = LookupGlobalProperty(var, &it, STORE); if (type == kUseCell) { Handle<PropertyCell> cell = it.GetPropertyCell(); PropertyCell::AddDependentCompilationInfo(cell, top_info()); if (it.property_details().cell_type() == PropertyCellType::kConstant) { Handle<Object> constant(cell->value(), isolate()); if (value->IsConstant()) { HConstant* c_value = HConstant::cast(value); if (!constant.is_identical_to(c_value->handle(isolate()))) { Add<HDeoptimize>(Deoptimizer::kConstantGlobalVariableAssignment, Deoptimizer::EAGER); } } else { HValue* c_constant = Add<HConstant>(constant); IfBuilder builder(this); if (constant->IsNumber()) { builder.If<HCompareNumericAndBranch>(value, c_constant, Token::EQ); } else { builder.If<HCompareObjectEqAndBranch>(value, c_constant); } builder.Then(); builder.Else(); Add<HDeoptimize>(Deoptimizer::kConstantGlobalVariableAssignment, Deoptimizer::EAGER); builder.End(); } } HConstant* cell_constant = Add<HConstant>(cell); HInstruction* instr = Add<HStoreNamedField>( cell_constant, HObjectAccess::ForPropertyCellValue(), value); instr->ClearChangesFlag(kInobjectFields); instr->SetChangesFlag(kGlobalVars); if (instr->HasObservableSideEffects()) { Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } } else { HValue* global_object = Add<HLoadNamedField>( context(), nullptr, HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); HStoreNamedGeneric* instr = Add<HStoreNamedGeneric>(global_object, var->name(), value, function_language_mode(), PREMONOMORPHIC); USE(instr); DCHECK(instr->HasObservableSideEffects()); Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } } void HOptimizedGraphBuilder::HandleCompoundAssignment(Assignment* expr) { Expression* target = expr->target(); VariableProxy* proxy = target->AsVariableProxy(); Property* prop = target->AsProperty(); DCHECK(proxy == NULL || prop == NULL); // We have a second position recorded in the FullCodeGenerator to have // type feedback for the binary operation. BinaryOperation* operation = expr->binary_operation(); if (proxy != NULL) { Variable* var = proxy->var(); if (var->mode() == LET) { return Bailout(kUnsupportedLetCompoundAssignment); } CHECK_ALIVE(VisitForValue(operation)); switch (var->location()) { case Variable::UNALLOCATED: HandleGlobalVariableAssignment(var, Top(), expr->AssignmentId()); break; case Variable::PARAMETER: case Variable::LOCAL: if (var->mode() == CONST_LEGACY) { return Bailout(kUnsupportedConstCompoundAssignment); } if (var->mode() == CONST) { return Bailout(kNonInitializerAssignmentToConst); } BindIfLive(var, Top()); break; case Variable::CONTEXT: { // Bail out if we try to mutate a parameter value in a function // using the arguments object. We do not (yet) correctly handle the // arguments property of the function. if (current_info()->scope()->arguments() != NULL) { // Parameters will be allocated to context slots. We have no // direct way to detect that the variable is a parameter so we do // a linear search of the parameter variables. int count = current_info()->scope()->num_parameters(); for (int i = 0; i < count; ++i) { if (var == current_info()->scope()->parameter(i)) { Bailout(kAssignmentToParameterFunctionUsesArgumentsObject); } } } HStoreContextSlot::Mode mode; switch (var->mode()) { case LET: mode = HStoreContextSlot::kCheckDeoptimize; break; case CONST: return Bailout(kNonInitializerAssignmentToConst); case CONST_LEGACY: return ast_context()->ReturnValue(Pop()); default: mode = HStoreContextSlot::kNoCheck; } HValue* context = BuildContextChainWalk(var); HStoreContextSlot* instr = Add<HStoreContextSlot>( context, var->index(), mode, Top()); if (instr->HasObservableSideEffects()) { Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE); } break; } case Variable::LOOKUP: return Bailout(kCompoundAssignmentToLookupSlot); } return ast_context()->ReturnValue(Pop()); } else if (prop != NULL) { CHECK_ALIVE(VisitForValue(prop->obj())); HValue* object = Top(); HValue* key = NULL; if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) { CHECK_ALIVE(VisitForValue(prop->key())); key = Top(); } CHECK_ALIVE(PushLoad(prop, object, key)); CHECK_ALIVE(VisitForValue(expr->value())); HValue* right = Pop(); HValue* left = Pop(); Push(BuildBinaryOperation(operation, left, right, PUSH_BEFORE_SIMULATE)); BuildStore(expr, prop, expr->id(), expr->AssignmentId(), expr->IsUninitialized()); } else { return Bailout(kInvalidLhsInCompoundAssignment); } } void HOptimizedGraphBuilder::VisitAssignment(Assignment* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); VariableProxy* proxy = expr->target()->AsVariableProxy(); Property* prop = expr->target()->AsProperty(); DCHECK(proxy == NULL || prop == NULL); if (expr->is_compound()) { HandleCompoundAssignment(expr); return; } if (prop != NULL) { HandlePropertyAssignment(expr); } else if (proxy != NULL) { Variable* var = proxy->var(); if (var->mode() == CONST) { if (expr->op() != Token::INIT_CONST) { return Bailout(kNonInitializerAssignmentToConst); } } else if (var->mode() == CONST_LEGACY) { if (expr->op() != Token::INIT_CONST_LEGACY) { CHECK_ALIVE(VisitForValue(expr->value())); return ast_context()->ReturnValue(Pop()); } if (var->IsStackAllocated()) { // We insert a use of the old value to detect unsupported uses of const // variables (e.g. initialization inside a loop). HValue* old_value = environment()->Lookup(var); Add<HUseConst>(old_value); } } if (proxy->IsArguments()) return Bailout(kAssignmentToArguments); // Handle the assignment. switch (var->location()) { case Variable::UNALLOCATED: CHECK_ALIVE(VisitForValue(expr->value())); HandleGlobalVariableAssignment(var, Top(), expr->AssignmentId()); return ast_context()->ReturnValue(Pop()); case Variable::PARAMETER: case Variable::LOCAL: { // Perform an initialization check for let declared variables // or parameters. if (var->mode() == LET && expr->op() == Token::ASSIGN) { HValue* env_value = environment()->Lookup(var); if (env_value == graph()->GetConstantHole()) { return Bailout(kAssignmentToLetVariableBeforeInitialization); } } // We do not allow the arguments object to occur in a context where it // may escape, but assignments to stack-allocated locals are // permitted. CHECK_ALIVE(VisitForValue(expr->value(), ARGUMENTS_ALLOWED)); HValue* value = Pop(); BindIfLive(var, value); return ast_context()->ReturnValue(value); } case Variable::CONTEXT: { // Bail out if we try to mutate a parameter value in a function using // the arguments object. We do not (yet) correctly handle the // arguments property of the function. if (current_info()->scope()->arguments() != NULL) { // Parameters will rewrite to context slots. We have no direct way // to detect that the variable is a parameter. int count = current_info()->scope()->num_parameters(); for (int i = 0; i < count; ++i) { if (var == current_info()->scope()->parameter(i)) { return Bailout(kAssignmentToParameterInArgumentsObject); } } } CHECK_ALIVE(VisitForValue(expr->value())); HStoreContextSlot::Mode mode; if (expr->op() == Token::ASSIGN) { switch (var->mode()) { case LET: mode = HStoreContextSlot::kCheckDeoptimize; break; case CONST: // This case is checked statically so no need to // perform checks here UNREACHABLE(); case CONST_LEGACY: return ast_context()->ReturnValue(Pop()); default: mode = HStoreContextSlot::kNoCheck; } } else if (expr->op() == Token::INIT_VAR || expr->op() == Token::INIT_LET || expr->op() == Token::INIT_CONST) { mode = HStoreContextSlot::kNoCheck; } else { DCHECK(expr->op() == Token::INIT_CONST_LEGACY); mode = HStoreContextSlot::kCheckIgnoreAssignment; } HValue* context = BuildContextChainWalk(var); HStoreContextSlot* instr = Add<HStoreContextSlot>( context, var->index(), mode, Top()); if (instr->HasObservableSideEffects()) { Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE); } return ast_context()->ReturnValue(Pop()); } case Variable::LOOKUP: return Bailout(kAssignmentToLOOKUPVariable); } } else { return Bailout(kInvalidLeftHandSideInAssignment); } } void HOptimizedGraphBuilder::VisitYield(Yield* expr) { // Generators are not optimized, so we should never get here. UNREACHABLE(); } void HOptimizedGraphBuilder::VisitThrow(Throw* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); if (!ast_context()->IsEffect()) { // The parser turns invalid left-hand sides in assignments into throw // statements, which may not be in effect contexts. We might still try // to optimize such functions; bail out now if we do. return Bailout(kInvalidLeftHandSideInAssignment); } CHECK_ALIVE(VisitForValue(expr->exception())); HValue* value = environment()->Pop(); if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position()); Add<HPushArguments>(value); Add<HCallRuntime>(isolate()->factory()->empty_string(), Runtime::FunctionForId(Runtime::kThrow), 1); Add<HSimulate>(expr->id()); // If the throw definitely exits the function, we can finish with a dummy // control flow at this point. This is not the case if the throw is inside // an inlined function which may be replaced. if (call_context() == NULL) { FinishExitCurrentBlock(New<HAbnormalExit>()); } } HInstruction* HGraphBuilder::AddLoadStringInstanceType(HValue* string) { if (string->IsConstant()) { HConstant* c_string = HConstant::cast(string); if (c_string->HasStringValue()) { return Add<HConstant>(c_string->StringValue()->map()->instance_type()); } } return Add<HLoadNamedField>( Add<HLoadNamedField>(string, nullptr, HObjectAccess::ForMap()), nullptr, HObjectAccess::ForMapInstanceType()); } HInstruction* HGraphBuilder::AddLoadStringLength(HValue* string) { if (string->IsConstant()) { HConstant* c_string = HConstant::cast(string); if (c_string->HasStringValue()) { return Add<HConstant>(c_string->StringValue()->length()); } } return Add<HLoadNamedField>(string, nullptr, HObjectAccess::ForStringLength()); } HInstruction* HOptimizedGraphBuilder::BuildNamedGeneric( PropertyAccessType access_type, Expression* expr, HValue* object, Handle<String> name, HValue* value, bool is_uninitialized) { if (is_uninitialized) { Add<HDeoptimize>( Deoptimizer::kInsufficientTypeFeedbackForGenericNamedAccess, Deoptimizer::SOFT); } if (access_type == LOAD) { HLoadNamedGeneric* result = New<HLoadNamedGeneric>(object, name, PREMONOMORPHIC); if (FLAG_vector_ics) { Handle<SharedFunctionInfo> current_shared = function_state()->compilation_info()->shared_info(); Handle<TypeFeedbackVector> vector = handle(current_shared->feedback_vector(), isolate()); FeedbackVectorICSlot slot = expr->AsProperty()->PropertyFeedbackSlot(); result->SetVectorAndSlot(vector, slot); } return result; } else { return New<HStoreNamedGeneric>(object, name, value, function_language_mode(), PREMONOMORPHIC); } } HInstruction* HOptimizedGraphBuilder::BuildKeyedGeneric( PropertyAccessType access_type, Expression* expr, HValue* object, HValue* key, HValue* value) { if (access_type == LOAD) { HLoadKeyedGeneric* result = New<HLoadKeyedGeneric>(object, key, PREMONOMORPHIC); if (FLAG_vector_ics) { Handle<SharedFunctionInfo> current_shared = function_state()->compilation_info()->shared_info(); Handle<TypeFeedbackVector> vector = handle(current_shared->feedback_vector(), isolate()); FeedbackVectorICSlot slot = expr->AsProperty()->PropertyFeedbackSlot(); result->SetVectorAndSlot(vector, slot); } return result; } else { return New<HStoreKeyedGeneric>(object, key, value, function_language_mode(), PREMONOMORPHIC); } } LoadKeyedHoleMode HOptimizedGraphBuilder::BuildKeyedHoleMode(Handle<Map> map) { // Loads from a "stock" fast holey double arrays can elide the hole check. LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE; if (*map == isolate()->get_initial_js_array_map(FAST_HOLEY_DOUBLE_ELEMENTS) && isolate()->IsFastArrayConstructorPrototypeChainIntact()) { Handle<JSObject> prototype(JSObject::cast(map->prototype()), isolate()); Handle<JSObject> object_prototype = isolate()->initial_object_prototype(); BuildCheckPrototypeMaps(prototype, object_prototype); load_mode = ALLOW_RETURN_HOLE; graph()->MarkDependsOnEmptyArrayProtoElements(); } return load_mode; } HInstruction* HOptimizedGraphBuilder::BuildMonomorphicElementAccess( HValue* object, HValue* key, HValue* val, HValue* dependency, Handle<Map> map, PropertyAccessType access_type, KeyedAccessStoreMode store_mode) { HCheckMaps* checked_object = Add<HCheckMaps>(object, map, dependency); if (access_type == STORE && map->prototype()->IsJSObject()) { // monomorphic stores need a prototype chain check because shape // changes could allow callbacks on elements in the chain that // aren't compatible with monomorphic keyed stores. PrototypeIterator iter(map); JSObject* holder = NULL; while (!iter.IsAtEnd()) { holder = JSObject::cast(*PrototypeIterator::GetCurrent(iter)); iter.Advance(); } DCHECK(holder && holder->IsJSObject()); BuildCheckPrototypeMaps(handle(JSObject::cast(map->prototype())), Handle<JSObject>(holder)); } LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map); return BuildUncheckedMonomorphicElementAccess( checked_object, key, val, map->instance_type() == JS_ARRAY_TYPE, map->elements_kind(), access_type, load_mode, store_mode); } static bool CanInlineElementAccess(Handle<Map> map) { return map->IsJSObjectMap() && !map->has_slow_elements_kind() && !map->has_indexed_interceptor() && !map->is_access_check_needed(); } HInstruction* HOptimizedGraphBuilder::TryBuildConsolidatedElementLoad( HValue* object, HValue* key, HValue* val, SmallMapList* maps) { // For polymorphic loads of similar elements kinds (i.e. all tagged or all // double), always use the "worst case" code without a transition. This is // much faster than transitioning the elements to the worst case, trading a // HTransitionElements for a HCheckMaps, and avoiding mutation of the array. bool has_double_maps = false; bool has_smi_or_object_maps = false; bool has_js_array_access = false; bool has_non_js_array_access = false; bool has_seen_holey_elements = false; Handle<Map> most_general_consolidated_map; for (int i = 0; i < maps->length(); ++i) { Handle<Map> map = maps->at(i); if (!CanInlineElementAccess(map)) return NULL; // Don't allow mixing of JSArrays with JSObjects. if (map->instance_type() == JS_ARRAY_TYPE) { if (has_non_js_array_access) return NULL; has_js_array_access = true; } else if (has_js_array_access) { return NULL; } else { has_non_js_array_access = true; } // Don't allow mixed, incompatible elements kinds. if (map->has_fast_double_elements()) { if (has_smi_or_object_maps) return NULL; has_double_maps = true; } else if (map->has_fast_smi_or_object_elements()) { if (has_double_maps) return NULL; has_smi_or_object_maps = true; } else { return NULL; } // Remember if we've ever seen holey elements. if (IsHoleyElementsKind(map->elements_kind())) { has_seen_holey_elements = true; } // Remember the most general elements kind, the code for its load will // properly handle all of the more specific cases. if ((i == 0) || IsMoreGeneralElementsKindTransition( most_general_consolidated_map->elements_kind(), map->elements_kind())) { most_general_consolidated_map = map; } } if (!has_double_maps && !has_smi_or_object_maps) return NULL; HCheckMaps* checked_object = Add<HCheckMaps>(object, maps); // FAST_ELEMENTS is considered more general than FAST_HOLEY_SMI_ELEMENTS. // If we've seen both, the consolidated load must use FAST_HOLEY_ELEMENTS. ElementsKind consolidated_elements_kind = has_seen_holey_elements ? GetHoleyElementsKind(most_general_consolidated_map->elements_kind()) : most_general_consolidated_map->elements_kind(); HInstruction* instr = BuildUncheckedMonomorphicElementAccess( checked_object, key, val, most_general_consolidated_map->instance_type() == JS_ARRAY_TYPE, consolidated_elements_kind, LOAD, NEVER_RETURN_HOLE, STANDARD_STORE); return instr; } HValue* HOptimizedGraphBuilder::HandlePolymorphicElementAccess( Expression* expr, HValue* object, HValue* key, HValue* val, SmallMapList* maps, PropertyAccessType access_type, KeyedAccessStoreMode store_mode, bool* has_side_effects) { *has_side_effects = false; BuildCheckHeapObject(object); if (access_type == LOAD) { HInstruction* consolidated_load = TryBuildConsolidatedElementLoad(object, key, val, maps); if (consolidated_load != NULL) { *has_side_effects |= consolidated_load->HasObservableSideEffects(); return consolidated_load; } } // Elements_kind transition support. MapHandleList transition_target(maps->length()); // Collect possible transition targets. MapHandleList possible_transitioned_maps(maps->length()); for (int i = 0; i < maps->length(); ++i) { Handle<Map> map = maps->at(i); // Loads from strings or loads with a mix of string and non-string maps // shouldn't be handled polymorphically. DCHECK(access_type != LOAD || !map->IsStringMap()); ElementsKind elements_kind = map->elements_kind(); if (CanInlineElementAccess(map) && IsFastElementsKind(elements_kind) && elements_kind != GetInitialFastElementsKind()) { possible_transitioned_maps.Add(map); } if (elements_kind == SLOPPY_ARGUMENTS_ELEMENTS) { HInstruction* result = BuildKeyedGeneric(access_type, expr, object, key, val); *has_side_effects = result->HasObservableSideEffects(); return AddInstruction(result); } } // Get transition target for each map (NULL == no transition). for (int i = 0; i < maps->length(); ++i) { Handle<Map> map = maps->at(i); Handle<Map> transitioned_map = map->FindTransitionedMap(&possible_transitioned_maps); transition_target.Add(transitioned_map); } MapHandleList untransitionable_maps(maps->length()); HTransitionElementsKind* transition = NULL; for (int i = 0; i < maps->length(); ++i) { Handle<Map> map = maps->at(i); DCHECK(map->IsMap()); if (!transition_target.at(i).is_null()) { DCHECK(Map::IsValidElementsTransition( map->elements_kind(), transition_target.at(i)->elements_kind())); transition = Add<HTransitionElementsKind>(object, map, transition_target.at(i)); } else { untransitionable_maps.Add(map); } } // If only one map is left after transitioning, handle this case // monomorphically. DCHECK(untransitionable_maps.length() >= 1); if (untransitionable_maps.length() == 1) { Handle<Map> untransitionable_map = untransitionable_maps[0]; HInstruction* instr = NULL; if (!CanInlineElementAccess(untransitionable_map)) { instr = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key, val)); } else { instr = BuildMonomorphicElementAccess( object, key, val, transition, untransitionable_map, access_type, store_mode); } *has_side_effects |= instr->HasObservableSideEffects(); return access_type == STORE ? val : instr; } HBasicBlock* join = graph()->CreateBasicBlock(); for (int i = 0; i < untransitionable_maps.length(); ++i) { Handle<Map> map = untransitionable_maps[i]; ElementsKind elements_kind = map->elements_kind(); HBasicBlock* this_map = graph()->CreateBasicBlock(); HBasicBlock* other_map = graph()->CreateBasicBlock(); HCompareMap* mapcompare = New<HCompareMap>(object, map, this_map, other_map); FinishCurrentBlock(mapcompare); set_current_block(this_map); HInstruction* access = NULL; if (!CanInlineElementAccess(map)) { access = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key, val)); } else { DCHECK(IsFastElementsKind(elements_kind) || IsExternalArrayElementsKind(elements_kind) || IsFixedTypedArrayElementsKind(elements_kind)); LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map); // Happily, mapcompare is a checked object. access = BuildUncheckedMonomorphicElementAccess( mapcompare, key, val, map->instance_type() == JS_ARRAY_TYPE, elements_kind, access_type, load_mode, store_mode); } *has_side_effects |= access->HasObservableSideEffects(); // The caller will use has_side_effects and add a correct Simulate. access->SetFlag(HValue::kHasNoObservableSideEffects); if (access_type == LOAD) { Push(access); } NoObservableSideEffectsScope scope(this); GotoNoSimulate(join); set_current_block(other_map); } // Ensure that we visited at least one map above that goes to join. This is // necessary because FinishExitWithHardDeoptimization does an AbnormalExit // rather than joining the join block. If this becomes an issue, insert a // generic access in the case length() == 0. DCHECK(join->predecessors()->length() > 0); // Deopt if none of the cases matched. NoObservableSideEffectsScope scope(this); FinishExitWithHardDeoptimization( Deoptimizer::kUnknownMapInPolymorphicElementAccess); set_current_block(join); return access_type == STORE ? val : Pop(); } HValue* HOptimizedGraphBuilder::HandleKeyedElementAccess( HValue* obj, HValue* key, HValue* val, Expression* expr, BailoutId ast_id, BailoutId return_id, PropertyAccessType access_type, bool* has_side_effects) { // TODO(mvstanton): This optimization causes trouble for vector-based // KeyedLoadICs, turn it off for now. if (!FLAG_vector_ics && key->ActualValue()->IsConstant()) { Handle<Object> constant = HConstant::cast(key->ActualValue())->handle(isolate()); uint32_t array_index; if (constant->IsString() && !Handle<String>::cast(constant)->AsArrayIndex(&array_index)) { if (!constant->IsUniqueName()) { constant = isolate()->factory()->InternalizeString( Handle<String>::cast(constant)); } HInstruction* instr = BuildNamedAccess(access_type, ast_id, return_id, expr, obj, Handle<String>::cast(constant), val, false); if (instr == NULL || instr->IsLinked()) { *has_side_effects = false; } else { AddInstruction(instr); *has_side_effects = instr->HasObservableSideEffects(); } return instr; } } DCHECK(!expr->IsPropertyName()); HInstruction* instr = NULL; SmallMapList* maps; bool monomorphic = ComputeReceiverTypes(expr, obj, &maps, zone()); bool force_generic = false; if (expr->GetKeyType() == PROPERTY) { // Non-Generic accesses assume that elements are being accessed, and will // deopt for non-index keys, which the IC knows will occur. // TODO(jkummerow): Consider adding proper support for property accesses. force_generic = true; monomorphic = false; } else if (access_type == STORE && (monomorphic || (maps != NULL && !maps->is_empty()))) { // Stores can't be mono/polymorphic if their prototype chain has dictionary // elements. However a receiver map that has dictionary elements itself // should be left to normal mono/poly behavior (the other maps may benefit // from highly optimized stores). for (int i = 0; i < maps->length(); i++) { Handle<Map> current_map = maps->at(i); if (current_map->DictionaryElementsInPrototypeChainOnly()) { force_generic = true; monomorphic = false; break; } } } else if (access_type == LOAD && !monomorphic && (maps != NULL && !maps->is_empty())) { // Polymorphic loads have to go generic if any of the maps are strings. // If some, but not all of the maps are strings, we should go generic // because polymorphic access wants to key on ElementsKind and isn't // compatible with strings. for (int i = 0; i < maps->length(); i++) { Handle<Map> current_map = maps->at(i); if (current_map->IsStringMap()) { force_generic = true; break; } } } if (monomorphic) { Handle<Map> map = maps->first(); if (!CanInlineElementAccess(map)) { instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key, val)); } else { BuildCheckHeapObject(obj); instr = BuildMonomorphicElementAccess( obj, key, val, NULL, map, access_type, expr->GetStoreMode()); } } else if (!force_generic && (maps != NULL && !maps->is_empty())) { return HandlePolymorphicElementAccess(expr, obj, key, val, maps, access_type, expr->GetStoreMode(), has_side_effects); } else { if (access_type == STORE) { if (expr->IsAssignment() && expr->AsAssignment()->HasNoTypeInformation()) { Add<HDeoptimize>(Deoptimizer::kInsufficientTypeFeedbackForKeyedStore, Deoptimizer::SOFT); } } else { if (expr->AsProperty()->HasNoTypeInformation()) { Add<HDeoptimize>(Deoptimizer::kInsufficientTypeFeedbackForKeyedLoad, Deoptimizer::SOFT); } } instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key, val)); } *has_side_effects = instr->HasObservableSideEffects(); return instr; } void HOptimizedGraphBuilder::EnsureArgumentsArePushedForAccess() { // Outermost function already has arguments on the stack. if (function_state()->outer() == NULL) return; if (function_state()->arguments_pushed()) return; // Push arguments when entering inlined function. HEnterInlined* entry = function_state()->entry(); entry->set_arguments_pushed(); HArgumentsObject* arguments = entry->arguments_object(); const ZoneList<HValue*>* arguments_values = arguments->arguments_values(); HInstruction* insert_after = entry; for (int i = 0; i < arguments_values->length(); i++) { HValue* argument = arguments_values->at(i); HInstruction* push_argument = New<HPushArguments>(argument); push_argument->InsertAfter(insert_after); insert_after = push_argument; } HArgumentsElements* arguments_elements = New<HArgumentsElements>(true); arguments_elements->ClearFlag(HValue::kUseGVN); arguments_elements->InsertAfter(insert_after); function_state()->set_arguments_elements(arguments_elements); } bool HOptimizedGraphBuilder::TryArgumentsAccess(Property* expr) { VariableProxy* proxy = expr->obj()->AsVariableProxy(); if (proxy == NULL) return false; if (!proxy->var()->IsStackAllocated()) return false; if (!environment()->Lookup(proxy->var())->CheckFlag(HValue::kIsArguments)) { return false; } HInstruction* result = NULL; if (expr->key()->IsPropertyName()) { Handle<String> name = expr->key()->AsLiteral()->AsPropertyName(); if (!String::Equals(name, isolate()->factory()->length_string())) { return false; } if (function_state()->outer() == NULL) { HInstruction* elements = Add<HArgumentsElements>(false); result = New<HArgumentsLength>(elements); } else { // Number of arguments without receiver. int argument_count = environment()-> arguments_environment()->parameter_count() - 1; result = New<HConstant>(argument_count); } } else { Push(graph()->GetArgumentsObject()); CHECK_ALIVE_OR_RETURN(VisitForValue(expr->key()), true); HValue* key = Pop(); Drop(1); // Arguments object. if (function_state()->outer() == NULL) { HInstruction* elements = Add<HArgumentsElements>(false); HInstruction* length = Add<HArgumentsLength>(elements); HInstruction* checked_key = Add<HBoundsCheck>(key, length); result = New<HAccessArgumentsAt>(elements, length, checked_key); } else { EnsureArgumentsArePushedForAccess(); // Number of arguments without receiver. HInstruction* elements = function_state()->arguments_elements(); int argument_count = environment()-> arguments_environment()->parameter_count() - 1; HInstruction* length = Add<HConstant>(argument_count); HInstruction* checked_key = Add<HBoundsCheck>(key, length); result = New<HAccessArgumentsAt>(elements, length, checked_key); } } ast_context()->ReturnInstruction(result, expr->id()); return true; } HInstruction* HOptimizedGraphBuilder::BuildNamedAccess( PropertyAccessType access, BailoutId ast_id, BailoutId return_id, Expression* expr, HValue* object, Handle<String> name, HValue* value, bool is_uninitialized) { SmallMapList* maps; ComputeReceiverTypes(expr, object, &maps, zone()); DCHECK(maps != NULL); if (maps->length() > 0) { PropertyAccessInfo info(this, access, maps->first(), name); if (!info.CanAccessAsMonomorphic(maps)) { HandlePolymorphicNamedFieldAccess(access, expr, ast_id, return_id, object, value, maps, name); return NULL; } HValue* checked_object; // Type::Number() is only supported by polymorphic load/call handling. DCHECK(!info.IsNumberType()); BuildCheckHeapObject(object); if (AreStringTypes(maps)) { checked_object = Add<HCheckInstanceType>(object, HCheckInstanceType::IS_STRING); } else { checked_object = Add<HCheckMaps>(object, maps); } return BuildMonomorphicAccess( &info, object, checked_object, value, ast_id, return_id); } return BuildNamedGeneric(access, expr, object, name, value, is_uninitialized); } void HOptimizedGraphBuilder::PushLoad(Property* expr, HValue* object, HValue* key) { ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED); Push(object); if (key != NULL) Push(key); BuildLoad(expr, expr->LoadId()); } void HOptimizedGraphBuilder::BuildLoad(Property* expr, BailoutId ast_id) { HInstruction* instr = NULL; if (expr->IsStringAccess()) { HValue* index = Pop(); HValue* string = Pop(); HInstruction* char_code = BuildStringCharCodeAt(string, index); AddInstruction(char_code); instr = NewUncasted<HStringCharFromCode>(char_code); } else if (expr->key()->IsPropertyName()) { Handle<String> name = expr->key()->AsLiteral()->AsPropertyName(); HValue* object = Pop(); instr = BuildNamedAccess(LOAD, ast_id, expr->LoadId(), expr, object, name, NULL, expr->IsUninitialized()); if (instr == NULL) return; if (instr->IsLinked()) return ast_context()->ReturnValue(instr); } else { HValue* key = Pop(); HValue* obj = Pop(); bool has_side_effects = false; HValue* load = HandleKeyedElementAccess( obj, key, NULL, expr, ast_id, expr->LoadId(), LOAD, &has_side_effects); if (has_side_effects) { if (ast_context()->IsEffect()) { Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } else { Push(load); Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); Drop(1); } } if (load == NULL) return; return ast_context()->ReturnValue(load); } return ast_context()->ReturnInstruction(instr, ast_id); } void HOptimizedGraphBuilder::VisitProperty(Property* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); if (TryArgumentsAccess(expr)) return; CHECK_ALIVE(VisitForValue(expr->obj())); if (!expr->key()->IsPropertyName() || expr->IsStringAccess()) { CHECK_ALIVE(VisitForValue(expr->key())); } BuildLoad(expr, expr->id()); } HInstruction* HGraphBuilder::BuildConstantMapCheck(Handle<JSObject> constant) { HCheckMaps* check = Add<HCheckMaps>( Add<HConstant>(constant), handle(constant->map())); check->ClearDependsOnFlag(kElementsKind); return check; } HInstruction* HGraphBuilder::BuildCheckPrototypeMaps(Handle<JSObject> prototype, Handle<JSObject> holder) { PrototypeIterator iter(isolate(), prototype, PrototypeIterator::START_AT_RECEIVER); while (holder.is_null() || !PrototypeIterator::GetCurrent(iter).is_identical_to(holder)) { BuildConstantMapCheck( Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter))); iter.Advance(); if (iter.IsAtEnd()) { return NULL; } } return BuildConstantMapCheck( Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter))); } void HOptimizedGraphBuilder::AddCheckPrototypeMaps(Handle<JSObject> holder, Handle<Map> receiver_map) { if (!holder.is_null()) { Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype())); BuildCheckPrototypeMaps(prototype, holder); } } HInstruction* HOptimizedGraphBuilder::NewPlainFunctionCall( HValue* fun, int argument_count, bool pass_argument_count) { return New<HCallJSFunction>(fun, argument_count, pass_argument_count); } HInstruction* HOptimizedGraphBuilder::NewArgumentAdaptorCall( HValue* fun, HValue* context, int argument_count, HValue* expected_param_count) { ArgumentAdaptorDescriptor descriptor(isolate()); HValue* arity = Add<HConstant>(argument_count - 1); HValue* op_vals[] = { context, fun, arity, expected_param_count }; Handle<Code> adaptor = isolate()->builtins()->ArgumentsAdaptorTrampoline(); HConstant* adaptor_value = Add<HConstant>(adaptor); return New<HCallWithDescriptor>( adaptor_value, argument_count, descriptor, Vector<HValue*>(op_vals, descriptor.GetEnvironmentLength())); } HInstruction* HOptimizedGraphBuilder::BuildCallConstantFunction( Handle<JSFunction> jsfun, int argument_count) { HValue* target = Add<HConstant>(jsfun); // For constant functions, we try to avoid calling the // argument adaptor and instead call the function directly int formal_parameter_count = jsfun->shared()->internal_formal_parameter_count(); bool dont_adapt_arguments = (formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel); int arity = argument_count - 1; bool can_invoke_directly = dont_adapt_arguments || formal_parameter_count == arity; if (can_invoke_directly) { if (jsfun.is_identical_to(current_info()->closure())) { graph()->MarkRecursive(); } return NewPlainFunctionCall(target, argument_count, dont_adapt_arguments); } else { HValue* param_count_value = Add<HConstant>(formal_parameter_count); HValue* context = Add<HLoadNamedField>( target, nullptr, HObjectAccess::ForFunctionContextPointer()); return NewArgumentAdaptorCall(target, context, argument_count, param_count_value); } UNREACHABLE(); return NULL; } class FunctionSorter { public: explicit FunctionSorter(int index = 0, int ticks = 0, int size = 0) : index_(index), ticks_(ticks), size_(size) {} int index() const { return index_; } int ticks() const { return ticks_; } int size() const { return size_; } private: int index_; int ticks_; int size_; }; inline bool operator<(const FunctionSorter& lhs, const FunctionSorter& rhs) { int diff = lhs.ticks() - rhs.ticks(); if (diff != 0) return diff > 0; return lhs.size() < rhs.size(); } void HOptimizedGraphBuilder::HandlePolymorphicCallNamed(Call* expr, HValue* receiver, SmallMapList* maps, Handle<String> name) { int argument_count = expr->arguments()->length() + 1; // Includes receiver. FunctionSorter order[kMaxCallPolymorphism]; bool handle_smi = false; bool handled_string = false; int ordered_functions = 0; int i; for (i = 0; i < maps->length() && ordered_functions < kMaxCallPolymorphism; ++i) { PropertyAccessInfo info(this, LOAD, maps->at(i), name); if (info.CanAccessMonomorphic() && info.IsDataConstant() && info.constant()->IsJSFunction()) { if (info.IsStringType()) { if (handled_string) continue; handled_string = true; } Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant()); if (info.IsNumberType()) { handle_smi = true; } expr->set_target(target); order[ordered_functions++] = FunctionSorter( i, target->shared()->profiler_ticks(), InliningAstSize(target)); } } std::sort(order, order + ordered_functions); if (i < maps->length()) { maps->Clear(); ordered_functions = -1; } HBasicBlock* number_block = NULL; HBasicBlock* join = NULL; handled_string = false; int count = 0; for (int fn = 0; fn < ordered_functions; ++fn) { int i = order[fn].index(); PropertyAccessInfo info(this, LOAD, maps->at(i), name); if (info.IsStringType()) { if (handled_string) continue; handled_string = true; } // Reloads the target. info.CanAccessMonomorphic(); Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant()); expr->set_target(target); if (count == 0) { // Only needed once. join = graph()->CreateBasicBlock(); if (handle_smi) { HBasicBlock* empty_smi_block = graph()->CreateBasicBlock(); HBasicBlock* not_smi_block = graph()->CreateBasicBlock(); number_block = graph()->CreateBasicBlock(); FinishCurrentBlock(New<HIsSmiAndBranch>( receiver, empty_smi_block, not_smi_block)); GotoNoSimulate(empty_smi_block, number_block); set_current_block(not_smi_block); } else { BuildCheckHeapObject(receiver); } } ++count; HBasicBlock* if_true = graph()->CreateBasicBlock(); HBasicBlock* if_false = graph()->CreateBasicBlock(); HUnaryControlInstruction* compare; Handle<Map> map = info.map(); if (info.IsNumberType()) { Handle<Map> heap_number_map = isolate()->factory()->heap_number_map(); compare = New<HCompareMap>(receiver, heap_number_map, if_true, if_false); } else if (info.IsStringType()) { compare = New<HIsStringAndBranch>(receiver, if_true, if_false); } else { compare = New<HCompareMap>(receiver, map, if_true, if_false); } FinishCurrentBlock(compare); if (info.IsNumberType()) { GotoNoSimulate(if_true, number_block); if_true = number_block; } set_current_block(if_true); AddCheckPrototypeMaps(info.holder(), map); HValue* function = Add<HConstant>(expr->target()); environment()->SetExpressionStackAt(0, function); Push(receiver); CHECK_ALIVE(VisitExpressions(expr->arguments())); bool needs_wrapping = info.NeedsWrappingFor(target); bool try_inline = FLAG_polymorphic_inlining && !needs_wrapping; if (FLAG_trace_inlining && try_inline) { Handle<JSFunction> caller = current_info()->closure(); SmartArrayPointer<char> caller_name = caller->shared()->DebugName()->ToCString(); PrintF("Trying to inline the polymorphic call to %s from %s\n", name->ToCString().get(), caller_name.get()); } if (try_inline && TryInlineCall(expr)) { // Trying to inline will signal that we should bailout from the // entire compilation by setting stack overflow on the visitor. if (HasStackOverflow()) return; } else { // Since HWrapReceiver currently cannot actually wrap numbers and strings, // use the regular CallFunctionStub for method calls to wrap the receiver. // TODO(verwaest): Support creation of value wrappers directly in // HWrapReceiver. HInstruction* call = needs_wrapping ? NewUncasted<HCallFunction>( function, argument_count, WRAP_AND_CALL) : BuildCallConstantFunction(target, argument_count); PushArgumentsFromEnvironment(argument_count); AddInstruction(call); Drop(1); // Drop the function. if (!ast_context()->IsEffect()) Push(call); } if (current_block() != NULL) Goto(join); set_current_block(if_false); } // Finish up. Unconditionally deoptimize if we've handled all the maps we // know about and do not want to handle ones we've never seen. Otherwise // use a generic IC. if (ordered_functions == maps->length() && FLAG_deoptimize_uncommon_cases) { FinishExitWithHardDeoptimization(Deoptimizer::kUnknownMapInPolymorphicCall); } else { Property* prop = expr->expression()->AsProperty(); HInstruction* function = BuildNamedGeneric( LOAD, prop, receiver, name, NULL, prop->IsUninitialized()); AddInstruction(function); Push(function); AddSimulate(prop->LoadId(), REMOVABLE_SIMULATE); environment()->SetExpressionStackAt(1, function); environment()->SetExpressionStackAt(0, receiver); CHECK_ALIVE(VisitExpressions(expr->arguments())); CallFunctionFlags flags = receiver->type().IsJSObject() ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD; HInstruction* call = New<HCallFunction>( function, argument_count, flags); PushArgumentsFromEnvironment(argument_count); Drop(1); // Function. if (join != NULL) { AddInstruction(call); if (!ast_context()->IsEffect()) Push(call); Goto(join); } else { return ast_context()->ReturnInstruction(call, expr->id()); } } // We assume that control flow is always live after an expression. So // even without predecessors to the join block, we set it as the exit // block and continue by adding instructions there. DCHECK(join != NULL); if (join->HasPredecessor()) { set_current_block(join); join->SetJoinId(expr->id()); if (!ast_context()->IsEffect()) return ast_context()->ReturnValue(Pop()); } else { set_current_block(NULL); } } void HOptimizedGraphBuilder::TraceInline(Handle<JSFunction> target, Handle<JSFunction> caller, const char* reason) { if (FLAG_trace_inlining) { SmartArrayPointer<char> target_name = target->shared()->DebugName()->ToCString(); SmartArrayPointer<char> caller_name = caller->shared()->DebugName()->ToCString(); if (reason == NULL) { PrintF("Inlined %s called from %s.\n", target_name.get(), caller_name.get()); } else { PrintF("Did not inline %s called from %s (%s).\n", target_name.get(), caller_name.get(), reason); } } } static const int kNotInlinable = 1000000000; int HOptimizedGraphBuilder::InliningAstSize(Handle<JSFunction> target) { if (!FLAG_use_inlining) return kNotInlinable; // Precondition: call is monomorphic and we have found a target with the // appropriate arity. Handle<JSFunction> caller = current_info()->closure(); Handle<SharedFunctionInfo> target_shared(target->shared()); // Always inline builtins marked for inlining. if (target->IsBuiltin()) { return target_shared->inline_builtin() ? 0 : kNotInlinable; } if (target_shared->IsApiFunction()) { TraceInline(target, caller, "target is api function"); return kNotInlinable; } // Do a quick check on source code length to avoid parsing large // inlining candidates. if (target_shared->SourceSize() > Min(FLAG_max_inlined_source_size, kUnlimitedMaxInlinedSourceSize)) { TraceInline(target, caller, "target text too big"); return kNotInlinable; } // Target must be inlineable. if (!target_shared->IsInlineable()) { TraceInline(target, caller, "target not inlineable"); return kNotInlinable; } if (target_shared->disable_optimization_reason() != kNoReason) { TraceInline(target, caller, "target contains unsupported syntax [early]"); return kNotInlinable; } int nodes_added = target_shared->ast_node_count(); return nodes_added; } bool HOptimizedGraphBuilder::TryInline(Handle<JSFunction> target, int arguments_count, HValue* implicit_return_value, BailoutId ast_id, BailoutId return_id, InliningKind inlining_kind) { if (target->context()->native_context() != top_info()->closure()->context()->native_context()) { return false; } int nodes_added = InliningAstSize(target); if (nodes_added == kNotInlinable) return false; Handle<JSFunction> caller = current_info()->closure(); if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) { TraceInline(target, caller, "target AST is too large [early]"); return false; } // Don't inline deeper than the maximum number of inlining levels. HEnvironment* env = environment(); int current_level = 1; while (env->outer() != NULL) { if (current_level == FLAG_max_inlining_levels) { TraceInline(target, caller, "inline depth limit reached"); return false; } if (env->outer()->frame_type() == JS_FUNCTION) { current_level++; } env = env->outer(); } // Don't inline recursive functions. for (FunctionState* state = function_state(); state != NULL; state = state->outer()) { if (*state->compilation_info()->closure() == *target) { TraceInline(target, caller, "target is recursive"); return false; } } // We don't want to add more than a certain number of nodes from inlining. // Always inline small methods (<= 10 nodes). if (inlined_count_ > Min(FLAG_max_inlined_nodes_cumulative, kUnlimitedMaxInlinedNodesCumulative)) { TraceInline(target, caller, "cumulative AST node limit reached"); return false; } // Parse and allocate variables. // Use the same AstValueFactory for creating strings in the sub-compilation // step, but don't transfer ownership to target_info. ParseInfo parse_info(zone(), target); parse_info.set_ast_value_factory( top_info()->parse_info()->ast_value_factory()); parse_info.set_ast_value_factory_owned(false); CompilationInfo target_info(&parse_info); Handle<SharedFunctionInfo> target_shared(target->shared()); if (!Compiler::ParseAndAnalyze(target_info.parse_info())) { if (target_info.isolate()->has_pending_exception()) { // Parse or scope error, never optimize this function. SetStackOverflow(); target_shared->DisableOptimization(kParseScopeError); } TraceInline(target, caller, "parse failure"); return false; } if (target_info.scope()->num_heap_slots() > 0) { TraceInline(target, caller, "target has context-allocated variables"); return false; } FunctionLiteral* function = target_info.function(); // The following conditions must be checked again after re-parsing, because // earlier the information might not have been complete due to lazy parsing. nodes_added = function->ast_node_count(); if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) { TraceInline(target, caller, "target AST is too large [late]"); return false; } if (function->dont_optimize()) { TraceInline(target, caller, "target contains unsupported syntax [late]"); return false; } // If the function uses the arguments object check that inlining of functions // with arguments object is enabled and the arguments-variable is // stack allocated. if (function->scope()->arguments() != NULL) { if (!FLAG_inline_arguments) { TraceInline(target, caller, "target uses arguments object"); return false; } } // All declarations must be inlineable. ZoneList<Declaration*>* decls = target_info.scope()->declarations(); int decl_count = decls->length(); for (int i = 0; i < decl_count; ++i) { if (!decls->at(i)->IsInlineable()) { TraceInline(target, caller, "target has non-trivial declaration"); return false; } } // Generate the deoptimization data for the unoptimized version of // the target function if we don't already have it. if (!Compiler::EnsureDeoptimizationSupport(&target_info)) { TraceInline(target, caller, "could not generate deoptimization info"); return false; } // ---------------------------------------------------------------- // After this point, we've made a decision to inline this function (so // TryInline should always return true). // Type-check the inlined function. DCHECK(target_shared->has_deoptimization_support()); AstTyper::Run(&target_info); int inlining_id = 0; if (top_info()->is_tracking_positions()) { inlining_id = top_info()->TraceInlinedFunction( target_shared, source_position(), function_state()->inlining_id()); } // Save the pending call context. Set up new one for the inlined function. // The function state is new-allocated because we need to delete it // in two different places. FunctionState* target_state = new FunctionState(this, &target_info, inlining_kind, inlining_id); HConstant* undefined = graph()->GetConstantUndefined(); HEnvironment* inner_env = environment()->CopyForInlining(target, arguments_count, function, undefined, function_state()->inlining_kind()); HConstant* context = Add<HConstant>(Handle<Context>(target->context())); inner_env->BindContext(context); // Create a dematerialized arguments object for the function, also copy the // current arguments values to use them for materialization. HEnvironment* arguments_env = inner_env->arguments_environment(); int parameter_count = arguments_env->parameter_count(); HArgumentsObject* arguments_object = Add<HArgumentsObject>(parameter_count); for (int i = 0; i < parameter_count; i++) { arguments_object->AddArgument(arguments_env->Lookup(i), zone()); } // If the function uses arguments object then bind bind one. if (function->scope()->arguments() != NULL) { DCHECK(function->scope()->arguments()->IsStackAllocated()); inner_env->Bind(function->scope()->arguments(), arguments_object); } // Capture the state before invoking the inlined function for deopt in the // inlined function. This simulate has no bailout-id since it's not directly // reachable for deopt, and is only used to capture the state. If the simulate // becomes reachable by merging, the ast id of the simulate merged into it is // adopted. Add<HSimulate>(BailoutId::None()); current_block()->UpdateEnvironment(inner_env); Scope* saved_scope = scope(); set_scope(target_info.scope()); HEnterInlined* enter_inlined = Add<HEnterInlined>(return_id, target, context, arguments_count, function, function_state()->inlining_kind(), function->scope()->arguments(), arguments_object); if (top_info()->is_tracking_positions()) { enter_inlined->set_inlining_id(inlining_id); } function_state()->set_entry(enter_inlined); VisitDeclarations(target_info.scope()->declarations()); VisitStatements(function->body()); set_scope(saved_scope); if (HasStackOverflow()) { // Bail out if the inline function did, as we cannot residualize a call // instead, but do not disable optimization for the outer function. TraceInline(target, caller, "inline graph construction failed"); target_shared->DisableOptimization(kInliningBailedOut); current_info()->RetryOptimization(kInliningBailedOut); delete target_state; return true; } // Update inlined nodes count. inlined_count_ += nodes_added; Handle<Code> unoptimized_code(target_shared->code()); DCHECK(unoptimized_code->kind() == Code::FUNCTION); Handle<TypeFeedbackInfo> type_info( TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info())); graph()->update_type_change_checksum(type_info->own_type_change_checksum()); TraceInline(target, caller, NULL); if (current_block() != NULL) { FunctionState* state = function_state(); if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) { // Falling off the end of an inlined construct call. In a test context the // return value will always evaluate to true, in a value context the // return value is the newly allocated receiver. if (call_context()->IsTest()) { Goto(inlined_test_context()->if_true(), state); } else if (call_context()->IsEffect()) { Goto(function_return(), state); } else { DCHECK(call_context()->IsValue()); AddLeaveInlined(implicit_return_value, state); } } else if (state->inlining_kind() == SETTER_CALL_RETURN) { // Falling off the end of an inlined setter call. The returned value is // never used, the value of an assignment is always the value of the RHS // of the assignment. if (call_context()->IsTest()) { inlined_test_context()->ReturnValue(implicit_return_value); } else if (call_context()->IsEffect()) { Goto(function_return(), state); } else { DCHECK(call_context()->IsValue()); AddLeaveInlined(implicit_return_value, state); } } else { // Falling off the end of a normal inlined function. This basically means // returning undefined. if (call_context()->IsTest()) { Goto(inlined_test_context()->if_false(), state); } else if (call_context()->IsEffect()) { Goto(function_return(), state); } else { DCHECK(call_context()->IsValue()); AddLeaveInlined(undefined, state); } } } // Fix up the function exits. if (inlined_test_context() != NULL) { HBasicBlock* if_true = inlined_test_context()->if_true(); HBasicBlock* if_false = inlined_test_context()->if_false(); HEnterInlined* entry = function_state()->entry(); // Pop the return test context from the expression context stack. DCHECK(ast_context() == inlined_test_context()); ClearInlinedTestContext(); delete target_state; // Forward to the real test context. if (if_true->HasPredecessor()) { entry->RegisterReturnTarget(if_true, zone()); if_true->SetJoinId(ast_id); HBasicBlock* true_target = TestContext::cast(ast_context())->if_true(); Goto(if_true, true_target, function_state()); } if (if_false->HasPredecessor()) { entry->RegisterReturnTarget(if_false, zone()); if_false->SetJoinId(ast_id); HBasicBlock* false_target = TestContext::cast(ast_context())->if_false(); Goto(if_false, false_target, function_state()); } set_current_block(NULL); return true; } else if (function_return()->HasPredecessor()) { function_state()->entry()->RegisterReturnTarget(function_return(), zone()); function_return()->SetJoinId(ast_id); set_current_block(function_return()); } else { set_current_block(NULL); } delete target_state; return true; } bool HOptimizedGraphBuilder::TryInlineCall(Call* expr) { return TryInline(expr->target(), expr->arguments()->length(), NULL, expr->id(), expr->ReturnId(), NORMAL_RETURN); } bool HOptimizedGraphBuilder::TryInlineConstruct(CallNew* expr, HValue* implicit_return_value) { return TryInline(expr->target(), expr->arguments()->length(), implicit_return_value, expr->id(), expr->ReturnId(), CONSTRUCT_CALL_RETURN); } bool HOptimizedGraphBuilder::TryInlineGetter(Handle<JSFunction> getter, Handle<Map> receiver_map, BailoutId ast_id, BailoutId return_id) { if (TryInlineApiGetter(getter, receiver_map, ast_id)) return true; return TryInline(getter, 0, NULL, ast_id, return_id, GETTER_CALL_RETURN); } bool HOptimizedGraphBuilder::TryInlineSetter(Handle<JSFunction> setter, Handle<Map> receiver_map, BailoutId id, BailoutId assignment_id, HValue* implicit_return_value) { if (TryInlineApiSetter(setter, receiver_map, id)) return true; return TryInline(setter, 1, implicit_return_value, id, assignment_id, SETTER_CALL_RETURN); } bool HOptimizedGraphBuilder::TryInlineIndirectCall(Handle<JSFunction> function, Call* expr, int arguments_count) { return TryInline(function, arguments_count, NULL, expr->id(), expr->ReturnId(), NORMAL_RETURN); } bool HOptimizedGraphBuilder::TryInlineBuiltinFunctionCall(Call* expr) { if (!expr->target()->shared()->HasBuiltinFunctionId()) return false; BuiltinFunctionId id = expr->target()->shared()->builtin_function_id(); switch (id) { case kMathExp: if (!FLAG_fast_math) break; // Fall through if FLAG_fast_math. case kMathRound: case kMathFround: case kMathFloor: case kMathAbs: case kMathSqrt: case kMathLog: case kMathClz32: if (expr->arguments()->length() == 1) { HValue* argument = Pop(); Drop(2); // Receiver and function. HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id); ast_context()->ReturnInstruction(op, expr->id()); return true; } break; case kMathImul: if (expr->arguments()->length() == 2) { HValue* right = Pop(); HValue* left = Pop(); Drop(2); // Receiver and function. HInstruction* op = HMul::NewImul(isolate(), zone(), context(), left, right); ast_context()->ReturnInstruction(op, expr->id()); return true; } break; default: // Not supported for inlining yet. break; } return false; } // static bool HOptimizedGraphBuilder::IsReadOnlyLengthDescriptor( Handle<Map> jsarray_map) { DCHECK(!jsarray_map->is_dictionary_map()); Isolate* isolate = jsarray_map->GetIsolate(); Handle<Name> length_string = isolate->factory()->length_string(); DescriptorArray* descriptors = jsarray_map->instance_descriptors(); int number = descriptors->SearchWithCache(*length_string, *jsarray_map); DCHECK_NE(DescriptorArray::kNotFound, number); return descriptors->GetDetails(number).IsReadOnly(); } // static bool HOptimizedGraphBuilder::CanInlineArrayResizeOperation( Handle<Map> receiver_map) { return !receiver_map.is_null() && receiver_map->instance_type() == JS_ARRAY_TYPE && IsFastElementsKind(receiver_map->elements_kind()) && !receiver_map->is_dictionary_map() && !IsReadOnlyLengthDescriptor(receiver_map) && !receiver_map->is_observed() && receiver_map->is_extensible(); } bool HOptimizedGraphBuilder::TryInlineBuiltinMethodCall( Call* expr, Handle<JSFunction> function, Handle<Map> receiver_map, int args_count_no_receiver) { if (!function->shared()->HasBuiltinFunctionId()) return false; BuiltinFunctionId id = function->shared()->builtin_function_id(); int argument_count = args_count_no_receiver + 1; // Plus receiver. if (receiver_map.is_null()) { HValue* receiver = environment()->ExpressionStackAt(args_count_no_receiver); if (receiver->IsConstant() && HConstant::cast(receiver)->handle(isolate())->IsHeapObject()) { receiver_map = handle(Handle<HeapObject>::cast( HConstant::cast(receiver)->handle(isolate()))->map()); } } // Try to inline calls like Math.* as operations in the calling function. switch (id) { case kStringCharCodeAt: case kStringCharAt: if (argument_count == 2) { HValue* index = Pop(); HValue* string = Pop(); Drop(1); // Function. HInstruction* char_code = BuildStringCharCodeAt(string, index); if (id == kStringCharCodeAt) { ast_context()->ReturnInstruction(char_code, expr->id()); return true; } AddInstruction(char_code); HInstruction* result = NewUncasted<HStringCharFromCode>(char_code); ast_context()->ReturnInstruction(result, expr->id()); return true; } break; case kStringFromCharCode: if (argument_count == 2) { HValue* argument = Pop(); Drop(2); // Receiver and function. HInstruction* result = NewUncasted<HStringCharFromCode>(argument); ast_context()->ReturnInstruction(result, expr->id()); return true; } break; case kMathExp: if (!FLAG_fast_math) break; // Fall through if FLAG_fast_math. case kMathRound: case kMathFround: case kMathFloor: case kMathAbs: case kMathSqrt: case kMathLog: case kMathClz32: if (argument_count == 2) { HValue* argument = Pop(); Drop(2); // Receiver and function. HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id); ast_context()->ReturnInstruction(op, expr->id()); return true; } break; case kMathPow: if (argument_count == 3) { HValue* right = Pop(); HValue* left = Pop(); Drop(2); // Receiver and function. HInstruction* result = NULL; // Use sqrt() if exponent is 0.5 or -0.5. if (right->IsConstant() && HConstant::cast(right)->HasDoubleValue()) { double exponent = HConstant::cast(right)->DoubleValue(); if (exponent == 0.5) { result = NewUncasted<HUnaryMathOperation>(left, kMathPowHalf); } else if (exponent == -0.5) { HValue* one = graph()->GetConstant1(); HInstruction* sqrt = AddUncasted<HUnaryMathOperation>( left, kMathPowHalf); // MathPowHalf doesn't have side effects so there's no need for // an environment simulation here. DCHECK(!sqrt->HasObservableSideEffects()); result = NewUncasted<HDiv>(one, sqrt); } else if (exponent == 2.0) { result = NewUncasted<HMul>(left, left); } } if (result == NULL) { result = NewUncasted<HPower>(left, right); } ast_context()->ReturnInstruction(result, expr->id()); return true; } break; case kMathMax: case kMathMin: if (argument_count == 3) { HValue* right = Pop(); HValue* left = Pop(); Drop(2); // Receiver and function. HMathMinMax::Operation op = (id == kMathMin) ? HMathMinMax::kMathMin : HMathMinMax::kMathMax; HInstruction* result = NewUncasted<HMathMinMax>(left, right, op); ast_context()->ReturnInstruction(result, expr->id()); return true; } break; case kMathImul: if (argument_count == 3) { HValue* right = Pop(); HValue* left = Pop(); Drop(2); // Receiver and function. HInstruction* result = HMul::NewImul(isolate(), zone(), context(), left, right); ast_context()->ReturnInstruction(result, expr->id()); return true; } break; case kArrayPop: { if (!CanInlineArrayResizeOperation(receiver_map)) return false; ElementsKind elements_kind = receiver_map->elements_kind(); Drop(args_count_no_receiver); HValue* result; HValue* reduced_length; HValue* receiver = Pop(); HValue* checked_object = AddCheckMap(receiver, receiver_map); HValue* length = Add<HLoadNamedField>(checked_object, nullptr, HObjectAccess::ForArrayLength(elements_kind)); Drop(1); // Function. { NoObservableSideEffectsScope scope(this); IfBuilder length_checker(this); HValue* bounds_check = length_checker.If<HCompareNumericAndBranch>( length, graph()->GetConstant0(), Token::EQ); length_checker.Then(); if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined()); length_checker.Else(); HValue* elements = AddLoadElements(checked_object); // Ensure that we aren't popping from a copy-on-write array. if (IsFastSmiOrObjectElementsKind(elements_kind)) { elements = BuildCopyElementsOnWrite(checked_object, elements, elements_kind, length); } reduced_length = AddUncasted<HSub>(length, graph()->GetConstant1()); result = AddElementAccess(elements, reduced_length, NULL, bounds_check, elements_kind, LOAD); HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind) ? graph()->GetConstantHole() : Add<HConstant>(HConstant::kHoleNaN); if (IsFastSmiOrObjectElementsKind(elements_kind)) { elements_kind = FAST_HOLEY_ELEMENTS; } AddElementAccess( elements, reduced_length, hole, bounds_check, elements_kind, STORE); Add<HStoreNamedField>( checked_object, HObjectAccess::ForArrayLength(elements_kind), reduced_length, STORE_TO_INITIALIZED_ENTRY); if (!ast_context()->IsEffect()) Push(result); length_checker.End(); } result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top(); Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) Drop(1); ast_context()->ReturnValue(result); return true; } case kArrayPush: { if (!CanInlineArrayResizeOperation(receiver_map)) return false; ElementsKind elements_kind = receiver_map->elements_kind(); // If there may be elements accessors in the prototype chain, the fast // inlined version can't be used. if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false; // If there currently can be no elements accessors on the prototype chain, // it doesn't mean that there won't be any later. Install a full prototype // chain check to trap element accessors being installed on the prototype // chain, which would cause elements to go to dictionary mode and result // in a map change. Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype())); BuildCheckPrototypeMaps(prototype, Handle<JSObject>()); const int argc = args_count_no_receiver; if (argc != 1) return false; HValue* value_to_push = Pop(); HValue* array = Pop(); Drop(1); // Drop function. HInstruction* new_size = NULL; HValue* length = NULL; { NoObservableSideEffectsScope scope(this); length = Add<HLoadNamedField>( array, nullptr, HObjectAccess::ForArrayLength(elements_kind)); new_size = AddUncasted<HAdd>(length, graph()->GetConstant1()); bool is_array = receiver_map->instance_type() == JS_ARRAY_TYPE; BuildUncheckedMonomorphicElementAccess(array, length, value_to_push, is_array, elements_kind, STORE, NEVER_RETURN_HOLE, STORE_AND_GROW_NO_TRANSITION); if (!ast_context()->IsEffect()) Push(new_size); Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) Drop(1); } ast_context()->ReturnValue(new_size); return true; } case kArrayShift: { if (!CanInlineArrayResizeOperation(receiver_map)) return false; ElementsKind kind = receiver_map->elements_kind(); // If there may be elements accessors in the prototype chain, the fast // inlined version can't be used. if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false; // If there currently can be no elements accessors on the prototype chain, // it doesn't mean that there won't be any later. Install a full prototype // chain check to trap element accessors being installed on the prototype // chain, which would cause elements to go to dictionary mode and result // in a map change. BuildCheckPrototypeMaps( handle(JSObject::cast(receiver_map->prototype()), isolate()), Handle<JSObject>::null()); // Threshold for fast inlined Array.shift(). HConstant* inline_threshold = Add<HConstant>(static_cast<int32_t>(16)); Drop(args_count_no_receiver); HValue* receiver = Pop(); HValue* function = Pop(); HValue* result; { NoObservableSideEffectsScope scope(this); HValue* length = Add<HLoadNamedField>( receiver, nullptr, HObjectAccess::ForArrayLength(kind)); IfBuilder if_lengthiszero(this); HValue* lengthiszero = if_lengthiszero.If<HCompareNumericAndBranch>( length, graph()->GetConstant0(), Token::EQ); if_lengthiszero.Then(); { if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined()); } if_lengthiszero.Else(); { HValue* elements = AddLoadElements(receiver); // Check if we can use the fast inlined Array.shift(). IfBuilder if_inline(this); if_inline.If<HCompareNumericAndBranch>( length, inline_threshold, Token::LTE); if (IsFastSmiOrObjectElementsKind(kind)) { // We cannot handle copy-on-write backing stores here. if_inline.AndIf<HCompareMap>( elements, isolate()->factory()->fixed_array_map()); } if_inline.Then(); { // Remember the result. if (!ast_context()->IsEffect()) { Push(AddElementAccess(elements, graph()->GetConstant0(), NULL, lengthiszero, kind, LOAD)); } // Compute the new length. HValue* new_length = AddUncasted<HSub>( length, graph()->GetConstant1()); new_length->ClearFlag(HValue::kCanOverflow); // Copy the remaining elements. LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement); { HValue* new_key = loop.BeginBody( graph()->GetConstant0(), new_length, Token::LT); HValue* key = AddUncasted<HAdd>(new_key, graph()->GetConstant1()); key->ClearFlag(HValue::kCanOverflow); ElementsKind copy_kind = kind == FAST_HOLEY_SMI_ELEMENTS ? FAST_HOLEY_ELEMENTS : kind; HValue* element = AddUncasted<HLoadKeyed>( elements, key, lengthiszero, copy_kind, ALLOW_RETURN_HOLE); HStoreKeyed* store = Add<HStoreKeyed>(elements, new_key, element, copy_kind); store->SetFlag(HValue::kAllowUndefinedAsNaN); } loop.EndBody(); // Put a hole at the end. HValue* hole = IsFastSmiOrObjectElementsKind(kind) ? graph()->GetConstantHole() : Add<HConstant>(HConstant::kHoleNaN); if (IsFastSmiOrObjectElementsKind(kind)) kind = FAST_HOLEY_ELEMENTS; Add<HStoreKeyed>( elements, new_length, hole, kind, INITIALIZING_STORE); // Remember new length. Add<HStoreNamedField>( receiver, HObjectAccess::ForArrayLength(kind), new_length, STORE_TO_INITIALIZED_ENTRY); } if_inline.Else(); { Add<HPushArguments>(receiver); result = Add<HCallJSFunction>(function, 1, true); if (!ast_context()->IsEffect()) Push(result); } if_inline.End(); } if_lengthiszero.End(); } result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top(); Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) Drop(1); ast_context()->ReturnValue(result); return true; } case kArrayIndexOf: case kArrayLastIndexOf: { if (receiver_map.is_null()) return false; if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false; ElementsKind kind = receiver_map->elements_kind(); if (!IsFastElementsKind(kind)) return false; if (receiver_map->is_observed()) return false; if (argument_count != 2) return false; if (!receiver_map->is_extensible()) return false; // If there may be elements accessors in the prototype chain, the fast // inlined version can't be used. if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false; // If there currently can be no elements accessors on the prototype chain, // it doesn't mean that there won't be any later. Install a full prototype // chain check to trap element accessors being installed on the prototype // chain, which would cause elements to go to dictionary mode and result // in a map change. BuildCheckPrototypeMaps( handle(JSObject::cast(receiver_map->prototype()), isolate()), Handle<JSObject>::null()); HValue* search_element = Pop(); HValue* receiver = Pop(); Drop(1); // Drop function. ArrayIndexOfMode mode = (id == kArrayIndexOf) ? kFirstIndexOf : kLastIndexOf; HValue* index = BuildArrayIndexOf(receiver, search_element, kind, mode); if (!ast_context()->IsEffect()) Push(index); Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) Drop(1); ast_context()->ReturnValue(index); return true; } default: // Not yet supported for inlining. break; } return false; } bool HOptimizedGraphBuilder::TryInlineApiFunctionCall(Call* expr, HValue* receiver) { Handle<JSFunction> function = expr->target(); int argc = expr->arguments()->length(); SmallMapList receiver_maps; return TryInlineApiCall(function, receiver, &receiver_maps, argc, expr->id(), kCallApiFunction); } bool HOptimizedGraphBuilder::TryInlineApiMethodCall( Call* expr, HValue* receiver, SmallMapList* receiver_maps) { Handle<JSFunction> function = expr->target(); int argc = expr->arguments()->length(); return TryInlineApiCall(function, receiver, receiver_maps, argc, expr->id(), kCallApiMethod); } bool HOptimizedGraphBuilder::TryInlineApiGetter(Handle<JSFunction> function, Handle<Map> receiver_map, BailoutId ast_id) { SmallMapList receiver_maps(1, zone()); receiver_maps.Add(receiver_map, zone()); return TryInlineApiCall(function, NULL, // Receiver is on expression stack. &receiver_maps, 0, ast_id, kCallApiGetter); } bool HOptimizedGraphBuilder::TryInlineApiSetter(Handle<JSFunction> function, Handle<Map> receiver_map, BailoutId ast_id) { SmallMapList receiver_maps(1, zone()); receiver_maps.Add(receiver_map, zone()); return TryInlineApiCall(function, NULL, // Receiver is on expression stack. &receiver_maps, 1, ast_id, kCallApiSetter); } bool HOptimizedGraphBuilder::TryInlineApiCall(Handle<JSFunction> function, HValue* receiver, SmallMapList* receiver_maps, int argc, BailoutId ast_id, ApiCallType call_type) { if (function->context()->native_context() != top_info()->closure()->context()->native_context()) { return false; } CallOptimization optimization(function); if (!optimization.is_simple_api_call()) return false; Handle<Map> holder_map; for (int i = 0; i < receiver_maps->length(); ++i) { auto map = receiver_maps->at(i); // Don't inline calls to receivers requiring accesschecks. if (map->is_access_check_needed()) return false; } if (call_type == kCallApiFunction) { // Cannot embed a direct reference to the global proxy map // as it maybe dropped on deserialization. CHECK(!isolate()->serializer_enabled()); DCHECK_EQ(0, receiver_maps->length()); receiver_maps->Add(handle(function->global_proxy()->map()), zone()); } CallOptimization::HolderLookup holder_lookup = CallOptimization::kHolderNotFound; Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType( receiver_maps->first(), &holder_lookup); if (holder_lookup == CallOptimization::kHolderNotFound) return false; if (FLAG_trace_inlining) { PrintF("Inlining api function "); function->ShortPrint(); PrintF("\n"); } bool is_function = false; bool is_store = false; switch (call_type) { case kCallApiFunction: case kCallApiMethod: // Need to check that none of the receiver maps could have changed. Add<HCheckMaps>(receiver, receiver_maps); // Need to ensure the chain between receiver and api_holder is intact. if (holder_lookup == CallOptimization::kHolderFound) { AddCheckPrototypeMaps(api_holder, receiver_maps->first()); } else { DCHECK_EQ(holder_lookup, CallOptimization::kHolderIsReceiver); } // Includes receiver. PushArgumentsFromEnvironment(argc + 1); is_function = true; break; case kCallApiGetter: // Receiver and prototype chain cannot have changed. DCHECK_EQ(0, argc); DCHECK_NULL(receiver); // Receiver is on expression stack. receiver = Pop(); Add<HPushArguments>(receiver); break; case kCallApiSetter: { is_store = true; // Receiver and prototype chain cannot have changed. DCHECK_EQ(1, argc); DCHECK_NULL(receiver); // Receiver and value are on expression stack. HValue* value = Pop(); receiver = Pop(); Add<HPushArguments>(receiver, value); break; } } HValue* holder = NULL; switch (holder_lookup) { case CallOptimization::kHolderFound: holder = Add<HConstant>(api_holder); break; case CallOptimization::kHolderIsReceiver: holder = receiver; break; case CallOptimization::kHolderNotFound: UNREACHABLE(); break; } Handle<CallHandlerInfo> api_call_info = optimization.api_call_info(); Handle<Object> call_data_obj(api_call_info->data(), isolate()); bool call_data_undefined = call_data_obj->IsUndefined(); HValue* call_data = Add<HConstant>(call_data_obj); ApiFunction fun(v8::ToCData<Address>(api_call_info->callback())); ExternalReference ref = ExternalReference(&fun, ExternalReference::DIRECT_API_CALL, isolate()); HValue* api_function_address = Add<HConstant>(ExternalReference(ref)); HValue* op_vals[] = {context(), Add<HConstant>(function), call_data, holder, api_function_address, nullptr}; HInstruction* call = nullptr; if (!is_function) { CallApiAccessorStub stub(isolate(), is_store, call_data_undefined); Handle<Code> code = stub.GetCode(); HConstant* code_value = Add<HConstant>(code); ApiAccessorDescriptor descriptor(isolate()); DCHECK(arraysize(op_vals) - 1 == descriptor.GetEnvironmentLength()); call = New<HCallWithDescriptor>( code_value, argc + 1, descriptor, Vector<HValue*>(op_vals, descriptor.GetEnvironmentLength())); } else if (argc <= CallApiFunctionWithFixedArgsStub::kMaxFixedArgs) { CallApiFunctionWithFixedArgsStub stub(isolate(), argc, call_data_undefined); Handle<Code> code = stub.GetCode(); HConstant* code_value = Add<HConstant>(code); ApiFunctionWithFixedArgsDescriptor descriptor(isolate()); DCHECK(arraysize(op_vals) - 1 == descriptor.GetEnvironmentLength()); call = New<HCallWithDescriptor>( code_value, argc + 1, descriptor, Vector<HValue*>(op_vals, descriptor.GetEnvironmentLength())); Drop(1); // Drop function. } else { op_vals[arraysize(op_vals) - 1] = Add<HConstant>(argc); CallApiFunctionStub stub(isolate(), call_data_undefined); Handle<Code> code = stub.GetCode(); HConstant* code_value = Add<HConstant>(code); ApiFunctionDescriptor descriptor(isolate()); DCHECK(arraysize(op_vals) == descriptor.GetEnvironmentLength()); call = New<HCallWithDescriptor>( code_value, argc + 1, descriptor, Vector<HValue*>(op_vals, descriptor.GetEnvironmentLength())); Drop(1); // Drop function. } ast_context()->ReturnInstruction(call, ast_id); return true; } void HOptimizedGraphBuilder::HandleIndirectCall(Call* expr, HValue* function, int arguments_count) { Handle<JSFunction> known_function; int args_count_no_receiver = arguments_count - 1; if (function->IsConstant() && HConstant::cast(function)->handle(isolate())->IsJSFunction()) { HValue* receiver = environment()->ExpressionStackAt(args_count_no_receiver); Handle<Map> receiver_map; if (receiver->IsConstant() && HConstant::cast(receiver)->handle(isolate())->IsHeapObject()) { receiver_map = handle(Handle<HeapObject>::cast( HConstant::cast(receiver)->handle(isolate()))->map()); } known_function = Handle<JSFunction>::cast(HConstant::cast(function)->handle(isolate())); if (TryInlineBuiltinMethodCall(expr, known_function, receiver_map, args_count_no_receiver)) { if (FLAG_trace_inlining) { PrintF("Inlining builtin "); known_function->ShortPrint(); PrintF("\n"); } return; } if (TryInlineIndirectCall(known_function, expr, args_count_no_receiver)) { return; } } PushArgumentsFromEnvironment(arguments_count); HInvokeFunction* call = New<HInvokeFunction>(function, known_function, arguments_count); Drop(1); // Function ast_context()->ReturnInstruction(call, expr->id()); } bool HOptimizedGraphBuilder::TryIndirectCall(Call* expr) { DCHECK(expr->expression()->IsProperty()); if (!expr->IsMonomorphic()) { return false; } Handle<Map> function_map = expr->GetReceiverTypes()->first(); if (function_map->instance_type() != JS_FUNCTION_TYPE || !expr->target()->shared()->HasBuiltinFunctionId()) { return false; } switch (expr->target()->shared()->builtin_function_id()) { case kFunctionCall: { if (expr->arguments()->length() == 0) return false; BuildFunctionCall(expr); return true; } case kFunctionApply: { // For .apply, only the pattern f.apply(receiver, arguments) // is supported. if (current_info()->scope()->arguments() == NULL) return false; if (!CanBeFunctionApplyArguments(expr)) return false; BuildFunctionApply(expr); return true; } default: { return false; } } UNREACHABLE(); } void HOptimizedGraphBuilder::BuildFunctionApply(Call* expr) { ZoneList<Expression*>* args = expr->arguments(); CHECK_ALIVE(VisitForValue(args->at(0))); HValue* receiver = Pop(); // receiver HValue* function = Pop(); // f Drop(1); // apply Handle<Map> function_map = expr->GetReceiverTypes()->first(); HValue* checked_function = AddCheckMap(function, function_map); if (function_state()->outer() == NULL) { HInstruction* elements = Add<HArgumentsElements>(false); HInstruction* length = Add<HArgumentsLength>(elements); HValue* wrapped_receiver = BuildWrapReceiver(receiver, checked_function); HInstruction* result = New<HApplyArguments>(function, wrapped_receiver, length, elements); ast_context()->ReturnInstruction(result, expr->id()); } else { // We are inside inlined function and we know exactly what is inside // arguments object. But we need to be able to materialize at deopt. DCHECK_EQ(environment()->arguments_environment()->parameter_count(), function_state()->entry()->arguments_object()->arguments_count()); HArgumentsObject* args = function_state()->entry()->arguments_object(); const ZoneList<HValue*>* arguments_values = args->arguments_values(); int arguments_count = arguments_values->length(); Push(function); Push(BuildWrapReceiver(receiver, checked_function)); for (int i = 1; i < arguments_count; i++) { Push(arguments_values->at(i)); } HandleIndirectCall(expr, function, arguments_count); } } // f.call(...) void HOptimizedGraphBuilder::BuildFunctionCall(Call* expr) { HValue* function = Top(); // f Handle<Map> function_map = expr->GetReceiverTypes()->first(); HValue* checked_function = AddCheckMap(function, function_map); // f and call are on the stack in the unoptimized code // during evaluation of the arguments. CHECK_ALIVE(VisitExpressions(expr->arguments())); int args_length = expr->arguments()->length(); int receiver_index = args_length - 1; // Patch the receiver. HValue* receiver = BuildWrapReceiver( environment()->ExpressionStackAt(receiver_index), checked_function); environment()->SetExpressionStackAt(receiver_index, receiver); // Call must not be on the stack from now on. int call_index = args_length + 1; environment()->RemoveExpressionStackAt(call_index); HandleIndirectCall(expr, function, args_length); } HValue* HOptimizedGraphBuilder::ImplicitReceiverFor(HValue* function, Handle<JSFunction> target) { SharedFunctionInfo* shared = target->shared(); if (is_sloppy(shared->language_mode()) && !shared->native()) { // Cannot embed a direct reference to the global proxy // as is it dropped on deserialization. CHECK(!isolate()->serializer_enabled()); Handle<JSObject> global_proxy(target->context()->global_proxy()); return Add<HConstant>(global_proxy); } return graph()->GetConstantUndefined(); } void HOptimizedGraphBuilder::BuildArrayCall(Expression* expression, int arguments_count, HValue* function, Handle<AllocationSite> site) { Add<HCheckValue>(function, array_function()); if (IsCallArrayInlineable(arguments_count, site)) { BuildInlinedCallArray(expression, arguments_count, site); return; } HInstruction* call = PreProcessCall(New<HCallNewArray>( function, arguments_count + 1, site->GetElementsKind())); if (expression->IsCall()) { Drop(1); } ast_context()->ReturnInstruction(call, expression->id()); } HValue* HOptimizedGraphBuilder::BuildArrayIndexOf(HValue* receiver, HValue* search_element, ElementsKind kind, ArrayIndexOfMode mode) { DCHECK(IsFastElementsKind(kind)); NoObservableSideEffectsScope no_effects(this); HValue* elements = AddLoadElements(receiver); HValue* length = AddLoadArrayLength(receiver, kind); HValue* initial; HValue* terminating; Token::Value token; LoopBuilder::Direction direction; if (mode == kFirstIndexOf) { initial = graph()->GetConstant0(); terminating = length; token = Token::LT; direction = LoopBuilder::kPostIncrement; } else { DCHECK_EQ(kLastIndexOf, mode); initial = length; terminating = graph()->GetConstant0(); token = Token::GT; direction = LoopBuilder::kPreDecrement; } Push(graph()->GetConstantMinus1()); if (IsFastDoubleElementsKind(kind) || IsFastSmiElementsKind(kind)) { // Make sure that we can actually compare numbers correctly below, see // https://code.google.com/p/chromium/issues/detail?id=407946 for details. search_element = AddUncasted<HForceRepresentation>( search_element, IsFastSmiElementsKind(kind) ? Representation::Smi() : Representation::Double()); LoopBuilder loop(this, context(), direction); { HValue* index = loop.BeginBody(initial, terminating, token); HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr, kind, ALLOW_RETURN_HOLE); IfBuilder if_issame(this); if_issame.If<HCompareNumericAndBranch>(element, search_element, Token::EQ_STRICT); if_issame.Then(); { Drop(1); Push(index); loop.Break(); } if_issame.End(); } loop.EndBody(); } else { IfBuilder if_isstring(this); if_isstring.If<HIsStringAndBranch>(search_element); if_isstring.Then(); { LoopBuilder loop(this, context(), direction); { HValue* index = loop.BeginBody(initial, terminating, token); HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr, kind, ALLOW_RETURN_HOLE); IfBuilder if_issame(this); if_issame.If<HIsStringAndBranch>(element); if_issame.AndIf<HStringCompareAndBranch>( element, search_element, Token::EQ_STRICT); if_issame.Then(); { Drop(1); Push(index); loop.Break(); } if_issame.End(); } loop.EndBody(); } if_isstring.Else(); { IfBuilder if_isnumber(this); if_isnumber.If<HIsSmiAndBranch>(search_element); if_isnumber.OrIf<HCompareMap>( search_element, isolate()->factory()->heap_number_map()); if_isnumber.Then(); { HValue* search_number = AddUncasted<HForceRepresentation>(search_element, Representation::Double()); LoopBuilder loop(this, context(), direction); { HValue* index = loop.BeginBody(initial, terminating, token); HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr, kind, ALLOW_RETURN_HOLE); IfBuilder if_element_isnumber(this); if_element_isnumber.If<HIsSmiAndBranch>(element); if_element_isnumber.OrIf<HCompareMap>( element, isolate()->factory()->heap_number_map()); if_element_isnumber.Then(); { HValue* number = AddUncasted<HForceRepresentation>(element, Representation::Double()); IfBuilder if_issame(this); if_issame.If<HCompareNumericAndBranch>( number, search_number, Token::EQ_STRICT); if_issame.Then(); { Drop(1); Push(index); loop.Break(); } if_issame.End(); } if_element_isnumber.End(); } loop.EndBody(); } if_isnumber.Else(); { LoopBuilder loop(this, context(), direction); { HValue* index = loop.BeginBody(initial, terminating, token); HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr, kind, ALLOW_RETURN_HOLE); IfBuilder if_issame(this); if_issame.If<HCompareObjectEqAndBranch>( element, search_element); if_issame.Then(); { Drop(1); Push(index); loop.Break(); } if_issame.End(); } loop.EndBody(); } if_isnumber.End(); } if_isstring.End(); } return Pop(); } bool HOptimizedGraphBuilder::TryHandleArrayCall(Call* expr, HValue* function) { if (!array_function().is_identical_to(expr->target())) { return false; } Handle<AllocationSite> site = expr->allocation_site(); if (site.is_null()) return false; BuildArrayCall(expr, expr->arguments()->length(), function, site); return true; } bool HOptimizedGraphBuilder::TryHandleArrayCallNew(CallNew* expr, HValue* function) { if (!array_function().is_identical_to(expr->target())) { return false; } Handle<AllocationSite> site = expr->allocation_site(); if (site.is_null()) return false; BuildArrayCall(expr, expr->arguments()->length(), function, site); return true; } bool HOptimizedGraphBuilder::CanBeFunctionApplyArguments(Call* expr) { ZoneList<Expression*>* args = expr->arguments(); if (args->length() != 2) return false; VariableProxy* arg_two = args->at(1)->AsVariableProxy(); if (arg_two == NULL || !arg_two->var()->IsStackAllocated()) return false; HValue* arg_two_value = LookupAndMakeLive(arg_two->var()); if (!arg_two_value->CheckFlag(HValue::kIsArguments)) return false; return true; } void HOptimizedGraphBuilder::VisitCall(Call* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); Expression* callee = expr->expression(); int argument_count = expr->arguments()->length() + 1; // Plus receiver. HInstruction* call = NULL; Property* prop = callee->AsProperty(); if (prop != NULL) { CHECK_ALIVE(VisitForValue(prop->obj())); HValue* receiver = Top(); SmallMapList* maps; ComputeReceiverTypes(expr, receiver, &maps, zone()); if (prop->key()->IsPropertyName() && maps->length() > 0) { Handle<String> name = prop->key()->AsLiteral()->AsPropertyName(); PropertyAccessInfo info(this, LOAD, maps->first(), name); if (!info.CanAccessAsMonomorphic(maps)) { HandlePolymorphicCallNamed(expr, receiver, maps, name); return; } } HValue* key = NULL; if (!prop->key()->IsPropertyName()) { CHECK_ALIVE(VisitForValue(prop->key())); key = Pop(); } CHECK_ALIVE(PushLoad(prop, receiver, key)); HValue* function = Pop(); if (function->IsConstant() && HConstant::cast(function)->handle(isolate())->IsJSFunction()) { // Push the function under the receiver. environment()->SetExpressionStackAt(0, function); Push(receiver); Handle<JSFunction> known_function = Handle<JSFunction>::cast( HConstant::cast(function)->handle(isolate())); expr->set_target(known_function); if (TryIndirectCall(expr)) return; CHECK_ALIVE(VisitExpressions(expr->arguments())); Handle<Map> map = maps->length() == 1 ? maps->first() : Handle<Map>(); if (TryInlineBuiltinMethodCall(expr, known_function, map, expr->arguments()->length())) { if (FLAG_trace_inlining) { PrintF("Inlining builtin "); known_function->ShortPrint(); PrintF("\n"); } return; } if (TryInlineApiMethodCall(expr, receiver, maps)) return; // Wrap the receiver if necessary. if (NeedsWrapping(maps->first(), known_function)) { // Since HWrapReceiver currently cannot actually wrap numbers and // strings, use the regular CallFunctionStub for method calls to wrap // the receiver. // TODO(verwaest): Support creation of value wrappers directly in // HWrapReceiver. call = New<HCallFunction>( function, argument_count, WRAP_AND_CALL); } else if (TryInlineCall(expr)) { return; } else { call = BuildCallConstantFunction(known_function, argument_count); } } else { ArgumentsAllowedFlag arguments_flag = ARGUMENTS_NOT_ALLOWED; if (CanBeFunctionApplyArguments(expr) && expr->is_uninitialized()) { // We have to use EAGER deoptimization here because Deoptimizer::SOFT // gets ignored by the always-opt flag, which leads to incorrect code. Add<HDeoptimize>( Deoptimizer::kInsufficientTypeFeedbackForCallWithArguments, Deoptimizer::EAGER); arguments_flag = ARGUMENTS_FAKED; } // Push the function under the receiver. environment()->SetExpressionStackAt(0, function); Push(receiver); CHECK_ALIVE(VisitExpressions(expr->arguments(), arguments_flag)); CallFunctionFlags flags = receiver->type().IsJSObject() ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD; call = New<HCallFunction>(function, argument_count, flags); } PushArgumentsFromEnvironment(argument_count); } else { VariableProxy* proxy = expr->expression()->AsVariableProxy(); if (proxy != NULL && proxy->var()->is_possibly_eval(isolate())) { return Bailout(kPossibleDirectCallToEval); } // The function is on the stack in the unoptimized code during // evaluation of the arguments. CHECK_ALIVE(VisitForValue(expr->expression())); HValue* function = Top(); if (function->IsConstant() && HConstant::cast(function)->handle(isolate())->IsJSFunction()) { Handle<Object> constant = HConstant::cast(function)->handle(isolate()); Handle<JSFunction> target = Handle<JSFunction>::cast(constant); expr->SetKnownGlobalTarget(target); } // Placeholder for the receiver. Push(graph()->GetConstantUndefined()); CHECK_ALIVE(VisitExpressions(expr->arguments())); if (expr->IsMonomorphic()) { Add<HCheckValue>(function, expr->target()); // Patch the global object on the stack by the expected receiver. HValue* receiver = ImplicitReceiverFor(function, expr->target()); const int receiver_index = argument_count - 1; environment()->SetExpressionStackAt(receiver_index, receiver); if (TryInlineBuiltinFunctionCall(expr)) { if (FLAG_trace_inlining) { PrintF("Inlining builtin "); expr->target()->ShortPrint(); PrintF("\n"); } return; } if (TryInlineApiFunctionCall(expr, receiver)) return; if (TryHandleArrayCall(expr, function)) return; if (TryInlineCall(expr)) return; PushArgumentsFromEnvironment(argument_count); call = BuildCallConstantFunction(expr->target(), argument_count); } else { PushArgumentsFromEnvironment(argument_count); HCallFunction* call_function = New<HCallFunction>(function, argument_count); call = call_function; if (expr->is_uninitialized() && expr->IsUsingCallFeedbackICSlot(isolate())) { // We've never seen this call before, so let's have Crankshaft learn // through the type vector. Handle<SharedFunctionInfo> current_shared = function_state()->compilation_info()->shared_info(); Handle<TypeFeedbackVector> vector = handle(current_shared->feedback_vector(), isolate()); FeedbackVectorICSlot slot = expr->CallFeedbackICSlot(); call_function->SetVectorAndSlot(vector, slot); } } } Drop(1); // Drop the function. return ast_context()->ReturnInstruction(call, expr->id()); } void HOptimizedGraphBuilder::BuildInlinedCallArray( Expression* expression, int argument_count, Handle<AllocationSite> site) { DCHECK(!site.is_null()); DCHECK(argument_count >= 0 && argument_count <= 1); NoObservableSideEffectsScope no_effects(this); // We should at least have the constructor on the expression stack. HValue* constructor = environment()->ExpressionStackAt(argument_count); // Register on the site for deoptimization if the transition feedback changes. AllocationSite::RegisterForDeoptOnTransitionChange(site, top_info()); ElementsKind kind = site->GetElementsKind(); HInstruction* site_instruction = Add<HConstant>(site); // In the single constant argument case, we may have to adjust elements kind // to avoid creating a packed non-empty array. if (argument_count == 1 && !IsHoleyElementsKind(kind)) { HValue* argument = environment()->Top(); if (argument->IsConstant()) { HConstant* constant_argument = HConstant::cast(argument); DCHECK(constant_argument->HasSmiValue()); int constant_array_size = constant_argument->Integer32Value(); if (constant_array_size != 0) { kind = GetHoleyElementsKind(kind); } } } // Build the array. JSArrayBuilder array_builder(this, kind, site_instruction, constructor, DISABLE_ALLOCATION_SITES); HValue* new_object = argument_count == 0 ? array_builder.AllocateEmptyArray() : BuildAllocateArrayFromLength(&array_builder, Top()); int args_to_drop = argument_count + (expression->IsCall() ? 2 : 1); Drop(args_to_drop); ast_context()->ReturnValue(new_object); } // Checks whether allocation using the given constructor can be inlined. static bool IsAllocationInlineable(Handle<JSFunction> constructor) { return constructor->has_initial_map() && constructor->initial_map()->instance_type() == JS_OBJECT_TYPE && constructor->initial_map()->instance_size() < HAllocate::kMaxInlineSize && constructor->initial_map()->InitialPropertiesLength() == 0; } bool HOptimizedGraphBuilder::IsCallArrayInlineable( int argument_count, Handle<AllocationSite> site) { Handle<JSFunction> caller = current_info()->closure(); Handle<JSFunction> target = array_function(); // We should have the function plus array arguments on the environment stack. DCHECK(environment()->length() >= (argument_count + 1)); DCHECK(!site.is_null()); bool inline_ok = false; if (site->CanInlineCall()) { // We also want to avoid inlining in certain 1 argument scenarios. if (argument_count == 1) { HValue* argument = Top(); if (argument->IsConstant()) { // Do not inline if the constant length argument is not a smi or // outside the valid range for unrolled loop initialization. HConstant* constant_argument = HConstant::cast(argument); if (constant_argument->HasSmiValue()) { int value = constant_argument->Integer32Value(); inline_ok = value >= 0 && value <= kElementLoopUnrollThreshold; if (!inline_ok) { TraceInline(target, caller, "Constant length outside of valid inlining range."); } } } else { TraceInline(target, caller, "Dont inline [new] Array(n) where n isn't constant."); } } else if (argument_count == 0) { inline_ok = true; } else { TraceInline(target, caller, "Too many arguments to inline."); } } else { TraceInline(target, caller, "AllocationSite requested no inlining."); } if (inline_ok) { TraceInline(target, caller, NULL); } return inline_ok; } void HOptimizedGraphBuilder::VisitCallNew(CallNew* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position()); int argument_count = expr->arguments()->length() + 1; // Plus constructor. Factory* factory = isolate()->factory(); // The constructor function is on the stack in the unoptimized code // during evaluation of the arguments. CHECK_ALIVE(VisitForValue(expr->expression())); HValue* function = Top(); CHECK_ALIVE(VisitExpressions(expr->arguments())); if (function->IsConstant() && HConstant::cast(function)->handle(isolate())->IsJSFunction()) { Handle<Object> constant = HConstant::cast(function)->handle(isolate()); expr->SetKnownGlobalTarget(Handle<JSFunction>::cast(constant)); } if (FLAG_inline_construct && expr->IsMonomorphic() && IsAllocationInlineable(expr->target())) { Handle<JSFunction> constructor = expr->target(); HValue* check = Add<HCheckValue>(function, constructor); // Force completion of inobject slack tracking before generating // allocation code to finalize instance size. if (constructor->IsInobjectSlackTrackingInProgress()) { constructor->CompleteInobjectSlackTracking(); } // Calculate instance size from initial map of constructor. DCHECK(constructor->has_initial_map()); Handle<Map> initial_map(constructor->initial_map()); int instance_size = initial_map->instance_size(); DCHECK(initial_map->InitialPropertiesLength() == 0); // Allocate an instance of the implicit receiver object. HValue* size_in_bytes = Add<HConstant>(instance_size); HAllocationMode allocation_mode; if (FLAG_pretenuring_call_new) { if (FLAG_allocation_site_pretenuring) { // Try to use pretenuring feedback. Handle<AllocationSite> allocation_site = expr->allocation_site(); allocation_mode = HAllocationMode(allocation_site); // Take a dependency on allocation site. AllocationSite::RegisterForDeoptOnTenureChange(allocation_site, top_info()); } } HAllocate* receiver = BuildAllocate( size_in_bytes, HType::JSObject(), JS_OBJECT_TYPE, allocation_mode); receiver->set_known_initial_map(initial_map); // Initialize map and fields of the newly allocated object. { NoObservableSideEffectsScope no_effects(this); DCHECK(initial_map->instance_type() == JS_OBJECT_TYPE); Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(initial_map, JSObject::kMapOffset), Add<HConstant>(initial_map)); HValue* empty_fixed_array = Add<HConstant>(factory->empty_fixed_array()); Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(initial_map, JSObject::kPropertiesOffset), empty_fixed_array); Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(initial_map, JSObject::kElementsOffset), empty_fixed_array); if (initial_map->inobject_properties() != 0) { HConstant* undefined = graph()->GetConstantUndefined(); for (int i = 0; i < initial_map->inobject_properties(); i++) { int property_offset = initial_map->GetInObjectPropertyOffset(i); Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(initial_map, property_offset), undefined); } } } // Replace the constructor function with a newly allocated receiver using // the index of the receiver from the top of the expression stack. const int receiver_index = argument_count - 1; DCHECK(environment()->ExpressionStackAt(receiver_index) == function); environment()->SetExpressionStackAt(receiver_index, receiver); if (TryInlineConstruct(expr, receiver)) { // Inlining worked, add a dependency on the initial map to make sure that // this code is deoptimized whenever the initial map of the constructor // changes. Map::AddDependentCompilationInfo( initial_map, DependentCode::kInitialMapChangedGroup, top_info()); return; } // TODO(mstarzinger): For now we remove the previous HAllocate and all // corresponding instructions and instead add HPushArguments for the // arguments in case inlining failed. What we actually should do is for // inlining to try to build a subgraph without mutating the parent graph. HInstruction* instr = current_block()->last(); do { HInstruction* prev_instr = instr->previous(); instr->DeleteAndReplaceWith(NULL); instr = prev_instr; } while (instr != check); environment()->SetExpressionStackAt(receiver_index, function); HInstruction* call = PreProcessCall(New<HCallNew>(function, argument_count)); return ast_context()->ReturnInstruction(call, expr->id()); } else { // The constructor function is both an operand to the instruction and an // argument to the construct call. if (TryHandleArrayCallNew(expr, function)) return; HInstruction* call = PreProcessCall(New<HCallNew>(function, argument_count)); return ast_context()->ReturnInstruction(call, expr->id()); } } template <class ViewClass> void HGraphBuilder::BuildArrayBufferViewInitialization( HValue* obj, HValue* buffer, HValue* byte_offset, HValue* byte_length) { for (int offset = ViewClass::kSize; offset < ViewClass::kSizeWithInternalFields; offset += kPointerSize) { Add<HStoreNamedField>(obj, HObjectAccess::ForObservableJSObjectOffset(offset), graph()->GetConstant0()); } Add<HStoreNamedField>( obj, HObjectAccess::ForJSArrayBufferViewByteOffset(), byte_offset); Add<HStoreNamedField>( obj, HObjectAccess::ForJSArrayBufferViewByteLength(), byte_length); if (buffer != NULL) { Add<HStoreNamedField>( obj, HObjectAccess::ForJSArrayBufferViewBuffer(), buffer); HObjectAccess weak_first_view_access = HObjectAccess::ForJSArrayBufferWeakFirstView(); Add<HStoreNamedField>( obj, HObjectAccess::ForJSArrayBufferViewWeakNext(), Add<HLoadNamedField>(buffer, nullptr, weak_first_view_access)); Add<HStoreNamedField>(buffer, weak_first_view_access, obj); } else { Add<HStoreNamedField>( obj, HObjectAccess::ForJSArrayBufferViewBuffer(), Add<HConstant>(static_cast<int32_t>(0))); Add<HStoreNamedField>(obj, HObjectAccess::ForJSArrayBufferViewWeakNext(), graph()->GetConstantUndefined()); } } void HOptimizedGraphBuilder::GenerateDataViewInitialize( CallRuntime* expr) { ZoneList<Expression*>* arguments = expr->arguments(); DCHECK(arguments->length()== 4); CHECK_ALIVE(VisitForValue(arguments->at(0))); HValue* obj = Pop(); CHECK_ALIVE(VisitForValue(arguments->at(1))); HValue* buffer = Pop(); CHECK_ALIVE(VisitForValue(arguments->at(2))); HValue* byte_offset = Pop(); CHECK_ALIVE(VisitForValue(arguments->at(3))); HValue* byte_length = Pop(); { NoObservableSideEffectsScope scope(this); BuildArrayBufferViewInitialization<JSDataView>( obj, buffer, byte_offset, byte_length); } } static Handle<Map> TypedArrayMap(Isolate* isolate, ExternalArrayType array_type, ElementsKind target_kind) { Handle<Context> native_context = isolate->native_context(); Handle<JSFunction> fun; switch (array_type) { #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case kExternal##Type##Array: \ fun = Handle<JSFunction>(native_context->type##_array_fun()); \ break; TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE } Handle<Map> map(fun->initial_map()); return Map::AsElementsKind(map, target_kind); } HValue* HOptimizedGraphBuilder::BuildAllocateExternalElements( ExternalArrayType array_type, bool is_zero_byte_offset, HValue* buffer, HValue* byte_offset, HValue* length) { Handle<Map> external_array_map( isolate()->heap()->MapForExternalArrayType(array_type)); // The HForceRepresentation is to prevent possible deopt on int-smi // conversion after allocation but before the new object fields are set. length = AddUncasted<HForceRepresentation>(length, Representation::Smi()); HValue* elements = Add<HAllocate>( Add<HConstant>(ExternalArray::kAlignedSize), HType::HeapObject(), NOT_TENURED, external_array_map->instance_type()); AddStoreMapConstant(elements, external_array_map); Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(), length); HValue* backing_store = Add<HLoadNamedField>( buffer, nullptr, HObjectAccess::ForJSArrayBufferBackingStore()); HValue* typed_array_start; if (is_zero_byte_offset) { typed_array_start = backing_store; } else { HInstruction* external_pointer = AddUncasted<HAdd>(backing_store, byte_offset); // Arguments are checked prior to call to TypedArrayInitialize, // including byte_offset. external_pointer->ClearFlag(HValue::kCanOverflow); typed_array_start = external_pointer; } Add<HStoreNamedField>(elements, HObjectAccess::ForExternalArrayExternalPointer(), typed_array_start); return elements; } HValue* HOptimizedGraphBuilder::BuildAllocateFixedTypedArray( ExternalArrayType array_type, size_t element_size, ElementsKind fixed_elements_kind, HValue* byte_length, HValue* length) { STATIC_ASSERT( (FixedTypedArrayBase::kHeaderSize & kObjectAlignmentMask) == 0); HValue* total_size; // if fixed array's elements are not aligned to object's alignment, // we need to align the whole array to object alignment. if (element_size % kObjectAlignment != 0) { total_size = BuildObjectSizeAlignment( byte_length, FixedTypedArrayBase::kHeaderSize); } else { total_size = AddUncasted<HAdd>(byte_length, Add<HConstant>(FixedTypedArrayBase::kHeaderSize)); total_size->ClearFlag(HValue::kCanOverflow); } // The HForceRepresentation is to prevent possible deopt on int-smi // conversion after allocation but before the new object fields are set. length = AddUncasted<HForceRepresentation>(length, Representation::Smi()); Handle<Map> fixed_typed_array_map( isolate()->heap()->MapForFixedTypedArray(array_type)); HValue* elements = Add<HAllocate>(total_size, HType::HeapObject(), NOT_TENURED, fixed_typed_array_map->instance_type()); AddStoreMapConstant(elements, fixed_typed_array_map); Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(), length); HValue* filler = Add<HConstant>(static_cast<int32_t>(0)); { LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement); HValue* key = builder.BeginBody( Add<HConstant>(static_cast<int32_t>(0)), length, Token::LT); Add<HStoreKeyed>(elements, key, filler, fixed_elements_kind); builder.EndBody(); } return elements; } void HOptimizedGraphBuilder::GenerateTypedArrayInitialize( CallRuntime* expr) { ZoneList<Expression*>* arguments = expr->arguments(); static const int kObjectArg = 0; static const int kArrayIdArg = 1; static const int kBufferArg = 2; static const int kByteOffsetArg = 3; static const int kByteLengthArg = 4; static const int kArgsLength = 5; DCHECK(arguments->length() == kArgsLength); CHECK_ALIVE(VisitForValue(arguments->at(kObjectArg))); HValue* obj = Pop(); if (arguments->at(kArrayIdArg)->IsLiteral()) { // This should never happen in real use, but can happen when fuzzing. // Just bail out. Bailout(kNeedSmiLiteral); return; } Handle<Object> value = static_cast<Literal*>(arguments->at(kArrayIdArg))->value(); if (!value->IsSmi()) { // This should never happen in real use, but can happen when fuzzing. // Just bail out. Bailout(kNeedSmiLiteral); return; } int array_id = Smi::cast(*value)->value(); HValue* buffer; if (!arguments->at(kBufferArg)->IsNullLiteral()) { CHECK_ALIVE(VisitForValue(arguments->at(kBufferArg))); buffer = Pop(); } else { buffer = NULL; } HValue* byte_offset; bool is_zero_byte_offset; if (arguments->at(kByteOffsetArg)->IsLiteral() && Smi::FromInt(0) == *static_cast<Literal*>(arguments->at(kByteOffsetArg))->value()) { byte_offset = Add<HConstant>(static_cast<int32_t>(0)); is_zero_byte_offset = true; } else { CHECK_ALIVE(VisitForValue(arguments->at(kByteOffsetArg))); byte_offset = Pop(); is_zero_byte_offset = false; DCHECK(buffer != NULL); } CHECK_ALIVE(VisitForValue(arguments->at(kByteLengthArg))); HValue* byte_length = Pop(); NoObservableSideEffectsScope scope(this); IfBuilder byte_offset_smi(this); if (!is_zero_byte_offset) { byte_offset_smi.If<HIsSmiAndBranch>(byte_offset); byte_offset_smi.Then(); } ExternalArrayType array_type = kExternalInt8Array; // Bogus initialization. size_t element_size = 1; // Bogus initialization. ElementsKind external_elements_kind = // Bogus initialization. EXTERNAL_INT8_ELEMENTS; ElementsKind fixed_elements_kind = // Bogus initialization. INT8_ELEMENTS; Runtime::ArrayIdToTypeAndSize(array_id, &array_type, &external_elements_kind, &fixed_elements_kind, &element_size); { // byte_offset is Smi. BuildArrayBufferViewInitialization<JSTypedArray>( obj, buffer, byte_offset, byte_length); HInstruction* length = AddUncasted<HDiv>(byte_length, Add<HConstant>(static_cast<int32_t>(element_size))); Add<HStoreNamedField>(obj, HObjectAccess::ForJSTypedArrayLength(), length); HValue* elements; if (buffer != NULL) { elements = BuildAllocateExternalElements( array_type, is_zero_byte_offset, buffer, byte_offset, length); Handle<Map> obj_map = TypedArrayMap( isolate(), array_type, external_elements_kind); AddStoreMapConstant(obj, obj_map); } else { DCHECK(is_zero_byte_offset); elements = BuildAllocateFixedTypedArray( array_type, element_size, fixed_elements_kind, byte_length, length); } Add<HStoreNamedField>( obj, HObjectAccess::ForElementsPointer(), elements); } if (!is_zero_byte_offset) { byte_offset_smi.Else(); { // byte_offset is not Smi. Push(obj); CHECK_ALIVE(VisitForValue(arguments->at(kArrayIdArg))); Push(buffer); Push(byte_offset); Push(byte_length); PushArgumentsFromEnvironment(kArgsLength); Add<HCallRuntime>(expr->name(), expr->function(), kArgsLength); } } byte_offset_smi.End(); } void HOptimizedGraphBuilder::GenerateMaxSmi(CallRuntime* expr) { DCHECK(expr->arguments()->length() == 0); HConstant* max_smi = New<HConstant>(static_cast<int32_t>(Smi::kMaxValue)); return ast_context()->ReturnInstruction(max_smi, expr->id()); } void HOptimizedGraphBuilder::GenerateTypedArrayMaxSizeInHeap( CallRuntime* expr) { DCHECK(expr->arguments()->length() == 0); HConstant* result = New<HConstant>(static_cast<int32_t>( FLAG_typed_array_max_size_in_heap)); return ast_context()->ReturnInstruction(result, expr->id()); } void HOptimizedGraphBuilder::GenerateArrayBufferGetByteLength( CallRuntime* expr) { DCHECK(expr->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(expr->arguments()->at(0))); HValue* buffer = Pop(); HInstruction* result = New<HLoadNamedField>( buffer, nullptr, HObjectAccess::ForJSArrayBufferByteLength()); return ast_context()->ReturnInstruction(result, expr->id()); } void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteLength( CallRuntime* expr) { DCHECK(expr->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(expr->arguments()->at(0))); HValue* buffer = Pop(); HInstruction* result = New<HLoadNamedField>( buffer, nullptr, HObjectAccess::ForJSArrayBufferViewByteLength()); return ast_context()->ReturnInstruction(result, expr->id()); } void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteOffset( CallRuntime* expr) { DCHECK(expr->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(expr->arguments()->at(0))); HValue* buffer = Pop(); HInstruction* result = New<HLoadNamedField>( buffer, nullptr, HObjectAccess::ForJSArrayBufferViewByteOffset()); return ast_context()->ReturnInstruction(result, expr->id()); } void HOptimizedGraphBuilder::GenerateTypedArrayGetLength( CallRuntime* expr) { DCHECK(expr->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(expr->arguments()->at(0))); HValue* buffer = Pop(); HInstruction* result = New<HLoadNamedField>( buffer, nullptr, HObjectAccess::ForJSTypedArrayLength()); return ast_context()->ReturnInstruction(result, expr->id()); } void HOptimizedGraphBuilder::VisitCallRuntime(CallRuntime* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); if (expr->is_jsruntime()) { return Bailout(kCallToAJavaScriptRuntimeFunction); } const Runtime::Function* function = expr->function(); DCHECK(function != NULL); switch (function->function_id) { #define CALL_INTRINSIC_GENERATOR(Name) \ case Runtime::kInline##Name: \ return Generate##Name(expr); FOR_EACH_HYDROGEN_INTRINSIC(CALL_INTRINSIC_GENERATOR) #undef CALL_INTRINSIC_GENERATOR default: { Handle<String> name = expr->name(); int argument_count = expr->arguments()->length(); CHECK_ALIVE(VisitExpressions(expr->arguments())); PushArgumentsFromEnvironment(argument_count); HCallRuntime* call = New<HCallRuntime>(name, function, argument_count); return ast_context()->ReturnInstruction(call, expr->id()); } } } void HOptimizedGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); switch (expr->op()) { case Token::DELETE: return VisitDelete(expr); case Token::VOID: return VisitVoid(expr); case Token::TYPEOF: return VisitTypeof(expr); case Token::NOT: return VisitNot(expr); default: UNREACHABLE(); } } void HOptimizedGraphBuilder::VisitDelete(UnaryOperation* expr) { Property* prop = expr->expression()->AsProperty(); VariableProxy* proxy = expr->expression()->AsVariableProxy(); if (prop != NULL) { CHECK_ALIVE(VisitForValue(prop->obj())); CHECK_ALIVE(VisitForValue(prop->key())); HValue* key = Pop(); HValue* obj = Pop(); HValue* function = AddLoadJSBuiltin(Builtins::DELETE); Add<HPushArguments>(obj, key, Add<HConstant>(function_language_mode())); // TODO(olivf) InvokeFunction produces a check for the parameter count, // even though we are certain to pass the correct number of arguments here. HInstruction* instr = New<HInvokeFunction>(function, 3); return ast_context()->ReturnInstruction(instr, expr->id()); } else if (proxy != NULL) { Variable* var = proxy->var(); if (var->IsUnallocated()) { Bailout(kDeleteWithGlobalVariable); } else if (var->IsStackAllocated() || var->IsContextSlot()) { // Result of deleting non-global variables is false. 'this' is not // really a variable, though we implement it as one. The // subexpression does not have side effects. HValue* value = var->is_this() ? graph()->GetConstantTrue() : graph()->GetConstantFalse(); return ast_context()->ReturnValue(value); } else { Bailout(kDeleteWithNonGlobalVariable); } } else { // Result of deleting non-property, non-variable reference is true. // Evaluate the subexpression for side effects. CHECK_ALIVE(VisitForEffect(expr->expression())); return ast_context()->ReturnValue(graph()->GetConstantTrue()); } } void HOptimizedGraphBuilder::VisitVoid(UnaryOperation* expr) { CHECK_ALIVE(VisitForEffect(expr->expression())); return ast_context()->ReturnValue(graph()->GetConstantUndefined()); } void HOptimizedGraphBuilder::VisitTypeof(UnaryOperation* expr) { CHECK_ALIVE(VisitForTypeOf(expr->expression())); HValue* value = Pop(); HInstruction* instr = New<HTypeof>(value); return ast_context()->ReturnInstruction(instr, expr->id()); } void HOptimizedGraphBuilder::VisitNot(UnaryOperation* expr) { if (ast_context()->IsTest()) { TestContext* context = TestContext::cast(ast_context()); VisitForControl(expr->expression(), context->if_false(), context->if_true()); return; } if (ast_context()->IsEffect()) { VisitForEffect(expr->expression()); return; } DCHECK(ast_context()->IsValue()); HBasicBlock* materialize_false = graph()->CreateBasicBlock(); HBasicBlock* materialize_true = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(expr->expression(), materialize_false, materialize_true)); if (materialize_false->HasPredecessor()) { materialize_false->SetJoinId(expr->MaterializeFalseId()); set_current_block(materialize_false); Push(graph()->GetConstantFalse()); } else { materialize_false = NULL; } if (materialize_true->HasPredecessor()) { materialize_true->SetJoinId(expr->MaterializeTrueId()); set_current_block(materialize_true); Push(graph()->GetConstantTrue()); } else { materialize_true = NULL; } HBasicBlock* join = CreateJoin(materialize_false, materialize_true, expr->id()); set_current_block(join); if (join != NULL) return ast_context()->ReturnValue(Pop()); } HInstruction* HOptimizedGraphBuilder::BuildIncrement( bool returns_original_input, CountOperation* expr) { // The input to the count operation is on top of the expression stack. Representation rep = Representation::FromType(expr->type()); if (rep.IsNone() || rep.IsTagged()) { rep = Representation::Smi(); } if (returns_original_input) { // We need an explicit HValue representing ToNumber(input). The // actual HChange instruction we need is (sometimes) added in a later // phase, so it is not available now to be used as an input to HAdd and // as the return value. HInstruction* number_input = AddUncasted<HForceRepresentation>(Pop(), rep); if (!rep.IsDouble()) { number_input->SetFlag(HInstruction::kFlexibleRepresentation); number_input->SetFlag(HInstruction::kCannotBeTagged); } Push(number_input); } // The addition has no side effects, so we do not need // to simulate the expression stack after this instruction. // Any later failures deopt to the load of the input or earlier. HConstant* delta = (expr->op() == Token::INC) ? graph()->GetConstant1() : graph()->GetConstantMinus1(); HInstruction* instr = AddUncasted<HAdd>(Top(), delta); if (instr->IsAdd()) { HAdd* add = HAdd::cast(instr); add->set_observed_input_representation(1, rep); add->set_observed_input_representation(2, Representation::Smi()); } instr->SetFlag(HInstruction::kCannotBeTagged); instr->ClearAllSideEffects(); return instr; } void HOptimizedGraphBuilder::BuildStoreForEffect(Expression* expr, Property* prop, BailoutId ast_id, BailoutId return_id, HValue* object, HValue* key, HValue* value) { EffectContext for_effect(this); Push(object); if (key != NULL) Push(key); Push(value); BuildStore(expr, prop, ast_id, return_id); } void HOptimizedGraphBuilder::VisitCountOperation(CountOperation* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position()); Expression* target = expr->expression(); VariableProxy* proxy = target->AsVariableProxy(); Property* prop = target->AsProperty(); if (proxy == NULL && prop == NULL) { return Bailout(kInvalidLhsInCountOperation); } // Match the full code generator stack by simulating an extra stack // element for postfix operations in a non-effect context. The return // value is ToNumber(input). bool returns_original_input = expr->is_postfix() && !ast_context()->IsEffect(); HValue* input = NULL; // ToNumber(original_input). HValue* after = NULL; // The result after incrementing or decrementing. if (proxy != NULL) { Variable* var = proxy->var(); if (var->mode() == CONST_LEGACY) { return Bailout(kUnsupportedCountOperationWithConst); } if (var->mode() == CONST) { return Bailout(kNonInitializerAssignmentToConst); } // Argument of the count operation is a variable, not a property. DCHECK(prop == NULL); CHECK_ALIVE(VisitForValue(target)); after = BuildIncrement(returns_original_input, expr); input = returns_original_input ? Top() : Pop(); Push(after); switch (var->location()) { case Variable::UNALLOCATED: HandleGlobalVariableAssignment(var, after, expr->AssignmentId()); break; case Variable::PARAMETER: case Variable::LOCAL: BindIfLive(var, after); break; case Variable::CONTEXT: { // Bail out if we try to mutate a parameter value in a function // using the arguments object. We do not (yet) correctly handle the // arguments property of the function. if (current_info()->scope()->arguments() != NULL) { // Parameters will rewrite to context slots. We have no direct // way to detect that the variable is a parameter so we use a // linear search of the parameter list. int count = current_info()->scope()->num_parameters(); for (int i = 0; i < count; ++i) { if (var == current_info()->scope()->parameter(i)) { return Bailout(kAssignmentToParameterInArgumentsObject); } } } HValue* context = BuildContextChainWalk(var); HStoreContextSlot::Mode mode = IsLexicalVariableMode(var->mode()) ? HStoreContextSlot::kCheckDeoptimize : HStoreContextSlot::kNoCheck; HStoreContextSlot* instr = Add<HStoreContextSlot>(context, var->index(), mode, after); if (instr->HasObservableSideEffects()) { Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE); } break; } case Variable::LOOKUP: return Bailout(kLookupVariableInCountOperation); } Drop(returns_original_input ? 2 : 1); return ast_context()->ReturnValue(expr->is_postfix() ? input : after); } // Argument of the count operation is a property. DCHECK(prop != NULL); if (returns_original_input) Push(graph()->GetConstantUndefined()); CHECK_ALIVE(VisitForValue(prop->obj())); HValue* object = Top(); HValue* key = NULL; if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) { CHECK_ALIVE(VisitForValue(prop->key())); key = Top(); } CHECK_ALIVE(PushLoad(prop, object, key)); after = BuildIncrement(returns_original_input, expr); if (returns_original_input) { input = Pop(); // Drop object and key to push it again in the effect context below. Drop(key == NULL ? 1 : 2); environment()->SetExpressionStackAt(0, input); CHECK_ALIVE(BuildStoreForEffect( expr, prop, expr->id(), expr->AssignmentId(), object, key, after)); return ast_context()->ReturnValue(Pop()); } environment()->SetExpressionStackAt(0, after); return BuildStore(expr, prop, expr->id(), expr->AssignmentId()); } HInstruction* HOptimizedGraphBuilder::BuildStringCharCodeAt( HValue* string, HValue* index) { if (string->IsConstant() && index->IsConstant()) { HConstant* c_string = HConstant::cast(string); HConstant* c_index = HConstant::cast(index); if (c_string->HasStringValue() && c_index->HasNumberValue()) { int32_t i = c_index->NumberValueAsInteger32(); Handle<String> s = c_string->StringValue(); if (i < 0 || i >= s->length()) { return New<HConstant>(std::numeric_limits<double>::quiet_NaN()); } return New<HConstant>(s->Get(i)); } } string = BuildCheckString(string); index = Add<HBoundsCheck>(index, AddLoadStringLength(string)); return New<HStringCharCodeAt>(string, index); } // Checks if the given shift amounts have following forms: // (N1) and (N2) with N1 + N2 = 32; (sa) and (32 - sa). static bool ShiftAmountsAllowReplaceByRotate(HValue* sa, HValue* const32_minus_sa) { if (sa->IsConstant() && const32_minus_sa->IsConstant()) { const HConstant* c1 = HConstant::cast(sa); const HConstant* c2 = HConstant::cast(const32_minus_sa); return c1->HasInteger32Value() && c2->HasInteger32Value() && (c1->Integer32Value() + c2->Integer32Value() == 32); } if (!const32_minus_sa->IsSub()) return false; HSub* sub = HSub::cast(const32_minus_sa); return sub->left()->EqualsInteger32Constant(32) && sub->right() == sa; } // Checks if the left and the right are shift instructions with the oposite // directions that can be replaced by one rotate right instruction or not. // Returns the operand and the shift amount for the rotate instruction in the // former case. bool HGraphBuilder::MatchRotateRight(HValue* left, HValue* right, HValue** operand, HValue** shift_amount) { HShl* shl; HShr* shr; if (left->IsShl() && right->IsShr()) { shl = HShl::cast(left); shr = HShr::cast(right); } else if (left->IsShr() && right->IsShl()) { shl = HShl::cast(right); shr = HShr::cast(left); } else { return false; } if (shl->left() != shr->left()) return false; if (!ShiftAmountsAllowReplaceByRotate(shl->right(), shr->right()) && !ShiftAmountsAllowReplaceByRotate(shr->right(), shl->right())) { return false; } *operand = shr->left(); *shift_amount = shr->right(); return true; } bool CanBeZero(HValue* right) { if (right->IsConstant()) { HConstant* right_const = HConstant::cast(right); if (right_const->HasInteger32Value() && (right_const->Integer32Value() & 0x1f) != 0) { return false; } } return true; } HValue* HGraphBuilder::EnforceNumberType(HValue* number, Type* expected) { if (expected->Is(Type::SignedSmall())) { return AddUncasted<HForceRepresentation>(number, Representation::Smi()); } if (expected->Is(Type::Signed32())) { return AddUncasted<HForceRepresentation>(number, Representation::Integer32()); } return number; } HValue* HGraphBuilder::TruncateToNumber(HValue* value, Type** expected) { if (value->IsConstant()) { HConstant* constant = HConstant::cast(value); Maybe<HConstant*> number = constant->CopyToTruncatedNumber(isolate(), zone()); if (number.IsJust()) { *expected = Type::Number(zone()); return AddInstruction(number.FromJust()); } } // We put temporary values on the stack, which don't correspond to anything // in baseline code. Since nothing is observable we avoid recording those // pushes with a NoObservableSideEffectsScope. NoObservableSideEffectsScope no_effects(this); Type* expected_type = *expected; // Separate the number type from the rest. Type* expected_obj = Type::Intersect(expected_type, Type::NonNumber(zone()), zone()); Type* expected_number = Type::Intersect(expected_type, Type::Number(zone()), zone()); // We expect to get a number. // (We need to check first, since Type::None->Is(Type::Any()) == true. if (expected_obj->Is(Type::None())) { DCHECK(!expected_number->Is(Type::None(zone()))); return value; } if (expected_obj->Is(Type::Undefined(zone()))) { // This is already done by HChange. *expected = Type::Union(expected_number, Type::Number(zone()), zone()); return value; } return value; } HValue* HOptimizedGraphBuilder::BuildBinaryOperation( BinaryOperation* expr, HValue* left, HValue* right, PushBeforeSimulateBehavior push_sim_result) { Type* left_type = expr->left()->bounds().lower; Type* right_type = expr->right()->bounds().lower; Type* result_type = expr->bounds().lower; Maybe<int> fixed_right_arg = expr->fixed_right_arg(); Handle<AllocationSite> allocation_site = expr->allocation_site(); HAllocationMode allocation_mode; if (FLAG_allocation_site_pretenuring && !allocation_site.is_null()) { allocation_mode = HAllocationMode(allocation_site); } HValue* result = HGraphBuilder::BuildBinaryOperation( expr->op(), left, right, left_type, right_type, result_type, fixed_right_arg, allocation_mode); // Add a simulate after instructions with observable side effects, and // after phis, which are the result of BuildBinaryOperation when we // inlined some complex subgraph. if (result->HasObservableSideEffects() || result->IsPhi()) { if (push_sim_result == PUSH_BEFORE_SIMULATE) { Push(result); Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); Drop(1); } else { Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); } } return result; } HValue* HGraphBuilder::BuildBinaryOperation( Token::Value op, HValue* left, HValue* right, Type* left_type, Type* right_type, Type* result_type, Maybe<int> fixed_right_arg, HAllocationMode allocation_mode) { Representation left_rep = Representation::FromType(left_type); Representation right_rep = Representation::FromType(right_type); bool maybe_string_add = op == Token::ADD && (left_type->Maybe(Type::String()) || left_type->Maybe(Type::Receiver()) || right_type->Maybe(Type::String()) || right_type->Maybe(Type::Receiver())); if (!left_type->IsInhabited()) { Add<HDeoptimize>( Deoptimizer::kInsufficientTypeFeedbackForLHSOfBinaryOperation, Deoptimizer::SOFT); // TODO(rossberg): we should be able to get rid of non-continuous // defaults. left_type = Type::Any(zone()); } else { if (!maybe_string_add) left = TruncateToNumber(left, &left_type); left_rep = Representation::FromType(left_type); } if (!right_type->IsInhabited()) { Add<HDeoptimize>( Deoptimizer::kInsufficientTypeFeedbackForRHSOfBinaryOperation, Deoptimizer::SOFT); right_type = Type::Any(zone()); } else { if (!maybe_string_add) right = TruncateToNumber(right, &right_type); right_rep = Representation::FromType(right_type); } // Special case for string addition here. if (op == Token::ADD && (left_type->Is(Type::String()) || right_type->Is(Type::String()))) { // Validate type feedback for left argument. if (left_type->Is(Type::String())) { left = BuildCheckString(left); } // Validate type feedback for right argument. if (right_type->Is(Type::String())) { right = BuildCheckString(right); } // Convert left argument as necessary. if (left_type->Is(Type::Number())) { DCHECK(right_type->Is(Type::String())); left = BuildNumberToString(left, left_type); } else if (!left_type->Is(Type::String())) { DCHECK(right_type->Is(Type::String())); HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_RIGHT); Add<HPushArguments>(left, right); return AddUncasted<HInvokeFunction>(function, 2); } // Convert right argument as necessary. if (right_type->Is(Type::Number())) { DCHECK(left_type->Is(Type::String())); right = BuildNumberToString(right, right_type); } else if (!right_type->Is(Type::String())) { DCHECK(left_type->Is(Type::String())); HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_LEFT); Add<HPushArguments>(left, right); return AddUncasted<HInvokeFunction>(function, 2); } // Fast paths for empty constant strings. Handle<String> left_string = left->IsConstant() && HConstant::cast(left)->HasStringValue() ? HConstant::cast(left)->StringValue() : Handle<String>(); Handle<String> right_string = right->IsConstant() && HConstant::cast(right)->HasStringValue() ? HConstant::cast(right)->StringValue() : Handle<String>(); if (!left_string.is_null() && left_string->length() == 0) return right; if (!right_string.is_null() && right_string->length() == 0) return left; if (!left_string.is_null() && !right_string.is_null()) { return AddUncasted<HStringAdd>( left, right, allocation_mode.GetPretenureMode(), STRING_ADD_CHECK_NONE, allocation_mode.feedback_site()); } // Register the dependent code with the allocation site. if (!allocation_mode.feedback_site().is_null()) { DCHECK(!graph()->info()->IsStub()); Handle<AllocationSite> site(allocation_mode.feedback_site()); AllocationSite::RegisterForDeoptOnTenureChange(site, top_info()); } // Inline the string addition into the stub when creating allocation // mementos to gather allocation site feedback, or if we can statically // infer that we're going to create a cons string. if ((graph()->info()->IsStub() && allocation_mode.CreateAllocationMementos()) || (left->IsConstant() && HConstant::cast(left)->HasStringValue() && HConstant::cast(left)->StringValue()->length() + 1 >= ConsString::kMinLength) || (right->IsConstant() && HConstant::cast(right)->HasStringValue() && HConstant::cast(right)->StringValue()->length() + 1 >= ConsString::kMinLength)) { return BuildStringAdd(left, right, allocation_mode); } // Fallback to using the string add stub. return AddUncasted<HStringAdd>( left, right, allocation_mode.GetPretenureMode(), STRING_ADD_CHECK_NONE, allocation_mode.feedback_site()); } if (graph()->info()->IsStub()) { left = EnforceNumberType(left, left_type); right = EnforceNumberType(right, right_type); } Representation result_rep = Representation::FromType(result_type); bool is_non_primitive = (left_rep.IsTagged() && !left_rep.IsSmi()) || (right_rep.IsTagged() && !right_rep.IsSmi()); HInstruction* instr = NULL; // Only the stub is allowed to call into the runtime, since otherwise we would // inline several instructions (including the two pushes) for every tagged // operation in optimized code, which is more expensive, than a stub call. if (graph()->info()->IsStub() && is_non_primitive) { HValue* function = AddLoadJSBuiltin(BinaryOpIC::TokenToJSBuiltin(op)); Add<HPushArguments>(left, right); instr = AddUncasted<HInvokeFunction>(function, 2); } else { switch (op) { case Token::ADD: instr = AddUncasted<HAdd>(left, right); break; case Token::SUB: instr = AddUncasted<HSub>(left, right); break; case Token::MUL: instr = AddUncasted<HMul>(left, right); break; case Token::MOD: { if (fixed_right_arg.IsJust() && !right->EqualsInteger32Constant(fixed_right_arg.FromJust())) { HConstant* fixed_right = Add<HConstant>(static_cast<int>(fixed_right_arg.FromJust())); IfBuilder if_same(this); if_same.If<HCompareNumericAndBranch>(right, fixed_right, Token::EQ); if_same.Then(); if_same.ElseDeopt(Deoptimizer::kUnexpectedRHSOfBinaryOperation); right = fixed_right; } instr = AddUncasted<HMod>(left, right); break; } case Token::DIV: instr = AddUncasted<HDiv>(left, right); break; case Token::BIT_XOR: case Token::BIT_AND: instr = AddUncasted<HBitwise>(op, left, right); break; case Token::BIT_OR: { HValue* operand, *shift_amount; if (left_type->Is(Type::Signed32()) && right_type->Is(Type::Signed32()) && MatchRotateRight(left, right, &operand, &shift_amount)) { instr = AddUncasted<HRor>(operand, shift_amount); } else { instr = AddUncasted<HBitwise>(op, left, right); } break; } case Token::SAR: instr = AddUncasted<HSar>(left, right); break; case Token::SHR: instr = AddUncasted<HShr>(left, right); if (instr->IsShr() && CanBeZero(right)) { graph()->RecordUint32Instruction(instr); } break; case Token::SHL: instr = AddUncasted<HShl>(left, right); break; default: UNREACHABLE(); } } if (instr->IsBinaryOperation()) { HBinaryOperation* binop = HBinaryOperation::cast(instr); binop->set_observed_input_representation(1, left_rep); binop->set_observed_input_representation(2, right_rep); binop->initialize_output_representation(result_rep); if (graph()->info()->IsStub()) { // Stub should not call into stub. instr->SetFlag(HValue::kCannotBeTagged); // And should truncate on HForceRepresentation already. if (left->IsForceRepresentation()) { left->CopyFlag(HValue::kTruncatingToSmi, instr); left->CopyFlag(HValue::kTruncatingToInt32, instr); } if (right->IsForceRepresentation()) { right->CopyFlag(HValue::kTruncatingToSmi, instr); right->CopyFlag(HValue::kTruncatingToInt32, instr); } } } return instr; } // Check for the form (%_ClassOf(foo) === 'BarClass'). static bool IsClassOfTest(CompareOperation* expr) { if (expr->op() != Token::EQ_STRICT) return false; CallRuntime* call = expr->left()->AsCallRuntime(); if (call == NULL) return false; Literal* literal = expr->right()->AsLiteral(); if (literal == NULL) return false; if (!literal->value()->IsString()) return false; if (!call->name()->IsOneByteEqualTo(STATIC_CHAR_VECTOR("_ClassOf"))) { return false; } DCHECK(call->arguments()->length() == 1); return true; } void HOptimizedGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); switch (expr->op()) { case Token::COMMA: return VisitComma(expr); case Token::OR: case Token::AND: return VisitLogicalExpression(expr); default: return VisitArithmeticExpression(expr); } } void HOptimizedGraphBuilder::VisitComma(BinaryOperation* expr) { CHECK_ALIVE(VisitForEffect(expr->left())); // Visit the right subexpression in the same AST context as the entire // expression. Visit(expr->right()); } void HOptimizedGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) { bool is_logical_and = expr->op() == Token::AND; if (ast_context()->IsTest()) { TestContext* context = TestContext::cast(ast_context()); // Translate left subexpression. HBasicBlock* eval_right = graph()->CreateBasicBlock(); if (is_logical_and) { CHECK_BAILOUT(VisitForControl(expr->left(), eval_right, context->if_false())); } else { CHECK_BAILOUT(VisitForControl(expr->left(), context->if_true(), eval_right)); } // Translate right subexpression by visiting it in the same AST // context as the entire expression. if (eval_right->HasPredecessor()) { eval_right->SetJoinId(expr->RightId()); set_current_block(eval_right); Visit(expr->right()); } } else if (ast_context()->IsValue()) { CHECK_ALIVE(VisitForValue(expr->left())); DCHECK(current_block() != NULL); HValue* left_value = Top(); // Short-circuit left values that always evaluate to the same boolean value. if (expr->left()->ToBooleanIsTrue() || expr->left()->ToBooleanIsFalse()) { // l (evals true) && r -> r // l (evals true) || r -> l // l (evals false) && r -> l // l (evals false) || r -> r if (is_logical_and == expr->left()->ToBooleanIsTrue()) { Drop(1); CHECK_ALIVE(VisitForValue(expr->right())); } return ast_context()->ReturnValue(Pop()); } // We need an extra block to maintain edge-split form. HBasicBlock* empty_block = graph()->CreateBasicBlock(); HBasicBlock* eval_right = graph()->CreateBasicBlock(); ToBooleanStub::Types expected(expr->left()->to_boolean_types()); HBranch* test = is_logical_and ? New<HBranch>(left_value, expected, eval_right, empty_block) : New<HBranch>(left_value, expected, empty_block, eval_right); FinishCurrentBlock(test); set_current_block(eval_right); Drop(1); // Value of the left subexpression. CHECK_BAILOUT(VisitForValue(expr->right())); HBasicBlock* join_block = CreateJoin(empty_block, current_block(), expr->id()); set_current_block(join_block); return ast_context()->ReturnValue(Pop()); } else { DCHECK(ast_context()->IsEffect()); // In an effect context, we don't need the value of the left subexpression, // only its control flow and side effects. We need an extra block to // maintain edge-split form. HBasicBlock* empty_block = graph()->CreateBasicBlock(); HBasicBlock* right_block = graph()->CreateBasicBlock(); if (is_logical_and) { CHECK_BAILOUT(VisitForControl(expr->left(), right_block, empty_block)); } else { CHECK_BAILOUT(VisitForControl(expr->left(), empty_block, right_block)); } // TODO(kmillikin): Find a way to fix this. It's ugly that there are // actually two empty blocks (one here and one inserted by // TestContext::BuildBranch, and that they both have an HSimulate though the // second one is not a merge node, and that we really have no good AST ID to // put on that first HSimulate. if (empty_block->HasPredecessor()) { empty_block->SetJoinId(expr->id()); } else { empty_block = NULL; } if (right_block->HasPredecessor()) { right_block->SetJoinId(expr->RightId()); set_current_block(right_block); CHECK_BAILOUT(VisitForEffect(expr->right())); right_block = current_block(); } else { right_block = NULL; } HBasicBlock* join_block = CreateJoin(empty_block, right_block, expr->id()); set_current_block(join_block); // We did not materialize any value in the predecessor environments, // so there is no need to handle it here. } } void HOptimizedGraphBuilder::VisitArithmeticExpression(BinaryOperation* expr) { CHECK_ALIVE(VisitForValue(expr->left())); CHECK_ALIVE(VisitForValue(expr->right())); SetSourcePosition(expr->position()); HValue* right = Pop(); HValue* left = Pop(); HValue* result = BuildBinaryOperation(expr, left, right, ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE : PUSH_BEFORE_SIMULATE); if (top_info()->is_tracking_positions() && result->IsBinaryOperation()) { HBinaryOperation::cast(result)->SetOperandPositions( zone(), ScriptPositionToSourcePosition(expr->left()->position()), ScriptPositionToSourcePosition(expr->right()->position())); } return ast_context()->ReturnValue(result); } void HOptimizedGraphBuilder::HandleLiteralCompareTypeof(CompareOperation* expr, Expression* sub_expr, Handle<String> check) { CHECK_ALIVE(VisitForTypeOf(sub_expr)); SetSourcePosition(expr->position()); HValue* value = Pop(); HTypeofIsAndBranch* instr = New<HTypeofIsAndBranch>(value, check); return ast_context()->ReturnControl(instr, expr->id()); } static bool IsLiteralCompareBool(Isolate* isolate, HValue* left, Token::Value op, HValue* right) { return op == Token::EQ_STRICT && ((left->IsConstant() && HConstant::cast(left)->handle(isolate)->IsBoolean()) || (right->IsConstant() && HConstant::cast(right)->handle(isolate)->IsBoolean())); } void HOptimizedGraphBuilder::VisitCompareOperation(CompareOperation* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position()); // Check for a few fast cases. The AST visiting behavior must be in sync // with the full codegen: We don't push both left and right values onto // the expression stack when one side is a special-case literal. Expression* sub_expr = NULL; Handle<String> check; if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) { return HandleLiteralCompareTypeof(expr, sub_expr, check); } if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) { return HandleLiteralCompareNil(expr, sub_expr, kUndefinedValue); } if (expr->IsLiteralCompareNull(&sub_expr)) { return HandleLiteralCompareNil(expr, sub_expr, kNullValue); } if (IsClassOfTest(expr)) { CallRuntime* call = expr->left()->AsCallRuntime(); DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); Literal* literal = expr->right()->AsLiteral(); Handle<String> rhs = Handle<String>::cast(literal->value()); HClassOfTestAndBranch* instr = New<HClassOfTestAndBranch>(value, rhs); return ast_context()->ReturnControl(instr, expr->id()); } Type* left_type = expr->left()->bounds().lower; Type* right_type = expr->right()->bounds().lower; Type* combined_type = expr->combined_type(); CHECK_ALIVE(VisitForValue(expr->left())); CHECK_ALIVE(VisitForValue(expr->right())); HValue* right = Pop(); HValue* left = Pop(); Token::Value op = expr->op(); if (IsLiteralCompareBool(isolate(), left, op, right)) { HCompareObjectEqAndBranch* result = New<HCompareObjectEqAndBranch>(left, right); return ast_context()->ReturnControl(result, expr->id()); } if (op == Token::INSTANCEOF) { // Check to see if the rhs of the instanceof is a global function not // residing in new space. If it is we assume that the function will stay the // same. Handle<JSFunction> target = Handle<JSFunction>::null(); VariableProxy* proxy = expr->right()->AsVariableProxy(); bool global_function = (proxy != NULL) && proxy->var()->IsUnallocated(); if (global_function && current_info()->has_global_object()) { Handle<String> name = proxy->name(); Handle<GlobalObject> global(current_info()->global_object()); LookupIterator it(global, name, LookupIterator::OWN_SKIP_INTERCEPTOR); Handle<Object> value = JSObject::GetDataProperty(&it); if (it.IsFound() && value->IsJSFunction()) { Handle<JSFunction> candidate = Handle<JSFunction>::cast(value); // If the function is in new space we assume it's more likely to // change and thus prefer the general IC code. if (!isolate()->heap()->InNewSpace(*candidate)) { target = candidate; } } } // If the target is not null we have found a known global function that is // assumed to stay the same for this instanceof. if (target.is_null()) { HInstanceOf* result = New<HInstanceOf>(left, right); return ast_context()->ReturnInstruction(result, expr->id()); } else { Add<HCheckValue>(right, target); HInstanceOfKnownGlobal* result = New<HInstanceOfKnownGlobal>(left, target); return ast_context()->ReturnInstruction(result, expr->id()); } // Code below assumes that we don't fall through. UNREACHABLE(); } else if (op == Token::IN) { HValue* function = AddLoadJSBuiltin(Builtins::IN); Add<HPushArguments>(left, right); // TODO(olivf) InvokeFunction produces a check for the parameter count, // even though we are certain to pass the correct number of arguments here. HInstruction* result = New<HInvokeFunction>(function, 2); return ast_context()->ReturnInstruction(result, expr->id()); } PushBeforeSimulateBehavior push_behavior = ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE : PUSH_BEFORE_SIMULATE; HControlInstruction* compare = BuildCompareInstruction( op, left, right, left_type, right_type, combined_type, ScriptPositionToSourcePosition(expr->left()->position()), ScriptPositionToSourcePosition(expr->right()->position()), push_behavior, expr->id()); if (compare == NULL) return; // Bailed out. return ast_context()->ReturnControl(compare, expr->id()); } HControlInstruction* HOptimizedGraphBuilder::BuildCompareInstruction( Token::Value op, HValue* left, HValue* right, Type* left_type, Type* right_type, Type* combined_type, SourcePosition left_position, SourcePosition right_position, PushBeforeSimulateBehavior push_sim_result, BailoutId bailout_id) { // Cases handled below depend on collected type feedback. They should // soft deoptimize when there is no type feedback. if (!combined_type->IsInhabited()) { Add<HDeoptimize>( Deoptimizer::kInsufficientTypeFeedbackForCombinedTypeOfBinaryOperation, Deoptimizer::SOFT); combined_type = left_type = right_type = Type::Any(zone()); } Representation left_rep = Representation::FromType(left_type); Representation right_rep = Representation::FromType(right_type); Representation combined_rep = Representation::FromType(combined_type); if (combined_type->Is(Type::Receiver())) { if (Token::IsEqualityOp(op)) { // HCompareObjectEqAndBranch can only deal with object, so // exclude numbers. if ((left->IsConstant() && HConstant::cast(left)->HasNumberValue()) || (right->IsConstant() && HConstant::cast(right)->HasNumberValue())) { Add<HDeoptimize>(Deoptimizer::kTypeMismatchBetweenFeedbackAndConstant, Deoptimizer::SOFT); // The caller expects a branch instruction, so make it happy. return New<HBranch>(graph()->GetConstantTrue()); } // Can we get away with map check and not instance type check? HValue* operand_to_check = left->block()->block_id() < right->block()->block_id() ? left : right; if (combined_type->IsClass()) { Handle<Map> map = combined_type->AsClass()->Map(); AddCheckMap(operand_to_check, map); HCompareObjectEqAndBranch* result = New<HCompareObjectEqAndBranch>(left, right); if (top_info()->is_tracking_positions()) { result->set_operand_position(zone(), 0, left_position); result->set_operand_position(zone(), 1, right_position); } return result; } else { BuildCheckHeapObject(operand_to_check); Add<HCheckInstanceType>(operand_to_check, HCheckInstanceType::IS_SPEC_OBJECT); HCompareObjectEqAndBranch* result = New<HCompareObjectEqAndBranch>(left, right); return result; } } else { Bailout(kUnsupportedNonPrimitiveCompare); return NULL; } } else if (combined_type->Is(Type::InternalizedString()) && Token::IsEqualityOp(op)) { // If we have a constant argument, it should be consistent with the type // feedback (otherwise we fail assertions in HCompareObjectEqAndBranch). if ((left->IsConstant() && !HConstant::cast(left)->HasInternalizedStringValue()) || (right->IsConstant() && !HConstant::cast(right)->HasInternalizedStringValue())) { Add<HDeoptimize>(Deoptimizer::kTypeMismatchBetweenFeedbackAndConstant, Deoptimizer::SOFT); // The caller expects a branch instruction, so make it happy. return New<HBranch>(graph()->GetConstantTrue()); } BuildCheckHeapObject(left); Add<HCheckInstanceType>(left, HCheckInstanceType::IS_INTERNALIZED_STRING); BuildCheckHeapObject(right); Add<HCheckInstanceType>(right, HCheckInstanceType::IS_INTERNALIZED_STRING); HCompareObjectEqAndBranch* result = New<HCompareObjectEqAndBranch>(left, right); return result; } else if (combined_type->Is(Type::String())) { BuildCheckHeapObject(left); Add<HCheckInstanceType>(left, HCheckInstanceType::IS_STRING); BuildCheckHeapObject(right); Add<HCheckInstanceType>(right, HCheckInstanceType::IS_STRING); HStringCompareAndBranch* result = New<HStringCompareAndBranch>(left, right, op); return result; } else { if (combined_rep.IsTagged() || combined_rep.IsNone()) { HCompareGeneric* result = Add<HCompareGeneric>(left, right, op); result->set_observed_input_representation(1, left_rep); result->set_observed_input_representation(2, right_rep); if (result->HasObservableSideEffects()) { if (push_sim_result == PUSH_BEFORE_SIMULATE) { Push(result); AddSimulate(bailout_id, REMOVABLE_SIMULATE); Drop(1); } else { AddSimulate(bailout_id, REMOVABLE_SIMULATE); } } // TODO(jkummerow): Can we make this more efficient? HBranch* branch = New<HBranch>(result); return branch; } else { HCompareNumericAndBranch* result = New<HCompareNumericAndBranch>(left, right, op); result->set_observed_input_representation(left_rep, right_rep); if (top_info()->is_tracking_positions()) { result->SetOperandPositions(zone(), left_position, right_position); } return result; } } } void HOptimizedGraphBuilder::HandleLiteralCompareNil(CompareOperation* expr, Expression* sub_expr, NilValue nil) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); DCHECK(expr->op() == Token::EQ || expr->op() == Token::EQ_STRICT); if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position()); CHECK_ALIVE(VisitForValue(sub_expr)); HValue* value = Pop(); if (expr->op() == Token::EQ_STRICT) { HConstant* nil_constant = nil == kNullValue ? graph()->GetConstantNull() : graph()->GetConstantUndefined(); HCompareObjectEqAndBranch* instr = New<HCompareObjectEqAndBranch>(value, nil_constant); return ast_context()->ReturnControl(instr, expr->id()); } else { DCHECK_EQ(Token::EQ, expr->op()); Type* type = expr->combined_type()->Is(Type::None()) ? Type::Any(zone()) : expr->combined_type(); HIfContinuation continuation; BuildCompareNil(value, type, &continuation); return ast_context()->ReturnContinuation(&continuation, expr->id()); } } HInstruction* HOptimizedGraphBuilder::BuildThisFunction() { // If we share optimized code between different closures, the // this-function is not a constant, except inside an inlined body. if (function_state()->outer() != NULL) { return New<HConstant>( function_state()->compilation_info()->closure()); } else { return New<HThisFunction>(); } } HInstruction* HOptimizedGraphBuilder::BuildFastLiteral( Handle<JSObject> boilerplate_object, AllocationSiteUsageContext* site_context) { NoObservableSideEffectsScope no_effects(this); InstanceType instance_type = boilerplate_object->map()->instance_type(); DCHECK(instance_type == JS_ARRAY_TYPE || instance_type == JS_OBJECT_TYPE); HType type = instance_type == JS_ARRAY_TYPE ? HType::JSArray() : HType::JSObject(); HValue* object_size_constant = Add<HConstant>( boilerplate_object->map()->instance_size()); PretenureFlag pretenure_flag = NOT_TENURED; Handle<AllocationSite> site(site_context->current()); if (FLAG_allocation_site_pretenuring) { pretenure_flag = site_context->current()->GetPretenureMode(); AllocationSite::RegisterForDeoptOnTenureChange(site, top_info()); } AllocationSite::RegisterForDeoptOnTransitionChange(site, top_info()); HInstruction* object = Add<HAllocate>(object_size_constant, type, pretenure_flag, instance_type, site_context->current()); // If allocation folding reaches Page::kMaxRegularHeapObjectSize the // elements array may not get folded into the object. Hence, we set the // elements pointer to empty fixed array and let store elimination remove // this store in the folding case. HConstant* empty_fixed_array = Add<HConstant>( isolate()->factory()->empty_fixed_array()); Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(), empty_fixed_array); BuildEmitObjectHeader(boilerplate_object, object); Handle<FixedArrayBase> elements(boilerplate_object->elements()); int elements_size = (elements->length() > 0 && elements->map() != isolate()->heap()->fixed_cow_array_map()) ? elements->Size() : 0; if (pretenure_flag == TENURED && elements->map() == isolate()->heap()->fixed_cow_array_map() && isolate()->heap()->InNewSpace(*elements)) { // If we would like to pretenure a fixed cow array, we must ensure that the // array is already in old space, otherwise we'll create too many old-to- // new-space pointers (overflowing the store buffer). elements = Handle<FixedArrayBase>( isolate()->factory()->CopyAndTenureFixedCOWArray( Handle<FixedArray>::cast(elements))); boilerplate_object->set_elements(*elements); } HInstruction* object_elements = NULL; if (elements_size > 0) { HValue* object_elements_size = Add<HConstant>(elements_size); InstanceType instance_type = boilerplate_object->HasFastDoubleElements() ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE; object_elements = Add<HAllocate>( object_elements_size, HType::HeapObject(), pretenure_flag, instance_type, site_context->current()); } BuildInitElementsInObjectHeader(boilerplate_object, object, object_elements); // Copy object elements if non-COW. if (object_elements != NULL) { BuildEmitElements(boilerplate_object, elements, object_elements, site_context); } // Copy in-object properties. if (boilerplate_object->map()->NumberOfFields() != 0 || boilerplate_object->map()->unused_property_fields() > 0) { BuildEmitInObjectProperties(boilerplate_object, object, site_context, pretenure_flag); } return object; } void HOptimizedGraphBuilder::BuildEmitObjectHeader( Handle<JSObject> boilerplate_object, HInstruction* object) { DCHECK(boilerplate_object->properties()->length() == 0); Handle<Map> boilerplate_object_map(boilerplate_object->map()); AddStoreMapConstant(object, boilerplate_object_map); Handle<Object> properties_field = Handle<Object>(boilerplate_object->properties(), isolate()); DCHECK(*properties_field == isolate()->heap()->empty_fixed_array()); HInstruction* properties = Add<HConstant>(properties_field); HObjectAccess access = HObjectAccess::ForPropertiesPointer(); Add<HStoreNamedField>(object, access, properties); if (boilerplate_object->IsJSArray()) { Handle<JSArray> boilerplate_array = Handle<JSArray>::cast(boilerplate_object); Handle<Object> length_field = Handle<Object>(boilerplate_array->length(), isolate()); HInstruction* length = Add<HConstant>(length_field); DCHECK(boilerplate_array->length()->IsSmi()); Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength( boilerplate_array->GetElementsKind()), length); } } void HOptimizedGraphBuilder::BuildInitElementsInObjectHeader( Handle<JSObject> boilerplate_object, HInstruction* object, HInstruction* object_elements) { DCHECK(boilerplate_object->properties()->length() == 0); if (object_elements == NULL) { Handle<Object> elements_field = Handle<Object>(boilerplate_object->elements(), isolate()); object_elements = Add<HConstant>(elements_field); } Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(), object_elements); } void HOptimizedGraphBuilder::BuildEmitInObjectProperties( Handle<JSObject> boilerplate_object, HInstruction* object, AllocationSiteUsageContext* site_context, PretenureFlag pretenure_flag) { Handle<Map> boilerplate_map(boilerplate_object->map()); Handle<DescriptorArray> descriptors(boilerplate_map->instance_descriptors()); int limit = boilerplate_map->NumberOfOwnDescriptors(); int copied_fields = 0; for (int i = 0; i < limit; i++) { PropertyDetails details = descriptors->GetDetails(i); if (details.type() != DATA) continue; copied_fields++; FieldIndex field_index = FieldIndex::ForDescriptor(*boilerplate_map, i); int property_offset = field_index.offset(); Handle<Name> name(descriptors->GetKey(i)); // The access for the store depends on the type of the boilerplate. HObjectAccess access = boilerplate_object->IsJSArray() ? HObjectAccess::ForJSArrayOffset(property_offset) : HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset); if (boilerplate_object->IsUnboxedDoubleField(field_index)) { CHECK(!boilerplate_object->IsJSArray()); double value = boilerplate_object->RawFastDoublePropertyAt(field_index); access = access.WithRepresentation(Representation::Double()); Add<HStoreNamedField>(object, access, Add<HConstant>(value)); continue; } Handle<Object> value(boilerplate_object->RawFastPropertyAt(field_index), isolate()); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); Handle<AllocationSite> current_site = site_context->EnterNewScope(); HInstruction* result = BuildFastLiteral(value_object, site_context); site_context->ExitScope(current_site, value_object); Add<HStoreNamedField>(object, access, result); } else { Representation representation = details.representation(); HInstruction* value_instruction; if (representation.IsDouble()) { // Allocate a HeapNumber box and store the value into it. HValue* heap_number_constant = Add<HConstant>(HeapNumber::kSize); // This heap number alloc does not have a corresponding // AllocationSite. That is okay because // 1) it's a child object of another object with a valid allocation site // 2) we can just use the mode of the parent object for pretenuring HInstruction* double_box = Add<HAllocate>(heap_number_constant, HType::HeapObject(), pretenure_flag, MUTABLE_HEAP_NUMBER_TYPE); AddStoreMapConstant(double_box, isolate()->factory()->mutable_heap_number_map()); // Unwrap the mutable heap number from the boilerplate. HValue* double_value = Add<HConstant>(Handle<HeapNumber>::cast(value)->value()); Add<HStoreNamedField>( double_box, HObjectAccess::ForHeapNumberValue(), double_value); value_instruction = double_box; } else if (representation.IsSmi()) { value_instruction = value->IsUninitialized() ? graph()->GetConstant0() : Add<HConstant>(value); // Ensure that value is stored as smi. access = access.WithRepresentation(representation); } else { value_instruction = Add<HConstant>(value); } Add<HStoreNamedField>(object, access, value_instruction); } } int inobject_properties = boilerplate_object->map()->inobject_properties(); HInstruction* value_instruction = Add<HConstant>(isolate()->factory()->one_pointer_filler_map()); for (int i = copied_fields; i < inobject_properties; i++) { DCHECK(boilerplate_object->IsJSObject()); int property_offset = boilerplate_object->GetInObjectPropertyOffset(i); HObjectAccess access = HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset); Add<HStoreNamedField>(object, access, value_instruction); } } void HOptimizedGraphBuilder::BuildEmitElements( Handle<JSObject> boilerplate_object, Handle<FixedArrayBase> elements, HValue* object_elements, AllocationSiteUsageContext* site_context) { ElementsKind kind = boilerplate_object->map()->elements_kind(); int elements_length = elements->length(); HValue* object_elements_length = Add<HConstant>(elements_length); BuildInitializeElementsHeader(object_elements, kind, object_elements_length); // Copy elements backing store content. if (elements->IsFixedDoubleArray()) { BuildEmitFixedDoubleArray(elements, kind, object_elements); } else if (elements->IsFixedArray()) { BuildEmitFixedArray(elements, kind, object_elements, site_context); } else { UNREACHABLE(); } } void HOptimizedGraphBuilder::BuildEmitFixedDoubleArray( Handle<FixedArrayBase> elements, ElementsKind kind, HValue* object_elements) { HInstruction* boilerplate_elements = Add<HConstant>(elements); int elements_length = elements->length(); for (int i = 0; i < elements_length; i++) { HValue* key_constant = Add<HConstant>(i); HInstruction* value_instruction = Add<HLoadKeyed>( boilerplate_elements, key_constant, nullptr, kind, ALLOW_RETURN_HOLE); HInstruction* store = Add<HStoreKeyed>(object_elements, key_constant, value_instruction, kind); store->SetFlag(HValue::kAllowUndefinedAsNaN); } } void HOptimizedGraphBuilder::BuildEmitFixedArray( Handle<FixedArrayBase> elements, ElementsKind kind, HValue* object_elements, AllocationSiteUsageContext* site_context) { HInstruction* boilerplate_elements = Add<HConstant>(elements); int elements_length = elements->length(); Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements); for (int i = 0; i < elements_length; i++) { Handle<Object> value(fast_elements->get(i), isolate()); HValue* key_constant = Add<HConstant>(i); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); Handle<AllocationSite> current_site = site_context->EnterNewScope(); HInstruction* result = BuildFastLiteral(value_object, site_context); site_context->ExitScope(current_site, value_object); Add<HStoreKeyed>(object_elements, key_constant, result, kind); } else { ElementsKind copy_kind = kind == FAST_HOLEY_SMI_ELEMENTS ? FAST_HOLEY_ELEMENTS : kind; HInstruction* value_instruction = Add<HLoadKeyed>(boilerplate_elements, key_constant, nullptr, copy_kind, ALLOW_RETURN_HOLE); Add<HStoreKeyed>(object_elements, key_constant, value_instruction, copy_kind); } } } void HOptimizedGraphBuilder::VisitThisFunction(ThisFunction* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); HInstruction* instr = BuildThisFunction(); return ast_context()->ReturnInstruction(instr, expr->id()); } void HOptimizedGraphBuilder::VisitSuperReference(SuperReference* expr) { DCHECK(!HasStackOverflow()); DCHECK(current_block() != NULL); DCHECK(current_block()->HasPredecessor()); return Bailout(kSuperReference); } void HOptimizedGraphBuilder::VisitDeclarations( ZoneList<Declaration*>* declarations) { DCHECK(globals_.is_empty()); AstVisitor::VisitDeclarations(declarations); if (!globals_.is_empty()) { Handle<FixedArray> array = isolate()->factory()->NewFixedArray(globals_.length(), TENURED); for (int i = 0; i < globals_.length(); ++i) array->set(i, *globals_.at(i)); int flags = DeclareGlobalsEvalFlag::encode(current_info()->is_eval()) | DeclareGlobalsNativeFlag::encode(current_info()->is_native()) | DeclareGlobalsLanguageMode::encode(current_info()->language_mode()); Add<HDeclareGlobals>(array, flags); globals_.Rewind(0); } } void HOptimizedGraphBuilder::VisitVariableDeclaration( VariableDeclaration* declaration) { VariableProxy* proxy = declaration->proxy(); VariableMode mode = declaration->mode(); Variable* variable = proxy->var(); bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY; switch (variable->location()) { case Variable::UNALLOCATED: globals_.Add(variable->name(), zone()); globals_.Add(variable->binding_needs_init() ? isolate()->factory()->the_hole_value() : isolate()->factory()->undefined_value(), zone()); return; case Variable::PARAMETER: case Variable::LOCAL: if (hole_init) { HValue* value = graph()->GetConstantHole(); environment()->Bind(variable, value); } break; case Variable::CONTEXT: if (hole_init) { HValue* value = graph()->GetConstantHole(); HValue* context = environment()->context(); HStoreContextSlot* store = Add<HStoreContextSlot>( context, variable->index(), HStoreContextSlot::kNoCheck, value); if (store->HasObservableSideEffects()) { Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE); } } break; case Variable::LOOKUP: return Bailout(kUnsupportedLookupSlotInDeclaration); } } void HOptimizedGraphBuilder::VisitFunctionDeclaration( FunctionDeclaration* declaration) { VariableProxy* proxy = declaration->proxy(); Variable* variable = proxy->var(); switch (variable->location()) { case Variable::UNALLOCATED: { globals_.Add(variable->name(), zone()); Handle<SharedFunctionInfo> function = Compiler::BuildFunctionInfo( declaration->fun(), current_info()->script(), top_info()); // Check for stack-overflow exception. if (function.is_null()) return SetStackOverflow(); globals_.Add(function, zone()); return; } case Variable::PARAMETER: case Variable::LOCAL: { CHECK_ALIVE(VisitForValue(declaration->fun())); HValue* value = Pop(); BindIfLive(variable, value); break; } case Variable::CONTEXT: { CHECK_ALIVE(VisitForValue(declaration->fun())); HValue* value = Pop(); HValue* context = environment()->context(); HStoreContextSlot* store = Add<HStoreContextSlot>( context, variable->index(), HStoreContextSlot::kNoCheck, value); if (store->HasObservableSideEffects()) { Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE); } break; } case Variable::LOOKUP: return Bailout(kUnsupportedLookupSlotInDeclaration); } } void HOptimizedGraphBuilder::VisitModuleDeclaration( ModuleDeclaration* declaration) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitImportDeclaration( ImportDeclaration* declaration) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitExportDeclaration( ExportDeclaration* declaration) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitModuleLiteral(ModuleLiteral* module) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitModulePath(ModulePath* module) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitModuleUrl(ModuleUrl* module) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitModuleStatement(ModuleStatement* stmt) { UNREACHABLE(); } // Generators for inline runtime functions. // Support for types. void HOptimizedGraphBuilder::GenerateIsSmi(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HIsSmiAndBranch* result = New<HIsSmiAndBranch>(value); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsSpecObject(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HHasInstanceTypeAndBranch* result = New<HHasInstanceTypeAndBranch>(value, FIRST_SPEC_OBJECT_TYPE, LAST_SPEC_OBJECT_TYPE); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsFunction(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HHasInstanceTypeAndBranch* result = New<HHasInstanceTypeAndBranch>(value, JS_FUNCTION_TYPE); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsMinusZero(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HCompareMinusZeroAndBranch* result = New<HCompareMinusZeroAndBranch>(value); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateHasCachedArrayIndex(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HHasCachedArrayIndexAndBranch* result = New<HHasCachedArrayIndexAndBranch>(value); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsArray(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HHasInstanceTypeAndBranch* result = New<HHasInstanceTypeAndBranch>(value, JS_ARRAY_TYPE); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsRegExp(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HHasInstanceTypeAndBranch* result = New<HHasInstanceTypeAndBranch>(value, JS_REGEXP_TYPE); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsObject(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HIsObjectAndBranch* result = New<HIsObjectAndBranch>(value); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsJSProxy(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HIfContinuation continuation; IfBuilder if_proxy(this); HValue* smicheck = if_proxy.IfNot<HIsSmiAndBranch>(value); if_proxy.And(); HValue* map = Add<HLoadNamedField>(value, smicheck, HObjectAccess::ForMap()); HValue* instance_type = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType()); if_proxy.If<HCompareNumericAndBranch>( instance_type, Add<HConstant>(FIRST_JS_PROXY_TYPE), Token::GTE); if_proxy.And(); if_proxy.If<HCompareNumericAndBranch>( instance_type, Add<HConstant>(LAST_JS_PROXY_TYPE), Token::LTE); if_proxy.CaptureContinuation(&continuation); return ast_context()->ReturnContinuation(&continuation, call->id()); } void HOptimizedGraphBuilder::GenerateHasFastPackedElements(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* object = Pop(); HIfContinuation continuation(graph()->CreateBasicBlock(), graph()->CreateBasicBlock()); IfBuilder if_not_smi(this); if_not_smi.IfNot<HIsSmiAndBranch>(object); if_not_smi.Then(); { NoObservableSideEffectsScope no_effects(this); IfBuilder if_fast_packed(this); HValue* elements_kind = BuildGetElementsKind(object); if_fast_packed.If<HCompareNumericAndBranch>( elements_kind, Add<HConstant>(FAST_SMI_ELEMENTS), Token::EQ); if_fast_packed.Or(); if_fast_packed.If<HCompareNumericAndBranch>( elements_kind, Add<HConstant>(FAST_ELEMENTS), Token::EQ); if_fast_packed.Or(); if_fast_packed.If<HCompareNumericAndBranch>( elements_kind, Add<HConstant>(FAST_DOUBLE_ELEMENTS), Token::EQ); if_fast_packed.JoinContinuation(&continuation); } if_not_smi.JoinContinuation(&continuation); return ast_context()->ReturnContinuation(&continuation, call->id()); } void HOptimizedGraphBuilder::GenerateIsUndetectableObject(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HIsUndetectableAndBranch* result = New<HIsUndetectableAndBranch>(value); return ast_context()->ReturnControl(result, call->id()); } // Support for construct call checks. void HOptimizedGraphBuilder::GenerateIsConstructCall(CallRuntime* call) { DCHECK(call->arguments()->length() == 0); if (function_state()->outer() != NULL) { // We are generating graph for inlined function. HValue* value = function_state()->inlining_kind() == CONSTRUCT_CALL_RETURN ? graph()->GetConstantTrue() : graph()->GetConstantFalse(); return ast_context()->ReturnValue(value); } else { return ast_context()->ReturnControl(New<HIsConstructCallAndBranch>(), call->id()); } } // Support for arguments.length and arguments[?]. void HOptimizedGraphBuilder::GenerateArgumentsLength(CallRuntime* call) { DCHECK(call->arguments()->length() == 0); HInstruction* result = NULL; if (function_state()->outer() == NULL) { HInstruction* elements = Add<HArgumentsElements>(false); result = New<HArgumentsLength>(elements); } else { // Number of arguments without receiver. int argument_count = environment()-> arguments_environment()->parameter_count() - 1; result = New<HConstant>(argument_count); } return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateArguments(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* index = Pop(); HInstruction* result = NULL; if (function_state()->outer() == NULL) { HInstruction* elements = Add<HArgumentsElements>(false); HInstruction* length = Add<HArgumentsLength>(elements); HInstruction* checked_index = Add<HBoundsCheck>(index, length); result = New<HAccessArgumentsAt>(elements, length, checked_index); } else { EnsureArgumentsArePushedForAccess(); // Number of arguments without receiver. HInstruction* elements = function_state()->arguments_elements(); int argument_count = environment()-> arguments_environment()->parameter_count() - 1; HInstruction* length = Add<HConstant>(argument_count); HInstruction* checked_key = Add<HBoundsCheck>(index, length); result = New<HAccessArgumentsAt>(elements, length, checked_key); } return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateValueOf(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* object = Pop(); IfBuilder if_objectisvalue(this); HValue* objectisvalue = if_objectisvalue.If<HHasInstanceTypeAndBranch>( object, JS_VALUE_TYPE); if_objectisvalue.Then(); { // Return the actual value. Push(Add<HLoadNamedField>( object, objectisvalue, HObjectAccess::ForObservableJSObjectOffset( JSValue::kValueOffset))); Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_objectisvalue.Else(); { // If the object is not a value return the object. Push(object); Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_objectisvalue.End(); return ast_context()->ReturnValue(Pop()); } void HOptimizedGraphBuilder::GenerateJSValueGetValue(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = Add<HLoadNamedField>( value, nullptr, HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset)); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateDateField(CallRuntime* call) { DCHECK(call->arguments()->length() == 2); DCHECK_NOT_NULL(call->arguments()->at(1)->AsLiteral()); Smi* index = Smi::cast(*(call->arguments()->at(1)->AsLiteral()->value())); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* date = Pop(); HDateField* result = New<HDateField>(date, index); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateOneByteSeqStringSetChar( CallRuntime* call) { DCHECK(call->arguments()->length() == 3); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); CHECK_ALIVE(VisitForValue(call->arguments()->at(2))); HValue* string = Pop(); HValue* value = Pop(); HValue* index = Pop(); Add<HSeqStringSetChar>(String::ONE_BYTE_ENCODING, string, index, value); Add<HSimulate>(call->id(), FIXED_SIMULATE); return ast_context()->ReturnValue(graph()->GetConstantUndefined()); } void HOptimizedGraphBuilder::GenerateTwoByteSeqStringSetChar( CallRuntime* call) { DCHECK(call->arguments()->length() == 3); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); CHECK_ALIVE(VisitForValue(call->arguments()->at(2))); HValue* string = Pop(); HValue* value = Pop(); HValue* index = Pop(); Add<HSeqStringSetChar>(String::TWO_BYTE_ENCODING, string, index, value); Add<HSimulate>(call->id(), FIXED_SIMULATE); return ast_context()->ReturnValue(graph()->GetConstantUndefined()); } void HOptimizedGraphBuilder::GenerateSetValueOf(CallRuntime* call) { DCHECK(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* value = Pop(); HValue* object = Pop(); // Check if object is a JSValue. IfBuilder if_objectisvalue(this); if_objectisvalue.If<HHasInstanceTypeAndBranch>(object, JS_VALUE_TYPE); if_objectisvalue.Then(); { // Create in-object property store to kValueOffset. Add<HStoreNamedField>(object, HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset), value); if (!ast_context()->IsEffect()) { Push(value); } Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_objectisvalue.Else(); { // Nothing to do in this case. if (!ast_context()->IsEffect()) { Push(value); } Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_objectisvalue.End(); if (!ast_context()->IsEffect()) { Drop(1); } return ast_context()->ReturnValue(value); } // Fast support for charCodeAt(n). void HOptimizedGraphBuilder::GenerateStringCharCodeAt(CallRuntime* call) { DCHECK(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* index = Pop(); HValue* string = Pop(); HInstruction* result = BuildStringCharCodeAt(string, index); return ast_context()->ReturnInstruction(result, call->id()); } // Fast support for string.charAt(n) and string[n]. void HOptimizedGraphBuilder::GenerateStringCharFromCode(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* char_code = Pop(); HInstruction* result = NewUncasted<HStringCharFromCode>(char_code); return ast_context()->ReturnInstruction(result, call->id()); } // Fast support for string.charAt(n) and string[n]. void HOptimizedGraphBuilder::GenerateStringCharAt(CallRuntime* call) { DCHECK(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* index = Pop(); HValue* string = Pop(); HInstruction* char_code = BuildStringCharCodeAt(string, index); AddInstruction(char_code); HInstruction* result = NewUncasted<HStringCharFromCode>(char_code); return ast_context()->ReturnInstruction(result, call->id()); } // Fast support for object equality testing. void HOptimizedGraphBuilder::GenerateObjectEquals(CallRuntime* call) { DCHECK(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* right = Pop(); HValue* left = Pop(); HCompareObjectEqAndBranch* result = New<HCompareObjectEqAndBranch>(left, right); return ast_context()->ReturnControl(result, call->id()); } // Fast support for StringAdd. void HOptimizedGraphBuilder::GenerateStringAdd(CallRuntime* call) { DCHECK_EQ(2, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* right = Pop(); HValue* left = Pop(); HInstruction* result = NewUncasted<HStringAdd>(left, right); return ast_context()->ReturnInstruction(result, call->id()); } // Fast support for SubString. void HOptimizedGraphBuilder::GenerateSubString(CallRuntime* call) { DCHECK_EQ(3, call->arguments()->length()); CHECK_ALIVE(VisitExpressions(call->arguments())); PushArgumentsFromEnvironment(call->arguments()->length()); HCallStub* result = New<HCallStub>(CodeStub::SubString, 3); return ast_context()->ReturnInstruction(result, call->id()); } // Fast support for StringCompare. void HOptimizedGraphBuilder::GenerateStringCompare(CallRuntime* call) { DCHECK_EQ(2, call->arguments()->length()); CHECK_ALIVE(VisitExpressions(call->arguments())); PushArgumentsFromEnvironment(call->arguments()->length()); HCallStub* result = New<HCallStub>(CodeStub::StringCompare, 2); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateStringGetLength(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* string = Pop(); HInstruction* result = AddLoadStringLength(string); return ast_context()->ReturnInstruction(result, call->id()); } // Support for direct calls from JavaScript to native RegExp code. void HOptimizedGraphBuilder::GenerateRegExpExec(CallRuntime* call) { DCHECK_EQ(4, call->arguments()->length()); CHECK_ALIVE(VisitExpressions(call->arguments())); PushArgumentsFromEnvironment(call->arguments()->length()); HCallStub* result = New<HCallStub>(CodeStub::RegExpExec, 4); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateDoubleLo(CallRuntime* call) { DCHECK_EQ(1, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::LOW); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateDoubleHi(CallRuntime* call) { DCHECK_EQ(1, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::HIGH); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateConstructDouble(CallRuntime* call) { DCHECK_EQ(2, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* lo = Pop(); HValue* hi = Pop(); HInstruction* result = NewUncasted<HConstructDouble>(hi, lo); return ast_context()->ReturnInstruction(result, call->id()); } // Construct a RegExp exec result with two in-object properties. void HOptimizedGraphBuilder::GenerateRegExpConstructResult(CallRuntime* call) { DCHECK_EQ(3, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); CHECK_ALIVE(VisitForValue(call->arguments()->at(2))); HValue* input = Pop(); HValue* index = Pop(); HValue* length = Pop(); HValue* result = BuildRegExpConstructResult(length, index, input); return ast_context()->ReturnValue(result); } // Support for fast native caches. void HOptimizedGraphBuilder::GenerateGetFromCache(CallRuntime* call) { return Bailout(kInlinedRuntimeFunctionGetFromCache); } // Fast support for number to string. void HOptimizedGraphBuilder::GenerateNumberToString(CallRuntime* call) { DCHECK_EQ(1, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* number = Pop(); HValue* result = BuildNumberToString(number, Type::Any(zone())); return ast_context()->ReturnValue(result); } // Fast call for custom callbacks. void HOptimizedGraphBuilder::GenerateCallFunction(CallRuntime* call) { // 1 ~ The function to call is not itself an argument to the call. int arg_count = call->arguments()->length() - 1; DCHECK(arg_count >= 1); // There's always at least a receiver. CHECK_ALIVE(VisitExpressions(call->arguments())); // The function is the last argument HValue* function = Pop(); // Push the arguments to the stack PushArgumentsFromEnvironment(arg_count); IfBuilder if_is_jsfunction(this); if_is_jsfunction.If<HHasInstanceTypeAndBranch>(function, JS_FUNCTION_TYPE); if_is_jsfunction.Then(); { HInstruction* invoke_result = Add<HInvokeFunction>(function, arg_count); if (!ast_context()->IsEffect()) { Push(invoke_result); } Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_is_jsfunction.Else(); { HInstruction* call_result = Add<HCallFunction>(function, arg_count); if (!ast_context()->IsEffect()) { Push(call_result); } Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_is_jsfunction.End(); if (ast_context()->IsEffect()) { // EffectContext::ReturnValue ignores the value, so we can just pass // 'undefined' (as we do not have the call result anymore). return ast_context()->ReturnValue(graph()->GetConstantUndefined()); } else { return ast_context()->ReturnValue(Pop()); } } // Fast call to math functions. void HOptimizedGraphBuilder::GenerateMathPow(CallRuntime* call) { DCHECK_EQ(2, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* right = Pop(); HValue* left = Pop(); HInstruction* result = NewUncasted<HPower>(left, right); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateMathClz32(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathClz32); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateMathFloor(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathFloor); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateMathLogRT(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathLog); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateMathSqrt(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathSqrt); return ast_context()->ReturnInstruction(result, call->id()); } HValue* HOptimizedGraphBuilder::BuildOrderedHashTableHashToBucket( HValue* hash, HValue* num_buckets) { HValue* mask = AddUncasted<HSub>(num_buckets, graph()->GetConstant1()); mask->ChangeRepresentation(Representation::Integer32()); mask->ClearFlag(HValue::kCanOverflow); return AddUncasted<HBitwise>(Token::BIT_AND, hash, mask); } template <typename CollectionType> HValue* HOptimizedGraphBuilder::BuildOrderedHashTableHashToEntry( HValue* table, HValue* hash, HValue* num_buckets) { HValue* bucket = BuildOrderedHashTableHashToBucket(hash, num_buckets); HValue* entry_index = AddUncasted<HAdd>( bucket, Add<HConstant>(CollectionType::kHashTableStartIndex)); entry_index->ClearFlag(HValue::kCanOverflow); HValue* entry = Add<HLoadKeyed>(table, entry_index, nullptr, FAST_ELEMENTS); entry->set_type(HType::Smi()); return entry; } template <typename CollectionType> HValue* HOptimizedGraphBuilder::BuildOrderedHashTableEntryToIndex( HValue* entry, HValue* num_buckets) { HValue* index = AddUncasted<HMul>(entry, Add<HConstant>(CollectionType::kEntrySize)); index->ClearFlag(HValue::kCanOverflow); index = AddUncasted<HAdd>(index, num_buckets); index->ClearFlag(HValue::kCanOverflow); index = AddUncasted<HAdd>( index, Add<HConstant>(CollectionType::kHashTableStartIndex)); index->ClearFlag(HValue::kCanOverflow); return index; } template <typename CollectionType> HValue* HOptimizedGraphBuilder::BuildOrderedHashTableFindEntry(HValue* table, HValue* key, HValue* hash) { HValue* num_buckets = Add<HLoadNamedField>( table, nullptr, HObjectAccess::ForOrderedHashTableNumberOfBuckets<CollectionType>()); HValue* entry = BuildOrderedHashTableHashToEntry<CollectionType>(table, hash, num_buckets); Push(entry); LoopBuilder loop(this); loop.BeginBody(1); entry = Pop(); { IfBuilder if_not_found(this); if_not_found.If<HCompareNumericAndBranch>( entry, Add<HConstant>(CollectionType::kNotFound), Token::EQ); if_not_found.Then(); Push(entry); loop.Break(); } HValue* key_index = BuildOrderedHashTableEntryToIndex<CollectionType>(entry, num_buckets); HValue* candidate_key = Add<HLoadKeyed>(table, key_index, nullptr, FAST_ELEMENTS); { IfBuilder if_keys_equal(this); if_keys_equal.If<HIsStringAndBranch>(candidate_key); if_keys_equal.AndIf<HStringCompareAndBranch>(candidate_key, key, Token::EQ_STRICT); if_keys_equal.Then(); Push(key_index); loop.Break(); } // BuildChainAt HValue* chain_index = AddUncasted<HAdd>( key_index, Add<HConstant>(CollectionType::kChainOffset)); chain_index->ClearFlag(HValue::kCanOverflow); entry = Add<HLoadKeyed>(table, chain_index, nullptr, FAST_ELEMENTS); entry->set_type(HType::Smi()); Push(entry); loop.EndBody(); return Pop(); } void HOptimizedGraphBuilder::GenerateMapGet(CallRuntime* call) { DCHECK(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* key = Pop(); HValue* receiver = Pop(); NoObservableSideEffectsScope no_effects(this); HIfContinuation continuation; HValue* hash = BuildStringHashLoadIfIsStringAndHashComputed(key, &continuation); { IfBuilder string_checker(this, &continuation); string_checker.Then(); { HValue* table = Add<HLoadNamedField>( receiver, nullptr, HObjectAccess::ForJSCollectionTable()); HValue* key_index = BuildOrderedHashTableFindEntry<OrderedHashMap>(table, key, hash); IfBuilder if_found(this); if_found.If<HCompareNumericAndBranch>( key_index, Add<HConstant>(OrderedHashMap::kNotFound), Token::NE); if_found.Then(); { HValue* value_index = AddUncasted<HAdd>( key_index, Add<HConstant>(OrderedHashMap::kValueOffset)); value_index->ClearFlag(HValue::kCanOverflow); Push(Add<HLoadKeyed>(table, value_index, nullptr, FAST_ELEMENTS)); } if_found.Else(); Push(graph()->GetConstantUndefined()); if_found.End(); } string_checker.Else(); { Add<HPushArguments>(receiver, key); Push(Add<HCallRuntime>(call->name(), Runtime::FunctionForId(Runtime::kMapGet), 2)); } } return ast_context()->ReturnValue(Pop()); } HValue* HOptimizedGraphBuilder::BuildStringHashLoadIfIsStringAndHashComputed( HValue* object, HIfContinuation* continuation) { IfBuilder string_checker(this); string_checker.If<HIsStringAndBranch>(object); string_checker.And(); HValue* hash = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForStringHashField()); HValue* hash_not_computed_mask = Add<HConstant>(String::kHashNotComputedMask); HValue* hash_computed_test = AddUncasted<HBitwise>(Token::BIT_AND, hash, hash_not_computed_mask); string_checker.If<HCompareNumericAndBranch>( hash_computed_test, graph()->GetConstant0(), Token::EQ); string_checker.Then(); HValue* shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(String::kHashShift)); string_checker.CaptureContinuation(continuation); return shifted_hash; } template <typename CollectionType> void HOptimizedGraphBuilder::BuildJSCollectionHas( CallRuntime* call, const Runtime::Function* c_function) { DCHECK(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* key = Pop(); HValue* receiver = Pop(); NoObservableSideEffectsScope no_effects(this); HIfContinuation continuation; HValue* hash = BuildStringHashLoadIfIsStringAndHashComputed(key, &continuation); { IfBuilder string_checker(this, &continuation); string_checker.Then(); { HValue* table = Add<HLoadNamedField>( receiver, nullptr, HObjectAccess::ForJSCollectionTable()); HValue* key_index = BuildOrderedHashTableFindEntry<CollectionType>(table, key, hash); { IfBuilder if_found(this); if_found.If<HCompareNumericAndBranch>( key_index, Add<HConstant>(CollectionType::kNotFound), Token::NE); if_found.Then(); Push(graph()->GetConstantTrue()); if_found.Else(); Push(graph()->GetConstantFalse()); } } string_checker.Else(); { Add<HPushArguments>(receiver, key); Push(Add<HCallRuntime>(call->name(), c_function, 2)); } } return ast_context()->ReturnValue(Pop()); } void HOptimizedGraphBuilder::GenerateMapHas(CallRuntime* call) { BuildJSCollectionHas<OrderedHashMap>( call, Runtime::FunctionForId(Runtime::kMapHas)); } void HOptimizedGraphBuilder::GenerateSetHas(CallRuntime* call) { BuildJSCollectionHas<OrderedHashSet>( call, Runtime::FunctionForId(Runtime::kSetHas)); } template <typename CollectionType> HValue* HOptimizedGraphBuilder::BuildOrderedHashTableAddEntry( HValue* table, HValue* key, HValue* hash, HIfContinuation* join_continuation) { HValue* num_buckets = Add<HLoadNamedField>( table, nullptr, HObjectAccess::ForOrderedHashTableNumberOfBuckets<CollectionType>()); HValue* capacity = AddUncasted<HMul>( num_buckets, Add<HConstant>(CollectionType::kLoadFactor)); capacity->ClearFlag(HValue::kCanOverflow); HValue* num_elements = Add<HLoadNamedField>( table, nullptr, HObjectAccess::ForOrderedHashTableNumberOfElements<CollectionType>()); HValue* num_deleted = Add<HLoadNamedField>( table, nullptr, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements< CollectionType>()); HValue* used = AddUncasted<HAdd>(num_elements, num_deleted); used->ClearFlag(HValue::kCanOverflow); IfBuilder if_space_available(this); if_space_available.If<HCompareNumericAndBranch>(capacity, used, Token::GT); if_space_available.Then(); HValue* bucket = BuildOrderedHashTableHashToBucket(hash, num_buckets); HValue* entry = used; HValue* key_index = BuildOrderedHashTableEntryToIndex<CollectionType>(entry, num_buckets); HValue* bucket_index = AddUncasted<HAdd>( bucket, Add<HConstant>(CollectionType::kHashTableStartIndex)); bucket_index->ClearFlag(HValue::kCanOverflow); HValue* chain_entry = Add<HLoadKeyed>(table, bucket_index, nullptr, FAST_ELEMENTS); chain_entry->set_type(HType::Smi()); HValue* chain_index = AddUncasted<HAdd>( key_index, Add<HConstant>(CollectionType::kChainOffset)); chain_index->ClearFlag(HValue::kCanOverflow); Add<HStoreKeyed>(table, bucket_index, entry, FAST_ELEMENTS); Add<HStoreKeyed>(table, chain_index, chain_entry, FAST_ELEMENTS); Add<HStoreKeyed>(table, key_index, key, FAST_ELEMENTS); HValue* new_num_elements = AddUncasted<HAdd>(num_elements, graph()->GetConstant1()); new_num_elements->ClearFlag(HValue::kCanOverflow); Add<HStoreNamedField>( table, HObjectAccess::ForOrderedHashTableNumberOfElements<CollectionType>(), new_num_elements); if_space_available.JoinContinuation(join_continuation); return key_index; } void HOptimizedGraphBuilder::GenerateMapSet(CallRuntime* call) { DCHECK(call->arguments()->length() == 3); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); CHECK_ALIVE(VisitForValue(call->arguments()->at(2))); HValue* value = Pop(); HValue* key = Pop(); HValue* receiver = Pop(); NoObservableSideEffectsScope no_effects(this); HIfContinuation return_or_call_runtime_continuation( graph()->CreateBasicBlock(), graph()->CreateBasicBlock()); HIfContinuation got_string_hash; HValue* hash = BuildStringHashLoadIfIsStringAndHashComputed(key, &got_string_hash); IfBuilder string_checker(this, &got_string_hash); string_checker.Then(); { HValue* table = Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForJSCollectionTable()); HValue* key_index = BuildOrderedHashTableFindEntry<OrderedHashMap>(table, key, hash); { IfBuilder if_found(this); if_found.If<HCompareNumericAndBranch>( key_index, Add<HConstant>(OrderedHashMap::kNotFound), Token::NE); if_found.Then(); { HValue* value_index = AddUncasted<HAdd>( key_index, Add<HConstant>(OrderedHashMap::kValueOffset)); value_index->ClearFlag(HValue::kCanOverflow); Add<HStoreKeyed>(table, value_index, value, FAST_ELEMENTS); } if_found.Else(); { HIfContinuation did_add(graph()->CreateBasicBlock(), graph()->CreateBasicBlock()); HValue* key_index = BuildOrderedHashTableAddEntry<OrderedHashMap>( table, key, hash, &did_add); IfBuilder if_did_add(this, &did_add); if_did_add.Then(); { HValue* value_index = AddUncasted<HAdd>( key_index, Add<HConstant>(OrderedHashMap::kValueOffset)); value_index->ClearFlag(HValue::kCanOverflow); Add<HStoreKeyed>(table, value_index, value, FAST_ELEMENTS); } if_did_add.JoinContinuation(&return_or_call_runtime_continuation); } } } string_checker.JoinContinuation(&return_or_call_runtime_continuation); { IfBuilder return_or_call_runtime(this, &return_or_call_runtime_continuation); return_or_call_runtime.Then(); Push(receiver); return_or_call_runtime.Else(); Add<HPushArguments>(receiver, key, value); Push(Add<HCallRuntime>(call->name(), Runtime::FunctionForId(Runtime::kMapSet), 3)); } return ast_context()->ReturnValue(Pop()); } void HOptimizedGraphBuilder::GenerateSetAdd(CallRuntime* call) { DCHECK(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* key = Pop(); HValue* receiver = Pop(); NoObservableSideEffectsScope no_effects(this); HIfContinuation return_or_call_runtime_continuation( graph()->CreateBasicBlock(), graph()->CreateBasicBlock()); HIfContinuation got_string_hash; HValue* hash = BuildStringHashLoadIfIsStringAndHashComputed(key, &got_string_hash); IfBuilder string_checker(this, &got_string_hash); string_checker.Then(); { HValue* table = Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForJSCollectionTable()); HValue* key_index = BuildOrderedHashTableFindEntry<OrderedHashSet>(table, key, hash); { IfBuilder if_not_found(this); if_not_found.If<HCompareNumericAndBranch>( key_index, Add<HConstant>(OrderedHashSet::kNotFound), Token::EQ); if_not_found.Then(); BuildOrderedHashTableAddEntry<OrderedHashSet>( table, key, hash, &return_or_call_runtime_continuation); } } string_checker.JoinContinuation(&return_or_call_runtime_continuation); { IfBuilder return_or_call_runtime(this, &return_or_call_runtime_continuation); return_or_call_runtime.Then(); Push(receiver); return_or_call_runtime.Else(); Add<HPushArguments>(receiver, key); Push(Add<HCallRuntime>(call->name(), Runtime::FunctionForId(Runtime::kSetAdd), 2)); } return ast_context()->ReturnValue(Pop()); } template <typename CollectionType> void HOptimizedGraphBuilder::BuildJSCollectionDelete( CallRuntime* call, const Runtime::Function* c_function) { DCHECK(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* key = Pop(); HValue* receiver = Pop(); NoObservableSideEffectsScope no_effects(this); HIfContinuation return_or_call_runtime_continuation( graph()->CreateBasicBlock(), graph()->CreateBasicBlock()); HIfContinuation got_string_hash; HValue* hash = BuildStringHashLoadIfIsStringAndHashComputed(key, &got_string_hash); IfBuilder string_checker(this, &got_string_hash); string_checker.Then(); { HValue* table = Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForJSCollectionTable()); HValue* key_index = BuildOrderedHashTableFindEntry<CollectionType>(table, key, hash); { IfBuilder if_found(this); if_found.If<HCompareNumericAndBranch>( key_index, Add<HConstant>(CollectionType::kNotFound), Token::NE); if_found.Then(); { // If we're removing an element, we might need to shrink. // If we do need to shrink, we'll be bailing out to the runtime. HValue* num_elements = Add<HLoadNamedField>( table, nullptr, HObjectAccess::ForOrderedHashTableNumberOfElements< CollectionType>()); num_elements = AddUncasted<HSub>(num_elements, graph()->GetConstant1()); num_elements->ClearFlag(HValue::kCanOverflow); HValue* num_buckets = Add<HLoadNamedField>( table, nullptr, HObjectAccess::ForOrderedHashTableNumberOfBuckets< CollectionType>()); // threshold is capacity >> 2; we simplify this to num_buckets >> 1 // since kLoadFactor is 2. STATIC_ASSERT(CollectionType::kLoadFactor == 2); HValue* threshold = AddUncasted<HShr>(num_buckets, graph()->GetConstant1()); IfBuilder if_need_not_shrink(this); if_need_not_shrink.If<HCompareNumericAndBranch>(num_elements, threshold, Token::GTE); if_need_not_shrink.Then(); { Add<HStoreKeyed>(table, key_index, graph()->GetConstantHole(), FAST_ELEMENTS); // For maps, also need to clear the value. if (CollectionType::kChainOffset > 1) { HValue* value_index = AddUncasted<HAdd>(key_index, graph()->GetConstant1()); value_index->ClearFlag(HValue::kCanOverflow); Add<HStoreKeyed>(table, value_index, graph()->GetConstantHole(), FAST_ELEMENTS); } STATIC_ASSERT(CollectionType::kChainOffset <= 2); HValue* num_deleted = Add<HLoadNamedField>( table, nullptr, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements< CollectionType>()); num_deleted = AddUncasted<HAdd>(num_deleted, graph()->GetConstant1()); num_deleted->ClearFlag(HValue::kCanOverflow); Add<HStoreNamedField>( table, HObjectAccess::ForOrderedHashTableNumberOfElements< CollectionType>(), num_elements); Add<HStoreNamedField>( table, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements< CollectionType>(), num_deleted); Push(graph()->GetConstantTrue()); } if_need_not_shrink.JoinContinuation( &return_or_call_runtime_continuation); } if_found.Else(); { // Not found, so we're done. Push(graph()->GetConstantFalse()); } } } string_checker.JoinContinuation(&return_or_call_runtime_continuation); { IfBuilder return_or_call_runtime(this, &return_or_call_runtime_continuation); return_or_call_runtime.Then(); return_or_call_runtime.Else(); Add<HPushArguments>(receiver, key); Push(Add<HCallRuntime>(call->name(), c_function, 2)); } return ast_context()->ReturnValue(Pop()); } void HOptimizedGraphBuilder::GenerateMapDelete(CallRuntime* call) { BuildJSCollectionDelete<OrderedHashMap>( call, Runtime::FunctionForId(Runtime::kMapDelete)); } void HOptimizedGraphBuilder::GenerateSetDelete(CallRuntime* call) { BuildJSCollectionDelete<OrderedHashSet>( call, Runtime::FunctionForId(Runtime::kSetDelete)); } void HOptimizedGraphBuilder::GenerateSetGetSize(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* receiver = Pop(); HValue* table = Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForJSCollectionTable()); HInstruction* result = New<HLoadNamedField>( table, nullptr, HObjectAccess::ForOrderedHashTableNumberOfElements<OrderedHashSet>()); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateMapGetSize(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* receiver = Pop(); HValue* table = Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForJSCollectionTable()); HInstruction* result = New<HLoadNamedField>( table, nullptr, HObjectAccess::ForOrderedHashTableNumberOfElements<OrderedHashMap>()); return ast_context()->ReturnInstruction(result, call->id()); } template <typename CollectionType> HValue* HOptimizedGraphBuilder::BuildAllocateOrderedHashTable() { static const int kCapacity = CollectionType::kMinCapacity; static const int kBucketCount = kCapacity / CollectionType::kLoadFactor; static const int kFixedArrayLength = CollectionType::kHashTableStartIndex + kBucketCount + (kCapacity * CollectionType::kEntrySize); static const int kSizeInBytes = FixedArray::kHeaderSize + (kFixedArrayLength * kPointerSize); // Allocate the table and add the proper map. HValue* table = Add<HAllocate>(Add<HConstant>(kSizeInBytes), HType::HeapObject(), NOT_TENURED, FIXED_ARRAY_TYPE); AddStoreMapConstant(table, isolate()->factory()->ordered_hash_table_map()); // Initialize the FixedArray... HValue* length = Add<HConstant>(kFixedArrayLength); Add<HStoreNamedField>(table, HObjectAccess::ForFixedArrayLength(), length); // ...and the OrderedHashTable fields. Add<HStoreNamedField>( table, HObjectAccess::ForOrderedHashTableNumberOfBuckets<CollectionType>(), Add<HConstant>(kBucketCount)); Add<HStoreNamedField>( table, HObjectAccess::ForOrderedHashTableNumberOfElements<CollectionType>(), graph()->GetConstant0()); Add<HStoreNamedField>( table, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements< CollectionType>(), graph()->GetConstant0()); // Fill the buckets with kNotFound. HValue* not_found = Add<HConstant>(CollectionType::kNotFound); for (int i = 0; i < kBucketCount; ++i) { Add<HStoreNamedField>( table, HObjectAccess::ForOrderedHashTableBucket<CollectionType>(i), not_found); } // Fill the data table with undefined. HValue* undefined = graph()->GetConstantUndefined(); for (int i = 0; i < (kCapacity * CollectionType::kEntrySize); ++i) { Add<HStoreNamedField>(table, HObjectAccess::ForOrderedHashTableDataTableIndex< CollectionType, kBucketCount>(i), undefined); } return table; } void HOptimizedGraphBuilder::GenerateSetInitialize(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* receiver = Pop(); NoObservableSideEffectsScope no_effects(this); HValue* table = BuildAllocateOrderedHashTable<OrderedHashSet>(); Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(), table); return ast_context()->ReturnValue(receiver); } void HOptimizedGraphBuilder::GenerateMapInitialize(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* receiver = Pop(); NoObservableSideEffectsScope no_effects(this); HValue* table = BuildAllocateOrderedHashTable<OrderedHashMap>(); Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(), table); return ast_context()->ReturnValue(receiver); } template <typename CollectionType> void HOptimizedGraphBuilder::BuildOrderedHashTableClear(HValue* receiver) { HValue* old_table = Add<HLoadNamedField>( receiver, nullptr, HObjectAccess::ForJSCollectionTable()); HValue* new_table = BuildAllocateOrderedHashTable<CollectionType>(); Add<HStoreNamedField>( old_table, HObjectAccess::ForOrderedHashTableNextTable<CollectionType>(), new_table); Add<HStoreNamedField>( old_table, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements< CollectionType>(), Add<HConstant>(CollectionType::kClearedTableSentinel)); Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(), new_table); } void HOptimizedGraphBuilder::GenerateSetClear(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* receiver = Pop(); NoObservableSideEffectsScope no_effects(this); BuildOrderedHashTableClear<OrderedHashSet>(receiver); return ast_context()->ReturnValue(graph()->GetConstantUndefined()); } void HOptimizedGraphBuilder::GenerateMapClear(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* receiver = Pop(); NoObservableSideEffectsScope no_effects(this); BuildOrderedHashTableClear<OrderedHashMap>(receiver); return ast_context()->ReturnValue(graph()->GetConstantUndefined()); } void HOptimizedGraphBuilder::GenerateGetCachedArrayIndex(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HGetCachedArrayIndex* result = New<HGetCachedArrayIndex>(value); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateFastOneByteArrayJoin(CallRuntime* call) { // Simply returning undefined here would be semantically correct and even // avoid the bailout. Nevertheless, some ancient benchmarks like SunSpider's // string-fasta would tank, because fullcode contains an optimized version. // Obviously the fullcode => Crankshaft => bailout => fullcode dance is // faster... *sigh* return Bailout(kInlinedRuntimeFunctionFastOneByteArrayJoin); } void HOptimizedGraphBuilder::GenerateDebugBreakInOptimizedCode( CallRuntime* call) { Add<HDebugBreak>(); return ast_context()->ReturnValue(graph()->GetConstant0()); } void HOptimizedGraphBuilder::GenerateDebugIsActive(CallRuntime* call) { DCHECK(call->arguments()->length() == 0); HValue* ref = Add<HConstant>(ExternalReference::debug_is_active_address(isolate())); HValue* value = Add<HLoadNamedField>(ref, nullptr, HObjectAccess::ForExternalUInteger8()); return ast_context()->ReturnValue(value); } void HOptimizedGraphBuilder::GenerateGetPrototype(CallRuntime* call) { DCHECK(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* object = Pop(); NoObservableSideEffectsScope no_effects(this); HValue* map = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMap()); HValue* bit_field = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField()); HValue* is_access_check_needed_mask = Add<HConstant>(1 << Map::kIsAccessCheckNeeded); HValue* is_access_check_needed_test = AddUncasted<HBitwise>( Token::BIT_AND, bit_field, is_access_check_needed_mask); HValue* proto = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForPrototype()); HValue* proto_map = Add<HLoadNamedField>(proto, nullptr, HObjectAccess::ForMap()); HValue* proto_bit_field = Add<HLoadNamedField>(proto_map, nullptr, HObjectAccess::ForMapBitField()); HValue* is_hidden_prototype_mask = Add<HConstant>(1 << Map::kIsHiddenPrototype); HValue* is_hidden_prototype_test = AddUncasted<HBitwise>( Token::BIT_AND, proto_bit_field, is_hidden_prototype_mask); { IfBuilder needs_runtime(this); needs_runtime.If<HCompareNumericAndBranch>( is_access_check_needed_test, graph()->GetConstant0(), Token::NE); needs_runtime.OrIf<HCompareNumericAndBranch>( is_hidden_prototype_test, graph()->GetConstant0(), Token::NE); needs_runtime.Then(); { Add<HPushArguments>(object); Push(Add<HCallRuntime>( call->name(), Runtime::FunctionForId(Runtime::kGetPrototype), 1)); } needs_runtime.Else(); Push(proto); } return ast_context()->ReturnValue(Pop()); } #undef CHECK_BAILOUT #undef CHECK_ALIVE HEnvironment::HEnvironment(HEnvironment* outer, Scope* scope, Handle<JSFunction> closure, Zone* zone) : closure_(closure), values_(0, zone), frame_type_(JS_FUNCTION), parameter_count_(0), specials_count_(1), local_count_(0), outer_(outer), entry_(NULL), pop_count_(0), push_count_(0), ast_id_(BailoutId::None()), zone_(zone) { Scope* declaration_scope = scope->DeclarationScope(); Initialize(declaration_scope->num_parameters() + 1, declaration_scope->num_stack_slots(), 0); } HEnvironment::HEnvironment(Zone* zone, int parameter_count) : values_(0, zone), frame_type_(STUB), parameter_count_(parameter_count), specials_count_(1), local_count_(0), outer_(NULL), entry_(NULL), pop_count_(0), push_count_(0), ast_id_(BailoutId::None()), zone_(zone) { Initialize(parameter_count, 0, 0); } HEnvironment::HEnvironment(const HEnvironment* other, Zone* zone) : values_(0, zone), frame_type_(JS_FUNCTION), parameter_count_(0), specials_count_(0), local_count_(0), outer_(NULL), entry_(NULL), pop_count_(0), push_count_(0), ast_id_(other->ast_id()), zone_(zone) { Initialize(other); } HEnvironment::HEnvironment(HEnvironment* outer, Handle<JSFunction> closure, FrameType frame_type, int arguments, Zone* zone) : closure_(closure), values_(arguments, zone), frame_type_(frame_type), parameter_count_(arguments), specials_count_(0), local_count_(0), outer_(outer), entry_(NULL), pop_count_(0), push_count_(0), ast_id_(BailoutId::None()), zone_(zone) { } void HEnvironment::Initialize(int parameter_count, int local_count, int stack_height) { parameter_count_ = parameter_count; local_count_ = local_count; // Avoid reallocating the temporaries' backing store on the first Push. int total = parameter_count + specials_count_ + local_count + stack_height; values_.Initialize(total + 4, zone()); for (int i = 0; i < total; ++i) values_.Add(NULL, zone()); } void HEnvironment::Initialize(const HEnvironment* other) { closure_ = other->closure(); values_.AddAll(other->values_, zone()); assigned_variables_.Union(other->assigned_variables_, zone()); frame_type_ = other->frame_type_; parameter_count_ = other->parameter_count_; local_count_ = other->local_count_; if (other->outer_ != NULL) outer_ = other->outer_->Copy(); // Deep copy. entry_ = other->entry_; pop_count_ = other->pop_count_; push_count_ = other->push_count_; specials_count_ = other->specials_count_; ast_id_ = other->ast_id_; } void HEnvironment::AddIncomingEdge(HBasicBlock* block, HEnvironment* other) { DCHECK(!block->IsLoopHeader()); DCHECK(values_.length() == other->values_.length()); int length = values_.length(); for (int i = 0; i < length; ++i) { HValue* value = values_[i]; if (value != NULL && value->IsPhi() && value->block() == block) { // There is already a phi for the i'th value. HPhi* phi = HPhi::cast(value); // Assert index is correct and that we haven't missed an incoming edge. DCHECK(phi->merged_index() == i || !phi->HasMergedIndex()); DCHECK(phi->OperandCount() == block->predecessors()->length()); phi->AddInput(other->values_[i]); } else if (values_[i] != other->values_[i]) { // There is a fresh value on the incoming edge, a phi is needed. DCHECK(values_[i] != NULL && other->values_[i] != NULL); HPhi* phi = block->AddNewPhi(i); HValue* old_value = values_[i]; for (int j = 0; j < block->predecessors()->length(); j++) { phi->AddInput(old_value); } phi->AddInput(other->values_[i]); this->values_[i] = phi; } } } void HEnvironment::Bind(int index, HValue* value) { DCHECK(value != NULL); assigned_variables_.Add(index, zone()); values_[index] = value; } bool HEnvironment::HasExpressionAt(int index) const { return index >= parameter_count_ + specials_count_ + local_count_; } bool HEnvironment::ExpressionStackIsEmpty() const { DCHECK(length() >= first_expression_index()); return length() == first_expression_index(); } void HEnvironment::SetExpressionStackAt(int index_from_top, HValue* value) { int count = index_from_top + 1; int index = values_.length() - count; DCHECK(HasExpressionAt(index)); // The push count must include at least the element in question or else // the new value will not be included in this environment's history. if (push_count_ < count) { // This is the same effect as popping then re-pushing 'count' elements. pop_count_ += (count - push_count_); push_count_ = count; } values_[index] = value; } HValue* HEnvironment::RemoveExpressionStackAt(int index_from_top) { int count = index_from_top + 1; int index = values_.length() - count; DCHECK(HasExpressionAt(index)); // Simulate popping 'count' elements and then // pushing 'count - 1' elements back. pop_count_ += Max(count - push_count_, 0); push_count_ = Max(push_count_ - count, 0) + (count - 1); return values_.Remove(index); } void HEnvironment::Drop(int count) { for (int i = 0; i < count; ++i) { Pop(); } } HEnvironment* HEnvironment::Copy() const { return new(zone()) HEnvironment(this, zone()); } HEnvironment* HEnvironment::CopyWithoutHistory() const { HEnvironment* result = Copy(); result->ClearHistory(); return result; } HEnvironment* HEnvironment::CopyAsLoopHeader(HBasicBlock* loop_header) const { HEnvironment* new_env = Copy(); for (int i = 0; i < values_.length(); ++i) { HPhi* phi = loop_header->AddNewPhi(i); phi->AddInput(values_[i]); new_env->values_[i] = phi; } new_env->ClearHistory(); return new_env; } HEnvironment* HEnvironment::CreateStubEnvironment(HEnvironment* outer, Handle<JSFunction> target, FrameType frame_type, int arguments) const { HEnvironment* new_env = new(zone()) HEnvironment(outer, target, frame_type, arguments + 1, zone()); for (int i = 0; i <= arguments; ++i) { // Include receiver. new_env->Push(ExpressionStackAt(arguments - i)); } new_env->ClearHistory(); return new_env; } HEnvironment* HEnvironment::CopyForInlining( Handle<JSFunction> target, int arguments, FunctionLiteral* function, HConstant* undefined, InliningKind inlining_kind) const { DCHECK(frame_type() == JS_FUNCTION); // Outer environment is a copy of this one without the arguments. int arity = function->scope()->num_parameters(); HEnvironment* outer = Copy(); outer->Drop(arguments + 1); // Including receiver. outer->ClearHistory(); if (inlining_kind == CONSTRUCT_CALL_RETURN) { // Create artificial constructor stub environment. The receiver should // actually be the constructor function, but we pass the newly allocated // object instead, DoComputeConstructStubFrame() relies on that. outer = CreateStubEnvironment(outer, target, JS_CONSTRUCT, arguments); } else if (inlining_kind == GETTER_CALL_RETURN) { // We need an additional StackFrame::INTERNAL frame for restoring the // correct context. outer = CreateStubEnvironment(outer, target, JS_GETTER, arguments); } else if (inlining_kind == SETTER_CALL_RETURN) { // We need an additional StackFrame::INTERNAL frame for temporarily saving // the argument of the setter, see StoreStubCompiler::CompileStoreViaSetter. outer = CreateStubEnvironment(outer, target, JS_SETTER, arguments); } if (arity != arguments) { // Create artificial arguments adaptation environment. outer = CreateStubEnvironment(outer, target, ARGUMENTS_ADAPTOR, arguments); } HEnvironment* inner = new(zone()) HEnvironment(outer, function->scope(), target, zone()); // Get the argument values from the original environment. for (int i = 0; i <= arity; ++i) { // Include receiver. HValue* push = (i <= arguments) ? ExpressionStackAt(arguments - i) : undefined; inner->SetValueAt(i, push); } inner->SetValueAt(arity + 1, context()); for (int i = arity + 2; i < inner->length(); ++i) { inner->SetValueAt(i, undefined); } inner->set_ast_id(BailoutId::FunctionEntry()); return inner; } std::ostream& operator<<(std::ostream& os, const HEnvironment& env) { for (int i = 0; i < env.length(); i++) { if (i == 0) os << "parameters\n"; if (i == env.parameter_count()) os << "specials\n"; if (i == env.parameter_count() + env.specials_count()) os << "locals\n"; if (i == env.parameter_count() + env.specials_count() + env.local_count()) { os << "expressions\n"; } HValue* val = env.values()->at(i); os << i << ": "; if (val != NULL) { os << val; } else { os << "NULL"; } os << "\n"; } return os << "\n"; } void HTracer::TraceCompilation(CompilationInfo* info) { Tag tag(this, "compilation"); if (info->IsOptimizing()) { Handle<String> name = info->function()->debug_name(); PrintStringProperty("name", name->ToCString().get()); PrintIndent(); trace_.Add("method \"%s:%d\"\n", name->ToCString().get(), info->optimization_id()); } else { CodeStub::Major major_key = info->code_stub()->MajorKey(); PrintStringProperty("name", CodeStub::MajorName(major_key, false)); PrintStringProperty("method", "stub"); } PrintLongProperty("date", static_cast<int64_t>(base::OS::TimeCurrentMillis())); } void HTracer::TraceLithium(const char* name, LChunk* chunk) { DCHECK(!chunk->isolate()->concurrent_recompilation_enabled()); AllowHandleDereference allow_deref; AllowDeferredHandleDereference allow_deferred_deref; Trace(name, chunk->graph(), chunk); } void HTracer::TraceHydrogen(const char* name, HGraph* graph) { DCHECK(!graph->isolate()->concurrent_recompilation_enabled()); AllowHandleDereference allow_deref; AllowDeferredHandleDereference allow_deferred_deref; Trace(name, graph, NULL); } void HTracer::Trace(const char* name, HGraph* graph, LChunk* chunk) { Tag tag(this, "cfg"); PrintStringProperty("name", name); const ZoneList<HBasicBlock*>* blocks = graph->blocks(); for (int i = 0; i < blocks->length(); i++) { HBasicBlock* current = blocks->at(i); Tag block_tag(this, "block"); PrintBlockProperty("name", current->block_id()); PrintIntProperty("from_bci", -1); PrintIntProperty("to_bci", -1); if (!current->predecessors()->is_empty()) { PrintIndent(); trace_.Add("predecessors"); for (int j = 0; j < current->predecessors()->length(); ++j) { trace_.Add(" \"B%d\"", current->predecessors()->at(j)->block_id()); } trace_.Add("\n"); } else { PrintEmptyProperty("predecessors"); } if (current->end()->SuccessorCount() == 0) { PrintEmptyProperty("successors"); } else { PrintIndent(); trace_.Add("successors"); for (HSuccessorIterator it(current->end()); !it.Done(); it.Advance()) { trace_.Add(" \"B%d\"", it.Current()->block_id()); } trace_.Add("\n"); } PrintEmptyProperty("xhandlers"); { PrintIndent(); trace_.Add("flags"); if (current->IsLoopSuccessorDominator()) { trace_.Add(" \"dom-loop-succ\""); } if (current->IsUnreachable()) { trace_.Add(" \"dead\""); } if (current->is_osr_entry()) { trace_.Add(" \"osr\""); } trace_.Add("\n"); } if (current->dominator() != NULL) { PrintBlockProperty("dominator", current->dominator()->block_id()); } PrintIntProperty("loop_depth", current->LoopNestingDepth()); if (chunk != NULL) { int first_index = current->first_instruction_index(); int last_index = current->last_instruction_index(); PrintIntProperty( "first_lir_id", LifetimePosition::FromInstructionIndex(first_index).Value()); PrintIntProperty( "last_lir_id", LifetimePosition::FromInstructionIndex(last_index).Value()); } { Tag states_tag(this, "states"); Tag locals_tag(this, "locals"); int total = current->phis()->length(); PrintIntProperty("size", current->phis()->length()); PrintStringProperty("method", "None"); for (int j = 0; j < total; ++j) { HPhi* phi = current->phis()->at(j); PrintIndent(); std::ostringstream os; os << phi->merged_index() << " " << NameOf(phi) << " " << *phi << "\n"; trace_.Add(os.str().c_str()); } } { Tag HIR_tag(this, "HIR"); for (HInstructionIterator it(current); !it.Done(); it.Advance()) { HInstruction* instruction = it.Current(); int uses = instruction->UseCount(); PrintIndent(); std::ostringstream os; os << "0 " << uses << " " << NameOf(instruction) << " " << *instruction; if (graph->info()->is_tracking_positions() && instruction->has_position() && instruction->position().raw() != 0) { const SourcePosition pos = instruction->position(); os << " pos:"; if (pos.inlining_id() != 0) os << pos.inlining_id() << "_"; os << pos.position(); } os << " <|@\n"; trace_.Add(os.str().c_str()); } } if (chunk != NULL) { Tag LIR_tag(this, "LIR"); int first_index = current->first_instruction_index(); int last_index = current->last_instruction_index(); if (first_index != -1 && last_index != -1) { const ZoneList<LInstruction*>* instructions = chunk->instructions(); for (int i = first_index; i <= last_index; ++i) { LInstruction* linstr = instructions->at(i); if (linstr != NULL) { PrintIndent(); trace_.Add("%d ", LifetimePosition::FromInstructionIndex(i).Value()); linstr->PrintTo(&trace_); std::ostringstream os; os << " [hir:" << NameOf(linstr->hydrogen_value()) << "] <|@\n"; trace_.Add(os.str().c_str()); } } } } } } void HTracer::TraceLiveRanges(const char* name, LAllocator* allocator) { Tag tag(this, "intervals"); PrintStringProperty("name", name); const Vector<LiveRange*>* fixed_d = allocator->fixed_double_live_ranges(); for (int i = 0; i < fixed_d->length(); ++i) { TraceLiveRange(fixed_d->at(i), "fixed", allocator->zone()); } const Vector<LiveRange*>* fixed = allocator->fixed_live_ranges(); for (int i = 0; i < fixed->length(); ++i) { TraceLiveRange(fixed->at(i), "fixed", allocator->zone()); } const ZoneList<LiveRange*>* live_ranges = allocator->live_ranges(); for (int i = 0; i < live_ranges->length(); ++i) { TraceLiveRange(live_ranges->at(i), "object", allocator->zone()); } } void HTracer::TraceLiveRange(LiveRange* range, const char* type, Zone* zone) { if (range != NULL && !range->IsEmpty()) { PrintIndent(); trace_.Add("%d %s", range->id(), type); if (range->HasRegisterAssigned()) { LOperand* op = range->CreateAssignedOperand(zone); int assigned_reg = op->index(); if (op->IsDoubleRegister()) { trace_.Add(" \"%s\"", DoubleRegister::AllocationIndexToString(assigned_reg)); } else { DCHECK(op->IsRegister()); trace_.Add(" \"%s\"", Register::AllocationIndexToString(assigned_reg)); } } else if (range->IsSpilled()) { LOperand* op = range->TopLevel()->GetSpillOperand(); if (op->IsDoubleStackSlot()) { trace_.Add(" \"double_stack:%d\"", op->index()); } else { DCHECK(op->IsStackSlot()); trace_.Add(" \"stack:%d\"", op->index()); } } int parent_index = -1; if (range->IsChild()) { parent_index = range->parent()->id(); } else { parent_index = range->id(); } LOperand* op = range->FirstHint(); int hint_index = -1; if (op != NULL && op->IsUnallocated()) { hint_index = LUnallocated::cast(op)->virtual_register(); } trace_.Add(" %d %d", parent_index, hint_index); UseInterval* cur_interval = range->first_interval(); while (cur_interval != NULL && range->Covers(cur_interval->start())) { trace_.Add(" [%d, %d[", cur_interval->start().Value(), cur_interval->end().Value()); cur_interval = cur_interval->next(); } UsePosition* current_pos = range->first_pos(); while (current_pos != NULL) { if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) { trace_.Add(" %d M", current_pos->pos().Value()); } current_pos = current_pos->next(); } trace_.Add(" \"\"\n"); } } void HTracer::FlushToFile() { AppendChars(filename_.start(), trace_.ToCString().get(), trace_.length(), false); trace_.Reset(); } void HStatistics::Initialize(CompilationInfo* info) { if (info->shared_info().is_null()) return; source_size_ += info->shared_info()->SourceSize(); } void HStatistics::Print() { PrintF( "\n" "----------------------------------------" "----------------------------------------\n" "--- Hydrogen timing results:\n" "----------------------------------------" "----------------------------------------\n"); base::TimeDelta sum; for (int i = 0; i < times_.length(); ++i) { sum += times_[i]; } for (int i = 0; i < names_.length(); ++i) { PrintF("%33s", names_[i]); double ms = times_[i].InMillisecondsF(); double percent = times_[i].PercentOf(sum); PrintF(" %8.3f ms / %4.1f %% ", ms, percent); size_t size = sizes_[i]; double size_percent = static_cast<double>(size) * 100 / total_size_; PrintF(" %9zu bytes / %4.1f %%\n", size, size_percent); } PrintF( "----------------------------------------" "----------------------------------------\n"); base::TimeDelta total = create_graph_ + optimize_graph_ + generate_code_; PrintF("%33s %8.3f ms / %4.1f %% \n", "Create graph", create_graph_.InMillisecondsF(), create_graph_.PercentOf(total)); PrintF("%33s %8.3f ms / %4.1f %% \n", "Optimize graph", optimize_graph_.InMillisecondsF(), optimize_graph_.PercentOf(total)); PrintF("%33s %8.3f ms / %4.1f %% \n", "Generate and install code", generate_code_.InMillisecondsF(), generate_code_.PercentOf(total)); PrintF( "----------------------------------------" "----------------------------------------\n"); PrintF("%33s %8.3f ms %9zu bytes\n", "Total", total.InMillisecondsF(), total_size_); PrintF("%33s (%.1f times slower than full code gen)\n", "", total.TimesOf(full_code_gen_)); double source_size_in_kb = static_cast<double>(source_size_) / 1024; double normalized_time = source_size_in_kb > 0 ? total.InMillisecondsF() / source_size_in_kb : 0; double normalized_size_in_kb = source_size_in_kb > 0 ? static_cast<double>(total_size_) / 1024 / source_size_in_kb : 0; PrintF("%33s %8.3f ms %7.3f kB allocated\n", "Average per kB source", normalized_time, normalized_size_in_kb); } void HStatistics::SaveTiming(const char* name, base::TimeDelta time, size_t size) { total_size_ += size; for (int i = 0; i < names_.length(); ++i) { if (strcmp(names_[i], name) == 0) { times_[i] += time; sizes_[i] += size; return; } } names_.Add(name); times_.Add(time); sizes_.Add(size); } HPhase::~HPhase() { if (ShouldProduceTraceOutput()) { isolate()->GetHTracer()->TraceHydrogen(name(), graph_); } #ifdef DEBUG graph_->Verify(false); // No full verify. #endif } } } // namespace v8::internal
[ "w.goesgens@arangodb.org" ]
w.goesgens@arangodb.org
2cf5731d02e3da2dd3ff27fc9de00fab637ee9e1
0a10b4d1471212c150ed98abcc347f1b1c8a5304
/src/utils/u_io.cpp
dad2eeb78b8bd23d40d747cf71dadfbaac0e485a
[ "MIT" ]
permissive
thefishlive/VkFPS
fdfecafa7033c49e3fe7c38dd62be9c502567b2b
42d66070f95285bef144300bd14c9927f30d32fe
refs/heads/master
2021-04-18T18:35:34.591944
2018-08-22T21:02:39
2018-08-22T21:02:39
126,699,649
0
0
null
null
null
null
UTF-8
C++
false
false
2,806
cpp
/****************************************************************************** * Copyright 2017 James Fitzpatrick <james_fitzpatrick@outlook.com> * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * * DEALINGS IN THE SOFTWARE. * ******************************************************************************/ #include "u_io.h" #include <iostream> bool read_file(std::string filename, file_data *data) { FILE *file; bool result; std::string path = FILENAME_TO_PATH(filename); void *buffer; size_t length, read_size; file = fopen(path.c_str(), "rb"); if (!file) { std::cerr << "Error reading file " << path << " " << std::strerror(errno) << std::endl; result = false; goto err_out; } fseek(file, 0, SEEK_END); length = ftell(file); fseek(file, 0, SEEK_SET); buffer = malloc(length); if (!buffer) { std::cerr << "Error allocating buffer " << std::endl; result = false; goto err_close; } read_size = fread(buffer, sizeof(char), length, file); if (ferror(file) != 0 || length != read_size) { std::cerr << "Error reading file " << path << " (" << read_size << "!=" << length << ") " << std::strerror(errno) << std::endl; result = false; goto err_out; } data->size = length; data->data = buffer; result = true; err_close: if (fclose(file) != 0) { std::cerr << "Error closing file " << path << " " << std::strerror(errno) << std::endl; result = false; goto err_out; } err_out: return result; }
[ "thefishlive@hotmail.com" ]
thefishlive@hotmail.com
62ce9eed87ac76bce00cc5f8a3340c20e86bf110
443cad83e66f7da248fad24d8af46f7e9499d985
/src/ssr.cpp
8ebc71bf85588f31a1af431b138c44d7f315c003
[]
no_license
vigno88/ctt_press
63ccc846804d610c0e45f8dc28f3698de5390148
020213638c77b9cbda158ee8bde36ae9c7b18347
refs/heads/main
2023-08-14T13:52:04.278258
2021-09-29T18:07:01
2021-09-29T18:07:01
370,136,957
0
0
null
null
null
null
UTF-8
C++
false
false
1,253
cpp
#include "ssr.hpp" SSR::SSR(const uint32_t cycleTime,uint8_t pin): _cycleTime(cycleTime), _pin(pin) { // Start the ssr with no voltage on the output pin _dutyCycle = 0; _isLow = 0; _lastTime = millis(); _stepTime = _cycleTime / 255; digitalWrite(_pin, LOW); } void SSR::setIntensity(uint8_t i) { _i = i; // Scale the intensity to a time between 0 and the cycleTime _dutyCycle = i * _stepTime; analogWrite(_pin, i); } // void SSR::run() { // // long currentTime = millis(); // // // Set the SSR to low if the _dutyCycle time as passed // // if(currentTime - _lastTime > _dutyCycle && currentTime - _lastTime < _cycleTime && _isLow < 1) { // // digitalWrite(_pin, LOW); // // Serial.println("Set ssr to low"); // // _isLow = 1; // // } // // // Set the SSR to high if the _cycleTime as passed (reset the cycle) // // if( currentTime - _lastTime > _cycleTime && currentTime - _lastTime < _cycleTime) { // // _lastTime = millis(); // // digitalWrite(_pin, HIGH); // // Serial.println("Set ssr to high"); // // _isLow = 0; // // } // } int SSR::getIntensity() { return _i; } bool SSR::isHigh() { return (_isLow == 0); }
[ "nathan.alix88@gmail.com" ]
nathan.alix88@gmail.com
74d1de1f2e9e1f7ca6847980571f39585ee38059
2ede149a68c26ddf49c9300e9ec8b3085ee935d9
/tmp/daytime.cpp
6e7fe0f4c38844f3963ba0a139d04a0dca977b70
[]
no_license
angtylook/codesnippet
e945b45900c80c8f3f275a71fa8aead3788b11db
8eb46630a14492203032ad7844d1d1962b3124d0
refs/heads/master
2022-05-02T03:53:24.575188
2022-04-17T11:38:03
2022-04-17T11:38:03
185,048,544
0
0
null
null
null
null
UTF-8
C++
false
false
939
cpp
#include <iostream> #include <boost/array.hpp> #include <boost/asio.hpp> using boost::asio::ip::tcp; int main(int argc,char* argv[]) { try { if (argc != 2) { std::cerr << "Usage:client <host>" << std::endl; return 1; } boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(argv[1],"daytime"); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::socket socket(io_service); boost::asio::connect(socket,endpoint_iterator); for(;;) { boost::array<char,128> buf; boost::system::error_code error; size_t len = socket.read_some(boost::asio::buffer(buf),error); if (error == boost::asio::error::eof) break; else if(error) throw boost::system::system_error(error); std::cout.write(buf.data(),len); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
[ "lookto2008@gmail.com" ]
lookto2008@gmail.com
afce498f02596304012b20f09863c6a0ac9a767b
2d957a15acf5c900f61001dd307a32d0f2ead0a3
/rl_lib/RLEnvironmentBase.h
389cecb8758125550ffea80717b68ebbcd4acc00
[]
no_license
iitca/rpstr
eb8dc385879acdaceadfc3a6bee758a6a76acf61
81549c75125a25756f349638bb54ea652b6b681f
refs/heads/master
2021-05-31T10:10:59.297429
2015-07-14T11:38:09
2015-07-14T11:38:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
317
h
#pragma once #ifndef RL_ENVIRONMENT_BASE_H #define RL_ENVIRONMENT_BASE_H #include "RLActionBase.h" namespace RL { ///RLExperimentBase pure abstract class class RLEnvironmentBase { private: /*function is called by the outer code to return the action*/ virtual RLActionBase* getAction() = 0; }; } #endif
[ "ti777@mail.ru" ]
ti777@mail.ru
7d6b2369a60aa09ad602ea9b3c1699c1389ea663
5ed15f758da0aec98fbab593ea497656f92cba26
/Filters/Thinning2D.hh
2fbdb817b9e9474cddf464b6acac22a25d807e6a
[]
no_license
meroJamjoom/MDA_win
777fdb0d2d175ff73f28be8b8800f53924def899
bf14a47cdc54428620f26e479a19e9ccf0acf129
refs/heads/master
2020-05-22T06:43:01.534736
2016-09-14T01:39:46
2016-09-14T01:39:46
64,056,480
0
0
null
null
null
null
UTF-8
C++
false
false
2,199
hh
// ========================================================================== // $Id: Thinning2D.hh 374 2009-09-21 21:13:13Z heidrich $ // A 2D morphological thinning operator // ========================================================================== // License: Internal use at UBC only! External use is a copyright violation! // ========================================================================== // (C)opyright: // // 2007-, UBC // // Creator: heidrich () // Email: heidrich@cs.ubc.ca // ========================================================================== #ifndef FILTERS_THINNING2D_H #define FILTERS_THINNING2D_H /*! \file Thinning2D.hh \brief A 2D morphological thinning operator */ #ifdef _WIN32 // this header file must be included before all the others #define NOMINMAX #include <windows.h> #endif #include "HitOrMiss2D.hh" namespace MDA { /** \class Thinning2D Thinning2D.hh A 2D morphological thinning operator */ template<class T> class Thinning2D: public Filter<T> { public: /** constructor */ Thinning2D(); /** destructor */ ~Thinning2D() { for( unsigned i= 0 ; i< 8 ; i++ ) delete hmt[i]; } /** apply the filter to a number of dimensions and channels */ virtual bool apply( Array<T> &a, BoundaryMethod boundary, ChannelList &channels, AxisList &axes ); private: /** the 8 Hit-or-Miss Transforms comprising a thinning operation */ HitOrMiss2D<T> *hmt[8]; }; /** \class Thickening2D Thinning2D.hh A 2D morphological thickening operator (dual of thinning) */ template<class T> class Thickening2D: public Filter<T> { public: /** constructor */ Thickening2D(); /** destructor */ ~Thickening2D() { for( unsigned i= 0 ; i< 8 ; i++ ) delete hmt[i]; } /** apply the filter to a number of dimensions and channels */ virtual bool apply( Array<T> &a, BoundaryMethod boundary, ChannelList &channels, AxisList &axes ); private: /** the 8 Hit-or-Miss Transforms comprising a thinning operation */ HitOrMiss2D<T> *hmt[8]; }; } /* namespace */ #endif /* FILTERS_THINNING2D_H */
[ "msjamjoom@effat.edu.sa" ]
msjamjoom@effat.edu.sa
ae90342d2cf09cfaf9ff1d485fd481b906ccf334
d49b8536d996a81fd2a356f2ccd850abd4447217
/VirusPack/Rose v1.3 2007 by DreamWoRK/aliaslog.cpp
4fc92bdc0aceda637290d7209f5ded7c51de40a9
[]
no_license
JonnyBanana/botnets
28a90ab80f973478d54579f3d3eadc5feb33ff77
995b9c20aca5de0ae585ae17780a31e8bdfd9844
refs/heads/master
2021-07-01T01:51:01.211451
2020-10-22T23:14:57
2020-10-22T23:14:57
148,392,362
9
5
null
null
null
null
UTF-8
C++
false
false
292
cpp
#include "includes.h" #include "functions.h" #include "extern.h" // globals char log1[LOGSIZE][LOGLINE]; BOOL searchlog(char *filter) { for (int i = 0; i < LOGSIZE; i++) if (log1[i][0] != '\0') { if (lstrstr(log1[i], filter)) return TRUE; } return FALSE; }
[ "mstr.be832920@gmail.com" ]
mstr.be832920@gmail.com
309e233320b48c66424de669f3225171f4003d61
ad9ca29988acfd2cdddd573c068cfd61dfa942f0
/src/crypto/hmac_sha512.h
417241dc414178af25b4158bf1628fb41c7c8663
[ "MIT" ]
permissive
5GL/5GL
5d6ca603079e7abf673596f59c38eaa96392c42f
6a24c394206d53de3bccd4cb79a9dc22fa782ffa
refs/heads/master
2020-07-27T00:36:33.568205
2019-09-16T13:52:11
2019-09-16T13:52:11
208,810,885
1
0
null
null
null
null
UTF-8
C++
false
false
756
h
// Copyright (c) 2019 The 5GL developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef 5GL_CRYPTO_HMAC_SHA512_H #define 5GL_CRYPTO_HMAC_SHA512_H #include "crypto/sha512.h" #include <stdint.h> #include <stdlib.h> /** A hasher class for HMAC-SHA-512. */ class CHMAC_SHA512 { private: CSHA512 outer; CSHA512 inner; public: static const size_t OUTPUT_SIZE = 64; CHMAC_SHA512(const unsigned char* key, size_t keylen); CHMAC_SHA512& Write(const unsigned char* data, size_t len) { inner.Write(data, len); return *this; } void Finalize(unsigned char hash[OUTPUT_SIZE]); }; #endif // 5GL_CRYPTO_HMAC_SHA512_H
[ "5GL@5GL.info" ]
5GL@5GL.info
73e25abe93d54e3b58650d534fb74f5b3f6ade8d
e36906be9399685b0d03daffec9c33735eda8ba1
/src/main/yocto/random/bits.hpp
e2efe7a3652c19be19161a1594efc8910f3f0a24
[]
no_license
ybouret/yocto4
20deaa21c1ed4f52d5d6a7991450d90103a7fe8e
c02aa079d21cf9828f188153e5d65c1f0d62021c
refs/heads/master
2020-04-06T03:34:11.834637
2016-09-09T14:41:55
2016-09-09T14:41:55
33,724,799
1
0
null
null
null
null
UTF-8
C++
false
false
1,384
hpp
#ifndef YOCTO_RANDOM_BITS_INCLUDED #define YOCTO_RANDOM_BITS_INCLUDED 1 #include "yocto/memory/buffer.hpp" namespace yocto { namespace Random { class Bits : public object { public: virtual ~Bits() throw(); //! returns a random bit virtual bool operator()(void) throw() = 0; //! fill partially an integer type template <typename T> inline T rand( size_t nbits ) throw() { static const T _t0(0); static const T _t1(1); T ans( _t0 ); for( size_t j=nbits; j>0;--j) { ans <<= 1; if( (*this)() ) ans |= _t1; } return ans; } //! fill an integer type with random bits template <typename T> inline T full(void) throw() { return this->rand<T>( sizeof(T)*8 ); } //! 0..X-1 template <typename T> inline T lt( T X ) throw() { static const T _t0(0); return X <= _t0 ? _t0 : ( full<T>() % X ); } //! fill partially an integer type template <typename T> inline T fuzz() throw() { return this->rand<T>( 1 + this->lt<size_t>( sizeof(T) * 8 ) ); } //! fill this buffer with random bits void fill( memory::rw_buffer & ) throw(); protected: explicit Bits() throw(); private: YOCTO_DISABLE_COPY_AND_ASSIGN(Bits); }; Bits & SimpleBits() throw(); Bits & CryptoBits() throw(); } } #endif
[ "yann.bouret@gmail.com@6d5338fb-0854-7327-6163-5cad528299e9" ]
yann.bouret@gmail.com@6d5338fb-0854-7327-6163-5cad528299e9
639cb30087ee22b35272dbb754ef1cb942685513
03b1187d22b5b5c516adad56ac060bb99b502525
/sadx-randomizer/EggHornet.cpp
89afd8ba094357aeec4f19789a2ed561def8df43
[]
no_license
Sora-yx/SADX-Randomizer
689e4d390dd32b8d25a65d33ebca0fbc06266009
e862cd4681bdd79aa1d5fb3fffb3a066071ee2a9
refs/heads/master
2023-07-15T20:52:02.915283
2023-06-28T21:36:54
2023-06-28T21:36:54
184,065,663
13
5
null
2020-05-28T14:54:47
2019-04-29T12:19:10
C++
UTF-8
C++
false
false
502
cpp
#include "stdafx.h" #include "data\EggHornet.h" TaskHook EggHornet_t((intptr_t)EggHornet_Main); void EggHornet_Main_R(task* tp) { ObjectMaster* obj = (ObjectMaster*)tp; EntityData1* data1 = obj->Data1; Check_AllocateObjectData2(obj, data1); EggHornet_t.Original(tp); } void __cdecl EggHornet_Init(const HelperFunctions& helperFunctions) { //Initiliaze data EggHornet_t.Hook(EggHornet_Main_R); for (int i = 0; i < 8; i++) helperFunctions.RegisterStartPosition(i, EH_StartPositions[0]); }
[ "sora.x@hotmail.fr" ]
sora.x@hotmail.fr
ac6331c2705f00112c59dfe62983d78f0952ea6f
9a8e3137db2b3e29dceb170887144e991974c1f2
/eXemplar's-collection/exemplar/Apps 'n Bots/Apps 'n Bots/OCR/FOCRSource/src/KFC_Common/common_initials.cpp
01d733eeb1f224f0ce8749b6487273a88b477fe5
[]
no_license
drewjbartlett/runescape-classic-dump
07155b735cfb6bf7b7b727557d1dd0c6f8e0db0b
f90e3bcc77ffb7ea4a78f087951f1d4cb0f6ad8e
refs/heads/master
2021-01-19T21:32:45.000029
2015-09-05T22:36:22
2015-09-05T22:36:22
88,663,647
1
0
null
2017-04-18T19:40:23
2017-04-18T19:40:23
null
UTF-8
C++
false
false
970
cpp
#include "kfc_common_pch.h" #include "common_initials.h" #include "common_consts.h" TCommonInitials g_CommonInitials; // ---------------- // Common initials // ---------------- TCommonInitials::TCommonInitials() : TGlobals(TEXT("Common initials"), 0) { } void TCommonInitials::OnUninitialize() { } void TCommonInitials::OnInitialize() { if(!g_CommonConsts.m_bSkipBasicCfgInitials) Load(), Save(); } void TCommonInitials::LoadItems(KRegistryKey& Key) { } void TCommonInitials::SaveItems(KRegistryKey& Key) const { } void TCommonInitials::Load() { TAssignmentsList::Load( g_CommonConsts.m_ApplicationRegistryKeyName + g_CommonConsts.m_RegistryKeyName + g_CommonConsts.m_InitialsRegistryKeyName); } void TCommonInitials::Save() const { TAssignmentsList::Save( g_CommonConsts.m_ApplicationRegistryKeyName + g_CommonConsts.m_RegistryKeyName + g_CommonConsts.m_InitialsRegistryKeyName); }
[ "tom@tom-fitzhenry.me.uk" ]
tom@tom-fitzhenry.me.uk
c695efa0703c854e4b3e6dac399bcc477ffba1e0
bc072898d9e4ad94700cc39ed67594c6ff7a58bf
/05-Functions/Program_6-4.cpp
aab4d587f8470eae69e4d0c7110f66e2d7659548
[ "MIT" ]
permissive
ringosimonchen0820/How-to-CPlusPlus
4ab9384ae3584d2a29ef6522da2046fa9b490f79
69b0310e6aeab25a7e2eed41e4d6cff85a034e00
refs/heads/master
2023-03-14T18:09:11.539561
2021-03-22T19:53:46
2021-03-22T19:53:46
293,198,202
0
2
null
null
null
null
UTF-8
C++
false
false
954
cpp
// This program has three functions: main, deep, and deeper #include <iostream> using namespace std; //******************************************** //* Definition of function deeper * //* This function displays a message * //******************************************** void deeper() { cout << "I am now inside the function deeper.\n"; } //******************************************** //* Definition of function deep * //* This function displays a message * //******************************************** void deep() { cout << "I am now inside the function deep.\n"; deeper(); cout << "Now I am back in deep.\n"; } //******************************************** //* Function main * //******************************************** int main() { cout << "I am starting in function main.\n"; deep(); cout << "Back in function main again.\n"; return 0; }
[ "54449798+ringosimonchen0820@users.noreply.github.com" ]
54449798+ringosimonchen0820@users.noreply.github.com
e9dc91bc758822eea73c496ae0ab0b80eee01ceb
d9cfe5dd9bcbd5e168c780c0f4ede892b9e9df63
/pfs.legacy/old/unix/threadls_unix.cpp
6d5031124895cbd610c6f06295e4ed205b8d07d6
[]
no_license
semenovf/archive
c196d326d85524f86ee734adee74b2f090eac6ee
5bc6d21d072292dedc9aa4d7a281bc75a1663441
refs/heads/master
2022-05-30T11:04:17.315475
2022-04-27T03:33:56
2022-04-27T03:33:56
130,155,339
0
0
null
null
null
null
UTF-8
C++
false
false
2,205
cpp
/* * threadls_unix.cpp * * Created on: Sep 19, 2013 * Author: wladt */ #include <pfs/vector.hpp> #include <pfs/threadls.hpp> #include "thread_unix.hpp" // for CWT_HAVE_TLS namespace pfs { // FIXME Implement these ! thread::tls_implementation_type thread::tls_implementation () { #ifdef CWT_HAVE_TLS return thread::TlsCompilerSpecific; #else return thread::TlsPosixThreads; #endif } #ifdef __COMMENT__ static Mutex destructorsMutex; typedef Vector<void (*)(void *)> DestructorMap; static DestructorMap * destructors() { static DestructorMap staticVariable; static atomic_pointer<DestructorMap> pointer; return pointer; } ThreadStorageData::ThreadStorageData(void (* cleanup)(void *)) { AutoLock<> locker(& destructorsMutex); DestructorMap * destr = destructors(); if (! destr) { /* the destructors vector has already been destroyed, yet a new ThreadStorage is being allocated. this can only happen during global destruction, at which point we assume that there is only one thread. in order to keep ThreadStorage working, we need somewhere to store the data, best place we have in this situation is at the tail of the current thread's tls vector. the destructor is ignored, since we have no where to store it, and no way to actually call it. */ ThreadData * data = ThreadData::current(); id = data->tls.count(); DEBUG_MSG("ThreadStorageData: Allocated id %d, destructor %p cannot be stored", id, func); return; } for (id = 0; id < destr->count(); id++) { if (destr->at(id) == 0) break; } if (id == destr->count()) { destr->append(func); } else { (*destr)[id] = func; } //DEBUG_MSG("ThreadStorageData: Allocated id %d, destructor %p", id, func); } //struct future_object_base; //struct tss_cleanup_function; //struct thread_exit_callback_node; struct tss_data_node { shared_ptr<ThreadLS::cleanup_functor> m_func; void * m_value; tss_data_node (shared_ptr<ThreadLS::cleanup_functor> func, void * value) : m_func(func) , m_value(value) {} }; #endif } // pfs
[ "fedor.v.semenov@gmail.com" ]
fedor.v.semenov@gmail.com
008ef8744c78b5afb592a039f14e44f64e9e00d2
aee1f3d03421ec2232670f8ed51df1e7af4d32d7
/items.cpp
982f8e3ef5b6fa1f7d60eee58917fcebf381c863
[]
no_license
kennethpham/DungeonGameCpp
cf3697c5245fc7ab38c83de4a77f4aded100abc4
47f9912c3ed84b5cbfadf4d6ae19912cf0164ee3
refs/heads/master
2020-12-04T08:52:58.098486
2020-08-11T21:41:05
2020-08-11T21:41:05
231,702,387
0
0
null
2020-02-20T02:18:12
2020-01-04T03:22:55
C++
UTF-8
C++
false
false
19
cpp
#include "items.h"
[ "kennethpham98@gmail.com" ]
kennethpham98@gmail.com
777cbedb66984df093864f824781bfbc73cc1aad
60bc4df912b11b88f7ba53e8cb1ab6c96dc28284
/abstract-factory/builders/abstract/BuilderSofa.cpp
8c2359108792540cac60bcb2bd703e6032055cda
[]
no_license
heyW0rld/Software-engineering
065bc930cb3e57350dd18e2da596858f1d569065
84902854cf5647055f0f2f5728605070be29af36
refs/heads/main
2023-04-05T10:40:04.888437
2021-04-18T18:32:58
2021-04-18T18:32:58
359,219,664
0
0
null
null
null
null
UTF-8
C++
false
false
64
cpp
// // Created by HW on 21.03.2021. // #include "BuilderSofa.h"
[ "porayj@gmail.com" ]
porayj@gmail.com
f58a74bec80c93f4b952de9fb8acefcfe7d07905
f697fab58be8b9519a71e0ca8eeeed5774aa5297
/08_Inheritance.cpp
44225bee5e0db229e78ecccd359ca78071544c81
[]
no_license
mbkhan721/ObjectOrientedProgrammingET580
96eacf6895aac9459d6f771667ca4b776682d74e
d7112b3f289bae27b3a5e7e7d81ffd31dc655517
refs/heads/master
2023-06-28T19:45:08.588557
2021-08-11T19:07:00
2021-08-11T19:07:00
382,126,678
0
0
null
null
null
null
UTF-8
C++
false
false
2,934
cpp
/* #include <iostream> using namespace std; // One class inherits from another class. Parent/child relationship. // It's a one-way down (hierarchy). A child does not give to the parent, parent give to the child. // When creating child classes, you're gonna automatically initialize a parent object. class Vehicle { public: Vehicle(string b): brand(b) { // Base or parent cout << "Vehicle constructor called. " << "\n"; } string getBrand() const {return brand;} private: string brand; }; class Car : public Vehicle { // Derived or child public: Car(string b): Vehicle(b) { cout << "Car constructor called. " << "\n"; } }; // ********************************************************************************* // ************************** MAIN FUNCTION ******************************* // ********************************************************************************* int main() { cout << "\n"; Vehicle v("Acura"); // Only calls the vehicle constr cout << "\n"; Car c("Lexus"); // Calls both Veh and Car constrs cout << "v: " << v.getBrand() << "\n"; cout << "c: " << c.getBrand() << "\n"; cout << "\n"; return 0; } // class Person { Base // Person() {} // }; // class Student : public Person { This means that Student inherits from Person. Or Student is-a Person. // Student(): Person() {} When we construct a student object, we must also construct a person object. // }; So the student constr calls the person constr // Whenever the student is created, we're also creating a person object and they're related to each other by // inheritance. // In this situation, we can call Person the parent class and Student the child class. // Or we call Person as the base class and Student the derived class. // output for above program: // Vehicle constructor called. // Vehicle constructor called. // Car constructor called. // v: Acura // c: Lexus // Inside Vehicle class, constr populates the value of data member brand. // Accessor function gets the value of brand and returns it. // In Car class, the only code I have is the constructor. // However, when we create a Car object, we also create a Vehicle object utilizing the string in Car class. // So Car is Creating the Vehicle. // Vehicle v("Acura"); // Only calls the vehicle constr // Car c("Lexus"); // Calls both Veh and Car constrs // Vehicle is called first because any code that's in the initialization list runs before what's in the parentheses. // When we create a Car object, the first thing it does is it calls Vehicle. Vehicle runs and print out "Vehicle // constructor called." Now the code inside the parentheses runs and prints out the second statement. // Car class inherited the getBrand function and getBrand data from Vehicle class. */
[ "muhammad.khan33@student.qcc.cuny.edu" ]
muhammad.khan33@student.qcc.cuny.edu
8df8160d379c5c1581ece22fae5e08a5ac1e9101
b2dab2373e810259a042febbfb832ea722769938
/tests/test_machine_base/test_machine_base.h
1de5f46de2917b2d004039b444bc6a011661df2c
[ "Apache-2.0" ]
permissive
shanihsu/Parallel-Genetic-Algorithm
1c5520331453574b4463c2976f0cc5edcb81f757
2e3776df60e2457f9ecf2b5c271152a237f117ed
refs/heads/main
2023-08-11T22:48:22.876663
2021-09-30T07:55:42
2021-09-30T07:55:42
342,235,530
0
0
Apache-2.0
2021-02-25T12:21:35
2021-02-25T12:21:34
null
UTF-8
C++
false
false
752
h
#ifndef __TEST_MACHINE_BASE_H__ #define __TEST_MACHINE_BASE_H__ #include "include/linked_list.h" #include <cstdlib> #include <iostream> #include <gtest/gtest.h> #include <include/machine_base.h> #include <include/job_base.h> #include <include/common.h> #include <cuda.h> struct Job{ JobBase base; LinkedListElement ele; double val; }; struct Machine{ MachineBase base; }; __device__ __host__ double machineSortJobs(void * self); __device__ __host__ double jobGetValue(void *); __device__ __host__ void addJob(void *_self, void * job); __device__ __host__ void sortJob(void *_self); __device__ __host__ void initMachine(void *self); __device__ __host__ void initJob(Job * _self); Job * newJob(double val); Machine *newMachine(); #endif
[ "yuchunlin0075@gmail.com" ]
yuchunlin0075@gmail.com
ae66cc901a3f4c246c5aac831bf6d54727da2817
387549ab27d89668e656771a19c09637612d57ed
/DRGLib UE project/Source/FSD/Private/MissionTemplate.cpp
f1885068b2bfa1510cdc6969df58874896971f7b
[ "MIT" ]
permissive
SamsDRGMods/DRGLib
3b7285488ef98b7b22ab4e00fec64a4c3fb6a30a
76f17bc76dd376f0d0aa09400ac8cb4daad34ade
refs/heads/main
2023-07-03T10:37:47.196444
2023-04-07T23:18:54
2023-04-07T23:18:54
383,509,787
16
5
MIT
2023-04-07T23:18:55
2021-07-06T15:08:14
C++
UTF-8
C++
false
false
1,820
cpp
#include "MissionTemplate.h" #include "Templates/SubclassOf.h" bool UMissionTemplate::IsLocked(UFSDSaveGame* SaveGame) const { return false; } TArray<UMissionDuration*> UMissionTemplate::GetValidDurations() const { return TArray<UMissionDuration*>(); } TArray<UMissionComplexity*> UMissionTemplate::GetValidComplexities() const { return TArray<UMissionComplexity*>(); } TSoftClassPtr<AProceduralSetup> UMissionTemplate::GetSoftReferenceToPLS() { return NULL; } FObjectiveMissionIcon UMissionTemplate::GetPrimaryObjectiveIconFromAsset(UMissionTemplate* mission, bool getSmallVersion) { return FObjectiveMissionIcon{}; } FObjectiveMissionIcon UMissionTemplate::GetPrimaryObjectiveIcon(bool getSmallVersion) const { return FObjectiveMissionIcon{}; } TSubclassOf<AProceduralSetup> UMissionTemplate::GetPLS() const { return NULL; } TSubclassOf<UObjective> UMissionTemplate::GetObjectiveClass() { return NULL; } int32 UMissionTemplate::GetMissionTypeIndex() const { return 0; } UTexture2D* UMissionTemplate::GetMissionImageLarge() const { return NULL; } UTexture2D* UMissionTemplate::GetMissionButtonImage() const { return NULL; } UGeneratedMission* UMissionTemplate::GenerateMission(const UObject* WorldContextObject, UBiome* Biome, int32 Seed, int32 GlobalSeed, int32 missionIndex, UMissionComplexity* limitComplexity, UMissionDuration* limitDuration, UMissionMutator* Mutator, TArray<UMissionWarning*> Warnings, TArray<TSubclassOf<UObjective>> forceSecondary) { return NULL; } UMissionTemplate::UMissionTemplate() { this->PrimaryObjective = NULL; this->MissionIcon = NULL; this->MissionIconSmall = NULL; this->MissionTypeIndex = 0; this->MustBeUnlocked = true; this->RoomEncounerScale = 1.00f; this->StationaryEnemyScale = 1.00f; }
[ "samamstar@gmail.com" ]
samamstar@gmail.com
ae4feeb198b927a795845d731e986ea7bb965cf7
b978ca6f3ae6e416941c5822da55c486a045eb97
/MainPage.xaml.cpp
e9c4cfd7b1d7050598b9dc37e859e497c35fc897
[]
no_license
Etto48/Branches-App
fbf0e574b9b35c7e316c9620962465d6044d8230
a59095a2587ffe2a091383e1cedac6a52cdcce4f
refs/heads/master
2022-11-30T22:32:57.654800
2020-07-31T19:48:16
2020-07-31T19:48:16
284,117,695
0
0
null
null
null
null
UTF-8
C++
false
false
5,004
cpp
// // MainPage.xaml.cpp // Implementation of the MainPage class. // #include "pch.h" #include "MainPage.xaml.h" #include "branches_core/branches_core.h" #include "Input.h" using namespace Branches; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 std::map<std::string, T> symMap; std::map<std::string, std::string> functions; MainPage::MainPage() { InitializeComponent(); } void Branches::MainPage::AddData(Platform::String^ data,bool emptyDataInputBox) { if (data != "") { ListViewItem^ newData = ref new ListViewItem(); try { auto val = filterInput(data, symMap); bool constant = std::get<0>(val); if ((functions.find(std::get<1>(val)) == functions.end()) && (symMap.find(std::get<1>(val)) == symMap.end())) { if (constant) { symMap.emplace(std::get<1>(val), std::get<3>(val)); } else { functions.emplace(std::get<1>(val), std::get<2>(val)); } } else return; newData->Content = Std_Str_To_Managed_Str((std::get<1>(val) + "=" + std::get<2>(val))); MainPage::DataList->Items->Append(newData); if(emptyDataInputBox) MainPage::DataInputBox->Text = ""; } catch (algebra_tools_::except& e) { MainPage::DebugText->Text = Std_Str_To_Managed_Str(e.what()); } } } void Branches::MainPage::AddButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { AddData(MainPage::DataInputBox->Text, true); } void Branches::MainPage::DeleteEntryFromMaps(Platform::String^ entry) { auto val = filterInput(entry, symMap); if (symMap.find(std::get<1>(val)) != symMap.end()) { symMap.erase(std::get<1>(val)); } else if (functions.find(std::get<1>(val)) != functions.end()) { functions.erase(std::get<1>(val)); } } void Branches::MainPage::DeleteEntry(Platform::String^ entry) { for (int i = 0; i < MainPage::DataList->Items->Size; i++) { if (((ListViewItem^)MainPage::DataList->Items->GetAt(i))->Content->ToString() == entry) { DeleteEntryFromMaps(entry); MainPage::DataList->Items->RemoveAt(i); break; } } } void Branches::MainPage::RemoveButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { if (MainPage::DataList->SelectedIndex > -1) { auto selectedText = ((ListViewItem^)(MainPage::DataList->SelectedItem))->Content->ToString(); DeleteEntry(selectedText); } } void Branches::MainPage::DataList_RightTapped(Platform::Object^ sender, Windows::UI::Xaml::Input::RightTappedRoutedEventArgs^ e) { auto a = ((FrameworkElement^)e->OriginalSource)->DataContext; for (int i=0;i<MainPage::DataList->Items->Size;i++) { if (((ListViewItem^)MainPage::DataList->Items->GetAt(i))->Content->ToString() == a->ToString()) { ((ListViewItem^)MainPage::DataList->Items->GetAt(i))->IsSelected = true; MainPage::Menu->ShowAt(MainPage::DataList, e->GetPosition(MainPage::DataList)); break; } } } void Branches::MainPage::savePartial(std::string dir) { auto selectedItem = ((ListViewItem^)(MainPage::DataList->SelectedItem)); if (selectedItem && selectedItem->Content->ToString() != "") { auto selectedText = selectedItem->Content->ToString(); ListViewItem^ newData = ref new ListViewItem(); try { auto val = filterInput(selectedText, symMap); auto der = Std_Str_To_Managed_Str(std::get<1>(val) + dir + "=" + algebraParser(std::get<2>(val)).derivative(dir)); AddData(der, false); } catch (algebra_tools_::except &e) { MainPage::DebugText->Text = Std_Str_To_Managed_Str(e.what()); } } } void Branches::MainPage::Partial_x(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { savePartial("x"); } void Branches::MainPage::Partial_y(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { savePartial("y"); } void Branches::MainPage::Partial_t(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { savePartial("t"); } void Branches::MainPage::Partial_u(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { savePartial("u"); } void Branches::MainPage::Partial_v(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { savePartial("v"); } void Branches::MainPage::Edit_Data(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { auto selectedItem = ((ListViewItem^)(MainPage::DataList->SelectedItem)); MainPage::DataInputBox->Text = selectedItem->Content->ToString(); DeleteEntry(selectedItem->Content->ToString()); } void Branches::MainPage::DrawButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { }
[ "minecraft.etto@gmail.com" ]
minecraft.etto@gmail.com
c7008e8b5d6e541250d866807304840e75d722bb
0e3eb3ee105a228b2be74681e5470fa4563237b4
/src/include/fspp/details/path.ipp
2bf5c83c02464c965fba5cfd260603ec773e9e02
[ "BSD-3-Clause", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hvellyr/fspplib
f287f98f8df3d548d578b4310e898a5acda6c1f3
34505a0d1d424eb76deb3cea3def6fb53f55a061
refs/heads/master
2021-07-02T06:19:10.954744
2020-12-28T22:13:52
2020-12-28T22:13:52
73,756,051
0
0
null
2017-12-17T22:28:03
2016-11-14T23:25:21
C++
UTF-8
C++
false
false
7,750
ipp
// Copyright (c) 2016 Gregor Klinke #pragma once #include "fspp/details/platform.hpp" #include <algorithm> #include <cctype> #include <istream> #include <ostream> #include <string> namespace eyestep { namespace filesystem { inline path::path(const std::string& source) { detail::convert(_data, source); } inline path::path(const char* source) { detail::convert(_data, source); } #if defined(FSPP_SUPPORT_WSTRING_API) inline path::path(const std::wstring& source) { detail::convert(_data, source); } inline path::path(const wchar_t* source) { detail::convert(_data, source); } #endif template <typename Source> inline path::path(const Source& source) { detail::convert(_data, source); } template <class InputIt> inline path::path(InputIt i_first, InputIt i_last) { detail::convert(_data, i_first, i_last); } inline auto path::begin() const -> iterator { return iterator(*this, std::begin(_data)); } inline auto path::end() const -> iterator { return iterator(*this, std::end(_data)); } #if defined(FSPP_IS_VS2013) inline path::path(path&& other) : _data(std::move(other._data)) { } inline path& path::operator=(path&& other) { _data = std::move(other._data); return *this; } #endif template <typename Source> inline path& path::operator=(const Source& source) { return this->assign(source); } template <typename Source> inline path& path::assign(const Source& source) { string_type data; detail::convert(data, source); _data.swap(data); return *this; } template <typename InputIt> inline path& path::assign(InputIt i_first, InputIt i_last) { detail::convert(_data, i_first, i_last); return *this; } template <class Source> inline path& path::operator/=(const Source& source) { return operator/=(path(source)); } template <class Source> inline path& path::append(const Source& source) { return operator/=(source); } template <typename InputIt> inline path& path::append(InputIt i_first, InputIt i_last) { return operator/=(path(i_first, i_last)); } inline path& path::operator+=(const path& p) { _data += p.native(); return *this; } inline path& path::operator+=(const string_type& str) { _data += str; return *this; } inline path& path::operator+=(const value_type* ptr) { _data += ptr; return *this; } template <typename CharT, typename std::enable_if<std::is_integral<CharT>::value>::type*> inline path& path::operator+=(CharT c) { CharT t[2] = {c, 0}; string_type p; detail::convert(p, t); _data += p; return *this; } template <class Source, typename std::enable_if<!std::is_integral<Source>::value>::type*> inline path& path::operator+=(const Source& source) { string_type p; detail::convert(p, source); _data += p; return *this; } template <class Source> inline path& path::concat(const Source& source) { return operator+=(path(source)); } inline void path::clear() { _data.clear(); } inline bool path::empty() const { return _data.empty(); } inline path& path::make_preferred() { #if defined(FSPP_IS_WIN) || defined(FSPP_EMULATE_WIN_PATH) using std::begin; using std::end; const auto ps = preferred_separator; std::replace(begin(_data), end(_data), static_cast<value_type>('/'), ps); #endif return *this; } inline void path::swap(path& other) { _data.swap(other._data); } inline auto path::c_str() const -> const value_type* { return native().c_str(); } inline auto path::native() const -> const string_type& { return _data; } inline path::operator string_type() const { return _data; } inline std::string path::string() const { return u8string(); } inline std::string path::u8string() const { std::string result; return detail::convert(result, _data); } inline std::string path::generic_string() const { return generic_u8string(); } inline std::string path::generic_u8string() const { using std::begin; using std::end; auto tmp = _data; std::replace(begin(tmp), end(tmp), '\\', '/'); std::string result; return detail::convert(result, tmp); } #if defined(FSPP_SUPPORT_WSTRING_API) inline std::wstring path::wstring() const { std::wstring result; return detail::convert(result, _data); } inline std::wstring path::generic_wstring() const { using std::begin; using std::end; auto tmp = _data; std::replace(begin(tmp), end(tmp), '\\', '/'); std::wstring result; return detail::convert(result, tmp); } #endif inline int path::compare(const string_type& str) const { return compare(path(str)); } inline int path::compare(const value_type* s) const { return compare(path(s)); } inline path& path::remove_filename() { *this = parent_path(); return *this; } inline path& path::replace_filename(const path& replacement) { *this = parent_path() / replacement; return *this; } inline bool path::is_absolute() const { #if defined(FSPP_IS_WIN) || defined(FSPP_EMULATE_WIN_PATH) return has_root_name() && has_root_directory(); #else return has_root_directory(); #endif } inline bool path::is_relative() const { return !is_absolute(); } inline bool operator==(const path& lhs, const path& rhs) { return lhs.compare(rhs) == 0; } inline bool operator!=(const path& lhs, const path& rhs) { return !operator==(lhs, rhs); } inline bool operator<(const path& lhs, const path& rhs) { return lhs.compare(rhs) < 0; } inline bool operator<=(const path& lhs, const path& rhs) { return lhs.compare(rhs) <= 0; } inline bool operator>(const path& lhs, const path& rhs) { return lhs.compare(rhs) > 0; } inline bool operator>=(const path& lhs, const path& rhs) { return lhs.compare(rhs) >= 0; } inline path operator/(const path& lhs, const path& rhs) { return path(lhs) /= rhs; } inline void swap(path& lhs, path& rhs) { lhs.swap(rhs); } template <class Source> inline path u8path(const Source& source) { return path(source); } template <class InputIt> path u8path(InputIt i_first, InputIt i_last) { return path(i_first, i_last); } //---------------------------------------------------------------------------------------- #if defined(FSPP_IS_VS2013) inline path::iterator::iterator(iterator&& rhs) : _data(std::move(rhs._data)) , _it(std::move(rhs._it)) , _elt(std::move(rhs._elt)) { } inline auto path::iterator::operator=(iterator&& rhs) -> iterator& { _data = std::move(rhs._data); _it = std::move(rhs._it); _elt = std::move(rhs._elt); return *this; } #endif inline bool path::iterator::operator==(const iterator& rhs) const { return _data == rhs._data && _it == rhs._it; } inline bool path::iterator::operator!=(const iterator& rhs) const { return !(operator==(rhs)); } inline auto path::iterator::operator--(int) -> iterator { auto i_tmp = iterator(*this); operator--(); return i_tmp; } inline auto path::iterator::operator++(int) -> iterator { auto i_tmp = iterator(*this); operator++(); return i_tmp; } inline auto path::iterator::operator*() -> reference { return _elt; } inline auto path::iterator::operator-> () -> pointer { return &_elt; } //---------------------------------------------------------------------------------------- inline ::std::ostream& operator<<(::std::ostream& os, const path& p) { os << p.u8string().c_str(); return os; } inline ::std::istream& operator>>(::std::istream& is, path& p) { std::string tmp; is >> tmp; p = path(tmp); return is; } #if defined(FSPP_SUPPORT_WSTRING_API) inline ::std::wostream& operator<<(::std::wostream& os, const path& p) { os << p.wstring().c_str(); return os; } inline ::std::wistream& operator>>(::std::wistream& is, path& p) { std::wstring tmp; is >> tmp; p = path(tmp); return is; } #endif } // namespace filesystem } // namespace eyestep
[ "gck@eyestep.org" ]
gck@eyestep.org
3259f26100169c2d87f6b100695f061a19af4d77
cccfb7be281ca89f8682c144eac0d5d5559b2deb
/ios/web/public/js_messaging/fuzzer_support/fuzzer_util.h
ce10a38e6040f9b1361b613f2c31915e9a541add
[ "BSD-3-Clause" ]
permissive
SREERAGI18/chromium
172b23d07568a4e3873983bf49b37adc92453dd0
fd8a8914ca0183f0add65ae55f04e287543c7d4a
refs/heads/master
2023-08-27T17:45:48.928019
2021-11-11T22:24:28
2021-11-11T22:24:28
428,659,250
1
0
BSD-3-Clause
2021-11-16T13:08:14
2021-11-16T13:08:14
null
UTF-8
C++
false
false
813
h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_WEB_PUBLIC_JS_MESSAGING_FUZZER_SUPPORT_FUZZER_UTIL_H_ #define IOS_WEB_PUBLIC_JS_MESSAGING_FUZZER_SUPPORT_FUZZER_UTIL_H_ #include <memory> #include "ios/web/public/js_messaging/fuzzer_support/js_message.pb.h" namespace web { class ScriptMessage; namespace fuzzer { // Converts a |ScriptMessageProto| to |ScriptMessage|. Logs fields in message // when |LPM_DUMP_NATIVE_INPUT| is in environment for easier debugging. std::unique_ptr<web::ScriptMessage> ProtoToScriptMessage( const web::ScriptMessageProto& proto); } // namespace fuzzer } // namespace web #endif // IOS_WEB_PUBLIC_JS_MESSAGING_FUZZER_SUPPORT_FUZZER_UTIL_H_
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
16ebce1924cebdc85c924bbd6e5e6c371aa1e47f
c7eed60e0fcee86f548e0ee9b827343837e47058
/9.cpp
d01b76a80984d080ea639bcc4b674a05b5885ffa
[]
no_license
Lethe0616/day-by-day
9483fff32f3723e61b095910cf2023501e3a02c2
c5a6662b3ef7e004dc26883dac9eb57e31bd0f27
refs/heads/master
2020-09-04T12:36:16.760812
2020-04-18T11:44:24
2020-04-18T11:44:24
219,733,878
0
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
#include<iostream> using namespace std; bool is_reback(string &str) { int begin=0; int end=str.size()-1; while(begin<end) { if(str[begin]!=str[end]) { return false; } begin++; end--; } return true; } int reback_Count() { string A; string B; getline(cin,A); getline(cin,B); int count=0; for(int i=0;i<=A.size();i++) { string str1=A; str1.insert(i,s2); if(is_reback(str1)) { count++; } } return count; }
[ "18792407909@163.com" ]
18792407909@163.com
d6e2cf69d29acbfe5fca406c35350363785d8c37
1375e9a4f67fa71273e263cd5ed79f36a5fd50d0
/attempt/1171.cpp
65e5a01642d1d2f67bbf70e60168018f03df947b
[]
no_license
yjl9903/XLor-HDu
6253850a0593f28e8c54878d17584cb85773cbc6
b1ccc113097abc614c7200222c9569f4ddb8d343
refs/heads/master
2020-03-21T09:25:31.862568
2019-10-07T15:30:45
2019-10-07T15:30:45
138,399,223
0
0
null
null
null
null
UTF-8
C++
false
false
1,425
cpp
#include <iostream> #include <cstring> #include <utility> #include <algorithm> #define ms(a,b) memset(a,b,sizeof(a)) using namespace std; typedef long long ll; typedef pair<int, int> PII; const int maxn = 1000 + 5; const int maxv = 250000 + 5; const int inf = 1 << 30; int n, v[maxn], m[maxn], dp[maxv], head, tail, head2, tail2; // PII dq[maxv]; int dq[maxv], dq2[maxv]; int main(){ while (cin >> n && n > 0){ int s = 0; for (int i = 0; i < n; i++) cin >> v[i] >> m[i], s += v[i] * m[i]; int w = s / 2; ms(dp, 0); // fill(dp, dp + maxv, inf); dp[0] = 0; for (int i = 0; i < n; i++){ for (int j = 0; j < v[i]; j++){ head = 1, tail = 0; head2 = 1, tail2 = 0; for (int k = j, cnt = 0; k <= w; k += v[i], cnt++){ if (tail2 - head2 == m[i]){ if (dq2[head2] == dq[head]) head++; head2++; } int t = dp[k] - cnt * v[i]; dq2[++tail2] = t; while (head <= tail && dq2[tail] < t) tail--; dq[++tail] = t; dp[k] = dq[head] + cnt * v[i]; } } } int a = 0; for (int i = w; i >= 1; i--) if (dp[i]) { a = dp[i]; break; } cout << s - a << ' ' << a << endl; } return 0; }
[ "yjl9903@vip.qq.com" ]
yjl9903@vip.qq.com
5da36fc57425212cb11007e206cefbbf8e7b43df
714423f3011f41ffd26d0534ed99640e482dbf93
/FtsUtilityAI/Source/FtsUtilityAI/Public/Score/FtsUtilityAIWeightScoreModifier.h
30f905a7281d0fc28cfe99882dbdf87ac4fbcdf9
[ "MIT" ]
permissive
FreetimeStudio/FtsUtilityAI
2053abd9e4e3ab9f415686e24b7de9d58cfc426c
cf1f214d685fcc3c24f426881bdad6c8257e36e3
refs/heads/main
2023-02-25T02:00:40.624764
2021-02-03T21:03:00
2021-02-03T21:03:00
312,661,459
1
0
null
null
null
null
UTF-8
C++
false
false
608
h
// (c) MIT 2020 by FreetimeStudio #pragma once #include "CoreMinimal.h" #include "Score/FtsUtilityAISingleScoreModifier.h" #include "FtsUtilityAIWeightScoreModifier.generated.h" /** * */ UCLASS() class FTSUTILITYAI_API UFtsUtilityAIWeightScoreModifier : public UFtsUtilityAISingleScoreModifier { GENERATED_BODY() protected: UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Utility AI") float Weight; public: UFtsUtilityAIWeightScoreModifier(); virtual float EvaluateScore_Implementation(float DeltaSeconds) override; #if WITH_EDITOR virtual FText GetNodeTitle() const override; #endif };
[ "pkrabbe@freetimestudio.net" ]
pkrabbe@freetimestudio.net
725ee0faf5058b7d7d2f616c5028c3eb1626af07
2d1ce28e5fe388bb9ea8a40db459c48bbcf37279
/itemRoom.cpp
1ac3a061cdc6ca67adb127258b39865d055e8674
[]
no_license
goldjay/textDungeon
4d570b1b0bd49879ada325e2f597f6d75f787676
394594cd1e26d07fa650b95fe2600df193267ac9
refs/heads/master
2020-12-24T12:39:54.585768
2016-11-06T03:58:58
2016-11-06T03:58:58
72,968,401
0
0
null
null
null
null
UTF-8
C++
false
false
4,766
cpp
/**************************************************************************************** **Program Filename: itemRoom.cpp **Author: Jay Steingold **Date: 3/9/16 **Description: itemRoom Room whose action gives the player an item **Input: none **Output: none ****************************************************************************************/ #include "itemRoom.hpp" #include "room.hpp" #include <iostream> #include <cstdlib> ItemRoom::ItemRoom() { this->type = "item"; north = NULL; south = NULL; east = NULL; west = NULL; } /**************************************************************************************** **Function: action **Description: Depending on the room, gives the player an item **Parameters: none **Pre-conditions: Must have a room **Post-Conditions: none ***************************************************************************************/ int ItemRoom::action() { int num = -1; /*Only for the 3rd room*/ if(this->number == 3) { std::cout << "\nYou enter a room held together by vines.\n"; std::cout << "Water flows down the cracked walls and\n"; std::cout << "into a small grate in the floor.\n"; std::cout << "In the center of the room is a large iron bed\n"; std::cout << "with fluffy white sheets.\n"; std::cout << "It's strange but your body aches from the venom.\n"; std::cout << "Do you rest in the bed?\n"; while(num != 1 && num != 2) { std::cout << "Type 1 for yes\n"; std::cout << "Type 2 for no\n"; std::cin >> num; } /*Sleep in the bed */ if(num == 1) { std::cout << "You settle into the sheets but something is poking"; std::cout << " you in the back!\n"; std::cout << "It's a key!\n"; return 100; } /*Don't sleep in the bed */ else { std::cout << "No, you'll be alright.\n"; } } /*For the gauntlet Room*/ else if(this->number == 7) { num = -1; std::cout << "\nYou arrive in a shining room of white marble.\n"; std::cout << "Three gauntlets stand on pedistols\n"; std::cout << "The first is made of crystal.\n"; std::cout << "Inside you can see a skeleton hand.\n"; std::cout << "The second is made of worn leather.\n"; std::cout << "Though it is quite worn you can see no holes.\n"; std::cout << "The third is a dull iron.\n"; std::cout << "Its surface marred with thousands of tiny scratches.\n"; std::cout << "What will you do?\n"; while(num <= 0 || num > 4) { std::cout << "Press 1 to choose the crystal gauntlet.\n"; std::cout << "Press 2 to choose the leather gauntles.\n"; std::cout << "Press 3 to choose the iron gauntlet.\n"; std::cout << "Press 4 to choose none of the gauntlets.\n"; std::cin >> num; } /*If the player chooses the crystal gauntlet*/ if(num == 1) { std::cout << "You grab the crystal gauntlet and the skeleton"; std::cout << " hand turns to dust.\n"; std::cout << "You put it on a feel a surge of power.\n"; return 103; } if(num == 2) { std::cout << "You take the leather gauntlet and put it on.\n"; std::cout << "It smells like a sweaty dungeon.\n"; std::cout << "You begin to regret your decision.\n"; return 104; } if(num == 3) { std::cout << "You have to lift the iron gauntlet with two hands.\n"; std::cout << "It's much heavier than you thought.\n"; return 105; } if(num == 4) { std::cout << "These sorts of things are better left alone.\n"; } } /*If it's a normal item room*/ else { //CHANGE BACK TO RANDOM int random = 2;//rand() % 2 + 1; /*Reset the input int*/ num = -1; /*Choose to get a torch */ if(random == 1) { std::cout << "Your eyes burn at the sight of a bright light.\n"; std::cout << "A voice whispers from the light\n"; std::cout << "Do you want my help, human?\n"; while(num != 1 && num != 2) { std::cout << "Press 1 for yes\n"; std::cout << "Press 2 for no\n"; std::cin >> num; } if (num == 1) { std::cout << "\nGood, but I should warn you,"; std::cout <<" I'm afriad of spiders.\n"; return 102; } else { std::cout << "\nSuit yourself human.\n"; } } /*Choose to get an old key*/ else if(random == 2) { std::cout << "There is a skeleton laying face-down on the floor.\n"; std::cout << "You spot a rusty key in its ribcage.\n"; std::cout << "Do you take it?\n"; while(num != 1 && num != 2) { std::cout << "Press 1 to take the key.\n"; std::cout << "Press 2 to leave the key for someone else.\n"; std::cin >> num; } /*Get the oldKey*/ if(num == 1) { std::cout << "You reach inside the ribcage and take the key.\n"; return 106; } /*Get nothing*/ if(num ==2) { std::cout << "It's too gross.\n"; return 0; } } } }
[ "jay.steingold@gmail.com" ]
jay.steingold@gmail.com
122507c5c34a22c946f2e3bc1e9db2127b079b4d
c6c61d3090c46e6e0f975c643cd61d75083a02a3
/src/Rox74HC165.h
e3a7cb0467d1e924ff9742076b95657328a8a300
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
neroroxxx/Rox74HC165
a0603e6e8f111d52582858349de68a42a800570d
ab4604458eadd73cfdb48255eca07e69edfbda63
refs/heads/master
2022-12-16T04:57:48.586863
2020-08-18T18:57:40
2020-08-18T18:57:40
273,553,818
1
0
null
null
null
null
UTF-8
C++
false
false
3,457
h
/* https://www.RoxXxtar.com/bmc Licensed under the MIT license. See LICENSE file in the project root for full license information. Library to read one or more 74HC165 multiplexers This library will read each pin of the mux and store it in RAM It was designed and tested for PJRC Teensy boards only. Use at your own risk. */ #ifndef Rox74HC165_h #define Rox74HC165_h #include <Arduino.h> template <uint8_t _muxCount> class Rox74HC165 { private: uint8_t clkPin = 0; uint8_t loadPin = 0; uint8_t dataPin = 0; uint8_t states[_muxCount]; public: Rox74HC165(){} void begin(uint8_t t_data, uint8_t t_load, uint8_t t_clk){ if(t_clk==t_load || t_clk==t_data || t_load==t_data){ Serial.println("invalid 74HC165 pins used"); while(1); } clkPin = t_clk; loadPin = t_load; dataPin = t_data; pinMode(clkPin, OUTPUT); pinMode(loadPin, OUTPUT); pinMode(dataPin, INPUT); digitalWrite(clkPin, LOW); digitalWrite(loadPin, HIGH); } void update(){ memset(states, 0, _muxCount); digitalWrite(loadPin, LOW); delayMicroseconds(5); digitalWrite(loadPin, HIGH); for(uint8_t mux = 0; mux < _muxCount; mux++){ for(int i = 7; i >= 0; i--){ uint8_t bit = digitalRead(dataPin); bitWrite(states[mux], i, bit); digitalWrite(clkPin, HIGH); delayMicroseconds(5); digitalWrite(clkPin, LOW); } } } uint8_t read(uint8_t n){ n = constrain(n, 0, _muxCount-1); return states[n]; } // read the first 4 mux starting from the first one // if there are less than 4 mux then just returns all of them uint32_t read(){ return read(0, _muxCount-1); } // return the values of up to 4 muxes at a time uint32_t read(uint8_t first, uint8_t last){ if(_muxCount==1){ return states[0]; } if(last>=_muxCount || first>=_muxCount || first>=last){ return 0; } uint32_t x = 0; for(uint8_t i = 0, e=first; i < 4; i++, e++){ if(e>=_muxCount){ break; } x |= states[e] << (i*8); } return x; } bool readPin(uint16_t n){ return readPin((n>>3), (n&0x07)); } // return true if the pin is active bool readPin(uint8_t t_mux, uint8_t t_bit){ t_mux = constrain(t_mux, 0, (_muxCount-1)); t_bit = constrain(t_bit, 0, 7); return !bitRead(states[t_mux], t_bit); } // return all the pins of the specified mux uint8_t readPins(uint8_t t_mux){ t_mux = constrain(t_mux, 0, (_muxCount-1)); return states[t_mux]; } }; template <uint8_t _muxCount> class RoxDual74HC165 { private: Rox74HC165 <(_muxCount*2)> mux; public: RoxDual74HC165(){} void begin(uint8_t t_data, uint8_t t_load, uint8_t t_clk){ mux.begin(t_data, t_load, t_clk); } void update(){ mux.update(); } // return true if the pin is active bool readPin(uint8_t t_mux=0, uint8_t t_bit=0){ t_mux = constrain(t_mux, 0, (_muxCount-1)); t_bit = constrain(t_bit, 0, 15); if(t_bit>=8){ t_mux++; t_bit -= 8; } if(t_mux>=(_muxCount*2)){ return false; } return mux.readPin(t_mux, t_bit); } uint16_t readPins(uint16_t t_mux){ if((t_mux+1)>=(_muxCount*2)){ return 0; } return mux.readPins(t_mux) | (mux.readPins(t_mux+1)<<8); } }; #endif
[ "neroroxxx@gmail.com" ]
neroroxxx@gmail.com
b75a66bc0fd52166026c0f379b0dfed563ba9557
0bbedd0294c023b5283ca197cefdef52a78ff458
/RiplGame/RiplGame.Shared/Content/Objects/World/Landscape.cpp
0e9616d69f521514f7aa4a80a8018505f4abeb0d
[]
no_license
michaeman/RiplGame
2b24cb3892991642ba111558501d803859307ada
02bb79335bc0aeb423445959a43dfc68e90adf99
refs/heads/master
2021-01-21T15:07:44.168302
2014-09-23T07:38:00
2014-09-23T07:38:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,053
cpp
#include "pch.h" #include "Landscape.h" // Namespaces just spare us from having to write "RiplGame." before everything using namespace RiplGame; using namespace DirectX; using namespace Windows::Foundation; // Loads vertex and pixel shaders from files and instantiates the cube geometry. // NOTE: This uses initialiser list syntax, essentially each part is initialised using the initialiser for that type. // DeviceResources uses a couple of initialisers to complete its initialisation, hence the braces. Landscape::Landscape(unsigned short sideLengthZ, unsigned short sideLengthX) { fillVertices(sideLengthZ, sideLengthX, this->vertices, XMFLOAT3(1.0f,1.0f,1.0f)); fillIndices(sideLengthZ, sideLengthX, this->indices); } // Fills a vertex array for a rectangular landscape void Landscape::fillVertices(unsigned short sideLengthZ, unsigned short sideLengthX, std::vector <VertexPositionNormalColour> vertices, XMFLOAT3 colour) { float zPos; float xPos; for (unsigned short z = 0; z < sideLengthZ; z++) { zPos = z - float(sideLengthZ)/2; for (unsigned short x = 0; x < sideLengthX; x++) { xPos = x - float(sideLengthZ)/2; XMFLOAT3 vPosition = XMFLOAT3(xPos, 0.0f, zPos); XMFLOAT3 vNormal = XMFLOAT3(0.0f, 0.0f, 0.0f); XMFLOAT3 vColour = colour; vertices.push_back(VertexPositionNormalColour(vPosition, vNormal, vColour)); } } } // Fills an index array for a rectangular landscape void Landscape::fillIndices(unsigned short sideLengthZ, unsigned short sideLengthX, unsigned short* indices) { sideLengthZ--; sideLengthX--; unsigned int arrayLength = sideLengthZ * sideLengthX * 6; indices = (unsigned short*)malloc(arrayLength *sizeof(unsigned short)); int x = 0; int row; for (unsigned short z = 0; z < arrayLength; z += 6) { indices[z] = x; indices[z + 1] = sideLengthX + x + 1; indices[z + 2] = sideLengthX + x + 2; indices[z + 3] = x; indices[z + 4] = sideLengthX + x + 2; indices[z + 5] = x + 1; x++; row = (z / 6) / (sideLengthX + 1) + 1; if (x + 1 - row * (sideLengthX + 1) == 0) x++; } }
[ "imadedend@gmail.com" ]
imadedend@gmail.com
8d1f820e92ca638bbca3ee272248d702976c4147
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/chrome/browser/supervised_user/legacy/supervised_user_refresh_token_fetcher.cc
0c8345493b7f2e4c753447736c14214c893adcf6
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
12,827
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/supervised_user/legacy/supervised_user_refresh_token_fetcher.h" #include "base/callback.h" #include "base/json/json_reader.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/values.h" #include "components/data_use_measurement/core/data_use_user_data.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/gaia_oauth_client.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/google_service_auth_error.h" #include "google_apis/gaia/oauth2_api_call_flow.h" #include "google_apis/gaia/oauth2_token_service.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/http/http_status_code.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request_status.h" using GaiaConstants::kChromeSyncSupervisedOAuth2Scope; using base::Time; using gaia::GaiaOAuthClient; using net::URLFetcher; using net::URLFetcherDelegate; using net::URLRequestContextGetter; namespace { const int kNumRetries = 1; static const char kIssueTokenBodyFormat[] = "client_id=%s" "&scope=%s" "&response_type=code" "&profile_id=%s" "&device_name=%s"; // kIssueTokenBodyFormatDeviceIdAddendum is appended to kIssueTokenBodyFormat // if device_id is provided. // TODO(pavely): lib_ver is passed to differentiate IssueToken requests from // different code locations. Remove once device_id mismatch is understood. // (crbug.com/481596) static const char kIssueTokenBodyFormatDeviceIdAddendum[] = "&device_id=%s&lib_ver=supervised_user"; static const char kAuthorizationHeaderFormat[] = "Authorization: Bearer %s"; static const char kCodeKey[] = "code"; class SupervisedUserRefreshTokenFetcherImpl : public SupervisedUserRefreshTokenFetcher, public OAuth2TokenService::Consumer, public URLFetcherDelegate, public GaiaOAuthClient::Delegate { public: SupervisedUserRefreshTokenFetcherImpl( OAuth2TokenService* oauth2_token_service, const std::string& account_id, const std::string& device_id, URLRequestContextGetter* context); ~SupervisedUserRefreshTokenFetcherImpl() override; // SupervisedUserRefreshTokenFetcher implementation: void Start(const std::string& supervised_user_id, const std::string& device_name, const TokenCallback& callback) override; protected: // OAuth2TokenService::Consumer implementation: void OnGetTokenSuccess(const OAuth2TokenService::Request* request, const std::string& access_token, const Time& expiration_time) override; void OnGetTokenFailure(const OAuth2TokenService::Request* request, const GoogleServiceAuthError& error) override; // net::URLFetcherDelegate implementation. void OnURLFetchComplete(const URLFetcher* source) override; // GaiaOAuthClient::Delegate implementation: void OnGetTokensResponse(const std::string& refresh_token, const std::string& access_token, int expires_in_seconds) override; void OnRefreshTokenResponse(const std::string& access_token, int expires_in_seconds) override; void OnOAuthError() override; void OnNetworkError(int response_code) override; private: // Requests an access token, which is the first thing we need. This is where // we restart when the returned access token has expired. void StartFetching(); void DispatchNetworkError(int error_code); void DispatchGoogleServiceAuthError(const GoogleServiceAuthError& error, const std::string& token); OAuth2TokenService* oauth2_token_service_; std::string account_id_; std::string device_id_; URLRequestContextGetter* context_; std::string device_name_; std::string supervised_user_id_; TokenCallback callback_; std::unique_ptr<OAuth2TokenService::Request> access_token_request_; std::string access_token_; bool access_token_expired_; std::unique_ptr<URLFetcher> url_fetcher_; std::unique_ptr<GaiaOAuthClient> gaia_oauth_client_; }; SupervisedUserRefreshTokenFetcherImpl::SupervisedUserRefreshTokenFetcherImpl( OAuth2TokenService* oauth2_token_service, const std::string& account_id, const std::string& device_id, URLRequestContextGetter* context) : OAuth2TokenService::Consumer("supervised_user"), oauth2_token_service_(oauth2_token_service), account_id_(account_id), device_id_(device_id), context_(context), access_token_expired_(false) {} SupervisedUserRefreshTokenFetcherImpl:: ~SupervisedUserRefreshTokenFetcherImpl() {} void SupervisedUserRefreshTokenFetcherImpl::Start( const std::string& supervised_user_id, const std::string& device_name, const TokenCallback& callback) { DCHECK(callback_.is_null()); supervised_user_id_ = supervised_user_id; device_name_ = device_name; callback_ = callback; StartFetching(); } void SupervisedUserRefreshTokenFetcherImpl::StartFetching() { OAuth2TokenService::ScopeSet scopes; scopes.insert(GaiaConstants::kOAuth1LoginScope); access_token_request_ = oauth2_token_service_->StartRequest( account_id_, scopes, this); } void SupervisedUserRefreshTokenFetcherImpl::OnGetTokenSuccess( const OAuth2TokenService::Request* request, const std::string& access_token, const Time& expiration_time) { DCHECK_EQ(access_token_request_.get(), request); access_token_ = access_token; GURL url(GaiaUrls::GetInstance()->oauth2_issue_token_url()); // GaiaOAuthClient uses id 0, so we use 1 to distinguish the requests in // unit tests. const int id = 1; net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation( "supervised_user_refresh_token_fetcher", R"( semantics { sender: "Supervised Users" description: "Fetches an OAuth2 refresh token scoped down to the Supervised " "User Sync scope and tied to the given Supervised User ID, " "identifying the Supervised User Profile to be created." trigger: "Called when creating a new Supervised User profile in Chromium " "to fetch OAuth credentials for using Sync with the new profile." data: "The request is authenticated with an OAuth2 access token " "identifying the Google account and contains the following " "information:\n* The Supervised User ID, a randomly generated " "64-bit identifier for the profile.\n* The device name, to " "identify the refresh token in account management." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can disable this feature by toggling 'Let anyone add a " "person to Chrome' in Chromium settings, under People." chrome_policy { SupervisedUserCreationEnabled { policy_options {mode: MANDATORY} SupervisedUserCreationEnabled: false } } })"); url_fetcher_ = URLFetcher::Create(id, url, URLFetcher::POST, this, traffic_annotation); data_use_measurement::DataUseUserData::AttachToFetcher( url_fetcher_.get(), data_use_measurement::DataUseUserData::SUPERVISED_USER); url_fetcher_->SetRequestContext(context_); url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); url_fetcher_->SetAutomaticallyRetryOnNetworkChanges(kNumRetries); url_fetcher_->AddExtraRequestHeader( base::StringPrintf(kAuthorizationHeaderFormat, access_token.c_str())); std::string body = base::StringPrintf( kIssueTokenBodyFormat, net::EscapeUrlEncodedData( GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true).c_str(), net::EscapeUrlEncodedData(kChromeSyncSupervisedOAuth2Scope, true).c_str(), net::EscapeUrlEncodedData(supervised_user_id_, true).c_str(), net::EscapeUrlEncodedData(device_name_, true).c_str()); if (!device_id_.empty()) { body.append(base::StringPrintf( kIssueTokenBodyFormatDeviceIdAddendum, net::EscapeUrlEncodedData(device_id_, true).c_str())); } url_fetcher_->SetUploadData("application/x-www-form-urlencoded", body); url_fetcher_->Start(); } void SupervisedUserRefreshTokenFetcherImpl::OnGetTokenFailure( const OAuth2TokenService::Request* request, const GoogleServiceAuthError& error) { DCHECK_EQ(access_token_request_.get(), request); callback_.Run(error, std::string()); callback_.Reset(); } void SupervisedUserRefreshTokenFetcherImpl::OnURLFetchComplete( const URLFetcher* source) { const net::URLRequestStatus& status = source->GetStatus(); if (!status.is_success()) { DispatchNetworkError(status.error()); return; } int response_code = source->GetResponseCode(); if (response_code == net::HTTP_UNAUTHORIZED && !access_token_expired_) { access_token_expired_ = true; oauth2_token_service_->InvalidateAccessToken( account_id_, OAuth2TokenService::ScopeSet(), access_token_); StartFetching(); return; } if (response_code != net::HTTP_OK) { // TODO(bauerb): We should return the HTTP response code somehow. DLOG(WARNING) << "HTTP error " << response_code; DispatchGoogleServiceAuthError( GoogleServiceAuthError(GoogleServiceAuthError::CONNECTION_FAILED), std::string()); return; } std::string response_body; source->GetResponseAsString(&response_body); std::unique_ptr<base::Value> value = base::JSONReader::Read(response_body); base::DictionaryValue* dict = NULL; if (!value.get() || !value->GetAsDictionary(&dict)) { DispatchNetworkError(net::ERR_INVALID_RESPONSE); return; } std::string auth_code; if (!dict->GetString(kCodeKey, &auth_code)) { DispatchNetworkError(net::ERR_INVALID_RESPONSE); return; } gaia::OAuthClientInfo client_info; GaiaUrls* urls = GaiaUrls::GetInstance(); client_info.client_id = urls->oauth2_chrome_client_id(); client_info.client_secret = urls->oauth2_chrome_client_secret(); gaia_oauth_client_.reset(new gaia::GaiaOAuthClient(context_)); gaia_oauth_client_->GetTokensFromAuthCode(client_info, auth_code, kNumRetries, this); } void SupervisedUserRefreshTokenFetcherImpl::OnGetTokensResponse( const std::string& refresh_token, const std::string& access_token, int expires_in_seconds) { // TODO(bauerb): It would be nice if we could pass the access token as well, // so we don't need to fetch another one immediately. DispatchGoogleServiceAuthError(GoogleServiceAuthError::AuthErrorNone(), refresh_token); } void SupervisedUserRefreshTokenFetcherImpl::OnRefreshTokenResponse( const std::string& access_token, int expires_in_seconds) { NOTREACHED(); } void SupervisedUserRefreshTokenFetcherImpl::OnOAuthError() { DispatchGoogleServiceAuthError( GoogleServiceAuthError(GoogleServiceAuthError::CONNECTION_FAILED), std::string()); } void SupervisedUserRefreshTokenFetcherImpl::OnNetworkError(int response_code) { // TODO(bauerb): We should return the HTTP response code somehow. DLOG(WARNING) << "HTTP error " << response_code; DispatchGoogleServiceAuthError( GoogleServiceAuthError(GoogleServiceAuthError::CONNECTION_FAILED), std::string()); } void SupervisedUserRefreshTokenFetcherImpl::DispatchNetworkError( int error_code) { DispatchGoogleServiceAuthError( GoogleServiceAuthError::FromConnectionError(error_code), std::string()); } void SupervisedUserRefreshTokenFetcherImpl::DispatchGoogleServiceAuthError( const GoogleServiceAuthError& error, const std::string& token) { callback_.Run(error, token); callback_.Reset(); } } // namespace // static std::unique_ptr<SupervisedUserRefreshTokenFetcher> SupervisedUserRefreshTokenFetcher::Create( OAuth2TokenService* oauth2_token_service, const std::string& account_id, const std::string& device_id, URLRequestContextGetter* context) { std::unique_ptr<SupervisedUserRefreshTokenFetcher> fetcher( new SupervisedUserRefreshTokenFetcherImpl( oauth2_token_service, account_id, device_id, context)); return fetcher; } SupervisedUserRefreshTokenFetcher::~SupervisedUserRefreshTokenFetcher() {}
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
f70787034918713989d466d19355eee325b5a99c
3474c77c4823990aa3884bb83c9e8b742cfcf0f4
/src/xsix/actor/actor_message.h
99d0d7e23c24ab79738f2bb57c471d2427e78f8a
[]
no_license
SixDayCoder/xsix
fb775e5c3e514c5444f71142bd8a67b43cf1efe0
a0a04911e779f8edb076a01d4d6092217af0edb9
refs/heads/master
2021-06-27T00:30:29.102115
2021-06-23T08:25:43
2021-06-23T08:25:43
232,528,170
0
0
null
null
null
null
UTF-8
C++
false
false
332
h
#pragma once #include "xsix/common_define.h" #include <memory> namespace xsix { class ActorBase; class IActorMessage; using ActorMsgPtr = std::shared_ptr<IActorMessage>; class IActorMessage { public: virtual std::string get_name() const = 0; virtual void handle_msg(ActorBase& actor) = 0; }; }
[ "sixdaycoder@gmail.com" ]
sixdaycoder@gmail.com
ee1758c43e7a5d4e0b39360b996c75a75a64b3cf
e2bb8568b21bb305de3b896cf81786650b1a11f9
/SDK/SCUM_Camo_Backpack_04_classes.hpp
863ac9452ae0ea8ec5a8cef882a262e22940a1d0
[]
no_license
Buttars/SCUM-SDK
822e03fe04c30e04df0ba2cb4406fe2c18a6228e
954f0ab521b66577097a231dab2bdc1dd35861d3
refs/heads/master
2020-03-28T02:45:14.719920
2018-09-05T17:53:23
2018-09-05T17:53:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
677
hpp
#pragma once // SCUM (0.1.17) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SCUM_Camo_Backpack_04_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Camo_Backpack_04.Camo_Backpack_04_C // 0x0000 (0x0800 - 0x0800) class ACamo_Backpack_04_C : public AClothesItem { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass Camo_Backpack_04.Camo_Backpack_04_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
2ce78bfcead308da3ed2c9f90e1dc086cd7cb79d
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/webkit/browser/database/databases_table.h
4a20ec11871cd62171d401ff75d0e32b82a6ce7f
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
1,798
h
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBKIT_BROWSER_DATABASE_DATABASES_TABLE_H_ #define WEBKIT_BROWSER_DATABASE_DATABASES_TABLE_H_ #include <vector> #include "base/strings/string16.h" #include "webkit/browser/webkit_storage_browser_export.h" namespace sql { class Connection; } namespace webkit_database { struct WEBKIT_STORAGE_BROWSER_EXPORT_PRIVATE DatabaseDetails { DatabaseDetails(); ~DatabaseDetails(); std::string origin_identifier; base::string16 database_name; base::string16 description; int64 estimated_size; }; class WEBKIT_STORAGE_BROWSER_EXPORT_PRIVATE DatabasesTable { public: explicit DatabasesTable(sql::Connection* db) : db_(db) { } bool Init(); int64 GetDatabaseID(const std::string& origin_identifier, const base::string16& database_name); bool GetDatabaseDetails(const std::string& origin_identifier, const base::string16& database_name, DatabaseDetails* details); bool InsertDatabaseDetails(const DatabaseDetails& details); bool UpdateDatabaseDetails(const DatabaseDetails& details); bool DeleteDatabaseDetails(const std::string& origin_identifier, const base::string16& database_name); bool GetAllOriginIdentifiers(std::vector<std::string>* origin_identifiers); bool GetAllDatabaseDetailsForOriginIdentifier( const std::string& origin_identifier, std::vector<DatabaseDetails>* details); bool DeleteOriginIdentifier(const std::string& origin_identifier); private: sql::Connection* db_; }; } // namespace webkit_database #endif // WEBKIT_BROWSER_DATABASE_DATABASES_TABLE_H_
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
41dd807e919440cf2c79687adb0b6800ab20d93c
6442a4dc1026b6861d042c3a32d8c10c1a9f55b0
/include/GameObject.hpp
1adf7d6d8182c4ddf883b337724eb3b2196c5cf7
[]
no_license
TechniMan/learn-opengl
af33511d8263f6c68bfaff61ac8dacdd34ae7d2f
71fee27be2b1d4310659b908c3cacf021122d84b
refs/heads/master
2022-07-29T14:11:09.927786
2020-05-15T19:54:11
2020-05-15T19:54:11
264,286,008
0
0
null
null
null
null
UTF-8
C++
false
false
1,023
hpp
#ifndef _GAMEOBJECT_HPP_ #define _GAMEOBJECT_HPP_ #include <vector> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/vec3.hpp> #include <glm/mat4x4.hpp> class GameObject { private: GLuint m_shaderId; GLuint m_vaoId; std::vector<GLfloat> m_vertices; std::vector<GLuint> m_indices; glm::vec3 m_position; glm::vec3 m_rotation; glm::vec3 m_scale; bool m_useIndices = false; public: GameObject(std::vector<GLfloat>& vertices); GameObject(std::vector<GLfloat>& vertices, std::vector<GLuint>& indices); void SetShader(GLuint& shaderId) noexcept; void SetPosition(glm::vec3& position) noexcept; void OffsetPosition(glm::vec3& posOffset) noexcept; void SetRotation(glm::vec3& rotation) noexcept; void OffsetRotation(glm::vec3& rotOffset) noexcept; void SetScale(glm::vec3& scale) noexcept; void OffsetScale(glm::vec3& sclOffset) noexcept; glm::mat4 GetTransform(void) const noexcept; void Render(void) const; }; #endif //_GAMEOBJECT_HPP_
[ "technimanx@googlemail.com" ]
technimanx@googlemail.com
45056063aef30979345228c92bd846195ccaf149
a3a90043a4586a31c5887a65a17c250cb969685c
/GRAPH/Adjacency Matrix/number-islands-gfg.cpp
44ded9bf9fbf01aa382716447fbec295a651ee46
[]
no_license
SuryankDixit/Problem-Solving
b400caf5a28ad378339ab823f017a3fe430fc301
931e33ad5ec6d4fec587cbffd968872f7785dc58
refs/heads/master
2023-08-12T05:11:00.241191
2021-10-13T08:11:12
2021-10-13T08:11:12
207,796,551
9
2
null
null
null
null
UTF-8
C++
false
false
1,202
cpp
#include<bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: int dx[8]={-1,-1,-1,0,0,1,1,1}; int dy[8]={-1,0,1,-1,1,-1,0,1}; void dfs(int i,int j,vector<vector<char>> &v){ if(i<0||j<0||i>=v.size()||j>=v[0].size()){ return; } if(v[i][j]!='1'){ return; } v[i][j]='0'; for(int x=0;x<8;x++){ dfs(i+dx[x],j+dy[x],v); } return; } int numIslands(vector<vector<char>>& v) { int n=v.size(); int n1=v[0].size(); int cnt=0; for(int i=0;i<n;i++){ for(int j=0;j<n1;j++){ if(v[i][j]=='1'){ cnt++; dfs(i,j,v); } } } return cnt; } }; // { Driver Code Starts. int main(){ int tc; cin >> tc; while(tc--){ int n, m; cin >> n >> m; vector<vector<char>>grid(n, vector<char>(m, '#')); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> grid[i][j]; } } Solution obj; int ans = obj.numIslands(grid); cout << ans <<'\n'; } return 0; } // } Driver Code Ends
[ "suryankdixit@gmail.com" ]
suryankdixit@gmail.com
d351846cf21cf8223e66d9e99e9986bd8fe0c705
ae04de28ac499e56988c13f306ba7d5f065584a9
/src/ripple/sitefiles/api/SiteFile.h
d7741dc3b2e9ff2d4d299c996164a5f584fb83fe
[ "ISC", "MIT-Wu", "MIT", "BSL-1.0" ]
permissive
russell-childs/rippled
6fc19073a880ef979011b00965d00b18c6168c7a
3eb1c7bd6f93e5d874192197f76571184338f702
refs/heads/master
2020-12-11T04:23:47.745279
2014-05-05T17:20:46
2014-05-05T17:20:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,787
h
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef RIPPLE_SITEFILES_SITEFILE_H_INCLUDED #define RIPPLE_SITEFILES_SITEFILE_H_INCLUDED #include "Section.h" #include "../../common/UnorderedMap.h" #include <string> #include <unordered_map> namespace ripple { namespace SiteFiles { class SiteFile { public: SiteFile (int = 0); // dummy argument for emplace typedef ripple::unordered_map <std::string, Section> SectionsType; /** Retrieve a section by name. */ /** @{ */ Section const& get (std::string const& name) const; Section const& operator[] (std::string const& key) const; /** @} */ /** Retrieve or create a section with the specified name. */ Section& insert (std::string const& name); private: SectionsType m_sections; }; } } #endif
[ "vinnie.falco@gmail.com" ]
vinnie.falco@gmail.com
4a033dc84b63e9025a31fb63fc64dbf14bb64491
19f3f327828fdab68302645762dac75e0bc85fed
/R-Type/V0.53/src/physiqueManager.cpp
7437f857049bafd70a5abf4812ffa2d218350fd6
[]
no_license
Laoup/C-_R-Type
8414a6b176870819349ae0f95d85a6404c962b88
69fe149b614df377c9ddbbb7230ac16b44b1a013
refs/heads/master
2020-04-01T09:56:27.089651
2019-03-29T08:39:47
2019-03-29T08:39:47
153,096,038
0
0
null
null
null
null
UTF-8
C++
false
false
10,632
cpp
#include "../include/element.hh" #include "../include/ennemy.hh" #include "../include/physiqueManager.hh" physiqueManager::physiqueManager() { } physiqueManager::~physiqueManager() { } void physiqueManager::moveEnnemy(std::shared_ptr<ship> ennemy) { STRATEGY st; int x; int y; st = ennemy->getStrategy(); if (st == STRATEGY::DEFAULT) ennemy->getDrawable().move(-1 * SPEED, 0); else if (st == STRATEGY::BOSS) { y = ennemy->getDrawable().getPosition().y; if (y > 375) ennemy->setMemorie(false); else if (y < 125) ennemy->setMemorie(true); if (ennemy->getMemorie() == false) ennemy->getDrawable().move(0, -1 * SPEED); if (ennemy->getMemorie() == true) ennemy->getDrawable().move(0, SPEED); } } void physiqueManager::moveObjectVector(std::vector<std::shared_ptr<object>> vec) { DIRECTION direct; int i; i = 0; while (i != vec.size()) { direct = vec[i]->getDirection(); if (direct == DIRECTION::LEFT) vec[i]->getDrawable().move(-1 * (SPEED * 3), 0); else if (direct == DIRECTION::RIGHT) vec[i]->getDrawable().move(SPEED * 3, 0); i++; } } void physiqueManager::checkCollision(std::shared_ptr<element> player, std::shared_ptr<element> ennemy, std::vector<std::shared_ptr<object>> &objs, std::shared_ptr<handlerSprite> sprite_manager) { std::array<float, 4> position_p; std::array<float, 4> position_e; //object *n_obj; std::shared_ptr<object> n_obj; position_p = player->getPositionVector(); position_e = ennemy->getPositionVector(); /*if (position_e[0] - position_e[3] > (position_p[0] + position_p[3]) || position_e[0] + position_e[3] < (position_p[0] - position_p[3]) || position_p[1] - (position_p[3] / 2) > position_e[1] + (position_e[3] / 2) || position_p[1] + (position_p[3] / 2) < position_e[1] - (position_e[3] / 2) || player->getOut() == 1 || ennemy->getOut() == 1 || player->getSolid() == false || ennemy->getSolid() == false) ;*/ //printf("\n\nPlayer -> vec.x = %f, vec.y = %f , height = %f\n", position_p[0], position_p[1], position_p[3]); //printf("Ennemy -> vec.x = %f, vec.y = %f, height = %f\n\n", position_e[0], position_e[1], position_e[3]); if (position_e[0] > (position_p[0] + position_p[2] - 10) || (position_e[1] + position_e[3] - 15) < position_p[1] || position_e[1] > (position_p[1] + position_p[3] - 10) || (position_e[0] + position_e[2] - 10) < position_p[0] || player->getOut() == 1 || ennemy->getOut() == 1 || player->getSolid() == false || ennemy->getSolid() == false) ; else { player->takeDamage(); ennemy->takeDamage(); if (player->getLifePoints() == 0) player->setOut(1); if (ennemy->getLifePoints() == 0) ennemy->setOut(1); printf("BOOOOOOOOOUM!!!!!!!!!!!!!!"); n_obj = std::make_shared<object> (sprite_manager, TYPE::EXPLOSION); //n_obj = new object(sprite_manager, TYPE::EXPLOSION); n_obj->getDrawable().setPosition(ennemy->getDrawable().getPosition().x, ennemy->getDrawable().getPosition().y); //objs.push_back(n_obj); objs.push_back(std::move(n_obj)); //FUTURE IMPLEMENTATION DES OBJETS ! /*n_obj = new object(TYPE::SHIELD); n_obj->setPosition(ennemy->getPosition().x - 75, ennemy->getPosition().y); objs.push_back(n_obj);*/ //printf("here player position x %f, and position y %f\n", position_p.x, position_p.y); } } void physiqueManager::checkBorderCollision(std::shared_ptr<element> player, view &v) { std::array<float, 4> pos; pos = player->getPositionVector(); if (player->getLimitedLeft() == true) { if (pos[0] - v.getLeftSidePos() < 50) player->setOut(1); else if (pos[1] - v.getUpSidePos() < 100) player->setOut(1); else if (pos[1] > v.getDownSidePos() - 100) player->setOut(1); } if (player->getLimitedRight() == true) { if (pos[0] > v.getRightSidePos() - 50) player->setOut(1); else if (pos[1] - v.getUpSidePos() < 100) player->setOut(1); else if (pos[1] > v.getDownSidePos() - 100) player->setOut(1); } } std::shared_ptr<object> physiqueManager::fireOrder(std::shared_ptr<ship> ship, DIRECTION direction) { return (ship->fireing(direction)); } void physiqueManager::TileTheMap(int xSizeWindow, int xSizeBackground, std::array<int, 3> &arr) { int ref; int count; count = 0; ref = xSizeWindow / 2; arr[2] = 0; if ((2 * ref) >= xSizeBackground) { arr[0] = -1; arr[1] = -1; } while (xSizeBackground >= ref) { xSizeBackground = xSizeBackground - ref; count = count + 1; } arr[0] = ref; arr[1] = count; } //Clairement des choses a revoir sur cette fonction ! void physiqueManager::generateEnnemys(int posSide, std::array<int, 3> &arr, std::vector<std::shared_ptr<ship>> &ships, int xSizeBackground, int xSizeWindow, std::shared_ptr<handlerSprite> sprite_manager) { int count; float stock; std::vector<std::shared_ptr<ship>>::iterator it; std::shared_ptr<ship> n_ship; bool boss; if (posSide + (X_SIZE_WINDOW / 2) < xSizeBackground - xSizeWindow) { count = 0; stock = 0; while (posSide >= stock) { count = count + 1; stock = (X_SIZE_WINDOW / 2) * count; } if (count != arr[2]) { this->createWaveEnnemys(posSide, arr, ships, sprite_manager); arr[2] = count; } } else { boss = false; it = ships.begin(); while (it != ships.end()) { if ((*it)->getBoss() == true) boss = true; it++; } if (boss == false) { n_ship = std::make_shared<ennemy> (sprite_manager, 3, STRATEGY::BOSS, 155, 166); ships.push_back(std::move(n_ship)); //ships.push_back(new ennemy(sprite_manager, 3, STRATEGY::BOSS, 155, 166)); it = ships.end() - 1; (*it)->setLifePoints(5); (*it)->promote(); //(*it)->setImortal(true); (*it)->getDrawable().setPosition(xSizeBackground - 155, 250);//+155 = largeur de l'ennemi (*it)->getDrawable().setRotation(90); } } } void physiqueManager::createWaveEnnemys(int posSide, std::array<int, 3> &arr, std::vector<std::shared_ptr<ship>> &ships, std::shared_ptr<handlerSprite> sprite_manager) { std::vector<std::shared_ptr<ship>>::iterator it; std::shared_ptr<ship> n_ship; int random_nb; int tmp; srand(time(NULL)); random_nb = (rand() % 8) + 1; tmp = random_nb; while (tmp != 0) { n_ship = std::make_shared<ennemy> (sprite_manager); ships.push_back(std::move(n_ship)); //ships.push_back(new ennemy(sprite_manager)); tmp = tmp - 1; } it = ships.end() - 1; if (random_nb == 1) (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,250); else if (random_nb == 2) { (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,175); it = ships.end() - 2; (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,325); } else if (random_nb == 3) { (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,125); it = ships.end() - 2; (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,425); it = ships.end() - 3; (*it)->getDrawable().setPosition(posSide + (arr[0] / 4) ,225); } else if (random_nb == 4) { (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,125); it = ships.end() - 2; (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,400); it = ships.end() - 3; (*it)->getDrawable().setPosition(posSide + (arr[0] / 4) ,225); it = ships.end() - 4; (*it)->getDrawable().setPosition(posSide + (arr[0] / 3) ,525); } else if (random_nb == 5) { (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,125); it = ships.end() - 2; (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,425); it = ships.end() - 3; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.9) , 150); it = ships.end() - 4; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.75) ,525); it = ships.end() - 5; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.75) ,250); } else if (random_nb == 6) { (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,125); it = ships.end() - 2; (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) ,425); it = ships.end() - 3; (*it)->getDrawable().setPosition(posSide + (arr[0] / 2) ,225); it = ships.end() - 4; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.75) ,100); it = ships.end() - 5; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.15) ,400); it = ships.end() - 6; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.75) ,200); } else if (random_nb == 7) { (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) , 50); it = ships.end() - 2; (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) , 550); it = ships.end() - 3; (*it)->getDrawable().setPosition(posSide + (arr[0] / 2) , 150); it = ships.end() - 4; (*it)->getDrawable().setPosition(posSide + (arr[0] / 2) , 450); it = ships.end() - 5; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.75) , 275); it = ships.end() - 6; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.75) , 375); it = ships.end() - 7; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.15) , 325); } else if (random_nb == 8) { (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) , 250); it = ships.end() - 2; (*it)->getDrawable().setPosition(posSide + (arr[0] / 6) , 450); it = ships.end() - 3; (*it)->getDrawable().setPosition(posSide + (arr[0] / 2) , 525); it = ships.end() - 4; (*it)->getDrawable().setPosition(posSide + (arr[0] / 2.5) , 150); it = ships.end() - 5; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.85) , 475); it = ships.end() - 6; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.65) , 375); it = ships.end() - 7; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.45) , 275); it = ships.end() - 8; (*it)->getDrawable().setPosition(posSide + (arr[0] / 0.25) , 100); } }
[ "korvin.meurice@gmail.com" ]
korvin.meurice@gmail.com
ad1d604248a16e0f4d9459c484d4c28ff3ecb335
b1e8ed1a1d10dc9d949d03397bafd74e5d97197f
/game_manager.h
b30ff1993707dd594c984e8f1c42b605072e3142
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
adan830/cheese-engine
4b0c408d0817dcaa6db6218ff83f14f16b1aefb7
7468c6710678a58c4b60ff7395a3f7b02f9b9154
refs/heads/master
2020-03-24T06:21:12.201454
2018-07-23T05:25:28
2018-07-23T05:25:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,746
h
/* Copyright (c) 2012 Cheese and Bacon Games, LLC */ /* This file is licensed under the MIT License. */ /* See the file docs/LICENSE.txt for the full license text. */ #ifndef game_manager_h #define game_manager_h #include "rng.h" #include "collision.h" #include "progress_bar.h" #include "file_io.h" #include <string> #include <vector> class Game_Manager{ private: static bool disallow_title; public: static bool display_scoreboard; //If true, a game is currently in progress //If false, a game is not in progress static bool in_progress; //If true, the game is paused //If false, the game is not paused static bool paused; //Current movement state of the camera static std::string cam_state; static double camera_delta_x; static double camera_delta_y; static double camera_speed; static double camera_zoom; static std::string current_music; //Holds a string representing each command that is currently in the on state, and is relevant for networking //This is updated each frame static std::vector<std::string> command_states; static Collision_Rect<double> camera; static void reset(); static void reset_camera_dimensions(); static std::string get_random_direction_cardinal(RNG& rng); static std::string get_random_direction_cardinal_ordinal(RNG& rng); static void on_startup(); //Returns true if the number of effects does not exceed the effect limit static bool effect_allowed(); static void manage_music(); static void toggle_pause(); //Once this is called, title loading/unloading/rendering will stop //This is used when unloading the engine static void done_with_title(); //Undoes the effect of done_with_title() //done_with_title() is really needed for when the engine is shutting down //However, it is used when unloading the engine, which also happens when changing mods //Thus, we have this function to reactivate the title system static void need_title_again(); static bool is_title_allowed(); static void start(); static void start_server_lockstep(); static void start_client(); static void stop(); static void center_camera(const Collision_Rect<double>& box); static void center_camera(const Collision_Circ<double>& circle); static void zoom_camera_in(const Collision_Rect<double>& box); static void zoom_camera_in(const Collision_Circ<double>& circle); static void zoom_camera_out(const Collision_Rect<double>& box); static void zoom_camera_out(const Collision_Circ<double>& circle); static void prepare_for_input(); static void handle_command_states_multiplayer(); static void handle_game_commands_multiplayer(); static void handle_input_states_gui(); static void handle_input_states(); static bool handle_game_command_gui(std::string command_name); static bool handle_game_command(std::string command_name); static bool handle_input_events_gui(); static bool handle_input_events(); static void set_camera(); static void handle_drag_and_drop(std::string file); static std::string get_game_window_caption(); static void clear_title(); static void setup_title(); static void update_title_background(); static void render_title_background(); static void render_scoreboard(); static void render_pause(); static void render_fps(int render_rate,double ms_per_frame,int logic_frame_rate); static void render_loading_screen(const Progress_Bar& bar,std::string message); static void load_data_game(Progress_Bar& bar); static void load_data_tag_game(std::string tag,File_IO_Load* load); static void unload_data_game(); }; #endif
[ "darkoppressor@gmail.com" ]
darkoppressor@gmail.com
db54faebe73074a839bd7e4d9c3d1f840b57d3b5
da269f65f88ef5d3bf5503695b6983aeff0cda19
/reboot-core/sources/Water.h
fa1a2c1f622dfba634dac75199cd65e917be6d80
[]
no_license
EvilWar/prj-reboot
144e27df6c56ab7da07650ff201bfb3701c27811
5dfef3492718b7b124a8d79ad87a800a19419385
refs/heads/master
2021-01-23T20:12:33.667289
2015-07-07T05:31:08
2015-07-07T05:31:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
649
h
#ifndef __WATER_H__ #define __WATER_H__ #include <iosfwd> #include <OgreSharedPtr.h> #include <OgrePrerequisites.h> namespace Hydrax{ class Hydrax; } using std::string; namespace reboot { class Water { public: Water(Ogre::SceneManager* scenemgr, Ogre::Camera* camera); void SetCamara(Ogre::Camera* camera); void SetViewport(Ogre::Viewport* viewport); void EnableHydrax(bool bHydrax); void Initialize(); void Update(const Ogre::Real timeSinceLastUpdate); private: bool m_bUseHydrax; Hydrax::Hydrax* m_hydrax; Ogre::Camera* m_camera; Ogre::Viewport* m_viewport; Ogre::SceneManager* m_scenemgr; }; } #endif
[ "swoorupj@gmail.com" ]
swoorupj@gmail.com
738d023dbd8d1ce507727acace5353fe28522fae
eb80296e7c74cf2ea3f2f06a144e1818cd367a56
/textshredder_core/libraries/network/models/setaliaspacket.cpp
98ac193b8ca721130851b707f93dcfcc5abb2cbc
[]
no_license
mitchelkuijpers/TextShredder
6d2ef5cef0ea6862eb70f7bd518d433c62ce38fc
742128cc810234bef791f82795ecc1cd7f013127
refs/heads/master
2020-08-10T14:51:40.529529
2011-06-14T12:56:02
2011-06-14T12:56:02
1,576,419
5
2
null
null
null
null
UTF-8
C++
false
false
215
cpp
#include "setaliaspacket.h" SetAliasPacket::SetAliasPacket(QObject *parent, QString alias) : TextShredderPacket(parent, kPacketTypeSetAlias) { QByteArray bytes; bytes.append(alias); this->setContent(bytes); }
[ "mstijlaart@gmail.com" ]
mstijlaart@gmail.com
117e118eb1fd710829ed6a502720370430e3b777
fe4a83e11a123a26c8a3e6a07bfe7d45d4099ab0
/Classes/GameBaseScene.cpp
b8128fd4b9ad1b60c301d7cf8d28d2ab7e3c5719
[]
no_license
Quanheng/RicherGame
7c9359f15930ecbd4f738ee16dfc11aebfd3d073
13c65a9a50d8cedd0791769b8b4a013470cd9738
refs/heads/master
2021-01-10T16:06:17.851709
2015-06-14T13:51:01
2015-06-14T13:51:01
36,113,554
1
0
null
null
null
null
GB18030
C++
false
false
54,963
cpp
#include "GameBaseScene.h" USING_NS_CC; //static 变量在类外初始化 int GameBaseLayer::tiledColsCount; int GameBaseLayer::tiledRowsCount; bool** GameBaseLayer::canPassGrid; Vector<RicherPlayer*> GameBaseLayer::players_vector; Vector<Sprite*> GameBaseLayer::pathMarkVector; TMXLayer* GameBaseLayer::landLayer; TMXLayer* GameBaseLayer::wayLayer; TMXTiledMap* GameBaseLayer::_map; int GameBaseLayer::blank_land_tiledID; int GameBaseLayer::strength_30_tiledID; int GameBaseLayer::strength_50_tiledID; int GameBaseLayer::strength_80_tiledID; int GameBaseLayer::randomEvent_tiledID; int GameBaseLayer::lottery_tiledID; int GameBaseLayer::stock_tiledID; int GameBaseLayer::player1_building_1_tiledID; int GameBaseLayer::player1_building_2_tiledID; int GameBaseLayer::player1_building_3_tiledID; int GameBaseLayer::player2_building_1_tiledID; int GameBaseLayer::player2_building_2_tiledID; int GameBaseLayer::player2_building_3_tiledID; bool GameBaseLayer::init() { if(!Layer::init()) { return false; } //addMap(); //添加地图 addRightBanner(); //添加右边的表格 drawTable(2); //画表格 addDigiteRoundSprite(); //添加数字精灵 refresshRoundDisplay(); //更新回合计数 addGoButton(); //添加Go按钮 //initTiledGrid(); //初始化地图二维数组,由于每个关卡的地图大小不一样,所以这个函数在子类中实现 setWayPassToGrid(); //根据图层way,设置canPassGrid数组相应的值为true addPathMark(); //添加路径标记 addPlayer(); //添加角色 addDice(); //添加骰子 addNotificationObserver(); //添加消息接收器 gameRoundCount = 0 ; //初始化回合数 initLandLayerFromMap(); //初始化land层 //initPropTiledID(); //初始化道具ID,由于每个关卡的地图大小不一样,所以这个函数在子类中实现 particleForBuyLand(); //加载脚印精灵的动作 initRandomAskEventMap(); //初始化Map容器,存放问号随机事件 addPlayerStrengthUpAniate(); //添加体力回升的动作 initAudioEffect(); //添加音效到容器中 return true; } void GameBaseLayer::onEnter() { Layer::onEnter(); log("GameBaseLayer onEnter"); } void GameBaseLayer::onExit() { Layer::onExit(); log("GameBaseLayer onExit"); for(int i=0; i < tiledRowsCount; i++) { CC_SAFE_DELETE(canPassGrid[i]); } CC_SAFE_DELETE(canPassGrid); diceAnimate->release(); scaleBy1ForBuyLand->release(); scaleBy2ForBuyLand->release(); landFadeIn->release(); landFadeOut->release(); strengthUpAnimate->release(); players_vector.clear(); pathMarkVector.clear(); } void GameBaseLayer::addRightBanner() { auto rightBanner = Sprite::create(RIGHT_BANNER); rightBanner->setPosition(Vec2(tableStartPosition_x,0)); rightBanner->setAnchorPoint(Vec2(0,0)); this->addChild(rightBanner); } void GameBaseLayer::drawTable(int playerNumber) { auto size = Director::getInstance()->getVisibleSize(); auto draw = DrawNode::create(); this->addChild(draw); for(int i=0;i<playerNumber;i++) { draw->drawSegment(Vec2(tableStartPosition_x,tableStartPosition_y-2*i*tableHeight), Vec2(tableStartPosition_x+ 3*tableWidth,tableStartPosition_y-2*i*tableHeight), 1, Color4F(0, 1, 0, 1)); draw->drawSegment(Vec2(tableStartPosition_x,tableStartPosition_y - 2*(i+1)*tableHeight), Vec2(tableStartPosition_x+ 3*tableWidth,tableStartPosition_y - 2*(i+1)*tableHeight), 1, Color4F(0, 1, 0, 1)); draw->drawSegment(Vec2(tableStartPosition_x+ tableWidth,tableStartPosition_y - tableHeight-2*i*tableHeight), Vec2(tableStartPosition_x+ 3*tableWidth,tableStartPosition_y - tableHeight-2*i*tableHeight), 1, Color4F(0, 1, 0, 1)); draw->drawSegment(Vec2(tableStartPosition_x+ tableWidth,tableStartPosition_y -2*i*tableHeight), Vec2(tableStartPosition_x+ tableWidth,tableStartPosition_y -2* tableHeight-2*i*tableHeight), 1, Color4F(0, 1, 0, 1)); } } void GameBaseLayer::addPlayerInfo() { //////////画表格start////////// Sprite* player1_logo = Sprite::create(PLAYER_ME); player1_logo->setPosition(tableStartPosition_x+tableWidth/2,tableStartPosition_y-tableHeight); this->addChild(player1_logo); player1_money_label = Label::createWithTTF("$","fonts/arial.ttf",25); player1_money_label->setAnchorPoint(Vec2(0,0.5)); player1_money_label->setPosition(tableStartPosition_x+tableWidth,tableStartPosition_y-tableHeight/2); addChild(player1_money_label); player1_strength_label = Label::createWithTTF("+","fonts/arial.ttf",28); player1_strength_label->setAnchorPoint(Vec2(0,0.5)); player1_strength_label->setPosition(tableStartPosition_x+tableWidth,tableStartPosition_y-tableHeight/2*3); addChild(player1_strength_label); Sprite* player2_logo = Sprite::create(PLAYER_ENEMY1); player2_logo->setPosition(tableStartPosition_x+tableWidth/2,tableStartPosition_y-3*tableHeight); addChild(player2_logo); player2_money_label = Label::createWithTTF("$","fonts/arial.ttf",25); player2_money_label->setAnchorPoint(Vec2(0,0.5)); player2_money_label->setPosition(tableStartPosition_x+tableWidth,tableStartPosition_y-tableHeight/2*5); addChild(player2_money_label); player2_strength_label = Label::createWithTTF("+","fonts/arial.ttf",28); player2_strength_label->setAnchorPoint(Vec2(0,0.5)); player2_strength_label->setPosition(tableStartPosition_x+tableWidth,tableStartPosition_y-tableHeight/2*7); addChild(player2_strength_label); //////////画表格end////////// } void GameBaseLayer::addPlayer() { addPlayerInfo(); /////////添加角色到地图的随机位置//////////// //指定随机数种子,随机数依据这个种子产生 采用当前时间生成随机种子: struct timeval now; gettimeofday(&now,NULL);//计算时间种子 unsigned rand_seed =(unsigned)(now.tv_sec*1000 + now.tv_usec/1000);// 初始化随机数 srand(rand_seed); //角色1 player1 = RicherPlayer::create(PLAYER_1_NAME,PLAYER_1_TAG,false); int _rand1 =rand()%(wayLayerPass_Vector.size()); //获取一个0~容器容量之间的随机数 Vec2 vec2ForPlayer1 = wayLayerPass_Vector.at(_rand1); //这个我们给纵向位置添加一个tiledHeight高度,目的是为了让角色居中显示在道路中 vec2ForPlayer1.y +=tiledHeight; player1->setPosition(vec2ForPlayer1); player1->setAnchorPoint(Vec2(0,0.5)); char money1[20]; memset(money1,0,20); sprintf(money1,"$%d",player1->getMoney()); player1_money_label->setString(money1); //显示角色金钱 char strength1[20]; memset(strength1,0,20); sprintf(strength1,"+%d",player1->getStrength()); player1_strength_label->setString(strength1); //显示角色体力 this->addChild(player1); players_vector.pushBack(player1); //角色2 player2 = RicherPlayer::create(PLAYER_2_NAME,PLAYER_2_TAG,true); int _rand2 =rand()%(wayLayerPass_Vector.size()); //获取一个0~容器容量之间的随机数 Vec2 vec2ForPlayer2 = wayLayerPass_Vector.at(_rand2); //这个我们给纵向位置添加一个tiledHeight高度,目的是为了让角色居中显示在道路中 vec2ForPlayer2.y +=tiledHeight; player2->setPosition(vec2ForPlayer2); player2->setAnchorPoint(Vec2(0,0.5)); char money2[20]; memset(money2,0,20); sprintf(money2,"$%d",player2->getMoney()); player2_money_label->setString(money2); //显示角色金钱 char strength2[20]; memset(strength2,0,20); sprintf(strength2,"+%d",player2->getStrength()); player2_strength_label->setString(strength2); //显示角色体力 this->addChild(player2); players_vector.pushBack(player2); } void GameBaseLayer::addGoButton() { //GO按钮 goMenuItem = MenuItemImage::create(GO_BUTTON_NORMAL,GO_BUTTON_SELECTED,CC_CALLBACK_1(GameBaseLayer::goButtomCallback,this)); goMenuItem->setPosition(Vec2(tableStartPosition_x + 1.5*tableWidth,tableStartPosition_y - tableHeight * 6.5)); goMenuItem->setScale(0.8); goMenuItem->setTag(GO_MENU_ITEM_TAG); goMenuItem->setAnchorPoint(Vec2(0.5,0.5)); //技能按钮 skillMenuItem = MenuItemImage::create("images/skill_button_normal.png","images/skill_button_pressed.png",CC_CALLBACK_1(GameBaseLayer::goButtomCallback,this)); skillMenuItem->setPosition(Vec2(tableStartPosition_x + 1.5*tableWidth,tableStartPosition_y - tableHeight * 7 - goMenuItem->getContentSize().height/2 )); skillMenuItem->setScale(0.8); skillMenuItem->setTag(SKILL_MENU_ITEM_TAG); skillMenuItem->setAnchorPoint(Vec2(0.5,0.5)); menu = Menu::create(goMenuItem,skillMenuItem,NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu,1,MENU_TAG); //暴风骤雨技能显示界面 skillStorm = SkillCard::createCardSprite( LanguageString::getInstance()->getLanguageString(RAIN), LanguageString::getInstance()->getLanguageString(LOST_STRENGTH), LanguageString::getInstance()->getLanguageString(DOWN_GRADE), skillSpriteCardWidth, skillSpriteCardHeight, 150, -130, skillStormTag, "images/thunderstorm.png" ); this->addChild(skillStorm,50); //巧取豪夺显示界面 skillTransfer = SkillCard::createCardSprite( LanguageString::getInstance()->getLanguageString(YOURS_IS_MINE), LanguageString::getInstance()->getLanguageString(LOST_STRENGTH), LanguageString::getInstance()->getLanguageString(YOURS_IS_MINE_INFO), skillSpriteCardWidth, skillSpriteCardHeight, 410, -130, skillTransferTag, "images/skill_transfer.png" ); this->addChild(skillTransfer,50); //添加各个技能界面点击回调方法 skillStorm->setSkillButtonCallback(this,callfuncN_selector(GameBaseLayer::skillStormCallback)); skillTransfer->setSkillButtonCallback(this,callfuncN_selector(GameBaseLayer::skillTransferCallback)); //技能界面是否在显示 isShowSkillLayer = false; } void GameBaseLayer::setWayPassToGrid() { wayLayer = _map->getLayer("way"); //获取地图way层 Size _mapSize = wayLayer->getLayerSize(); //根据way图层,获取道路的坐标,并转换成行列值,在canPassGrid相对应的位置设置true,来记录可以通过的道路 for(int i=0;i<_mapSize.width;i++) { for(int j=0;j<_mapSize.height;j++) { auto _sp = wayLayer->getTileAt(Point(i,j)); if(_sp) { int row = _sp->getPositionY()/tiledWidth; int col = _sp->getPositionX()/tiledHeight; canPassGrid[row][col] =true; Vec2 p = _sp->getPosition(); wayLayerPass_Vector.push_back(p); //将坐标保存到容器中 log("canPassGrid row= %d ,col =%d ,canpass = %d" ,row,col,canPassGrid[row][col]); } } } log("setWayPassToGrid finished"); } void GameBaseLayer::goButtomCallback(Ref *pSender) { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { SimpleAudioEngine::getInstance()->playEffect(BUTTON_CLICK_01); } auto menuItem = (MenuItem*)pSender; if(menuItem->getTag()==GO_MENU_ITEM_TAG) { randNumber= rand()%6 + 1; RouteNavigation::getInstance()->getPath(player1,randNumber,canPassGrid,tiledRowsCount,tiledColsCount); std::vector<int> rowVector = RouteNavigation::getInstance()->getPathRows_vector(); std::vector<int> colVector = RouteNavigation::getInstance()->getPathCols_vector(); for(int i=0;i<rowVector.size();i++) { log(" rowVector row is %d --- colVector col is %d",rowVector[i],colVector[i]); } NotificationCenter::getInstance()->postNotification(MSG_GO,String::create("0")); player1->startGo(rowVector,colVector); if(isShowSkillLayer) { showSkillSprites(); //隐藏技能界面函数 } } else if(menuItem->getTag() == SKILL_MENU_ITEM_TAG) { //设置消耗的体力 skillStorm->setStrength(50); skillTransfer->setStrength(100); showSkillSprites(); //显示/隐藏技能界面 } } void GameBaseLayer::showSkillSprites() //显示/隐藏技能界面函数 { if(!isShowSkillLayer) { skillStorm->runAction(MoveBy::create(0.3,Vec2(0,130))); skillTransfer->runAction(MoveBy::create(0.3,Vec2(0,130))); isShowSkillLayer = true; } else { skillStorm->runAction(MoveBy::create(0.3,Vec2(0,-130))); skillTransfer->runAction(MoveBy::create(0.3,Vec2(0,-130))); isShowSkillLayer = false; } } void GameBaseLayer::skillStormCallback(Node* node) { if(player1->getStop_x()<0) //判断停留位置是否是初始状态 { return; } if(player1->getStrength()>=50) //判断当前体力是否大于等于技能所需体力 { int landTag = landLayer->getTileGIDAt(Vec2(player1->getStop_x(),player1->getStop_y())); if(landTag != player1_building_1_tiledID && landTag != player1_building_2_tiledID && landTag != player1_building_3_tiledID) { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { SimpleAudioEngine::getInstance()->playEffect(STORM_EFFECT); int rand1 = rand()%(player1EffectVec_4.size()); SimpleAudioEngine::getInstance()->playEffect(player1EffectVec_4.at(rand1)->getCString()); nextPlayerEffectVec = player2EffectVec_5; this->scheduleOnce(schedule_selector(GameBaseLayer::playNextEffectVec),2.0f); } goMenuItem->setEnabled(false); //技能释放过程中,不允许行走,会影响技能判断当前位置 showSkillSprites(); //隐藏界面 refreshStrength(player1,-50); //扣除消耗的体力 Vec2 pointOfGL = Util::map2GL(Vec2(player1->getStop_x(),player1->getStop_y()),GameBaseLayer::_map); auto rainSprite = Sprite::createWithSpriteFrame(player1->getRain_skill_animate()->getAnimation()->getFrames().at(0)->getSpriteFrame()); rainSprite->setAnchorPoint(Vec2(0,0)); rainSprite->setPosition(pointOfGL + Vec2(-tiledWidth/2,tiledHeight/2)); this->addChild(rainSprite); rainSprite->runAction(Sequence::create( player1->getRain_skill_animate(), //播放动画 CallFunc::create([this,rainSprite]() { landLayer->setTileGID(blank_land_tiledID,Vec2(player1->getStop_x(),player1->getStop_y())); //将土地变成空地 rainSprite->removeFromParent(); //移除 goMenuItem->setEnabled(true); //技能释放完毕,允许行走 }), NULL)); } } else //如果体力不足,则提示 { CocosToast::createToast( this, LanguageString::getInstance()->getLanguageString(YOUR_STRENGTH_IS_LOW)->getCString(), TOAST_SHOW_TIME, winSize/2); } } void GameBaseLayer::skillTransferCallback(Node* node) { if(player1->getStop_x()<0) //判断停留位置是否是初始状态 { return; } if(player1->getStrength()>=100) //判断当前体力是否大于等于技能所需体力 { //获取土地的tiledID int transferLand = 0; if(transferLandTag== MSG_PAY_TOLLS_1_TAG) { transferLand = player1_building_1_tiledID; } if(transferLandTag== MSG_PAY_TOLLS_2_TAG) { transferLand = player1_building_2_tiledID; } if(transferLandTag== MSG_PAY_TOLLS_3_TAG) { transferLand = player1_building_3_tiledID; } transferLandTag = 0; if(transferLand !=0) { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player1EffectVec_2.size()); SimpleAudioEngine::getInstance()->playEffect(player1EffectVec_2.at(rand1)->getCString()); nextPlayerEffectVec = player2EffectVec_3; this->scheduleOnce(schedule_selector(GameBaseLayer::playNextEffectVec),2.0f); } goMenuItem->setEnabled(false); //技能释放过程中,不允许行走,会影响技能判断当前位置 showSkillSprites(); //隐藏界面 refreshStrength(player1,-100); //扣除消耗的体力 Vec2 pointOfGL = Util::map2GL(Vec2(player1->getStop_x(),player1->getStop_y()),GameBaseLayer::_map); auto transferSprite = Sprite::createWithSpriteFrame(player1->getTransfer_skill_animate()->getAnimation()->getFrames().at(0)->getSpriteFrame()); transferSprite->setAnchorPoint(Vec2(0,0)); transferSprite->setPosition(pointOfGL); this->addChild(transferSprite); transferSprite->runAction(Sequence::create( player1->getTransfer_skill_animate(), //播放动画 CallFunc::create([this,transferSprite,transferLand]() { landLayer->setTileGID(transferLand,Vec2(player1->getStop_x(),player1->getStop_y())); //将土地变成自己的 transferSprite->removeFromParent(); //移除 goMenuItem->setEnabled(true); //技能释放完毕,允许行走 }), NULL)); } } else //如果体力不足,则提示 { CocosToast::createToast( this, LanguageString::getInstance()->getLanguageString(YOUR_STRENGTH_IS_LOW)->getCString(), TOAST_SHOW_TIME, winSize/2); } } void GameBaseLayer::addNotificationObserver() { //监听MSG_GO消息,让go键出现/隐藏 NotificationCenter::getInstance()->addObserver( this, callfuncO_selector(GameBaseLayer::receiveNotificationOMsg), MSG_GO, NULL); //监听MSG_BUY消息,处理购买土地事件 NotificationCenter::getInstance()->addObserver( this, callfuncO_selector(GameBaseLayer::receiveNotificationOMsg), MSG_BUY, NULL); //监听MSG_PAY_TOLLS消息,处理缴纳过路费事件 NotificationCenter::getInstance()->addObserver( this, callfuncO_selector(GameBaseLayer::receiveNotificationOMsg), MSG_PAY_TOLLS, NULL); //监听MSG_RANDOM_ASK_EVENT消息,处理问号随机事件 NotificationCenter::getInstance()->addObserver( this, callfuncO_selector(GameBaseLayer::receiveNotificationOMsg), MSG_RANDOM_ASK_EVENT, NULL); //监听MSG_STRENGTH_UP消息,处理捡到体力的事件 NotificationCenter::getInstance()->addObserver( this, callfuncO_selector(GameBaseLayer::receiveNotificationOMsg), MSG_STRENGTH_UP, NULL); //监听MSG_USE_SKILL消息,处理敌方角色使用技能事件 NotificationCenter::getInstance()->addObserver( this, callfuncO_selector(GameBaseLayer::receiveNotificationOMsg), MSG_USE_SKILL, NULL); //监听游戏结束消息 NotificationCenter::getInstance()->addObserver( this, callfuncO_selector(GameBaseLayer::receiveNotificationOMsg), MSG_GAME_OVER, NULL); } void GameBaseLayer::receiveNotificationOMsg(Ref* pSender) { auto msgStr = (__String*)pSender; Vector<__String*> messageVector = Util::splitString(msgStr->getCString(),"-"); int retMsgType = messageVector.at(0)->intValue(); log("received go message is: %d",retMsgType); Vector<Node*> menu = this->getMenu()->getChildren(); if(messageVector.size()>3) { if(messageVector.at(3)->intValue() == PLAYER_1_TAG) //角色1 { //记录角色最后停留位置的四周的土地位置 player1->setStop_x(messageVector.at(1)->intValue()); player1->setStop_y(messageVector.at(2)->intValue()); } if(messageVector.at(3)->intValue() == PLAYER_2_TAG) //角色2 { //记录角色最后停留位置的四周的土地位置 player2->setStop_x(messageVector.at(1)->intValue()); player2->setStop_y(messageVector.at(2)->intValue()); } } switch(retMsgType) { case MSG_GO_SHOW_TAG: //当收到的消息是MSG_GO_SHOW_TAG时,表示要显示goMenuItem项 { for(int i =0;i<menu.size();i++) { Node* node = menu.at(i); node->runAction(MoveBy::create(0.3f,Vec2(-(node->getContentSize().width)*2,0))); diceSprite->resume(); //骰子恢复摇动 gameRoundCount++; //步数+1 refresshRoundDisplay(); //更新步数 goMenuItem->setEnabled(true); //go按钮可以按 } break; } case MSG_GO_HIDE_TAG: //当收到的消息是MSG_GO_HIDE_TAG时,表示要隐藏goMenuItem项 { for(int i =0;i<menu.size();i++) { goMenuItem->setEnabled(false); //go按钮不可以按 Node* node = menu.at(i); node->runAction(MoveBy::create(0.3f,Vec2(node->getContentSize().width*2,0))); } //设置骰子 __String *frameName = __String::createWithFormat("dice_%02d.png",randNumber); diceSprite->setSpriteFrame(diceFrameCache->getSpriteFrameByName(frameName->getCString())); diceSprite->pause(); //动作暂停 break; } case MSG_BUY_BLANK_TAG: //当收到的消息是MSG_BUY_BLANK_TAG时,表示要购买空地 { buy_land_x = messageVector.at(1)->floatValue(); buy_land_y = messageVector.at(2)->floatValue(); int playerType = messageVector.at(3)->intValue(); //根据角色分别处理购买土地事件 switch(playerType) { case PLAYER_1_TAG: showBuyLandDialog(MSG_BUY_BLANK_TAG); //如果是角色1 ,则弹出对话框 transferLandTag = 0; break; case PLAYER_2_TAG: //如果是角色2,则直接够买,并播放购买动画 { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player2EffectVec_8.size()); SimpleAudioEngine::getInstance()->playEffect(player2EffectVec_8.at(rand1)->getCString()); } buyLand(MSG_BUY_BLANK_TAG,buy_land_x,buy_land_y,foot2Sprite,player2_building_1_tiledID,player2,PLAYER2_1_PARTICLE_PLIST); NotificationCenter::getInstance()->postNotification(MSG_PICKONE_TOGO,String::createWithFormat("%d",MSG_PICKONE_TOGO_TAG)); //当该角色操作完时,发送信息,让下一个角色行动 break; } } break; } case MSG_BUY_LAND_1_TAG: //升级地图,脚印变为海星, { buy_land_x = messageVector.at(1)->floatValue(); buy_land_y = messageVector.at(2)->floatValue(); int playerType = messageVector.at(3)->intValue(); //根据角色分别处理购买土地事件 switch(playerType) { case PLAYER_1_TAG: showBuyLandDialog(MSG_BUY_LAND_1_TAG); //如果是角色1 ,则弹出对话框 transferLandTag = 0; break; case PLAYER_2_TAG: //如果是角色2,则直接够买,并播放购买动画 { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player2EffectVec_7.size()); SimpleAudioEngine::getInstance()->playEffect(player2EffectVec_7.at(rand1)->getCString()); } //升级土地 buyLand(MSG_BUY_LAND_1_TAG,buy_land_x,buy_land_y,star2Sprite,player2_building_2_tiledID,player2,PLAYER2_1_PARTICLE_PLIST); NotificationCenter::getInstance()->postNotification(MSG_PICKONE_TOGO,String::createWithFormat("%d",MSG_PICKONE_TOGO_TAG)); //当该角色操作完时,发送信息,让下一个角色行动 break; } } break; } case MSG_BUY_LAND_2_TAG: //升级地图,海星变为心形 { buy_land_x = messageVector.at(1)->floatValue(); buy_land_y = messageVector.at(2)->floatValue(); int playerType = messageVector.at(3)->intValue(); //根据角色分别处理购买土地事件 switch(playerType) { case PLAYER_1_TAG: showBuyLandDialog(MSG_BUY_LAND_2_TAG); //如果是角色1 ,则弹出对话框 transferLandTag = 0; break; case PLAYER_2_TAG: //如果是角色2,则直接够买,并播放购买动画 { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player2EffectVec_7.size()); SimpleAudioEngine::getInstance()->playEffect(player2EffectVec_7.at(rand1)->getCString()); } //升级土地 buyLand(MSG_BUY_LAND_2_TAG,buy_land_x,buy_land_y,heart2Sprite,player2_building_3_tiledID,player2,PLAYER2_1_PARTICLE_PLIST); NotificationCenter::getInstance()->postNotification(MSG_PICKONE_TOGO,String::createWithFormat("%d",MSG_PICKONE_TOGO_TAG)); //当该角色操作完时,发送信息,让下一个角色行动 break; } } break; } case MSG_PAY_TOLLS_1_TAG: //缴纳1级土地过路费 { buy_land_x = messageVector.at(1)->floatValue(); buy_land_y = messageVector.at(2)->floatValue(); int playerType = messageVector.at(3)->intValue(); payTolls(MSG_PAY_TOLLS_1_TAG,buy_land_x,buy_land_y,playerType); break; } case MSG_PAY_TOLLS_2_TAG: //缴纳2级土地过路费 { buy_land_x = messageVector.at(1)->floatValue(); buy_land_y = messageVector.at(2)->floatValue(); int playerType = messageVector.at(3)->intValue(); payTolls(MSG_PAY_TOLLS_2_TAG,buy_land_x,buy_land_y,playerType); break; } case MSG_PAY_TOLLS_3_TAG: //缴纳3级土地过路费 { buy_land_x = messageVector.at(1)->floatValue(); buy_land_y = messageVector.at(2)->floatValue(); int playerType = messageVector.at(3)->intValue(); payTolls(MSG_PAY_TOLLS_3_TAG,buy_land_x,buy_land_y,playerType); break; } case MSG_RANDOM_ASK_EVENT_TAG: //问号随机事件 { int playerTag = messageVector.at(3)->intValue(); switch(playerTag) { case PLAYER_1_TAG: doRandomAskEvent(player1); this->scheduleOnce(schedule_selector(GameBaseLayer::sendMSGDealLandRound),TOAST_SHOW_TIME); break; case PLAYER_2_TAG: doRandomAskEvent(player2); this->scheduleOnce(schedule_selector(GameBaseLayer::sendMSGDealLandRound),TOAST_SHOW_TIME); break; } break; } case MSG_STRENGTH_UP30_TAG: //捡到积分卡,恢复30体力 { int playerTag = messageVector.at(3)->intValue(); doStrengthUpEvent(MSG_STRENGTH_UP30_TAG,playerTag); this->scheduleOnce(schedule_selector(GameBaseLayer::sendMSGDealLandRound),TOAST_SHOW_TIME); break; } case MSG_STRENGTH_UP50_TAG: //捡到积分卡,恢复50体力 { int playerTag = messageVector.at(3)->intValue(); doStrengthUpEvent(MSG_STRENGTH_UP50_TAG,playerTag); //处理 this->scheduleOnce(schedule_selector(GameBaseLayer::sendMSGDealLandRound),TOAST_SHOW_TIME); break; } case MSG_STRENGTH_UP80_TAG: //捡到积分卡,恢复80体力 { int playerTag = messageVector.at(3)->intValue(); doStrengthUpEvent(MSG_STRENGTH_UP80_TAG,playerTag); //处理 this->scheduleOnce(schedule_selector(GameBaseLayer::sendMSGDealLandRound),TOAST_SHOW_TIME); break; } case MSG_USE_SKILL_TAG: //敌方角色使用技能 { //获取角色的tag int playerTag = messageVector.at(3)->intValue(); //角色要使用的技能 int kill_index = messageVector.at(4)->intValue(); //使用技能需要耗费的体力 int needLostStrength = messageVector.at(5)->intValue(); //当前地块的等级 int landLevel = messageVector.at(6)->intValue(); if(playerTag == PLAYER_2_TAG) { //让角色减少相应的体力 refreshStrength(player2,-needLostStrength); Vec2 pointOfGL = Util::map2GL(Vec2(player2->getStop_x(),player2->getStop_y()),_map); //播放技能相应动画 switch(kill_index) { case 0://暴风骤雨 { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player2EffectVec_4.size()); SimpleAudioEngine::getInstance()->playEffect(player2EffectVec_4.at(rand1)->getCString()); nextPlayerEffectVec = player1EffectVec_5; this->scheduleOnce(schedule_selector(GameBaseLayer::playNextEffectVec),2.0f); } auto rainSprite = Sprite::createWithSpriteFrame(player2->getRain_skill_animate()->getAnimation()->getFrames().at(0)->getSpriteFrame()); rainSprite->setAnchorPoint(Vec2(0,0)); rainSprite->setPosition(pointOfGL+Vec2(-tiledWidth/2,tiledHeight/2)); this->addChild(rainSprite); //动画播放,完毕后,设置地块为空地块。并发送角色继续行走的消息 rainSprite->runAction(Sequence::create( player2->getRain_skill_animate(), CallFunc::create([this,rainSprite]() { landLayer->setTileGID(blank_land_tiledID,Vec2(player2->getStop_x(),player2->getStop_y())); rainSprite->removeFromParent(); NotificationCenter::getInstance()->postNotification(MSG_PICKONE_TOGO,__String::createWithFormat("%d",MSG_PICKONE_TOGO_TAG)); }),NULL)); break; } case 1://巧取豪夺 { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player2EffectVec_2.size()); SimpleAudioEngine::getInstance()->playEffect(player2EffectVec_2.at(rand1)->getCString()); nextPlayerEffectVec = player1EffectVec_3; this->scheduleOnce(schedule_selector(GameBaseLayer::playNextEffectVec),2.0f); } auto transferSprite = Sprite::createWithSpriteFrame(player2->getTransfer_skill_animate()->getAnimation()->getFrames().at(0)->getSpriteFrame()); transferSprite->setAnchorPoint(Vec2(0,0)); transferSprite->setPosition(pointOfGL); this->addChild(transferSprite); //动画播放完毕后,设置地块为自己相应等级地块。并发送角色继续行走的消息 transferSprite->runAction(Sequence::create( player2->getTransfer_skill_animate(), CallFunc::create([this,landLevel,transferSprite]() { landLayer->setTileGID(landLevel,Vec2(player2->getStop_x(),player2->getStop_y())); transferSprite->removeFromParent(); NotificationCenter::getInstance()->postNotification(MSG_PICKONE_TOGO,__String::createWithFormat("%d",MSG_PICKONE_TOGO_TAG)); }),NULL)); break; } } } break; } case MSG_GAME_OVER_TAG: { int playerType = messageVector.at(3)->intValue(); /* if(playerType == PLAYER_1_TAG) //如果是角色1,则输了 { auto scene = Scene::create(); auto layer = GameOverLayer::createScene(MSG_LOSE_TAG); scene->addChild(layer); Director::getInstance()->replaceScene(scene); } else { auto scene = Scene::create(); auto layer = GameOverLayer::createScene(MSG_WIN_TAG); scene->addChild(layer); Director::getInstance()->replaceScene(scene); } break; */ if(playerType == PLAYER_2_TAG) { //播放粒子效果 ParticleSystem *particle = ParticleSystemQuad::create("images/win_particle.plist"); particle->setPosition(Vec2(winSize.width/2,winSize.height/2)); this->addChild(particle); auto winSprite = Sprite::create("images/win.png"); winSprite->setPosition(Vec2(winSize.width/2,winSize.height/2)); this->addChild(winSprite); } else { auto loseSprite = Sprite::create("images/lose.png"); loseSprite->setPosition(Vec2(winSize.width/2,winSize.height/2)); this->addChild(loseSprite); } break; } } } void GameBaseLayer::sendMSGDealLandRound(float dt) { NotificationCenter::getInstance()->postNotification(MSG_AROUND_LAND,__String::createWithFormat("%d",MSG_AROUND_LAND_TAG)); //发送信息,处理购买土地或缴费 } void GameBaseLayer::sendMSGPickOneToGO(float dt) { NotificationCenter::getInstance()->postNotification(MSG_PICKONE_TOGO,__String::createWithFormat("%d",MSG_PICKONE_TOGO_TAG)); //发送信息,让下一个角色行动 } void GameBaseLayer::initRandomAskEventMap() { randomAskEventMap.insert(TAX_REBATES_TAG,__String::create(TAX_REBATES)); randomAskEventMap.insert(PAY_TAXES_TAG,__String::create(PAY_TAXES)); randomAskEventMap.insert(LOSS_STRENGTH_TAG,__String::create(LOSS_STRENGTH)); randomAskEventMap.insert(PHYSICAL_RECOVERY_TAG,__String::create(PHYSICAL_RECOVERY)); randomAskEventMap.insert(INVESTMENT_DIVIDENDS_TAG,__String::create(INVESTMENT_DIVIDENDS)); randomAskEventMap.insert(INVESTMENT_LOSS_TAG,__String::create(INVESTMENT_LOSS)); } //处理捡到积分卡,体力回升事件 void GameBaseLayer::doStrengthUpEvent(int strengthUp,int playerTag) { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { SimpleAudioEngine::getInstance()->playEffect(PARTICLE_EFFECT); } int strengthValue = 0; switch(strengthUp) { case MSG_STRENGTH_UP30_TAG: strengthValue = 30; break; case MSG_STRENGTH_UP50_TAG: strengthValue = 50; break; case MSG_STRENGTH_UP80_TAG: strengthValue = 80; break; } switch(playerTag) { case PLAYER_1_TAG: { strengthUpSprite->setVisible(true); strengthUpSprite->setPosition(player1->getPosition()); auto action = Sequence::create( strengthUpAnimate, CallFunc::create([this](){ strengthUpSprite->setVisible(false); }), NULL); strengthUpSprite->runAction(action); //播放体力回升动画 //提示信息 CocosToast::createToast( this, __String::createWithFormat("%s %d",LanguageString::getInstance()->getLanguageString(STRENGTH_UP)->getCString(),strengthValue)->getCString(), TOAST_SHOW_TIME, player1->getPosition()); refreshStrength(player1,strengthValue); //更新体力显示 break; } case PLAYER_2_TAG: { strengthUpSprite->setVisible(true); strengthUpSprite->setPosition(player2->getPosition()); auto action = Sequence::create( strengthUpAnimate, CallFunc::create([this](){ strengthUpSprite->setVisible(false); }), NULL); strengthUpSprite->runAction(action); //播放体力回升动画 //提示信息 CocosToast::createToast( this, __String::createWithFormat("%s %d",LanguageString::getInstance()->getLanguageString(STRENGTH_UP)->getCString(),strengthValue)->getCString(), TOAST_SHOW_TIME, player2->getPosition()); refreshStrength(player2,strengthValue); //更新体力显示 break; } } } void GameBaseLayer::doRandomAskEvent(RicherPlayer *player) { int randomNumber = rand()%(randomAskEventMap.size()) + 1; //随机一个数字(1~Map的容量) switch(randomNumber) { case TAX_REBATES_TAG: refreshMoney(player,10000); //政府鼓励投资,返还税金10000 break; case PAY_TAXES_TAG: { //音效 if(player->getTag() == PLAYER_1_TAG) { if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player2EffectVec_9.size()); SimpleAudioEngine::getInstance()->playEffect(player2EffectVec_9.at(rand1)->getCString()); } } else if(player->getTag() == PLAYER_2_TAG) { if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player1EffectVec_9.size()); SimpleAudioEngine::getInstance()->playEffect(player1EffectVec_9.at(rand1)->getCString()); } } refreshMoney(player,-20000); //政府严查账务,补交税金20000 break; } case LOSS_STRENGTH_TAG: refreshStrength(player,-100); //喝到假酒,上吐下泻,体力耗光 break; case PHYSICAL_RECOVERY_TAG: refreshStrength(player,+100); //吃了大补丸,体力恢复 break; case INVESTMENT_DIVIDENDS_TAG: refreshMoney(player,20000); //投资获利,分红20000 break; case INVESTMENT_LOSS_TAG: refreshMoney(player,-30000); //投资失败,亏损30000 break; } __String *str = randomAskEventMap.at(randomNumber); CocosToast::createToast( this, LanguageString::getInstance()->getLanguageString(str->getCString())->getCString(), TOAST_SHOW_TIME, player->getPosition()); //Toast提示事件信息 } void GameBaseLayer::buyLand(int buyTag,float x,float y,Sprite *landSprite,int landLevel,RicherPlayer *player,char *particlelistName) { int money = 0; //判断购买土地需要多少钱 if(buyTag == MSG_BUY_BLANK_TAG) { money = LAND_BLANK_MONEY; } if(buyTag == MSG_BUY_LAND_1_TAG) { money = LAND_LEVEL_1_MONEY; } if(buyTag == MSG_BUY_LAND_2_TAG) { money = LAND_LEVEL_2_MONEY; } Vec2 pointOfMap = Vec2(x,y); Vec2 pointOfGL = Util::map2GL(pointOfMap,GameBaseLayer::_map); landSprite->setVisible(true); landSprite->setPosition(pointOfGL); landSprite->runAction(Sequence::create( scaleBy1ForBuyLand, scaleBy2ForBuyLand, CallFunc::create([this,pointOfMap,pointOfGL,particlelistName,x,y,landSprite,landLevel,player,money]() { playParticle(pointOfGL,particlelistName); landSprite->setVisible(false); landLayer->setTileGID(landLevel,Vec2(x,y)); refreshMoney(player,-money); }), NULL)); } void GameBaseLayer::payTolls(int payTollTag,float x,float y,int playerTag) { int money =0; //判断缴纳过路费的级别 if(payTollTag == MSG_PAY_TOLLS_1_TAG) { money = LAND_BLANK_MONEY; } else if(payTollTag == MSG_PAY_TOLLS_2_TAG) { money = LAND_LEVEL_1_MONEY; } else if(payTollTag == MSG_PAY_TOLLS_3_TAG) { money = LAND_LEVEL_2_MONEY; } RicherPlayer *landPlayer = getPlayerByTiled(x,y); if(playerTag ==PLAYER_1_TAG) //如果是角色1缴纳的话,就角色1扣钱,土地所有者加钱 { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player1EffectVec_1.size()); SimpleAudioEngine::getInstance()->playEffect(player1EffectVec_1.at(rand1)->getCString()); nextPlayerEffectVec = player2EffectVec_6; this->scheduleOnce(schedule_selector(GameBaseLayer::playNextEffectVec),2.0f); } refreshMoney(player1,-money); refreshMoney(landPlayer,money); CocosToast::createToast(this,__String::createWithFormat("-%d",money)->getCString(),TOAST_SHOW_TIME,player1->getPosition()); CocosToast::createToast(this,__String::createWithFormat("+%d",money)->getCString(),TOAST_SHOW_TIME,landPlayer->getPosition()); transferLandTag = payTollTag; } else if(playerTag ==PLAYER_2_TAG) //如果是角色2缴纳的话,就角色1扣钱,土地所有者加钱 { //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player2EffectVec_1.size()); SimpleAudioEngine::getInstance()->playEffect(player2EffectVec_1.at(rand1)->getCString()); nextPlayerEffectVec = player1EffectVec_6; this->scheduleOnce(schedule_selector(GameBaseLayer::playNextEffectVec),2.0f); } refreshMoney(player2,-money); refreshMoney(landPlayer,money); CocosToast::createToast(this,__String::createWithFormat("-%d",money)->getCString(),TOAST_SHOW_TIME,player2->getPosition()); CocosToast::createToast(this,__String::createWithFormat("+%d",money)->getCString(),TOAST_SHOW_TIME,landPlayer->getPosition()); } this->scheduleOnce(schedule_selector(GameBaseLayer::sendMSGPickOneToGO),TOAST_SHOW_TIME); } RicherPlayer* GameBaseLayer::getPlayerByTiled(float x,float y) { int gid = landLayer->getTileGIDAt(Vec2(x,y)); if(gid == player1_building_1_tiledID || gid == player1_building_2_tiledID || gid == player1_building_3_tiledID) //判断是不是角色1的土地 { return player1; } if(gid == player2_building_1_tiledID || gid == player2_building_2_tiledID || gid == player2_building_3_tiledID) //判断是不是角色2的土地 { return player2; } return nullptr; } void GameBaseLayer::refreshMoney(RicherPlayer *player,int money) { player->setMoney(player->getMoney() + money); if(player->getTag() == PLAYER_1_TAG) { __String *moeny1 = __String::createWithFormat("$%d",player->getMoney()); getPlayer1_money_label()->setString(moeny1->getCString()); } if(player->getTag() == PLAYER_2_TAG) { __String *moeny2 = __String::createWithFormat("$%d",player->getMoney()); getPlayer2_money_label()->setString(moeny2->getCString()); } } void GameBaseLayer::refreshStrength(RicherPlayer *player,int strength) { player->setStrength(player->getStrength() + strength); if(player->getTag() == PLAYER_1_TAG) { if(player->getStrength()>=0) { __String *strength1 = __String::createWithFormat("+%d",player->getStrength()); getPlayer1_strength_label()->setString(strength1->getCString()); } else { __String *strength1 = __String::createWithFormat("%d",player->getStrength()); getPlayer1_strength_label()->setString(strength1->getCString()); } } if(player->getTag() == PLAYER_2_TAG) { if(player->getStrength()>=0) { __String *strength2 = __String::createWithFormat("+%d",player->getStrength()); getPlayer2_strength_label()->setString(strength2->getCString()); } else { __String *strength2 = __String::createWithFormat("%d",player->getStrength()); getPlayer2_strength_label()->setString(strength2->getCString()); } } } void GameBaseLayer::addPathMark() { Sprite* mark1 = Sprite::create(PATH_MARK_1); Sprite* mark2 = Sprite::create(PATH_MARK_2); Sprite* mark3 = Sprite::create(PATH_MARK_3); Sprite* mark4 = Sprite::create(PATH_MARK_4); Sprite* mark5 = Sprite::create(PATH_MARK_5); Sprite* mark6 = Sprite::create(PATH_MARK_6); mark1->setAnchorPoint(Vec2(0,0)); mark2->setAnchorPoint(Vec2(0,0)); mark3->setAnchorPoint(Vec2(0,0)); mark4->setAnchorPoint(Vec2(0,0)); mark5->setAnchorPoint(Vec2(0,0)); mark6->setAnchorPoint(Vec2(0,0)); addChild(mark1); addChild(mark2); addChild(mark3); addChild(mark4); addChild(mark5); addChild(mark6); pathMarkVector.pushBack(mark1); pathMarkVector.pushBack(mark2); pathMarkVector.pushBack(mark3); pathMarkVector.pushBack(mark4); pathMarkVector.pushBack(mark5); pathMarkVector.pushBack(mark6); } void GameBaseLayer::drawPathMark(std::vector<int> rowVector,std::vector<int> colVector) { for(int i =0;i<rowVector.size()-1;i++) { pathMarkVector.at(i)->setPosition(Vec2(colVector[i+1]*32,rowVector[i+1]*32)); pathMarkVector.at(i)->setVisible(true); } } void GameBaseLayer::addDigiteRoundSprite() { gameRoundCount = 0 ; auto frameCache = SpriteFrameCache::getInstance(); frameCache->addSpriteFramesWithFile("map/digital_round.plist"); for(int i=0;i<10;i++) { __String *frameName = __String::createWithFormat("digital_%d.png",i); digitalRoundVector.pushBack(frameCache->getSpriteFrameByName(frameName->getCString())); } } void GameBaseLayer::refresshRoundDisplay() { for(int i=0;i<refreshRoundVector.size();i++) { refreshRoundVector.at(i)->setVisible(false); } refreshRoundVector.clear(); int count = gameRoundCount; Sprite *st; //游戏开始时,回合为0 if(count == 0) { st = Sprite::createWithSpriteFrame(digitalRoundVector.at(0)); this->addChild(st); refreshRoundVector.pushBack(st); } //将回合数转换成sprite,存放都容器中 while(count>0) { st = Sprite::createWithSpriteFrame(digitalRoundVector.at(count%10)); //先从个位数开始存 refreshRoundVector.pushBack(st); this->addChild(st); count = count/10; } refreshRoundVector.reverse(); //因为存放时都是倒序存放的,现在要将顺序倒回来 for(int i = 0; i<refreshRoundVector.size();i++) { refreshRoundVector.at(i)->setPosition(Vec2((tableStartPosition_x + 50)+ (i*25),50)); refreshRoundVector.at(i)->setAnchorPoint(Vec2(0,1)); refreshRoundVector.at(i)->setVisible(true); } } void GameBaseLayer::buyLandCallBack(Node* node) { if(node->getTag() == Btn_OK_TAG) { switch(popDialog->getDataTag()) { case MSG_BUY_BLANK_TAG: //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player1EffectVec_8.size()); SimpleAudioEngine::getInstance()->playEffect(player1EffectVec_8.at(rand1)->getCString()); } buyLand(MSG_BUY_BLANK_TAG,buy_land_x,buy_land_y,foot1Sprite,player1_building_1_tiledID,player1,PLAYER1_1_PARTICLE_PLIST); break; case MSG_BUY_LAND_1_TAG: //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player1EffectVec_7.size()); SimpleAudioEngine::getInstance()->playEffect(player1EffectVec_7.at(rand1)->getCString()); } buyLand(MSG_BUY_LAND_1_TAG,buy_land_x,buy_land_y,star1Sprite,player1_building_2_tiledID,player1,PLAYER1_1_PARTICLE_PLIST); break; case MSG_BUY_LAND_2_TAG: //音效 if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(player1EffectVec_7.size()); SimpleAudioEngine::getInstance()->playEffect(player1EffectVec_7.at(rand1)->getCString()); } buyLand(MSG_BUY_LAND_2_TAG,buy_land_x,buy_land_y,heart1Sprite,player1_building_3_tiledID,player1,PLAYER1_1_PARTICLE_PLIST); break; } //购买完毕后,让对话框消失,并发送消息,让其他角色行走 popDialog->removeFromParent(); this->scheduleOnce(schedule_selector(GameBaseLayer::sendMSGPickOneToGO),1.0f); } else { //点击取消,让对话框消失,并发送消息,让其他角色行走 popDialog->removeFromParent(); NotificationCenter::getInstance()->postNotification(MSG_PICKONE_TOGO,String::createWithFormat("%d",MSG_PICKONE_TOGO_TAG)); } } void GameBaseLayer::initPopDialog() { popDialog = PopupLayer::create(DIALOG_BG); popDialog->setContentSize(Size(Dialog_Size_Width,Dialog_Size_Height)); popDialog->setTitle(LanguageString::getInstance()->getLanguageString(DIALOG_TITLE)->getCString()); popDialog->setContentText("",20,60,250); popDialog->setCallbackFunc(this,callfuncN_selector(GameBaseLayer::buyLandCallBack)); popDialog->addButton(BUTTON_BG1,BUTTON_BG3,LanguageString::getInstance()->getLanguageString(OK)->getCString(),Btn_OK_TAG); popDialog->addButton(BUTTON_BG1,BUTTON_BG3,LanguageString::getInstance()->getLanguageString(CANCEL)->getCString(),Btn_Cancel_TAG); this->addChild(popDialog); } void GameBaseLayer::showBuyLandDialog(int landTag) { initPopDialog(); __String *showContentText; switch(landTag) { case MSG_BUY_BLANK_TAG: //购买空地,显示的信息 showContentText = __String::createWithFormat("%s %d",LanguageString::getInstance()->getLanguageString(BUY_LAND_MSG)->getCString(),LAND_BLANK_MONEY); break; case MSG_BUY_LAND_1_TAG: //升级土地,显示的信息 showContentText = __String::createWithFormat("%s %d",LanguageString::getInstance()->getLanguageString(BUY_LAND_MSG)->getCString(),LAND_LEVEL_1_MONEY); break; case MSG_BUY_LAND_2_TAG: //升级土地,显示的信息 showContentText = __String::createWithFormat("%s %d",LanguageString::getInstance()->getLanguageString(BUY_LAND_MSG)->getCString(),LAND_LEVEL_2_MONEY); break; } popDialog->getLabelContentText()->setString(showContentText->getCString()); popDialog->setDataTag(landTag); } //添加骰子 void GameBaseLayer::addDice() { diceFrameCache = SpriteFrameCache::getInstance(); diceFrameCache->addSpriteFramesWithFile("map/dice.plist","map/dice.png"); Vector<SpriteFrame*> diceVector; for(int i=1;i<=6;i++) { __String *frameName = __String::createWithFormat("dice_%02d.png",i); diceVector.pushBack(diceFrameCache->getSpriteFrameByName(frameName->getCString())); } if(!AnimationCache::getInstance()->getAnimation("dice_animation")) { AnimationCache::getInstance()->addAnimation(Animation::createWithSpriteFrames(diceVector,0.1),"dice_animation"); } diceAnimate = Animate::create(AnimationCache::getInstance()->getAnimation("dice_animation")); diceAnimate->retain(); diceSprite = Sprite::createWithSpriteFrame(diceFrameCache->getSpriteFrameByName("dice_01.png")); diceSprite->setPosition(Vec2(tableStartPosition_x + 1.5*tableWidth, tableStartPosition_y - tableHeight*5)); this->addChild(diceSprite); diceSprite->runAction(RepeatForever::create(diceAnimate)); } void GameBaseLayer::addPlayerStrengthUpAniate() { strengthUpFrameCache = SpriteFrameCache::getInstance(); strengthUpFrameCache->addSpriteFramesWithFile("images/strength_up.plist","images/strength_up.png"); Vector<SpriteFrame*> strengthUpSprite_vector; //存放体力回升精灵的容器 for(int i =1;i<=14;i++) { __String *framename = __String::createWithFormat("strength_up_%02d.png",i); strengthUpSprite_vector.pushBack(strengthUpFrameCache->getSpriteFrameByName(framename->getCString())); } auto animation = Animation::createWithSpriteFrames(strengthUpSprite_vector,0.1f); strengthUpAnimate = Animate::create(animation); strengthUpAnimate->retain(); strengthUpSprite = Sprite::createWithSpriteFrame(strengthUpFrameCache->getSpriteFrameByName("strength_up_01.png")); strengthUpSprite->setAnchorPoint(Vec2(0,0.5)); this->addChild(strengthUpSprite); } void GameBaseLayer::initLandLayerFromMap() { landLayer = _map->getLayer("land"); } void GameBaseLayer::particleForBuyLand() { //1级土地--脚印的动作 scaleBy1ForBuyLand = ScaleBy::create(0.1,1.5); //放大 scaleBy2ForBuyLand = ScaleBy::create(0.5,0.7); //缩小 scaleBy1ForBuyLand->retain(); scaleBy2ForBuyLand->retain(); foot1Sprite = Sprite::create(PLAYER1_1_PARTICLE_PNG); //脚印精灵 foot1Sprite->setAnchorPoint(Vec2(0,0)); this->addChild(foot1Sprite); foot2Sprite = Sprite::create(PLAYER2_1_PARTICLE_PNG); foot2Sprite->setAnchorPoint(Vec2(0,0)); this->addChild(foot2Sprite); //2级土地--海星的动作 landFadeOut = FadeOut::create(0.1); //淡出 landFadeIn = FadeIn::create(0.1); //淡入 landFadeIn->retain(); landFadeOut->retain(); star1Sprite = Sprite::create(PLAYER1_2_PARTICLE_PNG); star1Sprite->setAnchorPoint(Vec2(0,0)); this->addChild(star1Sprite); star2Sprite = Sprite::create(PLAYER2_2_PARTICLE_PNG); star2Sprite->setAnchorPoint(Vec2(0,0)); this->addChild(star2Sprite); //3级土地--心形的动作 heart1Sprite = Sprite::create(PLAYER1_3_PARTICLE_PNG); heart1Sprite->setAnchorPoint(Vec2(0,0)); this->addChild(heart1Sprite); heart2Sprite = Sprite::create(PLAYER2_3_PARTICLE_PNG); heart2Sprite->setAnchorPoint(Vec2(0,0)); this->addChild(heart2Sprite); } void GameBaseLayer::playParticle(cocos2d::Vec2 point,char *plistName) { //粒子效果 ParticleSystem *particleSystem_foot = ParticleSystemQuad::create(plistName); particleSystem_foot->retain(); ParticleBatchNode *batch = ParticleBatchNode::createWithTexture(particleSystem_foot->getTexture()); batch->addChild(particleSystem_foot); this->addChild(batch); particleSystem_foot->setPosition(point + Vec2(tiledWidth/2,tiledHeight/2)); particleSystem_foot->release(); } void GameBaseLayer::initAudioEffect() { //交过路费声音0-6 player2EffectVec_1.pushBack(String::create(P2_SPEAKING01)); player2EffectVec_1.pushBack(String::create(P2_QISIWOLE)); player2EffectVec_1.pushBack(String::create(P2_XINHAOKONGA)); player2EffectVec_1.pushBack(String::create(P2_BUHUIBA)); player2EffectVec_1.pushBack(String::create(P2_PAYHIGH)); player2EffectVec_1.pushBack(String::create(P2_QIANGQIANA)); player2EffectVec_1.pushBack(String::create(P2_HEBAOCHUXIE)); //抢夺别人地块7-10 player2EffectVec_2.pushBack(String::create(P2_BIEGUAIWO)); player2EffectVec_2.pushBack(String::create(P2_SPEAKING02)); player2EffectVec_2.pushBack(String::create(P2_TIGER)); player2EffectVec_2.pushBack(String::create(P2_NIDEJIUSHODE)); //房屋被抢夺11-14 player2EffectVec_3.pushBack(String::create(P2_ZHENMIANMU)); player2EffectVec_3.pushBack(String::create(P2_WODEDIQI)); player2EffectVec_3.pushBack(String::create(P2_HAOQIFU)); player2EffectVec_3.pushBack(String::create(P2_WANGFA)); //摧毁别人房屋15-18 player2EffectVec_4.pushBack(String::create(P2_NIGAIWOCHAI)); player2EffectVec_4.pushBack(String::create(P2_KANWODE)); player2EffectVec_4.pushBack(String::create(P2_HAIRENLE)); player2EffectVec_4.pushBack(String::create(P2_BAOCHOU)); //房屋被摧毁19-22 player2EffectVec_5.pushBack(String::create(P2_WODEYANGFANG)); player2EffectVec_5.pushBack(String::create(P2_QIFURENJIA)); player2EffectVec_5.pushBack(String::create(P2_SHAQIANDAO)); player2EffectVec_5.pushBack(String::create(P2_LIANXIANGXIYU)); player2EffectVec_5.pushBack(String::create(P2_HAOJIUGAIHAO)); //收取过路费23 - 28 player2EffectVec_6.pushBack(String::create(P2_RENBUWEIJI)); player2EffectVec_6.pushBack(String::create(P2_XIAOQI)); player2EffectVec_6.pushBack(String::create(P2_RONGXING)); player2EffectVec_6.pushBack(String::create(P2_MANYI)); player2EffectVec_6.pushBack(String::create(P2_XIAOFUPO)); player2EffectVec_6.pushBack(String::create(P2_DUOGEI)); //升级房子29-30 player2EffectVec_7.pushBack(String::create(P2_HIGHER)); player2EffectVec_7.pushBack(String::create(P2_WANZHANGGAOLOU)); //买地31 - 34 player2EffectVec_8.pushBack(String::create(P2_BUYIT)); player2EffectVec_8.pushBack(String::create(P2_HAODEKAISHI)); player2EffectVec_8.pushBack(String::create(P2_RANGNIZHU)); player2EffectVec_8.pushBack(String::create(P2_MAIWOBA)); //对方被罚收税35-38 player2EffectVec_9.pushBack(String::create(P2_TOUSHUI)); player2EffectVec_9.pushBack(String::create(P2_FALVZHICAI)); player2EffectVec_9.pushBack(String::create(P2_GUOKU)); player2EffectVec_9.pushBack(String::create(P2_NASHUI)); //交过路费声音 player1EffectVec_1.pushBack(String::create(P1_Speaking_00435)); player1EffectVec_1.pushBack(String::create(P1_Speaking_00461)); player1EffectVec_1.pushBack(String::create(P1_Speaking_00475)); player1EffectVec_1.pushBack(String::create(P1_Speaking_01060)); player1EffectVec_1.pushBack(String::create(P1_Speaking_01062)); //抢夺别人地块 player1EffectVec_2.pushBack(String::create(P1_Speaking_00429)); //房屋被抢夺 player1EffectVec_3.pushBack(String::create(P1_Speaking_00430)); player1EffectVec_3.pushBack(String::create(P1_Speaking_00464)); player1EffectVec_3.pushBack(String::create(P1_Speaking_00469)); player1EffectVec_3.pushBack(String::create(P1_Speaking_00470)); player1EffectVec_3.pushBack(String::create(P1_Speaking_00476)); //摧毁别人房屋 player1EffectVec_4.pushBack(String::create(P1_Speaking_00433)); player1EffectVec_4.pushBack(String::create(P1_Speaking_00437)); //房屋被摧毁 player1EffectVec_5.pushBack(String::create(P1_Speaking_00462)); player1EffectVec_5.pushBack(String::create(P1_Speaking_00463)); player1EffectVec_5.pushBack(String::create(P1_Speaking_00466)); player1EffectVec_5.pushBack(String::create(P1_Speaking_00468)); player1EffectVec_5.pushBack(String::create(P1_Speaking_00474)); player1EffectVec_5.pushBack(String::create(P1_Speaking_01061)); //收取过路费 player1EffectVec_6.pushBack(String::create(P1_Speaking_00453)); player1EffectVec_6.pushBack(String::create(P1_Speaking_01059)); player1EffectVec_6.pushBack(String::create(P1_Speaking_01057)); //升级房子 player1EffectVec_7.pushBack(String::create(P1_Speaking_01051)); player1EffectVec_7.pushBack(String::create(P1_Speaking_01066)); //买地 player1EffectVec_8.pushBack(String::create(P1_Speaking_00458)); player1EffectVec_8.pushBack(String::create(P1_Speaking_01067)); //对方被罚收税 player1EffectVec_9.pushBack(String::create(P1_Speaking_00452)); } void GameBaseLayer::playNextEffectVec(float t) { if(UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { int rand1 = rand()%(nextPlayerEffectVec.size()); SimpleAudioEngine::getInstance()->playEffect(nextPlayerEffectVec.at(rand1)->getCString()); } }
[ "568206196@qq.com" ]
568206196@qq.com
138b552b6fdea7f09ecd8612294f82b7d8e3f8b2
89b9b885f9f7bb533b220f8de2a3b41761fa83c4
/Plugins/LeapMotion/Source/LeapMotion/Private/HandList.h
21663e733e94a59ef79c8844197531ea979fe825
[ "MIT" ]
permissive
Sirrah/leap-ue4
e374f5745b90d83780642267261bd16ad8c9e37c
6a717216031b8c459ddec712992abaad1fcae22e
refs/heads/master
2021-01-18T09:50:58.985288
2014-10-15T09:55:22
2014-10-15T09:55:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,248
h
#pragma once #include "LeapMotionPrivatePCH.h" #include "HandList.generated.h" UCLASS(BlueprintType) class UHandList : public UObject { GENERATED_UCLASS_BODY() public: ~UHandList(); UFUNCTION(BlueprintCallable, meta = (FriendlyName = "isEmpty", CompactNodeTitle = "", Keywords = "is empty"), Category = Leap) bool isEmpty() const; UFUNCTION(BlueprintCallable, meta = (FriendlyName = "count", CompactNodeTitle = "", Keywords = "count lenght"), Category = Leap) int32 Count(); UFUNCTION(BlueprintCallable, meta = (FriendlyName = "frontmost", CompactNodeTitle = "", Keywords = "frontmost front hand"), Category = Leap) class UHand *frontmost(); UFUNCTION(BlueprintCallable, meta = (FriendlyName = "leftmost", CompactNodeTitle = "", Keywords = "leftmost left hand"), Category = Leap) class UHand *leftmost(); UFUNCTION(BlueprintCallable, meta = (FriendlyName = "rightmost", CompactNodeTitle = "", Keywords = "rightmost right hand"), Category = Leap) class UHand *rightmost(); UFUNCTION(BlueprintCallable, meta = (FriendlyName = "getIndex", CompactNodeTitle = "", Keywords = "get index"), Category = Leap) class UHand *getIndex(int32 index); void setHandList(const Leap::HandList &handlist); private: Leap::HandList _hands; };
[ "marc.wieser@epitech.eu" ]
marc.wieser@epitech.eu
8ea158bc401a03c1a592a146667b879adb4d05d4
efd304a7256c2b5bf1364891051898c43782b1b5
/fram/Fuzzy/Sugeno/SugenoDefuzz.h
6e62e3f619a241ffe1da22eadc80a978d62d496b
[]
no_license
Commortel/FrameworkFlou
04b83b6927a848deb82024982b8bb960f8298894
15ebf1a0d008466939ef903ab609d18d44de83cc
refs/heads/master
2016-09-05T13:26:55.399950
2013-06-03T20:47:46
2013-06-03T20:47:46
8,738,636
1
1
null
null
null
null
UTF-8
C++
false
false
1,214
h
#ifndef SUGENODEFUZZ_H #define SUGENODEFUZZ_H #include "../../Core/Nary/NaryExpression.h" #include "../../Core/Binary/BinaryExpressionModel.h" #include "SugenoThen.h" namespace Fuzzy { template<class T> class SugenoDefuzz : public Core::NaryExpression<T> { public: SugenoDefuzz (); virtual ~SugenoDefuzz(){}; virtual T Evaluate(std::vector<const Core::Expression<T>*> *operands) const; }; template<class T> SugenoDefuzz<T>::SugenoDefuzz(){} template<class T> T SugenoDefuzz<T>::Evaluate(std::vector<const Core::Expression<T>*> *operands) const { typename std::vector<const Core::Expression<T>*>::const_iterator it ; T num = 0, denum = 0; for(it = operands->begin(); it != operands->end(); it++) { num += (*it)->Evaluate(); } for(it = operands->begin(); it != operands->end(); it++) { Core::BinaryExpressionModel<T> *bem = (Core::BinaryExpressionModel<T>*) (*it); Core::BinaryShadowExpression<T> *bse = (Core::BinaryShadowExpression<T>*) bem->GetOperator(); SugenoThen<T> *st = (SugenoThen<T>*) bse->GetTarget(); denum += st->GetPremiseValue(); } std::cout << denum << " " << num; if(denum != 0) return num/denum; else return 0; } } #endif
[ "contact@thibaut-meyer.fr" ]
contact@thibaut-meyer.fr
f70adea34ddc6298a8d30a45b63e6b345955c8ef
63b15515c81558e856ed47e2b30325d33274962e
/Topology/tpzpoint.h
4cee6208ec76da5716d1ff9a6247e8cd3b96d168
[]
no_license
diogocecilio/neopz-master
eb14d4b6087e9655763440934d67b419f781d1a0
7fb9346f00afa883ccf4d07e3ac0af466dfadce1
refs/heads/master
2022-04-04T21:44:17.897614
2019-10-25T20:34:47
2019-10-25T20:34:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,097
h
/** * @file * @brief Contains the TPZPoint class which defines the topology of a point. */ #ifndef PZTOPOLOGYTPZPOINT_H #define PZTOPOLOGYTPZPOINT_H #include "pzreal.h" #include "pzfmatrix.h" #include "pzvec.h" #include "pztrnsform.h" #include "tpzpoint.h" #include "pzeltype.h" class TPZIntPoints; class TPZInt1Point; class TPZGraphEl1dd; class TPZCompEl; class TPZGeoEl; class TPZCompMesh; /// Groups all classes defining the structure of the master element namespace pztopology { /** * @ingroup topology * @author Philippe R. B. Devloo * @brief Defines the topology of a point. \ref topology "Topology" * It has a one side (the same element). */ class TPZPoint { public: /** @brief Enumerate for topological characteristics */ enum {NCornerNodes = 1, NSides = 1, Dimension = 0, NFaces = 0}; /** @brief Default constructor */ TPZPoint() { } /** @brief Default destructor */ virtual ~TPZPoint() { } /** @name About sides of the topological element * @{ */ /** @brief Returns the dimension of the side */ static int SideDimension(int side) { return 0; } /** @brief Get all sides with lower dimension on side */ static void LowerDimensionSides(int side,TPZStack<int> &smallsides) { } /** @brief Get all sides with lower dimension but equal to DimTarget on side */ static void LowerDimensionSides(int side,TPZStack<int> &smallsides, int targetdim) { } /** * @brief Returns all sides whose closure contains side * @param side Smaller dimension side * @param high Vector which will contain all sides whose closure contain sidefrom */ static void HigherDimensionSides(int side, TPZStack<int> &high) { } /** @brief Returns the number of nodes (not connectivities) associated with a side */ static int NSideNodes(int side) { return 1; } /** @brief Returns the local node number of the node "node" along side "side" */ static int SideNodeLocId(int side, int node) { return 0; } /** @brief Returns number of connects of the element ??? */ static int NumSides() { return 1; } /** @brief Returns the number of connects for a set dimension // Jorge ??? */ static int NumSides(int dimension) { return 0; }; /** @brief Returns the number of nodes (not connectivities) associated with a side // Jorge - sides or nodes??? */ static int NContainedSides(int side) { return 1; } /** @brief Returns the local connect number of the connect "c" along side "side" */ static int ContainedSideLocId(int side, int c) { return 0; } /** @} */ /** @name About points at the parametric spaces * @{ */ /** @brief Returns the barycentric coordinates in the master element space of the original element */ static void CenterPoint(int side, TPZVec<REAL> &center) { } /** @brief Verifies if the parametric point pt is in the element parametric domain */ static bool IsInParametricDomain(TPZVec<REAL> &pt, REAL tol = 1e-6){ return true; } static bool MapToSide(int side, TPZVec<REAL> &InternalPar, TPZVec<REAL> &SidePar, TPZFMatrix<REAL> &JacToSide); static void ParametricDomainNodeCoord(int node, TPZVec<REAL> &nodeCoord); /** @} */ /** @name About type of the topological element * @{ */ /** @brief Returns the type of the element as specified in file pzeltype.h */ static MElementType Type(); /** @brief Returns the type of the element side as specified in file pzeltype.h */ static MElementType Type(int side) ; /** @} */ /** @name About Transformations * @{ */ /** * @brief Returns the transformation which takes a point from the side sidefrom to the side sideto * @param sidefrom side where the point resides * @param sideto side whose closure contains sidefrom */ static TPZTransform SideToSideTransform(int sidefrom, int sideto) { TPZTransform result(0,0); return result; } /** * @brief Returns the transformation which transform a point from the side to the interior of the element * @param side Side from which the point will be tranformed (0<=side<=2) * @return TPZTransform object * @see the class TPZTransform */ static TPZTransform TransformSideToElement(int side) { TPZTransform result(0,0); return result; } static TPZTransform TransformElementToSide(int side){ TPZTransform t(0,0); return t; } /** * @brief Method which identifies the transformation based on the IDs of the corner nodes * @param id Indexes of the corner nodes * @return Index of the transformation of the point corresponding to the topology */ static int GetTransformId(TPZVec<long> &id); /** * @brief Method which identifies the transformation of a side based on the IDs * of the corner nodes * @param side Index of side * @param id Indexes of the corner nodes * @return Index of the transformation of the point corresponding to the topology */ static int GetTransformId(int side, TPZVec<long> &id); /** @} */ /** @name Methods related over numeric integration * @{ */ /** * @brief Create an integration rule over side * @param side Side to create integration rule * @param order Order of the integration rule to be created */ static TPZIntPoints *CreateSideIntegrationRule(int side, int order); /** @brief Typedef to numerical integration rule */ typedef TPZInt1Point IntruleType; /* @} */ /** * @brief Identifies the permutation of the nodes needed to make neighbouring elements compatible * in terms of order of shape functions * @param side Side for which the permutation is needed * @param id Ids of the corner nodes of the elements * @param permgather Permutation vector in a gather order */ static void GetSideHDivPermutation(int transformationid, TPZVec<int> &permgather) { permgather[0] = 0; return; } /** @brief Volume of the master element (measure of the element) */ static REAL RefElVolume() { return 0.; } /* Given side and gradx the method returns directions needed for Hdiv space */ static void ComputeDirections(int side, TPZFMatrix<REAL> &gradx, TPZFMatrix<REAL> &directions, TPZVec<int> &sidevectors); static void GetSideDirections(TPZVec<int> &sides, TPZVec<int> &dir, TPZVec<int> &bilinearounao) { sides[0] = 0; dir[0] = 0; bilinearounao[0] = 0; } static void GetSideDirections(TPZVec<int> &sides, TPZVec<int> &dir, TPZVec<int> &bilinearounao, TPZVec<int> &sidevectors) { sides[0] = 0; dir[0] = 0; bilinearounao[0] = 0; sidevectors[0] = 0; } /// Compute the directions of the HDiv vectors static void ComputeDirections(TPZFMatrix<REAL> &gradx, REAL detjac, TPZFMatrix<REAL> &directions) { } /** * Returns the number of bilinear sides to this shape. Needed to compute the number shapefunctions( NConnectShapeF ) */ static int NBilinearSides(); }; } #endif
[ "cecilio.diogo@gmail.com" ]
cecilio.diogo@gmail.com
84fe3a667e3a2722b452ad33f88802b2a6c19f45
7d331c7fab5f5c9aa6ed8026fb6e1b65a333d2b0
/c++/template.cc
7452e4c2614687e31c15ace57671366dd1ee2829
[]
no_license
bhusalashish/DSA
5dcd3d58ad18ed1187eb9d92ab9d1dd179478c65
7df60e6915de839062d8c9a5325a71ba60ac5aef
refs/heads/main
2023-02-02T22:16:55.425440
2020-12-19T04:19:40
2020-12-19T04:19:40
311,925,283
0
0
null
null
null
null
UTF-8
C++
false
false
1,368
cc
#include<bits/stdc++.h> using namespace std; #define ll long long typedef pair<int, int> pi; auto speedup = [](){ ios_base::sync_with_stdio(false); cin.tie(nullptr); //#ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); //#endif return 0; }(); template <typename T1, typename T2> void print(const T1 array[], T2 size) { for(size_t i = 0; i < size; ++i) cout << array[i] << " "; cout<<endl; } template<typename T> void print(vector<T> &vec){ for(T &element : vec) cout<<element<<" "; cout<<endl; } template<typename T> void print(vector<vector<T> > &vec){ for(auto elements : vec){ for(T &element : elements) cout<<element<<" "; cout<<endl; } } template<typename T> void print(set<T> &set){ for(auto it : set) cout<<it<<" "; cout<<endl; } template<typename T1, typename T2> void print(map<T1, T2> &map){ for(auto it : map) cout<<it.first<<" -> "<<it.second<<"\n"; } template<typename T> void print(unordered_set<T> &uset){ for(auto it : uset) cout<<it<<" "; cout<<endl; } template<typename T1, typename T2> void print(unordered_map<T1, T2> &umap){ for(auto it : umap) cout<<it.first<<" -> "<<it.second<<"\n"; } int main(){ int test_cases; cin>>test_cases; while(test_cases--){ int number_of_elements; cin>>number_of_elements; vector<int> nums(number_of_elements); for(int &num : nums) cin>>num; } }
[ "ashish.bhusal.16999@gmail.com" ]
ashish.bhusal.16999@gmail.com
d573e9db708d36ff93c3cceddce16f16bde336cf
6197740e6297da2f3d0c8ffd2a1d7ef5d8b3d2cb
/cmake-2.8.12.2/Source/cmEndFunctionCommand.h
8232fd744aab84f568928f4f72269fafba201b89
[ "BSD-3-Clause" ]
permissive
ssh352/cppcode
1159d4137b68ada253678718b3d416639d3849ba
5b7c28963286295dfc9af087bed51ac35cd79ce6
refs/heads/master
2020-11-24T18:07:17.587795
2016-07-15T13:13:05
2016-07-15T13:13:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,173
h
/*============================================================================ CMake - Cross Platform Makefile Generator Copyright 2000-2009 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #ifndef cmEndFunctionCommand_h #define cmEndFunctionCommand_h #include "cmCommand.h" /** \class cmEndFunctionCommand * \brief ends an if block * * cmEndFunctionCommand ends an if block */ class cmEndFunctionCommand : public cmCommand { public: /** * This is a virtual constructor for the command. */ virtual cmCommand* Clone() { return new cmEndFunctionCommand; } /** * Override cmCommand::InvokeInitialPass to get arguments before * expansion. */ virtual bool InvokeInitialPass(std::vector<cmListFileArgument> const&, cmExecutionStatus &); /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ virtual bool InitialPass(std::vector<std::string> const&, cmExecutionStatus &) {return false;} /** * This determines if the command is invoked when in script mode. */ virtual bool IsScriptable() const { return true; } /** * The name of the command as specified in CMakeList.txt. */ virtual const char* GetName() const { return "endfunction";} /** * Succinct documentation. */ virtual const char* GetTerseDocumentation() const { return "Ends a list of commands in a function block."; } /** * More documentation. */ virtual const char* GetFullDocumentation() const { return " endfunction(expression)\n" "See the function command."; } cmTypeMacro(cmEndFunctionCommand, cmCommand); }; #endif
[ "qq410029478@ff87cf93-6e24-4a51-a1f1-68835326ac4f" ]
qq410029478@ff87cf93-6e24-4a51-a1f1-68835326ac4f
cf8e6025902e65f41fcd74dfe3f4b4d9044594ba
7e62f0928681aaaecae7daf360bdd9166299b000
/external/DirectXShaderCompiler/tools/clang/test/SemaCXX/gnu-case-ranges.cpp
dc7a58cb3d4d7fdfdb1eb49ff3fa429f46f24534
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yuri410/rpg
949b001bd0aec47e2a046421da0ff2a1db62ce34
266282ed8cfc7cd82e8c853f6f01706903c24628
refs/heads/master
2020-08-03T09:39:42.253100
2020-06-16T15:38:03
2020-06-16T15:38:03
211,698,323
0
0
null
null
null
null
UTF-8
C++
false
false
389
cpp
// RUN: %clang_cc1 -verify -Wno-covered-switch-default %s // expected-no-diagnostics enum E { one, two, three, four }; int test(enum E e) { switch (e) { case one: return 7; case two ... two + 1: return 42; case four: return 25; default: return 0; } }
[ "yuri410@users.noreply.github.com" ]
yuri410@users.noreply.github.com
79f23ac17f996159b8d443f31bd7f7247fb72906
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/AdvApp2Var_SequenceNodeOfSequenceOfPatch.hxx
06e9f30912681fe000bd18c26cfb371cd3d9c569
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
2,371
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _AdvApp2Var_SequenceNodeOfSequenceOfPatch_HeaderFile #define _AdvApp2Var_SequenceNodeOfSequenceOfPatch_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_AdvApp2Var_SequenceNodeOfSequenceOfPatch_HeaderFile #include <Handle_AdvApp2Var_SequenceNodeOfSequenceOfPatch.hxx> #endif #ifndef _AdvApp2Var_Patch_HeaderFile #include <AdvApp2Var_Patch.hxx> #endif #ifndef _TCollection_SeqNode_HeaderFile #include <TCollection_SeqNode.hxx> #endif #ifndef _TCollection_SeqNodePtr_HeaderFile #include <TCollection_SeqNodePtr.hxx> #endif class AdvApp2Var_Patch; class AdvApp2Var_SequenceOfPatch; class AdvApp2Var_SequenceNodeOfSequenceOfPatch : public TCollection_SeqNode { public: AdvApp2Var_SequenceNodeOfSequenceOfPatch(const AdvApp2Var_Patch& I,const TCollection_SeqNodePtr& n,const TCollection_SeqNodePtr& p); AdvApp2Var_Patch& Value() const; DEFINE_STANDARD_RTTI(AdvApp2Var_SequenceNodeOfSequenceOfPatch) protected: private: AdvApp2Var_Patch myValue; }; #define SeqItem AdvApp2Var_Patch #define SeqItem_hxx <AdvApp2Var_Patch.hxx> #define TCollection_SequenceNode AdvApp2Var_SequenceNodeOfSequenceOfPatch #define TCollection_SequenceNode_hxx <AdvApp2Var_SequenceNodeOfSequenceOfPatch.hxx> #define Handle_TCollection_SequenceNode Handle_AdvApp2Var_SequenceNodeOfSequenceOfPatch #define TCollection_SequenceNode_Type_() AdvApp2Var_SequenceNodeOfSequenceOfPatch_Type_() #define TCollection_Sequence AdvApp2Var_SequenceOfPatch #define TCollection_Sequence_hxx <AdvApp2Var_SequenceOfPatch.hxx> #include <TCollection_SequenceNode.lxx> #undef SeqItem #undef SeqItem_hxx #undef TCollection_SequenceNode #undef TCollection_SequenceNode_hxx #undef Handle_TCollection_SequenceNode #undef TCollection_SequenceNode_Type_ #undef TCollection_Sequence #undef TCollection_Sequence_hxx // other Inline functions and methods (like "C++: function call" methods) #endif
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
2deb17484030e5d790371433e8275e69c1df6087
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/inetsrv/iis/config/src/urt/wmi/netprovider/assocwebappchild.cpp
3755fca6eaeaaf91d46de2dc28d5b992e6c07d07
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,524
cpp
/**************************************************************************++ Copyright (c) 2001 Microsoft Corporation Module name: assocwebappchild.cpp $Header: $ Abstract: Creates child/parent assocation for webapplications Author: marcelv 2/9/2001 Initial Release Revision History: --**************************************************************************/ #include "assocwebappchild.h" #include "assoctypes.h" static LPCWSTR wszIISW3SVC = L"iis://localhost/W3SVC/"; static LPCWSTR wszLMW3SVC = L"/LM/W3SVC/"; static SIZE_T cIISW3SVC = wcslen (wszIISW3SVC); static SIZE_T cLMW3SVC = wcslen (wszLMW3SVC); //================================================================================= // Function: CAssocWebAppChild::CAssocWebAppChild // // Synopsis: Constructor //================================================================================= CAssocWebAppChild::CAssocWebAppChild () { m_fGetChildren = false; } //================================================================================= // Function: CAssocWebAppChild::~CAssocWebAppChild // // Synopsis: Destructor //================================================================================= CAssocWebAppChild::~CAssocWebAppChild () { } //================================================================================= // Function: CAssocWebAppChild::CreateAssocations // // Synopsis: Creates the assocations. Because the assocations are one-way (from web-app to // children or parent), we only check for Node. If Node is not specified, we simply // return //================================================================================= HRESULT CAssocWebAppChild::CreateAssocations () { HRESULT hr = S_OK; const CWQLProperty * pProp = m_pWQLParser->GetProperty (0); ASSERT (pProp != 0); if (_wcsicmp (pProp->GetName (), L"Node") == 0) { hr = GetAssocType (); // sets m_fGetChildren if (FAILED (hr)) { TRACE (L"Unable to get association type"); return hr; } if (m_fGetChildren) { hr = CreateChildAssocs (); } else { hr = CreateParentAssoc (); } if (FAILED (hr)) { TRACE (L"Unable to create parent/child assocations for web-app"); return hr; } } return hr; } //================================================================================= // Function: CAssocWebAppChild::GetAssocType // // Synopsis: Gets the assocation type from the class qualifier, and sets the boolean // m_fGetChildren. //================================================================================= HRESULT CAssocWebAppChild::GetAssocType () { ASSERT (m_fInitialized); CComPtr<IWbemQualifierSet> spPropQualifierSet; HRESULT hr = m_spClassObject->GetQualifierSet (&spPropQualifierSet); if (FAILED (hr)) { TRACE (L"Unable to get QualifierSet for class %s", m_pWQLParser->GetClass ()); return hr; } _variant_t varAssocType; hr = spPropQualifierSet->Get (L"AssocType", 0, &varAssocType, 0); if (FAILED (hr)) { TRACE (L"Unable to get AssocType qualifier for class %s", m_pWQLParser->GetClass ()); return hr; } ASSERT (varAssocType.vt == VT_BSTR); LPCWSTR wszAssocType = varAssocType.bstrVal; if (_wcsicmp (wszAssocType, g_wszAssocTypeWebAppChild) == 0) { m_fGetChildren = true; } else { ASSERT (_wcsicmp (wszAssocType, g_wszAssocTypeWebAppParent) == 0); } _bstr_t bstrNodeType; hr = GetConfigClass (L"Node", bstrNodeType); if (FAILED (hr)) { TRACE (L"Unable to get configuration class in webapp parent/child association"); return hr; } return hr; } //================================================================================= // Function: CAssocWebAppChild::CreateChildAssocs // // Synopsis: Create child webapps assocations. Loop through the metabase, and find the // subkeys of the current webapp. For each subkey, check if it has an approot // property. If it has, we need to create an instance of a webapp assocation. //================================================================================= HRESULT CAssocWebAppChild::CreateChildAssocs () { HRESULT hr = CoCreateInstance(CLSID_MSAdminBase, NULL, CLSCTX_ALL, IID_IMSAdminBase, (void **) &m_spAdminBase); if (FAILED (hr)) { TRACE (L"CoCreateInstance failed for CLSID_MSAdminBase, interface IID_IMSAdminBase"); return hr; } // m_knownObjectParser contains information. const CWMIProperty * pSelector = m_knownObjectParser.GetPropertyByName (WSZSELECTOR); if (pSelector == 0) { return E_INVALIDARG; } LPCWSTR wszSelector = pSelector->GetValue (); if (_wcsnicmp (wszSelector, wszIISW3SVC, cIISW3SVC) != 0) { TRACE (L"Selector should start with iis://localhost/w3svc"); return E_INVALIDARG; } SIZE_T cSelectorLen = wcslen (wszSelector); if (wszSelector[cSelectorLen - 1] == L'\\' || wszSelector[cSelectorLen - 1] == L'/') { TRACE (L"Selector for webapplication cannot end with backslash"); return E_ST_INVALIDSELECTOR; } // Replace iis://localhost with LM (so metabase stuff works) TSmartPointerArray<WCHAR> wszMBSelector = new WCHAR[cSelectorLen + 1 - cIISW3SVC + cLMW3SVC + 1]; // +1 for possible backslash if (wszMBSelector == 0) { return E_OUTOFMEMORY; } wsprintf (wszMBSelector, L"%s%s", wszLMW3SVC, wszSelector + cIISW3SVC); // loop through all the subkeys WCHAR wszSubKey[METADATA_MAX_NAME_LEN]; for (ULONG idx=0; ; idx++) { hr = m_spAdminBase->EnumKeys (METADATA_MASTER_ROOT_HANDLE, wszMBSelector, wszSubKey, idx); if (hr == HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS)) { hr = S_OK; break; } if (FAILED (hr)) { TRACE (L"EnumKeys failed for selector %s and subkey %s", wszMBSelector, wszSubKey); return hr; } // add subkey to selector and check if it is an approot TSmartPointerArray<WCHAR> wszNewPath = new WCHAR [wcslen (wszSubKey) + wcslen (wszMBSelector) + 2]; if (wszNewPath == 0) { return E_OUTOFMEMORY; } wsprintf (wszNewPath, L"%s/%s", wszMBSelector, wszSubKey); hr = CreateInstanceForAppRoot (wszNewPath, L"ChildNode"); if (FAILED (hr)) { TRACE (L"CreateInstanceForAppRoot failed"); return hr; } } return hr; } //================================================================================= // Function: CAssocWebAppChild::CreateParentAssoc // // Synopsis: Create parent webapp if it exists. Use the selector, find the last dir, chop // it of, and check if the resulting MB path is an approot. If so, create an assocation // else do nothing //================================================================================= HRESULT CAssocWebAppChild::CreateParentAssoc () { HRESULT hr = CoCreateInstance(CLSID_MSAdminBase, NULL, CLSCTX_ALL, IID_IMSAdminBase, (void **) &m_spAdminBase); if (FAILED (hr)) { TRACE (L"CoCreateInstance failed for CLSID_MSAdminBase, interface IID_IMSAdminBase"); return hr; } // m_knownObjectParser contains information. const CWMIProperty * pSelector = m_knownObjectParser.GetPropertyByName (WSZSELECTOR); if (pSelector == 0) { return E_INVALIDARG; } // copy and replace iis://localhost with LM LPCWSTR wszSelector = pSelector->GetValue (); TSmartPointerArray<WCHAR> saMBSelector = new WCHAR[wcslen (wszSelector) + 1 - cIISW3SVC + cLMW3SVC]; if (saMBSelector == 0) { return E_OUTOFMEMORY; } wsprintf (saMBSelector, L"%s%s", wszLMW3SVC, wszSelector + cIISW3SVC); // remove slash at the end, and search for last slash, to chop off the last directory SIZE_T cMBSelLen = wcslen (saMBSelector); if (saMBSelector[cMBSelLen - 1] == L'/') { saMBSelector [cMBSelLen - 1] = L'\0'; } LPWSTR pLastDirStart = wcsrchr (saMBSelector, L'/'); if (pLastDirStart != 0) { *pLastDirStart = L'\0'; } hr = CreateInstanceForAppRoot (saMBSelector, L"Parent"); if (FAILED (hr)) { TRACE (L"IsAppRoot failed"); return hr; } return hr; } //================================================================================= // Function: CAssocWebAppChild::CreateInstanceForAppRoot // // Synopsis: Create an webappassocation instance if i_wszNewInstance is an approot. If // not, it simply returns without creating anything // // Arguments: [i_wszNewInstance] - MB path for which we want to create a new instance // [i_wszChildOrParent] - Do we create a child or a parent (makes it easy to use // the function for both child and parent creation //================================================================================= HRESULT CAssocWebAppChild::CreateInstanceForAppRoot (LPCWSTR i_wszNewInstance, LPCWSTR i_wszChildOrParent) { ASSERT (i_wszNewInstance != 0); ASSERT (i_wszChildOrParent != 0); // are we an approot? WCHAR wszResult[1024]; DWORD dwRequired; METADATA_RECORD resRec; resRec.dwMDIdentifier = MD_APP_ROOT; resRec.dwMDDataLen = sizeof (wszResult)/sizeof(WCHAR); resRec.pbMDData = (BYTE *)wszResult; resRec.dwMDAttributes = 0; resRec.dwMDDataType = STRING_METADATA; HRESULT hr = m_spAdminBase->GetData (METADATA_MASTER_ROOT_HANDLE, i_wszNewInstance, &resRec, &dwRequired); if (hr == HRESULT_FROM_WIN32(MD_ERROR_DATA_NOT_FOUND)) { // APPROOT doesn't exist for this key. This is ok, simply return in this case return S_OK; } if (FAILED (hr)) { TRACE (L"GetData failed for key %s", i_wszNewInstance); return hr; } // create a new instance of the assocation CComPtr<IWbemClassObject> spNewInst; hr = m_spClassObject->SpawnInstance(0, &spNewInst); if (FAILED (hr)) { TRACE (L"Unable to create new instance for class %s", m_pWQLParser->GetClass ()); return hr; } // Node is part of the query, so is easy to set _variant_t varValue = m_pWQLParser->GetProperty (0)->GetValue(); hr = spNewInst->Put(L"Node", 0, &varValue, 0); if (FAILED (hr)) { TRACE (L"WMI Put property failed. Property=%s, value=%s", m_knownObjectParser.GetClass (), varValue.bstrVal); return hr; } // convert /LM to iis://localhost in i_wszNewInstance and add a slash at the end _bstr_t bstrValue = "WebApplication.Selector=\"iis://localhost"; bstrValue += (i_wszNewInstance + 3); bstrValue += L"\""; _variant_t varNewValue = bstrValue; hr = spNewInst->Put(i_wszChildOrParent, 0, &varNewValue, 0); if (FAILED (hr)) { TRACE (L"WMI Put property failed."); return hr; } IWbemClassObject* pNewInstRaw = spNewInst; hr = m_spResponseHandler->Indicate(1,&pNewInstRaw); if (FAILED (hr)) { TRACE (L"WMI Indicate failed"); } return hr; }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
c6bfc911ed365c10c26b2f9438f87aab788eee3b
52db3ea0dea90f7afb9120ab0e1f3d5faf4d1f09
/src/mod/kgtonull.cpp
b019adcdf3da662df92f0883b5264f28f0baee56
[]
no_license
The-Alchemist/nysol_python
3f5d9d34ca77b00bddf483371aabf92eb7e37032
c6e320057331c28fc06b8b72bdef492c10025d3f
refs/heads/master
2020-06-05T10:51:55.313455
2019-06-01T14:34:39
2019-06-01T14:34:39
192,415,346
0
0
null
2019-06-17T20:37:34
2019-06-17T20:37:34
null
UTF-8
C++
false
false
7,847
cpp
/* ////////// LICENSE INFO //////////////////// * Copyright (C) 2013 by NYSOL CORPORATION * * Unless you have received this program directly from NYSOL pursuant * to the terms of a commercial license agreement with NYSOL, then * this program is licensed to you under the terms of the GNU Affero General * Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF * NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * Please refer to the AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) * for more details. ////////// LICENSE INFO ////////////////////*/ // ============================================================================= // kgtonull.h NULL値の置換クラス // ============================================================================= #include <cstdio> #include <string> #include <cstring> #include <vector> #include <kgtonull.h> #include <kgError.h> #include <kgConfig.h> using namespace std; using namespace kglib; using namespace kgmod; // ----------------------------------------------------------------------------- // 文字列比較(当てはまればtrue)vstrにある文字列のどれかに一致すればtrue // ----------------------------------------------------------------------------- namespace { // ワイド文字による部分文字列比較 bool strCompSub(char* str,vector<wstring>& vstr){ for(vector<wstring>::size_type i=0;i<vstr.size();i++){ wstring ws=toWcs(str); if(ws.find(vstr[i])!=wstring::npos) {return true;} } return false; } // 通常の部分文字列比較 bool strCompSub(char* str,vector<string>& vstr){ for(vector<string>::size_type i=0;i<vstr.size();i++){ if(NULL!=strstr(str,vstr[i].c_str())) {return true;} } return false; } // 完全マッチ比較 bool strComp(char* str,vector<string>& vstr){ for(vector<string>::size_type i=0;i<vstr.size();i++){ if(!strcmp(str,vstr[i].c_str())) {return true;} } return false; } } // ----------------------------------------------------------------------------- // コンストラクタ(モジュール名,バージョン登録) // ----------------------------------------------------------------------------- const char * kgTonull::_ipara[] = {"i",""}; const char * kgTonull::_opara[] = {"o",""}; kgTonull::kgTonull(void) { _name = "kgtonull"; _version = "###VERSION###"; _paralist = "i=,o=,f=,v=,-sub,-W"; _paraflg = kgArgs::COMMON|kgArgs::IODIFF|kgArgs::NULL_IN; #include <help/en/kgtonullHelp.h> _titleL = _title; _docL = _doc; #ifdef JPN_FORMAT #include <help/jp/kgtonullHelp.h> #endif } // ----------------------------------------------------------------------------- // パラメータセット&入出力ファイルオープン // ----------------------------------------------------------------------------- void kgTonull::setArgsMain(void) { _iFile.read_header(); // f= 項目引数のセット vector<kgstr_t> vs_f = _args.toStringVector("f=",true); _fField.set(vs_f, &_iFile,_fldByNum); // -sub 部分マッチフラグ _substr = _args.toBool("-sub"); _widechr = _args.toBool("-W"); // v= 項目引数のセット _vField = _args.toStringVector("v=",true); for(vector<kgstr_t>::size_type i=0;i<_vField.size();i++){ if(_substr && _widechr){ _vFieldw.push_back(toWcs(_vField[i])); } } } // ----------------------------------------------------------------------------- // パラメータセット&入出力ファイルオープン // ----------------------------------------------------------------------------- void kgTonull::setArgs(void) { // パラメータチェック _args.paramcheck(_paralist,_paraflg); // ファイルオープン _iFile.open(_args.toString("i=",false),_env,_nfn_i); _oFile.open(_args.toString("o=",false),_env,_nfn_o); setArgsMain(); } // ----------------------------------------------------------------------------- // パラメータセット&入出力ファイルオープン // ----------------------------------------------------------------------------- void kgTonull::setArgs(int inum,int *i_p,int onum ,int *o_p) { int iopencnt = 0; int oopencnt = 0; try{ _args.paramcheck(_paralist,_paraflg); if(inum>1 || onum>1){ throw kgError("no match IO");} if(inum==1 && *i_p>0){ _iFile.popen(*i_p, _env,_nfn_i); } else { _iFile.open(_args.toString("i=",true), _env,_nfn_i); } iopencnt++; if(onum==1 && *o_p>0){ _oFile.popen(*o_p, _env,_nfn_o); } else { _oFile.open(_args.toString("o=",true), _env,_nfn_o);} oopencnt++; setArgsMain(); }catch(...){ for(int i=iopencnt; i<inum ;i++){ if(*(i_p+i)>0){ ::close(*(i_p+i)); } } for(int i=oopencnt; i<onum ;i++){ if(*(o_p+i)>0){ ::close(*(o_p+i)); } } throw; } } // ----------------------------------------------------------------------------- // 実行 // ----------------------------------------------------------------------------- int kgTonull::runMain(void) { // 項目名出力 _oFile.writeFldName(_iFile); while( EOF != _iFile.read() ){ const vector<int>* flg=_fField.getFlg_p(); for(vector<int>::size_type i=0; i<flg->size(); i++){ bool eol= (i==flg->size()-1); // 改行出力フラグ int num = flg->at(i); // f=で指定されたかどうか char* str = _iFile.getVal(i); // 項目の値 // f=で指定された項目以外の場合はそのまま出力 if(num == -1){ _oFile.writeStr(str, eol); }else{ // f=で指定された項目の場合 if(_assertNullIN && *str=='\0') { _existNullIN = true;} if(_substr){ // 部分マッチの比較 if(_widechr){ if( strCompSub(str, _vFieldw) ) _oFile.writeStr("" ,eol); else _oFile.writeStr(str,eol); }else{ if( strCompSub(str, _vField ) ) _oFile.writeStr("" ,eol); else _oFile.writeStr(str,eol); } }else{// 完全一致の比較 if( strComp(str, _vField) ) _oFile.writeStr("" ,eol); else _oFile.writeStr(str,eol); } } } } // 終了処理 _iFile.close(); _oFile.close(); return 0; } // ----------------------------------------------------------------------------- // 実行 // ----------------------------------------------------------------------------- int kgTonull::run(void) { try { setArgs(); int sts = runMain(); successEnd(); return sts; }catch(kgOPipeBreakError& err){ runErrEnd(); successEnd(); return 0; }catch(kgError& err){ runErrEnd(); errorEnd(err); }catch (const exception& e) { runErrEnd(); kgError err(e.what()); errorEnd(err); }catch(char * er){ runErrEnd(); kgError err(er); errorEnd(err); }catch(...){ runErrEnd(); kgError err("unknown error" ); errorEnd(err); } return 1; } ///* thraad cancel action static void cleanup_handler(void *arg) { ((kgTonull*)arg)->runErrEnd(); } int kgTonull::run(int inum,int *i_p,int onum, int* o_p,string &msg) { int sts=1; pthread_cleanup_push(&cleanup_handler, this); try { setArgs(inum, i_p, onum,o_p); sts = runMain(); msg.append(successEndMsg()); }catch(kgOPipeBreakError& err){ runErrEnd(); msg.append(successEndMsg()); sts = 0; }catch(kgError& err){ runErrEnd(); msg.append(errorEndMsg(err)); }catch (const exception& e) { runErrEnd(); kgError err(e.what()); msg.append(errorEndMsg(err)); }catch(char * er){ runErrEnd(); kgError err(er); msg.append(errorEndMsg(err)); } KG_ABI_CATCH catch(...){ runErrEnd(); kgError err("unknown error" ); msg.append(errorEndMsg(err)); } pthread_cleanup_pop(0); return sts; }
[ "nain0606@gmial.com" ]
nain0606@gmial.com
0d223e2965dbb87decc2ef89a2fee34ba78e271e
b0dd7779c225971e71ae12c1093dc75ed9889921
/libs/foreach/test/cstr_byval_r.cpp
307562b4317e669b1b67f87da143da365a18caea
[ "LicenseRef-scancode-warranty-disclaimer", "BSL-1.0" ]
permissive
blackberry/Boost
6e653cd91a7806855a162347a5aeebd2a8c055a2
fc90c3fde129c62565c023f091eddc4a7ed9902b
refs/heads/1_48_0-gnu
2021-01-15T14:31:33.706351
2013-06-25T16:02:41
2013-06-25T16:02:41
2,599,411
244
154
BSL-1.0
2018-10-13T18:35:09
2011-10-18T14:25:18
C++
UTF-8
C++
false
false
1,450
cpp
// (C) Copyright Eric Niebler 2004. // Use, modification and distribution are subject to 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) /* Revision history: 25 August 2005 : Initial version. */ #include <boost/test/minimal.hpp> #include <boost/foreach.hpp> /////////////////////////////////////////////////////////////////////////////// // define the container types, used by utility.hpp to generate the helper functions typedef char *foreach_container_type; typedef char const *foreach_const_container_type; typedef char foreach_value_type; typedef char &foreach_reference_type; typedef char const &foreach_const_reference_type; #include "./utility.hpp" /////////////////////////////////////////////////////////////////////////////// // define some containers // char my_ntcs_buffer[] = "\1\2\3\4\5"; char *my_ntcs = my_ntcs_buffer; char const *my_const_ntcs = my_ntcs; /////////////////////////////////////////////////////////////////////////////// // test_main // int test_main( int, char*[] ) { boost::mpl::true_ *p = BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(my_ntcs); // non-const containers by value BOOST_CHECK(sequence_equal_byval_n_r(my_ntcs, "\5\4\3\2\1")); // const containers by value BOOST_CHECK(sequence_equal_byval_c_r(my_const_ntcs, "\5\4\3\2\1")); return 0; }
[ "tvaneerd@rim.com" ]
tvaneerd@rim.com
8d98d52dc89ec353b70419773dea323396a2698b
aa56208b0fbecc5bc26fb0134a7ffe16c259496a
/Motyl/gk2_deviceHelper.h
39396f618b8c7ff286d3055c842ade49417ef518
[]
no_license
lukaszw896/PUMA
de06fa714aacdad0de11644aa696a1ebe626ed9e
8fb8a9bb3e9398b2e5e5b342dd2c26d4a3dca502
refs/heads/master
2020-12-31T04:55:51.212389
2016-04-24T18:49:02
2016-04-24T18:49:02
56,993,238
0
0
null
null
null
null
UTF-8
C++
false
false
3,155
h
#ifndef __GK2_DEVICE_HELPER_H_ #define __GK2_DEVICE_HELPER_H_ #include <memory> #include <d3d11.h> #include <vector> #include "gk2_utils.h" namespace gk2 { class DeviceHelper { public: std::shared_ptr<ID3D11Device> m_deviceObject; /*std::shared_ptr<ID3DBlob> CompileD3DShader(const std::wstring& filePath, const std::string& entry, const std::string& shaderModel);*/ unique_ptr_del<ID3D11VertexShader> CreateVertexShader(const void* byteCode, size_t byteCodeLength) const; unique_ptr_del<ID3D11PixelShader> CreatePixelShader(const void* byteCode, size_t byteCodeLength) const; unique_ptr_del<ID3D11InputLayout> CreateInputLayout(const D3D11_INPUT_ELEMENT_DESC* layout, unsigned int layoutElements, const void* vsByteCode, size_t vsByteCodeLength) const; template<typename T> unique_ptr_del<ID3D11InputLayout> CreateInputLayout(const void* vsByteCode, size_t vsByteCodeLength) { return CreateInputLayout(T::Layout, T::LayoutElements, vsByteCode, vsByteCodeLength); } template<typename T> unique_ptr_del<ID3D11Buffer> CreateVertexBuffer(const std::vector<T>& vertices) { return _CreateBufferInternal(reinterpret_cast<const void*>(vertices.data()), sizeof(T) * vertices.size(), D3D11_BIND_VERTEX_BUFFER); } template<typename T> unique_ptr_del<ID3D11Buffer> CreateVertexBuffer(const T* vertices, unsigned int count) { return _CreateBufferInternal(reinterpret_cast<const void*>(vertices), sizeof(T) * count, D3D11_BIND_VERTEX_BUFFER); } unique_ptr_del<ID3D11Buffer> CreateIndexBuffer(const unsigned short* indices, unsigned int count) const { return _CreateBufferInternal(reinterpret_cast<const void*>(indices), sizeof(unsigned short) * count, D3D11_BIND_INDEX_BUFFER); } unique_ptr_del<ID3D11Buffer> CreateBuffer(const D3D11_BUFFER_DESC& desc, const void* pData = nullptr) const; //std::shared_ptr<ID3D11ShaderResourceView> CreateShaderResourceView(const std::wstring& fileName); unique_ptr_del<ID3D11SamplerState> CreateSamplerState() const; unique_ptr_del<ID3D11Texture2D> CreateDepthStencilTexture(SIZE size) const; unique_ptr_del<ID3D11RenderTargetView> CreateRenderTargetView( const unique_ptr_del<ID3D11Texture2D>& backBufferTexture) const; unique_ptr_del<ID3D11DepthStencilView> CreateDepthStencilView( const unique_ptr_del<ID3D11Texture2D>& depthStencilTexture) const; static D3D11_DEPTH_STENCIL_DESC DefaultDepthStencilDesc(); unique_ptr_del<ID3D11DepthStencilState> CreateDepthStencilState(D3D11_DEPTH_STENCIL_DESC& desc) const; static D3D11_RASTERIZER_DESC DefaultRasterizerDesc(); unique_ptr_del<ID3D11RasterizerState> CreateRasterizerState(D3D11_RASTERIZER_DESC& desc) const; static D3D11_BLEND_DESC DefaultBlendDesc(); unique_ptr_del<ID3D11BlendState> CreateBlendState(D3D11_BLEND_DESC& desc) const; private: unique_ptr_del<ID3D11Buffer> _CreateBufferInternal(const void* pData, unsigned int byteWidth, D3D11_BIND_FLAG bindFlags) const; }; } #endif __GK2_DEVICE_HELPER_H_
[ "lukaszw896@gmail.com" ]
lukaszw896@gmail.com
a1459c62af981224d4ab6a8f9260bb2b15492494
1fe29d432f7338d725ece6347037faa53198ceed
/feb. 28th/feb. 28th/hi lol.cpp
c4d8dc0c7f061884757cb5bb52308a1cbf5d6abf
[]
no_license
docta-a/Feb.-warm-ups
0fdd96b94db622abf5554539c1669097557a3ed1
930f8aa03a93a867bbc465eee46208fc75aca6fd
refs/heads/master
2020-12-31T00:41:00.156961
2017-03-08T16:49:33
2017-03-08T16:49:33
80,633,619
0
1
null
null
null
null
UTF-8
C++
false
false
676
cpp
#include <iostream> #include <Windows.h> using namespace std; int main() { void annoying(); system("color 4F"); Beep(523, 500); Beep(587, 500); Beep(659, 500); Beep(698, 500); Beep(784, 800); Beep(784, 500); Beep(876, 400); Beep(876, 400); Beep(876, 400); Beep(876, 400); Beep(784, 800); Beep(876, 400); Beep(876, 400); Beep(876, 400); Beep(876, 400); Beep(784, 800); Beep(698, 400); Beep(698, 400); Beep(698, 400); Beep(698, 400); Beep(659, 700); Beep(659, 500); Beep(587, 400); Beep(587, 400); Beep(587, 400); Beep(587, 400); Beep(523, 1000); { for (int i = 0; i<30;i++) MessageBox(NULL, "Suckaa", "Eat my shorts", MB_OK); return 0; } }
[ "Game110AM@605-110-STU20" ]
Game110AM@605-110-STU20
8b5c6b042f4704757d2442a82171e5a1f65b2a01
2044a81b6f3143fbacb2664cc4282f7280065551
/coś.cpp
468bfec64beb172e45c5cd6feb41918d8ed784b2
[]
no_license
Krizuu/Sort_C
780f2be351ea86d35cc467322a0b751bd33ad433
2e7de10e3ed6f45a1bf012397a71f3f4afccc722
refs/heads/master
2020-06-17T03:11:04.987823
2019-07-08T09:11:27
2019-07-08T09:12:25
195,776,824
0
0
null
null
null
null
UTF-8
C++
false
false
580
cpp
#include <stdio.h> int main(void) { int a[5], b, i=0, j=0, t; printf("Ile porostowac? \n"); scanf("%d",&b); printf("Podaj liczbe: \n"); for(i=0; i<b; i++){ scanf("%d", &a[i]); } for(j=0; j<b; j++){ for(i=0; i<b; i++){ if(a[i]>a[i+1]){ t=a[i]; a[i]=a[i+1]; a[i+1]=t; } } } printf("\nPosortowane:\n"); for(i=0; i<b; i++) printf("%d\n", a[i]); }
[ "krzysztof.agas.lange@gmail.com" ]
krzysztof.agas.lange@gmail.com
5c61056808415ad9ae654f3604a0c5e50ccdc563
df49c51ce6de875127bdda7179cfb789de579987
/data.cpp
3aab15a039240c53ce57287587b6f0238782c206
[]
no_license
IgorKIX/Object-oriented-with-txt
a284fcaf72ffa6e0fb90e15fe035ec3cfa58829a
0a2dc5dc08828bed86a7d746ae08f42dd473ec02
refs/heads/master
2020-12-03T00:26:00.303401
2017-07-02T18:37:23
2017-07-02T18:37:23
96,029,847
0
0
null
null
null
null
UTF-8
C++
false
false
608
cpp
#include"data.h" using namespace std; string Data::return_name() { return name; } string Data::return_iban() { return iban; } string Data::return_surname() { return surname; } float Data::return_balance() { return account_balance; } void Data::set_name(string _name) { name = _name; } void Data::set_iban(string _iban) { iban = _iban; } void Data::set_surname(string _surname) { surname = _surname; } void Data::set_balance(float _balance) { account_balance = _balance; } void Data::view() { cout<<name<<endl<<surname<<endl<<iban<<endl<<account_balance<<endl; }
[ "igiblackix@gmail.com" ]
igiblackix@gmail.com
870ea6b21a4634a1767d1dc99acb71fa5a49e8f2
902e56e5eb4dcf96da2b8c926c63e9a0cc30bf96
/Design/Network/NetworkIPBlacklist.h
5d8cf463ae865891106d2fb41f3c3cf76bbce275
[ "BSD-3-Clause" ]
permissive
benkaraban/anima-games-engine
d4e26c80f1025dcef05418a071c0c9cbd18a5670
8aa7a5368933f1b82c90f24814f1447119346c3b
refs/heads/master
2016-08-04T18:31:46.790039
2015-03-22T08:13:55
2015-03-22T08:13:55
32,633,432
2
0
null
null
null
null
UTF-8
C++
false
false
3,297
h
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef NETWORK_NETWORKIPBLACKLIST_H_ #define NETWORK_NETWORKIPBLACKLIST_H_ #include <Core/Standard.h> #include <Core/List.h> #include <Core/Map.h> #include <Core/DateAndTime.h> #include "NetworkEnum.h" namespace Network { const uint32 MIN_TIME_BETWEEN_TWO_CONNECTION = 3;//3 secondes //Blacklist si on dépasse les cent tentatives de connexion en moins de 10 minutes const uint32 BLACKLIST_PERIOD = 600;//10 minutes (600 secondes) const uint32 BLACKLIST_THRESHOLD = 100; class NetworkConnectionAttempts : public Core::Object { public: NetworkConnectionAttempts() : _latestConnectionAttempt(0), _blacklisted(false) { Core::Clock clock; _timeValue = clock.universalTime(); } NetworkConnectionAttempts(const NetworkConnectionAttempts & networkConnectionAttempts) : _latestConnectionAttempt(networkConnectionAttempts._latestConnectionAttempt), _blacklisted(networkConnectionAttempts._blacklisted), _timeValue(networkConnectionAttempts._timeValue) {} ENetworkIPStatus AddConnectionAttempt(); private: uint32 _latestConnectionAttempt; bool _blacklisted; Core::TimeValue _timeValue; Core::List<uint32> _lastPeriodConnectionAttempts; }; class NetworkIPBlacklist : public Core::Object { public: NetworkIPBlacklist(){} ENetworkIPStatus NetworkIPBlacklist::IsClientBlacklisted(uint32 ipAddress); private: Core::Map<uint32, NetworkConnectionAttempts> _connectionAttempsByIP; }; } // namespace Network #endif /* NETWORK_NETWORKIPBLACKLIST_H_ */
[ "contact@anima-games.com@bd273c4a-bd8d-77bb-0e36-6aa87360798c" ]
contact@anima-games.com@bd273c4a-bd8d-77bb-0e36-6aa87360798c
5358b93ee05539cf2fc8b8c5f5314b8cfb1e7f42
c7a04413bf7890f270e0c9298945e004ba41bda1
/Lab16/Lab16.5/Lab16.5.cpp
355790dda194d9c89f4b134c356742ef4cf1bd65
[]
no_license
Matvey191-726/LabsVVP
645187156f91c9bbf43b5fd5d0a9216ece199e5c
7c7d624ddc43030869e35fbafc49a07596e3985a
refs/heads/master
2022-03-27T12:30:19.087681
2019-12-25T10:46:37
2019-12-25T10:46:37
218,157,264
0
0
null
null
null
null
UTF-8
C++
false
false
2,442
cpp
// Lab16.5.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> using namespace std; void Fillmas(int* const mas, const int size) { for (int i = 0; i < size; i++) { cin >> mas[i]; } } void Showmas(int* const mas, const int size) { for (int i = 0; i < size; i++) { cout << mas[i] << " "; } } int main() { setlocale(LC_ALL, "ru"); int size,secondsize, temp = 0; cout << "Введите размер массива: "; cin >> size; int* mas = new int[size]; Fillmas(mas, size); cout << "\n"; Showmas(mas, size); cout << "\n"; for (int i = 0; i < size; i++) { if (mas[i] > 0) { temp++; } } secondsize=size+temp; int* secondmas = new int[secondsize]; for (int i = 0, j = 0; i < secondsize; i++, j++) { if (mas[j] > 0) { secondmas[i] = 0; i++; secondmas[i] = mas[j]; } else { secondmas[i] = mas[j]; } } Showmas(secondmas, secondsize); return 0; delete[] secondmas; delete[] mas; } // Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки" // Отладка программы: F5 или меню "Отладка" > "Запустить отладку" // Советы по началу работы // 1. В окне обозревателя решений можно добавлять файлы и управлять ими. // 2. В окне Team Explorer можно подключиться к системе управления версиями. // 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения. // 4. В окне "Список ошибок" можно просматривать ошибки. // 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода. // 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
[ "matvey.starshiy@mail.ru" ]
matvey.starshiy@mail.ru