hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
8b2d95faad0871688f3c8865c65f8a40e061898d
2,042
cpp
C++
third_party/skia_m63/tests/GrTextureMipMapInvalidationTest.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
2
2018-02-20T15:49:51.000Z
2018-08-22T13:52:30.000Z
third_party/skia_m63/tests/GrTextureMipMapInvalidationTest.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
2
2019-03-14T10:26:45.000Z
2021-08-06T01:24:06.000Z
third_party/skia_m63/tests/GrTextureMipMapInvalidationTest.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
1
2019-09-15T04:51:52.000Z
2019-09-15T04:51:52.000Z
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrTexturePriv.h" #include "SkCanvas.h" #include "SkImage_Base.h" #include "SkSurface.h" #include "Test.h" // Tests that MIP maps are created and invalidated as expected when drawing to and from GrTextures. DEF_GPUTEST_FOR_NULLGL_CONTEXT(GrTextureMipMapInvalidationTest, reporter, ctxInfo) { auto isMipped = [] (SkSurface* surf) { return surf->makeImageSnapshot()->getTexture()->texturePriv().hasMipMaps(); }; auto mipsAreDirty = [] (SkSurface* surf) { return surf->makeImageSnapshot()->getTexture()->texturePriv().mipMapsAreDirty(); }; GrContext* context = ctxInfo.grContext(); auto info = SkImageInfo::MakeN32Premul(256, 256); auto surf1 = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, info); auto surf2 = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, info); // Draw something just in case we ever had a solid color optimization surf1->getCanvas()->drawCircle(128, 128, 50, SkPaint()); surf1->getCanvas()->flush(); // No mipmaps initially REPORTER_ASSERT(reporter, !isMipped(surf1.get())); // Painting with downscale and medium filter quality should result in mipmap creation SkPaint paint; paint.setFilterQuality(kMedium_SkFilterQuality); surf2->getCanvas()->scale(0.2f, 0.2f); surf2->getCanvas()->drawImage(surf1->makeImageSnapshot(), 0, 0, &paint); surf2->getCanvas()->flush(); REPORTER_ASSERT(reporter, isMipped(surf1.get())); REPORTER_ASSERT(reporter, !mipsAreDirty(surf1.get())); // Changing the contents of the surface should invalidate the mipmap, but not de-allocate surf1->getCanvas()->drawCircle(128, 128, 100, SkPaint()); surf1->getCanvas()->flush(); REPORTER_ASSERT(reporter, isMipped(surf1.get())); REPORTER_ASSERT(reporter, mipsAreDirty(surf1.get())); } #endif
35.824561
99
0.70764
[ "solid" ]
8b2e95b6dbc0c220225cd976aab104e5ec4d47cd
1,073
cpp
C++
TC/TCHS08-Round1-1000.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
TC/TCHS08-Round1-1000.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
TC/TCHS08-Round1-1000.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } using namespace std; typedef long long Int; typedef unsigned uint; class DecorationDay { public: int howMany(vector <int>); }; const int MOD = 10000003; int N; vector<int> groups; int dp[60][100005]; int DecorationDay::howMany(vector <int> groups) { int i, j; int N = (int) groups.size(); int M = *max_element(groups.begin(), groups.end()) + 1; dp[0][0] = 1; for (i = 1; i <= N; i++) { dp[i][groups[i - 1]] += 1; for (j = 1; j <= M; j++) { dp[i][gcd(j, groups[i - 1])] = (dp[i][gcd(j, groups[i - 1])] + dp[i - 1][j]) % MOD; } for (j = 1; j <= M; j++) { dp[i + 1][j] = (dp[i + 1][j] + dp[i][j]) % MOD; } } return dp[N][1] % MOD; } //Powered by [KawigiEdit] 2.0!
21.039216
87
0.507922
[ "vector" ]
8b31985ce231767f4809060c65fa9accb46bfc58
3,851
cpp
C++
modules/arm_plugin/tests/functional/shared_tests_instances/behavior/plugin/config.cpp
openvinotoolkit/contrib
fc430b6d29d355d1797633b6dc64c5d42c0b1b67
[ "Apache-2.0" ]
null
null
null
modules/arm_plugin/tests/functional/shared_tests_instances/behavior/plugin/config.cpp
openvinotoolkit/contrib
fc430b6d29d355d1797633b6dc64c5d42c0b1b67
[ "Apache-2.0" ]
null
null
null
modules/arm_plugin/tests/functional/shared_tests_instances/behavior/plugin/config.cpp
openvinotoolkit/contrib
fc430b6d29d355d1797633b6dc64c5d42c0b1b67
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2020-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "multi-device/multi_device_config.hpp" #include "behavior/plugin/configuration_tests.hpp" #include <thread> using namespace BehaviorTestsDefinitions; namespace { const std::vector<std::map<std::string, std::string>> conf = { {} }; const std::vector<std::map<std::string, std::string>> Configs = { {}, {{InferenceEngine::PluginConfigParams::KEY_CPU_THROUGHPUT_STREAMS, InferenceEngine::PluginConfigParams::CPU_THROUGHPUT_AUTO}}, {{InferenceEngine::PluginConfigParams::KEY_CPU_THROUGHPUT_STREAMS, InferenceEngine::PluginConfigParams::CPU_THROUGHPUT_NUMA}}, {{InferenceEngine::PluginConfigParams::KEY_CPU_THROUGHPUT_STREAMS, std::to_string(std::thread::hardware_concurrency())}}, {{InferenceEngine::PluginConfigParams::KEY_CPU_BIND_THREAD, InferenceEngine::PluginConfigParams::NO}}, {{InferenceEngine::PluginConfigParams::KEY_CPU_BIND_THREAD, InferenceEngine::PluginConfigParams::YES}}, }; const std::vector<std::map<std::string, std::string>> MultiConfigs = { {{InferenceEngine::MultiDeviceConfigParams::KEY_MULTI_DEVICE_PRIORITIES , CommonTestUtils::DEVICE_CPU}} }; INSTANTIATE_TEST_CASE_P(smoke_BehaviorTests, CorrectConfigTests, ::testing::Combine( ::testing::Values(CommonTestUtils::DEVICE_CPU), ::testing::ValuesIn(Configs)), CorrectConfigTests::getTestCaseName); INSTANTIATE_TEST_CASE_P(smoke_Multi_BehaviorTests, CorrectConfigTests, ::testing::Combine( ::testing::Values(CommonTestUtils::DEVICE_MULTI), ::testing::ValuesIn(MultiConfigs)), CorrectConfigTests::getTestCaseName); const std::vector<std::map<std::string, std::string>> inconfigs = { {{InferenceEngine::PluginConfigParams::KEY_CPU_THROUGHPUT_STREAMS, "OFF"}}, {{InferenceEngine::PluginConfigParams::KEY_CPU_BIND_THREAD, "OFF"}}, }; const std::vector<std::map<std::string, std::string>> multiinconfigs = { {{InferenceEngine::MultiDeviceConfigParams::KEY_MULTI_DEVICE_PRIORITIES , CommonTestUtils::DEVICE_CPU}, {InferenceEngine::PluginConfigParams::KEY_CPU_THROUGHPUT_STREAMS, "OFF"}}, {{InferenceEngine::MultiDeviceConfigParams::KEY_MULTI_DEVICE_PRIORITIES , CommonTestUtils::DEVICE_CPU}, {InferenceEngine::PluginConfigParams::KEY_CPU_BIND_THREAD, "OFF"}}, }; const std::vector<std::map<std::string, std::string>> multiconf = { {{InferenceEngine::MultiDeviceConfigParams::KEY_MULTI_DEVICE_PRIORITIES , CommonTestUtils::DEVICE_CPU}} }; INSTANTIATE_TEST_CASE_P(smoke_BehaviorTests, IncorrectConfigTests, ::testing::Combine( ::testing::Values(CommonTestUtils::DEVICE_CPU), ::testing::ValuesIn(inconfigs)), IncorrectConfigTests::getTestCaseName); INSTANTIATE_TEST_CASE_P(smoke_Multi_BehaviorTests, IncorrectConfigTests, ::testing::Combine( ::testing::Values(CommonTestUtils::DEVICE_MULTI), ::testing::ValuesIn(multiinconfigs)), IncorrectConfigTests::getTestCaseName); INSTANTIATE_TEST_CASE_P(smoke_BehaviorTests, IncorrectConfigAPITests, ::testing::Combine( ::testing::Values(CommonTestUtils::DEVICE_CPU), ::testing::ValuesIn(inconfigs)), IncorrectConfigAPITests::getTestCaseName); INSTANTIATE_TEST_CASE_P(smoke_Multi_BehaviorTests, IncorrectConfigAPITests, ::testing::Combine( ::testing::Values(CommonTestUtils::DEVICE_MULTI), ::testing::ValuesIn(multiinconfigs)), IncorrectConfigAPITests::getTestCaseName); } // namespace
47.54321
138
0.692288
[ "vector" ]
8b329f64dc6b5c1641e367d7d63cf603a9b02220
251,645
cpp
C++
openr/decision/tests/DecisionTest.cpp
ivanmurashko/openr
5c58b712527446e81281d135979c40fb7163a8f4
[ "MIT" ]
null
null
null
openr/decision/tests/DecisionTest.cpp
ivanmurashko/openr
5c58b712527446e81281d135979c40fb7163a8f4
[ "MIT" ]
null
null
null
openr/decision/tests/DecisionTest.cpp
ivanmurashko/openr
5c58b712527446e81281d135979c40fb7163a8f4
[ "MIT" ]
null
null
null
/** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <memory> #include <fb303/ServiceData.h> #include <folly/IPAddress.h> #include <folly/IPAddressV4.h> #include <folly/IPAddressV6.h> #include <folly/Optional.h> #include <folly/Random.h> #include <folly/futures/Promise.h> #include <folly/init/Init.h> #include <gflags/gflags.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <thrift/lib/cpp2/Thrift.h> #include <thrift/lib/cpp2/protocol/Serializer.h> #include <openr/common/Constants.h> #include <openr/common/NetworkUtil.h> #include <openr/common/Util.h> #include <openr/config/tests/Utils.h> #include <openr/decision/Decision.h> #include <openr/decision/RouteUpdate.h> #include <openr/tests/OpenrThriftServerWrapper.h> DEFINE_bool(stress_test, false, "pass this to run the stress test"); using namespace std; using namespace openr; using namespace testing; namespace fb303 = facebook::fb303; using apache::thrift::CompactSerializer; using apache::thrift::FRAGILE; namespace { /// R1 -> R2, R3 const auto adj12 = createAdjacency("2", "1/2", "2/1", "fe80::2", "192.168.0.2", 10, 100002); const auto adj13 = createAdjacency("3", "1/3", "3/1", "fe80::3", "192.168.0.3", 10, 100003); const auto adj14 = createAdjacency("4", "1/4", "4/1", "fe80::4", "192.168.0.4", 10, 100004); const auto adj12_old_1 = createAdjacency("2", "1/2", "2/1", "fe80::2", "192.168.0.2", 10, 1000021); const auto adj12_old_2 = createAdjacency("2", "1/2", "2/1", "fe80::2", "192.168.0.2", 20, 1000022); const auto adj13_old = createAdjacency("3", "1/3", "3/1", "fe80::3", "192.168.0.3", 10, 1000031); // R2 -> R1, R3, R4 const auto adj21 = createAdjacency("1", "2/1", "1/2", "fe80::1", "192.168.0.1", 10, 100001); const auto adj21_old_1 = createAdjacency("1", "2/1", "1/2", "fe80::1", "192.168.0.1", 10, 1000011); const auto adj23 = createAdjacency("3", "2/3", "3/2", "fe80::3", "192.168.0.3", 10, 100003); const auto adj24 = createAdjacency("4", "2/4", "4/2", "fe80::4", "192.168.0.4", 10, 100004); // R3 -> R1, R2, R4 const auto adj31 = createAdjacency("1", "3/1", "1/3", "fe80::1", "192.168.0.1", 10, 100001); const auto adj31_old = createAdjacency("1", "3/1", "1/3", "fe80::1", "192.168.0.1", 10, 1000011); const auto adj32 = createAdjacency("2", "3/2", "2/3", "fe80::2", "192.168.0.2", 10, 100002); const auto adj34 = createAdjacency("4", "3/4", "4/3", "fe80::4", "192.168.0.4", 10, 100004); // R4 -> R2, R3 const auto adj41 = createAdjacency("1", "4/1", "1/4", "fe80::1", "192.168.0.1", 10, 100001); const auto adj42 = createAdjacency("2", "4/2", "2/4", "fe80::2", "192.168.0.2", 10, 100002); const auto adj43 = createAdjacency("3", "4/3", "3/4", "fe80::3", "192.168.0.3", 10, 100003); // R5 -> R4 const auto adj54 = createAdjacency("4", "5/4", "4/5", "fe80::4", "192.168.0.4", 10, 100001); const auto addr1 = toIpPrefix("::ffff:10.1.1.1/128"); const auto addr2 = toIpPrefix("::ffff:10.2.2.2/128"); const auto addr3 = toIpPrefix("::ffff:10.3.3.3/128"); const auto addr4 = toIpPrefix("::ffff:10.4.4.4/128"); const auto addr5 = toIpPrefix("::ffff:10.4.4.5/128"); const auto addr6 = toIpPrefix("::ffff:10.4.4.6/128"); const auto addr1V4 = toIpPrefix("10.1.1.1/32"); const auto addr2V4 = toIpPrefix("10.2.2.2/32"); const auto addr3V4 = toIpPrefix("10.3.3.3/32"); const auto addr4V4 = toIpPrefix("10.4.4.4/32"); const auto addr1Cidr = toIPNetwork(addr1); const auto addr2Cidr = toIPNetwork(addr2); const auto addr2V4Cidr = toIPNetwork(addr2V4); const auto bgpAddr1 = toIpPrefix("2401:1::10.1.1.1/32"); const auto bgpAddr2 = toIpPrefix("2401:2::10.2.2.2/32"); const auto bgpAddr3 = toIpPrefix("2401:3::10.3.3.3/32"); const auto bgpAddr4 = toIpPrefix("2401:4::10.4.4.4/32"); const auto bgpAddr1V4 = toIpPrefix("10.11.1.1/16"); const auto bgpAddr2V4 = toIpPrefix("10.22.2.2/16"); const auto bgpAddr3V4 = toIpPrefix("10.33.3.3/16"); const auto bgpAddr4V4 = toIpPrefix("10.43.4.4/16"); const auto prefixDb1 = createPrefixDb("1", {createPrefixEntry(addr1)}); const auto prefixDb2 = createPrefixDb("2", {createPrefixEntry(addr2)}); const auto prefixDb3 = createPrefixDb("3", {createPrefixEntry(addr3)}); const auto prefixDb4 = createPrefixDb("4", {createPrefixEntry(addr4)}); const auto prefixDb1V4 = createPrefixDb("1", {createPrefixEntry(addr1V4)}); const auto prefixDb2V4 = createPrefixDb("2", {createPrefixEntry(addr2V4)}); const auto prefixDb3V4 = createPrefixDb("3", {createPrefixEntry(addr3V4)}); const auto prefixDb4V4 = createPrefixDb("4", {createPrefixEntry(addr4V4)}); const thrift::MplsAction labelPopAction{ createMplsAction(thrift::MplsActionCode::POP_AND_LOOKUP)}; const thrift::MplsAction labelPhpAction{ createMplsAction(thrift::MplsActionCode::PHP)}; const thrift::MplsAction labelSwapAction1{ createMplsAction(thrift::MplsActionCode::SWAP, 1)}; const thrift::MplsAction labelSwapAction2{ createMplsAction(thrift::MplsActionCode::SWAP, 2)}; const thrift::MplsAction labelSwapAction3{ createMplsAction(thrift::MplsActionCode::SWAP, 3)}; const thrift::MplsAction labelSwapAction4{ createMplsAction(thrift::MplsActionCode::SWAP, 4)}; const thrift::MplsAction labelSwapAction5{ createMplsAction(thrift::MplsActionCode::SWAP, 5)}; const thrift::NextHopThrift labelPopNextHop{createNextHop( toBinaryAddress(folly::IPAddressV6("::")), std::nullopt /* ifName */, 0 /* metric */, labelPopAction, kTestingAreaName)}; // timeout to wait until decision debounce // (i.e. spf recalculation, route rebuild) finished const std::chrono::milliseconds debounceTimeoutMin{10}; const std::chrono::milliseconds debounceTimeoutMax{500}; // Empty Perf Events const thrift::AdjacencyDatabase kEmptyAdjDb; const apache::thrift::optional_field_ref<thrift::PerfEvents const&> kEmptyPerfEventRef{kEmptyAdjDb.perfEvents_ref()}; // TODO @girasoley - Remove this once we implement feature in BGP to not // program Open/R received routes. // Decision enforces the need for loopback address of the node void addLoopbackAddress(thrift::PrefixDatabase& prefixDb, bool v4Enabled) { const auto index = folly::to<size_t>(prefixDb.thisNodeName_ref().value()); if (v4Enabled) { prefixDb.prefixEntries_ref()->emplace_back( createPrefixEntry(toIpPrefix(folly::sformat("172.0.0.{}/32", index)))); } else { prefixDb.prefixEntries_ref()->emplace_back( createPrefixEntry(toIpPrefix(folly::sformat("fd00::{}/128", index)))); } } thrift::PrefixDatabase createPrefixDbWithKspfAlgo( thrift::PrefixDatabase const& prefixDb, std::optional<thrift::PrefixType> prefixType = std::nullopt, std::optional<thrift::IpPrefix> prefix = std::nullopt, std::optional<uint32_t> prependLabel = std::nullopt, bool v4Enabled = false) { thrift::PrefixDatabase newPrefixDb = prefixDb; for (auto& p : *newPrefixDb.prefixEntries_ref()) { p.forwardingType_ref() = thrift::PrefixForwardingType::SR_MPLS; p.forwardingAlgorithm_ref() = thrift::PrefixForwardingAlgorithm::KSP2_ED_ECMP; if (prefixType == thrift::PrefixType::BGP and not prefix.has_value()) { p.type_ref() = thrift::PrefixType::BGP; p.mv_ref() = thrift::MetricVector(); } } if (prefix.has_value()) { thrift::PrefixEntry entry; *entry.prefix_ref() = prefix.value(); entry.forwardingType_ref() = thrift::PrefixForwardingType::SR_MPLS; entry.forwardingAlgorithm_ref() = thrift::PrefixForwardingAlgorithm::KSP2_ED_ECMP; entry.mv_ref() = thrift::MetricVector(); entry.type_ref() = thrift::PrefixType::BGP; if (prependLabel.has_value()) { entry.prependLabel_ref() = prependLabel.value(); } newPrefixDb.prefixEntries_ref()->push_back(entry); } // Add loopback address if any if (prefixType == thrift::PrefixType::BGP and not prefix.has_value()) { addLoopbackAddress(newPrefixDb, v4Enabled); } return newPrefixDb; } thrift::NextHopThrift createNextHopFromAdj( thrift::Adjacency adj, bool isV4, int32_t metric, std::optional<thrift::MplsAction> mplsAction = std::nullopt, const std::string& area = kTestingAreaName) { return createNextHop( isV4 ? *adj.nextHopV4_ref() : *adj.nextHopV6_ref(), *adj.ifName_ref(), metric, std::move(mplsAction), area, *adj.otherNodeName_ref()); } thrift::PrefixMetrics createMetrics(int32_t pp, int32_t sp, int32_t d) { thrift::PrefixMetrics metrics; metrics.path_preference_ref() = pp; metrics.source_preference_ref() = sp; metrics.distance_ref() = d; return metrics; } thrift::PrefixEntry createPrefixEntryWithMetrics( thrift::IpPrefix const& prefix, thrift::PrefixType const& type, thrift::PrefixMetrics const& metrics) { thrift::PrefixEntry entry; entry.prefix_ref() = prefix; entry.type_ref() = type; entry.metrics_ref() = metrics; return entry; } // Note: use unordered_set bcoz paths in a route can be in arbitrary order using NextHops = unordered_set<thrift::NextHopThrift>; using RouteMap = unordered_map< pair<string /* node name */, string /* prefix or label */>, NextHops>; using PrefixRoutes = unordered_map< pair<string /* node name */, string /* prefix or label */>, thrift::UnicastRoute>; // Note: routeMap will be modified void fillRouteMap( const string& node, RouteMap& routeMap, const DecisionRouteDb& routeDb) { for (auto const& [_, entry] : routeDb.unicastRoutes) { auto prefix = folly::IPAddress::networkToString(entry.prefix); for (const auto& nextHop : entry.nexthops) { VLOG(4) << "node: " << node << " prefix: " << prefix << " -> " << toString(nextHop); routeMap[make_pair(node, prefix)].emplace(nextHop); } } for (auto const& [_, entry] : routeDb.mplsRoutes) { auto topLabelStr = std::to_string(entry.label); for (const auto& nextHop : entry.nexthops) { VLOG(4) << "node: " << node << " label: " << topLabelStr << " -> " << toString(nextHop); routeMap[make_pair(node, topLabelStr)].emplace(nextHop); } } } void fillRouteMap( const string& node, RouteMap& routeMap, const thrift::RouteDatabase& routeDb) { for (auto const& route : *routeDb.unicastRoutes_ref()) { auto prefix = toString(*route.dest_ref()); for (const auto& nextHop : *route.nextHops_ref()) { VLOG(4) << "node: " << node << " prefix: " << prefix << " -> " << toString(nextHop); routeMap[make_pair(node, prefix)].emplace(nextHop); } } for (auto const& route : *routeDb.mplsRoutes_ref()) { auto topLabelStr = std::to_string(*route.topLabel_ref()); for (const auto& nextHop : *route.nextHops_ref()) { VLOG(4) << "node: " << node << " label: " << topLabelStr << " -> " << toString(nextHop); routeMap[make_pair(node, topLabelStr)].emplace(nextHop); } } } RouteMap getRouteMap( SpfSolver& spfSolver, const vector<string>& nodes, std::unordered_map<std::string, LinkState> const& areaLinkStates, PrefixState const& prefixState) { RouteMap routeMap; for (string const& node : nodes) { auto routeDb = spfSolver.buildRouteDb(node, areaLinkStates, prefixState); if (not routeDb.has_value()) { continue; } fillRouteMap(node, routeMap, routeDb.value()); } return routeMap; } // Note: routeMap will be modified void fillPrefixRoutes( const string& node, PrefixRoutes& prefixRoutes, const DecisionRouteDb& routeDb) { for (auto const& [_, entry] : routeDb.unicastRoutes) { auto prefix = folly::IPAddress::networkToString(entry.prefix); prefixRoutes[make_pair(node, prefix)] = entry.toThrift(); } } PrefixRoutes getUnicastRoutes( SpfSolver& spfSolver, const vector<string>& nodes, std::unordered_map<std::string, LinkState> const& areaLinkStates, PrefixState const& prefixState) { PrefixRoutes prefixRoutes; for (string const& node : nodes) { auto routeDb = spfSolver.buildRouteDb(node, areaLinkStates, prefixState); if (not routeDb.has_value()) { continue; } fillPrefixRoutes(node, prefixRoutes, routeDb.value()); } return prefixRoutes; } void validateAdjLabelRoutes( RouteMap const& routeMap, std::string const& nodeName, std::vector<thrift::Adjacency> const& adjs) { for (auto const& adj : adjs) { const std::pair<std::string, std::string> routeKey{ nodeName, std::to_string(*adj.adjLabel_ref())}; ASSERT_EQ(1, routeMap.count(routeKey)); EXPECT_EQ( routeMap.at(routeKey), NextHops({createNextHopFromAdj( adj, false, *adj.metric_ref(), labelPhpAction)})); } } void validatePopLabelRoute( RouteMap const& routeMap, std::string const& nodeName, int32_t nodeLabel) { const std::pair<std::string, std::string> routeKey{ nodeName, std::to_string(nodeLabel)}; ASSERT_EQ(1, routeMap.count(routeKey)); EXPECT_EQ(routeMap.at(routeKey), NextHops({labelPopNextHop})); } void printRouteDb(const std::optional<thrift::RouteDatabase>& routeDb) { for (const auto ucRoute : *routeDb.value().unicastRoutes_ref()) { LOG(INFO) << "dest: " << toString(*ucRoute.dest_ref()); if (ucRoute.adminDistance_ref().has_value()) { LOG(INFO) << "ad_dis: " << static_cast<int>(ucRoute.adminDistance_ref().value()); } LOG(INFO) << "doNotInstall: " << *ucRoute.doNotInstall_ref(); for (const auto nh : *ucRoute.nextHops_ref()) { LOG(INFO) << "nexthops: " << toString(nh); } } } const auto& getUnicastNextHops(const thrift::UnicastRoute& r) { return *r.nextHops_ref(); } const auto& getMplsNextHops(const thrift::MplsRoute& r) { return *r.nextHops_ref(); } // DPERECTAED: utility functions provided for old test callsites that once used // PrefixState::updatePrefixDatabase() expecting all node route advertisments to // be synced. // // In newly written tests, prefer // PrefixState::updatePrefix() and PrefixState::deletePrefix() for writing // PrefixState::getReceivedRoutesFiltered() for reading thrift::PrefixDatabase getPrefixDbForNode( PrefixState const& state, std::string const& name, std::string const& area = kTestingAreaName) { thrift::PrefixDatabase prefixDb; prefixDb.thisNodeName_ref() = name; prefixDb.area_ref() = area; thrift::ReceivedRouteFilter filter; filter.nodeName_ref() = name; filter.areaName_ref() = area; for (auto const& routeDetail : state.getReceivedRoutesFiltered(filter)) { prefixDb.prefixEntries_ref()->push_back( routeDetail.get_routes().at(0).get_route()); } return prefixDb; } std::unordered_set<folly::CIDRNetwork> updatePrefixDatabase( PrefixState& state, thrift::PrefixDatabase const& prefixDb) { auto const& nodeName = prefixDb.get_thisNodeName(); auto const& area = prefixDb.get_area(); std::unordered_set<PrefixKey> oldKeys, newKeys; auto oldDb = getPrefixDbForNode( state, prefixDb.get_thisNodeName(), prefixDb.get_area()); for (auto const& entry : oldDb.get_prefixEntries()) { oldKeys.emplace(nodeName, toIPNetwork(entry.get_prefix()), area); } std::unordered_set<folly::CIDRNetwork> changed; for (auto const& entry : prefixDb.get_prefixEntries()) { PrefixKey key(nodeName, toIPNetwork(entry.get_prefix()), area); changed.merge(state.updatePrefix(key, entry)); newKeys.insert(std::move(key)); } for (auto const& key : oldKeys) { if (not newKeys.count(key)) { changed.merge(state.deletePrefix(key)); } } return changed; } } // anonymous namespace // // Create a broken topology where R1 and R2 connect no one // Expect no routes coming out of the spfSolver // TEST(ShortestPathTest, UnreachableNodes) { // no adjacency auto adjacencyDb1 = createAdjDb("1", {}, 0); auto adjacencyDb2 = createAdjDb("2", {}, 0); std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* disable v4 */, false /* disable LFA */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb2).topologyChanged); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2).empty()); unordered_map< pair<string /* node name */, string /* ip prefix */>, thrift::UnicastRoute> routeMap; vector<string> allNodes = {"1", "2"}; for (string const& node : allNodes) { auto routeDb = spfSolver.buildRouteDb(node, areaLinkStates, prefixState); ASSERT_TRUE(routeDb.has_value()); EXPECT_EQ(0, routeDb->unicastRoutes.size()); EXPECT_EQ(0, routeDb->mplsRoutes.size()); // No label routes } } // // R1 and R2 are adjacent, and R1 has this declared in its // adjacency database. However, R1 is missing the AdjDb from // R2. It should not be able to compute path to R2 in this case. // TEST(ShortestPathTest, MissingNeighborAdjacencyDb) { auto adjacencyDb1 = createAdjDb("1", {adj12}, 0); std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* disable v4 */, false /* disable LFA */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; // // Feed SPF solver with R1's AdjDb and all prefixes, but do not // mention the R2's AdjDb. Add R2's prefixes though. // EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2).empty()); auto routeDb = spfSolver.buildRouteDb("1", areaLinkStates, prefixState); ASSERT_TRUE(routeDb.has_value()); EXPECT_EQ(0, routeDb->unicastRoutes.size()); EXPECT_EQ(0, routeDb->mplsRoutes.size()); } // // R1 and R2 are adjacent, and R1 has this declared in its // adjacency database. R1 received AdjacencyDatabase from R2, // but it missing adjacency to R1. We should not see routes // from R1 to R2. // TEST(ShortestPathTest, EmptyNeighborAdjacencyDb) { auto adjacencyDb1 = createAdjDb("1", {adj12}, 0); auto adjacencyDb2 = createAdjDb("2", {}, 0); std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* disable v4 */, false /* disable LFA */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; // // Feed SPF solver with R1's AdjDb and all prefixes, but do not // mention the R2's AdjDb. Add R2's prefixes though. // EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb2).topologyChanged); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2).empty()); // dump routes for both nodes, expect no routing entries auto routeDb = spfSolver.buildRouteDb("1", areaLinkStates, prefixState); ASSERT_TRUE(routeDb.has_value()); EXPECT_EQ(0, routeDb->unicastRoutes.size()); routeDb = spfSolver.buildRouteDb("2", areaLinkStates, prefixState); ASSERT_TRUE(routeDb.has_value()); EXPECT_EQ(0, routeDb->unicastRoutes.size()); } // // Query route for unknown neighbor. It should return none // TEST(ShortestPathTest, UnknownNode) { std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* disable v4 */, false /* disable LFA */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); PrefixState prefixState; auto routeDb = spfSolver.buildRouteDb("1", areaLinkStates, prefixState); EXPECT_FALSE(routeDb.has_value()); routeDb = spfSolver.buildRouteDb("2", areaLinkStates, prefixState); EXPECT_FALSE(routeDb.has_value()); } /** * Test to verify adjacencyDatabase update */ TEST(SpfSolver, AdjacencyUpdate) { auto adjacencyDb1 = createAdjDb("1", {adj12}, 1); auto adjacencyDb2 = createAdjDb("2", {adj21}, 2); std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* disable v4 */, false /* disable LFA */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; // // Feed SPF solver with R1 and R2's adjacency + prefix dbs // { auto res = linkState.updateAdjacencyDatabase(adjacencyDb1); EXPECT_FALSE(res.topologyChanged); EXPECT_TRUE(res.nodeLabelChanged); // label changed for node1 } { auto res = linkState.updateAdjacencyDatabase(adjacencyDb2); EXPECT_TRUE(res.topologyChanged); EXPECT_TRUE(res.nodeLabelChanged); } EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2).empty()); // // dump routes for both nodes, expect 4 route entries (1 unicast, 3 label) on // each (node1-label, node2-label and adjacency-label) // auto routeDb = spfSolver.buildRouteDb("1", areaLinkStates, prefixState); ASSERT_TRUE(routeDb.has_value()); EXPECT_EQ(1, routeDb->unicastRoutes.size()); EXPECT_EQ(3, routeDb->mplsRoutes.size()); // node and adj route routeDb = spfSolver.buildRouteDb("2", areaLinkStates, prefixState); ASSERT_TRUE(routeDb.has_value()); EXPECT_EQ(1, routeDb->unicastRoutes.size()); EXPECT_EQ(3, routeDb->mplsRoutes.size()); // node and adj route // // Update adjacency database of node 1 by changing it's nexthops and verift // that update properly responds to the event // *adjacencyDb1.adjacencies_ref()[0].nextHopV6_ref() = toBinaryAddress("fe80::1234:b00c"); { auto res = linkState.updateAdjacencyDatabase(adjacencyDb1); EXPECT_FALSE(res.topologyChanged); EXPECT_TRUE(res.linkAttributesChanged); } // // dump routes for both nodes, expect 4 route entries (1 unicast, 3 label) on // each (node1-label, node2-label and adjacency-label) // routeDb = spfSolver.buildRouteDb("1", areaLinkStates, prefixState); ASSERT_TRUE(routeDb.has_value()); EXPECT_EQ(1, routeDb->unicastRoutes.size()); EXPECT_EQ(3, routeDb->mplsRoutes.size()); // node and adj route routeDb = spfSolver.buildRouteDb("2", areaLinkStates, prefixState); ASSERT_TRUE(routeDb.has_value()); EXPECT_EQ(1, routeDb->unicastRoutes.size()); EXPECT_EQ(3, routeDb->mplsRoutes.size()); // node and adj route // // Update adjacency database of node 2 by changing it's nexthops and verift // that update properly responds to the event (no spf trigger needed) // *adjacencyDb2.adjacencies_ref()[0].nextHopV6_ref() = toBinaryAddress("fe80::5678:b00c"); { auto res = linkState.updateAdjacencyDatabase(adjacencyDb2); EXPECT_FALSE(res.topologyChanged); EXPECT_TRUE(res.linkAttributesChanged); } // // dump routes for both nodes, expect 4 route entries (1 unicast, 3 label) on // each (node1-label, node2-label and adjacency-label) // routeDb = spfSolver.buildRouteDb("1", areaLinkStates, prefixState); ASSERT_TRUE(routeDb.has_value()); EXPECT_EQ(1, routeDb->unicastRoutes.size()); EXPECT_EQ(3, routeDb->mplsRoutes.size()); // node and adj route routeDb = spfSolver.buildRouteDb("2", areaLinkStates, prefixState); ASSERT_TRUE(routeDb.has_value()); EXPECT_EQ(1, routeDb->unicastRoutes.size()); EXPECT_EQ(3, routeDb->mplsRoutes.size()); // node and adj route // // Change adjLabel. This should report route-attribute change only for node1 // and not for node2's adjLabel change // adjacencyDb1.adjacencies_ref()[0].adjLabel_ref() = 111; { auto res = linkState.updateAdjacencyDatabase(adjacencyDb1); EXPECT_FALSE(res.topologyChanged); EXPECT_TRUE(res.linkAttributesChanged); } adjacencyDb2.adjacencies_ref()[0].adjLabel_ref() = 222; { auto res = linkState.updateAdjacencyDatabase(adjacencyDb2); EXPECT_FALSE(res.topologyChanged); EXPECT_TRUE(res.linkAttributesChanged); } // Change nodeLabel. adjacencyDb1.nodeLabel_ref() = 11; { auto res = linkState.updateAdjacencyDatabase(adjacencyDb1); EXPECT_FALSE(res.topologyChanged); EXPECT_FALSE(res.linkAttributesChanged); EXPECT_TRUE(res.nodeLabelChanged); } adjacencyDb2.nodeLabel_ref() = 22; { auto res = linkState.updateAdjacencyDatabase(adjacencyDb2); EXPECT_FALSE(res.topologyChanged); EXPECT_FALSE(res.linkAttributesChanged); EXPECT_TRUE(res.nodeLabelChanged); } } // // Node-1 connects to 2 but 2 doesn't report bi-directionality // Node-2 and Node-3 are bi-directionally connected // TEST(MplsRoutes, BasicTest) { const std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* disable v4 */, false /* disable LFA */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; // Add all adjacency DBs auto adjacencyDb1 = createAdjDb("1", {adj12}, 1); auto adjacencyDb2 = createAdjDb("2", {adj23}, 0); // No node label auto adjacencyDb3 = createAdjDb("3", {adj32}, 3); EXPECT_EQ( LinkState::LinkStateChange(false, false, true), linkState.updateAdjacencyDatabase(adjacencyDb1)); EXPECT_EQ( LinkState::LinkStateChange(false, false, false), linkState.updateAdjacencyDatabase(adjacencyDb1)); EXPECT_EQ( LinkState::LinkStateChange(false, false, false), linkState.updateAdjacencyDatabase(adjacencyDb2)); EXPECT_EQ( LinkState::LinkStateChange(true, false, true), linkState.updateAdjacencyDatabase(adjacencyDb3)); auto routeMap = getRouteMap(spfSolver, {"1", "2", "3"}, areaLinkStates, prefixState); EXPECT_EQ(5, routeMap.size()); // Validate 1's routes validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); // Validate 2's routes (no node label route) validateAdjLabelRoutes(routeMap, "2", {adj23}); // Validate 3's routes validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", {adj32}); } TEST(BGPRedistribution, BasicOperation) { std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* disable v4 */, false /* disable LFA */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; auto adjacencyDb1 = createAdjDb("1", {adj12, adj13}, 0); auto adjacencyDb2 = createAdjDb("2", {adj21}, 0); auto adjacencyDb3 = createAdjDb("3", {adj31}, 0); EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb2).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); thrift::PrefixDatabase prefixDb1WithBGP = prefixDb1; thrift::PrefixDatabase prefixDb2WithBGP = prefixDb2; std::string data1 = "data1", data2 = "data2"; thrift::IpPrefix bgpPrefix1 = addr3; thrift::MetricVector mv1, mv2; int64_t numMetrics = 5; mv1.metrics_ref()->resize(numMetrics); mv2.metrics_ref()->resize(numMetrics); for (int64_t i = 0; i < numMetrics; ++i) { mv1.metrics_ref()[i].type_ref() = i; mv2.metrics_ref()[i].type_ref() = i; mv1.metrics_ref()[i].priority_ref() = i; mv2.metrics_ref()[i].priority_ref() = i; mv1.metrics_ref()[i].op_ref() = thrift::CompareType::WIN_IF_PRESENT; mv2.metrics_ref()[i].op_ref() = thrift::CompareType::WIN_IF_PRESENT; mv1.metrics_ref()[i].isBestPathTieBreaker_ref() = false; mv2.metrics_ref()[i].isBestPathTieBreaker_ref() = false; *mv1.metrics_ref()[i].metric_ref() = *mv2.metrics_ref()[i].metric_ref() = {i}; } // only node1 advertises the BGP prefix, it will have the best path prefixDb1WithBGP.prefixEntries_ref()->push_back(createPrefixEntry( bgpPrefix1, thrift::PrefixType::BGP, data1, thrift::PrefixForwardingType::IP, thrift::PrefixForwardingAlgorithm::SP_ECMP, mv1, std::nullopt)); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1WithBGP).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2WithBGP).empty()); auto decisionRouteDb = *spfSolver.buildRouteDb("2", areaLinkStates, prefixState); auto routeDb = decisionRouteDb.toThrift(); auto route1 = createUnicastRoute( bgpPrefix1, {createNextHopFromAdj(adj21, false, *adj21.metric_ref())}); route1.doNotInstall_ref() = false; EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(2)); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::Contains(route1)); // add the prefix to node2 with the same metric vector. we expect the bgp // route to be gone since both nodes have same metric vector we can't // determine a best path prefixDb2WithBGP.prefixEntries_ref()->push_back(createPrefixEntry( bgpPrefix1, thrift::PrefixType::BGP, data2, thrift::PrefixForwardingType::IP, thrift::PrefixForwardingAlgorithm::SP_ECMP, mv2, std::nullopt)); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2WithBGP).empty()); decisionRouteDb = *spfSolver.buildRouteDb("1", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(1)); // decrease the one of second node's metrics and expect to see the route // toward just the first prefixDb2WithBGP.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .metric_ref() ->front()--; EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2WithBGP).empty()); decisionRouteDb = *spfSolver.buildRouteDb("2", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(2)); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::Contains(route1)); // now make 2 better prefixDb2WithBGP.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .metric_ref() ->front() += 2; EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2WithBGP).empty()); auto route2 = createUnicastRoute( bgpPrefix1, {createNextHopFromAdj(adj12, false, *adj12.metric_ref())}); route2.doNotInstall_ref() = false; decisionRouteDb = *spfSolver.buildRouteDb("1", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(2)); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::Contains(route2)); // now make that a tie break for a multipath route prefixDb1WithBGP.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .isBestPathTieBreaker_ref() = true; prefixDb2WithBGP.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .isBestPathTieBreaker_ref() = true; EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1WithBGP).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2WithBGP).empty()); // 1 and 2 will not program BGP route EXPECT_THAT( spfSolver.buildRouteDb("1", areaLinkStates, prefixState) .value() .unicastRoutes, testing::SizeIs(1)); // 3 will program the BGP route towards both decisionRouteDb = *spfSolver.buildRouteDb("3", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(3)); EXPECT_THAT( *routeDb.unicastRoutes_ref(), testing::Contains(AllOf( Truly([&bgpPrefix1](auto i) { return i.dest_ref() == bgpPrefix1; }), ResultOf( getUnicastNextHops, testing::UnorderedElementsAre( createNextHopFromAdj(adj31, false, 10)))))); // dicsonnect the network, each node will consider it's BGP route the best, // and thus not program anything EXPECT_TRUE(linkState.updateAdjacencyDatabase(createAdjDb("1", {}, 0)) .topologyChanged); decisionRouteDb = *spfSolver.buildRouteDb("1", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT( *routeDb.unicastRoutes_ref(), testing::AllOf( testing::Not(testing::Contains(route1)), testing::Not(testing::Contains(route2)))); decisionRouteDb = *spfSolver.buildRouteDb("2", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT( *routeDb.unicastRoutes_ref(), testing::AllOf( testing::Not(testing::Contains(route1)), testing::Not(testing::Contains(route2)))); } /** * node1 connects to node2 and node3. Both are same distance away (10). Both * node2 and node3 announces prefix1 with same metric vector. Routes for prefix1 * is inspected on node1 at each step. Test outline follows * * 1) prefix1 -> {node2, node3} * 2) Increase cost towards node3 to 20; prefix -> {node2} * 3) mark link towards node2 as drained; prefix1 -> {node3} * 3) Set cost towards node2 to 20 (still drained); prefix1 -> {node3} * 4) Undrain link; prefix1 -> {node2, node3} */ TEST(BGPRedistribution, IgpMetric) { const std::string data1{"data1"}; const auto expectedAddr = addr1; std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* enableV4 */, false /* enableOrderedFib */, false /* bgpDryRun */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; // // Create BGP prefix // thrift::MetricVector metricVector; int64_t numMetrics = 5; metricVector.metrics_ref()->resize(numMetrics); for (int64_t i = 0; i < numMetrics; ++i) { metricVector.metrics_ref()[i].type_ref() = i; metricVector.metrics_ref()[i].priority_ref() = i; metricVector.metrics_ref()[i].op_ref() = thrift::CompareType::WIN_IF_PRESENT; metricVector.metrics_ref()[i].isBestPathTieBreaker_ref() = (i == numMetrics - 1); *metricVector.metrics_ref()[i].metric_ref() = {i}; } const auto bgpPrefix2 = createPrefixEntry( addr1, thrift::PrefixType::BGP, data1, thrift::PrefixForwardingType::IP, thrift::PrefixForwardingAlgorithm::SP_ECMP, metricVector); // Make tie breaking metric different *metricVector.metrics_ref()->at(4).metric_ref() = {100}; // Make it different const auto bgpPrefix3 = createPrefixEntry( addr1, thrift::PrefixType::BGP, data1, thrift::PrefixForwardingType::IP, thrift::PrefixForwardingAlgorithm::SP_ECMP, metricVector); // // Setup adjacencies // auto adjacencyDb1 = createAdjDb("1", {adj12, adj13}, 0); auto adjacencyDb2 = createAdjDb("2", {adj21}, 0); auto adjacencyDb3 = createAdjDb("3", {adj31}, 0); EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb2).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); // // Update prefix databases // auto prefixDb2WithBgp = createPrefixDb("2", {createPrefixEntry(addr2), bgpPrefix2}); auto prefixDb3WithBgp = createPrefixDb("3", {createPrefixEntry(addr3), bgpPrefix3}); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2WithBgp).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb3WithBgp).empty()); // // Step-1 prefix1 -> {node2, node3} // auto decisionRouteDb = *spfSolver.buildRouteDb("1", areaLinkStates, prefixState); auto routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(3)); EXPECT_THAT( *routeDb.unicastRoutes_ref(), testing::Contains(AllOf( Truly( [&expectedAddr](auto i) { return i.dest_ref() == expectedAddr; }), ResultOf( getUnicastNextHops, testing::UnorderedElementsAre( createNextHopFromAdj(adj12, false, 10), createNextHopFromAdj(adj13, false, 10)))))); // // Increase cost towards node3 to 20; prefix -> {node2} // adjacencyDb1.adjacencies_ref()[1].metric_ref() = 20; EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); decisionRouteDb = *spfSolver.buildRouteDb("1", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(3)); EXPECT_THAT( *routeDb.unicastRoutes_ref(), testing::Contains(AllOf( Truly( [&expectedAddr](auto i) { return i.dest_ref() == expectedAddr; }), ResultOf( getUnicastNextHops, testing::UnorderedElementsAre( createNextHopFromAdj(adj12, false, 10)))))); // // mark link towards node2 as drained; prefix1 -> {node3} // No route towards addr2 (node2's loopback) // adjacencyDb1.adjacencies_ref()[0].isOverloaded_ref() = true; EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); decisionRouteDb = *spfSolver.buildRouteDb("1", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(2)); EXPECT_THAT( *routeDb.unicastRoutes_ref(), testing::Contains(AllOf( Truly( [&expectedAddr](auto i) { return i.dest_ref() == expectedAddr; }), ResultOf( getUnicastNextHops, testing::UnorderedElementsAre( createNextHopFromAdj(adj13, false, 20)))))); // // Set cost towards node2 to 20 (still drained); prefix1 -> {node3} // No route towards addr2 (node2's loopback) // adjacencyDb1.adjacencies_ref()[0].metric_ref() = 20; EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); decisionRouteDb = *spfSolver.buildRouteDb("1", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(2)); EXPECT_THAT( *routeDb.unicastRoutes_ref(), testing::Contains(AllOf( Truly( [&expectedAddr](auto i) { return i.dest_ref() == expectedAddr; }), ResultOf( getUnicastNextHops, testing::UnorderedElementsAre( createNextHopFromAdj(adj13, false, 20)))))); // // Undrain link; prefix1 -> {node2, node3} // adjacencyDb1.adjacencies_ref()[0].isOverloaded_ref() = false; EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); decisionRouteDb = *spfSolver.buildRouteDb("1", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(3)); EXPECT_THAT( *routeDb.unicastRoutes_ref(), testing::Contains(AllOf( Truly( [&expectedAddr](auto i) { return i.dest_ref() == expectedAddr; }), ResultOf( getUnicastNextHops, testing::UnorderedElementsAre( createNextHopFromAdj(adj12, false, 20), createNextHopFromAdj(adj13, false, 20)))))); } TEST(Decision, BestRouteSelection) { std::string nodeName("1"); const auto expectedAddr = addr1; SpfSolver spfSolver( nodeName, false /* enableV4 */, false /* enableOrderedFib */, false /* bgpDryRun */, true /* enableBestRouteSelection */); std::unordered_map<std::string, LinkState> areaLinkStates; PrefixState prefixState; // // Setup adjacencies // 2 <--> 1 <--> 3 // auto adjacencyDb1 = createAdjDb("1", {adj12, adj13}, 1); auto adjacencyDb2 = createAdjDb("2", {adj21}, 2); auto adjacencyDb3 = createAdjDb("3", {adj31}, 3); areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb2).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); // // Setup prefixes. node2 and node3 announces the same prefix with same metrics // const auto node2Prefix = createPrefixEntryWithMetrics( addr1, thrift::PrefixType::DEFAULT, createMetrics(200, 0, 0)); const auto node3Prefix = createPrefixEntryWithMetrics( addr1, thrift::PrefixType::DEFAULT, createMetrics(200, 0, 0)); EXPECT_FALSE( updatePrefixDatabase(prefixState, createPrefixDb("2", {node2Prefix})) .empty()); EXPECT_FALSE( updatePrefixDatabase(prefixState, createPrefixDb("3", {node3Prefix})) .empty()); // // Verifies that best routes cache is empty // EXPECT_TRUE(spfSolver.getBestRoutesCache().empty()); // // Case-1 node1 ECMP towards {node2, node3} // auto decisionRouteDb = *spfSolver.buildRouteDb("1", areaLinkStates, prefixState); auto routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(1)); EXPECT_THAT( *routeDb.unicastRoutes_ref(), testing::Contains(AllOf( Truly( [&expectedAddr](auto i) { return i.dest_ref() == expectedAddr; }), ResultOf( getUnicastNextHops, testing::UnorderedElementsAre( createNextHopFromAdj(adj12, false, 10), createNextHopFromAdj(adj13, false, 10)))))); // // Verify that prefix-state report two best routes // { auto bestRoutesCache = spfSolver.getBestRoutesCache(); ASSERT_EQ(1, bestRoutesCache.count(toIPNetwork(addr1))); auto& bestRoutes = bestRoutesCache.at(toIPNetwork(addr1)); EXPECT_EQ(2, bestRoutes.allNodeAreas.size()); EXPECT_EQ(1, bestRoutes.allNodeAreas.count({"2", kTestingAreaName})); EXPECT_EQ(1, bestRoutes.allNodeAreas.count({"3", kTestingAreaName})); EXPECT_EQ("2", bestRoutes.bestNodeArea.first); } // // Case-2 node1 prefers node2 (prefix metrics) // const auto node2PrefixPreferred = createPrefixEntryWithMetrics( addr1, thrift::PrefixType::DEFAULT, createMetrics(200, 100, 0)); EXPECT_FALSE(updatePrefixDatabase( prefixState, createPrefixDb("2", {node2PrefixPreferred})) .empty()); decisionRouteDb = *spfSolver.buildRouteDb("1", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(1)); EXPECT_THAT( *routeDb.unicastRoutes_ref(), testing::Contains(AllOf( Truly( [&expectedAddr](auto i) { return i.dest_ref() == expectedAddr; }), ResultOf( getUnicastNextHops, testing::UnorderedElementsAre( createNextHopFromAdj(adj12, false, 10)))))); // // Verify that prefix-state report only one best route // { auto bestRoutesCache = spfSolver.getBestRoutesCache(); ASSERT_EQ(1, bestRoutesCache.count(toIPNetwork(addr1))); auto& bestRoutes = bestRoutesCache.at(toIPNetwork(addr1)); EXPECT_EQ(1, bestRoutes.allNodeAreas.size()); EXPECT_EQ(1, bestRoutes.allNodeAreas.count({"2", kTestingAreaName})); EXPECT_EQ("2", bestRoutes.bestNodeArea.first); } // // Verify that forwarding type is selected from the best entry // node2 - advertising SR_MPLS forwarding type // node3 - advertising IP forwarding type // Decision chooses MPLS entry // auto node2PrefixPreferredMpls = createPrefixEntryWithMetrics( addr1, thrift::PrefixType::DEFAULT, createMetrics(200, 100, 0)); node2PrefixPreferredMpls.forwardingType_ref() = thrift::PrefixForwardingType::SR_MPLS; EXPECT_FALSE(updatePrefixDatabase( prefixState, createPrefixDb("2", {node2PrefixPreferredMpls})) .empty()); decisionRouteDb = *spfSolver.buildRouteDb("3", areaLinkStates, prefixState); routeDb = decisionRouteDb.toThrift(); EXPECT_THAT(*routeDb.unicastRoutes_ref(), testing::SizeIs(1)); auto push2 = createMplsAction( thrift::MplsActionCode::PUSH, std::nullopt, std::vector<int32_t>{2}); LOG(INFO) << toString(routeDb.unicastRoutes_ref()->at(0)); EXPECT_EQ(*routeDb.unicastRoutes_ref()->at(0).dest_ref(), addr1); EXPECT_THAT( *routeDb.unicastRoutes_ref()->at(0).nextHops_ref(), testing::UnorderedElementsAre( createNextHopFromAdj(adj31, false, 20, push2))); } // // Test topology: // connected bidirectionally // 1 <----> 2 <----> 3 // partitioned // 1 <---- 2 ----> 3 // class ConnectivityTest : public ::testing::TestWithParam<bool> {}; TEST_P(ConnectivityTest, GraphConnectedOrPartitioned) { auto partitioned = GetParam(); auto adjacencyDb1 = createAdjDb("1", {}, 1); auto adjacencyDb2 = createAdjDb("2", {adj21, adj23}, 2); auto adjacencyDb3 = createAdjDb("3", {}, 3); if (!partitioned) { adjacencyDb1 = createAdjDb("1", {adj12}, 1); adjacencyDb3 = createAdjDb("3", {adj32}, 3); } std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* disable v4 */, false /* disable LFA */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; EXPECT_EQ( LinkState::LinkStateChange(false, false, true), linkState.updateAdjacencyDatabase(adjacencyDb1)); EXPECT_EQ( LinkState::LinkStateChange(!partitioned, false, true), linkState.updateAdjacencyDatabase(adjacencyDb2)); EXPECT_EQ( LinkState::LinkStateChange(!partitioned, false, true), linkState.updateAdjacencyDatabase(adjacencyDb3)); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb3).empty()); // route from 1 to 3 auto routeDb = spfSolver.buildRouteDb("1", areaLinkStates, prefixState); bool foundRouteV6 = false; bool foundRouteNodeLabel = false; if (routeDb.has_value()) { for (auto const& [prefix, _] : routeDb->unicastRoutes) { if (toIpPrefix(prefix) == addr3) { foundRouteV6 = true; break; } } for (auto const& [label, _] : routeDb->mplsRoutes) { if (label == 3) { foundRouteNodeLabel = true; } } } EXPECT_EQ(partitioned, !foundRouteV6); EXPECT_EQ(partitioned, !foundRouteNodeLabel); } INSTANTIATE_TEST_CASE_P( PartitionedTopologyInstance, ConnectivityTest, ::testing::Bool()); // // Overload node test in a linear topology with shortest path calculation // // 1<--->2<--->3 // 10 10 // TEST(ConnectivityTest, OverloadNodeTest) { std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* disable v4 */, false /* disable LFA */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; // Add all adjacency DBs auto adjacencyDb1 = createAdjDb("1", {adj12}, 1); auto adjacencyDb2 = createAdjDb("2", {adj21, adj23}, 2); auto adjacencyDb3 = createAdjDb("3", {adj32}, 3); // Make node-2 overloaded adjacencyDb2.isOverloaded_ref() = true; EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb3).empty()); EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb2).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); auto routeMap = getRouteMap(spfSolver, {"1", "2", "3"}, areaLinkStates, prefixState); // We only expect 4 unicast routes, 7 node label routes because node-1 and // node-3 are disconnected. // node-1 => node-2 (label + unicast) // node-2 => node-1, node-3 (label + unicast) // node-3 => node-2 (label + unicast) // // NOTE: Adjacency label route remains up regardless of overloaded status and // there will be 4 of them EXPECT_EQ(15, routeMap.size()); // validate router 1 EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops({createNextHopFromAdj(adj12, false, 10)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj( adj12, false, *adj12.metric_ref(), labelPhpAction)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(addr3))], NextHops({createNextHopFromAdj(adj23, false, 10)})); EXPECT_EQ( routeMap[make_pair("2", toString(addr1))], NextHops({createNextHopFromAdj(adj21, false, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj( adj21, false, *adj21.metric_ref(), labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj( adj23, false, *adj23.metric_ref(), labelPhpAction)})); validatePopLabelRoute(routeMap, "2", *adjacencyDb2.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "2", *adjacencyDb2.adjacencies_ref()); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(addr2))], NextHops({createNextHopFromAdj(adj32, false, 10)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj( adj32, false, *adj32.metric_ref(), labelPhpAction)})); validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); } // // AdjacencyDb compatibility test in a circle topology with shortest path // calculation // In old version remoter interface name is not sepcified // 1(old)<--->2(new)<--->3(new) // | 20 10 ^ // | | // | | // |------------------| TEST(ConnectivityTest, CompatibilityNodeTest) { std::string nodeName("1"); SpfSolver spfSolver( nodeName, false /* disable v4 */, false /* disable LFA */); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; // Add all adjacency DBs auto adjacencyDb1 = createAdjDb("1", {adj12_old_1}, 1); auto adjacencyDb2 = createAdjDb("2", {adj21_old_1, adj23}, 2); auto adjacencyDb3 = createAdjDb("3", {adj32, adj31_old}, 3); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb3).empty()); EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb2).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); // add/update adjacency of node1 with old versions adjacencyDb1 = createAdjDb("1", {adj12_old_1, adj13_old}, 1); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); adjacencyDb1 = createAdjDb("1", {adj12_old_2, adj13_old}, 1); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); auto routeMap = getRouteMap(spfSolver, {"1", "2", "3"}, areaLinkStates, prefixState); // We only expect 6 unicast routes, 9 node label routes and 6 adjacency routes // node-1 => node-2, node-3 // node-2 => node-1, node-3 // node-3 => node-2, node-1 EXPECT_EQ(21, routeMap.size()); // validate router 1 EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops( {createNextHopFromAdj(adj12_old_2, false, 20), createNextHopFromAdj(adj13_old, false, 20)})); EXPECT_EQ( routeMap[make_pair("1", toString(addr3))], NextHops({createNextHopFromAdj(adj13, false, 10)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12_old_2, false, 20, labelPhpAction), createNextHopFromAdj(adj13_old, false, 20, labelSwapAction2)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj( adj13_old, false, *adj13_old.metric_ref(), labelPhpAction)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(addr3))], NextHops({createNextHopFromAdj(adj23, false, 10)})); EXPECT_EQ( routeMap[make_pair("2", toString(addr1))], NextHops({createNextHopFromAdj(adj21, false, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj( adj21, false, *adj21.metric_ref(), labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj( adj23, false, *adj23.metric_ref(), labelPhpAction)})); validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(addr2))], NextHops({createNextHopFromAdj(adj32, false, 10)})); EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops({createNextHopFromAdj(adj31, false, 10)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj( adj31, false, *adj31.metric_ref(), labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj( adj32, false, *adj32.metric_ref(), labelPhpAction)})); validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); // adjacency update (remove adjacency) for node1 adjacencyDb1 = createAdjDb("1", {adj12_old_2}, 0); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); adjacencyDb3 = createAdjDb("3", {adj32}, 0); EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); adjacencyDb1 = createAdjDb("1", {adj12_old_2, adj13_old}, 0); EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); } // // Test topology: // // 1------2 // | \ | // | \ | // 3------4 // // Test both IP v4 & v6 // 1,2,3,4 are simply meshed with each other with 1 parallet links // class SimpleRingMeshTopologyFixture : public ::testing::TestWithParam< std::tuple<bool, std::optional<thrift::PrefixType>>> { public: SimpleRingMeshTopologyFixture() : v4Enabled(std::get<0>(GetParam())) {} protected: void CustomSetUp( bool calculateLfas, bool useKsp2Ed, std::optional<thrift::PrefixType> prefixType = std::nullopt, bool createNewBgpRoute = false) { std::string nodeName("1"); spfSolver = std::make_unique<SpfSolver>(nodeName, v4Enabled, calculateLfas); adjacencyDb1 = createAdjDb("1", {adj12, adj13, adj14}, 1); adjacencyDb2 = createAdjDb("2", {adj21, adj23, adj24}, 2); adjacencyDb3 = createAdjDb("3", {adj31, adj32, adj34}, 3); adjacencyDb4 = createAdjDb("4", {adj41, adj42, adj43}, 4); areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); EXPECT_EQ( LinkState::LinkStateChange(false, false, true), linkState.updateAdjacencyDatabase(adjacencyDb1)); EXPECT_EQ( LinkState::LinkStateChange(true, false, true), linkState.updateAdjacencyDatabase(adjacencyDb2)); EXPECT_EQ( LinkState::LinkStateChange(true, false, true), linkState.updateAdjacencyDatabase(adjacencyDb3)); EXPECT_EQ( LinkState::LinkStateChange(true, false, true), linkState.updateAdjacencyDatabase(adjacencyDb4)); auto pdb1 = v4Enabled ? prefixDb1V4 : prefixDb1; auto pdb2 = v4Enabled ? prefixDb2V4 : prefixDb2; auto pdb3 = v4Enabled ? prefixDb3V4 : prefixDb3; auto pdb4 = v4Enabled ? prefixDb4V4 : prefixDb4; auto bgp1 = v4Enabled ? bgpAddr1V4 : bgpAddr1; auto bgp2 = v4Enabled ? bgpAddr2V4 : bgpAddr2; auto bgp3 = v4Enabled ? bgpAddr3V4 : bgpAddr3; auto bgp4 = v4Enabled ? bgpAddr4V4 : bgpAddr4; updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( pdb1, prefixType, createNewBgpRoute ? std::make_optional<thrift::IpPrefix>(bgp1) : std::nullopt, std::nullopt, v4Enabled) : pdb1); updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( pdb2, prefixType, createNewBgpRoute ? std::make_optional<thrift::IpPrefix>(bgp2) : std::nullopt, std::nullopt, v4Enabled) : pdb2); updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( pdb3, prefixType, createNewBgpRoute ? std::make_optional<thrift::IpPrefix>(bgp3) : std::nullopt, std::nullopt, v4Enabled) : pdb3); updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( pdb4, prefixType, createNewBgpRoute ? std::make_optional<thrift::IpPrefix>(bgp4) : std::nullopt, std::nullopt, v4Enabled) : pdb4); } thrift::AdjacencyDatabase adjacencyDb1, adjacencyDb2, adjacencyDb3, adjacencyDb4; bool v4Enabled{false}; std::unique_ptr<SpfSolver> spfSolver; std::unordered_map<std::string, LinkState> areaLinkStates; PrefixState prefixState; }; INSTANTIATE_TEST_CASE_P( SimpleRingMeshTopologyInstance, SimpleRingMeshTopologyFixture, ::testing::Values( std::make_tuple(true, std::nullopt), std::make_tuple(false, std::nullopt), std::make_tuple(true, thrift::PrefixType::BGP), std::make_tuple(false, thrift::PrefixType::BGP))); TEST_P(SimpleRingMeshTopologyFixture, Ksp2EdEcmp) { CustomSetUp( false /* multipath - ignored */, true /* useKsp2Ed */, std::get<1>(GetParam())); auto routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); auto pushCode = thrift::MplsActionCode::PUSH; auto push1 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1}); auto push2 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2}); auto push3 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{3}); auto push4 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{4}); auto push24 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2, 4}); auto push34 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{3, 4}); auto push43 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{4, 3}); auto push13 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1, 3}); auto push42 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{4, 2}); auto push12 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1, 2}); auto push31 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{3, 1}); auto push21 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2, 1}); // validate router 1 EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr4V4 : addr4))], NextHops( {createNextHopFromAdj(adj14, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj12, v4Enabled, 20, push4), createNextHopFromAdj(adj13, v4Enabled, 20, push4)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj14, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr3V4 : addr3))], NextHops( {createNextHopFromAdj(adj13, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj12, v4Enabled, 20, push3), createNextHopFromAdj(adj14, v4Enabled, 20, push3)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr2V4 : addr2))], NextHops( {createNextHopFromAdj(adj12, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj13, v4Enabled, 20, push2), createNextHopFromAdj(adj14, v4Enabled, 20, push2)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); adjacencyDb3.isOverloaded_ref() = true; auto& linkState = areaLinkStates.at(kTestingAreaName); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr4V4 : addr4))], NextHops( {createNextHopFromAdj(adj14, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj12, v4Enabled, 20, push4)})); } // // Test topology: // // 1------2 // | | // | | // 3------4 // // Test both IP v4 & v6 // class SimpleRingTopologyFixture : public ::testing::TestWithParam< std::tuple<bool, std::optional<thrift::PrefixType>>> { public: SimpleRingTopologyFixture() : v4Enabled(std::get<0>(GetParam())) {} protected: void CustomSetUp( bool calculateLfas, bool useKsp2Ed, std::optional<thrift::PrefixType> prefixType = std::nullopt, bool createNewBgpRoute = false) { std::string nodeName("1"); spfSolver = std::make_unique<SpfSolver>(nodeName, v4Enabled, calculateLfas); adjacencyDb1 = createAdjDb("1", {adj12, adj13}, 1); adjacencyDb2 = createAdjDb("2", {adj21, adj24}, 2); adjacencyDb3 = createAdjDb("3", {adj31, adj34}, 3); adjacencyDb4 = createAdjDb("4", {adj42, adj43}, 4); areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); EXPECT_EQ( LinkState::LinkStateChange(false, false, true), linkState.updateAdjacencyDatabase(adjacencyDb1)); EXPECT_EQ( LinkState::LinkStateChange(true, false, true), linkState.updateAdjacencyDatabase(adjacencyDb2)); EXPECT_EQ( LinkState::LinkStateChange(true, false, true), linkState.updateAdjacencyDatabase(adjacencyDb3)); EXPECT_EQ( LinkState::LinkStateChange(true, false, true), linkState.updateAdjacencyDatabase(adjacencyDb4)); auto pdb1 = v4Enabled ? prefixDb1V4 : prefixDb1; auto pdb2 = v4Enabled ? prefixDb2V4 : prefixDb2; auto pdb3 = v4Enabled ? prefixDb3V4 : prefixDb3; auto pdb4 = v4Enabled ? prefixDb4V4 : prefixDb4; auto bgp1 = v4Enabled ? bgpAddr1V4 : bgpAddr1; auto bgp2 = v4Enabled ? bgpAddr2V4 : bgpAddr2; auto bgp3 = v4Enabled ? bgpAddr3V4 : bgpAddr3; auto bgp4 = v4Enabled ? bgpAddr4V4 : bgpAddr4; updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( pdb1, prefixType, createNewBgpRoute ? std::make_optional<thrift::IpPrefix>(bgp1) : std::nullopt, std::nullopt, v4Enabled) : pdb1); updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( pdb2, prefixType, createNewBgpRoute ? std::make_optional<thrift::IpPrefix>(bgp2) : std::nullopt, std::nullopt, v4Enabled) : pdb2); updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( pdb3, prefixType, createNewBgpRoute ? std::make_optional<thrift::IpPrefix>(bgp3) : std::nullopt, std::nullopt, v4Enabled) : pdb3); updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( pdb4, prefixType, createNewBgpRoute ? std::make_optional<thrift::IpPrefix>(bgp4) : std::nullopt, std::nullopt, v4Enabled) : pdb4); } thrift::AdjacencyDatabase adjacencyDb1, adjacencyDb2, adjacencyDb3, adjacencyDb4; bool v4Enabled{false}; std::unique_ptr<SpfSolver> spfSolver; std::unordered_map<std::string, LinkState> areaLinkStates; PrefixState prefixState; void verifyRouteInUpdateNoDelete( std::string nodeName, int32_t mplsLabel, const DecisionRouteDb& compDb) { // verify route DB change in node 1. auto deltaRoutes = compDb.calculateUpdate( spfSolver->buildRouteDb(nodeName, areaLinkStates, prefixState).value()); int find = 0; for (const auto& mplsRoute : deltaRoutes.mplsRoutesToUpdate) { if (mplsRoute.label == mplsLabel) { find++; } } EXPECT_EQ(find, 1); EXPECT_EQ(deltaRoutes.mplsRoutesToDelete.size(), 0); } }; INSTANTIATE_TEST_CASE_P( SimpleRingTopologyInstance, SimpleRingTopologyFixture, ::testing::Values( std::make_tuple(true, std::nullopt), std::make_tuple(false, std::nullopt), std::make_tuple(true, thrift::PrefixType::BGP), std::make_tuple(false, thrift::PrefixType::BGP))); // // Verify SpfSolver finds the shortest path // TEST_P(SimpleRingTopologyFixture, ShortestPathTest) { CustomSetUp(false /* disable LFA */, false /* useKsp2Ed */); fb303::fbData->resetAllData(); auto routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); // Unicast routes => 4 * (4 - 1) = 12 // Node label routes => 4 * 4 = 16 // Adj label routes => 4 * 2 = 8 EXPECT_EQ(36, routeMap.size()); // validate router 1 const auto counters = fb303::fbData->getCounters(); EXPECT_EQ(counters.at("decision.spf_runs.count"), 4); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr4V4 : addr4))], NextHops( {createNextHopFromAdj(adj12, v4Enabled, 20), createNextHopFromAdj(adj13, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12, false, 20, labelSwapAction4), createNextHopFromAdj(adj13, false, 20, labelSwapAction4)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr3V4 : addr3))], NextHops({createNextHopFromAdj(adj13, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj13, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj12, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj12, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj24, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj24, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr3V4 : addr3))], NextHops( {createNextHopFromAdj(adj21, v4Enabled, 20), createNextHopFromAdj(adj24, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj21, false, 20, labelSwapAction3), createNextHopFromAdj(adj24, false, 20, labelSwapAction3)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj21, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj21, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "2", *adjacencyDb2.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "2", *adjacencyDb2.adjacencies_ref()); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj34, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj34, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr2V4 : addr2))], NextHops( {createNextHopFromAdj(adj31, v4Enabled, 20), createNextHopFromAdj(adj34, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj31, false, 20, labelSwapAction2), createNextHopFromAdj(adj34, false, 20, labelSwapAction2)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj31, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj31, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); // validate router 4 EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr3V4 : addr3))], NextHops({createNextHopFromAdj(adj43, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj43, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj42, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj42, v4Enabled, 20), createNextHopFromAdj(adj43, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj42, false, 20, labelSwapAction1), createNextHopFromAdj(adj43, false, 20, labelSwapAction1)})); validatePopLabelRoute(routeMap, "4", *adjacencyDb4.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "4", *adjacencyDb4.adjacencies_ref()); } // // Verify duplicate mpls routes case // let two nodes announcing same mpls label. Verify that the one with higher // name value would win. // change one node to use a different mpls label. verify routes gets programmed // and no withdraw happened. // TEST_P(SimpleRingTopologyFixture, DuplicateMplsRoutes) { CustomSetUp(false /* disable LFA */, false /* useKsp2Ed */); fb303::fbData->resetAllData(); // make node1's mpls label same as node2. adjacencyDb1.nodeLabel_ref() = 2; auto& linkState = areaLinkStates.at(kTestingAreaName); linkState.updateAdjacencyDatabase(adjacencyDb1); // verify route DB change in node 1, 2 ,3. // verify that only one route to mpls lable 1 is installed in all nodes DecisionRouteDb emptyRouteDb; verifyRouteInUpdateNoDelete("1", 2, emptyRouteDb); verifyRouteInUpdateNoDelete("2", 2, emptyRouteDb); verifyRouteInUpdateNoDelete("3", 2, emptyRouteDb); auto counters = fb303::fbData->getCounters(); // verify the counters to be 3 because each node will noticed a duplicate // for mpls label 1. EXPECT_EQ(counters.at("decision.duplicate_node_label.count.60"), 3); auto compDb1 = spfSolver->buildRouteDb("1", areaLinkStates, prefixState).value(); auto compDb2 = spfSolver->buildRouteDb("2", areaLinkStates, prefixState).value(); auto compDb3 = spfSolver->buildRouteDb("3", areaLinkStates, prefixState).value(); counters = fb303::fbData->getCounters(); // now the counter should be 6, becasue we called buildRouteDb 3 times. EXPECT_EQ(counters.at("decision.duplicate_node_label.count.60"), 6); // change nodelabel of node 1 to be 1. Now each node has it's own // mpls label, there should be no duplicate. // verify that there is an update entry for mpls route to label 1. // verify that no withdrawals of mpls routes to label 1. adjacencyDb1.nodeLabel_ref() = 1; linkState.updateAdjacencyDatabase(adjacencyDb1); verifyRouteInUpdateNoDelete("1", 2, compDb1); verifyRouteInUpdateNoDelete("2", 2, compDb2); verifyRouteInUpdateNoDelete("3", 2, compDb3); // because there is no duplicate anymore, so that counter should keep as 6. counters = fb303::fbData->getCounters(); EXPECT_EQ(counters.at("decision.duplicate_node_label.count.60"), 6); } // // Use the same topology, but test multi-path routing // TEST_P(SimpleRingTopologyFixture, MultiPathTest) { CustomSetUp(true /* multipath */, false /* useKsp2Ed */); auto routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); // Unicast routes => 4 * (4 - 1) = 12 // Node label routes => 4 * 4 = 16 // Adj label routes => 4 * 2 = 8 EXPECT_EQ(36, routeMap.size()); // validate router 1 EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr4V4 : addr4))], NextHops( {createNextHopFromAdj(adj12, v4Enabled, 20), createNextHopFromAdj(adj13, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12, false, 20, labelSwapAction4), createNextHopFromAdj(adj13, false, 20, labelSwapAction4)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr3V4 : addr3))], NextHops({createNextHopFromAdj(adj13, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj13, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj12, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj12, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj24, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj24, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr3V4 : addr3))], NextHops( {createNextHopFromAdj(adj21, v4Enabled, 20), createNextHopFromAdj(adj24, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj21, false, 20, labelSwapAction3), createNextHopFromAdj(adj24, false, 20, labelSwapAction3)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj21, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj21, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "2", *adjacencyDb2.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "2", *adjacencyDb2.adjacencies_ref()); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj34, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj34, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr2V4 : addr2))], NextHops( {createNextHopFromAdj(adj31, v4Enabled, 20), createNextHopFromAdj(adj34, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj31, false, 20, labelSwapAction2), createNextHopFromAdj(adj34, false, 20, labelSwapAction2)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj31, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj31, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); // validate router 4 EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr3V4 : addr3))], NextHops({createNextHopFromAdj(adj43, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj43, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj42, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj42, v4Enabled, 20), createNextHopFromAdj(adj43, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj42, false, 20, labelSwapAction1), createNextHopFromAdj(adj43, false, 20, labelSwapAction1)})); validatePopLabelRoute(routeMap, "4", *adjacencyDb4.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "4", *adjacencyDb4.adjacencies_ref()); } /** * Validates the IP to MPLS path generataion for shortest path * - No label prepend * - Label prepend * - Min-nexthop requirement * - Label prepend with static next-hops */ TEST_P(SimpleRingTopologyFixture, IpToMplsLabelPrepend) { const int32_t prependLabel{10001}; CustomSetUp( false /* multipath - ignored */, true /* useKsp2Ed */, std::get<1>(GetParam())); auto const push1 = createMplsAction( thrift::MplsActionCode::PUSH, std::nullopt, std::vector<int32_t>{adjacencyDb1.nodeLabel_ref().value()}); auto const pushPrepend = createMplsAction( thrift::MplsActionCode::PUSH, std::nullopt, std::vector<int32_t>{prependLabel}); auto const push1Prepend = createMplsAction( thrift::MplsActionCode::PUSH, std::nullopt, std::vector<int32_t>{prependLabel, adjacencyDb1.nodeLabel_ref().value()}); auto const push4Prepend = createMplsAction( thrift::MplsActionCode::PUSH, std::nullopt, std::vector<int32_t>{prependLabel, adjacencyDb4.nodeLabel_ref().value()}); // // Case-1 IP to MPLS routes towards node1 // auto prefixDb = getPrefixDbForNode(prefixState, "1"); auto& entry1 = prefixDb.prefixEntries_ref()->back(); for (auto& prefixEntry : prefixDb.prefixEntries_ref().value()) { prefixEntry.forwardingAlgorithm_ref() = thrift::PrefixForwardingAlgorithm::SP_ECMP; } if (entry1.mv_ref()) { // Add metric entity with tie-breaker for best path calculation success thrift::MetricEntity entity; entity.type_ref() = 1; entity.priority_ref() = 1; entity.isBestPathTieBreaker_ref() = true; entity.metric_ref()->emplace_back(1); entry1.mv_ref()->metrics_ref()->push_back(entity); } updatePrefixDatabase(prefixState, prefixDb); auto routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); EXPECT_EQ( 0, routeMap.count(make_pair("1", toString(v4Enabled ? addr1V4 : addr1)))); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj21, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj31, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj42, v4Enabled, 20, push1), createNextHopFromAdj(adj43, v4Enabled, 20, push1)})); // // Case-2 Min-nexthop requirement. No route on node2 and node3 because it // doesn't qualify min-nexthop requirement of 2 // entry1.minNexthop_ref() = 2; updatePrefixDatabase(prefixState, prefixDb); routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); EXPECT_EQ( 0, routeMap.count(make_pair("1", toString(v4Enabled ? addr1V4 : addr1)))); EXPECT_EQ( 0, routeMap.count(make_pair("2", toString(v4Enabled ? addr1V4 : addr1)))); EXPECT_EQ( 0, routeMap.count(make_pair("3", toString(v4Enabled ? addr1V4 : addr1)))); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj42, v4Enabled, 20, push1), createNextHopFromAdj(adj43, v4Enabled, 20, push1)})); // // Case-3 Add label prepend instruction // entry1.prependLabel_ref() = prependLabel; updatePrefixDatabase(prefixState, prefixDb); routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); EXPECT_EQ( 0, routeMap.count(make_pair("1", toString(v4Enabled ? addr1V4 : addr1)))); EXPECT_EQ( 0, routeMap.count(make_pair("2", toString(v4Enabled ? addr1V4 : addr1)))); EXPECT_EQ( 0, routeMap.count(make_pair("3", toString(v4Enabled ? addr1V4 : addr1)))); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj42, v4Enabled, 20, push1Prepend), createNextHopFromAdj(adj43, v4Enabled, 20, push1Prepend)})); // // Case-4 Announce same prefix from node4 // // Advertise addr1[V4] from node4 as well with prepend label auto prefixDb4 = getPrefixDbForNode(prefixState, "4"); prefixDb4.prefixEntries_ref()->emplace_back(entry1); if (entry1.mv_ref()) { auto& entry4 = prefixDb4.prefixEntries_ref()->back(); entry4.mv_ref()->metrics_ref()->at(0).metric_ref()->at(0) += 1; } updatePrefixDatabase(prefixState, prefixDb4); // insert the new nexthop to mpls static routes cache const auto nh1Addr = toBinaryAddress("1.1.1.1"); const auto nh2Addr = toBinaryAddress("2.2.2.2"); const auto phpAction = createMplsAction(thrift::MplsActionCode::PHP); std::vector<thrift::NextHopThrift> staticNextHops{ createNextHop(nh1Addr, std::nullopt, 0, phpAction), createNextHop(nh2Addr, std::nullopt, 0, phpAction)}; staticNextHops.at(0).area_ref().reset(); staticNextHops.at(1).area_ref().reset(); thrift::RouteDatabaseDelta routesDelta; routesDelta.mplsRoutesToUpdate_ref() = { createMplsRoute(prependLabel, staticNextHops)}; spfSolver->updateStaticMplsRoutes( *routesDelta.mplsRoutesToUpdate_ref(), *routesDelta.mplsRoutesToDelete_ref()); // Get and verify next-hops. Both node1 & node4 will report static next-hops // NOTE: PUSH action is removed. routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj12, v4Enabled, 20, push4Prepend), createNextHopFromAdj(adj13, v4Enabled, 20, push4Prepend), createNextHop(nh1Addr, std::nullopt, 0, std::nullopt), createNextHop(nh2Addr, std::nullopt, 0, std::nullopt)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj21, v4Enabled, 10, pushPrepend), createNextHopFromAdj(adj24, v4Enabled, 10, pushPrepend)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj31, v4Enabled, 10, pushPrepend), createNextHopFromAdj(adj34, v4Enabled, 10, pushPrepend)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj42, v4Enabled, 20, push1Prepend), createNextHopFromAdj(adj43, v4Enabled, 20, push1Prepend), createNextHop(nh1Addr, std::nullopt, 0, std::nullopt), createNextHop(nh2Addr, std::nullopt, 0, std::nullopt)})); } // // Validate KSP2_ED_ECMP routes on SimpleRingTopology // TEST_P(SimpleRingTopologyFixture, Ksp2EdEcmp) { CustomSetUp( true /* multipath - ignored */, true /* useKsp2Ed */, std::get<1>(GetParam())); fb303::fbData->resetAllData(); auto routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); // Unicast routes => 4 * (4 - 1) = 12 // Node label routes => 4 * 4 = 16 // Adj label routes => 4 * 2 = 8 EXPECT_EQ( (std::get<1>(GetParam()) == thrift::PrefixType::BGP ? 48 : 36), routeMap.size()); const auto counters = fb303::fbData->getCounters(); // 4 + 4 * 3 peer per node (clean runs are memoized, 2nd runs with linksTo // ignore are not so we redo for each neighbor) EXPECT_EQ(counters.at("decision.spf_runs.count"), 16); auto pushCode = thrift::MplsActionCode::PUSH; auto push1 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1}); auto push2 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2}); auto push3 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{3}); auto push4 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{4}); auto push24 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2, 4}); auto push34 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{3, 4}); auto push43 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{4, 3}); auto push13 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1, 3}); auto push42 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{4, 2}); auto push12 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1, 2}); auto push31 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{3, 1}); auto push21 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2, 1}); // validate router 1 EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr4V4 : addr4))], NextHops( {createNextHopFromAdj(adj12, v4Enabled, 20, push4), createNextHopFromAdj(adj13, v4Enabled, 20, push4)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12, false, 20, labelSwapAction4), createNextHopFromAdj(adj13, false, 20, labelSwapAction4)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr3V4 : addr3))], NextHops( {createNextHopFromAdj(adj13, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj12, v4Enabled, 30, push34)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj13, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr2V4 : addr2))], NextHops( {createNextHopFromAdj(adj12, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj13, v4Enabled, 30, push24)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj12, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr4V4 : addr4))], NextHops( {createNextHopFromAdj(adj24, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj21, v4Enabled, 30, push43)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj24, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr3V4 : addr3))], NextHops( {createNextHopFromAdj(adj21, v4Enabled, 20, push3), createNextHopFromAdj(adj24, v4Enabled, 20, push3)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj21, false, 20, labelSwapAction3), createNextHopFromAdj(adj24, false, 20, labelSwapAction3)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj21, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj24, v4Enabled, 30, push13)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj21, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "2", *adjacencyDb2.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "2", *adjacencyDb2.adjacencies_ref()); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr4V4 : addr4))], NextHops( {createNextHopFromAdj(adj34, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj31, v4Enabled, 30, push42)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj34, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr2V4 : addr2))], NextHops( {createNextHopFromAdj(adj31, v4Enabled, 20, push2), createNextHopFromAdj(adj34, v4Enabled, 20, push2)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj31, false, 20, labelSwapAction2), createNextHopFromAdj(adj34, false, 20, labelSwapAction2)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj31, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj34, v4Enabled, 30, push12)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj31, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); // validate router 4 EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr3V4 : addr3))], NextHops( {createNextHopFromAdj(adj43, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj42, v4Enabled, 30, push31)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj43, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr2V4 : addr2))], NextHops( {createNextHopFromAdj(adj42, v4Enabled, 10, std::nullopt), createNextHopFromAdj(adj43, v4Enabled, 30, push21)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr1V4 : addr1))], NextHops( {createNextHopFromAdj(adj42, v4Enabled, 20, push1), createNextHopFromAdj(adj43, v4Enabled, 20, push1)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj42, false, 20, labelSwapAction1), createNextHopFromAdj(adj43, false, 20, labelSwapAction1)})); validatePopLabelRoute(routeMap, "4", *adjacencyDb4.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "4", *adjacencyDb4.adjacencies_ref()); // this is to test corner cases for traceEdgeDisjointPaths algorithm. // In this example, node 3 is overloaded, and link between node 1 and node 2 // are overloaded. In such case, there is no route from node 1 to node 2 and 4 adjacencyDb1.adjacencies_ref()[0].isOverloaded_ref() = true; adjacencyDb3.isOverloaded_ref() = true; auto& linkState = areaLinkStates.at(kTestingAreaName); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); EXPECT_EQ( routeMap.find(make_pair("1", toString(v4Enabled ? addr4V4 : addr4))), routeMap.end()); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr3V4 : addr3))], NextHops({createNextHopFromAdj(adj13, v4Enabled, 10, std::nullopt)})); EXPECT_EQ( routeMap.find(make_pair("1", toString(v4Enabled ? addr2V4 : addr2))), routeMap.end()); } TEST_P(SimpleRingTopologyFixture, Ksp2EdEcmpForBGP) { CustomSetUp( true /* multipath - ignored */, true /* useKsp2Ed */, thrift::PrefixType::BGP, true); fb303::fbData->resetAllData(); thrift::MetricVector mv1, mv2; int64_t numMetrics = 5; mv1.metrics_ref()->resize(numMetrics); mv2.metrics_ref()->resize(numMetrics); for (int64_t i = 0; i < numMetrics; ++i) { mv1.metrics_ref()[i].type_ref() = i; mv2.metrics_ref()[i].type_ref() = i; mv1.metrics_ref()[i].priority_ref() = i; mv2.metrics_ref()[i].priority_ref() = i; mv1.metrics_ref()[i].op_ref() = thrift::CompareType::WIN_IF_PRESENT; mv2.metrics_ref()[i].op_ref() = thrift::CompareType::WIN_IF_PRESENT; mv1.metrics_ref()[i].isBestPathTieBreaker_ref() = false; mv2.metrics_ref()[i].isBestPathTieBreaker_ref() = false; *mv1.metrics_ref()[i].metric_ref() = *mv2.metrics_ref()[i].metric_ref() = {i}; } auto prefixDBOne = getPrefixDbForNode(prefixState, "1"); auto prefixDBTwo = getPrefixDbForNode(prefixState, "2"); // Set metric vector for addr1 prefixes in two nodes to be same // for both, put this element at the back of the entries list auto& entriesVec = *prefixDBOne.prefixEntries_ref(); for (auto entryIter = entriesVec.begin(); entryIter != entriesVec.end(); ++entryIter) { if ((!v4Enabled && entryIter->get_prefix() == bgpAddr1) || (v4Enabled && entryIter->get_prefix() == bgpAddr1V4)) { entryIter->mv_ref() = mv1; prefixDBTwo.prefixEntries_ref()->push_back(*entryIter); entriesVec.erase(entryIter); break; } } entriesVec.push_back(prefixDBTwo.prefixEntries_ref()->back()); // only node 1 is announcing the prefix with prependLabel. // node 2 is announcing the prefix without prependLabel. prefixDBOne.prefixEntries_ref()->back().prependLabel_ref() = 60000; updatePrefixDatabase(prefixState, prefixDBOne); updatePrefixDatabase(prefixState, prefixDBTwo); auto routeMap = getRouteMap(*spfSolver, {"3"}, areaLinkStates, prefixState); auto pushCode = thrift::MplsActionCode::PUSH; auto push2 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2}); auto push12 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1, 2}); auto push2AndPrependLabel = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{60000, 2}); auto push12AndPrependLabel = createMplsAction( pushCode, std::nullopt, std::vector<int32_t>{60000, 1, 2}); auto pushPrependLabel = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{60000}); // in router 3, we are expecting addr1 to be null because it is a bgp route // with same metric vector from two nodes // in current setup, if we don't setup tie break to be true, in case of tie, // we counld not determine which node to be best dest node, hence we will not // program routes to it. EXPECT_EQ( routeMap.find( make_pair("3", toString(v4Enabled ? bgpAddr1V4 : bgpAddr1))), routeMap.end()); // decrease mv for the second node, now router 3 should point to 1 prefixDBTwo.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .metric_ref() ->front()--; // change data to some special case for verification prefixDBOne.prefixEntries_ref()->at(1).data_ref() = "123"; updatePrefixDatabase(prefixState, prefixDBTwo); updatePrefixDatabase(prefixState, prefixDBOne); routeMap = getRouteMap(*spfSolver, {"3"}, areaLinkStates, prefixState); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? bgpAddr1V4 : bgpAddr1))], NextHops( {createNextHopFromAdj(adj31, v4Enabled, 10, pushPrependLabel), createNextHopFromAdj(adj34, v4Enabled, 30, push12AndPrependLabel)})); auto route = getUnicastRoutes( *spfSolver, {"3"}, areaLinkStates, prefixState)[make_pair("3", toString(v4Enabled ? bgpAddr1V4 : bgpAddr1))]; // increase mv for the second node by 2, now router 3 should point to 2 prefixDBTwo.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .metric_ref() ->front() += 2; updatePrefixDatabase(prefixState, prefixDBTwo); routeMap = getRouteMap(*spfSolver, {"3"}, areaLinkStates, prefixState); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? bgpAddr1V4 : bgpAddr1))], NextHops( {createNextHopFromAdj(adj31, v4Enabled, 20, push2), createNextHopFromAdj(adj34, v4Enabled, 20, push2)})); route = getUnicastRoutes( *spfSolver, {"3"}, areaLinkStates, prefixState)[make_pair("3", toString(v4Enabled ? bgpAddr1V4 : bgpAddr1))]; // set the tie breaker to be true. in this case, both nodes will be selected prefixDBTwo.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .isBestPathTieBreaker_ref() = true; prefixDBOne.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .isBestPathTieBreaker_ref() = true; updatePrefixDatabase(prefixState, prefixDBTwo); updatePrefixDatabase(prefixState, prefixDBOne); routeMap = getRouteMap(*spfSolver, {"3"}, areaLinkStates, prefixState); // createNextHopFromAdj(adj34, v4Enabled, 30, push12, true) getting ignored // because in kspf, we will ignore second shortest path if it starts with // one of shortest path for anycast prefix EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? bgpAddr1V4 : bgpAddr1))], NextHops( {createNextHopFromAdj(adj31, v4Enabled, 20, push2), createNextHopFromAdj(adj34, v4Enabled, 20, push2), createNextHopFromAdj(adj31, v4Enabled, 10, pushPrependLabel)})); route = getUnicastRoutes( *spfSolver, {"3"}, areaLinkStates, prefixState)[make_pair("3", toString(v4Enabled ? bgpAddr1V4 : bgpAddr1))]; // verify on node 1. From node 1 point of view, both node 1 and node 2 are // are annoucing the prefix. So it will program 3 nexthops. // 1: recursively resolved MPLS nexthops of prependLabel // 2: shortest path to node 2. // 3: second shortest path node 2. int32_t staticMplsRouteLabel = 60000; // insert the new nexthop to mpls static routes cache thrift::NextHopThrift nh; *nh.address_ref() = toBinaryAddress("1.1.1.1"); nh.mplsAction_ref() = createMplsAction(thrift::MplsActionCode::PHP); thrift::MplsRoute staticMplsRoute; staticMplsRoute.topLabel_ref() = staticMplsRouteLabel; staticMplsRoute.nextHops_ref()->emplace_back(nh); thrift::RouteDatabaseDelta routesDelta; routesDelta.mplsRoutesToUpdate_ref() = {staticMplsRoute}; spfSolver->updateStaticMplsRoutes( *routesDelta.mplsRoutesToUpdate_ref(), *routesDelta.mplsRoutesToDelete_ref()); routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); // NOTE: 60000 is the static MPLS route on node 2 which prevent routing loop. auto push24 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2, 4}); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? bgpAddr1V4 : bgpAddr1))], NextHops( {createNextHop( toBinaryAddress("1.1.1.1"), std::nullopt, 0, std::nullopt), createNextHopFromAdj(adj13, v4Enabled, 30, push24), createNextHopFromAdj(adj12, v4Enabled, 10, std::nullopt)})); } TEST_P(SimpleRingTopologyFixture, Ksp2EdEcmpForBGP123) { CustomSetUp( true /* multipath - ignored */, true /* useKsp2Ed */, thrift::PrefixType::BGP, true); fb303::fbData->resetAllData(); thrift::MetricVector mv1, mv2; int64_t numMetrics = 5; mv1.metrics_ref()->resize(numMetrics); mv2.metrics_ref()->resize(numMetrics); for (int64_t i = 0; i < numMetrics; ++i) { mv1.metrics_ref()[i].type_ref() = i; mv2.metrics_ref()[i].type_ref() = i; mv1.metrics_ref()[i].priority_ref() = i; mv2.metrics_ref()[i].priority_ref() = i; mv1.metrics_ref()[i].op_ref() = thrift::CompareType::WIN_IF_PRESENT; mv2.metrics_ref()[i].op_ref() = thrift::CompareType::WIN_IF_PRESENT; mv1.metrics_ref()[i].isBestPathTieBreaker_ref() = false; mv2.metrics_ref()[i].isBestPathTieBreaker_ref() = false; *mv1.metrics_ref()[i].metric_ref() = *mv2.metrics_ref()[i].metric_ref() = {i}; } auto prefixDBOne = getPrefixDbForNode(prefixState, "1"); auto prefixDBTwo = getPrefixDbForNode(prefixState, "2"); // Set metric vector for addr1 prefixes in two nodes to be same // for both, put this element at the back of the entries list auto& entriesVec = *prefixDBOne.prefixEntries_ref(); for (auto entryIter = entriesVec.begin(); entryIter != entriesVec.end(); ++entryIter) { if ((!v4Enabled && entryIter->get_prefix() == bgpAddr1) || (v4Enabled && entryIter->get_prefix() == bgpAddr1V4)) { entryIter->mv_ref() = mv1; prefixDBTwo.prefixEntries_ref()->push_back(*entryIter); entriesVec.erase(entryIter); break; } } entriesVec.push_back(prefixDBTwo.prefixEntries_ref()->back()); // only node 1 is announcing the prefix with prependLabel. // node 2 is announcing the prefix without prependLabel. prefixDBOne.prefixEntries_ref()->back().prependLabel_ref() = 60000; // increase mv for the second node by 2, now router 3 should point to 2 prefixDBTwo.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .metric_ref() ->front() += 1; // set the tie breaker to be true. in this case, both nodes will be selected prefixDBTwo.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .isBestPathTieBreaker_ref() = true; prefixDBOne.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .isBestPathTieBreaker_ref() = true; updatePrefixDatabase(prefixState, prefixDBOne); updatePrefixDatabase(prefixState, prefixDBTwo); auto pushCode = thrift::MplsActionCode::PUSH; // verify on node 1. From node 1 point of view, both node 1 and node 2 are // are annoucing the prefix. So it will program 3 nexthops. // 1: recursively resolved MPLS nexthops of prependLabel // 2: shortest path to node 2. // 3: second shortest path node 2. int32_t staticMplsRouteLabel = 60000; // insert the new nexthop to mpls static routes cache thrift::NextHopThrift nh; *nh.address_ref() = toBinaryAddress("1.1.1.1"); nh.mplsAction_ref() = createMplsAction(thrift::MplsActionCode::PHP); thrift::MplsRoute staticMplsRoute; staticMplsRoute.topLabel_ref() = staticMplsRouteLabel; staticMplsRoute.nextHops_ref()->emplace_back(nh); thrift::RouteDatabaseDelta routesDelta; routesDelta.mplsRoutesToUpdate_ref() = {staticMplsRoute}; spfSolver->updateStaticMplsRoutes( *routesDelta.mplsRoutesToUpdate_ref(), *routesDelta.mplsRoutesToDelete_ref()); auto routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); // NOTE: 60000 is the static MPLS route on node 2 which prevent routing loop. auto push24 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2, 4}); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? bgpAddr1V4 : bgpAddr1))], NextHops( {createNextHop( toBinaryAddress("1.1.1.1"), std::nullopt, 0, std::nullopt), createNextHopFromAdj(adj13, v4Enabled, 30, push24), createNextHopFromAdj(adj12, v4Enabled, 10, std::nullopt)})); prefixDBOne.prefixEntries_ref()->at(1).minNexthop_ref() = 3; updatePrefixDatabase(prefixState, prefixDBOne); routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); EXPECT_EQ( routeMap.find( make_pair("1", toString(v4Enabled ? bgpAddr1V4 : bgpAddr1))), routeMap.end()); } // // attach nodes to outside world, e.g., POP // verify all non-POP nodes find their closest POPs // TEST_P(SimpleRingTopologyFixture, AttachedNodesTest) { CustomSetUp(true /* multipath */, false /* useKsp2Ed */); // Advertise default prefixes from node-1 and node-4 auto defaultRoutePrefix = v4Enabled ? "0.0.0.0/0" : "::/0"; auto defaultRoute = toIpPrefix(defaultRoutePrefix); auto prefixDb1 = createPrefixDb( "1", {createPrefixEntry(addr1), createPrefixEntry(defaultRoute)}); auto prefixDb4 = createPrefixDb( "4", {createPrefixEntry(addr4), createPrefixEntry(defaultRoute)}); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1).empty()); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb4).empty()); auto routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); // Unicast routes => 4 * (4 - 1) + 2 (default routes) = 14 // Node label routes => 4 * 4 = 16 // Adj label routes => 4 * 2 = 8 EXPECT_EQ(38, routeMap.size()); // validate router 1 // no default route boz it's attached // i.e., spfSolver(false), bcoz we set node 1 to be "1" distance away from the // dummy node and its neighbors are all further away, thus there is no route // to the dummy node EXPECT_EQ(0, routeMap.count({"1", defaultRoutePrefix})); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", defaultRoutePrefix)], NextHops( {createNextHopFromAdj(adj21, v4Enabled, 10), createNextHopFromAdj(adj24, v4Enabled, 10)})); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", defaultRoutePrefix)], NextHops( {createNextHopFromAdj(adj31, v4Enabled, 10), createNextHopFromAdj(adj34, v4Enabled, 10)})); // validate router 4 // no default route boz it's attached EXPECT_EQ(0, routeMap.count({"4", defaultRoutePrefix})); } // // Verify overload bit setting of a node's adjacency DB with multipath // enabled. Make node-3 and node-2 overloaded and verify routes. // It will disconnect node-1 with node-4 but rests should be reachable // TEST_P(SimpleRingTopologyFixture, OverloadNodeTest) { CustomSetUp(true /* multipath */, false /* useKsp2Ed */); adjacencyDb2.isOverloaded_ref() = true; adjacencyDb3.isOverloaded_ref() = true; auto& linkState = areaLinkStates.at(kTestingAreaName); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb2).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); auto routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); // Unicast routes => 2 + 3 + 3 + 2 = 10 // Node label routes => 3 + 4 + 4 + 3 = 14 // Adj label routes => 4 * 2 = 8 EXPECT_EQ(32, routeMap.size()); // validate router 1 EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr3V4 : addr3))], NextHops({createNextHopFromAdj(adj13, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj13, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj12, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj12, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj24, v4Enabled, 10)})); // No LFA EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj24, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr3V4 : addr3))], NextHops( {createNextHopFromAdj(adj21, v4Enabled, 20), createNextHopFromAdj(adj24, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj21, false, 20, labelSwapAction3), createNextHopFromAdj(adj24, false, 20, labelSwapAction3)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj21, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj21, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "2", *adjacencyDb2.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "2", *adjacencyDb2.adjacencies_ref()); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj34, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj34, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr2V4 : addr2))], NextHops( {createNextHopFromAdj(adj31, v4Enabled, 20), createNextHopFromAdj(adj34, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj31, false, 20, labelSwapAction2), createNextHopFromAdj(adj34, false, 20, labelSwapAction2)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj31, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj31, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); // validate router 4 EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr3V4 : addr3))], NextHops({createNextHopFromAdj(adj43, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj43, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj42, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "4", *adjacencyDb4.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "4", *adjacencyDb4.adjacencies_ref()); } // // Verify overload bit setting of individual adjacencies with multipath // enabled. node-3 will get disconnected // TEST_P(SimpleRingTopologyFixture, OverloadLinkTest) { CustomSetUp(true /* multipath */, false /* useKsp2Ed */); adjacencyDb3.adjacencies_ref()[0].isOverloaded_ref() = true; // make adj31 overloaded auto& linkState = areaLinkStates.at(kTestingAreaName); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); auto routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); // Unicast routes => 4 * (4 - 1) = 12 // Node label routes => 4 * 4 = 16 // Adj label routes => 4 * 2 = 8 EXPECT_EQ(36, routeMap.size()); // validate router 1 EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj12, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj12, false, 20, labelSwapAction4)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr3V4 : addr3))], NextHops({createNextHopFromAdj(adj12, v4Enabled, 30)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj12, false, 30, labelSwapAction3)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj12, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj12, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj24, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj24, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr3V4 : addr3))], NextHops({createNextHopFromAdj(adj24, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj24, false, 20, labelSwapAction3)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj21, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj21, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "2", *adjacencyDb2.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "2", *adjacencyDb2.adjacencies_ref()); // validate router 3 // no routes for router 3 EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj34, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj34, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj34, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj34, false, 20, labelSwapAction2)})); EXPECT_EQ( routeMap[make_pair("3", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj34, v4Enabled, 30)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj34, false, 30, labelSwapAction1)})); validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); // validate router 4 EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr3V4 : addr3))], NextHops({createNextHopFromAdj(adj43, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj43, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj42, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj42, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 20, labelSwapAction1)})); validatePopLabelRoute(routeMap, "4", *adjacencyDb4.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "4", *adjacencyDb4.adjacencies_ref()); // Now also make adj34 overloaded which will disconnect the node-3 adjacencyDb3.adjacencies_ref()[1].isOverloaded_ref() = true; EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); // Unicast routes => 2 + 2 + 0 + 2 = 6 // Node label routes => 3 * 3 + 1 = 10 // Adj label routes => 4 * 2 = 8 EXPECT_EQ(24, routeMap.size()); // validate router 1 EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj12, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj12, false, 20, labelSwapAction4)})); EXPECT_EQ( routeMap[make_pair("1", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj12, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj12, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr4V4 : addr4))], NextHops({createNextHopFromAdj(adj24, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj24, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj21, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj21, false, 10, labelPhpAction)})); validatePopLabelRoute(routeMap, "2", *adjacencyDb2.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "2", *adjacencyDb2.adjacencies_ref()); // validate router 3 validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); // validate router 4 EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr2V4 : addr2))], NextHops({createNextHopFromAdj(adj42, v4Enabled, 10)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(v4Enabled ? addr1V4 : addr1))], NextHops({createNextHopFromAdj(adj42, v4Enabled, 20)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 20, labelSwapAction1)})); validatePopLabelRoute(routeMap, "4", *adjacencyDb4.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "4", *adjacencyDb4.adjacencies_ref()); } /* add this block comment to suppress multiline breaker "\"s below // // Test topology: ring with parallel adjacencies, *x* denotes metric // ---*11*--- // / \ // 1----*11*----2 // |\ /| // | ---*20*--- | // *11* *11* // | | // | ---*11*--- | // |/ \| // 3----*20*----4 // \ / // ---*20*--- // */ class ParallelAdjRingTopologyFixture : public ::testing::TestWithParam<std::optional<thrift::PrefixType>> { public: ParallelAdjRingTopologyFixture() {} protected: void CustomSetUp( bool calculateLfas, bool useKsp2Ed, std::optional<thrift::PrefixType> prefixType = std::nullopt) { std::string nodeName("1"); spfSolver = std::make_unique<SpfSolver>(nodeName, false, calculateLfas); // R1 -> R2 adj12_1 = createAdjacency("2", "2/1", "1/1", "fe80::2:1", "192.168.2.1", 11, 201); adj12_2 = createAdjacency("2", "2/2", "1/2", "fe80::2:2", "192.168.2.2", 11, 202); adj12_3 = createAdjacency("2", "2/3", "1/3", "fe80::2:3", "192.168.2.3", 20, 203); // R1 -> R3 adj13_1 = createAdjacency("3", "3/1", "1/1", "fe80::3:1", "192.168.3.1", 11, 301); // R2 -> R1 adj21_1 = createAdjacency("1", "1/1", "2/1", "fe80::1:1", "192.168.1.1", 11, 101); adj21_2 = createAdjacency("1", "1/2", "2/2", "fe80::1:2", "192.168.1.2", 11, 102); adj21_3 = createAdjacency("1", "1/3", "2/3", "fe80::1:3", "192.168.1.3", 20, 103); // R2 -> R4 adj24_1 = createAdjacency("4", "4/1", "2/1", "fe80::4:1", "192.168.4.1", 11, 401); // R3 -> R1 adj31_1 = createAdjacency("1", "1/1", "3/1", "fe80::1:1", "192.168.1.1", 11, 101); // R3 -> R4 adj34_1 = createAdjacency("4", "4/1", "3/1", "fe80::4:1", "192.168.4.1", 11, 401); adj34_2 = createAdjacency("4", "4/2", "3/2", "fe80::4:2", "192.168.4.2", 20, 402); adj34_3 = createAdjacency("4", "4/3", "3/3", "fe80::4:3", "192.168.4.3", 20, 403); // R4 -> R2 adj42_1 = createAdjacency("2", "2/1", "4/1", "fe80::2:1", "192.168.2.1", 11, 201); adj43_1 = createAdjacency("3", "3/1", "4/1", "fe80::3:1", "192.168.3.1", 11, 301); adj43_2 = createAdjacency("3", "3/2", "4/2", "fe80::3:2", "192.168.3.2", 20, 302); adj43_3 = createAdjacency("3", "3/3", "4/3", "fe80::3:3", "192.168.3.3", 20, 303); adjacencyDb1 = createAdjDb("1", {adj12_1, adj12_2, adj12_3, adj13_1}, 1); adjacencyDb2 = createAdjDb("2", {adj21_1, adj21_2, adj21_3, adj24_1}, 2); adjacencyDb3 = createAdjDb("3", {adj31_1, adj34_1, adj34_2, adj34_3}, 3); adjacencyDb4 = createAdjDb("4", {adj42_1, adj43_1, adj43_2, adj43_3}, 4); // Adjacency db's areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); EXPECT_FALSE( linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_TRUE( linkState.updateAdjacencyDatabase(adjacencyDb2).topologyChanged); EXPECT_TRUE( linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); EXPECT_TRUE( linkState.updateAdjacencyDatabase(adjacencyDb4).topologyChanged); // Prefix db's updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( prefixDb1, prefixType, std::nullopt, std::nullopt, false) : prefixDb1); updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( prefixDb2, prefixType, std::nullopt, std::nullopt, false) : prefixDb2); updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( prefixDb3, prefixType, std::nullopt, std::nullopt, false) : prefixDb3); updatePrefixDatabase( prefixState, useKsp2Ed ? createPrefixDbWithKspfAlgo( prefixDb4, prefixType, std::nullopt, std::nullopt, false) : prefixDb4); } thrift::Adjacency adj12_1, adj12_2, adj12_3, adj13_1, adj21_1, adj21_2, adj21_3, adj24_1, adj31_1, adj34_1, adj34_2, adj34_3, adj42_1, adj43_1, adj43_2, adj43_3; thrift::AdjacencyDatabase adjacencyDb1, adjacencyDb2, adjacencyDb3, adjacencyDb4; std::unique_ptr<SpfSolver> spfSolver; std::unordered_map<std::string, LinkState> areaLinkStates; PrefixState prefixState; }; INSTANTIATE_TEST_CASE_P( ParallelAdjRingTopologyInstance, ParallelAdjRingTopologyFixture, ::testing::Values(std::nullopt, thrift::PrefixType::BGP)); TEST_F(ParallelAdjRingTopologyFixture, ShortestPathTest) { CustomSetUp(false /* shortest path */, false /* useKsp2Ed */); auto routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); // Unicast routes => 4 * (4 - 1) = 12 // Node label routes => 4 * 4 = 16 // Adj label routes => 4 * 4 = 16 EXPECT_EQ(44, routeMap.size()); // validate router 1 EXPECT_EQ( routeMap[make_pair("1", toString(addr4))], NextHops( {createNextHopFromAdj(adj12_2, false, 22), createNextHopFromAdj(adj13_1, false, 22), createNextHopFromAdj(adj12_1, false, 22)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12_2, false, 22, labelSwapAction4), createNextHopFromAdj(adj13_1, false, 22, labelSwapAction4), createNextHopFromAdj(adj12_1, false, 22, labelSwapAction4)})); EXPECT_EQ( routeMap[make_pair("1", toString(addr3))], NextHops({createNextHopFromAdj(adj13_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj13_1, false, 11, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops( {createNextHopFromAdj(adj12_2, false, 11), createNextHopFromAdj(adj12_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12_2, false, 11, labelPhpAction), createNextHopFromAdj(adj12_1, false, 11, labelPhpAction)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(addr4))], NextHops({createNextHopFromAdj(adj24_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj24_1, false, 11, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", toString(addr3))], NextHops( {createNextHopFromAdj(adj21_2, false, 22), createNextHopFromAdj(adj21_1, false, 22), createNextHopFromAdj(adj24_1, false, 22)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj21_2, false, 22, labelSwapAction3), createNextHopFromAdj(adj21_1, false, 22, labelSwapAction3), createNextHopFromAdj(adj24_1, false, 22, labelSwapAction3)})); EXPECT_EQ( routeMap[make_pair("2", toString(addr1))], NextHops( {createNextHopFromAdj(adj21_2, false, 11), createNextHopFromAdj(adj21_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj21_2, false, 11, labelPhpAction), createNextHopFromAdj(adj21_1, false, 11, labelPhpAction)})); validatePopLabelRoute(routeMap, "2", *adjacencyDb2.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "2", *adjacencyDb2.adjacencies_ref()); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(addr4))], NextHops({createNextHopFromAdj(adj34_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj34_1, false, 11, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("3", toString(addr2))], NextHops( {createNextHopFromAdj(adj31_1, false, 22), createNextHopFromAdj(adj34_1, false, 22)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj31_1, false, 22, labelSwapAction2), createNextHopFromAdj(adj34_1, false, 22, labelSwapAction2)})); EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops({createNextHopFromAdj(adj31_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj31_1, false, 11, labelPhpAction)})); validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); // validate router 4 EXPECT_EQ( routeMap[make_pair("4", toString(addr3))], NextHops({createNextHopFromAdj(adj43_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj43_1, false, 11, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(addr2))], NextHops({createNextHopFromAdj(adj42_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42_1, false, 11, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(addr1))], NextHops( {createNextHopFromAdj(adj42_1, false, 22), createNextHopFromAdj(adj43_1, false, 22)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj42_1, false, 22, labelSwapAction1), createNextHopFromAdj(adj43_1, false, 22, labelSwapAction1)})); validatePopLabelRoute(routeMap, "4", *adjacencyDb4.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "4", *adjacencyDb4.adjacencies_ref()); } // // Use the same topology, but test multi-path routing // TEST_F(ParallelAdjRingTopologyFixture, MultiPathTest) { CustomSetUp(true /* multipath */, false /* useKsp2Ed */); auto routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); // Unicast routes => 4 * (4 - 1) = 12 // Node label routes => 4 * 4 = 16 // Adj label routes => 4 * 4 = 16 EXPECT_EQ(44, routeMap.size()); // validate router 1 // adj "2/3" is also selected in spite of large metric EXPECT_EQ( routeMap[make_pair("1", toString(addr4))], NextHops( {createNextHopFromAdj(adj12_1, false, 22), createNextHopFromAdj(adj12_2, false, 22), createNextHopFromAdj(adj13_1, false, 22)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12_1, false, 22, labelSwapAction4), createNextHopFromAdj(adj12_2, false, 22, labelSwapAction4), createNextHopFromAdj(adj13_1, false, 22, labelSwapAction4)})); EXPECT_EQ( routeMap[make_pair("1", toString(addr3))], NextHops({createNextHopFromAdj(adj13_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj13_1, false, 11, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops( {createNextHopFromAdj(adj12_1, false, 11), createNextHopFromAdj(adj12_2, false, 11)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12_1, false, 11, labelPhpAction), createNextHopFromAdj(adj12_2, false, 11, labelPhpAction)})); validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "1", *adjacencyDb1.adjacencies_ref()); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(addr4))], NextHops({createNextHopFromAdj(adj24_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj24_1, false, 11, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", toString(addr3))], NextHops( {createNextHopFromAdj(adj21_1, false, 22), createNextHopFromAdj(adj21_2, false, 22), createNextHopFromAdj(adj24_1, false, 22)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj21_1, false, 22, labelSwapAction3), createNextHopFromAdj(adj21_2, false, 22, labelSwapAction3), createNextHopFromAdj(adj24_1, false, 22, labelSwapAction3)})); EXPECT_EQ( routeMap[make_pair("2", toString(addr1))], NextHops( {createNextHopFromAdj(adj21_1, false, 11), createNextHopFromAdj(adj21_2, false, 11)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj21_1, false, 11, labelPhpAction), createNextHopFromAdj(adj21_2, false, 11, labelPhpAction)})); validatePopLabelRoute(routeMap, "2", *adjacencyDb2.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "2", *adjacencyDb2.adjacencies_ref()); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(addr4))], NextHops({createNextHopFromAdj(adj34_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj34_1, false, 11, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("3", toString(addr2))], NextHops( {createNextHopFromAdj(adj31_1, false, 22), createNextHopFromAdj(adj34_1, false, 22)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj31_1, false, 22, labelSwapAction2), createNextHopFromAdj(adj34_1, false, 22, labelSwapAction2)})); EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops({createNextHopFromAdj(adj31_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj31_1, false, 11, labelPhpAction)})); validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "3", *adjacencyDb3.adjacencies_ref()); // validate router 4 EXPECT_EQ( routeMap[make_pair("4", toString(addr3))], NextHops({createNextHopFromAdj(adj43_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj43_1, false, 11, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(addr2))], NextHops({createNextHopFromAdj(adj42_1, false, 11)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42_1, false, 11, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", toString(addr1))], NextHops( {createNextHopFromAdj(adj42_1, false, 22), createNextHopFromAdj(adj43_1, false, 22)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj42_1, false, 22, labelSwapAction1), createNextHopFromAdj(adj43_1, false, 22, labelSwapAction1)})); validatePopLabelRoute(routeMap, "4", *adjacencyDb4.nodeLabel_ref()); validateAdjLabelRoutes(routeMap, "4", *adjacencyDb4.adjacencies_ref()); } // // Use the same topology, but test KSP2_ED_ECMP routing // TEST_P(ParallelAdjRingTopologyFixture, Ksp2EdEcmp) { std::optional<thrift::PrefixType> prefixType = GetParam(); CustomSetUp(true /* multipath, ignored */, true /* useKsp2Ed */, prefixType); auto pushCode = thrift::MplsActionCode::PUSH; auto push1 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1}); auto push2 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2}); auto push3 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{3}); auto push4 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{4}); auto push34 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{3, 4}); auto push43 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{4, 3}); auto push12 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1, 2}); auto push21 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2, 1}); // Verify parallel link case between node-1 and node-2 auto routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops( {createNextHopFromAdj(adj12_1, false, 11, std::nullopt), createNextHopFromAdj(adj12_2, false, 11, std::nullopt), createNextHopFromAdj(adj12_3, false, 20, std::nullopt)})); auto prefixDBFour = getPrefixDbForNode(prefixState, "4"); // start to test minNexthop feature by injecting an ondeman prefix with // threshold to be 4 at the beginning. auto newPrefix = createPrefixEntry( bgpAddr1, thrift::PrefixType::LOOPBACK, "", thrift::PrefixForwardingType::SR_MPLS, thrift::PrefixForwardingAlgorithm::KSP2_ED_ECMP, std::nullopt, std::make_optional<int64_t>(4)); prefixDBFour.prefixEntries_ref()->push_back(newPrefix); updatePrefixDatabase(prefixState, prefixDBFour); routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); // in theory, kspf will choose adj12_2, adj13_1 as nexthops, // but since we set threhold to be 4, this route will get ignored. EXPECT_EQ(routeMap.find(make_pair("1", toString(bgpAddr1))), routeMap.end()); // updating threshold hold to be 2. // becasue we use edge disjoint algorithm, we should expect adj12_2 and // adj13_1 as nexthop prefixDBFour.prefixEntries_ref()->pop_back(); apache::thrift::fromFollyOptional( newPrefix.minNexthop_ref(), folly::make_optional<int64_t>(2)); prefixDBFour.prefixEntries_ref()->push_back(newPrefix); updatePrefixDatabase(prefixState, prefixDBFour); routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); EXPECT_EQ( routeMap[make_pair("1", toString(bgpAddr1))], NextHops( {createNextHopFromAdj(adj12_2, false, 22, push4), createNextHopFromAdj(adj13_1, false, 22, push4)})); for (const auto& nexthop : routeMap[make_pair("1", toString(bgpAddr1))]) { LOG(INFO) << (toString(nexthop)); } // Let node 3 announcing same prefix with limit 4. In this case, // threshold should be 4 instead of 2. And the ip is an anycast from node // 3 and 4. so nexthops should be adj12_2, adj13_1(shortes to node 4) // and adj13_1 shortest to node 3. The second shortes are all eliminated // becasue of purging logic we have for any cast ip. auto prefixDBThr = getPrefixDbForNode(prefixState, "3"); apache::thrift::fromFollyOptional( newPrefix.minNexthop_ref(), folly::make_optional<int64_t>(4)); prefixDBThr.prefixEntries_ref()->push_back(newPrefix); updatePrefixDatabase(prefixState, prefixDBThr); routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); EXPECT_EQ(routeMap.find(make_pair("1", toString(bgpAddr1))), routeMap.end()); // Revert the setup to normal state prefixDBFour.prefixEntries_ref()->pop_back(); prefixDBThr.prefixEntries_ref()->pop_back(); updatePrefixDatabase(prefixState, prefixDBFour); updatePrefixDatabase(prefixState, prefixDBThr); // // Bring down adj12_2 and adj34_2 to make our nexthop validations easy // Then validate routing table of all the nodes // adjacencyDb1.adjacencies_ref()->at(1).isOverloaded_ref() = true; adjacencyDb3.adjacencies_ref()->at(2).isOverloaded_ref() = true; auto& linkState = areaLinkStates.at(kTestingAreaName); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4"}, areaLinkStates, prefixState); // Unicast routes => 4 * (4 - 1) = 12 // Node label routes => 4 * 4 = 16 // Adj label routes => 4 * 3 = 16 EXPECT_EQ((GetParam() == thrift::PrefixType::BGP ? 56 : 44), routeMap.size()); // validate router 1 EXPECT_EQ( routeMap[make_pair("1", toString(addr4))], NextHops( {createNextHopFromAdj(adj12_1, false, 22, push4), createNextHopFromAdj(adj13_1, false, 22, push4)})); EXPECT_EQ( routeMap[make_pair("1", toString(addr3))], NextHops( {createNextHopFromAdj(adj13_1, false, 11, std::nullopt), createNextHopFromAdj(adj12_1, false, 33, push34)})); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops( {createNextHopFromAdj(adj12_1, false, 11, std::nullopt), createNextHopFromAdj(adj12_3, false, 20, std::nullopt)})); // validate router 2 EXPECT_EQ( routeMap[make_pair("2", toString(addr4))], NextHops( {createNextHopFromAdj(adj24_1, false, 11, std::nullopt), createNextHopFromAdj(adj21_1, false, 33, push43)})); EXPECT_EQ( routeMap[make_pair("2", toString(addr3))], NextHops( {createNextHopFromAdj(adj21_1, false, 22, push3), createNextHopFromAdj(adj24_1, false, 22, push3)})); EXPECT_EQ( routeMap[make_pair("2", toString(addr1))], NextHops( {createNextHopFromAdj(adj21_1, false, 11, std::nullopt), createNextHopFromAdj(adj21_3, false, 20, std::nullopt)})); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(addr4))], NextHops( {createNextHopFromAdj(adj34_1, false, 11, std::nullopt), createNextHopFromAdj(adj34_3, false, 20, std::nullopt)})); EXPECT_EQ( routeMap[make_pair("3", toString(addr2))], NextHops( {createNextHopFromAdj(adj31_1, false, 22, push2), createNextHopFromAdj(adj34_1, false, 22, push2)})); EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops( {createNextHopFromAdj(adj31_1, false, 11, std::nullopt), createNextHopFromAdj(adj34_1, false, 33, push12)})); // validate router 4 EXPECT_EQ( routeMap[make_pair("4", toString(addr3))], NextHops( {createNextHopFromAdj(adj43_1, false, 11, std::nullopt), createNextHopFromAdj(adj43_3, false, 20, std::nullopt)})); EXPECT_EQ( routeMap[make_pair("4", toString(addr2))], NextHops( {createNextHopFromAdj(adj42_1, false, 11, std::nullopt), createNextHopFromAdj(adj43_1, false, 33, push21)})); EXPECT_EQ( routeMap[make_pair("4", toString(addr1))], NextHops( {createNextHopFromAdj(adj42_1, false, 22, push1), createNextHopFromAdj(adj43_1, false, 22, push1)})); } TEST_P(ParallelAdjRingTopologyFixture, Ksp2EdEcmpForBGP) { CustomSetUp( true /* multipath, ignored */, true /* useKsp2Ed */, thrift::PrefixType::BGP); auto pushCode = thrift::MplsActionCode::PUSH; auto push1 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1}); auto push2 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2}); auto push3 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{3}); auto push4 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{4}); auto push34 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{3, 4}); auto push43 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{4, 3}); auto push12 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{1, 2}); auto push21 = createMplsAction(pushCode, std::nullopt, std::vector<int32_t>{2, 1}); // // Verify parallel link case between node-1 and node-2 auto routeMap = getRouteMap(*spfSolver, {"1"}, areaLinkStates, prefixState); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops( {createNextHopFromAdj(adj12_1, false, 11, std::nullopt), createNextHopFromAdj(adj12_2, false, 11, std::nullopt), createNextHopFromAdj(adj12_3, false, 20, std::nullopt)})); // // Bring down adj12_2 and adj34_2 to make our nexthop validations easy // Then validate routing table of all the nodes // adjacencyDb1.adjacencies_ref()->at(1).isOverloaded_ref() = true; adjacencyDb3.adjacencies_ref()->at(2).isOverloaded_ref() = true; auto& linkState = areaLinkStates.at(kTestingAreaName); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); thrift::MetricVector mv1, mv2; int64_t numMetrics = 5; mv1.metrics_ref()->resize(numMetrics); mv2.metrics_ref()->resize(numMetrics); for (int64_t i = 0; i < numMetrics; ++i) { mv1.metrics_ref()[i].type_ref() = i; mv2.metrics_ref()[i].type_ref() = i; mv1.metrics_ref()[i].priority_ref() = i; mv2.metrics_ref()[i].priority_ref() = i; mv1.metrics_ref()[i].op_ref() = thrift::CompareType::WIN_IF_PRESENT; mv2.metrics_ref()[i].op_ref() = thrift::CompareType::WIN_IF_PRESENT; mv1.metrics_ref()[i].isBestPathTieBreaker_ref() = false; mv2.metrics_ref()[i].isBestPathTieBreaker_ref() = false; *mv1.metrics_ref()[i].metric_ref() = *mv2.metrics_ref()[i].metric_ref() = {i}; } auto prefixDBOne = getPrefixDbForNode(prefixState, "1"); auto prefixDBTwo = getPrefixDbForNode(prefixState, "2"); // set metric vector for addr1 prefixes in two nodes to be same // for both, put this element at the back of the entries list auto& entriesVec = *prefixDBOne.prefixEntries_ref(); for (auto entryIter = entriesVec.begin(); entryIter != entriesVec.end(); ++entryIter) { if (entryIter->get_prefix() == addr1) { entryIter->mv_ref() = mv1; prefixDBTwo.prefixEntries_ref()->push_back(*entryIter); entriesVec.erase(entryIter); break; } } entriesVec.push_back(prefixDBTwo.prefixEntries_ref()->back()); updatePrefixDatabase(prefixState, prefixDBOne); updatePrefixDatabase(prefixState, prefixDBTwo); routeMap = getRouteMap(*spfSolver, {"3"}, areaLinkStates, prefixState); // validate router 3 EXPECT_EQ(routeMap.find(make_pair("3", toString(addr1))), routeMap.end()); // decrease mv for the second node, now router 3 should point to 1 // also set the threshold hold on non-best node to be 4. Threshold // on best node is 2. In such case, we should allow the route to be // programmed and announced. prefixDBTwo.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .metric_ref() ->front()--; prefixDBTwo.prefixEntries_ref()->back().minNexthop_ref() = 4; prefixDBOne.prefixEntries_ref()->back().minNexthop_ref() = 2; updatePrefixDatabase(prefixState, prefixDBTwo); updatePrefixDatabase(prefixState, prefixDBOne); routeMap = getRouteMap(*spfSolver, {"3"}, areaLinkStates, prefixState); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops( {createNextHopFromAdj(adj31_1, false, 11, std::nullopt), createNextHopFromAdj(adj34_1, false, 33, push12)})); // node 1 is the preferred node. Set threshold on Node 1 to be 4. // threshold on node 2 is 2. In such case, threshold should be respected // and we should not program/annouce any routes prefixDBTwo.prefixEntries_ref()->back().minNexthop_ref() = 2; prefixDBOne.prefixEntries_ref()->back().minNexthop_ref() = 4; updatePrefixDatabase(prefixState, prefixDBTwo); updatePrefixDatabase(prefixState, prefixDBOne); routeMap = getRouteMap(*spfSolver, {"3"}, areaLinkStates, prefixState); // validate router 3 EXPECT_EQ(routeMap.find(make_pair("3", toString(addr1))), routeMap.end()); // reset min nexthop to rest of checks prefixDBTwo.prefixEntries_ref()->back().minNexthop_ref().reset(); prefixDBOne.prefixEntries_ref()->back().minNexthop_ref().reset(); updatePrefixDatabase(prefixState, prefixDBTwo); updatePrefixDatabase(prefixState, prefixDBOne); // decrease mv for the second node, now router 3 should point to 2 prefixDBTwo.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .metric_ref() ->front() += 2; updatePrefixDatabase(prefixState, prefixDBTwo); routeMap = getRouteMap(*spfSolver, {"3"}, areaLinkStates, prefixState); // validate router 3 EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops( {createNextHopFromAdj(adj31_1, false, 22, push2), createNextHopFromAdj(adj34_1, false, 22, push2)})); // set the tie breaker to be true. in this case, both nodes will be selected prefixDBTwo.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .isBestPathTieBreaker_ref() = true; prefixDBOne.prefixEntries_ref() ->back() .mv_ref() .value() .metrics_ref() ->at(numMetrics - 1) .isBestPathTieBreaker_ref() = true; updatePrefixDatabase(prefixState, prefixDBTwo); updatePrefixDatabase(prefixState, prefixDBOne); routeMap = getRouteMap(*spfSolver, {"3"}, areaLinkStates, prefixState); // createNextHopFromAdj(adj34, v4Enabled, 30, push12, true) getting ignored // because in kspf, we will ignore second shortest path if it starts with // one of shortest path for anycast prefix EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops( {createNextHopFromAdj(adj31_1, false, 22, push2), createNextHopFromAdj(adj34_1, false, 22, push2), createNextHopFromAdj(adj31_1, false, 11, std::nullopt)})); } /** * Topology * R2 - - - - - - R4 * // \ 10 / * // 10 \ / * // \10 / 20 * R1 \ / * \ / * \ 10 / \ * \ / \ * R3 - - - - R5 * 10 * * Node-4, Node-5 announces the default route. We validates following * - IP2MPLS routes for prefixes announced from each node * - MPLS routes for each node * - No adjacency routes were accounted */ TEST(DecisionTest, Ip2MplsRoutes) { std::string nodeName("1"); auto spfSolver = std::make_unique<SpfSolver>(nodeName, false, true); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; // R1 auto adj12_1 = createAdjacency("2", "2/1", "1/1", "fe80::2", "192.168.1.2", 10, 0); auto adj12_2 = createAdjacency("2", "2/2", "1/2", "fe80::2", "192.168.1.2", 10, 0); auto adj13 = createAdjacency("3", "3/1", "1/1", "fe80::3", "192.168.1.3", 10, 0); // R2 auto adj21_1 = createAdjacency("1", "1/1", "2/1", "fe80::1", "192.168.1.1", 10, 0); auto adj21_2 = createAdjacency("1", "1/2", "2/2", "fe80::1", "192.168.1.1", 10, 0); auto adj24 = createAdjacency("4", "4/1", "2/1", "fe80::4", "192.168.1.4", 10, 0); auto adj25 = createAdjacency("5", "5/1", "2/1", "fe80::5", "192.168.1.5", 10, 0); // R3 auto adj31 = createAdjacency("1", "1/1", "3/1", "fe80::1", "192.168.1.1", 10, 0); auto adj34 = createAdjacency("4", "4/1", "3/1", "fe80::4", "192.168.1.4", 20, 0); auto adj35 = createAdjacency("5", "5/1", "3/1", "fe80::5", "192.168.1.5", 10, 0); // R4 auto adj42 = createAdjacency("2", "2/1", "4/1", "fe80::2", "192.168.1.2", 10, 0); auto adj43 = createAdjacency("3", "3/1", "4/1", "fe80::3", "192.168.1.3", 20, 0); // R5 auto adj52 = createAdjacency("2", "2/1", "5/1", "fe80::2", "192.168.1.2", 10, 0); auto adj53 = createAdjacency("3", "3/1", "5/1", "fe80::3", "192.168.1.3", 10, 0); auto adjacencyDb1 = createAdjDb("1", {adj12_1, adj12_2, adj13}, 1); auto adjacencyDb2 = createAdjDb("2", {adj21_1, adj21_2, adj24, adj25}, 2); auto adjacencyDb3 = createAdjDb("3", {adj31, adj34, adj35}, 3); auto adjacencyDb4 = createAdjDb("4", {adj42, adj43}, 4); auto adjacencyDb5 = createAdjDb("5", {adj52, adj53}, 5); // Adjacency db's EXPECT_FALSE(linkState.updateAdjacencyDatabase(adjacencyDb1).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb2).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb3).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb4).topologyChanged); EXPECT_TRUE(linkState.updateAdjacencyDatabase(adjacencyDb5).topologyChanged); // Prefix db's const auto defaultPrefixV6 = toIpPrefix("::/0"); const auto prefixDb1_ = createPrefixDb( "1", {createPrefixEntry( addr1, thrift::PrefixType::LOOPBACK, {}, thrift::PrefixForwardingType::SR_MPLS)}); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb1_).empty()); const auto prefixDb2_ = createPrefixDb( "2", {createPrefixEntry( addr2, thrift::PrefixType::LOOPBACK, {}, thrift::PrefixForwardingType::SR_MPLS)}); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb2_).empty()); const auto prefixDb3_ = createPrefixDb( "3", {createPrefixEntry( addr3, thrift::PrefixType::LOOPBACK, {}, thrift::PrefixForwardingType::SR_MPLS)}); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb3_).empty()); const auto prefixDb4_ = createPrefixDb( "4", {createPrefixEntry( defaultPrefixV6, thrift::PrefixType::LOOPBACK, {}, thrift::PrefixForwardingType::SR_MPLS)}); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb4_).empty()); const auto prefixDb5_ = createPrefixDb( "5", {createPrefixEntry( defaultPrefixV6, thrift::PrefixType::LOOPBACK, {}, thrift::PrefixForwardingType::SR_MPLS)}); EXPECT_FALSE(updatePrefixDatabase(prefixState, prefixDb5_).empty()); // Some actions auto const labelPush1 = createMplsAction( thrift::MplsActionCode::PUSH, std::nullopt, std::vector<int32_t>{1}); auto const labelPush2 = createMplsAction( thrift::MplsActionCode::PUSH, std::nullopt, std::vector<int32_t>{2}); auto const labelPush3 = createMplsAction( thrift::MplsActionCode::PUSH, std::nullopt, std::vector<int32_t>{3}); auto const labelPush4 = createMplsAction( thrift::MplsActionCode::PUSH, std::nullopt, std::vector<int32_t>{4}); auto const labelPush5 = createMplsAction( thrift::MplsActionCode::PUSH, std::nullopt, std::vector<int32_t>{5}); // // Get route-map // auto routeMap = getRouteMap( *spfSolver, {"1", "2", "3", "4", "5"}, areaLinkStates, prefixState); // Unicast routes => 15 (5 * 3) // Node label routes => 5 * 5 = 25 // Adj label routes => 0 EXPECT_EQ(40, routeMap.size()); // Validate router-1 validatePopLabelRoute(routeMap, "1", *adjacencyDb1.nodeLabel_ref()); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops( {createNextHopFromAdj(adj12_2, false, 10, std::nullopt), createNextHopFromAdj(adj12_1, false, 10, std::nullopt)})); EXPECT_EQ( routeMap[make_pair("1", toString(addr3))], NextHops({createNextHopFromAdj(adj13, false, 10, std::nullopt)})); EXPECT_EQ( routeMap[make_pair("1", "::/0")], NextHops( {createNextHopFromAdj(adj13, false, 20, labelPush5), createNextHopFromAdj(adj12_2, false, 20, labelPush4), createNextHopFromAdj(adj12_2, false, 20, labelPush5), createNextHopFromAdj(adj12_1, false, 20, labelPush4), createNextHopFromAdj(adj12_1, false, 20, labelPush5)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12_1, false, 10, labelPhpAction), createNextHopFromAdj(adj12_2, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj13, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12_1, false, 20, labelSwapAction4), createNextHopFromAdj(adj12_2, false, 20, labelSwapAction4)})); EXPECT_EQ( routeMap[make_pair("1", std::to_string(*adjacencyDb5.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj12_1, false, 20, labelSwapAction5), createNextHopFromAdj(adj12_2, false, 20, labelSwapAction5), createNextHopFromAdj(adj13, false, 20, labelSwapAction5)})); // Validate router-2 validatePopLabelRoute(routeMap, "2", *adjacencyDb2.nodeLabel_ref()); EXPECT_EQ( routeMap[make_pair("2", toString(addr1))], NextHops( {createNextHopFromAdj(adj21_1, false, 10), createNextHopFromAdj(adj21_2, false, 10)})); EXPECT_EQ( routeMap[make_pair("2", toString(addr3))], NextHops( {createNextHopFromAdj(adj21_1, false, 20, labelPush3), createNextHopFromAdj(adj21_2, false, 20, labelPush3), createNextHopFromAdj(adj25, false, 20, labelPush3)})); EXPECT_EQ( routeMap[make_pair("2", "::/0")], NextHops( {createNextHopFromAdj(adj24, false, 10), createNextHopFromAdj(adj25, false, 10)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj21_1, false, 10, labelPhpAction), createNextHopFromAdj(adj21_2, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj21_1, false, 20, labelSwapAction3), createNextHopFromAdj(adj21_2, false, 20, labelSwapAction3), createNextHopFromAdj(adj25, false, 20, labelSwapAction3)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj24, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("2", std::to_string(*adjacencyDb5.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj25, false, 10, labelPhpAction)})); // Validate router-3 validatePopLabelRoute(routeMap, "3", *adjacencyDb3.nodeLabel_ref()); EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops({createNextHopFromAdj(adj31, false, 10)})); EXPECT_EQ( routeMap[make_pair("3", toString(addr2))], NextHops( {createNextHopFromAdj(adj31, false, 20, labelPush2), createNextHopFromAdj(adj35, false, 20, labelPush2)})); EXPECT_EQ( routeMap[make_pair("3", "::/0")], NextHops({createNextHopFromAdj(adj35, false, 10)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj31, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj31, false, 20, labelSwapAction2), createNextHopFromAdj(adj35, false, 20, labelSwapAction2)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj34, false, 20, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("3", std::to_string(*adjacencyDb5.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj35, false, 10, labelPhpAction)})); // Validate router-4 validatePopLabelRoute(routeMap, "4", *adjacencyDb4.nodeLabel_ref()); EXPECT_EQ( routeMap[make_pair("4", toString(addr1))], NextHops({createNextHopFromAdj(adj42, false, 20, labelPush1)})); EXPECT_EQ( routeMap[make_pair("4", toString(addr2))], NextHops({createNextHopFromAdj(adj42, false, 10)})); EXPECT_EQ( routeMap[make_pair("4", toString(addr3))], NextHops({createNextHopFromAdj(adj43, false, 20)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 20, labelSwapAction1)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj43, false, 20, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("4", std::to_string(*adjacencyDb5.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj42, false, 20, labelSwapAction5)})); // Validate router-5 validatePopLabelRoute(routeMap, "5", *adjacencyDb5.nodeLabel_ref()); EXPECT_EQ( routeMap[make_pair("5", toString(addr1))], NextHops( {createNextHopFromAdj(adj52, false, 20, labelPush1), createNextHopFromAdj(adj53, false, 20, labelPush1)})); EXPECT_EQ( routeMap[make_pair("5", toString(addr2))], NextHops({createNextHopFromAdj(adj52, false, 10)})); EXPECT_EQ( routeMap[make_pair("5", toString(addr3))], NextHops({createNextHopFromAdj(adj53, false, 10)})); EXPECT_EQ( routeMap[make_pair("5", std::to_string(*adjacencyDb1.nodeLabel_ref()))], NextHops( {createNextHopFromAdj(adj52, false, 20, labelSwapAction1), createNextHopFromAdj(adj53, false, 20, labelSwapAction1)})); EXPECT_EQ( routeMap[make_pair("5", std::to_string(*adjacencyDb2.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj52, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("5", std::to_string(*adjacencyDb3.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj53, false, 10, labelPhpAction)})); EXPECT_EQ( routeMap[make_pair("5", std::to_string(*adjacencyDb4.nodeLabel_ref()))], NextHops({createNextHopFromAdj(adj52, false, 20, labelSwapAction4)})); } // // Test topology: // // n * n grid // A box m has up to 4 interfaces named 0/1, 0/2, 0/3, and 0/4 // m + n // | // 0/4 // | // m-1 ----0/3---- m ----0/1---- m + 1 // | // 0/2 // | // m - n // add adjacencies to neighbor at grid(i, j) void addAdj( int i, int j, string ifName, vector<thrift::Adjacency>& adjs, int n, string otherIfName) { if (i < 0 || i >= n || j < 0 || j >= n) { return; } auto neighbor = i * n + j; adjs.emplace_back(createThriftAdjacency( folly::sformat("{}", neighbor), ifName, folly::sformat("fe80::{}", neighbor), folly::sformat("192.168.{}.{}", neighbor / 256, neighbor % 256), 1, 100001 + neighbor /* adjacency-label */, false /* overload-bit */, 100, 10000 /* timestamp */, 1 /* weight */, otherIfName)); } string nodeToPrefixV6(int node) { return folly::sformat("::ffff:10.1.{}.{}/128", node / 256, node % 256); } void createGrid(LinkState& linkState, PrefixState& prefixState, int n) { LOG(INFO) << "grid: " << n << " by " << n; // confined bcoz of min("fe80::{}", "192.168.{}.{}", "::ffff:10.1.{}.{}") EXPECT_TRUE(n * n < 10000) << "n is too large"; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { auto node = i * n + j; auto nodeName = folly::sformat("{}", node); // adjacency vector<thrift::Adjacency> adjs; addAdj(i, j + 1, "0/1", adjs, n, "0/3"); addAdj(i - 1, j, "0/2", adjs, n, "0/4"); addAdj(i, j - 1, "0/3", adjs, n, "0/1"); addAdj(i + 1, j, "0/4", adjs, n, "0/2"); auto adjacencyDb = createAdjDb(nodeName, adjs, node + 1); linkState.updateAdjacencyDatabase(adjacencyDb); // prefix auto addrV6 = toIpPrefix(nodeToPrefixV6(node)); updatePrefixDatabase( prefixState, createPrefixDb(nodeName, {createPrefixEntry(addrV6)})); } } } class GridTopologyFixture : public ::testing::TestWithParam<int> { public: GridTopologyFixture() : spfSolver(nodeName, false, false) {} protected: void SetUp() override { n = GetParam(); areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); createGrid(linkState, prefixState, n); } // n * n grid int n; std::string nodeName{"1"}; SpfSolver spfSolver; std::unordered_map<std::string, LinkState> areaLinkStates; PrefixState prefixState; }; INSTANTIATE_TEST_CASE_P( GridTopology, GridTopologyFixture, ::testing::Range(2, 17, 2)); // distance from node a to b in the grid n*n of unit link cost int gridDistance(int a, int b, int n) { int x_a = a % n, x_b = b % n; int y_a = a / n, y_b = b / n; return abs(x_a - x_b) + abs(y_a - y_b); } TEST_P(GridTopologyFixture, ShortestPathTest) { vector<string> allNodes; for (int i = 0; i < n * n; ++i) { allNodes.push_back(folly::sformat("{}", i)); } auto routeMap = getRouteMap(spfSolver, allNodes, areaLinkStates, prefixState); // unicastRoutes => n^2 * (n^2 - 1) // node label routes => n^2 * n^2 // adj label routes => 2 * 2 * n * (n - 1) (each link is reported twice) // Total => 2n^4 + 3n^2 - 4n EXPECT_EQ(2 * n * n * n * n + 3 * n * n - 4 * n, routeMap.size()); int src{0}, dst{0}; NextHops nextHops; // validate route // 1) from corner to corner // primary diagnal src = 0; dst = n * n - 1; LOG(INFO) << "distance " << src << " -> " << dst << ": " << gridDistance(src, dst, n); nextHops = routeMap[make_pair(folly::sformat("{}", src), nodeToPrefixV6(dst))]; EXPECT_EQ(gridDistance(src, dst, n), *nextHops.begin()->metric_ref()); // secondary diagnal src = n - 1; dst = n * (n - 1); LOG(INFO) << "distance " << src << " -> " << dst << ": " << gridDistance(src, dst, n); nextHops = routeMap[make_pair(folly::sformat("{}", src), nodeToPrefixV6(dst))]; EXPECT_EQ(gridDistance(src, dst, n), *nextHops.begin()->metric_ref()); // 2) from origin (i.e., node 0) to random inner node src = 0; dst = folly::Random::rand32() % (n * n - 1) + 1; LOG(INFO) << "distance " << src << " -> " << dst << ": " << gridDistance(src, dst, n); nextHops = routeMap[make_pair(folly::sformat("{}", src), nodeToPrefixV6(dst))]; EXPECT_EQ(gridDistance(src, dst, n), *nextHops.begin()->metric_ref()); // 3) from one random node to another src = folly::Random::rand32() % (n * n); while ((dst = folly::Random::rand32() % (n * n)) == src) { } LOG(INFO) << "distance " << src << " -> " << dst << ": " << gridDistance(src, dst, n); nextHops = routeMap[make_pair(folly::sformat("{}", src), nodeToPrefixV6(dst))]; EXPECT_EQ(gridDistance(src, dst, n), *nextHops.begin()->metric_ref()); } // measure SPF execution time for large networks TEST(GridTopology, StressTest) { if (!FLAGS_stress_test) { return; } std::string nodeName("1"); SpfSolver spfSolver(nodeName, false, true); std::unordered_map<std::string, LinkState> areaLinkStates; areaLinkStates.emplace(kTestingAreaName, LinkState(kTestingAreaName)); auto& linkState = areaLinkStates.at(kTestingAreaName); PrefixState prefixState; createGrid(linkState, prefixState, 99); spfSolver.buildRouteDb("523", areaLinkStates, prefixState); } // // Start the decision thread and simulate KvStore communications // Expect proper RouteDatabase publications to appear // class DecisionTestFixture : public ::testing::Test { protected: void SetUp() override { // reset all global counters fb303::fbData->resetAllData(); auto tConfig = createConfig(); config = std::make_shared<Config>(tConfig); decision = make_shared<Decision>( config, false, /* bgpDryRun */ debounceTimeoutMin, debounceTimeoutMax, kvStoreUpdatesQueue.getReader(), staticRoutesUpdateQueue.getReader(), routeUpdatesQueue); decisionThread = std::make_unique<std::thread>([this]() { LOG(INFO) << "Decision thread starting"; decision->run(); LOG(INFO) << "Decision thread finishing"; }); decision->waitUntilRunning(); } void TearDown() override { kvStoreUpdatesQueue.close(); staticRoutesUpdateQueue.close(); LOG(INFO) << "Stopping the decision thread"; decision->stop(); decisionThread->join(); LOG(INFO) << "Decision thread got stopped"; } virtual openr::thrift::OpenrConfig createConfig() { auto tConfig = getBasicOpenrConfig("1"); // set coldstart to be longer than debounce time tConfig.eor_time_s_ref() = ((debounceTimeoutMax.count() * 2) / 1000); return tConfig; } // // member methods // std::unordered_map<std::string, thrift::RouteDatabase> dumpRouteDb(const vector<string>& allNodes) { std::unordered_map<std::string, thrift::RouteDatabase> routeMap; for (string const& node : allNodes) { auto resp = decision->getDecisionRouteDb(node).get(); EXPECT_TRUE(resp); EXPECT_EQ(node, *resp->thisNodeName_ref()); routeMap[node] = std::move(*resp); } return routeMap; } DecisionRouteUpdate recvRouteUpdates() { auto maybeRouteDb = routeUpdatesQueueReader.get(); EXPECT_FALSE(maybeRouteDb.hasError()); auto routeDbDelta = maybeRouteDb.value(); return routeDbDelta; } // publish routeDb void sendKvPublication(const thrift::Publication& publication) { kvStoreUpdatesQueue.push(publication); } void sendStaticRoutesUpdate(const thrift::RouteDatabaseDelta& publication) { DecisionRouteUpdate routeUpdate; for (const auto& unicastRoute : *publication.unicastRoutesToUpdate_ref()) { auto nhs = std::unordered_set<thrift::NextHopThrift>( unicastRoute.nextHops_ref()->begin(), unicastRoute.nextHops_ref()->end()); routeUpdate.addRouteToUpdate(RibUnicastEntry( toIPNetwork(*unicastRoute.dest_ref()), std::move(nhs))); } for (const auto& prefix : *publication.unicastRoutesToDelete_ref()) { routeUpdate.unicastRoutesToDelete.push_back(toIPNetwork(prefix)); } for (const auto& mplsRoute : *publication.mplsRoutesToUpdate_ref()) { auto nhs = std::unordered_set<thrift::NextHopThrift>( mplsRoute.nextHops_ref()->begin(), mplsRoute.nextHops_ref()->end()); routeUpdate.mplsRoutesToUpdate.push_back( RibMplsEntry(*mplsRoute.topLabel_ref(), std::move(nhs))); } for (const auto& label : *publication.mplsRoutesToDelete_ref()) { routeUpdate.mplsRoutesToDelete.push_back(label); } staticRoutesUpdateQueue.push(routeUpdate); } // helper function thrift::Value createAdjValue( const string& node, int64_t version, const vector<thrift::Adjacency>& adjs, bool overloaded = false, int32_t nodeId = 0) { auto adjDB = createAdjDb(node, adjs, nodeId); adjDB.isOverloaded_ref() = overloaded; return thrift::Value( FRAGILE, version, "originator-1", writeThriftObjStr(adjDB, serializer), Constants::kTtlInfinity /* ttl */, 0 /* ttl version */, 0 /* hash */); } thrift::Value createPrefixValue( const string& node, int64_t version, thrift::PrefixDatabase const& prefixDb) { return createThriftValue( version, node, writeThriftObjStr(prefixDb, serializer), Constants::kTtlInfinity /* ttl */, 0 /* ttl version */, 0 /* hash */); } thrift::Value createPrefixValue( const string& node, int64_t version, const vector<thrift::IpPrefix>& prefixes = {}, const string& area = kTestingAreaName) { vector<thrift::PrefixEntry> prefixEntries; for (const auto& prefix : prefixes) { prefixEntries.emplace_back(createPrefixEntry(prefix)); } return createPrefixValue( node, version, createPrefixDb(node, prefixEntries, area)); } std::unordered_map<std::string, thrift::Value> createPerPrefixKeyValue( const string& node, int64_t version, const vector<thrift::IpPrefix>& prefixes) { std::unordered_map<std::string, thrift::Value> keyVal{}; for (const auto& prefix : prefixes) { const auto prefixKey = PrefixKey( node, folly::IPAddress::createNetwork(toString(prefix)), kTestingAreaName); keyVal[prefixKey.getPrefixKey()] = createThriftValue( version, node, writeThriftObjStr( createPrefixDb(node, {createPrefixEntry(prefix)}), serializer), Constants::kTtlInfinity /* ttl */, 0 /* ttl version */, 0 /* hash */); } return keyVal; } /** * Check whether two DecisionRouteUpdates to be equal */ bool checkEqualRoutesDelta( DecisionRouteUpdate& lhsC, thrift::RouteDatabaseDelta& rhs) { auto lhs = lhsC.toThrift(); std::sort( lhs.unicastRoutesToUpdate_ref()->begin(), lhs.unicastRoutesToUpdate_ref()->end()); std::sort( rhs.unicastRoutesToUpdate_ref()->begin(), rhs.unicastRoutesToUpdate_ref()->end()); std::sort( lhs.unicastRoutesToDelete_ref()->begin(), lhs.unicastRoutesToDelete_ref()->end()); std::sort( rhs.unicastRoutesToDelete_ref()->begin(), rhs.unicastRoutesToDelete_ref()->end()); return *lhs.unicastRoutesToUpdate_ref() == *rhs.unicastRoutesToUpdate_ref() && *lhs.unicastRoutesToDelete_ref() == *rhs.unicastRoutesToDelete_ref(); } // // member variables // // Thrift serializer object for serializing/deserializing of thrift objects // to/from bytes CompactSerializer serializer{}; std::shared_ptr<Config> config; messaging::ReplicateQueue<thrift::Publication> kvStoreUpdatesQueue; messaging::ReplicateQueue<DecisionRouteUpdate> staticRoutesUpdateQueue; messaging::ReplicateQueue<DecisionRouteUpdate> routeUpdatesQueue; messaging::RQueue<DecisionRouteUpdate> routeUpdatesQueueReader{ routeUpdatesQueue.getReader()}; // Decision owned by this wrapper. std::shared_ptr<Decision> decision{nullptr}; // Thread in which decision will be running. std::unique_ptr<std::thread> decisionThread{nullptr}; }; // The following topology is used: // // 1---2---3 // // We upload the link 1---2 with the initial sync and later publish // the 2---3 link information. We then request the full routing dump // from the decision process via respective socket. // TEST_F(DecisionTestFixture, BasicOperations) { // // publish the link state info to KvStore // auto publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12}, false, 1)}, {"adj:2", createAdjValue("2", 1, {adj21}, false, 2)}, createPrefixKeyValue("1", 1, addr1), createPrefixKeyValue("2", 1, addr2)}, {}, {}, {}, std::string("")); auto routeDbBefore = dumpRouteDb({"1"})["1"]; sendKvPublication(publication); auto routeDbDelta = recvRouteUpdates(); EXPECT_EQ(1, routeDbDelta.unicastRoutesToUpdate.size()); // self mpls route, node 2 mpls route and adj12 label route EXPECT_EQ(3, routeDbDelta.mplsRoutesToUpdate.size()); EXPECT_EQ(0, routeDbDelta.mplsRoutesToDelete.size()); EXPECT_EQ(0, routeDbDelta.unicastRoutesToDelete.size()); auto routeDb = dumpRouteDb({"1"})["1"]; std::sort( routeDb.unicastRoutes_ref()->begin(), routeDb.unicastRoutes_ref()->end()); std::sort(routeDb.mplsRoutes_ref()->begin(), routeDb.mplsRoutes_ref()->end()); auto routeDelta = findDeltaRoutes(routeDb, routeDbBefore); EXPECT_TRUE(checkEqualRoutesDelta(routeDbDelta, routeDelta)); RouteMap routeMap; fillRouteMap("1", routeMap, routeDb); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops({createNextHopFromAdj(adj12, false, 10)})); // // publish the link state info to KvStore via the KvStore pub socket // we simulate adding a new router R3 // // Some tricks here; we need to bump the time-stamp on router 2's data, so // it can override existing; for router 3 we publish new key-value publication = createThriftPublication( {{"adj:3", createAdjValue("3", 1, {adj32}, false, 3)}, {"adj:2", createAdjValue("2", 3, {adj21, adj23}, false, 2)}, {"adj:4", createAdjValue("4", 1, {}, false, 4)}, // No adjacencies createPrefixKeyValue("3", 1, addr3)}, {}, {}, {}, std::string("")); routeDbBefore = dumpRouteDb({"1"})["1"]; std::sort( routeDbBefore.unicastRoutes_ref()->begin(), routeDbBefore.unicastRoutes_ref()->end()); std::sort( routeDbBefore.mplsRoutes_ref()->begin(), routeDbBefore.mplsRoutes_ref()->end()); sendKvPublication(publication); // validate routers // receive my local Decision routeDbDelta publication routeDbDelta = recvRouteUpdates(); // only expect to add a route to addr3 EXPECT_EQ(1, routeDbDelta.unicastRoutesToUpdate.size()); EXPECT_EQ( routeDbDelta.unicastRoutesToUpdate.begin()->second.prefix, toIPNetwork(addr3)); EXPECT_EQ(1, routeDbDelta.mplsRoutesToUpdate.size()); EXPECT_EQ(0, routeDbDelta.mplsRoutesToDelete.size()); EXPECT_EQ(0, routeDbDelta.unicastRoutesToDelete.size()); routeDb = dumpRouteDb({"1"})["1"]; std::sort( routeDb.unicastRoutes_ref()->begin(), routeDb.unicastRoutes_ref()->end()); std::sort(routeDb.mplsRoutes_ref()->begin(), routeDb.mplsRoutes_ref()->end()); routeDelta = findDeltaRoutes(routeDb, routeDbBefore); EXPECT_TRUE(checkEqualRoutesDelta(routeDbDelta, routeDelta)); fillRouteMap("1", routeMap, routeDb); // 1 EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops({createNextHopFromAdj(adj12, false, 10)})); EXPECT_EQ( routeMap[make_pair("1", toString(addr3))], NextHops({createNextHopFromAdj(adj12, false, 20)})); // dump other nodes' routeDB auto routeDbMap = dumpRouteDb({"2", "3"}); EXPECT_EQ(2, routeDbMap["2"].unicastRoutes_ref()->size()); EXPECT_EQ(2, routeDbMap["3"].unicastRoutes_ref()->size()); for (auto& [key, value] : routeDbMap) { fillRouteMap(key, routeMap, value); } // 2 EXPECT_EQ( routeMap[make_pair("2", toString(addr1))], NextHops({createNextHopFromAdj(adj21, false, 10)})); EXPECT_EQ( routeMap[make_pair("2", toString(addr3))], NextHops({createNextHopFromAdj(adj23, false, 10)})); // 3 EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops({createNextHopFromAdj(adj32, false, 20)})); EXPECT_EQ( routeMap[make_pair("3", toString(addr2))], NextHops({createNextHopFromAdj(adj32, false, 10)})); // remove 3 publication = createThriftPublication( thrift::KeyVals{}, {"adj:3", "prefix:3", "adj:4"} /* expired keys */, {}, {}, std::string("")); routeDbBefore = dumpRouteDb({"1"})["1"]; std::sort( routeDbBefore.unicastRoutes_ref()->begin(), routeDbBefore.unicastRoutes_ref()->end()); std::sort( routeDbBefore.mplsRoutes_ref()->begin(), routeDbBefore.mplsRoutes_ref()->end()); sendKvPublication(publication); routeDbDelta = recvRouteUpdates(); EXPECT_EQ(1, routeDbDelta.unicastRoutesToDelete.size()); EXPECT_EQ(1, routeDbDelta.mplsRoutesToDelete.size()); routeDb = dumpRouteDb({"1"})["1"]; std::sort( routeDb.unicastRoutes_ref()->begin(), routeDb.unicastRoutes_ref()->end()); std::sort(routeDb.mplsRoutes_ref()->begin(), routeDb.mplsRoutes_ref()->end()); routeDelta = findDeltaRoutes(routeDb, routeDbBefore); EXPECT_TRUE(checkEqualRoutesDelta(routeDbDelta, routeDelta)); fillRouteMap("1", routeMap, routeDb); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops({createNextHopFromAdj(adj12, false, 10)})); publication = createThriftPublication( {{"adj:3", createAdjValue("3", 1, {adj32}, false, 3)}, {"adj:2", createAdjValue("2", 4, {adj21, adj23}, false, 2)}, createPrefixKeyValue("3", 1, addr3)}, {}, {}, {}, std::string("")); routeDbBefore = dumpRouteDb({"1"})["1"]; std::sort( routeDbBefore.unicastRoutes_ref()->begin(), routeDbBefore.unicastRoutes_ref()->end()); std::sort( routeDbBefore.mplsRoutes_ref()->begin(), routeDbBefore.mplsRoutes_ref()->end()); sendKvPublication(publication); // validate routers // receive my local Decision routeDbDelta publication routeDbDelta = recvRouteUpdates(); // only expect to add a route to addr3 EXPECT_EQ(1, routeDbDelta.unicastRoutesToUpdate.size()); EXPECT_EQ( routeDbDelta.unicastRoutesToUpdate.begin()->second.prefix, toIPNetwork(addr3)); EXPECT_EQ(0, routeDbDelta.mplsRoutesToDelete.size()); EXPECT_EQ(1, routeDbDelta.mplsRoutesToUpdate.size()); routeDb = dumpRouteDb({"1"})["1"]; std::sort( routeDb.unicastRoutes_ref()->begin(), routeDb.unicastRoutes_ref()->end()); std::sort(routeDb.mplsRoutes_ref()->begin(), routeDb.mplsRoutes_ref()->end()); routeDelta = findDeltaRoutes(routeDb, routeDbBefore); EXPECT_TRUE(checkEqualRoutesDelta(routeDbDelta, routeDelta)); // construct new static mpls route add thrift::RouteDatabaseDelta input; thrift::NextHopThrift nh, nh1; *nh.address_ref() = toBinaryAddress(folly::IPAddressV6("::1")); *nh1.address_ref() = toBinaryAddress(folly::IPAddressV6("::2")); nh.mplsAction_ref() = createMplsAction(thrift::MplsActionCode::POP_AND_LOOKUP); nh1.mplsAction_ref() = createMplsAction(thrift::MplsActionCode::POP_AND_LOOKUP); thrift::MplsRoute route; route.topLabel_ref() = 32011; route.nextHops_ref() = {nh}; input.mplsRoutesToUpdate_ref()->push_back(route); // record number of mplsRoute as reference const auto mplsRouteCnt = decision->getDecisionRouteDb("").get()->mplsRoutes_ref()->size(); // Update 32011 and make sure only that is updated sendStaticRoutesUpdate(input); auto routesDelta = routeUpdatesQueueReader.get().value(); routesDelta.perfEvents.reset(); EXPECT_EQ(routesDelta.toThrift(), input); // Update 32012 and make sure only that is updated route.topLabel_ref() = 32012; input.mplsRoutesToUpdate_ref() = {route}; sendStaticRoutesUpdate(input); routesDelta = routeUpdatesQueueReader.get().value(); routesDelta.perfEvents.reset(); EXPECT_EQ(routesDelta.toThrift(), input); auto mplsRoutes = *decision->getDecisionRouteDb("").get()->mplsRoutes_ref(); EXPECT_THAT(mplsRoutes, testing::SizeIs(mplsRouteCnt + 2)); EXPECT_THAT( mplsRoutes, testing::Contains(AllOf( Truly([&](auto route) { return route.topLabel_ref() == 32011 or route.topLabel_ref() == 32012; }), ResultOf(getMplsNextHops, testing::UnorderedElementsAre(nh))))); // Test our consolidating logic, we first update 32011 then delete 32011 // making sure only delete for 32011 is emitted. route.topLabel_ref() = 32011; route.nextHops_ref() = {nh, nh1}; input.mplsRoutesToUpdate_ref() = {route}; input.mplsRoutesToDelete_ref()->clear(); sendStaticRoutesUpdate(input); input.mplsRoutesToUpdate_ref()->clear(); input.mplsRoutesToDelete_ref() = {32011}; sendStaticRoutesUpdate(input); routesDelta = routeUpdatesQueueReader.get().value(); routesDelta.perfEvents.reset(); EXPECT_EQ(routesDelta.mplsRoutesToDelete.at(0), 32011); EXPECT_EQ(routesDelta.mplsRoutesToUpdate.size(), 0); mplsRoutes = *decision->getDecisionRouteDb("").get()->mplsRoutes_ref(); EXPECT_THAT(mplsRoutes, testing::SizeIs(mplsRouteCnt + 1)); EXPECT_THAT( mplsRoutes, testing::Contains(AllOf( Truly([&](auto route) { return route.topLabel_ref() == 32012; }), ResultOf(getMplsNextHops, testing::UnorderedElementsAre(nh))))); // test our consolidating logic, we first delete 32012 then update 32012 // making sure only update for 32012 is emitted. input.mplsRoutesToUpdate_ref()->clear(); input.mplsRoutesToDelete_ref() = {32012}; sendStaticRoutesUpdate(input); route.topLabel_ref() = 32012; route.nextHops_ref() = {nh, nh1}; input.mplsRoutesToUpdate_ref() = {route}; input.mplsRoutesToDelete_ref()->clear(); sendStaticRoutesUpdate(input); routesDelta = routeUpdatesQueueReader.get().value(); routesDelta.perfEvents.reset(); EXPECT_EQ(1, routesDelta.mplsRoutesToUpdate.size()); EXPECT_EQ(32012, routesDelta.mplsRoutesToUpdate.at(0).label); EXPECT_THAT( routesDelta.mplsRoutesToUpdate.at(0).nexthops, testing::UnorderedElementsAre(nh, nh1)); mplsRoutes = *decision->getDecisionRouteDb("").get()->mplsRoutes_ref(); EXPECT_THAT(mplsRoutes, testing::SizeIs(mplsRouteCnt + 1)); EXPECT_THAT( mplsRoutes, testing::Contains(AllOf( Truly([&](auto route) { return route.topLabel_ref() == 32012; }), ResultOf(getMplsNextHops, testing::UnorderedElementsAre(nh, nh1))))); routeDb = dumpRouteDb({"1"})["1"]; bool foundLabelRoute{false}; for (auto const& mplsRoute : *routeDb.mplsRoutes_ref()) { if (*mplsRoute.topLabel_ref() != 32012) { continue; } EXPECT_THAT( *mplsRoute.nextHops_ref(), testing::UnorderedElementsAreArray({nh, nh1})); foundLabelRoute = true; break; } EXPECT_TRUE(foundLabelRoute); } /** * Publish all types of update to Decision and expect that Decision emits * a full route database that includes all the routes as its first update. * * Types of information updated * - Adjacencies (with MPLS labels) * - Prefixes * - MPLS Static routes */ TEST_F(DecisionTestFixture, InitialRouteUpdate) { // Send adj publication sendKvPublication(createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12}, false, 1)}, {"adj:2", createAdjValue("2", 1, {adj21}, false, 2)}}, {}, {}, {}, std::string(""))); // Send prefix publication sendKvPublication(createThriftPublication( {createPrefixKeyValue("1", 1, addr1), createPrefixKeyValue("2", 1, addr2)}, {}, {}, {}, std::string(""))); // Send static MPLS routes thrift::RouteDatabaseDelta staticRoutes; { thrift::NextHopThrift nh; nh.address_ref() = toBinaryAddress(folly::IPAddressV6("::1")); nh.mplsAction_ref() = createMplsAction(thrift::MplsActionCode::POP_AND_LOOKUP); thrift::MplsRoute mplsRoute; mplsRoute.topLabel_ref() = 32011; mplsRoute.nextHops_ref() = {nh}; staticRoutes.mplsRoutesToUpdate_ref()->push_back(mplsRoute); } sendStaticRoutesUpdate(staticRoutes); // Receive & verify all the expected updates auto routeDbDelta = recvRouteUpdates(); EXPECT_EQ(1, routeDbDelta.unicastRoutesToUpdate.size()); // self mpls route, node 2 mpls route, adj12 label route, static MPLS route EXPECT_EQ(4, routeDbDelta.mplsRoutesToUpdate.size()); EXPECT_EQ(0, routeDbDelta.mplsRoutesToDelete.size()); EXPECT_EQ(0, routeDbDelta.unicastRoutesToDelete.size()); } /* * Route Origination Test: * - Test 1: * - static prefixes advertised from `PrefixManager` * - expect `routesToUpdate` contains prefixes advertised; * - Test 2: * - advertise SAME prefix from `Decision`(i.e. prefix update in KvStore) * - expect `routesToUpdate` contains prefixes BUT NHs overridden * by `decision`; * - Test 3: * - withdraw static prefixes from `PrefixManager` * - expect `routesToUpdate` contains prefixes BUT NHs overridden * by `deicision`; * - Test 4: * - re-advertise static prefixes from `PrefixManager` * - expect `routesToUpdate` contains prefixes BUT NHs overridden * by `deicision`; * - Test 5: * - withdraw prefixes from `Decision`(i.e. prefix deleted in KvStore) * - expect `routesToUpdate` contains static prefixes from `PrefixManager` * - Test 6: * - withdraw static prefixes from `PrefixManager` * - expect `routesToDelete` contains static prefixes */ TEST_F(DecisionTestFixture, RouteOrigination) { // eventbase to control the pace of tests OpenrEventBase evb; // prepare prefix/nexthops structure const std::string prefixV4 = "10.0.0.1/24"; const std::string prefixV6 = "fe80::1/64"; thrift::NextHopThrift nhV4, nhV6; nhV4.address_ref() = toBinaryAddress(Constants::kLocalRouteNexthopV4.toString()); nhV6.address_ref() = toBinaryAddress(Constants::kLocalRouteNexthopV6.toString()); const auto networkV4 = folly::IPAddress::createNetwork(prefixV4); const auto networkV6 = folly::IPAddress::createNetwork(prefixV6); auto routeV4 = createUnicastRoute(toIpPrefix(prefixV4), {nhV4}); auto routeV6 = createUnicastRoute(toIpPrefix(prefixV6), {nhV6}); // Send adj publication // ATTN: to trigger `buildRouteDb()`. Must provide LinkState // info containing self-node id("1") auto scheduleAt = std::chrono::milliseconds{0}; evb.scheduleTimeout(scheduleAt, [&]() noexcept { sendKvPublication(createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12}, false, 1)}, {"adj:2", createAdjValue("2", 1, {adj21}, false, 2)}}, {}, {}, {}, std::string(""))); }); // // Test1: advertise prefixes from `PrefixManager` // evb.scheduleTimeout(scheduleAt += 3 * debounceTimeoutMax, [&]() noexcept { // wait for initial cold-timer to fire auto routeDbDelta = recvRouteUpdates(); LOG(INFO) << "Advertising static prefixes from PrefixManager"; thrift::RouteDatabaseDelta routeDb; routeDb.unicastRoutesToUpdate_ref()->emplace_back(routeV4); routeDb.unicastRoutesToUpdate_ref()->emplace_back(routeV6); sendStaticRoutesUpdate(std::move(routeDb)); }); // wait for debouncer to fire evb.scheduleTimeout( scheduleAt += (debounceTimeoutMax + std::chrono::milliseconds(100)), [&]() noexcept { // Receive & verify all the expected updates auto routeDbDelta = recvRouteUpdates(); EXPECT_THAT(routeDbDelta.unicastRoutesToUpdate, testing::SizeIs(2)); EXPECT_THAT(routeDbDelta.unicastRoutesToDelete, testing::SizeIs(0)); const auto& routeToUpdate = routeDbDelta.unicastRoutesToUpdate; ASSERT_TRUE(routeToUpdate.count(networkV4)); ASSERT_TRUE(routeToUpdate.count(networkV6)); EXPECT_THAT( routeToUpdate.at(networkV4), testing::Truly([&networkV4](auto i) { return i.prefix == networkV4 and i.doNotInstall == false; })); EXPECT_THAT( routeToUpdate.at(networkV6), testing::Truly([&networkV6](auto i) { return i.prefix == networkV6 and i.doNotInstall == false; })); // NOTE: no SAME route from decision, program DROP route EXPECT_THAT( routeToUpdate.at(networkV4).nexthops, testing::UnorderedElementsAre(nhV4)); EXPECT_THAT( routeToUpdate.at(networkV6).nexthops, testing::UnorderedElementsAre(nhV6)); }); // // Test2: advertise SAME prefixes from `Decision` // evb.scheduleTimeout( scheduleAt += std::chrono::milliseconds(100), [&]() noexcept { LOG(INFO) << "Advertising SAME prefixes from Decision"; sendKvPublication(createThriftPublication( {createPrefixKeyValue("2", 1, toIpPrefix(prefixV4)), createPrefixKeyValue("2", 1, toIpPrefix(prefixV6))}, {}, {}, {}, std::string(""))); // Receive & verify all the expected updates auto routeDbDelta = recvRouteUpdates(); EXPECT_THAT(routeDbDelta.unicastRoutesToUpdate, testing::SizeIs(2)); EXPECT_THAT(routeDbDelta.unicastRoutesToDelete, testing::SizeIs(0)); const auto& routeToUpdate = routeDbDelta.unicastRoutesToUpdate; ASSERT_TRUE(routeToUpdate.count(networkV4)); ASSERT_TRUE(routeToUpdate.count(networkV6)); // NOTE: route from decision takes higher priority EXPECT_THAT( routeToUpdate.at(networkV4).nexthops, Not(testing::UnorderedElementsAre(nhV4))); EXPECT_THAT( routeToUpdate.at(networkV6).nexthops, Not(testing::UnorderedElementsAre(nhV6))); }); // // Test3: withdraw prefixes from `PrefixManager` // evb.scheduleTimeout( scheduleAt += std::chrono::milliseconds(100), [&]() noexcept { LOG(INFO) << "Withdrawing static prefixes from PrefixManager"; thrift::RouteDatabaseDelta routeDb; routeDb.unicastRoutesToDelete_ref()->emplace_back( toIpPrefix(networkV4)); routeDb.unicastRoutesToDelete_ref()->emplace_back( toIpPrefix(networkV6)); sendStaticRoutesUpdate(std::move(routeDb)); }); // wait for debouncer to fire evb.scheduleTimeout( scheduleAt += (debounceTimeoutMax + std::chrono::milliseconds(100)), [&]() noexcept { // Receive & verify all the expected updates auto routeDbDelta = recvRouteUpdates(); EXPECT_THAT(routeDbDelta.unicastRoutesToUpdate, testing::SizeIs(2)); EXPECT_THAT(routeDbDelta.unicastRoutesToDelete, testing::SizeIs(0)); const auto& routeToUpdate = routeDbDelta.unicastRoutesToUpdate; ASSERT_TRUE(routeToUpdate.count(networkV4)); ASSERT_TRUE(routeToUpdate.count(networkV6)); // NOTE: route from Decision is the ONLY output EXPECT_THAT( routeToUpdate.at(networkV4).nexthops, Not(testing::UnorderedElementsAre(nhV4))); EXPECT_THAT( routeToUpdate.at(networkV6).nexthops, Not(testing::UnorderedElementsAre(nhV6))); }); // // Test4: re-advertise prefixes from `PrefixManager` // evb.scheduleTimeout( scheduleAt += std::chrono::milliseconds(100), [&]() noexcept { LOG(INFO) << "Re-advertising static prefixes from PrefixManager"; thrift::RouteDatabaseDelta routeDb; routeDb.unicastRoutesToUpdate_ref()->emplace_back(routeV4); routeDb.unicastRoutesToUpdate_ref()->emplace_back(routeV6); sendStaticRoutesUpdate(std::move(routeDb)); }); // wait for debouncer to fire evb.scheduleTimeout( scheduleAt += (debounceTimeoutMax + std::chrono::milliseconds(100)), [&]() noexcept { // Receive & verify all the expected updates auto routeDbDelta = recvRouteUpdates(); EXPECT_THAT(routeDbDelta.unicastRoutesToUpdate, testing::SizeIs(2)); EXPECT_THAT(routeDbDelta.unicastRoutesToDelete, testing::SizeIs(0)); const auto& routeToUpdate = routeDbDelta.unicastRoutesToUpdate; ASSERT_TRUE(routeToUpdate.count(networkV4)); ASSERT_TRUE(routeToUpdate.count(networkV6)); // NOTE: route from decision takes higher priority EXPECT_THAT( routeToUpdate.at(networkV4).nexthops, Not(testing::UnorderedElementsAre(nhV4))); EXPECT_THAT( routeToUpdate.at(networkV6).nexthops, Not(testing::UnorderedElementsAre(nhV6))); }); // // Test5: withdraw prefixes from `Decision` // evb.scheduleTimeout( scheduleAt += std::chrono::milliseconds(100), [&]() noexcept { LOG(INFO) << "Withdrawing prefixes from Decision"; sendKvPublication(createThriftPublication( {createPrefixKeyValue( "2", 1, toIpPrefix(prefixV4), kTestingAreaName, true), createPrefixKeyValue( "2", 1, toIpPrefix(prefixV6), kTestingAreaName, true)}, {}, {}, {}, std::string(""))); // Receive & verify all the expected updates auto routeDbDelta = recvRouteUpdates(); EXPECT_THAT(routeDbDelta.unicastRoutesToUpdate, testing::SizeIs(2)); EXPECT_THAT(routeDbDelta.unicastRoutesToDelete, testing::SizeIs(0)); const auto& routeToUpdate = routeDbDelta.unicastRoutesToUpdate; ASSERT_TRUE(routeToUpdate.count(networkV4)); ASSERT_TRUE(routeToUpdate.count(networkV6)); // NOTE: no routes from decision. Program DROP routes. EXPECT_THAT( routeToUpdate.at(networkV4).nexthops, testing::UnorderedElementsAre(nhV4)); EXPECT_THAT( routeToUpdate.at(networkV6).nexthops, testing::UnorderedElementsAre(nhV6)); }); // // Test6: withdraw prefixes from `PrefixManager` // evb.scheduleTimeout( scheduleAt += std::chrono::milliseconds(100), [&]() noexcept { LOG(INFO) << "Withdrawing prefixes from PrefixManager"; thrift::RouteDatabaseDelta routeDb; routeDb.unicastRoutesToDelete_ref()->emplace_back( toIpPrefix(networkV4)); routeDb.unicastRoutesToDelete_ref()->emplace_back( toIpPrefix(networkV6)); sendStaticRoutesUpdate(std::move(routeDb)); }); // wait for debouncer to fire evb.scheduleTimeout( scheduleAt += (debounceTimeoutMax + std::chrono::milliseconds(100)), [&]() noexcept { // Receive & verify all the expected updates auto routeDbDelta = recvRouteUpdates(); EXPECT_THAT(routeDbDelta.unicastRoutesToUpdate, testing::SizeIs(0)); EXPECT_THAT(routeDbDelta.unicastRoutesToDelete, testing::SizeIs(2)); EXPECT_THAT( routeDbDelta.unicastRoutesToDelete, testing::UnorderedElementsAre(networkV4, networkV6)); evb.stop(); }); // magic happens evb.run(); } // The following topology is used: // 1--- A ---2 // | | // B A // | | // 3--- B ---4 // // area A: adj12, adj24 // area B: adj13, adj34 TEST_F(DecisionTestFixture, MultiAreaBestPathCalculation) { // // publish area A adj and prefix // "1" originate addr1 into A // "2" originate addr2 into A // auto publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12}, false, 1)}, {"adj:2", createAdjValue("2", 1, {adj21, adj24}, false, 2)}, {"adj:4", createAdjValue("4", 1, {adj42}, false, 4)}, createPrefixKeyValue("1", 1, addr1, "A"), createPrefixKeyValue("2", 1, addr2, "A")}, {}, /* expiredKeys */ {}, /* nodeIds */ {}, /* keysToUpdate */ std::string(""), /*floodRootId */ "A"); sendKvPublication(publication); recvRouteUpdates(); // // publish area B adj and prefix // "3" originate addr3 into B // "4" originate addr4 into B // publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj13}, false, 1)}, {"adj:3", createAdjValue("3", 1, {adj31, adj34}, false, 3)}, {"adj:4", createAdjValue("4", 1, {adj43}, false, 4)}, createPrefixKeyValue("3", 1, addr3, "B"), createPrefixKeyValue("4", 1, addr4, "B")}, {}, /* expiredKeys */ {}, /* nodeIds */ {}, /* keysToUpdate */ std::string(""), /*floodRootId */ "B"); sendKvPublication(publication); recvRouteUpdates(); auto routeDb1 = dumpRouteDb({"1"})["1"]; auto routeDb2 = dumpRouteDb({"2"})["2"]; auto routeDb3 = dumpRouteDb({"3"})["3"]; auto routeDb4 = dumpRouteDb({"4"})["4"]; // routeDb1 from node "1" { auto routeToAddr2 = createUnicastRoute( addr2, {createNextHopFromAdj(adj12, false, 10, std::nullopt, "A")}); auto routeToAddr3 = createUnicastRoute( addr3, {createNextHopFromAdj(adj13, false, 10, std::nullopt, "B")}); // addr4 is only originated in area B auto routeToAddr4 = createUnicastRoute( addr4, {createNextHopFromAdj(adj12, false, 20, std::nullopt, "A"), createNextHopFromAdj(adj13, false, 20, std::nullopt, "B")}); EXPECT_THAT(*routeDb1.unicastRoutes_ref(), testing::SizeIs(3)); EXPECT_THAT( *routeDb1.unicastRoutes_ref(), testing::UnorderedElementsAre( routeToAddr2, routeToAddr3, routeToAddr4)); } // routeDb2 from node "2" will only see addr1 in area A { auto routeToAddr1 = createUnicastRoute( addr1, {createNextHopFromAdj(adj21, false, 10, std::nullopt, "A")}); EXPECT_THAT(*routeDb2.unicastRoutes_ref(), testing::SizeIs(1)); EXPECT_THAT( *routeDb2.unicastRoutes_ref(), testing::UnorderedElementsAre(routeToAddr1)); } // routeDb3 will only see addr4 in area B { auto routeToAddr4 = createUnicastRoute( addr4, {createNextHopFromAdj(adj34, false, 10, std::nullopt, "B")}); EXPECT_THAT(*routeDb3.unicastRoutes_ref(), testing::SizeIs(1)); EXPECT_THAT( *routeDb3.unicastRoutes_ref(), testing::UnorderedElementsAre(routeToAddr4)); } // routeDb4 { auto routeToAddr2 = createUnicastRoute( addr2, {createNextHopFromAdj(adj42, false, 10, std::nullopt, "A")}); auto routeToAddr3 = createUnicastRoute( addr3, {createNextHopFromAdj(adj43, false, 10, std::nullopt, "B")}); // addr1 is only originated in area A auto routeToAddr1 = createUnicastRoute( addr1, {createNextHopFromAdj(adj42, false, 20, std::nullopt, "A"), createNextHopFromAdj(adj43, false, 20, std::nullopt, "B")}); EXPECT_THAT(*routeDb4.unicastRoutes_ref(), testing::SizeIs(3)); EXPECT_THAT( *routeDb4.unicastRoutes_ref(), testing::UnorderedElementsAre( routeToAddr2, routeToAddr3, routeToAddr1)); } // // "1" originate addr1 into B // publication = createThriftPublication( {createPrefixKeyValue("1", 1, addr1, "B")}, {}, /* expiredKeys */ {}, /* nodeIds */ {}, /* keysToUpdate */ std::string(""), /*floodRootId */ "B"); sendKvPublication(publication); recvRouteUpdates(); routeDb3 = dumpRouteDb({"3"})["3"]; routeDb4 = dumpRouteDb({"4"})["4"]; // routeMap3 now should see addr1 in areaB { auto routeToAddr1 = createUnicastRoute( addr1, {createNextHopFromAdj(adj31, false, 10, std::nullopt, "B")}); EXPECT_THAT(*routeDb3.unicastRoutes_ref(), testing::Contains(routeToAddr1)); } // routeMap4 now could reach addr1 through areaA or areaB { auto routeToAddr1 = createUnicastRoute( addr1, {createNextHopFromAdj(adj43, false, 20, std::nullopt, "B"), createNextHopFromAdj(adj42, false, 20, std::nullopt, "A")}); EXPECT_THAT(*routeDb4.unicastRoutes_ref(), testing::Contains(routeToAddr1)); } } // MultiArea Tology topology is used: // 1--- A ---2 // | // B // | // 3 // // area A: adj12 // area B: adj13 TEST_F(DecisionTestFixture, SelfReditributePrefixPublication) { // // publish area A adj and prefix // "2" originate addr2 into A // auto originKeyStr = PrefixKey("2", toIPNetwork(addr2), "A").getPrefixKey(); auto originPfx = createPrefixEntry(addr2); originPfx.area_stack_ref() = {"65000"}; auto originPfxVal = createPrefixValue("2", 1, createPrefixDb("2", {originPfx}, "A")); auto publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12}, false, 1)}, {"adj:2", createAdjValue("2", 1, {adj21}, false, 2)}, {originKeyStr, originPfxVal}}, {}, /* expiredKeys */ {}, /* nodeIds */ {}, /* keysToUpdate */ std::string(""), /*floodRootId */ "A"); sendKvPublication(publication); recvRouteUpdates(); // // publish area B adj and prefix // publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj13}, false, 1)}, {"adj:3", createAdjValue("3", 1, {adj31}, false, 3)}}, {}, /* expiredKeys */ {}, /* nodeIds */ {}, /* keysToUpdate */ std::string(""), /*floodRootId */ "B"); sendKvPublication(publication); recvRouteUpdates(); // // "1" reditribute addr2 into B // - this should not cause prefix db update // - not route update // auto redistributeKeyStr = PrefixKey("1", toIPNetwork(addr2), "B").getPrefixKey(); auto redistributePfx = createPrefixEntry(addr2, thrift::PrefixType::RIB); redistributePfx.area_stack_ref() = {"65000", "A"}; auto redistributePfxVal = createPrefixValue("1", 1, createPrefixDb("1", {redistributePfx}, "B")); publication = createThriftPublication( {{redistributeKeyStr, redistributePfxVal}}, {}, /* expiredKeys */ {}, /* nodeIds */ {}, /* keysToUpdate */ std::string(""), /*floodRootId */ "B"); sendKvPublication(publication); // wait for publication to be processed /* sleep override */ std::this_thread::sleep_for( debounceTimeoutMax + std::chrono::milliseconds(100)); EXPECT_EQ(0, routeUpdatesQueueReader.size()); } /** * Exhaustively RibPolicy feature in Decision. The intention here is to * verify the functionality of RibPolicy in Decision module. RibPolicy * is also unit-tested for it's complete correctness and we don't aim * it here. * * Test covers * - Get policy without setting (exception case) * - Set policy * - Get policy after setting * - Verify that set-policy triggers the route database change (apply policy) * - Set the policy with 0 weight. See that route dis-appears * - Expire policy. Verify it triggers the route database change (undo policy) */ TEST_F(DecisionTestFixture, RibPolicy) { // Setup topology and prefixes. 1 unicast route will be computed auto publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12}, false, 1)}, {"adj:2", createAdjValue("2", 1, {adj21}, false, 2)}, createPrefixKeyValue("1", 1, addr1), createPrefixKeyValue("2", 1, addr2)}, {}, {}, {}, std::string("")); sendKvPublication(publication); // Expect route update. Verify next-hop weight to be 0 (ECMP) { auto updates = recvRouteUpdates(); ASSERT_EQ(1, updates.unicastRoutesToUpdate.size()); EXPECT_EQ( 0, *updates.unicastRoutesToUpdate.begin() ->second.nexthops.begin() ->weight_ref()); } // Get policy test. Expect failure EXPECT_THROW(decision->getRibPolicy().get(), thrift::OpenrError); // Create rib policy thrift::RibRouteActionWeight actionWeight; actionWeight.neighbor_to_weight_ref()->emplace("2", 2); thrift::RibPolicyStatement policyStatement; policyStatement.matcher_ref()->prefixes_ref() = std::vector<thrift::IpPrefix>({addr2}); policyStatement.action_ref()->set_weight_ref() = actionWeight; thrift::RibPolicy policy; policy.statements_ref()->emplace_back(policyStatement); policy.ttl_secs_ref() = 1; // Set rib policy EXPECT_NO_THROW(decision->setRibPolicy(policy).get()); // Get rib policy and verify { auto retrievedPolicy = decision->getRibPolicy().get(); EXPECT_EQ(*policy.statements_ref(), *retrievedPolicy.statements_ref()); EXPECT_GE(*policy.ttl_secs_ref(), *retrievedPolicy.ttl_secs_ref()); } // Expect the route database change with next-hop weight to be 2 { auto updates = recvRouteUpdates(); ASSERT_EQ(1, updates.unicastRoutesToUpdate.size()); EXPECT_EQ( 2, *updates.unicastRoutesToUpdate.begin() ->second.nexthops.begin() ->weight_ref()); } // Set the policy with empty weight. Expect route remains intact and error // counter is reported policy.statements_ref() ->at(0) .action_ref() ->set_weight_ref() ->neighbor_to_weight_ref()["2"] = 0; EXPECT_NO_THROW(decision->setRibPolicy(policy).get()); { auto updates = recvRouteUpdates(); EXPECT_EQ(1, updates.unicastRoutesToUpdate.size()); ASSERT_EQ(0, updates.unicastRoutesToDelete.size()); ASSERT_EQ(1, updates.unicastRoutesToUpdate.count(toIPNetwork(addr2))); for (auto& nh : updates.unicastRoutesToUpdate.at(toIPNetwork(addr2)).nexthops) { EXPECT_FALSE(nh.weight_ref().is_set()); } auto counters = fb303::fbData->getCounters(); EXPECT_EQ(1, counters.at("decision.rib_policy.invalidated_routes.count")); } // trigger addr2 recalc by flapping the advertisement publication = createThriftPublication( {createPrefixKeyValue( "2", 2, addr2, kTestingAreaName, true /* withdraw */)}, {}, {}, {}, std::string("")); sendKvPublication(publication); publication = createThriftPublication( {createPrefixKeyValue("2", 3, addr2)}, {}, {}, {}, std::string("")); sendKvPublication(publication); { auto updates = recvRouteUpdates(); ASSERT_EQ(1, updates.unicastRoutesToUpdate.size()); ASSERT_EQ(0, updates.unicastRoutesToDelete.size()); ASSERT_EQ(1, updates.unicastRoutesToUpdate.count(toIPNetwork(addr2))); for (auto& nh : updates.unicastRoutesToUpdate.at(toIPNetwork(addr2)).nexthops) { EXPECT_FALSE(nh.weight_ref().is_set()); } auto counters = fb303::fbData->getCounters(); EXPECT_EQ(2, counters.at("decision.rib_policy.invalidated_routes.count")); } // Let the policy expire. Wait for another route database change { auto updates = recvRouteUpdates(); ASSERT_EQ(0, updates.unicastRoutesToUpdate.size()); auto retrievedPolicy = decision->getRibPolicy().get(); EXPECT_GE(0, *retrievedPolicy.ttl_secs_ref()); } } /** * Verifies that error is set if RibPolicy is invalid */ TEST_F(DecisionTestFixture, RibPolicyError) { // Set empty rib policy auto sf = decision->setRibPolicy(thrift::RibPolicy{}); // Expect an error to be set immediately (validation happens inline) EXPECT_TRUE(sf.isReady()); EXPECT_TRUE(sf.hasException()); EXPECT_THROW(std::move(sf).get(), thrift::OpenrError); } /** * Verifies that a policy gets cleared */ TEST_F(DecisionTestFixture, RibPolicyClear) { // Setup topology and prefixes. 1 unicast route will be computed auto publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12}, false, 1)}, {"adj:2", createAdjValue("2", 1, {adj21}, false, 2)}, {"prefix:1", createPrefixValue("1", 1, {addr1})}, {"prefix:2", createPrefixValue("2", 1, {addr2})}}, {}, {}, {}, std::string("")); sendKvPublication(publication); // Expect route update. { auto updates = recvRouteUpdates(); ASSERT_EQ(1, updates.unicastRoutesToUpdate.size()); EXPECT_EQ( 0, *updates.unicastRoutesToUpdate.begin() ->second.nexthops.begin() ->weight_ref()); } // Get policy test. Expect failure EXPECT_THROW(decision->getRibPolicy().get(), thrift::OpenrError); // Create rib policy thrift::RibRouteActionWeight actionWeight; actionWeight.neighbor_to_weight_ref()->emplace("2", 2); actionWeight.neighbor_to_weight_ref()->emplace("1", 1); thrift::RibPolicyStatement policyStatement; policyStatement.matcher_ref()->prefixes_ref() = std::vector<thrift::IpPrefix>({addr2}); policyStatement.action_ref()->set_weight_ref() = actionWeight; thrift::RibPolicy policy; policy.statements_ref()->emplace_back(policyStatement); policy.ttl_secs_ref() = 1; // Set rib policy EXPECT_NO_THROW(decision->setRibPolicy(policy).get()); // Get rib policy and verify { auto retrievedPolicy = decision->getRibPolicy().get(); EXPECT_EQ(*policy.statements_ref(), *retrievedPolicy.statements_ref()); EXPECT_GE(*policy.ttl_secs_ref(), *retrievedPolicy.ttl_secs_ref()); } // Expect route update. Verify next-hop weight to be 2 (ECMP) auto updates = recvRouteUpdates(); ASSERT_EQ(1, updates.unicastRoutesToUpdate.size()); EXPECT_EQ( 2, *updates.unicastRoutesToUpdate.begin() ->second.nexthops.begin() ->weight_ref()); // Clear rib policy and expect nexthop weight change EXPECT_NO_THROW(decision->clearRibPolicy()); updates = recvRouteUpdates(); ASSERT_EQ(1, updates.unicastRoutesToUpdate.size()); EXPECT_EQ( 0, *updates.unicastRoutesToUpdate.begin() ->second.nexthops.begin() ->weight_ref()); // Verify that get rib policy throws no exception EXPECT_THROW(decision->getRibPolicy().get(), thrift::OpenrError); } /** * Verifies that set/get APIs throws exception if RibPolicy feature is not * enabled. */ TEST(Decision, RibPolicyFeatureKnob) { auto tConfig = getBasicOpenrConfig("1"); tConfig.enable_rib_policy_ref() = false; // Disable rib_policy feature auto config = std::make_shared<Config>(tConfig); ASSERT_FALSE(config->isRibPolicyEnabled()); messaging::ReplicateQueue<thrift::Publication> kvStoreUpdatesQueue; messaging::ReplicateQueue<DecisionRouteUpdate> staticRoutesUpdateQueue; messaging::ReplicateQueue<DecisionRouteUpdate> routeUpdatesQueue; auto decision = std::make_unique<Decision>( config, false, /* bgpDryRun */ debounceTimeoutMin, debounceTimeoutMax, kvStoreUpdatesQueue.getReader(), staticRoutesUpdateQueue.getReader(), routeUpdatesQueue); // SET { // Create valid rib policy thrift::RibRouteActionWeight actionWeight; actionWeight.neighbor_to_weight_ref()->emplace("2", 2); thrift::RibPolicyStatement policyStatement; policyStatement.matcher_ref()->prefixes_ref() = std::vector<thrift::IpPrefix>({addr2}); policyStatement.action_ref()->set_weight_ref() = actionWeight; thrift::RibPolicy policy; policy.statements_ref()->emplace_back(policyStatement); policy.ttl_secs_ref() = 1; auto sf = decision->setRibPolicy(policy); EXPECT_TRUE(sf.isReady()); EXPECT_TRUE(sf.hasException()); EXPECT_THROW(std::move(sf).get(), thrift::OpenrError); } // GET { auto sf = decision->getRibPolicy(); EXPECT_TRUE(sf.isReady()); EXPECT_TRUE(sf.hasException()); EXPECT_THROW(std::move(sf).get(), thrift::OpenrError); } kvStoreUpdatesQueue.close(); staticRoutesUpdateQueue.close(); routeUpdatesQueue.close(); } // The following topology is used: // // 100 // 1--- ---------- 2 // \_ _/ // \_ ____ _/ // 800 // We upload parallel link 1---2 with the initial sync and later bring down // the one with lower metric. We then verify updated route database is // received // TEST_F(DecisionTestFixture, ParallelLinks) { auto adj12_1 = createAdjacency("2", "1/2-1", "2/1-1", "fe80::2", "192.168.0.2", 100, 0); auto adj12_2 = createAdjacency("2", "1/2-2", "2/1-2", "fe80::2", "192.168.0.2", 800, 0); auto adj21_1 = createAdjacency("1", "2/1-1", "1/2-1", "fe80::1", "192.168.0.1", 100, 0); auto adj21_2 = createAdjacency("1", "2/1-2", "1/2-2", "fe80::1", "192.168.0.1", 800, 0); auto publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12_1, adj12_2})}, {"adj:2", createAdjValue("2", 1, {adj21_1, adj21_2})}, createPrefixKeyValue("1", 1, addr1), createPrefixKeyValue("2", 1, addr2)}, {}, {}, {}, std::string("")); auto routeDbBefore = dumpRouteDb({"1"})["1"]; sendKvPublication(publication); auto routeDbDelta = recvRouteUpdates(); EXPECT_EQ(1, routeDbDelta.unicastRoutesToUpdate.size()); auto routeDb = dumpRouteDb({"1"})["1"]; auto routeDelta = findDeltaRoutes(routeDb, routeDbBefore); EXPECT_TRUE(checkEqualRoutesDelta(routeDbDelta, routeDelta)); RouteMap routeMap; fillRouteMap("1", routeMap, routeDb); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops({createNextHopFromAdj(adj12_1, false, 100)})); publication = createThriftPublication( {{"adj:2", createAdjValue("2", 2, {adj21_2})}}, {}, {}, {}, std::string("")); routeDbBefore = dumpRouteDb({"1"})["1"]; sendKvPublication(publication); // receive my local Decision routeDb publication routeDbDelta = recvRouteUpdates(); EXPECT_EQ(1, routeDbDelta.unicastRoutesToUpdate.size()); routeDb = dumpRouteDb({"1"})["1"]; routeDelta = findDeltaRoutes(routeDb, routeDbBefore); EXPECT_TRUE(checkEqualRoutesDelta(routeDbDelta, routeDelta)); routeMap.clear(); fillRouteMap("1", routeMap, routeDb); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops({createNextHopFromAdj(adj12_2, false, 800)})); // restore the original state publication = createThriftPublication( {{"adj:2", createAdjValue("2", 2, {adj21_1, adj21_2})}}, {}, {}, {}, std::string("")); routeDbBefore = dumpRouteDb({"1"})["1"]; sendKvPublication(publication); // receive my local Decision routeDb publication routeDbDelta = recvRouteUpdates(); EXPECT_EQ(1, routeDbDelta.unicastRoutesToUpdate.size()); routeDb = dumpRouteDb({"1"})["1"]; routeDelta = findDeltaRoutes(routeDb, routeDbBefore); EXPECT_TRUE(checkEqualRoutesDelta(routeDbDelta, routeDelta)); routeMap.clear(); fillRouteMap("1", routeMap, routeDb); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops({createNextHopFromAdj(adj12_1, false, 100)})); // overload the least cost link auto adj21_1_overloaded = adj21_1; adj21_1_overloaded.isOverloaded_ref() = true; publication = createThriftPublication( {{"adj:2", createAdjValue("2", 2, {adj21_1_overloaded, adj21_2})}}, {}, {}, {}, std::string("")); routeDbBefore = dumpRouteDb({"1"})["1"]; sendKvPublication(publication); // receive my local Decision routeDb publication routeDbDelta = recvRouteUpdates(); EXPECT_EQ(1, routeDbDelta.unicastRoutesToUpdate.size()); routeDb = dumpRouteDb({"1"})["1"]; routeDelta = findDeltaRoutes(routeDb, routeDbBefore); EXPECT_TRUE(checkEqualRoutesDelta(routeDbDelta, routeDelta)); routeMap.clear(); fillRouteMap("1", routeMap, routeDb); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops({createNextHopFromAdj(adj12_2, false, 800)})); } // The following topology is used: // // 1---2---3---4 // // We upload the link 1---2 with the initial sync and later publish // the 2---3 & 3---4 link information. We expect it to trigger SPF only once. // TEST_F(DecisionTestFixture, PubDebouncing) { // // publish the link state info to KvStore // auto publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12})}, {"adj:2", createAdjValue("2", 1, {adj21})}, createPrefixKeyValue("1", 1, addr1), createPrefixKeyValue("2", 1, addr2)}, {}, {}, {}, std::string("")); auto counters = fb303::fbData->getCounters(); EXPECT_EQ(0, counters["decision.spf_runs.count"]); EXPECT_EQ(0, counters["decision.route_build_runs.count"]); sendKvPublication(publication); recvRouteUpdates(); // validate SPF after initial sync, no rebouncing here counters = fb303::fbData->getCounters(); EXPECT_EQ(1, counters["decision.spf_runs.count"]); EXPECT_EQ(1, counters["decision.route_build_runs.count"]); // // publish the link state info to KvStore via the KvStore pub socket // we simulate adding a new router R3 // // Some tricks here; we need to bump the time-stamp on router 2's data, so // it can override existing; for router 3 we publish new key-value publication = createThriftPublication( {{"adj:3", createAdjValue("3", 1, {adj32})}, {"adj:2", createAdjValue("2", 3, {adj21, adj23})}, createPrefixKeyValue("3", 1, addr3)}, {}, {}, {}, std::string("")); sendKvPublication(publication); // we simulate adding a new router R4 // Some tricks here; we need to bump the time-stamp on router 3's data, so // it can override existing; publication = createThriftPublication( {{"adj:4", createAdjValue("4", 1, {adj43})}, {"adj:3", createAdjValue("3", 5, {adj32, adj34})}}, {}, {}, {}, std::string("")); sendKvPublication(publication); recvRouteUpdates(); counters = fb303::fbData->getCounters(); EXPECT_EQ(2, counters["decision.spf_runs.count"]); EXPECT_EQ(2, counters["decision.route_build_runs.count"]); // // Only publish prefix updates // auto getRouteForPrefixCount = counters.at("decision.get_route_for_prefix.count"); publication = createThriftPublication( {createPrefixKeyValue("4", 1, addr4)}, {}, {}, {}, std::string("")); sendKvPublication(publication); recvRouteUpdates(); counters = fb303::fbData->getCounters(); EXPECT_EQ(2, counters["decision.spf_runs.count"]); // only prefix changed no full rebuild needed EXPECT_EQ(2, counters["decision.route_build_runs.count"]); EXPECT_EQ( getRouteForPrefixCount + 1, counters["decision.get_route_for_prefix.count"]); // // publish adj updates right after prefix updates // Decision is supposed to only trigger spf recalculation // Some tricks here; we need to bump the time-stamp on router 4's data, so // it can override existing; publication = createThriftPublication( {createPrefixKeyValue("4", 2, addr4), createPrefixKeyValue("4", 2, addr5)}, {}, {}, {}, std::string("")); sendKvPublication(publication); publication = createThriftPublication( {{"adj:2", createAdjValue("2", 5, {adj21})}}, {}, {}, {}, std::string("")); sendKvPublication(publication); recvRouteUpdates(); counters = fb303::fbData->getCounters(); EXPECT_EQ(3, counters["decision.spf_runs.count"]); EXPECT_EQ(3, counters["decision.route_build_runs.count"]); // // publish multiple prefix updates in a row // Decision is supposed to process prefix update only once // Some tricks here; we need to bump the version on router 4's data, so // it can override existing; getRouteForPrefixCount = counters.at("decision.get_route_for_prefix.count"); publication = createThriftPublication( {createPrefixKeyValue("4", 5, addr4)}, {}, {}, {}, std::string("")); sendKvPublication(publication); publication = createThriftPublication( {createPrefixKeyValue("4", 7, addr4), createPrefixKeyValue("4", 7, addr6)}, {}, {}, {}, std::string("")); sendKvPublication(publication); publication = createThriftPublication( {createPrefixKeyValue("4", 8, addr4), createPrefixKeyValue("4", 8, addr5), createPrefixKeyValue("4", 8, addr6)}, {}, {}, {}, std::string("")); sendKvPublication(publication); recvRouteUpdates(); counters = fb303::fbData->getCounters(); // only prefix has changed so spf_runs is unchanged EXPECT_EQ(3, counters["decision.spf_runs.count"]); // addr6 is seen to have been advertised in this interval EXPECT_EQ( getRouteForPrefixCount + 1, counters["decision.get_route_for_prefix.count"]); } // // Send unrelated key-value pairs to Decision // Make sure they do not trigger SPF runs, but rather ignored // TEST_F(DecisionTestFixture, NoSpfOnIrrelevantPublication) { // // publish the link state info to KvStore, but use different markers // those must be ignored by the decision module // auto publication = createThriftPublication( {{"adj2:1", createAdjValue("1", 1, {adj12})}, {"adji2:2", createAdjValue("2", 1, {adj21})}, createPrefixKeyValue("1", 1, addr1), createPrefixKeyValue("2", 1, addr2)}, {}, {}, {}, std::string("")); auto counters = fb303::fbData->getCounters(); EXPECT_EQ(0, counters["decision.spf_runs.count"]); sendKvPublication(publication); // wait for SPF to finish /* sleep override */ std::this_thread::sleep_for(3 * debounceTimeoutMax); // make sure the counter did not increment counters = fb303::fbData->getCounters(); EXPECT_EQ(0, counters["decision.spf_runs.count"]); } // // Send duplicate key-value pairs to Decision // Make sure subsquent duplicates are ignored. // TEST_F(DecisionTestFixture, NoSpfOnDuplicatePublication) { // // publish initial link state info to KvStore, This should trigger the // SPF run. // auto const publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12})}, {"adj:2", createAdjValue("2", 1, {adj21})}, createPrefixKeyValue("1", 1, addr1), createPrefixKeyValue("2", 1, addr2)}, {}, {}, {}, std::string("")); auto counters = fb303::fbData->getCounters(); EXPECT_EQ(0, counters["decision.spf_runs.count"]); sendKvPublication(publication); // wait for SPF to finish /* sleep override */ std::this_thread::sleep_for(3 * debounceTimeoutMax); // make sure counter is incremented counters = fb303::fbData->getCounters(); EXPECT_EQ(1, counters["decision.spf_runs.count"]); // Send same publication again to Decision using pub socket sendKvPublication(publication); // wait for SPF to finish /* sleep override */ std::this_thread::sleep_for(3 * debounceTimeoutMax); // make sure counter is not incremented counters = fb303::fbData->getCounters(); EXPECT_EQ(1, counters["decision.spf_runs.count"]); } /** * Test to verify route calculation when a prefix is advertised from more than * one node. * * * node4(p4) * | * 5 | * | 10 * node1(p1) --------- node2(p2) * | * | 10 * | * node3(p2) */ TEST_F(DecisionTestFixture, DuplicatePrefixes) { // Note: local copy overwriting global ones, to be changed in this test auto adj14 = createAdjacency("4", "1/4", "4/1", "fe80::4", "192.168.0.4", 5, 0); auto adj41 = createAdjacency("1", "4/1", "1/4", "fe80::1", "192.168.0.1", 5, 0); auto adj12 = createAdjacency("2", "1/2", "2/1", "fe80::2", "192.168.0.2", 10, 0); auto adj21 = createAdjacency("1", "2/1", "1/2", "fe80::1", "192.168.0.1", 10, 0); // // publish initial link state info to KvStore, This should trigger the // SPF run. // auto publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj14, adj12, adj13})}, {"adj:2", createAdjValue("2", 1, {adj21})}, {"adj:3", createAdjValue("3", 1, {adj31})}, {"adj:4", createAdjValue("4", 1, {adj41})}, createPrefixKeyValue("1", 1, addr1), createPrefixKeyValue("2", 1, addr2), // node3 has same address w/ node2 createPrefixKeyValue("3", 1, addr2), createPrefixKeyValue("4", 1, addr4)}, {}, {}, {}, std::string("")); sendKvPublication(publication); recvRouteUpdates(); // Expect best route selection to be populated in route-details for addr2 { thrift::ReceivedRouteFilter filter; filter.prefixes_ref() = std::vector<thrift::IpPrefix>({addr2}); auto routes = decision->getReceivedRoutesFiltered(filter).get(); ASSERT_EQ(1, routes->size()); auto const& routeDetails = routes->at(0); EXPECT_EQ(2, routeDetails.bestKeys_ref()->size()); EXPECT_EQ("2", routeDetails.bestKey_ref()->node_ref().value()); } // Query new information // validate routers auto routeMapList = dumpRouteDb({"1", "2", "3", "4"}); EXPECT_EQ(4, routeMapList.size()); // 1 route per neighbor RouteMap routeMap; for (auto& [key, value] : routeMapList) { fillRouteMap(key, routeMap, value); } // 1 EXPECT_EQ(2, routeMapList["1"].unicastRoutes_ref()->size()); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops( {createNextHopFromAdj(adj12, false, 10), createNextHopFromAdj(adj13, false, 10)})); // 2 EXPECT_EQ(2, routeMapList["2"].unicastRoutes_ref()->size()); EXPECT_EQ( routeMap[make_pair("2", toString(addr1))], NextHops({createNextHopFromAdj(adj21, false, 10)})); // 3 EXPECT_EQ(2, routeMapList["3"].unicastRoutes_ref()->size()); EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops({createNextHopFromAdj(adj31, false, 10)})); // 4 EXPECT_EQ(2, routeMapList["4"].unicastRoutes_ref()->size()); EXPECT_EQ( routeMap[make_pair("4", toString(addr2))], NextHops({createNextHopFromAdj(adj41, false, 15)})); /** * Overload node-2 and node-4. Now we on node-1 will only route p2 toward * node-3 but will still have route p4 toward node-4 since it's unicast * * node4(p4) * | * 5 | * | 10 (overloaded) * node1(p1) --------- node2(p2) * | * | 10 * | * node3(p2) */ publication = createThriftPublication( {{"adj:2", createAdjValue("2", 1, {adj21}, true /* overloaded */)}, {"adj:4", createAdjValue("4", 1, {adj41}, true /* overloaded */)}}, {}, {}, {}, std::string("")); // Send same publication again to Decision using pub socket sendKvPublication(publication); recvRouteUpdates(); routeMapList = dumpRouteDb({"1"}); RouteMap routeMap2; for (auto& [key, value] : routeMapList) { fillRouteMap(key, routeMap2, value); } EXPECT_EQ( routeMap2[make_pair("1", toString(addr2))], NextHops({createNextHopFromAdj(adj13, false, 10)})); EXPECT_EQ( routeMap2[make_pair("1", toString(addr4))], NextHops({createNextHopFromAdj(adj14, false, 5)})); /** * Increase the distance between node-1 and node-2 to 100. Now we on node-1 * will reflect weights into nexthops and FIB will not do multipath * * node4(p4) * | * 5 | * | 100 * node1(p1) --------- node2(p2) * | * | 10 * | * node3(p2) */ adj12.metric_ref() = 100; adj21.metric_ref() = 100; publication = createThriftPublication( {{"adj:1", createAdjValue("1", 2, {adj12, adj13, adj14})}, {"adj:2", createAdjValue("2", 2, {adj21, adj23})}}, {}, {}, {}, std::string("")); // Send same publication again to Decision using pub socket sendKvPublication(publication); recvRouteUpdates(); // Query new information // validate routers routeMapList = dumpRouteDb({"1", "2", "3", "4"}); EXPECT_EQ(4, routeMapList.size()); // 1 route per neighbor routeMap.clear(); for (auto& [key, value] : routeMapList) { fillRouteMap(key, routeMap, value); } // 1 EXPECT_EQ(2, routeMapList["1"].unicastRoutes_ref()->size()); EXPECT_EQ( routeMap[make_pair("1", toString(addr2))], NextHops({createNextHopFromAdj(adj13, false, 10)})); // 2 EXPECT_EQ(2, routeMapList["2"].unicastRoutes_ref()->size()); EXPECT_EQ( routeMap[make_pair("2", toString(addr1))], NextHops({createNextHopFromAdj(adj21, false, 100)})); // 3 EXPECT_EQ(2, routeMapList["3"].unicastRoutes_ref()->size()); EXPECT_EQ( routeMap[make_pair("3", toString(addr1))], NextHops({createNextHopFromAdj(adj31, false, 10)})); // 4 EXPECT_EQ(2, routeMapList["4"].unicastRoutes_ref()->size()); EXPECT_EQ( routeMap[make_pair("4", toString(addr2))], NextHops({createNextHopFromAdj(adj41, false, 15)})); } /** * Tests reliability of Decision SUB socket. We overload SUB socket with lot * of messages and make sure none of them are lost. We make decision compute * routes for a large network topology taking good amount of CPU time. We * do not try to validate routes here instead we validate messages processed * by decision and message sent by us. * * Topology consists of 1000 nodes linear where node-i connects to 3 nodes * before it and 3 nodes after it. * */ TEST_F(DecisionTestFixture, DecisionSubReliability) { thrift::Publication initialPub; initialPub.area_ref() = kTestingAreaName; // wait for the inital coldstart sync, expect it to be empty EXPECT_EQ(0, recvRouteUpdates().unicastRoutesToUpdate.size()); std::string keyToDup; // Create full topology for (int i = 1; i <= 1000; i++) { const std::string src = folly::to<std::string>(i); // Create prefixDb value const auto addr = toIpPrefix(folly::sformat("face:cafe:babe::{}/128", i)); auto kv = createPrefixKeyValue(src, 1, addr); if (1 == i) { // arbitrarily choose the first key to send duplicate publications for keyToDup = kv.first; } initialPub.keyVals_ref()->emplace(kv); // Create adjDb value vector<thrift::Adjacency> adjs; for (int j = std::max(1, i - 3); j <= std::min(1000, i + 3); j++) { if (i == j) continue; const std::string dst = folly::to<std::string>(j); auto adj = createAdjacency( dst, folly::sformat("{}/{}", src, dst), folly::sformat("{}/{}", dst, src), folly::sformat("fe80::{}", dst), "192.168.0.1" /* unused */, 10 /* metric */, 0 /* adj label */); adjs.emplace_back(std::move(adj)); } initialPub.keyVals_ref()->emplace( folly::sformat("adj:{}", src), createAdjValue(src, 1, adjs)); } // // publish initial link state info to KvStore, This should trigger the // SPF run. // sendKvPublication(initialPub); // // Hammer Decision with lot of duplicate publication for 2 * ThrottleTimeout // We want to ensure that we hammer Decision for atleast once during it's // SPF run. This will cause lot of pending publications on Decision. This // is not going to cause any SPF computation // thrift::Publication duplicatePub; duplicatePub.area_ref() = kTestingAreaName; duplicatePub.keyVals_ref()[keyToDup] = initialPub.keyVals_ref()->at(keyToDup); int64_t totalSent = 0; auto start = std::chrono::steady_clock::now(); while (true) { auto diff = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - start); if (diff > (2 * debounceTimeoutMax)) { LOG(INFO) << "Hammered decision with " << totalSent << " updates. Stopping"; break; } ++totalSent; sendKvPublication(duplicatePub); } // Receive RouteUpdate from Decision auto routeUpdates1 = recvRouteUpdates(); EXPECT_EQ(999, routeUpdates1.unicastRoutesToUpdate.size()); // Route to all // nodes except // mine // // Advertise prefix update. Decision gonna take some // good amount of time to process this last update (as it has many queued // updates). // thrift::Publication newPub; newPub.area_ref() = kTestingAreaName; auto newAddr = toIpPrefix("face:b00c:babe::1/128"); newPub.keyVals_ref() = {createPrefixKeyValue("1", 1, newAddr)}; LOG(INFO) << "Advertising prefix update"; sendKvPublication(newPub); // Receive RouteDelta from Decision auto routeUpdates2 = recvRouteUpdates(); // Expect no routes delta EXPECT_EQ(0, routeUpdates2.unicastRoutesToUpdate.size()); // // Verify counters information // const int64_t adjUpdateCnt = 1000 /* initial */; const int64_t prefixUpdateCnt = totalSent + 1000 /* initial */ + 1 /* end */; auto counters = fb303::fbData->getCounters(); EXPECT_EQ(1, counters["decision.spf_runs.count"]); EXPECT_EQ(adjUpdateCnt, counters["decision.adj_db_update.count"]); EXPECT_EQ(prefixUpdateCnt, counters["decision.prefix_db_update.count"]); } // // This test aims to verify counter reporting from Decision module // TEST_F(DecisionTestFixture, Counters) { // Verifiy some initial/default counters { decision->updateGlobalCounters(); const auto counters = fb303::fbData->getCounters(); EXPECT_EQ(counters.at("decision.num_nodes"), 1); EXPECT_EQ(counters.at("decision.num_conflicting_prefixes"), 0); } // set up first publication // Node1 and Node2 has both v4/v6 loopbacks, Node3 has only V6 auto mplsPrefixEntry1 = createPrefixEntry( // Incompatible forwarding type toIpPrefix("10.1.0.0/16"), thrift::PrefixType::LOOPBACK, "", thrift::PrefixForwardingType::IP, thrift::PrefixForwardingAlgorithm::KSP2_ED_ECMP); auto bgpPrefixEntry1 = createPrefixEntry( // Missing loopback toIpPrefix("10.2.0.0/16"), thrift::PrefixType::BGP, "data=10.2.0.0/16", thrift::PrefixForwardingType::IP, thrift::PrefixForwardingAlgorithm::SP_ECMP, thrift::MetricVector{} /* empty metric vector */); auto bgpPrefixEntry2 = createPrefixEntry( // Missing metric vector toIpPrefix("10.3.0.0/16"), thrift::PrefixType::BGP, "data=10.3.0.0/16", thrift::PrefixForwardingType::IP, thrift::PrefixForwardingAlgorithm::SP_ECMP, std::nullopt /* missing metric vector */); auto bgpPrefixEntry3 = createPrefixEntry( // Conflicting forwarding type toIpPrefix("10.3.0.0/16"), thrift::PrefixType::BGP, "data=10.3.0.0/16", thrift::PrefixForwardingType::SR_MPLS, thrift::PrefixForwardingAlgorithm::SP_ECMP, thrift::MetricVector{} /* empty metric vector */); std::unordered_map<std::string, thrift::Value> pubKvs = { {"adj:1", createAdjValue("1", 1, {adj12, adj13}, false, 1)}, {"adj:2", createAdjValue("2", 1, {adj21, adj23}, false, 2)}, {"adj:3", createAdjValue("3", 1, {adj31}, false, 3 << 20)}, // invalid // mpls // label {"adj:4", createAdjValue("4", 1, {}, false, 4)} // Disconnected node }; pubKvs.emplace(createPrefixKeyValue("1", 1, addr1)); pubKvs.emplace(createPrefixKeyValue("1", 1, addr1V4)); pubKvs.emplace(createPrefixKeyValue("2", 1, addr2)); pubKvs.emplace(createPrefixKeyValue("2", 1, addr2V4)); pubKvs.emplace(createPrefixKeyValue("3", 1, addr3)); pubKvs.emplace(createPrefixKeyValue("3", 1, bgpPrefixEntry1)); pubKvs.emplace(createPrefixKeyValue("3", 1, bgpPrefixEntry3)); pubKvs.emplace(createPrefixKeyValue("3", 1, mplsPrefixEntry1)); pubKvs.emplace(createPrefixKeyValue("4", 1, addr4)); pubKvs.emplace(createPrefixKeyValue("4", 1, bgpPrefixEntry2)); // Node1 connects to 2/3, Node2 connects to 1, Node3 connects to 1 // Node2 has partial adjacency auto publication0 = createThriftPublication(pubKvs, {}, {}, {}, std::string("")); sendKvPublication(publication0); const auto routeDb = recvRouteUpdates(); for (const auto& [_, uniRoute] : routeDb.unicastRoutesToUpdate) { EXPECT_NE( folly::IPAddress::networkToString(uniRoute.prefix), "10.1.0.0/16"); } // Verify counters decision->updateGlobalCounters(); const auto counters = fb303::fbData->getCounters(); EXPECT_EQ(counters.at("decision.num_conflicting_prefixes"), 1); EXPECT_EQ(counters.at("decision.num_partial_adjacencies"), 1); EXPECT_EQ(counters.at("decision.num_complete_adjacencies"), 2); EXPECT_EQ(counters.at("decision.num_nodes"), 4); EXPECT_EQ(counters.at("decision.num_prefixes"), 9); EXPECT_EQ(counters.at("decision.no_route_to_prefix.count.60"), 1); EXPECT_EQ(counters.at("decision.incompatible_forwarding_type.count.60"), 1); EXPECT_EQ(counters.at("decision.skipped_unicast_route.count.60"), 0); EXPECT_EQ(counters.at("decision.skipped_mpls_route.count.60"), 1); EXPECT_EQ(counters.at("decision.no_route_to_label.count.60"), 1); // fully disconnect node 2 auto publication1 = createThriftPublication( {{"adj:1", createAdjValue("1", 2, {adj13}, false, 1)}}, {}, {}, {}, std::string("")); sendKvPublication(publication1); // wait for update recvRouteUpdates(); decision->updateGlobalCounters(); EXPECT_EQ( fb303::fbData->getCounters().at("decision.num_partial_adjacencies"), 0); } TEST_F(DecisionTestFixture, ExceedMaxBackoff) { for (int i = debounceTimeoutMin.count(); true; i *= 2) { auto nodeName = std::to_string(i); auto publication = createThriftPublication( {createPrefixKeyValue(nodeName, 1, addr1)}, {}, {}, {}, std::string("")); sendKvPublication(publication); if (i >= debounceTimeoutMax.count()) { break; } } // wait for debouncer to try to fire /* sleep override */ std::this_thread::sleep_for( debounceTimeoutMax + std::chrono::milliseconds(100)); // send one more update auto publication = createThriftPublication( {createPrefixKeyValue("2", 1, addr1)}, {}, {}, {}, std::string("")); sendKvPublication(publication); } // DecisionTestFixture with different enableBestRouteSelection_ input class EnableBestRouteSelectionFixture : public DecisionTestFixture, public ::testing::WithParamInterface<bool> { openr::thrift::OpenrConfig createConfig() override { auto tConfig = DecisionTestFixture::createConfig(); tConfig.enable_best_route_selection_ref() = GetParam(); return tConfig; } }; INSTANTIATE_TEST_CASE_P( EnableBestRouteSelectionInstance, EnableBestRouteSelectionFixture, ::testing::Bool()); // // Mixed type prefix announcements (e.g. prefix1 with type BGP and type RIB ) // are allowed when enableBestRouteSelection_ = true, // Otherwise prefix will be skipped in route programming. // TEST_P(EnableBestRouteSelectionFixture, PrefixWithMixedTypeRoutes) { // Verifiy some initial/default counters { decision->updateGlobalCounters(); const auto counters = fb303::fbData->getCounters(); EXPECT_EQ(counters.at("decision.num_nodes"), 1); } // set up first publication // node 2/3 announce loopbacks { const auto prefixDb2 = createPrefixDb( "2", {createPrefixEntry(addr2), createPrefixEntry(addr2V4)}); const auto prefixDb3 = createPrefixDb( "3", {createPrefixEntry(addr3), createPrefixEntry(addr3V4)}); // Node1 connects to 2/3, Node2 connects to 1, Node3 connects to 1 auto publication = createThriftPublication( {{"adj:1", createAdjValue("1", 1, {adj12, adj13}, false, 1)}, {"adj:2", createAdjValue("2", 1, {adj21}, false, 2)}, {"adj:3", createAdjValue("3", 1, {adj31}, false, 3)}, createPrefixKeyValue("2", 1, addr2), createPrefixKeyValue("2", 1, addr2V4), createPrefixKeyValue("3", 1, addr3), createPrefixKeyValue("3", 1, addr3V4)}, {}, {}, {}, std::string("")); sendKvPublication(publication); recvRouteUpdates(); } // Node2 annouce prefix in BGP type, // Node3 announce prefix in Rib type { auto bgpPrefixEntry = createPrefixEntry( toIpPrefix("10.1.0.0/16"), thrift::PrefixType::BGP, "data=10.1.0.0/16", thrift::PrefixForwardingType::IP, thrift::PrefixForwardingAlgorithm::SP_ECMP, thrift::MetricVector{} /* empty metric vector */); auto ribPrefixEntry = createPrefixEntry( toIpPrefix("10.1.0.0/16"), thrift::PrefixType::RIB, "", thrift::PrefixForwardingType::IP, thrift::PrefixForwardingAlgorithm::SP_ECMP); auto publication = createThriftPublication( // node 2 announce BGP prefix with loopback {createPrefixKeyValue("2", 1, bgpPrefixEntry), createPrefixKeyValue("3", 1, ribPrefixEntry)}, {}, {}, {}, std::string("")); sendKvPublication(publication); recvRouteUpdates(); } // Verify counters decision->updateGlobalCounters(); const auto counters = fb303::fbData->getCounters(); int skippedUnicastRouteCnt = GetParam() ? 0 : 1; EXPECT_EQ( skippedUnicastRouteCnt, counters.at("decision.skipped_unicast_route.count.60")); } TEST(DecisionPendingUpdates, needsFullRebuild) { openr::detail::DecisionPendingUpdates updates("node1"); LinkState::LinkStateChange linkStateChange; linkStateChange.linkAttributesChanged = true; updates.applyLinkStateChange("node2", linkStateChange, kEmptyPerfEventRef); EXPECT_FALSE(updates.needsRouteUpdate()); EXPECT_FALSE(updates.needsFullRebuild()); updates.applyLinkStateChange("node1", linkStateChange, kEmptyPerfEventRef); EXPECT_TRUE(updates.needsRouteUpdate()); EXPECT_TRUE(updates.needsFullRebuild()); updates.reset(); EXPECT_FALSE(updates.needsRouteUpdate()); EXPECT_FALSE(updates.needsFullRebuild()); linkStateChange.linkAttributesChanged = false; linkStateChange.topologyChanged = true; updates.applyLinkStateChange("node2", linkStateChange, kEmptyPerfEventRef); EXPECT_TRUE(updates.needsRouteUpdate()); EXPECT_TRUE(updates.needsFullRebuild()); updates.reset(); linkStateChange.topologyChanged = false; linkStateChange.nodeLabelChanged = true; updates.applyLinkStateChange("node2", linkStateChange, kEmptyPerfEventRef); EXPECT_TRUE(updates.needsRouteUpdate()); EXPECT_TRUE(updates.needsFullRebuild()); } TEST(DecisionPendingUpdates, updatedPrefixes) { openr::detail::DecisionPendingUpdates updates("node1"); EXPECT_FALSE(updates.needsRouteUpdate()); EXPECT_FALSE(updates.needsFullRebuild()); EXPECT_TRUE(updates.updatedPrefixes().empty()); // empty update no change updates.applyPrefixStateChange({}, kEmptyPerfEventRef); EXPECT_FALSE(updates.needsRouteUpdate()); EXPECT_FALSE(updates.needsFullRebuild()); EXPECT_TRUE(updates.updatedPrefixes().empty()); updates.applyPrefixStateChange( {addr1Cidr, toIPNetwork(addr2V4)}, kEmptyPerfEventRef); EXPECT_TRUE(updates.needsRouteUpdate()); EXPECT_FALSE(updates.needsFullRebuild()); EXPECT_THAT( updates.updatedPrefixes(), testing::UnorderedElementsAre(addr1Cidr, addr2V4Cidr)); updates.applyPrefixStateChange({addr2Cidr}, kEmptyPerfEventRef); EXPECT_TRUE(updates.needsRouteUpdate()); EXPECT_FALSE(updates.needsFullRebuild()); EXPECT_THAT( updates.updatedPrefixes(), testing::UnorderedElementsAre(addr1Cidr, addr2V4Cidr, addr2Cidr)); updates.reset(); EXPECT_FALSE(updates.needsRouteUpdate()); EXPECT_FALSE(updates.needsFullRebuild()); EXPECT_TRUE(updates.updatedPrefixes().empty()); } TEST(DecisionPendingUpdates, perfEvents) { openr::detail::DecisionPendingUpdates updates("node1"); LinkState::LinkStateChange linkStateChange; updates.applyLinkStateChange("node2", linkStateChange, kEmptyPerfEventRef); EXPECT_THAT(*updates.perfEvents()->events_ref(), testing::SizeIs(1)); EXPECT_EQ( *updates.perfEvents()->events_ref()->front().eventDescr_ref(), "DECISION_RECEIVED"); thrift::PrefixDatabase perfEventDb; perfEventDb.perfEvents_ref() = openr::thrift::PerfEvents(); auto& earlierEvents = *perfEventDb.perfEvents_ref(); earlierEvents.events_ref()->push_back({}); *earlierEvents.events_ref()->back().nodeName_ref() = "node3"; *earlierEvents.events_ref()->back().eventDescr_ref() = "EARLIER"; earlierEvents.events_ref()->back().unixTs_ref() = 1; updates.applyPrefixStateChange({}, perfEventDb.perfEvents_ref()); // expect what we hasd to be displaced by this EXPECT_THAT(*updates.perfEvents()->events_ref(), testing::SizeIs(2)); EXPECT_EQ( *updates.perfEvents()->events_ref()->front().eventDescr_ref(), "EARLIER"); EXPECT_EQ( *updates.perfEvents()->events_ref()->back().eventDescr_ref(), "DECISION_RECEIVED"); } int main(int argc, char* argv[]) { // Parse command line flags testing::InitGoogleTest(&argc, argv); gflags::ParseCommandLineFlags(&argc, &argv, true); folly::init(&argc, &argv); google::InstallFailureSignalHandler(); // Run the tests return RUN_ALL_TESTS(); }
36.618888
80
0.670727
[ "object", "vector" ]
8b32f7a5ff0308114ca7bae6e372bda23348b30e
5,911
cc
C++
iree/base/atomic_slist_test.cc
metagraph-dev/iree
3d6acd1c47072fdf4cfab842807f70b1c2d34396
[ "Apache-2.0" ]
null
null
null
iree/base/atomic_slist_test.cc
metagraph-dev/iree
3d6acd1c47072fdf4cfab842807f70b1c2d34396
[ "Apache-2.0" ]
null
null
null
iree/base/atomic_slist_test.cc
metagraph-dev/iree
3d6acd1c47072fdf4cfab842807f70b1c2d34396
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iree/base/atomic_slist.h" #include "iree/testing/gtest.h" namespace { struct dummy_entry_t { // NOTE: we purposefully offset the entry pointer size_t value = 0; iree_atomic_slist_intrusive_ptr_t slist_next = NULL; }; IREE_TYPED_ATOMIC_SLIST_WRAPPER(dummy, dummy_entry_t, offsetof(dummy_entry_t, slist_next)); std::vector<dummy_entry_t> MakeDummySListItems(size_t base_index, size_t count) { std::vector<dummy_entry_t> items(count); for (size_t i = 0; i < count; ++i) { items[i].value = base_index + i; } return items; } TEST(AtomicSList, Lifetime) { iree_atomic_slist_t list; // NOTE: intentionally uninitialized. iree_atomic_slist_initialize(&list); iree_atomic_slist_deinitialize(&list); } TEST(AtomicSList, BasicUsage) { dummy_slist_t list; dummy_slist_initialize(&list); // List starts empty. EXPECT_EQ(NULL, dummy_slist_pop(&list)); // Push some items into the list (LIFO order). // New contents: 5 4 3 2 1 0 auto item_storage = MakeDummySListItems(0, 6); for (size_t i = 0; i < item_storage.size(); ++i) { dummy_slist_push(&list, &item_storage[i]); } // Now pop them out - they should be in reverse order. // New contents: e for (size_t i = 0; i < item_storage.size(); ++i) { dummy_entry_t* p = dummy_slist_pop(&list); ASSERT_TRUE(p); EXPECT_EQ(item_storage.size() - i - 1, p->value); } // List ends empty. EXPECT_EQ(NULL, dummy_slist_pop(&list)); dummy_slist_deinitialize(&list); } TEST(AtomicSList, Concat) { dummy_slist_t list; dummy_slist_initialize(&list); // Push some initial items into the list (LIFO order). // New contents: 1 0 auto initial_item_storage = MakeDummySListItems(0, 2); for (size_t i = 0; i < initial_item_storage.size(); ++i) { dummy_slist_push(&list, &initial_item_storage[i]); } // Stitch items together modeling what a user may do when building the list // themselves. // Items: 2 3 4 auto span_item_storage = MakeDummySListItems(2, 3); for (size_t i = 0; i < span_item_storage.size() - 1; ++i) { dummy_slist_set_next(&span_item_storage[i], &span_item_storage[i + 1]); } // Push all of the items to the list at once. // New contents: 2 3 4 1 0 dummy_slist_concat(&list, &span_item_storage.front(), &span_item_storage.back()); // Pop the span items and verify they are in the correct order: we effectively // pushed them such that popping is FIFO (2->4). // New contents: 1 0 for (size_t i = 0; i < span_item_storage.size(); ++i) { dummy_entry_t* p = dummy_slist_pop(&list); ASSERT_TRUE(p); EXPECT_EQ(/*base_index=*/2 + i, p->value); } // Pop the initial items and ensure they survived. // New contents: e for (size_t i = 0; i < initial_item_storage.size(); ++i) { dummy_entry_t* p = dummy_slist_pop(&list); ASSERT_TRUE(p); EXPECT_EQ(initial_item_storage.size() - i - 1, p->value); } dummy_slist_deinitialize(&list); } TEST(AtomicSList, FlushLIFO) { dummy_slist_t list; dummy_slist_initialize(&list); // Flushing when empty is ok. dummy_entry_t* head = NULL; dummy_entry_t* tail = NULL; EXPECT_FALSE(dummy_slist_flush( &list, IREE_ATOMIC_SLIST_FLUSH_ORDER_APPROXIMATE_LIFO, &head, &tail)); // Push items into the list (LIFO order). // New contents: 3 2 1 0 auto item_storage = MakeDummySListItems(0, 4); for (size_t i = 0; i < item_storage.size(); ++i) { dummy_slist_push(&list, &item_storage[i]); } // Flush in LIFO order and verify empty. // New contents: e EXPECT_TRUE(dummy_slist_flush( &list, IREE_ATOMIC_SLIST_FLUSH_ORDER_APPROXIMATE_LIFO, &head, &tail)); EXPECT_EQ(NULL, dummy_slist_pop(&list)); // Verify LIFO order and list pointer walking. // Note that head and tail are reverse of item storage! EXPECT_EQ(&item_storage.back(), head); EXPECT_EQ(&item_storage.front(), tail); dummy_entry_t* p = head; for (size_t i = 0; i < item_storage.size(); ++i) { ASSERT_TRUE(p); EXPECT_EQ(item_storage.size() - i - 1, p->value); p = dummy_slist_get_next(p); } EXPECT_EQ(NULL, p); dummy_slist_deinitialize(&list); } TEST(AtomicSList, FlushFIFO) { dummy_slist_t list; dummy_slist_initialize(&list); // Flushing when empty is ok. dummy_entry_t* head = NULL; dummy_entry_t* tail = NULL; EXPECT_FALSE(dummy_slist_flush( &list, IREE_ATOMIC_SLIST_FLUSH_ORDER_APPROXIMATE_FIFO, &head, &tail)); // Push items into the list (LIFO order). // New contents: 3 2 1 0 auto item_storage = MakeDummySListItems(0, 4); for (size_t i = 0; i < item_storage.size(); ++i) { dummy_slist_push(&list, &item_storage[i]); } // Flush in FIFO order and verify empty. // New contents: e EXPECT_TRUE(dummy_slist_flush( &list, IREE_ATOMIC_SLIST_FLUSH_ORDER_APPROXIMATE_FIFO, &head, &tail)); EXPECT_EQ(NULL, dummy_slist_pop(&list)); // Verify FIFO order and list pointer walking. EXPECT_EQ(&item_storage.front(), head); EXPECT_EQ(&item_storage.back(), tail); dummy_entry_t* p = head; for (size_t i = 0; i < item_storage.size(); ++i) { ASSERT_TRUE(p); EXPECT_EQ(i, p->value); p = dummy_slist_get_next(p); } EXPECT_EQ(NULL, p); dummy_slist_deinitialize(&list); } } // namespace
30.786458
80
0.683641
[ "vector" ]
8b37d6bb72c98ab08f731c9f7d2d2eddc897820f
7,230
inl
C++
Code/Framework/AzCore/AzCore/DOM/DomPrefixTree.inl
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
1
2022-03-28T08:06:58.000Z
2022-03-28T08:06:58.000Z
Code/Framework/AzCore/AzCore/DOM/DomPrefixTree.inl
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzCore/AzCore/DOM/DomPrefixTree.inl
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once namespace AZ::Dom { template<class T> DomPrefixTree<T>::DomPrefixTree(AZStd::initializer_list<AZStd::pair<Path, T>> init) { for (const auto& [path, value] : init) { SetValue(path, value); } } template <class T> template<class Range, class> DomPrefixTree<T>::DomPrefixTree(Range&& range) { for (auto&& [path, value] : AZStd::forward<Range>(range)) { SetValue(path, value); } } template<class T> auto DomPrefixTree<T>::GetNodeForPath(const Path& path) -> Node* { Node* node = &m_rootNode; for (const auto& entry : path) { auto entryIt = node->m_values.find(entry); if (entryIt == node->m_values.end()) { return nullptr; } node = &entryIt->second; } return node; } template<class T> auto DomPrefixTree<T>::GetNodeForPath(const Path& path) const -> const Node* { const Node* node = &m_rootNode; for (const auto& entry : path) { auto entryIt = node->m_values.find(entry); if (entryIt == node->m_values.end()) { return nullptr; } node = &entryIt->second; } return node; } template<class T> void DomPrefixTree<T>::VisitPath(const Path& path, PrefixTreeMatch match, const VisitorFunction& visitor) const { const Node* rootNode = GetNodeForPath(path); if (rootNode == nullptr) { return; } if ((match == PrefixTreeMatch::ExactPath || match == PrefixTreeMatch::PathAndSubpaths) && rootNode->m_data.has_value()) { visitor(path, rootNode->m_data.value()); } if (match == PrefixTreeMatch::ExactPath) { return; } Path currentPath = path; struct PopPathEntry { }; using StackEntry = AZStd::variant<const Node*, PathEntry, PopPathEntry>; AZStd::stack<StackEntry> stack({ rootNode }); while (!stack.empty()) { StackEntry entry = AZStd::move(stack.top()); stack.pop(); AZStd::visit( [&](auto&& value) { using CurrentType = AZStd::decay_t<decltype(value)>; if constexpr (AZStd::is_same_v<CurrentType, const Node*>) { if (value != rootNode && value->m_data.has_value()) { visitor(currentPath, value->m_data.value()); } for (const auto& entry : value->m_values) { // The stack runs this in reverse order, so we'll: // 1) Push the current path entry to currentPath // 2a) Process the value at the path (if any) // 2b) Process the value's descendants at the path (if any) // 3) Pop the path entry from the stack stack.push(PopPathEntry{}); stack.push(&entry.second); stack.push(entry.first); } } else if constexpr (AZStd::is_same_v<CurrentType, PathEntry>) { currentPath.Push(value); } else if constexpr (AZStd::is_same_v<CurrentType, PopPathEntry>) { currentPath.Pop(); } }, entry); } } template<class T> T* DomPrefixTree<T>::ValueAtPath(const Path& path, PrefixTreeMatch match) { // Just look up the node if we're looking for an exact path if (match == PrefixTreeMatch::ExactPath) { if (Node* node = GetNodeForPath(path); node != nullptr && node->m_data.has_value()) { return &node->m_data.value(); } return {}; } // Otherwise, walk to find the closest anscestor with a value Node* node = &m_rootNode; T* result = nullptr; const size_t lengthToIterate = match == PrefixTreeMatch::SubpathsOnly ? path.Size() - 1 : path.Size(); for (size_t i = 0; i < lengthToIterate; ++i) { if (node->m_data.has_value()) { result = &node->m_data.value(); } const PathEntry& entry = path[i]; auto entryIt = node->m_values.find(entry); if (entryIt == node->m_values.end()) { break; } node = &entryIt->second; } if (node->m_data.has_value()) { result = &node->m_data.value(); } return result; } template<class T> const T* DomPrefixTree<T>::ValueAtPath(const Path& path, PrefixTreeMatch match) const { // Const coerce the ValueAtPath result, which doesn't mutate but returns a mutable pointer return const_cast<DomPrefixTree<T>*>(this)->ValueAtPath(path, match); } template<class T> template<class Deduced> T DomPrefixTree<T>::ValueAtPathOrDefault(const Path& path, Deduced&& defaultValue, PrefixTreeMatch match) const { const T* value = ValueAtPath(path, match); return value == nullptr ? AZStd::forward<Deduced>(defaultValue) : *value; } template<class T> template<class Deduced> void DomPrefixTree<T>::SetValue(const Path& path, Deduced&& value) { Node* node = &m_rootNode; for (const PathEntry& entry : path) { // Get or create an entry in this node node = &node->m_values[entry]; } node->m_data = AZStd::forward<Deduced>(value); } template<class T> void DomPrefixTree<T>::EraseValue(const Path& path, bool removeChildren) { Node* node = &m_rootNode; const size_t entriesToIterate = path.Size() - 1; for (size_t i = 0; i < entriesToIterate; ++i) { const PathEntry& entry = path[i]; auto nodeIt = node->m_values.find(entry); if (nodeIt == node->m_values.end()) { return; } node = &nodeIt->second; } auto nodeIt = node->m_values.find(path[path.Size() - 1]); if (nodeIt != node->m_values.end()) { if (removeChildren) { node->m_values.erase(nodeIt); } else { nodeIt->second.m_data = {}; } } } template<class T> void DomPrefixTree<T>::Clear() { m_rootNode = Node(); } } // namespace AZ::Dom
30.765957
127
0.500553
[ "3d" ]
8b3e10b963566247b995966d614f4da9c5700cc8
4,229
cpp
C++
src/base/math/Exp.cpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
1
2018-09-18T07:09:36.000Z
2018-09-18T07:09:36.000Z
src/base/math/Exp.cpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
null
null
null
src/base/math/Exp.cpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
2
2020-06-18T04:45:30.000Z
2021-07-20T02:11:54.000Z
//$Id$ //------------------------------------------------------------------------------ // Exp //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: LaMont Ruley // Created: 2006/04/14 // /** * Implements Exp class. */ //------------------------------------------------------------------------------ #include "Exp.hpp" #include "MessageInterface.hpp" //--------------------------------- // public methods //--------------------------------- //------------------------------------------------------------------------------ // Exp() //------------------------------------------------------------------------------ /** * Constructor. */ //------------------------------------------------------------------------------ Exp::Exp(const std::string &nomme) : MathFunction("Exp", nomme) { } //------------------------------------------------------------------------------ // ~Exp() //------------------------------------------------------------------------------ /** * Destructor. */ //------------------------------------------------------------------------------ Exp::~Exp() { } //------------------------------------------------------------------------------ // Exp(const Exp &copy) //------------------------------------------------------------------------------ /** * Constructs the Exp object (copy constructor). * * @param <copy> Object that is copied */ //------------------------------------------------------------------------------ Exp::Exp(const Exp &copy) : MathFunction (copy) { } //------------------------------------------------------------------------------ // GmatBase* Clone() const //------------------------------------------------------------------------------ /** * Clone of the Exp operation. * * @return clone of the Exp operation. * */ //------------------------------------------------------------------------------ GmatBase* Exp::Clone() const { return (new Exp(*this)); } //------------------------------------------------------------------------------ // void GetOutputInfo(Integer &type, Integer &rowCount, Integer &colCount) //------------------------------------------------------------------------------ void Exp::GetOutputInfo(Integer &type, Integer &rowCount, Integer &colCount) { GetScalarOutputInfo(type, rowCount, colCount); } //------------------------------------------------------------------------------ // bool ValidateInputs() //------------------------------------------------------------------------------ /** * This method calls its subnodes and checks to be sure that the subnodes return * compatible data for the function. */ //------------------------------------------------------------------------------ bool Exp::ValidateInputs() { return ValidateScalarInputs(); } //------------------------------------------------------------------------------ // Real Evaluate() //------------------------------------------------------------------------------ /** * @return the exponential value * */ //------------------------------------------------------------------------------ Real Exp::Evaluate() { return GmatMathUtil::Exp(leftNode->Evaluate()); }
32.282443
81
0.346418
[ "object" ]
8b4343161ded4e2d614b0ca2c778ffbe515bf9f3
21,665
cc
C++
content/browser/browser_child_process_host_impl.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
content/browser/browser_child_process_host_impl.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/browser_child_process_host_impl.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/browser_child_process_host_impl.h" #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/debug/dump_without_crashing.h" #include "base/feature_list.h" #include "base/files/file_path.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/macros.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/persistent_histogram_allocator.h" #include "base/metrics/persistent_memory_allocator.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "components/tracing/common/tracing_switches.h" #include "content/browser/histogram_message_filter.h" #include "content/browser/loader/resource_message_filter.h" #include "content/browser/memory/memory_message_filter.h" #include "content/browser/profiler_message_filter.h" #include "content/browser/service_manager/service_manager_context.h" #include "content/browser/tracing/trace_message_filter.h" #include "content/common/child_process_host_impl.h" #include "content/common/child_process_messages.h" #include "content/common/service_manager/child_connection.h" #include "content/public/browser/browser_child_process_host_delegate.h" #include "content/public/browser/browser_child_process_observer.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/content_browser_client.h" #include "content/public/common/connection_filter.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/mojo_channel_switches.h" #include "content/public/common/process_type.h" #include "content/public/common/result_codes.h" #include "content/public/common/service_manager_connection.h" #include "device/power_monitor/power_monitor_message_broadcaster.h" #include "mojo/edk/embedder/embedder.h" #include "services/service_manager/public/cpp/interface_registry.h" #if defined(OS_MACOSX) #include "content/browser/mach_broker_mac.h" #endif namespace content { namespace { static base::LazyInstance<BrowserChildProcessHostImpl::BrowserChildProcessList> g_child_process_list = LAZY_INSTANCE_INITIALIZER; base::LazyInstance<base::ObserverList<BrowserChildProcessObserver>> g_observers = LAZY_INSTANCE_INITIALIZER; void NotifyProcessLaunchedAndConnected(const ChildProcessData& data) { for (auto& observer : g_observers.Get()) observer.BrowserChildProcessLaunchedAndConnected(data); } void NotifyProcessHostConnected(const ChildProcessData& data) { for (auto& observer : g_observers.Get()) observer.BrowserChildProcessHostConnected(data); } void NotifyProcessHostDisconnected(const ChildProcessData& data) { for (auto& observer : g_observers.Get()) observer.BrowserChildProcessHostDisconnected(data); } void NotifyProcessCrashed(const ChildProcessData& data, int exit_code) { for (auto& observer : g_observers.Get()) observer.BrowserChildProcessCrashed(data, exit_code); } void NotifyProcessKilled(const ChildProcessData& data, int exit_code) { for (auto& observer : g_observers.Get()) observer.BrowserChildProcessKilled(data, exit_code); } class ConnectionFilterImpl : public ConnectionFilter { public: ConnectionFilterImpl() {} private: // ConnectionFilter: bool OnConnect(const service_manager::Identity& remote_identity, service_manager::InterfaceRegistry* registry, service_manager::Connector* connector) override { registry->AddInterface( base::Bind(&device::PowerMonitorMessageBroadcaster::Create)); return true; } DISALLOW_COPY_AND_ASSIGN(ConnectionFilterImpl); }; } // namespace BrowserChildProcessHost* BrowserChildProcessHost::Create( content::ProcessType process_type, BrowserChildProcessHostDelegate* delegate) { return Create(process_type, delegate, std::string()); } BrowserChildProcessHost* BrowserChildProcessHost::Create( content::ProcessType process_type, BrowserChildProcessHostDelegate* delegate, const std::string& service_name) { return new BrowserChildProcessHostImpl(process_type, delegate, service_name); } BrowserChildProcessHost* BrowserChildProcessHost::FromID(int child_process_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); BrowserChildProcessHostImpl::BrowserChildProcessList* process_list = g_child_process_list.Pointer(); for (BrowserChildProcessHostImpl* host : *process_list) { if (host->GetData().id == child_process_id) return host; } return nullptr; } #if defined(OS_MACOSX) base::PortProvider* BrowserChildProcessHost::GetPortProvider() { return MachBroker::GetInstance(); } #endif // static BrowserChildProcessHostImpl::BrowserChildProcessList* BrowserChildProcessHostImpl::GetIterator() { return g_child_process_list.Pointer(); } // static void BrowserChildProcessHostImpl::AddObserver( BrowserChildProcessObserver* observer) { DCHECK_CURRENTLY_ON(BrowserThread::UI); g_observers.Get().AddObserver(observer); } // static void BrowserChildProcessHostImpl::RemoveObserver( BrowserChildProcessObserver* observer) { // TODO(phajdan.jr): Check thread after fixing http://crbug.com/167126. g_observers.Get().RemoveObserver(observer); } BrowserChildProcessHostImpl::BrowserChildProcessHostImpl( content::ProcessType process_type, BrowserChildProcessHostDelegate* delegate, const std::string& service_name) : data_(process_type), delegate_(delegate), child_token_(mojo::edk::GenerateRandomToken()), is_channel_connected_(false), notify_child_disconnected_(false), weak_factory_(this) { data_.id = ChildProcessHostImpl::GenerateChildProcessUniqueId(); child_process_host_.reset(ChildProcessHost::Create(this)); AddFilter(new TraceMessageFilter(data_.id)); AddFilter(new ProfilerMessageFilter(process_type)); AddFilter(new HistogramMessageFilter); AddFilter(new MemoryMessageFilter(this, process_type)); g_child_process_list.Get().push_back(this); GetContentClient()->browser()->BrowserChildProcessHostCreated(this); if (!service_name.empty()) { DCHECK_CURRENTLY_ON(BrowserThread::IO); child_connection_.reset(new ChildConnection( service_name, base::StringPrintf("%d", data_.id), child_token_, ServiceManagerContext::GetConnectorForIOThread(), base::ThreadTaskRunnerHandle::Get())); } // May be null during test execution. if (ServiceManagerConnection::GetForProcess()) { ServiceManagerConnection::GetForProcess()->AddConnectionFilter( base::MakeUnique<ConnectionFilterImpl>()); } // Create a persistent memory segment for subprocess histograms. CreateMetricsAllocator(); } BrowserChildProcessHostImpl::~BrowserChildProcessHostImpl() { g_child_process_list.Get().remove(this); if (notify_child_disconnected_) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&NotifyProcessHostDisconnected, data_)); } } // static void BrowserChildProcessHostImpl::TerminateAll() { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Make a copy since the BrowserChildProcessHost dtor mutates the original // list. BrowserChildProcessList copy = g_child_process_list.Get(); for (BrowserChildProcessList::iterator it = copy.begin(); it != copy.end(); ++it) { delete (*it)->delegate(); // ~*HostDelegate deletes *HostImpl. } } // static void BrowserChildProcessHostImpl::CopyFeatureAndFieldTrialFlags( base::CommandLine* cmd_line) { std::string enabled_features; std::string disabled_features; base::FeatureList::GetInstance()->GetFeatureOverrides(&enabled_features, &disabled_features); if (!enabled_features.empty()) cmd_line->AppendSwitchASCII(switches::kEnableFeatures, enabled_features); if (!disabled_features.empty()) cmd_line->AppendSwitchASCII(switches::kDisableFeatures, disabled_features); // If we run base::FieldTrials, we want to pass to their state to the // child process so that it can act in accordance with each state. base::FieldTrialList::CopyFieldTrialStateToFlags(switches::kFieldTrialHandle, cmd_line); } void BrowserChildProcessHostImpl::Launch( SandboxedProcessLauncherDelegate* delegate, base::CommandLine* cmd_line, bool terminate_on_shutdown) { DCHECK_CURRENTLY_ON(BrowserThread::IO); GetContentClient()->browser()->AppendExtraCommandLineSwitches( cmd_line, data_.id); const base::CommandLine& browser_command_line = *base::CommandLine::ForCurrentProcess(); static const char* const kForwardSwitches[] = { switches::kDisableLogging, switches::kEnableLogging, switches::kIPCConnectionTimeout, switches::kLoggingLevel, switches::kTraceToConsole, switches::kV, switches::kVModule, }; cmd_line->CopySwitchesFrom(browser_command_line, kForwardSwitches, arraysize(kForwardSwitches)); if (child_connection_) { cmd_line->AppendSwitchASCII(switches::kServiceRequestChannelToken, child_connection_->service_token()); } notify_child_disconnected_ = true; child_process_.reset(new ChildProcessLauncher( delegate, cmd_line, data_.id, this, child_token_, base::Bind(&BrowserChildProcessHostImpl::OnMojoError, weak_factory_.GetWeakPtr(), base::ThreadTaskRunnerHandle::Get()), terminate_on_shutdown)); } const ChildProcessData& BrowserChildProcessHostImpl::GetData() const { DCHECK_CURRENTLY_ON(BrowserThread::IO); return data_; } ChildProcessHost* BrowserChildProcessHostImpl::GetHost() const { DCHECK_CURRENTLY_ON(BrowserThread::IO); return child_process_host_.get(); } const base::Process& BrowserChildProcessHostImpl::GetProcess() const { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(child_process_.get()) << "Requesting a child process handle before launching."; DCHECK(child_process_->GetProcess().IsValid()) << "Requesting a child process handle before launch has completed OK."; return child_process_->GetProcess(); } std::unique_ptr<base::SharedPersistentMemoryAllocator> BrowserChildProcessHostImpl::TakeMetricsAllocator() { return std::move(metrics_allocator_); } void BrowserChildProcessHostImpl::SetName(const base::string16& name) { DCHECK_CURRENTLY_ON(BrowserThread::IO); data_.name = name; } void BrowserChildProcessHostImpl::SetHandle(base::ProcessHandle handle) { DCHECK_CURRENTLY_ON(BrowserThread::IO); data_.handle = handle; } void BrowserChildProcessHostImpl::ForceShutdown() { DCHECK_CURRENTLY_ON(BrowserThread::IO); g_child_process_list.Get().remove(this); child_process_host_->ForceShutdown(); } void BrowserChildProcessHostImpl::SetBackgrounded(bool backgrounded) { child_process_->SetProcessBackgrounded(backgrounded); } void BrowserChildProcessHostImpl::AddFilter(BrowserMessageFilter* filter) { child_process_host_->AddFilter(filter->GetFilter()); } service_manager::InterfaceProvider* BrowserChildProcessHostImpl::GetRemoteInterfaces() { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!child_connection_) return nullptr; return child_connection_->GetRemoteInterfaces(); } void BrowserChildProcessHostImpl::HistogramBadMessageTerminated( int process_type) { UMA_HISTOGRAM_ENUMERATION("ChildProcess.BadMessgeTerminated", process_type, PROCESS_TYPE_MAX); } base::TerminationStatus BrowserChildProcessHostImpl::GetTerminationStatus( bool known_dead, int* exit_code) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!child_process_) // If the delegate doesn't use Launch() helper. return base::GetTerminationStatus(data_.handle, exit_code); return child_process_->GetChildTerminationStatus(known_dead, exit_code); } bool BrowserChildProcessHostImpl::OnMessageReceived( const IPC::Message& message) { return delegate_->OnMessageReceived(message); } void BrowserChildProcessHostImpl::OnChannelConnected(int32_t peer_pid) { DCHECK_CURRENTLY_ON(BrowserThread::IO); is_channel_connected_ = true; notify_child_disconnected_ = true; #if defined(OS_WIN) // From this point onward, the exit of the child process is detected by an // error on the IPC channel. early_exit_watcher_.StopWatching(); #endif BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&NotifyProcessHostConnected, data_)); delegate_->OnChannelConnected(peer_pid); if (IsProcessLaunched()) { ShareMetricsAllocatorToProcess(); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&NotifyProcessLaunchedAndConnected, data_)); } } void BrowserChildProcessHostImpl::OnChannelError() { delegate_->OnChannelError(); } void BrowserChildProcessHostImpl::OnBadMessageReceived( const IPC::Message& message) { TerminateOnBadMessageReceived(message.type()); } void BrowserChildProcessHostImpl::TerminateOnBadMessageReceived(uint32_t type) { HistogramBadMessageTerminated(data_.process_type); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableKillAfterBadIPC)) { return; } LOG(ERROR) << "Terminating child process for bad IPC message of type " << type; // Create a memory dump. This will contain enough stack frames to work out // what the bad message was. base::debug::DumpWithoutCrashing(); child_process_->GetProcess().Terminate(RESULT_CODE_KILLED_BAD_MESSAGE, false); } bool BrowserChildProcessHostImpl::CanShutdown() { return delegate_->CanShutdown(); } void BrowserChildProcessHostImpl::OnChildDisconnected() { DCHECK_CURRENTLY_ON(BrowserThread::IO); #if defined(OS_WIN) // OnChildDisconnected may be called without OnChannelConnected, so stop the // early exit watcher so GetTerminationStatus can close the process handle. early_exit_watcher_.StopWatching(); #endif if (child_process_.get() || data_.handle) { int exit_code; base::TerminationStatus status = GetTerminationStatus( true /* known_dead */, &exit_code); switch (status) { case base::TERMINATION_STATUS_PROCESS_CRASHED: case base::TERMINATION_STATUS_ABNORMAL_TERMINATION: { delegate_->OnProcessCrashed(exit_code); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&NotifyProcessCrashed, data_, exit_code)); UMA_HISTOGRAM_ENUMERATION("ChildProcess.Crashed2", data_.process_type, PROCESS_TYPE_MAX); break; } #if defined(OS_ANDROID) case base::TERMINATION_STATUS_OOM_PROTECTED: #endif #if defined(OS_CHROMEOS) case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM: #endif case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: { delegate_->OnProcessCrashed(exit_code); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&NotifyProcessKilled, data_, exit_code)); // Report that this child process was killed. UMA_HISTOGRAM_ENUMERATION("ChildProcess.Killed2", data_.process_type, PROCESS_TYPE_MAX); break; } case base::TERMINATION_STATUS_STILL_RUNNING: { UMA_HISTOGRAM_ENUMERATION("ChildProcess.DisconnectedAlive2", data_.process_type, PROCESS_TYPE_MAX); } default: break; } UMA_HISTOGRAM_ENUMERATION("ChildProcess.Disconnected2", data_.process_type, PROCESS_TYPE_MAX); #if defined(OS_CHROMEOS) if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM) { UMA_HISTOGRAM_ENUMERATION("ChildProcess.Killed2.OOM", data_.process_type, PROCESS_TYPE_MAX); } #endif } delete delegate_; // Will delete us } bool BrowserChildProcessHostImpl::Send(IPC::Message* message) { return child_process_host_->Send(message); } void BrowserChildProcessHostImpl::CreateMetricsAllocator() { // Create a persistent memory segment for subprocess histograms only if // they're active in the browser. // TODO(bcwhite): Remove this once persistence is always enabled. if (!base::GlobalHistogramAllocator::Get()) return; // Determine the correct parameters based on the process type. size_t memory_size; base::StringPiece metrics_name; switch (data_.process_type) { case PROCESS_TYPE_UTILITY: memory_size = 64 << 10; // 64 KiB metrics_name = "UtilityMetrics"; break; case PROCESS_TYPE_ZYGOTE: memory_size = 64 << 10; // 64 KiB metrics_name = "ZygoteMetrics"; break; case PROCESS_TYPE_SANDBOX_HELPER: memory_size = 64 << 10; // 64 KiB metrics_name = "SandboxHelperMetrics"; break; case PROCESS_TYPE_GPU: memory_size = 64 << 10; // 64 KiB metrics_name = "GpuMetrics"; break; case PROCESS_TYPE_PPAPI_PLUGIN: memory_size = 64 << 10; // 64 KiB metrics_name = "PpapiPluginMetrics"; break; case PROCESS_TYPE_PPAPI_BROKER: memory_size = 64 << 10; // 64 KiB metrics_name = "PpapiBrokerMetrics"; break; default: UMA_HISTOGRAM_ENUMERATION( "UMA.SubprocessMetricsProvider.UntrackedProcesses", data_.process_type, PROCESS_TYPE_CONTENT_END); return; } // Create the shared memory segment and attach an allocator to it. // Mapping the memory shouldn't fail but be safe if it does; everything // will continue to work but just as if persistence weren't available. std::unique_ptr<base::SharedMemory> shm(new base::SharedMemory()); if (!shm->CreateAndMapAnonymous(memory_size)) return; metrics_allocator_.reset(new base::SharedPersistentMemoryAllocator( std::move(shm), static_cast<uint64_t>(data_.id), metrics_name, /*readonly=*/false)); } void BrowserChildProcessHostImpl::ShareMetricsAllocatorToProcess() { if (metrics_allocator_) { base::SharedMemoryHandle shm_handle; metrics_allocator_->shared_memory()->ShareToProcess(data_.handle, &shm_handle); Send(new ChildProcessMsg_SetHistogramMemory( shm_handle, metrics_allocator_->shared_memory()->mapped_size())); } } void BrowserChildProcessHostImpl::OnProcessLaunchFailed(int error_code) { delegate_->OnProcessLaunchFailed(error_code); notify_child_disconnected_ = false; delete delegate_; // Will delete us } void BrowserChildProcessHostImpl::OnProcessLaunched() { DCHECK_CURRENTLY_ON(BrowserThread::IO); const base::Process& process = child_process_->GetProcess(); DCHECK(process.IsValid()); if (child_connection_) child_connection_->SetProcessHandle(process.Handle()); #if defined(OS_WIN) // Start a WaitableEventWatcher that will invoke OnProcessExitedEarly if the // child process exits. This watcher is stopped once the IPC channel is // connected and the exit of the child process is detecter by an error on the // IPC channel thereafter. DCHECK(!early_exit_watcher_.GetWatchedObject()); early_exit_watcher_.StartWatchingOnce(process.Handle(), this); #endif // TODO(rvargas) crbug.com/417532: Don't store a handle. data_.handle = process.Handle(); delegate_->OnProcessLaunched(); if (is_channel_connected_) { ShareMetricsAllocatorToProcess(); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&NotifyProcessLaunchedAndConnected, data_)); } } bool BrowserChildProcessHostImpl::IsProcessLaunched() const { DCHECK_CURRENTLY_ON(BrowserThread::IO); return child_process_.get() && child_process_->GetProcess().IsValid(); } // static void BrowserChildProcessHostImpl::OnMojoError( base::WeakPtr<BrowserChildProcessHostImpl> process, scoped_refptr<base::SingleThreadTaskRunner> task_runner, const std::string& error) { if (!task_runner->BelongsToCurrentThread()) { task_runner->PostTask( FROM_HERE, base::Bind(&BrowserChildProcessHostImpl::OnMojoError, process, task_runner, error)); } if (!process) return; HistogramBadMessageTerminated(process->data_.process_type); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableKillAfterBadIPC)) { return; } LOG(ERROR) << "Terminating child process for bad Mojo message: " << error; // Create a memory dump with the error message aliased. This will make it easy // to determine details about what interface call failed. base::debug::Alias(&error); base::debug::DumpWithoutCrashing(); process->child_process_->GetProcess().Terminate( RESULT_CODE_KILLED_BAD_MESSAGE, false); } #if defined(OS_WIN) void BrowserChildProcessHostImpl::OnObjectSignaled(HANDLE object) { OnChildDisconnected(); } #endif } // namespace content
35.056634
80
0.732287
[ "object" ]
8b4a3c387ce3732a78b963cc720ba7ae84cc7464
135
hpp
C++
halfedge.hpp
uyen9vba/Wupty
be093987194e92f207b0f545fc0ad34a4de4b192
[ "MIT" ]
2
2021-08-30T07:30:21.000Z
2021-08-31T05:49:33.000Z
halfedge.hpp
uyen9vba/Wupty
be093987194e92f207b0f545fc0ad34a4de4b192
[ "MIT" ]
null
null
null
halfedge.hpp
uyen9vba/Wupty
be093987194e92f207b0f545fc0ad34a4de4b192
[ "MIT" ]
null
null
null
#include <vector> struct HalfEdge { int river; Point midpoint; // initalized Site* site; // initialized, points to middle site }
15
50
0.703704
[ "vector" ]
8b4a6dd4f4f62dcb8b55a516d5c0a104a716ec8a
18,220
cpp
C++
src/trunk/libs/seiscomp3/io/quakelink/connection.cpp
thefroid/seiscomp3
0b05d5550dcea000a93c7d9a39c5347d8786a91a
[ "Naumen", "Condor-1.1", "MS-PL" ]
2
2015-09-17T22:43:50.000Z
2017-11-29T20:27:11.000Z
src/trunk/libs/seiscomp3/io/quakelink/connection.cpp
thefroid/seiscomp3
0b05d5550dcea000a93c7d9a39c5347d8786a91a
[ "Naumen", "Condor-1.1", "MS-PL" ]
2
2016-04-26T00:03:09.000Z
2017-12-05T02:24:50.000Z
src/trunk/libs/seiscomp3/io/quakelink/connection.cpp
salichon/seiscomp3
4f7715f9ff9a35e7912c379ebf10446d0bceaeb2
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2022-01-13T02:49:31.000Z
2022-01-13T02:49:31.000Z
/*************************************************************************** * Copyright (C) by GFZ Potsdam * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public License. * * * * 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 * * SeisComP Public License for more details. * * * * Author: Stephan Herrnkind * * Email : herrnkind@gempa.de * ***************************************************************************/ #define SEISCOMP_COMPONENT QLClient #define DEFAULT_PORT ":18010" #define MAX_CONTENT_LENGTH 10485760 // 10MiB #include <sstream> #include <string> //#include <seiscomp3/client/application.h> #include <seiscomp3/core/strings.h> #include <seiscomp3/logging/log.h> #include "connection.h" using namespace std; namespace Seiscomp { namespace IO { namespace QuakeLink { namespace { bool equals(const string &found, const string &expected) { return found.length() == expected.length() && strncmp(found.c_str(), expected.c_str(), expected.length()) == 0; } bool startsWith(const string &found, const string &expected) { return found.length() >= expected.length() && strncmp(found.c_str(), expected.c_str(), expected.length()) == 0; } string requestFormat(RequestFormat format) { return format == rfNative ? " AS NATIVE" : format == rfGZNative ? " AS GZNATIVE" : format == rfXML ? " AS XML" : format == rfGZXML ? " AS GZXML" : " AS SUMMARY"; } bool readHeaderValue(string &value, const string &line, const string &key) { if ( !startsWith(line, key) ) return false; value = line.substr(key.length()); Core::trim(value); return true; } ContentType contentType(const string &type) { return startsWith(type, "quakelink/xml") ? ctXML : startsWith(type, "quakelink/evsum") ? ctEvSum : startsWith(type, "quakelink/evlog") ? ctEvLog : startsWith(type, "text/plain") ? ctText : ctUndefined; } string intToString(int i) { stringstream ss; ss << i; return ss.str(); } } // ns anonymous const char *SummaryTimeFormat = "%F %T"; const char *RequestTimeFormat = "%Y,%m,%d,%H,%M,%S,%6f"; Connection::Connection() : _sock(NULL), _options(opIgnore) {} Connection::~Connection() { if ( _sock ) { disconnect(); delete _sock; _sock = NULL; } } bool Connection::connected() const { return _sock && _sock->isOpen(); } bool Connection::init(const string &url, int options) { SEISCOMP_DEBUG("%sinitializing service with URL: %s", _logPrefix.c_str(), url.c_str()); disconnect(); delete _sock; _sock = NULL; setOptions(options); // parse URL, e.g. qls://user:pass@host:port // step 1: protocol size_t pos; string protocol; string connection; pos = url.find("://"); if ( pos == string::npos ) { protocol = "ql"; connection = url; } else { protocol = url.substr(0, pos); connection = url.substr(pos + 3); } bool ssl = protocol == "qls"; if ( !ssl && protocol != "ql" ) { SEISCOMP_ERROR("%sunsupported protocol: %s", _logPrefix.c_str(), protocol.c_str()); return false; } // step 2: user:pass vector<string> tokens; if ( Core::split(tokens, connection.c_str(), "@") >= 2 ) { string login = tokens[0]; _service = tokens[1]; Core::split(tokens, login.c_str(), ":"); _user = tokens.size() > 0 ? tokens[0] : ""; _pass = tokens.size() > 1 ? tokens[1] : ""; } else _service = connection; // step 3: host:port _service = _service.substr(0, _service.find('/')); if ( _service.find(':') == string::npos ) _service += DEFAULT_PORT; _sock = ssl ? new SSLSocket() : new Socket(); SEISCOMP_DEBUG("%sservice initialized: %s, ssl=%i", _logPrefix.c_str(), _service.c_str(), ssl); return true; } void Connection::disconnect() { if ( connected() ) { _sock->close(); SEISCOMP_DEBUG("%sconnection to %s closed", _logPrefix.c_str(), _service.c_str()); } } bool Connection::setOptions(int options) { if ( _options == options ) return true; int oldOptions = _options; _options = options; // if connected updated only those options which have been changed return !connected() || sendOptions(oldOptions ^ _options); } bool Connection::getUpdates(Response &response, const std::string &eventid) { if ( !connect() ) return false; // send request, format is restricted to SUMMARY string req = "GET UPDATES OF EVENT " + eventid + requestFormat(rfSummary); if ( !sendRequest(req) ) { response.data = "Error sending data request"; return false; } // evaluate response code string code; if ( !readResponseCode(code) ) return false; // data found if ( startsWith(code, "DATA/GET 200") ) { return readResponse(response); } // no data available if ( startsWith(code, "DATA/GET 404") ) assertLineBreak(); else logInvalidResp("DATA/GET 200", code.c_str()); return false; } bool Connection::get(Response &response, const std::string &eventId, int revision, RequestFormat format) { if ( !connect() ) return false; // send request for either the latest or a specific revision string req = revision < 0 ? "GET EVENT " : "GET UPDATE " + intToString(revision) + " OF EVENT "; if ( !sendRequest(req + eventId + requestFormat(format)) ) { response.data = "Error sending data request"; return false; } // evaluate response code string code; if ( !readResponseCode(code) ) return false; // data found if ( startsWith(code, "DATA/GET 200") ) { return readResponse(response); } // no data available if ( startsWith(code, "DATA/GET 404") ) assertLineBreak(); else logInvalidResp("DATA/GET 200", code.c_str()); return false; } bool Connection::selectArchived(Responses &responses, const Core::Time &from, const Core::Time &to, RequestFormat format, const std::string &where) { responses.clear(); if ( !connect() ) return false; // send request string req = "SELECT ARCHIVED EVENTS"; if ( from ) req += " FROM " + from.toString(RequestTimeFormat); if ( to ) req += " TO " + to.toString(RequestTimeFormat); req += requestFormat(format); if ( where.size() > 0 ) req += " WHERE " + where; if ( !sendRequest(req) ) return false; // read responses string code; while ( readResponseCode(code) ) { if ( startsWith(code, "EOD/SELECT/ARCHIVED") ) { if ( !readResponseCode(code) ) break; if ( !equals(code, "EOD/SELECT") ) { logInvalidResp("EOD/SELECT", code.c_str()); break; } return true; } if ( !startsWith(code, "DATA/SELECT/ARCHIVED 200") ) { logInvalidResp("DATA/SELECT/ARCHIVED 200", code.c_str()); break; } responses.resize(responses.size() + 1); if ( !readResponse(responses.back()) ) { responses.resize(responses.size() - 1); return false; } if ( responses.back().type == ctXML && !responses.back().timestamp.valid() ) { responses.resize(responses.size() - 1); SEISCOMP_WARNING("%sinvalid timestamp in archived data, skipping", _logPrefix.c_str()); } } return false; } bool Connection::select(bool archived, const Core::Time &from, const Core::Time &to, RequestFormat format, const std::string &where, int updatedBufferSize) { if ( !connect() ) return false; // send request string req = archived ? "SELECT EVENTS" : "SELECT UPDATED EVENTS"; if ( from ) req += " FROM " + from.toString(RequestTimeFormat); if ( to ) req += " TO " + to.toString(RequestTimeFormat); req += requestFormat(format); if ( where.size() > 0 ) req += " WHERE " + where; if ( !sendRequest(req) ) return false; // cache of updates received during selection of archived events ResponsesPtr updatesBetween; Response *response; string code; while ( readResponseCode(code) ) { if ( !archived && equals(code, "EOD/SELECT") ) { SEISCOMP_DEBUG("%sEOD/SELECT", _logPrefix.c_str()); return true; } if ( archived && startsWith(code, "EOD/SELECT/ARCHIVED") ) { archived = false; SEISCOMP_DEBUG("%sEOD/SELECT/ARCHIVED", _logPrefix.c_str()); if ( updatesBetween.size() > 0 ) { SEISCOMP_INFO("%sprocessing %lu updates received in between", _logPrefix.c_str(), (unsigned long) updatesBetween.size()); for ( ResponsesPtr::iterator it = updatesBetween.begin(); it != updatesBetween.end(); ++it ) processResponse(*it); updatesBetween.clear(); } SEISCOMP_INFO("%swaiting for data updates", _logPrefix.c_str()); continue; } if ( !startsWith(code, "DATA/SELECT/") ) { logInvalidResp("DATA/SELECT/*", code.c_str()); break; } response = new Response(); if ( readResponse(*response) ) { if ( archived && startsWith(code, "DATA/SELECT/ARCHIVED 200") ) { processResponse(response); continue; } else if ( startsWith(code, "DATA/SELECT/UPDATED 200") ) { response->timestamp = Core::Time::GMT(); // archived data processed or cache disabled: sent update immediately if ( !archived || updatedBufferSize < 0 ) { processResponse(response); continue; } // intermediate update, try to buffer if ( updatesBetween.size() < (unsigned) updatedBufferSize ) { updatesBetween.push_back(response); continue; } SEISCOMP_WARNING("%sreceived to many updates while still " "proccessing archived events, ignoring " "archived data now", _logPrefix.c_str()); } else SEISCOMP_WARNING("%sunsupported DATA/SELECT mode: %s", _logPrefix.c_str(), code.c_str()); } delete response; } for ( ResponsesPtr::iterator it = updatesBetween.begin(); it != updatesBetween.end(); ++it ) delete *it; return false; } bool Connection::abort() { if ( connected() ) return sendRequest("ABORT"); return true; } //////////////////////////////////////////////////////////////////////////////// // Private //////////////////////////////////////////////////////////////////////////////// bool Connection::connect() { if ( connected() ) return true; if ( !_sock ) { SEISCOMP_ERROR("%sinstance not initialized", _logPrefix.c_str()); return false; } try { _sock->open(_service); } catch ( SocketException &se ) { SEISCOMP_ERROR("%scould not connect to service '%s': %s ", _logPrefix.c_str(), _service.c_str(), se.what()); _sock->close(); return false; } if ( _user.empty() ) { SEISCOMP_DEBUG("%sskipping authentication", _logPrefix.c_str()); } else { SEISCOMP_DEBUG("%sperforming authentication", _logPrefix.c_str()); if ( sendRequest("auth " + _user + " " + _pass, false) ) SEISCOMP_DEBUG("%sauthentication successful", _logPrefix.c_str()); else SEISCOMP_ERROR("%scould not authenticate to service %s", _logPrefix.c_str(), _service.c_str()); } return connected() && sendOptions(opAll); } bool Connection::sendRequest(const string& req, bool log) { SEISCOMP_DEBUG("%ssending request: %s", _logPrefix.c_str(), log ? req.c_str() : "***"); try { _sock->write(req + "\r\n"); } catch ( SocketException &se ) { SEISCOMP_ERROR("%scould not send request '%s': %s", _logPrefix.c_str(), log ? req.c_str() : "***", se.what()); disconnect(); return false; } return true; } bool Connection::sendOptions(int changedOptions) { if ( changedOptions <= 0 ) return true; if ( !connected() ) return false; // special case: if defaults are in place they must be always set prior to // any other option if ( _options & opDefaults && !sendRequest("SET DEFAULTS") ) return false; // send only those options which have changed return updateOption(opXMLIndent, "XML.INDENT", changedOptions) && updateOption(opDataPicks, "DATA.PICKS", changedOptions) && updateOption(opDataAmplitudes, "DATA.AMPLITUDES", changedOptions) && updateOption(opDataStaMags, "DATA.STAMAGS", changedOptions) && updateOption(opDataArrivals, "DATA.ARRIVALS", changedOptions) && updateOption(opDataStaMts, "DATA.STAMTS", changedOptions) && updateOption(opDataPreferred, "DATA.PREFERRED", changedOptions) && updateOption(opKeepAlive, "KEEPALIVE", changedOptions); } bool Connection::updateOption(Options option, const char *cmd, int changedOptions) { if ( ! (changedOptions & option ) ) return true; const static string req = "SET "; return sendRequest(req + cmd + (_options & option ? " ON" : " OFF")); } bool Connection::readResponse(Response &response) { // reset response object response.reset(); // read header lines string line, value; while ( readLine(line) != 0 ) { if ( readHeaderValue(value, line, "Content-Type:") ) { if ( (response.type = contentType(value)) == ctUndefined ) { logAndDisconnect("response header: Unsupported Content-Type", value.c_str()); return false; } } else if ( readHeaderValue(value, line, "Content-Length:") ) { if ( !Core::fromString(response.length, value) ) { logAndDisconnect("response header: Invalid Content-Length", value.c_str()); return false; } if ( response.length > MAX_CONTENT_LENGTH ) { logAndDisconnect("response header: Content-Length exceeds " "maximum of %s bytes", value.c_str()); return false; } } else if ( readHeaderValue(value, line, "Content-Format:") ) { response.format = value; } else if ( readHeaderValue(value, line, "Content-Encoding:") ) { response.gzip = startsWith(value, "gzip"); if ( !response.gzip ) { logAndDisconnect("response header: Invalid Content-Encoding", value.c_str()); return false; } } else if ( readHeaderValue(value, line, "Content-Timestamp:") ) { if ( !response.timestamp.fromString(value.c_str(), "%FT%T.%f") ) { logAndDisconnect("response header: Invalid Content-Timestamp", value.c_str()); return false; } } else if ( readHeaderValue(value, line, "Content-Revision:") ) { int rev; if ( !Core::fromString(rev, value.c_str()) ) { logAndDisconnect("response header: Invalid Content-Revision", value.c_str()); return false; } response.revision = rev; } else if ( readHeaderValue(value, line, "Disposed:") ) { bool disposed; if ( !Core::fromString(disposed, value.c_str()) ) { logAndDisconnect("response header: Invalid Disposed value", value.c_str()); return false; } response.disposed = disposed; } else { SEISCOMP_DEBUG("%sreponse header: Unsupported header line: %s", _logPrefix.c_str(), line.c_str()); } } // the header must at least contain a content type and length if ( response.type == ctUndefined ) { logAndDisconnect("response header: Missing Content-Type"); return false; } if ( response.length <= 0 ) { logAndDisconnect("response header: Missing Content-Length"); return false; } // read payload if ( !readPayload(response.data, response.length) ) return false; // read terminating new line return assertLineBreak(); } size_t Connection::readLine(string &line) { line.clear(); try { line = _sock->readline(); } catch ( SocketException& ) {} // strip carriage return size_t len = line.size(); if ( len && line[len-1] == '\r' ) line.resize(--len); return len; } void Connection::logAndDisconnect(const char *msg, const char *detail) { if ( detail != 0 ) SEISCOMP_ERROR("%s%s: %s, disconnecting", _logPrefix.c_str(), msg, detail); else SEISCOMP_ERROR("%s%s, disconnecting", _logPrefix.c_str(), msg); disconnect(); } void Connection::logInvalidResp(const char *expected, const char *got) { string detail = string("expected: '") + expected + string("', got: '") + got + string("'"); logAndDisconnect("received unexpected response code", detail.c_str()); } bool Connection::readResponseCode(std::string &code) { while (readLine(code)) { if ( code == "ALIVE") SEISCOMP_DEBUG("%sreceived ALIVE message", _logPrefix.c_str()); else { SEISCOMP_DEBUG("%sread response code: %s", _logPrefix.c_str(), code.c_str()); return true; } } logAndDisconnect("received empty response code"); return false; } bool Connection::assertResponseCode(const std::string &expected) { string code; if ( !readResponseCode(code) ) return false; if ( startsWith(code, expected) ) return true; logInvalidResp(expected.c_str(), code.c_str()); return false; } bool Connection::assertLineBreak() { try { string s = _sock->read(1); if ( s == "\r") s = _sock->read(1); if ( s == "\n") return true; logAndDisconnect("could not read line break"); } catch ( SocketException& se) { logAndDisconnect("could not read line break", se.what()); } return false; } bool Connection::readPayload(string &data, uint n) { SEISCOMP_DEBUG("%sreading %u payload bytes", _logPrefix.c_str(), n); uint read = 0; uint total = 0; data.reserve(n); while ( total < n ) { read = n - total < BUFSIZE ? n - total : BUFSIZE; try { data += _sock->read(read); } catch ( SocketException& se) { logAndDisconnect("could not read response payload", se.what()); return false; } total += read; } if ( total < n ) { logAndDisconnect("read incomplete response payload"); return false; } return true; } } // ns QuakeLink } // ns IO } // ns Seiscomp
29.529984
80
0.611581
[ "object", "vector" ]
8b4ae4887e2cec558f4ca0449496c286ac8fec50
43,992
cpp
C++
isis/src/base/objs/Spice/Spice.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
null
null
null
isis/src/base/objs/Spice/Spice.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
null
null
null
isis/src/base/objs/Spice/Spice.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
1
2021-07-12T06:05:03.000Z
2021-07-12T06:05:03.000Z
/** * @file * $Revision: 7229 $ * $Date: 2016-11-10 21:04:46 -0700 (Thu, 10 Nov 2016) $ * * Unless noted otherwise, the portions of Isis written by the USGS are public * domain. See individual third-party library and package descriptions for * intellectual property information,user agreements, and related information. * * Although Isis has been used by the USGS, no warranty, expressed or implied, * is made by the USGS as to the accuracy and functioning of such software * and related material nor shall the fact of distribution constitute any such * warranty, and no responsibility is assumed by the USGS in connection * therewith. * * For additional information, launch * $ISISROOT/doc//documents/Disclaimers/Disclaimers.html in a browser or see * the Privacy &amp; Disclaimers page on the Isis website, * http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on * http://www.usgs.gov/privacy.html. */ #include "Spice.h" #include <cfloat> #include <iomanip> #include <QDebug> #include <QVector> #include <getSpkAbCorrState.hpp> #include "Constants.h" #include "Distance.h" #include "EllipsoidShape.h" #include "EndianSwapper.h" #include "FileName.h" #include "IException.h" #include "IString.h" #include "iTime.h" #include "Longitude.h" #include "LightTimeCorrectionState.h" #include "NaifStatus.h" #include "ShapeModel.h" #include "SpacecraftPosition.h" #include "Target.h" using namespace std; namespace Isis { /** * Constructs a Spice object and loads SPICE kernels using information from the * label object. The constructor expects an Instrument and Kernels group to be * in the labels. * * @param lab Label containing Instrument and Kernels groups. */ // TODO: DOCUMENT EVERYTHING Spice::Spice(Pvl &lab) { PvlGroup kernels = lab.findGroup("Kernels", Pvl::Traverse); bool hasTables = (kernels["TargetPosition"][0] == "Table"); init(lab, !hasTables); } /** * Constructs a Spice object and loads SPICE kernels using information from the * label object. The constructor expects an Instrument and Kernels group to be * in the labels. * * @param lab Label containing Instrument and Kernels groups. * * @internal * @history 2005-10-07 Jim Torson - Modified the constructor so it can * handle multiple SpacecraftPosition and * multiple SpacecraftPointing kernel files * @history 2005-11-29 Debbie A. Cook - Added loop to allow multiple frames * kernels and code to initialize Naif * codes when no platform is used (landers) * @history 2006-01-03 Debbie A. Cook - Added loop to allow multiple spacecraft * clock kernels (for Viking) * @history 2006-02-21 Jeff Anderson/Debbie Cook - Refactor to use SpicePosition * and SpiceRotation classes * @history 2009-03-18 Tracie Sucharski - Remove code for old keywords. */ // TODO: DOCUMENT EVERYTHING Spice::Spice(Cube &cube) { Pvl &lab = *cube.label(); PvlGroup kernels = lab.findGroup("Kernels", Pvl::Traverse); bool hasTables = (kernels["TargetPosition"][0] == "Table"); init(lab, !hasTables); } /** * Constructs a Spice object. * * @param lab Pvl labels. * @param noTables Indicates the use of tables. */ Spice::Spice(Cube &cube, bool noTables) { init(*cube.label(), noTables); } /** * Initialization of Spice object. * * @param lab Pvl labels * @param noTables Indicates the use of tables. * * @throw Isis::IException::Io - "Can not find NAIF code for NAIF target" * @throw Isis::IException::Camera - "No camera pointing available" * @throw Isis::IException::Camera - "No instrument position available" * * @internal * @history 2011-02-08 Jeannie Walldren - Initialize pointers to null. */ void Spice::init(Pvl &lab, bool noTables) { NaifStatus::CheckErrors(); // Initialize members m_solarLongitude = new Longitude; m_et = NULL; m_kernels = new QVector<QString>; m_startTime = new iTime; m_endTime = new iTime; m_cacheSize = new SpiceDouble; *m_cacheSize = 0; m_startTimePadding = new SpiceDouble; *m_startTimePadding = 0; m_endTimePadding = new SpiceDouble; *m_endTimePadding = 0; m_instrumentPosition = NULL; m_instrumentRotation = NULL; m_sunPosition = NULL; m_bodyRotation = NULL; m_allowDownsizing = false; m_spkCode = new SpiceInt; m_ckCode = new SpiceInt; m_ikCode = new SpiceInt; m_sclkCode = new SpiceInt; m_spkBodyCode = new SpiceInt; m_bodyFrameCode = new SpiceInt; m_naifKeywords = new PvlObject("NaifKeywords"); // m_sky = false; // Get the kernel group and load main kernels PvlGroup kernels = lab.findGroup("Kernels", Pvl::Traverse); // Get the time padding first if (kernels.hasKeyword("StartPadding")) { *m_startTimePadding = toDouble(kernels["StartPadding"][0]); } else { *m_startTimePadding = 0.0; } if (kernels.hasKeyword("EndPadding")) { *m_endTimePadding = toDouble(kernels["EndPadding"][0]); } else { *m_endTimePadding = 0.0; } m_usingNaif = !lab.hasObject("NaifKeywords") || noTables; // Modified to load planetary ephemeris SPKs before s/c SPKs since some // missions (e.g., MESSENGER) may augment the s/c SPK with new planet // ephemerides. (2008-02-27 (KJB)) if (m_usingNaif) { if (noTables) { load(kernels["TargetPosition"], noTables); load(kernels["InstrumentPosition"], noTables); load(kernels["InstrumentPointing"], noTables); } if (kernels.hasKeyword("Frame")) { load(kernels["Frame"], noTables); } load(kernels["TargetAttitudeShape"], noTables); if (kernels.hasKeyword("Instrument")) { load(kernels["Instrument"], noTables); } // Always load after instrument if (kernels.hasKeyword("InstrumentAddendum")) { load(kernels["InstrumentAddendum"], noTables); } load(kernels["LeapSecond"], noTables); if ( kernels.hasKeyword("SpacecraftClock")) { load(kernels["SpacecraftClock"], noTables); } // Modified to load extra kernels last to allow overriding default values // (2010-04-07) (DAC) if (kernels.hasKeyword("Extra")) { load(kernels["Extra"], noTables); } // Moved the construction of the Target after the NAIF kenels have been loaded or the // NAIF keywords have been pulled from the cube labels, so we can find target body codes // that are defined in kernels and not just body codes build into spicelib // TODO: Move this below the else once the rings code below has been refactored m_target = new Target(this, lab); // This should not be here. Consider having spiceinit add the necessary rings kernels to the // Extra parameter if the user has set the shape model to RingPlane. // If Target is Saturn and ShapeModel is RingPlane, load the extra rings pck file // which changes the prime meridian values to report longitudes with respect to // the ascending node of the ringplane. if (m_target->name().toUpper() == "SATURN" && m_target->shape()->name().toUpper() == "PLANE") { PvlKeyword ringPck = PvlKeyword("RingPCK","$cassini/kernels/pck/saturnRings_v001.tpc"); load(ringPck, noTables); } } else { *m_naifKeywords = lab.findObject("NaifKeywords"); // Moved the construction of the Target after the NAIF kenels have been loaded or the // NAIF keywords have been pulled from the cube labels, so we can find target body codes // that are defined in kernels and not just body codes build into spicelib // TODO: Move this below the else once the rings code above has been refactored m_target = new Target(this, lab); } // Get NAIF ik, spk, sclk, and ck codes // // Use ikcode to get parameters from instrument kernel such as focal // length, distortions, focal plane maps, etc // // Use spkcode to get spacecraft position from spk file // // Use sclkcode to transform times from et to tics // // Use ckcode to transform between frames // // Use bodycode to obtain radii and attitude (pole position/omega0) // // Use spkbodycode to read body position from spk QString trykey = "NaifIkCode"; if (kernels.hasKeyword("NaifFrameCode")) trykey = "NaifFrameCode"; *m_ikCode = toInt(kernels[trykey][0]); *m_spkCode = *m_ikCode / 1000; *m_sclkCode = *m_spkCode; *m_ckCode = *m_ikCode; if (!m_target->isSky()) { QString radiiKey = "BODY" + Isis::toString(m_target->naifBodyCode()) + "_RADII"; std::vector<Distance> radii(3,Distance()); radii[0] = Distance(getDouble(radiiKey, 0), Distance::Kilometers); radii[1] = Distance(getDouble(radiiKey, 1), Distance::Kilometers); radii[2] = Distance(getDouble(radiiKey, 2), Distance::Kilometers); // m_target doesn't have the getDouble method so Spice gets the radii for it m_target->setRadii(radii); } *m_spkBodyCode = m_target->naifBodyCode(); // Override them if they exist in the labels if (kernels.hasKeyword("NaifSpkCode")) { *m_spkCode = (int) kernels["NaifSpkCode"]; } if (kernels.hasKeyword("NaifCkCode")) { *m_ckCode = (int) kernels["NaifCkCode"]; } if (kernels.hasKeyword("NaifSclkCode")) { *m_sclkCode = (int) kernels["NaifSclkCode"]; } if (!m_target->isSky()) { if (kernels.hasKeyword("NaifSpkBodyCode")) { *m_spkBodyCode = (int) kernels["NaifSpkBodyCode"]; } } if (m_target->isSky()) { // Create the identity rotation for sky targets // Everything in bodyfixed will really be J2000 m_bodyRotation = new SpiceRotation(1); } else { // JAA - Modified to store and look for the frame body code in the cube labels SpiceInt frameCode; if ((m_usingNaif) || (!m_naifKeywords->hasKeyword("BODY_FRAME_CODE"))) { char frameName[32]; SpiceBoolean found; cidfrm_c(*m_spkBodyCode, sizeof(frameName), &frameCode, frameName, &found); if (!found) { QString naifTarget = "IAU_" + m_target->name().toUpper(); namfrm_c(naifTarget.toLatin1().data(), &frameCode); if (frameCode == 0) { QString msg = "Can not find NAIF BODY_FRAME_CODE for target [" + m_target->name() + "]"; throw IException(IException::Io, msg, _FILEINFO_); } } QVariant result = (int)frameCode; storeValue("BODY_FRAME_CODE", 0, SpiceIntType, result); } else { frameCode = getInteger("BODY_FRAME_CODE", 0); } m_bodyRotation = new SpiceRotation(frameCode); *m_bodyFrameCode = frameCode; } m_instrumentRotation = new SpiceRotation(*m_ckCode); // Set up for observer/target and light time correction to between s/c // and target body. LightTimeCorrectionState ltState(*m_ikCode, this); ltState.checkSpkKernelsForAberrationCorrection(); vector<Distance> radius = m_target->radii(); Distance targetRadius((radius[0] + radius[2])/2.0); m_instrumentPosition = new SpacecraftPosition(*m_spkCode, *m_spkBodyCode, ltState, targetRadius); m_sunPosition = new SpicePosition(10, m_target->naifBodyCode()); // Check to see if we have nadir pointing that needs to be computed & // See if we have table blobs to load if (kernels["TargetPosition"][0].toUpper() == "TABLE") { Table t("SunPosition", lab.fileName(), lab); m_sunPosition->LoadCache(t); Table t2("BodyRotation", lab.fileName(), lab); m_bodyRotation->LoadCache(t2); if (t2.Label().hasKeyword("SolarLongitude")) { *m_solarLongitude = Longitude(t2.Label()["SolarLongitude"], Angle::Degrees); } else { solarLongitude(); } } // We can't assume InstrumentPointing & InstrumentPosition exist, old // files may be around with the old keywords, SpacecraftPointing & // SpacecraftPosition. The old keywords were in existance before the // Table option, so we don't need to check for Table under the old // keywords. if (kernels["InstrumentPointing"].size() == 0) { throw IException(IException::Unknown, "No camera pointing available", _FILEINFO_); } // 2009-03-18 Tracie Sucharski - Removed test for old keywords, any files // with the old keywords should be re-run through spiceinit. if (kernels["InstrumentPointing"][0].toUpper() == "NADIR") { if (m_instrumentRotation) { delete m_instrumentRotation; m_instrumentRotation = NULL; } m_instrumentRotation = new SpiceRotation(*m_ikCode, *m_spkBodyCode); } else if (kernels["InstrumentPointing"][0].toUpper() == "TABLE") { Table t("InstrumentPointing", lab.fileName(), lab); m_instrumentRotation->LoadCache(t); } if (kernels["InstrumentPosition"].size() == 0) { throw IException(IException::Unknown, "No instrument position available", _FILEINFO_); } if (kernels["InstrumentPosition"][0].toUpper() == "TABLE") { Table t("InstrumentPosition", lab.fileName(), lab); m_instrumentPosition->LoadCache(t); } NaifStatus::CheckErrors(); } /** * Loads/furnishes NAIF kernel(s) * * @param key PvlKeyword * @param noTables Indicates the use of tables. * * @throw Isis::IException::Io - "Spice file does not exist." */ void Spice::load(PvlKeyword &key, bool noTables) { NaifStatus::CheckErrors(); for (int i = 0; i < key.size(); i++) { if (key[i] == "") continue; if (key[i].toUpper() == "NULL") break; if (key[i].toUpper() == "NADIR") break; if (key[i].toUpper() == "TABLE" && !noTables) break; if (key[i].toUpper() == "TABLE" && noTables) continue; FileName file(key[i]); if (!file.fileExists()) { QString msg = "Spice file does not exist [" + file.expanded() + "]"; throw IException(IException::Io, msg, _FILEINFO_); } QString fileName = file.expanded(); furnsh_c(fileName.toLatin1().data()); m_kernels->push_back(key[i]); } NaifStatus::CheckErrors(); } /** * Destroys the Spice object */ Spice::~Spice() { NaifStatus::CheckErrors(); if (m_solarLongitude != NULL) { delete m_solarLongitude; m_solarLongitude = NULL; } if (m_et != NULL) { delete m_et; m_et = NULL; } if (m_startTime != NULL) { delete m_startTime; m_startTime = NULL; } if (m_endTime != NULL) { delete m_endTime; m_endTime = NULL; } if (m_cacheSize != NULL) { delete m_cacheSize; m_cacheSize = NULL; } if (m_startTimePadding != NULL) { delete m_startTimePadding; m_startTimePadding = NULL; } if (m_endTimePadding != NULL) { delete m_endTimePadding; m_endTimePadding = NULL; } if (m_instrumentPosition != NULL) { delete m_instrumentPosition; m_instrumentPosition = NULL; } if (m_instrumentRotation != NULL) { delete m_instrumentRotation; m_instrumentRotation = NULL; } if (m_sunPosition != NULL) { delete m_sunPosition; m_sunPosition = NULL; } if (m_bodyRotation != NULL) { delete m_bodyRotation; m_bodyRotation = NULL; } if (m_spkCode != NULL) { delete m_spkCode; m_spkCode = NULL; } if (m_ckCode != NULL) { delete m_ckCode; m_ckCode = NULL; } if (m_ikCode != NULL) { delete m_ikCode; m_ikCode = NULL; } if (m_sclkCode != NULL) { delete m_sclkCode; m_sclkCode = NULL; } if (m_spkBodyCode != NULL) { delete m_spkBodyCode; m_spkBodyCode = NULL; } if (m_bodyFrameCode != NULL) { delete m_bodyFrameCode; m_bodyFrameCode = NULL; } if (m_target != NULL) { delete m_target; m_target = NULL; } // Unload the kernels (TODO: Can this be done faster) for (int i = 0; m_kernels && i < m_kernels->size(); i++) { FileName file(m_kernels->at(i)); QString fileName = file.expanded(); unload_c(fileName.toLatin1().data()); } if (m_kernels != NULL) { delete m_kernels; m_kernels = NULL; } NaifStatus::CheckErrors(); } /** * This method creates an internal cache of spacecraft and sun positions over a * specified time range. The SPICE kernels are then immediately unloaded. This * allows multiple instances of the Spice object to be created as the NAIF * toolkit can clash if multiple sets of SPICE kernels are loaded. Note that * the cache size is specified as an argument. Therefore, times requested via * setTime() which are not directly loaded in the cache will be interpolated. * If the instrument position is not cached and cacheSize is greater than 3, * the tolerance is passed to the SpicePosition Memcache2HermiteCache() * method. * * @b Note: Before this method is called, the private variables m_cacheSize, * m_startTime and m_endTime must be set. This is done in the Camera classes * using the methods SetCacheSize() and SetStartEndEphemerisTime(). * * @param startTime Starting ephemeris time to cache * @param endTime Ending ephemeris time to cache * @param size Size of the cache. * @param tol Tolerance. * * @throw Isis::IException::Programmer - "Argument cacheSize must be greater * than zero" * @throw Isis::IException::Programmer - "Argument startTime must be less than * or equal to endTime" * @throw Isis::IException::User - "This instrument does not support time * padding" * * @internal * @history 2011-04-10 Debbie A. Cook - Updated to only create cache for * instrumentPosition if type is Spice. */ void Spice::createCache(iTime startTime, iTime endTime, int cacheSize, double tol) { NaifStatus::CheckErrors(); // Check for errors if (cacheSize <= 0) { QString msg = "Argument cacheSize must be greater than zero"; throw IException(IException::Programmer, msg, _FILEINFO_); } if (startTime > endTime) { QString msg = "Argument startTime must be less than or equal to endTime"; throw IException(IException::Programmer, msg, _FILEINFO_); } if (*m_cacheSize > 0) { QString msg = "A cache has already been created"; throw IException(IException::Programmer, msg, _FILEINFO_); } if (cacheSize == 1 && (*m_startTimePadding != 0 || *m_endTimePadding != 0)) { QString msg = "This instrument does not support time padding"; throw IException(IException::User, msg, _FILEINFO_); } string abcorr; if (getSpkAbCorrState(abcorr)) { instrumentPosition()->SetAberrationCorrection("NONE"); } iTime avgTime((startTime.Et() + endTime.Et()) / 2.0); computeSolarLongitude(avgTime); // Cache everything if (!m_bodyRotation->IsCached()) { int bodyRotationCacheSize = cacheSize; if (cacheSize > 2) bodyRotationCacheSize = 2; m_bodyRotation->LoadCache( startTime.Et() - *m_startTimePadding, endTime.Et() + *m_endTimePadding, bodyRotationCacheSize); } if (m_instrumentRotation->GetSource() < SpiceRotation::Memcache) { if (cacheSize > 3) m_instrumentRotation->MinimizeCache(SpiceRotation::Yes); m_instrumentRotation->LoadCache( startTime.Et() - *m_startTimePadding, endTime.Et() + *m_endTimePadding, cacheSize); } if (m_instrumentPosition->GetSource() < SpicePosition::Memcache) { m_instrumentPosition->LoadCache( startTime.Et() - *m_startTimePadding, endTime.Et() + *m_endTimePadding, cacheSize); if (cacheSize > 3) m_instrumentPosition->Memcache2HermiteCache(tol); } if (!m_sunPosition->IsCached()) { int sunPositionCacheSize = cacheSize; if (cacheSize > 2) sunPositionCacheSize = 2; m_sunPosition->LoadCache( startTime.Et() - *m_startTimePadding, endTime.Et() + *m_endTimePadding, sunPositionCacheSize); } // Save the time and cache size *m_startTime = startTime; *m_endTime = endTime; *m_cacheSize = cacheSize; m_et = NULL; // Unload the kernels (TODO: Can this be done faster) for (int i = 0; i < m_kernels->size(); i++) { FileName file(m_kernels->at(i)); QString fileName = file.expanded(); unload_c(fileName.toLatin1().data()); } m_kernels->clear(); NaifStatus::CheckErrors(); } /** * Accessor method for the cache start time. * @return @b iTime Start time for the image. * @author Steven Lambright * @internal * @history 2011-02-09 Steven Lambright - Original version. */ iTime Spice::cacheStartTime() const { if (m_startTime) { return *m_startTime; } return iTime(); } /** * Accessor method for the cache end time. * @return @b iTime End time for the image. * @author Steven Lambright * @internal * @history 2011-02-09 Steven Lambright - Original version. */ iTime Spice::cacheEndTime() const { if (m_endTime) { return *m_endTime; } return iTime(); } /** * Sets the ephemeris time and reads the spacecraft and sun position from the * kernels at that instant in time. * * @param et Ephemeris time (read NAIF documentation for a detailed * description) * * @see http://naif.jpl.nasa.gov/naif/ * @internal * @history 2005-11-29 Debbie A. Cook - Added alternate code for processing * instruments without a platform * @history 2011-02-09 Steven Lambright - Changed name from * SetEphemerisTime() */ void Spice::setTime(const iTime &et) { if (m_et == NULL) { m_et = new iTime(); // Before the Spice is cached, but after the camera aberration correction // is set, check to see if the instrument position kernel was created // by spkwriter. If so turn off aberration corrections because the camera // set aberration corrections are included in the spk already. string abcorr; if (*m_cacheSize == 0) { if (m_startTime->Et() == 0.0 && m_endTime->Et() == 0.0 && getSpkAbCorrState(abcorr)) { instrumentPosition()->SetAberrationCorrection("NONE"); } } } *m_et = et; m_bodyRotation->SetEphemerisTime(et.Et()); m_instrumentRotation->SetEphemerisTime(et.Et()); m_instrumentPosition->SetEphemerisTime(et.Et()); m_sunPosition->SetEphemerisTime(et.Et()); std::vector<double> uB = m_bodyRotation->ReferenceVector(m_sunPosition->Coordinate()); m_uB[0] = uB[0]; m_uB[1] = uB[1]; m_uB[2] = uB[2]; computeSolarLongitude(*m_et); } /** * Returns the spacecraft position in body-fixed frame km units. * * @param p[] Spacecraft position * * @see setTime() * * @throw Isis::iException::Programmer - "You must call SetTime first" */ void Spice::instrumentPosition(double p[3]) const { instrumentBodyFixedPosition(p); } /** * Returns the spacecraft position in body-fixed frame km units. * * @param p[] Spacecraft position * * @see setTime() * * @throw Isis::iException::Programmer - "You must call SetTime first" */ void Spice::instrumentBodyFixedPosition(double p[3]) const { if (m_et == NULL) { QString msg = "Unable to retrieve instrument's body fixed position." " Spice::SetTime must be called first."; throw IException(IException::Programmer, msg, _FILEINFO_); } std::vector<double> sB = m_bodyRotation->ReferenceVector(m_instrumentPosition->Coordinate()); p[0] = sB[0]; p[1] = sB[1]; p[2] = sB[2]; } /** * Returns the spacecraft velocity in body-fixed frame km/sec units. * * @param v[] Spacecraft velocity */ void Spice::instrumentBodyFixedVelocity(double v[3]) const { if (m_et == NULL) { QString msg = "Unable to retrieve instrument's body fixed velocity." " Spice::SetTime must be called first."; throw IException(IException::Programmer, msg, _FILEINFO_); } std::vector<double> state; state.push_back(m_instrumentPosition->Coordinate()[0]); state.push_back(m_instrumentPosition->Coordinate()[1]); state.push_back(m_instrumentPosition->Coordinate()[2]); state.push_back(m_instrumentPosition->Velocity()[0]); state.push_back(m_instrumentPosition->Velocity()[1]); state.push_back(m_instrumentPosition->Velocity()[2]); std::vector<double> vB = m_bodyRotation->ReferenceVector(state); v[0] = vB[3]; v[1] = vB[4]; v[2] = vB[5]; } /** * Returns the ephemeris time in seconds which was used to obtain the * spacecraft and sun positions. * * @return @b iTime the currently set ephemeris time * * @throws IException::Programmer "Unable to retrieve the time Spice::setTime must be called * first." */ iTime Spice::time() const { if (m_et == NULL) { QString msg = "Unable to retrieve the time." " Spice::SetTime must be called first."; throw IException(IException::Programmer, msg, _FILEINFO_); } return *m_et; } /** * Fills the input vector with sun position information, in either body-fixed * or J2000 reference frame and km units. * * @param p[] Sun position * * @see setTime() */ void Spice::sunPosition(double p[3]) const { if (m_et == NULL) { QString msg = "Unable to retrieve sun's position." " Spice::SetTime must be called first."; throw IException(IException::Programmer, msg, _FILEINFO_); } p[0] = m_uB[0]; p[1] = m_uB[1]; p[2] = m_uB[2]; } /** * Calculates and returns the distance from the spacecraft to the target center * * @return double Distance to the center of the target from the spacecraft */ double Spice::targetCenterDistance() const { std::vector<double> sB = m_bodyRotation->ReferenceVector(m_instrumentPosition->Coordinate()); return sqrt(pow(sB[0], 2) + pow(sB[1], 2) + pow(sB[2], 2)); } /** * Returns the radii of the body in km. The radii are obtained from the * appropriate SPICE kernel for the body specified by TargetName in the * Instrument group of the labels. * * @param r[] Radii of the target in kilometers */ void Spice::radii(Distance r[3]) const { for (int i = 0; i < 3; i++) r[i] =m_target->radii()[i]; } /** * This returns the NAIF body code of the target indicated in the labels. * * @return @b SpiceInt NAIF body code * */ SpiceInt Spice::naifBodyCode() const { return (int) m_target->naifBodyCode(); } /** * This returns the NAIF SPK code to use when reading from SPK kernels. * * @return @b SpiceInt NAIF SPK code */ SpiceInt Spice::naifSpkCode() const { return *m_spkCode; } /** * This returns the NAIF CK code to use when reading from CK kernels. * * @return @b SpiceInt NAIF CK code */ SpiceInt Spice::naifCkCode() const { return *m_ckCode; } /** * This returns the NAIF IK code to use when reading from instrument kernels. * * @return @b SpiceInt NAIF IK code */ SpiceInt Spice::naifIkCode() const { return *m_ikCode; } /** * This returns the NAIF SCLK code to use when reading from instrument * kernels. * * @return @b SpiceInt NAIF SCLK code */ SpiceInt Spice::naifSclkCode() const { return *m_sclkCode; } /** * This returns the NAIF body frame code. It is read from the labels, if it * exists. Otherwise, it's calculated by the init() method. * * @return @b SpiceInt NAIF body frame code * */ SpiceInt Spice::naifBodyFrameCode() const { return *m_bodyFrameCode; } /** * This returns the PvlObject that stores all of the requested Naif data * and can be a replacement for furnishing text kernels. */ PvlObject Spice::getStoredNaifKeywords() const { return *m_naifKeywords; } /** * Virtual method that returns the pixel resolution of the sensor in * meters/pix. * * @return @b double Resolution value of 1.0 */ double Spice::resolution() { return 1.; }; /** * This returns a value from the NAIF text pool. It is a static convience * * @param key Name of NAIF keyword to obtain from the pool * @param index If the keyword is an array, the element to obtain. * Defaults to 0 * * @return @b SpiceInt Spice integer from NAIF text pool * * @throw Isis::iException::Io - "Can not find key in instrument kernels */ SpiceInt Spice::getInteger(const QString &key, int index) { return readValue(key, SpiceIntType, index).toInt(); } /** * This returns a value from the NAIF text pool. It is a static convience method * * @param key Name of NAIF keyword to obtain from the pool * @param index If the keyword is an array, the element to obtain. Defaults to 0 * * @return @b SpiceDouble Spice double from NAIF text pool * * @throw Isis::iException::Io - "Can not find key in instrument kernels." */ SpiceDouble Spice::getDouble(const QString &key, int index) { return readValue(key, SpiceDoubleType, index).toDouble(); } /** * This converts the spacecraft clock ticks value (clockValue) to an iTime. * * Use this when possible because naif calls (such as scs2e_c) cannot be * called when not using naif. */ iTime Spice::getClockTime(QString clockValue, int sclkCode) { if (sclkCode == -1) { sclkCode = naifSclkCode(); } iTime result; QString key = "CLOCK_ET_" + Isis::toString(sclkCode) + "_" + clockValue; QVariant storedClockTime = getStoredResult(key, SpiceDoubleType); if (storedClockTime.isNull()) { SpiceDouble timeOutput; NaifStatus::CheckErrors(); scs2e_c(sclkCode, clockValue.toLatin1().data(), &timeOutput); NaifStatus::CheckErrors(); storedClockTime = timeOutput; storeResult(key, SpiceDoubleType, timeOutput); } result = storedClockTime.toDouble(); return result; } /** * This should be used for reading ALL text naif kernel values. This will * read it from Naif if we're using naif/not attached kernels. If we have * attached kernels and a NaifKeywords label object we will grab it from * there instead. This allows us to not furnish kernels after spiceinit. * * @param key The naif keyword,value name * @param type The naif value's primitive type * @param index The index into the naif keyword array to read */ QVariant Spice::readValue(QString key, SpiceValueType type, int index) { QVariant result; if (m_usingNaif) { NaifStatus::CheckErrors(); // This is the success status of the naif call SpiceBoolean found = false; // Naif tells us how many values were read, but we always just read one. // Use this variable to make naif happy. SpiceInt numValuesRead; if (type == SpiceDoubleType) { SpiceDouble kernelValue; gdpool_c(key.toLatin1().data(), (SpiceInt)index, 1, &numValuesRead, &kernelValue, &found); if (found) result = kernelValue; } else if (type == SpiceStringType) { char kernelValue[512]; gcpool_c(key.toLatin1().data(), (SpiceInt)index, 1, sizeof(kernelValue), &numValuesRead, kernelValue, &found); if (found) result = kernelValue; } else if (type == SpiceIntType) { SpiceInt kernelValue; gipool_c(key.toLatin1().data(), (SpiceInt)index, 1, &numValuesRead, &kernelValue, &found); if (found) result = (int)kernelValue; } if (!found) { QString msg = "Can not find [" + key + "] in text kernels"; throw IException(IException::Io, msg, _FILEINFO_); } storeValue(key, index, type, result); NaifStatus::CheckErrors(); } else { // Read from PvlObject that is our naif keywords result = readStoredValue(key, type, index); if (result.isNull()) { QString msg = "The camera is requesting spice data [" + key + "] that " "was not attached, please re-run spiceinit"; throw IException(IException::Unknown, msg, _FILEINFO_); } } return result; } void Spice::storeResult(QString name, SpiceValueType type, QVariant value) { if (type == SpiceDoubleType) { EndianSwapper swapper("LSB"); double doubleVal = value.toDouble(); doubleVal = swapper.Double(&doubleVal); QByteArray byteCode((char *) &doubleVal, sizeof(double)); value = byteCode; type = SpiceByteCodeType; } storeValue(name + "_COMPUTED", 0, type, value); } QVariant Spice::getStoredResult(QString name, SpiceValueType type) { bool wasDouble = false; if (type == SpiceDoubleType) { wasDouble = true; type = SpiceByteCodeType; } QVariant stored = readStoredValue(name + "_COMPUTED", type, 0); if (wasDouble && !stored.isNull()) { EndianSwapper swapper("LSB"); double doubleVal = swapper.Double((void *)QByteArray::fromHex( stored.toByteArray()).data()); stored = doubleVal; } return stored; } void Spice::storeValue(QString key, int index, SpiceValueType type, QVariant value) { if (!m_naifKeywords->hasKeyword(key)) { m_naifKeywords->addKeyword(PvlKeyword(key)); } PvlKeyword &storedKey = m_naifKeywords->findKeyword(key); while(index >= storedKey.size()) { storedKey.addValue(""); } if (type == SpiceByteCodeType) { storedKey[index] = QString(value.toByteArray().toHex().data()); } else if (type == SpiceStringType) { storedKey[index] = value.toString(); } else if (type == SpiceDoubleType) { storedKey[index] = toString(value.toDouble()); } else if (type == SpiceIntType) { storedKey[index] = toString(value.toInt()); } else { QString msg = "Unable to store variant in labels for key [" + key + "]"; throw IException(IException::Unknown, msg, _FILEINFO_); } } QVariant Spice::readStoredValue(QString key, SpiceValueType type, int index) { // Read from PvlObject that is our naif keywords QVariant result; if (m_naifKeywords->hasKeyword(key) && !m_usingNaif) { PvlKeyword &storedKeyword = m_naifKeywords->findKeyword(key); try { if (type == SpiceDoubleType) { result = toDouble(storedKeyword[index]); } else if (type == SpiceStringType) { result = storedKeyword[index]; } else if (type == SpiceByteCodeType || SpiceStringType) { result = storedKeyword[index].toLatin1(); } else if (type == SpiceIntType) { result = toInt(storedKeyword[index]); } } catch(IException &) { } } return result; } /** * This returns a value from the NAIF text pool. It is a static convience * method * * @param key Name of NAIF keyword to obtain from the pool * @param index If the keyword is an array, the element to obtain. Defaults to 0 * * @return @b QString Value from the NAIF text pool * * @throw Isis::IException::Io - "Can not find key in instrument kernels." */ QString Spice::getString(const QString &key, int index) { return readValue(key, SpiceStringType, index).toString(); } /** * Returns the sub-spacecraft latitude/longitude in universal coordinates * (0-360 positive east, ocentric) * * @param lat Sub-spacecraft latitude * * @param lon Sub-spacecraft longitude * * @see setTime() * @throw Isis::IException::Programmer - "You must call SetTime * first." */ void Spice::subSpacecraftPoint(double &lat, double &lon) { NaifStatus::CheckErrors(); if (m_et == NULL) { QString msg = "Unable to retrieve subspacecraft position." " Spice::SetTime must be called first."; throw IException(IException::Programmer, msg, _FILEINFO_); } SpiceDouble usB[3], dist; std::vector<double> vsB = m_bodyRotation->ReferenceVector(m_instrumentPosition->Coordinate()); SpiceDouble sB[3]; sB[0] = vsB[0]; sB[1] = vsB[1]; sB[2] = vsB[2]; unorm_c(sB, usB, &dist); std::vector<Distance> radii = target()->radii(); SpiceDouble a = radii[0].kilometers(); SpiceDouble b = radii[1].kilometers(); SpiceDouble c = radii[2].kilometers(); SpiceDouble originB[3]; originB[0] = originB[1] = originB[2] = 0.0; SpiceBoolean found; SpiceDouble subB[3]; surfpt_c(originB, usB, a, b, c, subB, &found); SpiceDouble mylon, mylat; reclat_c(subB, &a, &mylon, &mylat); lat = mylat * 180.0 / PI; lon = mylon * 180.0 / PI; if (lon < 0.0) lon += 360.0; NaifStatus::CheckErrors(); } /** * Returns the sub-solar latitude/longitude in universal coordinates (0-360 * positive east, ocentric) * * @param lat Sub-solar latitude * @param lon Sub-solar longitude * * @see setTime() * @throw Isis::IException::Programmer - "You must call SetTime * first." */ void Spice::subSolarPoint(double &lat, double &lon) { NaifStatus::CheckErrors(); if (m_et == NULL) { QString msg = "Unable to retrieve subsolar point." " Spice::SetTime must be called first."; throw IException(IException::Programmer, msg, _FILEINFO_); } SpiceDouble uuB[3], dist; unorm_c(m_uB, uuB, &dist); std::vector<Distance> radii = target()->radii(); SpiceDouble a = radii[0].kilometers(); SpiceDouble b = radii[1].kilometers(); SpiceDouble c = radii[2].kilometers(); SpiceDouble originB[3]; originB[0] = originB[1] = originB[2] = 0.0; SpiceBoolean found; SpiceDouble subB[3]; surfpt_c(originB, uuB, a, b, c, subB, &found); SpiceDouble mylon, mylat; reclat_c(subB, &a, &mylon, &mylat); lat = mylat * 180.0 / PI; lon = mylon * 180.0 / PI; if (lon < 0.0) lon += 360.0; NaifStatus::CheckErrors(); } /** * Returns a pointer to the target object * * @return string */ Target *Spice::target() const { return m_target; } /** * Returns the QString name of the target * * @return QString */ QString Spice::targetName() const { return m_target->name(); } /** * Computes the solar longitude for the given ephemeris time. If the target * is sky, the longitude is set to -999.0. * * @param et Ephemeris time */ void Spice::computeSolarLongitude(iTime et) { NaifStatus::CheckErrors(); if (m_target->isSky()) { *m_solarLongitude = Longitude(); return; } if (m_bodyRotation->IsCached()) return; double tipm[3][3], npole[3]; char frameName[32]; SpiceInt frameCode; SpiceBoolean found; cidfrm_c(*m_spkBodyCode, sizeof(frameName), &frameCode, frameName, &found); if (found) { pxform_c("J2000", frameName, et.Et(), tipm); } else { tipbod_c("J2000", *m_spkBodyCode, et.Et(), tipm); } for (int i = 0; i < 3; i++) { npole[i] = tipm[2][i]; } double state[6], lt; spkez_c(*m_spkBodyCode, et.Et(), "J2000", "NONE", 10, state, &lt); double uavel[3]; ucrss_c(state, &state[3], uavel); double x[3], y[3], z[3]; vequ_c(uavel, z); ucrss_c(npole, z, x); ucrss_c(z, x, y); double trans[3][3]; for (int i = 0; i < 3; i++) { trans[0][i] = x[i]; trans[1][i] = y[i]; trans[2][i] = z[i]; } spkez_c(10, et.Et(), "J2000", "LT+S", *m_spkBodyCode, state, &lt); double pos[3]; mxv_c(trans, state, pos); double radius, ls, lat; reclat_c(pos, &radius, &ls, &lat); *m_solarLongitude = Longitude(ls, Angle::Radians).force360Domain(); NaifStatus::CheckErrors(); } /** * Returns the solar longitude * * @return @b double The Solar Longitude */ Longitude Spice::solarLongitude() { if (m_et) { computeSolarLongitude(*m_et); return *m_solarLongitude; } return Longitude(); } /** * Returns true if the kernel group has kernel files * * @param lab Label containing Instrument and Kernels groups. * * @return @b bool status of kernel files in the kernel group */ bool Spice::hasKernels(Pvl &lab) { // Get the kernel group and check main kernels PvlGroup kernels = lab.findGroup("Kernels", Pvl::Traverse); std::vector<string> keywords; keywords.push_back("TargetPosition"); if (kernels.hasKeyword("SpacecraftPosition")) { keywords.push_back("SpacecraftPosition"); } else { keywords.push_back("InstrumentPosition"); } if (kernels.hasKeyword("SpacecraftPointing")) { keywords.push_back("SpacecraftPointing"); } else { keywords.push_back("InstrumentPointing"); } if (kernels.hasKeyword("Frame")) { keywords.push_back("Frame"); } if (kernels.hasKeyword("Extra")) { keywords.push_back("Extra"); } PvlKeyword key; for (int ikey = 0; ikey < (int) keywords.size(); ikey++) { key = kernels[ikey]; for (int i = 0; i < key.size(); i++) { if (key[i] == "") return false; if (key[i].toUpper() == "NULL") return false; if (key[i].toUpper() == "NADIR") return false; if (key[i].toUpper() == "TABLE") return false; } } return true; } /** * Returns true if time has been initialized. * * @author 2016-10-19 Kristin Berry * * @return @b bool true if time has been set */ bool Spice::isTimeSet(){ return !(m_et == NULL); } /** * Accessor method for the sun position. * @return @b iTime Sun position for the image. * @author Steven Lambright * @internal * @history 2011-02-09 Steven Lambright - Original version. */ SpicePosition *Spice::sunPosition() const { return m_sunPosition; } /** * Accessor method for the instrument position. * @return @b iTime Instrument position for the image. * @author Steven Lambright * @internal * @history 2011-02-09 Steven Lambright - Original version. */ SpicePosition *Spice::instrumentPosition() const { return m_instrumentPosition; } /** * Accessor method for the body rotation. * @return @b iTime Body rotation for the image. * @author Steven Lambright * @internal * @history 2011-02-09 Steven Lambright - Original version. */ SpiceRotation *Spice::bodyRotation() const { return m_bodyRotation; } /** * Accessor method for the instrument rotation. * @return @b iTime Instrument rotation for the image. * @author Steven Lambright * @internal * @history 2011-02-09 Steven Lambright - Original version. */ SpiceRotation *Spice::instrumentRotation() const { return m_instrumentRotation; } }
29.704254
101
0.626523
[ "object", "shape", "vector", "model", "transform" ]
8b4db6505d66fc842340da5ec3639149e87a9365
2,097
hpp
C++
include/codegen/include/Valve/VR/IVRSystem__GetButtonIdNameFromEnum.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Valve/VR/IVRSystem__GetButtonIdNameFromEnum.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Valve/VR/IVRSystem__GetButtonIdNameFromEnum.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:11 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" // Including type: Valve.VR.IVRSystem #include "Valve/VR/IVRSystem.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: Valve::VR namespace Valve::VR { // Forward declaring type: EVRButtonId struct EVRButtonId; } // Completed forward declares // Type namespace: Valve.VR namespace Valve::VR { // Autogenerated type: Valve.VR.IVRSystem/_GetButtonIdNameFromEnum class IVRSystem::_GetButtonIdNameFromEnum : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x16BA758 static IVRSystem::_GetButtonIdNameFromEnum* New_ctor(::Il2CppObject* object, System::IntPtr method); // public System.IntPtr Invoke(Valve.VR.EVRButtonId eButtonId) // Offset: 0x16BA76C System::IntPtr Invoke(Valve::VR::EVRButtonId eButtonId); // public System.IAsyncResult BeginInvoke(Valve.VR.EVRButtonId eButtonId, System.AsyncCallback callback, System.Object object) // Offset: 0x16BA9E0 System::IAsyncResult* BeginInvoke(Valve::VR::EVRButtonId eButtonId, System::AsyncCallback* callback, ::Il2CppObject* object); // public System.IntPtr EndInvoke(System.IAsyncResult result) // Offset: 0x16BAA6C System::IntPtr EndInvoke(System::IAsyncResult* result); }; // Valve.VR.IVRSystem/_GetButtonIdNameFromEnum } DEFINE_IL2CPP_ARG_TYPE(Valve::VR::IVRSystem::_GetButtonIdNameFromEnum*, "Valve.VR", "IVRSystem/_GetButtonIdNameFromEnum"); #pragma pack(pop)
41.94
130
0.737244
[ "object" ]
8b4e2f67321315ada302b5742fd75dc4f3077c86
2,893
hpp
C++
liboh/plugins/ogre/MeshObject.hpp
princeofcode/sirikata
41d33a574934aea2d8a30ce3514509b7a4ec182e
[ "BSD-3-Clause" ]
1
2016-05-09T07:55:37.000Z
2016-05-09T07:55:37.000Z
liboh/plugins/ogre/MeshObject.hpp
princeofcode/sirikata
41d33a574934aea2d8a30ce3514509b7a4ec182e
[ "BSD-3-Clause" ]
null
null
null
liboh/plugins/ogre/MeshObject.hpp
princeofcode/sirikata
41d33a574934aea2d8a30ce3514509b7a4ec182e
[ "BSD-3-Clause" ]
null
null
null
/* Sirikata Graphical Object Host * MeshObject.hpp * * Copyright (c) 2009, Patrick Reiter Horn * 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 Sirikata 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 SIRIKATA_GRAPHICS_MESHOBJECT_HPP__ #define SIRIKATA_GRAPHICS_MESHOBJECT_HPP__ #include <oh/Platform.hpp> #include "options/Options.hpp" #include "OgreSystem.hpp" #include "OgrePlugin.hpp" #include <oh/ProxyMeshObject.hpp> #include <oh/MeshListener.hpp> #include "Entity.hpp" #include <OgreEntity.h> namespace Sirikata { namespace Graphics { class MeshObject : public Entity, public MeshListener { URI mMeshURI; void created(const Ogre::MeshPtr &mesh); Ogre::Entity *getOgreEntity() const { return static_cast<Ogre::Entity*const>(mOgreObject); } public: const ProxyMeshObject &getProxy() const { return *std::tr1::static_pointer_cast<const ProxyMeshObject>(mProxy); } MeshObject(OgreSystem *scene, const std::tr1::shared_ptr<const ProxyMeshObject> &pmo, const UUID &id); virtual ~MeshObject(); void meshChanged(const URI&meshFile); Vector3f getScale() const { return Vector3f(0,0,0);//fromOgre(getOgreEntity()->getScale()); } void setScale(const Vector3f &scale) { //getOgreEntity()->setScale(toOgre(scale)); } /* virtual bool loadMesh(const String&name){ return false; } */ }; } } #endif
31.445652
77
0.721742
[ "mesh", "object" ]
332de5a58520c5eee340df509d8b0aee0f23c7e3
12,969
cpp
C++
src/smppconnection.cpp
ichramm/opensmpp
b20ef2d09705070fb11c9898d1353999450e2ba1
[ "MIT" ]
null
null
null
src/smppconnection.cpp
ichramm/opensmpp
b20ef2d09705070fb11c9898d1353999450e2ba1
[ "MIT" ]
null
null
null
src/smppconnection.cpp
ichramm/opensmpp
b20ef2d09705070fb11c9898d1353999450e2ba1
[ "MIT" ]
null
null
null
/*! * \file smppconnection.cpp * \author ichramm */ #include "stdafx.h" #include "smppconnection.hpp" #include "smppcommands.hpp" #include "logger.h" #include <boost/lexical_cast.hpp> #include <boost/make_shared.hpp> #include <cstdlib> //#define DISABLE_SMPP_BUFFER_DUMP #if !defined(DUMP_BUFFER_SIZE) #define DUMP_BUFFER_SIZE 8192 #endif #if GCC_VERSION > 0 __thread char __dump_buffer[DUMP_BUFFER_SIZE]; #define DUMP_SMPP_PDU(connId, cmdId, pduptr, msg) do { \ if (0 == smpp34_dumpPdu( cmdId, (uint8_t *)__dump_buffer, DUMP_BUFFER_SIZE-1, pduptr)) \ fprintf(stderr, "Connection %d - %s:\n%s\n", connId, msg, __dump_buffer); \ } while(0) #define DUMP_SMPP_BUFFER(connId, msg, inbuff, inbufflen) do { \ if (0 == smpp34_dumpBuf((uint8_t *)__dump_buffer, DUMP_BUFFER_SIZE-1, (uint8_t *)inbuff, inbufflen)) \ fprintf(stderr, "Connection %d - %s:\n%s\n", connId, msg, __dump_buffer); \ } while (0) #elif defined(_WIN32) extern DWORD dwTlsIndexDumpBuffer; #define ENSURE_BUFFER() \ char *__dump_buffer = (char *)TlsGetValue(dwTlsIndexDumpBuffer); \ if (__dump_buffer == NULL) { \ __dump_buffer = (char *)LocalAlloc(LPTR, DUMP_BUFFER_SIZE); \ TlsSetValue(dwTlsIndexDumpBuffer, (LPVOID)__dump_buffer); \ } #define DUMP_SMPP_PDU(connId, cmdId, pduptr, msg) do { \ ENSURE_BUFFER() \ if (0 == smpp34_dumpPdu( cmdId, (uint8_t *)__dump_buffer, DUMP_BUFFER_SIZE-1, pduptr)) \ fprintf(stderr, "Connection %d - %s:\n%s\n", connId, msg, __dump_buffer); \ } while (0) #define DUMP_SMPP_BUFFER(connId, msg, inbuff, inbufflen) do { \ ENSURE_BUFFER() \ if (0 == smpp34_dumpBuf((uint8_t *)__dump_buffer, DUMP_BUFFER_SIZE-1, (uint8_t *)inbuff, inbufflen)) \ fprintf(stderr, "Connection %d - %s:\n%s\n", connId, msg, __dump_buffer); \ } while (0) #endif // default response timeout #ifndef RESPONSE_TIMEOUT #define RESPONSE_TIMEOUT ((unsigned int)40) #endif // defines a range for initial randomized sequence numbers #ifndef SEQ_NUM_INITIAL_RANGE #define SEQ_NUM_INITIAL_RANGE 0x00004000 #endif // creates a randomized number from 1 to SEQ_NUM_INITIAL_RANGE #define INITIAL_SEQ_NUMBER() ((unsigned int)(rand() % SEQ_NUM_INITIAL_RANGE + 1)) using namespace std; using namespace boost; namespace opensmpp { CSMPPConnection::CSMPPConnection(unsigned int connectionId, ioservice_t &ioservice, const NewCommandCallback& onNewData, const ConnectionLostCallback& onConnectionLost) : m_connectionId(connectionId), m_nextSequenceNumber(INITIAL_SEQ_NUMBER()), m_connectionError(false), m_closeRequested(false), m_ioservice(ioservice), m_socket(m_ioservice), m_onNewDataEvent(onNewData), m_onConnectionLostEvent(onConnectionLost) { SMPP_TRACE(); } CSMPPConnection::~CSMPPConnection() { SMPP_TRACE(); Close(); } socket_t& CSMPPConnection::socket() { return m_socket; } unsigned int CSMPPConnection::GetConnectionId() const { return m_connectionId; } unsigned int CSMPPConnection::NextSequenceNumber() { SMPP_TRACE(); lock_guard<recursive_mutex> lock(m_mutex); m_nextSequenceNumber++; if (m_nextSequenceNumber == UINT_MAX) { m_nextSequenceNumber = INITIAL_SEQ_NUMBER(); } return m_nextSequenceNumber; } void CSMPPConnection::Close() { lock_guard<recursive_mutex> lock(m_mutex); if (m_closeRequested) { return; } smpp_log_profile("Connection %u: Closing socket", m_connectionId); m_closeRequested = true; if(m_socket.is_open()) { boost::system::error_code err; m_socket.close(err); } m_connectionError = false; m_pendingResponses.clear(); } void CSMPPConnection::ReadAsync() { SMPP_TRACE(); asio::async_read(socket(), asio::buffer(&m_pduHeader, sizeof(PDUHeader)), bind(&CSMPPConnection::ReadHandler, shared_from_this(), asio::placeholders::error) ); } int CSMPPConnection::SendRequest(shared_ptr<ISMPPCommand> cmd) { SMPP_TRACE(); recursive_mutex::scoped_lock lock(m_mutex); int res = SendPDU(cmd, false); if(res != RESULT_OK) { smpp_log_warning("Connection %u: Failed to send PDU of type %#X", m_connectionId, cmd->request_id()); return res; } PendingResponse respdata = {cmd, new condition()}; m_pendingResponses[cmd->sequence_number()] = respdata; bool timed_out = !respdata.condition->timed_wait(lock, posix_time::seconds(RESPONSE_TIMEOUT)); m_pendingResponses.erase(cmd->sequence_number()); delete respdata.condition; if(timed_out) { return RESULT_TIMEOUT; } if(m_connectionError) { return RESULT_NETERROR; } if(-1 == cmd->command_status()) { return RESULT_INVRESP; } return RESULT_OK; } int CSMPPConnection::SendResponse(shared_ptr<ISMPPCommand> cmd) { SMPP_TRACE(); lock_guard<recursive_mutex> lock(m_mutex); return SendPDU(cmd, true); } int CSMPPConnection::SendPDU(shared_ptr<ISMPPCommand> cmd, bool response) { SMPP_TRACE(); if(!socket().is_open()) { return RESULT_NETERROR; } unsigned int (ISMPPCommand::*pack_fn)(char*, unsigned int, int&); if(response) { // select the proper function and dump the response pdu pack_fn = &ISMPPCommand::pack_response; DUMP_SMPP_PDU(m_connectionId, cmd->response_id(), cmd->response_ptr(), "Sending PDU"); } else { pack_fn = &ISMPPCommand::pack_request; DUMP_SMPP_PDU(m_connectionId, cmd->request_id(), cmd->request_ptr(), "Sending PDU"); } int err; std::vector<char> buffer(256); unsigned int len = ((*cmd).*pack_fn)(&buffer[0], buffer.size(), err); while(-1 == err && buffer.size() < (2 << 11) ) // 4096 bytes max { buffer.resize(buffer.size()*2); len = ((*cmd).*pack_fn)(&buffer[0], buffer.size(), err); } if(err == -1) { smpp_log_error("Connection %u: Failed to unpack pDU", m_connectionId); return RESULT_SYSERROR; } if (len < buffer.size()) { // len cannot be bigger than size() buffer.resize(len); } try { asio::write(socket(), asio::buffer(&buffer[0], len)); return RESULT_OK; } catch (const std::exception& e) { smpp_log_error("Failed to call asio::write: %s", e.what()); return RESULT_NETERROR; } } void CSMPPConnection::ReadHandler(const boost::system::error_code& error) { smpp_log_warning("Connection %u", m_connectionId); recursive_mutex::scoped_lock lock(m_mutex); if(error) { m_connectionError = true; MapPendingResponse::iterator it = m_pendingResponses.begin(); for ( ; it != m_pendingResponses.end(); it++) { it->second.command->command_status(-1); it->second.condition->notify_one(); } if (!m_closeRequested) { smpp_log_warning("Connection %u: Network error: %s", m_connectionId, error.message().c_str()); try { Close(); lock.unlock(); m_onConnectionLostEvent(shared_from_this()); } catch (const std::exception &e) { smpp_log_warning("Connection %u: Error cleaning up: %s", m_connectionId, e.what()); } } return; } unsigned int commandId = ntohl(m_pduHeader.command_id); unsigned int seqNumber = ntohl(m_pduHeader.sequence_number); unsigned int commandLength = ntohl(m_pduHeader.command_length); try { std::string pdu((char *)&m_pduHeader, sizeof(PDUHeader)); if (commandLength > sizeof(PDUHeader)) { // read PDU body pdu.resize(commandLength, 0); asio::read(socket(), asio::buffer(&pdu[0]+sizeof(PDUHeader), pdu.size() - sizeof(PDUHeader))); } DUMP_SMPP_BUFFER(m_connectionId, "Read buffer", &pdu[0], pdu.size()); if (commandId & SMPP_RESPONSE_BIT) { // response packet if(m_pendingResponses.count(seqNumber)) { // someone is waiting for this packet (to be honest, there are not so many people using this API, but is good for self-esteem) int err; shared_ptr<ISMPPCommand> cmd = m_pendingResponses[seqNumber].command; if( (commandId & SUBMIT_SM) == SUBMIT_SM) { // Handle non-standard response PDU's size_t nullPos = pdu.find_first_of('\0', SMPP_HEADER_SIZE); // look for the first NULL starting after the header if(nullPos != string::npos && nullPos < pdu.size()-1) { // make sure message_id is the last field pdu.resize(nullPos+1, 0); uint32_t tmp = htonl(pdu.size()); memcpy(&pdu[0], &tmp, sizeof(uint32_t)); } } cmd->unpack_response(&pdu[0], pdu.size(), err); if (err) { // this should not happen, I suppose... cmd->command_status(-1); } else { // ok, now we are ready to see the packet in a human readable format DUMP_SMPP_PDU(m_connectionId, cmd->response_id(), cmd->response_ptr(), "Read PDU"); } // tell the guy on the door that his response has come... m_pendingResponses[seqNumber].condition->notify_one(); } else { // ups, what is going on here? smpp_log_warning("Connection %u: Unexpected PDU response: cmd[%#x], seqnumber[%d]", m_connectionId, commandId, seqNumber); } } else if(m_onNewDataEvent) { // new packet shared_ptr<ISMPPCommand> cmd = CreateCommandFromBuffer(commandId, seqNumber, pdu); if(cmd) { DUMP_SMPP_PDU(m_connectionId, cmd->request_id(), cmd->request_ptr(), "Read PDU"); // We should not wait until the callback returns, must start reading before that ReadAsync(); lock.unlock(); m_onNewDataEvent(shared_from_this(), cmd); return; // we dont want to call ReadAsync() twice! } else { // failed to unpack the buffer? You gotta be kidding me! shared_ptr<ISMPPCommand> cmd(new CSMPPGenericNack(seqNumber)); SendPDU(cmd, true); } } else { // no handler? this is evil... ok, send a NO-ACK and forget about it shared_ptr<ISMPPCommand> cmd(new CSMPPGenericNack(seqNumber)); SendPDU(cmd, true); } // keep reading! ReadAsync(); } catch (const std::exception &e) { // I think the only one who could throw exception is asio::read, but you can never be sure ... if (!m_closeRequested) { // if the connection was closed the read fails, so ignore this error smpp_log_warning("Connection %u: Something failed while reading, the exception message is: %s", m_connectionId, e.what()); if (commandId & SMPP_RESPONSE_BIT) { m_pendingResponses[seqNumber].command->command_status(-1); m_pendingResponses[seqNumber].condition->notify_one(); } Close(); } } } shared_ptr<ISMPPCommand> CSMPPConnection::CreateCommandFromBuffer(unsigned int commandId, unsigned int seqNumber, const std::string &buffer) { shared_ptr<ISMPPCommand> res; switch (commandId) { case BIND_RECEIVER: res.reset(new CBindReceiver(seqNumber)); break; case BIND_TRANSMITTER: res.reset(new CBindTransmitter(seqNumber)); break; case BIND_TRANSCEIVER: res.reset(new CBindTransceiver(seqNumber)); break; case UNBIND: res.reset(new CSMPPUnbind(seqNumber)); break; case SUBMIT_SM: res.reset(new CSMPPSubmitSingle(seqNumber)); break; case ENQUIRE_LINK: res.reset(new CSMPPEnquireLink(seqNumber)); break; case DELIVER_SM: res.reset(new CSMPPDelivery(seqNumber)); break; case QUERY_SM: case REPLACE_SM: case CANCEL_SM: case SUBMIT_MULTI: default: res.reset(new CSMPPGenericNack(seqNumber)); break; } if(res->request_id() != GENERIC_NACK) { int err; res->unpack_request(&buffer[0], buffer.size(), err); if(err) { // sorry, it didn't work res.reset(); } } return res; } /************************************************************************/ /************************************************************************/ static volatile unsigned int g_clientConnectionCounter = 1000; CSMPPClientConnection::CSMPPClientConnection(ioservice_t& ioservice, const NewCommandCallback& onNewData, const ConnectionLostCallback& onConnectionLost) : CSMPPConnection(++g_clientConnectionCounter, ioservice, onNewData, onConnectionLost) { SMPP_TRACE(); } int CSMPPClientConnection::Connect( const std::string server, unsigned short port ) { resolver_t resolver(m_ioservice); resolver_t::query query(server, lexical_cast<std::string>(port)); resolver_t::iterator endpoint_iterator = resolver.resolve(query); resolver_t::iterator end; boost::system::error_code error = asio::error::host_not_found; smpp_log_info("Connection %u: Connecting to server %s:%d", m_connectionId, server.c_str(), port); while (error && endpoint_iterator != end) { socket().close(); socket().connect(*endpoint_iterator++, error); } if (error) { smpp_log_warning("Connection %u: Cannot connect to host %s:%d: %s", m_connectionId, server.c_str(), port, error.message().c_str()); return -1; } m_connectionError = false; m_closeRequested = false; ReadAsync(); return 0; } CSMPPClientConnection::~CSMPPClientConnection() { SMPP_TRACE(); } /************************************************************************/ /************************************************************************/ CSMPPServerConnection::CSMPPServerConnection(unsigned int connectionId, ioservice_t &ioservice, const NewCommandCallback& onNewData, const ConnectionLostCallback& onConnectionLost) : CSMPPConnection(connectionId, ioservice, onNewData, onConnectionLost) { SMPP_TRACE(); } CSMPPServerConnection::~CSMPPServerConnection() { SMPP_TRACE(); } } // namespace opensmpp
27.418605
140
0.70044
[ "vector" ]
332ea929456485d8c1d7f172cd24358dc3bea7ad
5,689
cpp
C++
test/feasibility_test_files/test_generate_data.cpp
stevenjj/icra2020locomanipulation
414085b68cc1b3b24f7b920b543bba9d95350c16
[ "MIT" ]
5
2020-01-06T11:43:18.000Z
2021-12-14T22:59:09.000Z
test/feasibility_test_files/test_generate_data.cpp
stevenjj/icra2020locomanipulation
414085b68cc1b3b24f7b920b543bba9d95350c16
[ "MIT" ]
null
null
null
test/feasibility_test_files/test_generate_data.cpp
stevenjj/icra2020locomanipulation
414085b68cc1b3b24f7b920b543bba9d95350c16
[ "MIT" ]
2
2020-09-03T16:08:34.000Z
2022-02-17T11:13:49.000Z
#include <iostream> #include <string> #include <sstream> #include <avatar_locomanipulation/feasibility/feasibility_data_generator.hpp> #include <avatar_locomanipulation/bridge/rviz_visualizer.hpp> void initialize_config(Eigen::VectorXd & q_init, std::shared_ptr<RobotModel> & robot_model){ Eigen::VectorXd q_start; q_start = Eigen::VectorXd::Zero(robot_model->getDimQ()); double theta = 0.0; Eigen::AngleAxis<double> aa(theta, Eigen::Vector3d(0.0, 0.0, 1.0)); Eigen::Quaternion<double> init_quat(1.0, 0.0, 0.0, 0.0); //Initialized to remember the w component comes first init_quat = aa; q_start[3] = init_quat.x(); q_start[4] = init_quat.y(); q_start[5] = init_quat.z(); q_start[6] = init_quat.w(); // Set up the quaternion in q q_start[2] = 1.0; // set z value to 1.0, this is the pelvis location q_start[robot_model->getJointIndex("leftHipPitch")] = -0.3; q_start[robot_model->getJointIndex("rightHipPitch")] = -0.3; q_start[robot_model->getJointIndex("leftKneePitch")] = 0.6; q_start[robot_model->getJointIndex("rightKneePitch")] = 0.6; q_start[robot_model->getJointIndex("leftAnklePitch")] = -0.3; q_start[robot_model->getJointIndex("rightAnklePitch")] = 0.0;//-0.3; q_start[robot_model->getJointIndex("rightShoulderPitch")] = 0.2; q_start[robot_model->getJointIndex("rightShoulderRoll")] = 1.1; q_start[robot_model->getJointIndex("rightElbowPitch")] = 1.0 ; //0.4; q_start[robot_model->getJointIndex("rightForearmYaw")] = 1.5; q_start[robot_model->getJointIndex("leftShoulderPitch")] = -0.2; q_start[robot_model->getJointIndex("leftShoulderRoll")] = -1.1; q_start[robot_model->getJointIndex("leftElbowPitch")] = -0.4; q_start[robot_model->getJointIndex("leftForearmYaw")] = 1.5; q_init = q_start; } void test_generate_and_visualize_N_contact_transition_data(int argc, char ** argv, int N_input, std::string yaml_file, bool visualize, bool generate_positive_data_only){ std::cout << "[Testing FeasibilityDataGenerator]" << std::endl; std::string filename = THIS_PACKAGE_PATH"models/valkyrie_simplified.urdf"; std::shared_ptr<RobotModel> robot_model(new RobotModel(filename)); Eigen::VectorXd q_ik_start; initialize_config(q_ik_start, robot_model); // Initialize feasibility data generator FeasibilityDataGenerator feas_data_gen; // Set the robot model feas_data_gen.setRobotModel(robot_model); // Set the initial IK configuration feas_data_gen.setStartingIKConfig(q_ik_start); // set the data data_gen_config_filename configuration file path std::string data_gen_config_filename = std::string(THIS_PACKAGE_PATH) + std::string("data_generation_yaml_configurations/") + yaml_file; feas_data_gen.loadParamFile(data_gen_config_filename); // Initialize and start the visualizer ros::init(argc, argv, "data_generation"); std::shared_ptr<ros::NodeHandle> ros_node(std::make_shared<ros::NodeHandle>()); RVizVisualizer visualizer(ros_node, robot_model); Eigen::VectorXd q_begin = q_ik_start; // Attempt to generate a contact transition data until success. Visualize each successful result. int N_positive_data_to_generate = N_input; // whether or not we only want to generate positive examples: if (generate_positive_data_only){ feas_data_gen.setGenerateOnlyPositiveExamples(true); } bool store_data = true; bool visualize_once = true; int generated_data_count = 0; while(generated_data_count < N_positive_data_to_generate){ // if we generate a data successfully, increment the counter if (feas_data_gen.generateContactTransitionData(store_data)){ generated_data_count++; std::cout << " Generated positive example # " << generated_data_count << std::endl; if (visualize){ std::cout << " Begin visualizing the trajectory..." << std::endl; // Get q_begin feas_data_gen.ctg->traj_q_config.get_pos(0, q_begin); // Visualize visualizer.visualizeConfigurationTrajectory(q_begin, feas_data_gen.ctg->traj_q_config, visualize_once); } } } } int main(int argc, char ** argv){ std::string yaml_filename = "right_hand_left_stance.yaml"; int N = 1; bool visualize = false; bool generate_positive_data_only = false; // for(int i = 0; i < argc; i++){ // std::cout << i << ", " << argv[i] << std::endl; // } if (argc > 5){ N = std::stoi(std::string(argv[1])); yaml_filename = std::string(argv[2]); std::stringstream ss_visualize(argv[3]); if (!(ss_visualize >> std::boolalpha >> visualize)){ std::cout << "3rd argument must be either true or false" << std::endl; return 0; } std::stringstream ss_pos_samples_only(argv[4]); if (!(ss_pos_samples_only >> std::boolalpha >> generate_positive_data_only)){ std::cout << "4th argument must be either true or false" << std::endl; return 0; } }else{ std::cout << "Expected 4 arguments: N(int) yaml_filename(string), visualize(bool) generate_positive_data_only(bool)" << std::endl; std::cout << "Using defaults. Perhaps look at the launch file launch_generate_training_data.launch" << std::endl; } std::cout << " Generating training data..." << std::endl; std::cout << " N = " << N << " , the number of positive samples to be generated" << std::endl; std::cout << " Loading yaml file: " << yaml_filename << std::endl; std::cout << " visualize = " << (visualize ? "true" : "false") << std::endl; std::cout << " generate_positive_data_only = " << (generate_positive_data_only ? "true" : "false") << std::endl; test_generate_and_visualize_N_contact_transition_data(argc, argv, N, yaml_filename, visualize, generate_positive_data_only); }
40.635714
169
0.711549
[ "model" ]
33313b8437152d34638c77cbf0f23403d6beef49
1,310
hpp
C++
include/grend/octree.hpp
grend3d/grend
379d8e7eac9953b6257f6b7de7b36fbced82e774
[ "MIT" ]
5
2021-03-11T08:34:56.000Z
2021-11-14T15:41:21.000Z
include/grend/octree.hpp
mushrom/grend
379d8e7eac9953b6257f6b7de7b36fbced82e774
[ "MIT" ]
1
2021-08-14T08:48:15.000Z
2021-08-14T10:25:42.000Z
include/grend/octree.hpp
mushrom/grend
379d8e7eac9953b6257f6b7de7b36fbced82e774
[ "MIT" ]
null
null
null
#pragma once #include <grend/glmIncludes.hpp> #include <grend/gameModel.hpp> #include <utility> #include <set> #include <stdint.h> namespace grendx { class octree { public: // // (not yet) 'double' is depth of collision (0 for non-colliding), // 'bool' is whether there's a collision // 'vec3' is the normal for the colliding node typedef std::pair<float, glm::vec3> collision; class node; octree(double _leaf_size=0.1 /* meters */) { leaf_size = _leaf_size; }; ~octree() {}; // TODO: clear() void grow(double size); void add_tri(const glm::vec3 tri[3], const glm::vec3 normals[3]); void add_model(gameModel::ptr mod, glm::mat4 transform); void set_leaf(glm::vec3 location, glm::vec3 normal); node *get_leaf(glm::vec3 location); uint32_t count_nodes(void); collision collides(glm::vec3 begin, glm::vec3 end); collision collides_sphere(glm::vec3 position, float radius); node *root = nullptr; unsigned levels = 0; double leaf_size; }; class octree::node { public: node() { for (unsigned i = 0; i < 8; i++) { subnodes[!!(i&1)][!!(i&2)][!!(i&4)] = nullptr; } } uint32_t count_nodes(void); node *subnodes[2][2][2]; /* [x][y][z] */ unsigned level = 0; glm::vec3 normals = {0, 0, 0}; size_t normal_samples = 0; }; // namespace grendx }
22.586207
71
0.648855
[ "transform" ]
33359da86fa86ea1317c5706d5b0604e6ee8a1a9
6,768
cpp
C++
src/catchup/CatchupWorkTests.cpp
distributedledgerinc/mxnc-stellar
e621584d490a75b6726efdb7433be482f129bdb0
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
5
2019-01-28T08:05:56.000Z
2020-07-23T03:33:16.000Z
src/catchup/CatchupWorkTests.cpp
distributedledgerinc/mxnc-stellar
e621584d490a75b6726efdb7433be482f129bdb0
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
1
2019-05-10T09:44:15.000Z
2019-05-17T10:24:02.000Z
src/catchup/CatchupWorkTests.cpp
distributedledgerinc/mxnc-stellar
e621584d490a75b6726efdb7433be482f129bdb0
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
3
2019-01-28T10:15:56.000Z
2019-05-02T05:31:59.000Z
// Copyright 2017 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "catchup/CatchupWorkTests.h" #include "catchup/CatchupConfiguration.h" #include "catchup/CatchupWork.h" #include "ledger/CheckpointRange.h" #include "test/TestUtils.h" #include "test/test.h" #include "util/Timer.h" #include <lib/catch.hpp> #include <lib/util/format.h> using namespace stellar; auto max = std::numeric_limits<uint32_t>::max(); namespace stellar { std::vector<std::pair<uint32_t, CatchupConfiguration>> gCatchupRangeCases{ // fresh database // catchup to ledger in middle of first checkpoint {1, {2, 0}}, {1, {2, 1}}, {1, {2, max}}, // catchup to ledger at the end of first checkpoint {1, {63, 0}}, {1, {63, 1}}, {1, {63, 2}}, {1, {63, max}}, // catchup to ledger at start of second checkpoint {1, {64, 0}}, {1, {64, 1}}, {1, {64, 2}}, {1, {64, 3}}, {1, {64, max}}, // catchup to ledger at end of some checkpoint {1, {191, 0}}, {1, {191, 1}}, {1, {191, 2}}, {1, {191, 65}}, {1, {191, 66}}, {1, {191, 128}}, {1, {191, max}}, // catchup to ledger at start of some checkpoint {1, {320, 0}}, {1, {320, 1}}, {1, {320, 2}}, {1, {320, 3}}, {1, {320, 66}}, {1, {320, 67}}, {1, {320, 319}}, {1, {320, 320}}, {1, {320, max}}, // almost one checkpoint in database // catchup to ledger at the end of first checkpoint {62, {63, 0}}, {62, {63, 1}}, {62, {63, 2}}, {62, {63, max}}, // catchup to ledger at start of second checkpoint {62, {64, 0}}, {62, {64, 1}}, {62, {64, max}}, // catchup to ledger at end of some checkpoint {62, {319, 0}}, {62, {319, 1}}, {62, {319, 65}}, {62, {319, 66}}, {62, {319, 129}}, {62, {319, 130}}, {62, {319, 319}}, {62, {319, max}}, // catchup to ledger at start of some checkpoint {62, {320, 0}}, {62, {320, 1}}, {62, {320, 66}}, {62, {320, 67}}, {62, {320, 319}}, {62, {320, 320}}, {62, {320, max}}, // one checkpoint in database // catchup to ledger at start of second checkpoint {63, {64, 0}}, {63, {64, 1}}, {63, {64, max}}, // catchup to ledger at end of some checkpoint {63, {319, 0}}, {63, {319, 1}}, {63, {319, 65}}, {63, {319, 66}}, {63, {319, 129}}, {63, {319, 130}}, {63, {319, 319}}, {63, {319, max}}, // catchup to ledger at start of some checkpoint {63, {320, 0}}, {63, {320, 1}}, {63, {320, 66}}, {63, {320, 67}}, {63, {320, 319}}, {63, {320, 320}}, {63, {320, max}}, // one checkpoint and one ledger in database // catchup to ledger at start of second checkpoint {64, {64, 0}}, {64, {64, 1}}, {64, {64, max}}, // catchup to ledger at end of some checkpoint {64, {319, 0}}, {64, {319, 1}}, {64, {319, 65}}, {64, {319, 66}}, {64, {319, 319}}, {64, {319, max}}, // catchup to ledger at start of some checkpoint {64, {320, 0}}, {64, {320, 1}}, {64, {320, 66}}, {64, {320, 67}}, {64, {320, 319}}, {64, {320, 320}}, {64, {320, max}}}; } TEST_CASE("compute CatchupRange from CatchupConfiguration", "[catchupWork]") { VirtualClock clock; auto app = createTestApplication(clock, getTestConfig()); auto& historyManager = app->getHistoryManager(); for (auto const& test : gCatchupRangeCases) { auto lastClosedLedger = test.first; auto configuration = test.second; auto sectionName = fmt::format( "lcl = {}, to ledger = {}, count = {}", lastClosedLedger, configuration.toLedger(), configuration.count()); SECTION(sectionName) { auto range = CatchupWork::makeCatchupRange( lastClosedLedger, configuration, historyManager); // we need to finish where we wanted to finish REQUIRE(configuration.toLedger() == range.first.last()); // if LCL was later than our first checkpoint, we would either // apply buckets at or before LCL, or do a lot of unnecessary // attempts to apply transactions REQUIRE(lastClosedLedger <= range.first.first()); if (range.second) { // this contains 1 bucket apply operation and // stopAt - firstCheckpoint ledger apply operations auto appliedCount = range.first.last() - range.first.first() + 1; // we aren't applying buckets just after lcl... REQUIRE(range.first.first() > lastClosedLedger + 1); // we are applying at least configuration.count() REQUIRE(appliedCount >= configuration.count()); if (std::numeric_limits<uint32_t>::max() - historyManager.getCheckpointFrequency() >= configuration.count()) { // but at most count + getCheckpointFrequency // doing more would mean we are doing non-needed work REQUIRE(appliedCount <= configuration.count() + historyManager.getCheckpointFrequency()); } } else { // if buckets are not applied we need to apply ledgers // starting from lastClosedLedger + 1, so lastClosedLedger + 1 // must be in first checkpoint auto checkpointRange = CheckpointRange{range.first, historyManager}; REQUIRE(lastClosedLedger + historyManager.getCheckpointFrequency() >= checkpointRange.first()); if (std::numeric_limits<uint32_t>::max() - historyManager.getCheckpointFrequency() >= configuration.count()) { // and we are applying at most count() + // getCheckpointFrequency() ledgers // more would mean we are doing non-needed work // less just means that lastClosedLedger is too close to // target ledger auto appliedCount = range.first.last() - lastClosedLedger; REQUIRE(appliedCount <= configuration.count() + historyManager.getCheckpointFrequency()); } } } } }
32.538462
78
0.521868
[ "vector" ]
33360367649950fb4b41bbd691303f66f7a7de8a
23,276
cpp
C++
Iyan3dEngineFiles/SGCloudRenderingHelper.cpp
codetiger/Iyan3d
259454d44d032004688d916b4afcd901d5dd7be1
[ "MIT" ]
28
2017-04-12T10:26:40.000Z
2021-12-29T11:46:37.000Z
iyan3d/trunk/Iyan3D-Android/app/src/main/jni/Iyan3dEngineFiles/SGCloudRenderingHelper.cpp
lanping100/Iyan3d
c21bb191cec06039a3f6e9b2f19381cbd7537757
[ "MIT" ]
24
2017-09-13T02:13:24.000Z
2022-02-20T02:56:42.000Z
iyan3d/trunk/Iyan3D-Android/app/src/main/jni/Iyan3dEngineFiles/SGCloudRenderingHelper.cpp
lanping100/Iyan3d
c21bb191cec06039a3f6e9b2f19381cbd7537757
[ "MIT" ]
16
2017-05-23T12:20:45.000Z
2021-03-11T06:54:32.000Z
// // SGCloudRenderingHelper.cpp // Iyan3D // // Created by karthik on 18/08/15. // Copyright (c) 2015 Smackall Games. All rights reserved. // #include "../SGEngine2/Core/Nodes/ParticleManager.h" #include "HeaderFiles/SGCloudRenderingHelper.h" SGCloudRenderingHelper::SGCloudRenderingHelper() { } bool SGCloudRenderingHelper::writeFrameData(SGEditorScene *scene , SceneManager *smgr, int frameId) { string outputFileName = FileHelper::getDocumentsDirectory() + to_string(frameId) + ".sgfd"; ofstream frameFilePtr(outputFileName , ios::binary); scene->renHelper->setRenderCameraOrientation(); Vector3 camPos = scene->renderCamera->getAbsolutePosition(); FileHelper::writeFloat(&frameFilePtr, camPos.x); FileHelper::writeFloat(&frameFilePtr, camPos.y); FileHelper::writeFloat(&frameFilePtr, camPos.z); Vector3 camTarget = scene->renderCamera->getTarget(); FileHelper::writeFloat(&frameFilePtr, camTarget.x); FileHelper::writeFloat(&frameFilePtr, camTarget.y); FileHelper::writeFloat(&frameFilePtr, camTarget.z); Vector3 camRotation = Vector3();//scene->nodes[NODE_CAMERA]->node->getRotation(); camRotation += 180.0f; FileHelper::writeFloat(&frameFilePtr, camRotation.x); FileHelper::writeFloat(&frameFilePtr, camRotation.y); FileHelper::writeFloat(&frameFilePtr, camRotation.z); FileHelper::writeFloat(&frameFilePtr, scene->nodes[NODE_CAMERA]->getProperty(FOV).value.x); // Camera FOV short nodesCount = (short)scene->nodes.size()-1; for (int i = 0; i < (int)scene->nodes.size(); i++) { if (!scene->nodes[i]->getProperty(VISIBILITY).value.x) { nodesCount--; } else if(scene->nodes[i]->getProperty(VISIBILITY).value.x && scene->nodes[i]->getType() == NODE_PARTICLES) { shared_ptr< ParticleManager > pNode = dynamic_pointer_cast<ParticleManager>(scene->nodes[i]->node); nodesCount += pNode->getParticlesCount() - 1; } } FileHelper::writeShort(&frameFilePtr, nodesCount); // Nodes Count for (int nodeId = 1; nodeId < (int)scene->nodes.size(); nodeId++) { SGCloudRenderingHelper *renderHelper = new SGCloudRenderingHelper(); if(scene->nodes[nodeId]->getType() == NODE_PARTICLES) { shared_ptr< ParticleManager > pNode = dynamic_pointer_cast<ParticleManager>(scene->nodes[nodeId]->node); for(int i = 0; i < 48; i++) { pNode->update(); // pNode->sortParticles(scene->renderCamera->getAbsolutePosition()); pNode->updateParticles(true, scene->renderCamera->getAbsolutePosition()); } Vector4* positions = pNode->getPositions(); Vector4 props = pNode->getParticleProps(); Vector4 sColor = pNode->startColor; Vector4 mColor = pNode->midColor; Vector4 eColor = pNode->endColor; for(int i = 0; i < pNode->getParticlesCount(); i++) { float percent = positions[i].w/float(props.x); float phase = float(percent > 0.5); Vector4 s = sColor * (1 - phase) + mColor * phase; Vector4 e = mColor * (1 - phase) + eColor * phase; float age = (percent * (1 - phase) + (percent - 0.5) * phase) * 2.0; Vector4 color = s * (1 - age) + e * age; renderHelper->writeNodeData(scene, nodeId, frameId, &frameFilePtr, i, color); } } else renderHelper->writeNodeData(scene, nodeId, frameId, &frameFilePtr); if(renderHelper) delete renderHelper; } frameFilePtr.close(); smgr->setActiveCamera(scene->viewCamera); return true; } void SGCloudRenderingHelper::writeNodeData(SGEditorScene *scene, int nodeId, int frameId, ofstream *frameFilePtr, int particleIndex, Vector4 pColor) { NODE_TYPE nodeType = scene->nodes[nodeId]->getType(); SGNode *thisNode = scene->nodes[nodeId]; if(thisNode->getProperty(VISIBILITY).value.x) { Vector4 vertColor = thisNode->getProperty(VERTEX_COLOR).value; Vector3 lightDir = Vector3(0.0, -1.0, 0.0); if(nodeType == NODE_ADDITIONAL_LIGHT) { FileHelper::writeFloat(frameFilePtr, thisNode->getProperty(SPECIFIC_FLOAT).value.x/DEFAULT_FADE_DISTANCE); // Emission } else FileHelper::writeFloat(frameFilePtr, (nodeType == NODE_LIGHT) ? 1.0 : 0.0); // Emission Vector3 lightColor = Vector3(0.0); if(nodeType == NODE_ADDITIONAL_LIGHT || nodeType == NODE_LIGHT) { FileHelper::writeInt(frameFilePtr, thisNode->getProperty(LIGHT_TYPE).value.x); Quaternion lightRot = KeyHelper::getKeyInterpolationForFrame<int, SGRotationKey, Quaternion>(frameId, scene->nodes[nodeId]->rotationKeys); Mat4 rotMat; rotMat.setRotation(lightRot); rotMat.rotateVect(lightDir); lightColor = KeyHelper::getKeyInterpolationForFrame<int, SGScaleKey, Vector3>(frameId, scene->nodes[nodeId]->scaleKeys); } FileHelper::writeFloat(frameFilePtr, lightColor.x); //Emission Color r FileHelper::writeFloat(frameFilePtr, lightColor.y); //Emission Color g FileHelper::writeFloat(frameFilePtr, lightColor.z); //Emission Color b FileHelper::writeFloat(frameFilePtr, 0.5); //Emission Radius if(nodeType == NODE_PARTICLES) { FileHelper::writeFloat(frameFilePtr, pColor.x); // Diffusion Color r FileHelper::writeFloat(frameFilePtr, pColor.y); // Diffusion Color g FileHelper::writeFloat(frameFilePtr, pColor.z); // Diffusion Color b } else { FileHelper::writeFloat(frameFilePtr, vertColor.x); // Diffusion Color r FileHelper::writeFloat(frameFilePtr, vertColor.y); // Diffusion Color g FileHelper::writeFloat(frameFilePtr, vertColor.z); // Diffusion Color b } if (nodeType == NODE_LIGHT || nodeType == NODE_ADDITIONAL_LIGHT) { FileHelper::writeFloat(frameFilePtr, lightDir.x); // LightDir FileHelper::writeFloat(frameFilePtr, lightDir.y); FileHelper::writeFloat(frameFilePtr, lightDir.z); } bool hasTexture = (nodeType == NODE_LIGHT || nodeType == NODE_ADDITIONAL_LIGHT || thisNode->getProperty(TEXTURE).fileName == "-1" || thisNode->getProperty(TEXTURE).fileName == "") ? false : true; FileHelper::writeBool(frameFilePtr, hasTexture); // Has Texture unsigned long lastSlashPos = (thisNode->getProperty(TEXTURE).fileName).find_last_of("\\/"); string textureFileName; if(string::npos != lastSlashPos) textureFileName = (thisNode->getProperty(TEXTURE).fileName).substr( lastSlashPos + 1) + ".png"; else textureFileName = thisNode->getProperty(TEXTURE).fileName + ".png"; FileHelper::writeString(frameFilePtr, textureFileName); // Texture File Name with extension FileHelper::writeFloat(frameFilePtr, scene->nodes[nodeId]->getProperty(REFLECTION).value.x); FileHelper::writeFloat(frameFilePtr, scene->nodes[nodeId]->getProperty(REFRACTION).value.x); FileHelper::writeFloat(frameFilePtr, scene->nodes[nodeId]->getProperty(TRANSPARENCY).value.x); FileHelper::writeBool(frameFilePtr, (nodeType == NODE_PARTICLES) ? false : scene->nodes[nodeId]->getProperty(LIGHTING).value.x); // node lighting FileHelper::writeBool(frameFilePtr, scene->nodes[nodeId]->smoothTexture); vector<TriangleData> trianglesData; if(nodeType == NODE_PARTICLES) trianglesData = calculateTriangleDataForParticleNode(thisNode, particleIndex); else trianglesData = calculateTriangleDataForNode(thisNode); FileHelper::writeInt(frameFilePtr, (int)trianglesData.size()); for (int index = 0; index < (int)trianglesData.size(); index++) { FileHelper::writeFloat(frameFilePtr, trianglesData[index].Pos1.x); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Pos1.y); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Pos1.z); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Pos2.x); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Pos2.y); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Pos2.z); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Pos3.x); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Pos3.y); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Pos3.z); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Normal1.x); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Normal1.y); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Normal1.z); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Normal2.x); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Normal2.y); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Normal2.z); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Normal3.x); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Normal3.y); FileHelper::writeFloat(frameFilePtr, trianglesData[index].Normal3.z); FileHelper::writeFloat(frameFilePtr, trianglesData[index].UV1.x); FileHelper::writeFloat(frameFilePtr, trianglesData[index].UV1.y); FileHelper::writeFloat(frameFilePtr, trianglesData[index].UV2.x); FileHelper::writeFloat(frameFilePtr, trianglesData[index].UV2.y); FileHelper::writeFloat(frameFilePtr, trianglesData[index].UV3.x); FileHelper::writeFloat(frameFilePtr, trianglesData[index].UV3.y); } } } vector<TriangleData> SGCloudRenderingHelper::calculateTriangleDataForNode(SGNode *sgNode) { vector<TriangleData> trianglesData; vector<vertexData> allverticesData; vector<unsigned int> highPolyIndices; //TODO Write according to new meshbuffer implementation if (sgNode->getType() == NODE_TEXT_SKIN || sgNode->getType() == NODE_RIG) { unsigned int verticesCount = dynamic_pointer_cast<AnimatedMeshNode>(sgNode->node)->getMesh()->getVerticesCount(); sgNode->node->updateAbsoluteTransformation(); sgNode->node->updateAbsoluteTransformationOfChildren(); dynamic_pointer_cast<AnimatedMeshNode>(sgNode->node)->update(); Mesh * currentMesh = dynamic_pointer_cast<AnimatedMeshNode>(sgNode->node)->getMesh(); unsigned int indicesCount = currentMesh->getTotalIndicesCount(); highPolyIndices = currentMesh->getTotalIndicesArray(); if(currentMesh->meshType == MESH_TYPE_HEAVY) { for (unsigned int index = 0; index < verticesCount; index++) { vertexDataHeavy *currentVertex = currentMesh->getHeavyVertexByIndex(index); allverticesData.push_back(calculateFinalVertexData(sgNode->node, currentVertex)); } } else { for (unsigned int index = 0; index < verticesCount; index++) { vertexData *currentVertex = currentMesh->getLiteVertexByIndex(index); allverticesData.push_back(calculateFinalVertexData(sgNode->node, currentVertex)); } } for(unsigned int i = 0; i < indicesCount; i+=3) { TriangleData tData; tData.Pos1 = allverticesData[highPolyIndices[i]].vertPosition; tData.Pos2 = allverticesData[highPolyIndices[i+1]].vertPosition; tData.Pos3 = allverticesData[highPolyIndices[i+2]].vertPosition; tData.Normal1 = allverticesData[highPolyIndices[i]].vertNormal; tData.Normal2 = allverticesData[highPolyIndices[i+1]].vertNormal; tData.Normal3 = allverticesData[highPolyIndices[i+2]].vertNormal; tData.UV1 = allverticesData[highPolyIndices[i]].texCoord1; tData.UV2 = allverticesData[highPolyIndices[i+1]].texCoord1; tData.UV3 = allverticesData[highPolyIndices[i+2]].texCoord1; trianglesData.push_back(tData); } } else { unsigned int verticesCount = dynamic_pointer_cast<MeshNode>(sgNode->node)->getMesh()->getVerticesCount(); Mesh * currentMesh = dynamic_pointer_cast<MeshNode>(sgNode->node)->getMesh(); unsigned int indicesCount = currentMesh->getTotalIndicesCount(); highPolyIndices = currentMesh->getTotalIndicesArray(); if(currentMesh->meshType == MESH_TYPE_HEAVY) { for (unsigned int index = 0; index < verticesCount; index++) { vertexDataHeavy *currentVertex = currentMesh->getHeavyVertexByIndex(index); allverticesData.push_back(calculateFinalVertexData(sgNode->node, currentVertex)); } } else { for (unsigned int index = 0; index < verticesCount; index++) { vertexData *currentVertex = currentMesh->getLiteVertexByIndex(index); allverticesData.push_back(calculateFinalVertexData(sgNode->node, currentVertex)); } } for(unsigned int i = 0; i < indicesCount; i+=3) { TriangleData tData; tData.Pos1 = allverticesData[highPolyIndices[i]].vertPosition; tData.Pos2 = allverticesData[highPolyIndices[i+1]].vertPosition; tData.Pos3 = allverticesData[highPolyIndices[i+2]].vertPosition; tData.Normal1 = allverticesData[highPolyIndices[i]].vertNormal; tData.Normal2 = allverticesData[highPolyIndices[i+1]].vertNormal; tData.Normal3 = allverticesData[highPolyIndices[i+2]].vertNormal; tData.UV1 = allverticesData[highPolyIndices[i]].texCoord1; tData.UV2 = allverticesData[highPolyIndices[i+1]].texCoord1; tData.UV3 = allverticesData[highPolyIndices[i+2]].texCoord1; trianglesData.push_back(tData); } } return trianglesData; } vector<TriangleData> SGCloudRenderingHelper::calculateTriangleDataForParticleNode(SGNode *sgNode, int index) { vector<TriangleData> trianglesData; vector<unsigned int> highPolyIndices; unsigned int verticesCount = dynamic_pointer_cast<MeshNode>(sgNode->node)->getMesh()->getVerticesCount(); Mesh * currentMesh = dynamic_pointer_cast<MeshNode>(sgNode->node)->getMesh(); unsigned int indicesCount = currentMesh->getTotalIndicesCount(); highPolyIndices = currentMesh->getTotalIndicesArray(); shared_ptr< ParticleManager > pNode = dynamic_pointer_cast<ParticleManager>(sgNode->node); highPolyIndices = currentMesh->getTotalIndicesArray(); Vector4* positions = pNode->getPositions(); Vector4* rotations = pNode->getRotations(); vector<vertexData> allverticesData; for (unsigned int i = 0; i < verticesCount; i++) { vertexData *currentVertex = currentMesh->getLiteVertexByIndex(i); allverticesData.push_back(calculateFinalVertexDataForParticle(sgNode->node, currentVertex, index, positions[index], rotations[index])); } for(unsigned int i = 0; i < indicesCount; i+=3) { TriangleData tData; tData.Pos1 = allverticesData[highPolyIndices[i]].vertPosition; tData.Pos2 = allverticesData[highPolyIndices[i+1]].vertPosition; tData.Pos3 = allverticesData[highPolyIndices[i+2]].vertPosition; tData.Normal1 = allverticesData[highPolyIndices[i]].vertNormal; tData.Normal2 = allverticesData[highPolyIndices[i+1]].vertNormal; tData.Normal3 = allverticesData[highPolyIndices[i+2]].vertNormal; tData.UV1 = allverticesData[highPolyIndices[i]].texCoord1; tData.UV2 = allverticesData[highPolyIndices[i+1]].texCoord1; tData.UV3 = allverticesData[highPolyIndices[i+2]].texCoord1; trianglesData.push_back(tData); } printf("\n Particles %d updated ", index); allverticesData.clear(); return trianglesData; } vertexData SGCloudRenderingHelper::calculateFinalVertexData(shared_ptr<Node> node , void * vertex) { vertexData finalVertData; Mesh * mesh = dynamic_pointer_cast<MeshNode>(node)->getMesh(); if (mesh->meshType == MESH_TYPE_HEAVY) { finalVertData.vertPosition = ((vertexDataHeavy*)vertex)->vertPosition; finalVertData.vertNormal = ((vertexDataHeavy*)vertex)->vertNormal; finalVertData.texCoord1 = ((vertexDataHeavy*)vertex)->texCoord1; SkinMesh *sMesh = (SkinMesh*)mesh; vector<Mat4> jointTransforms; for(int i = 0; i < (int)sMesh->joints->size(); ++i){ Mat4 JointVertexPull; JointVertexPull.setbyproduct((*sMesh->joints)[i]->GlobalAnimatedMatrix, (*sMesh->joints)[i]->GlobalInversedMatrix); jointTransforms.push_back(JointVertexPull); } calculateJointTransforms(((vertexDataHeavy*)vertex), jointTransforms, finalVertData.vertPosition, finalVertData.vertNormal); Vector4 finalPos = node->getModelMatrix() * Vector4(finalVertData.vertPosition , 1.0); Vector4 finalNorm = (node->getModelMatrix() * Vector4(finalVertData.vertNormal , 0.0).normalize()).normalize(); finalVertData.vertPosition = Vector3(finalPos.x , finalPos.y ,finalPos.z); finalVertData.vertNormal = Vector3(finalNorm.x , finalNorm.y , finalNorm.z); return finalVertData; } else { finalVertData.vertPosition = ((vertexData*)vertex)->vertPosition; finalVertData.vertNormal = ((vertexData*)vertex)->vertNormal; finalVertData.texCoord1 = ((vertexData*)vertex)->texCoord1; Mat4 model = node->getModelMatrix(); // printf("\n Translation %f %f %f ", model[12],model[13],model[14]); Vector4 finalPos = model * Vector4(finalVertData.vertPosition , 1.0); Vector4 finalNorm = (model * Vector4(finalVertData.vertNormal , 0.0).normalize()).normalize(); finalVertData.vertPosition = Vector3(finalPos.x , finalPos.y ,finalPos.z); finalVertData.vertNormal = Vector3(finalNorm.x , finalNorm.y , finalNorm.z); return finalVertData; } } vertexData SGCloudRenderingHelper::calculateFinalVertexDataForParticle(shared_ptr<Node> node , void * vertex, int index, Vector4 position, Vector4 rotation) { vertexData finalVertData; finalVertData.vertPosition = ((vertexData*)vertex)->vertPosition; finalVertData.vertNormal = ((vertexData*)vertex)->vertNormal; finalVertData.texCoord1 = ((vertexData*)vertex)->texCoord1; shared_ptr<ParticleManager> pNode = dynamic_pointer_cast<ParticleManager>(node); Vector4 props = pNode->getParticleProps(); Mat4 translation = Mat4(); translation.setElement(12, position.x); translation.setElement(13, position.y); translation.setElement(14, position.z); Mat4 rotationMat = Mat4(); float cr = cos(rotation.x); float sr = sin(rotation.x); float cp = cos(rotation.y); float sp = sin(rotation.y); float cy = cos(rotation.z); float sy = sin(rotation.z); rotationMat.setElement(0, (cp * cy)); rotationMat.setElement(1, (cp * sy)); rotationMat.setElement(2, -sp); float srsp = sr * sp; float crsp = cr * sp; rotationMat.setElement(4, srsp * cy - cr * sy); rotationMat.setElement(5, srsp * sy + cr * cy); rotationMat.setElement(6, sr * cp); rotationMat.setElement(8, crsp * cy + sr * sy); rotationMat.setElement(9, crsp * sy - sr * cy); rotationMat.setElement(10, cr * cp); float live = float(position.w > 0.0 && position.w <= float(props.x)); if(live <= 0.0) { for(int i = 0; i < 16; i ++) translation.setElement(i, 0); } Mat4 pModel = translation * rotationMat; Vector4 vPos = pModel * Vector4(finalVertData.vertPosition , 1.0); finalVertData.vertPosition = Vector3(vPos.x, vPos.y, vPos.z); return finalVertData; } void SGCloudRenderingHelper::calculateJointTransforms(vertexDataHeavy *vertex , vector<Mat4> jointTransforms , Vector3 &vertPosition, Vector3 &vertNormal) { Vector4 pos = Vector4(0.0); Vector4 nor = Vector4(0.0); int jointId = int(vertex->optionalData1.x); float strength = vertex->optionalData2.x ; if(jointId > 0){ pos = pos + (jointTransforms[jointId - 1] * Vector4(vertPosition,1.0)) * strength; nor = nor + (jointTransforms[jointId - 1] * Vector4(vertNormal,0.0)) * strength; }else{ pos = Vector4(vertPosition,1.0); nor = Vector4(vertNormal,0.0); } jointId = int(vertex->optionalData1.y); strength = vertex->optionalData2.y; if(jointId > 0){ pos = pos + (jointTransforms[jointId - 1] * Vector4(vertPosition,1.0)) * strength; nor = nor + (jointTransforms[jointId - 1] * Vector4(vertNormal,0.0)) * strength; } jointId = int( vertex->optionalData1.z); strength = vertex->optionalData2.z; if(jointId > 0){ pos = pos + (jointTransforms[jointId - 1] * Vector4(vertPosition,1.0)) * strength; nor = nor + (jointTransforms[jointId - 1] * Vector4(vertNormal,0.0)) * strength; } jointId = int( vertex->optionalData1.w); strength = vertex->optionalData2.w; if(jointId > 0){ pos = pos + (jointTransforms[jointId - 1] * Vector4(vertPosition,1.0)) * strength; nor = nor + (jointTransforms[jointId - 1] * Vector4(vertNormal,0.0)) * strength; } jointId = int( vertex->optionalData3.x); strength = vertex->optionalData4.x; if(jointId > 0){ pos = pos + (jointTransforms[jointId - 1] * Vector4(vertPosition,1.0)) * strength; nor = nor + (jointTransforms[jointId - 1] * Vector4(vertNormal,0.0)) * strength; } jointId = int( vertex->optionalData3.y); strength = vertex->optionalData4.y; if(jointId > 0){ pos = pos + (jointTransforms[jointId - 1] * Vector4(vertPosition,1.0)) * strength; nor = nor + (jointTransforms[jointId - 1] * Vector4(vertNormal,0.0)) * strength; } jointId = int( vertex->optionalData3.z); strength = vertex->optionalData4.z; if(jointId > 0){ pos = pos + (jointTransforms[jointId - 1] * Vector4(vertPosition,1.0)) * strength; nor = nor + (jointTransforms[jointId - 1] * Vector4(vertNormal,0.0)) * strength; } jointId = int( vertex->optionalData3.w); strength = vertex->optionalData4.w; if(jointId > 0){ pos = pos + (jointTransforms[jointId - 1] * Vector4(vertPosition,1.0)) * strength; nor = nor + (jointTransforms[jointId - 1] * Vector4(vertNormal,0.0)) * strength; } vertPosition = Vector3(pos.x , pos.y, pos.z); vertNormal = Vector3(nor.x, nor.y,nor.z); } void SGCloudRenderingHelper::copyMat(float* pointer,Mat4& mat){ for(int i = 0;i < 16;++i) *pointer++ = mat[i]; }
47.405295
204
0.65531
[ "mesh", "vector", "model" ]
333790574f46e5851c64e08877860da9a042b553
16,542
cc
C++
cpp/src/keyczar/base/json_reader.cc
nawien-sharma/keyczar
c55563bbd70f4b6fefc7444e296aab9894475f9a
[ "Apache-2.0" ]
null
null
null
cpp/src/keyczar/base/json_reader.cc
nawien-sharma/keyczar
c55563bbd70f4b6fefc7444e296aab9894475f9a
[ "Apache-2.0" ]
null
null
null
cpp/src/keyczar/base/json_reader.cc
nawien-sharma/keyczar
c55563bbd70f4b6fefc7444e296aab9894475f9a
[ "Apache-2.0" ]
1
2021-04-13T05:05:30.000Z
2021-04-13T05:05:30.000Z
// Copyright (c) 2006-2008 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 <keyczar/base/json_reader.h> #include <keyczar/base/logging.h> #include <keyczar/base/scoped_ptr.h> #include <keyczar/base/stl_util-inl.h> #include <keyczar/base/string_util.h> #include <keyczar/base/values.h> namespace keyczar { namespace base { static const JSONReader::Token kInvalidToken(JSONReader::Token::INVALID_TOKEN, 0, 0); } // namespace base } // namespace keyczar namespace { static const int kStackLimit = 100; inline int HexToInt(char c) { if ('0' <= c && c <= '9') { return c - '0'; } else if ('A' <= c && c <= 'F') { return c - 'A' + 10; } else if ('a' <= c && c <= 'f') { return c - 'a' + 10; } NOTREACHED(); return 0; } // A helper method for ParseNumberToken. It reads an int from the end of // token. The method returns false if there is no valid integer at the end of // the token. bool ReadInt(keyczar::base::JSONReader::Token& token, bool can_have_leading_zeros) { char first = token.NextChar(); int len = 0; // Read in more digits char c = first; while ('\0' != c && '0' <= c && c <= '9') { ++token.length; ++len; c = token.NextChar(); } // We need at least 1 digit. if (len == 0) return false; if (!can_have_leading_zeros && len > 1 && '0' == first) return false; return true; } // A helper method for ParseStringToken. It reads |digits| hex digits from the // token. If the sequence if digits is not valid (contains other characters), // the method returns false. bool ReadHexDigits(keyczar::base::JSONReader::Token& token, int digits) { for (int i = 1; i <= digits; ++i) { char c = *(token.begin + token.length + i); if ('\0' == c) return false; if (!(('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'))) { return false; } } token.length += digits; return true; } } // anonymous namespace namespace keyczar { namespace base { const char* JSONReader::kBadRootElementType = "Root value must be an array or object."; const char* JSONReader::kInvalidEscape = "Invalid escape sequence."; const char* JSONReader::kSyntaxError = "Syntax error."; const char* JSONReader::kTrailingComma = "Trailing comma not allowed."; const char* JSONReader::kTooMuchNesting = "Too much nesting."; const char* JSONReader::kUnexpectedDataAfterRoot = "Unexpected data after root element."; const char* JSONReader::kUnsupportedEncoding = "Unsupported encoding. JSON must be UTF-8."; const char* JSONReader::kUnquotedDictionaryKey = "Dictionary keys must be quoted."; /* static */ Value* JSONReader::Read(const std::string& json, bool allow_trailing_comma) { return ReadAndReturnError(json, allow_trailing_comma, NULL); } /* static */ Value* JSONReader::ReadAndReturnError(const std::string& json, bool allow_trailing_comma, std::string *error_message_out) { JSONReader reader = JSONReader(); Value* root = reader.JsonToValue(json, true, allow_trailing_comma); if (root) return root; if (error_message_out) *error_message_out = reader.error_message(); return NULL; } JSONReader::JSONReader() : start_pos_(NULL), json_pos_(NULL), stack_depth_(0), allow_trailing_comma_(false) {} Value* JSONReader::JsonToValue(const std::string& json, bool check_root, bool allow_trailing_comma) { // The input must be in UTF-8. if (!IsStringUTF8(json.c_str())) { error_message_ = kUnsupportedEncoding; return NULL; } start_pos_ = json.c_str(); json_pos_ = start_pos_; allow_trailing_comma_ = allow_trailing_comma; stack_depth_ = 0; error_message_.clear(); scoped_ptr<Value> root(BuildValue(check_root)); if (root.get()) { if (ParseToken().type == Token::END_OF_INPUT) { return root.release(); } else { SetErrorMessage(kUnexpectedDataAfterRoot, json_pos_); } } // Default to calling errors "syntax errors". if (error_message_.empty()) SetErrorMessage(kSyntaxError, json_pos_); return NULL; } Value* JSONReader::BuildValue(bool is_root) { ++stack_depth_; if (stack_depth_ > kStackLimit) { SetErrorMessage(kTooMuchNesting, json_pos_); return NULL; } Token token = ParseToken(); // The root token must be an array or an object. if (is_root && token.type != Token::OBJECT_BEGIN && token.type != Token::ARRAY_BEGIN) { SetErrorMessage(kBadRootElementType, json_pos_); return NULL; } scoped_ptr<Value> node; switch (token.type) { case Token::END_OF_INPUT: case Token::INVALID_TOKEN: return NULL; case Token::NULL_TOKEN: node.reset(Value::CreateNullValue()); break; case Token::BOOL_TRUE: node.reset(Value::CreateBooleanValue(true)); break; case Token::BOOL_FALSE: node.reset(Value::CreateBooleanValue(false)); break; case Token::NUMBER: node.reset(DecodeNumber(token)); if (!node.get()) return NULL; break; case Token::STRING: node.reset(DecodeString(token)); if (!node.get()) return NULL; break; case Token::ARRAY_BEGIN: { json_pos_ += token.length; token = ParseToken(); node.reset(new ListValue()); while (token.type != Token::ARRAY_END) { Value* array_node = BuildValue(false); if (!array_node) return NULL; static_cast<ListValue*>(node.get())->Append(array_node); // After a list value, we expect a comma or the end of the list. token = ParseToken(); if (token.type == Token::LIST_SEPARATOR) { json_pos_ += token.length; token = ParseToken(); // Trailing commas are invalid according to the JSON RFC, but some // consumers need the parsing leniency, so handle accordingly. if (token.type == Token::ARRAY_END) { if (!allow_trailing_comma_) { SetErrorMessage(kTrailingComma, json_pos_); return NULL; } // Trailing comma OK, stop parsing the Array. break; } } else if (token.type != Token::ARRAY_END) { // Unexpected value after list value. Bail out. return NULL; } } if (token.type != Token::ARRAY_END) { return NULL; } break; } case Token::OBJECT_BEGIN: { json_pos_ += token.length; token = ParseToken(); node.reset(new DictionaryValue); while (token.type != Token::OBJECT_END) { if (token.type != Token::STRING) { SetErrorMessage(kUnquotedDictionaryKey, json_pos_); return NULL; } scoped_ptr<Value> dict_key_value(DecodeString(token)); if (!dict_key_value.get()) return NULL; std::string dict_key; bool success = dict_key_value->GetAsString(&dict_key); DCHECK(success); json_pos_ += token.length; token = ParseToken(); if (token.type != Token::OBJECT_PAIR_SEPARATOR) return NULL; json_pos_ += token.length; token = ParseToken(); Value* dict_value = BuildValue(false); if (!dict_value) return NULL; static_cast<DictionaryValue*>(node.get())->Set(dict_key, dict_value); // After a key/value pair, we expect a comma or the end of the // object. token = ParseToken(); if (token.type == Token::LIST_SEPARATOR) { json_pos_ += token.length; token = ParseToken(); // Trailing commas are invalid according to the JSON RFC, but some // consumers need the parsing leniency, so handle accordingly. if (token.type == Token::OBJECT_END) { if (!allow_trailing_comma_) { SetErrorMessage(kTrailingComma, json_pos_); return NULL; } // Trailing comma OK, stop parsing the Object. break; } } else if (token.type != Token::OBJECT_END) { // Unexpected value after last object value. Bail out. return NULL; } } if (token.type != Token::OBJECT_END) return NULL; break; } default: // We got a token that's not a value. return NULL; } json_pos_ += token.length; --stack_depth_; return node.release(); } JSONReader::Token JSONReader::ParseNumberToken() { // We just grab the number here. We validate the size in DecodeNumber. // According to RFC4627, a valid number is: [minus] int [frac] [exp] Token token(Token::NUMBER, json_pos_, 0); char c = *json_pos_; if ('-' == c) { ++token.length; c = token.NextChar(); } if (!ReadInt(token, false)) return kInvalidToken; // Optional fraction part c = token.NextChar(); if ('.' == c) { ++token.length; if (!ReadInt(token, true)) return kInvalidToken; c = token.NextChar(); } // Optional exponent part if ('e' == c || 'E' == c) { ++token.length; c = token.NextChar(); if ('-' == c || '+' == c) { ++token.length; c = token.NextChar(); } if (!ReadInt(token, true)) return kInvalidToken; } return token; } Value* JSONReader::DecodeNumber(const Token& token) { const std::string num_string(token.begin, token.length); char* enptr = NULL; int num_int = strto32(num_string.c_str(), &enptr, 10); return Value::CreateIntegerValue(num_int); } JSONReader::Token JSONReader::ParseStringToken() { Token token(Token::STRING, json_pos_, 1); char c = token.NextChar(); while ('\0' != c) { if ('\\' == c) { ++token.length; c = token.NextChar(); // Make sure the escaped char is valid. switch (c) { case 'x': if (!ReadHexDigits(token, 2)) { SetErrorMessage(kInvalidEscape, json_pos_ + token.length); return kInvalidToken; } break; case 'u': if (!ReadHexDigits(token, 4)) { SetErrorMessage(kInvalidEscape, json_pos_ + token.length); return kInvalidToken; } break; case '\\': case '/': case 'b': case 'f': case 'n': case 'r': case 't': case 'v': case '"': break; default: SetErrorMessage(kInvalidEscape, json_pos_ + token.length); return kInvalidToken; } } else if ('"' == c) { ++token.length; return token; } ++token.length; c = token.NextChar(); } return kInvalidToken; } Value* JSONReader::DecodeString(const Token& token) { ScopedSafeString decoded_str(new std::string()); decoded_str->reserve(token.length - 2); for (int i = 1; i < token.length - 1; ++i) { char c = *(token.begin + i); if ('\\' == c) { ++i; c = *(token.begin + i); switch (c) { case '"': case '/': case '\\': decoded_str->push_back(c); break; case 'b': decoded_str->push_back('\b'); break; case 'f': decoded_str->push_back('\f'); break; case 'n': decoded_str->push_back('\n'); break; case 'r': decoded_str->push_back('\r'); break; case 't': decoded_str->push_back('\t'); break; case 'v': decoded_str->push_back('\v'); break; case 'x': decoded_str->push_back((HexToInt(*(token.begin + i + 1)) << 4) + HexToInt(*(token.begin + i + 2))); i += 2; break; case 'u': decoded_str->push_back((HexToInt(*(token.begin + i + 1)) << 12) + (HexToInt(*(token.begin + i + 2)) << 8) + (HexToInt(*(token.begin + i + 3)) << 4) + HexToInt(*(token.begin + i + 4))); i += 4; break; default: // We should only have valid strings at this point. If not, // ParseStringToken didn't do it's job. NOTREACHED(); return NULL; } } else { // Not escaped decoded_str->push_back(c); } } return Value::CreateStringValue(*decoded_str); } JSONReader::Token JSONReader::ParseToken() { static const std::string kNullString("null"); static const std::string kTrueString("true"); static const std::string kFalseString("false"); EatWhitespaceAndComments(); Token token(Token::INVALID_TOKEN, 0, 0); switch (*json_pos_) { case '\0': token.type = Token::END_OF_INPUT; break; case 'n': if (NextStringMatch(kNullString)) token = Token(Token::NULL_TOKEN, json_pos_, 4); break; case 't': if (NextStringMatch(kTrueString)) token = Token(Token::BOOL_TRUE, json_pos_, 4); break; case 'f': if (NextStringMatch(kFalseString)) token = Token(Token::BOOL_FALSE, json_pos_, 5); break; case '[': token = Token(Token::ARRAY_BEGIN, json_pos_, 1); break; case ']': token = Token(Token::ARRAY_END, json_pos_, 1); break; case ',': token = Token(Token::LIST_SEPARATOR, json_pos_, 1); break; case '{': token = Token(Token::OBJECT_BEGIN, json_pos_, 1); break; case '}': token = Token(Token::OBJECT_END, json_pos_, 1); break; case ':': token = Token(Token::OBJECT_PAIR_SEPARATOR, json_pos_, 1); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': token = ParseNumberToken(); break; case '"': token = ParseStringToken(); break; } return token; } bool JSONReader::NextStringMatch(const std::string& str) { for (size_t i = 0; i < str.length(); ++i) { if ('\0' == *json_pos_) return false; if (*(json_pos_ + i) != str[i]) return false; } return true; } void JSONReader::EatWhitespaceAndComments() { while ('\0' != *json_pos_) { switch (*json_pos_) { case ' ': case '\n': case '\r': case '\t': ++json_pos_; break; case '/': // TODO(tc): This isn't in the RFC so it should be a parser flag. if (!EatComment()) return; break; default: // Not a whitespace char, just exit. return; } } } bool JSONReader::EatComment() { if ('/' != *json_pos_) return false; char next_char = *(json_pos_ + 1); if ('/' == next_char) { // Line comment, read until \n or \r json_pos_ += 2; while ('\0' != *json_pos_) { switch (*json_pos_) { case '\n': case '\r': ++json_pos_; return true; default: ++json_pos_; } } } else if ('*' == next_char) { // Block comment, read until */ json_pos_ += 2; while ('\0' != *json_pos_) { switch (*json_pos_) { case '*': if ('/' == *(json_pos_ + 1)) { json_pos_ += 2; return true; } default: ++json_pos_; } } } else { return false; } return true; } void JSONReader::SetErrorMessage(const char* description, const char* error_pos) { int line_number = 1; int column_number = 1; // Figure out the line and column the error occured at. for (const char* pos = start_pos_; pos != error_pos; ++pos) { if (*pos == '\0') { NOTREACHED(); return; } if (*pos == '\n') { ++line_number; column_number = 1; } else { ++column_number; } } error_message_.append("Line: "); error_message_.append(IntToString(line_number)); error_message_.append(", column: "); error_message_.append(IntToString(column_number)); error_message_.append(description); error_message_.append("\n"); } } // namespace base } // namespace keyczar
26.132701
79
0.559848
[ "object" ]
333813c7a929b7c43c5ae956469e26658e768178
2,051
cpp
C++
sdk/packages/planner_cost/gems/polyline_distance_quadratic_cost.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
null
null
null
sdk/packages/planner_cost/gems/polyline_distance_quadratic_cost.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
null
null
null
sdk/packages/planner_cost/gems/polyline_distance_quadratic_cost.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2022-01-28T16:37:51.000Z
2022-01-28T16:37:51.000Z
/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #include "packages/planner_cost/gems/polyline_distance_quadratic_cost.hpp" #include "engine/core/math/types.hpp" #include "engine/gems/geometry/smooth_distance.hpp" namespace isaac { namespace planner_cost { double PolylineDistanceQuadraticCost::evaluate(double /*time*/, const VectorXd& state) { const double distance = geometry::SmoothDistanceToPolyline( polyline_, Vector2d(state[indices_[0]], state[indices_[1]])); return 0.5 * gain_ * distance * distance + state[indices_[2]] * speed_reward_; } void PolylineDistanceQuadraticCost::addGradient(double /*time*/, const VectorXd& state, Eigen::Ref<VectorXd> gradient) { Vector2d grad; const double distance = geometry::SmoothDistanceToPolyline( polyline_, Vector2d(state[indices_[0]], state[indices_[1]]), &grad); gradient[indices_[0]] += gain_ * distance * grad[0]; gradient[indices_[1]] += gain_ * distance * grad[1]; gradient[indices_[2]] += speed_reward_; } void PolylineDistanceQuadraticCost::addHessian(double /*time*/, const VectorXd& state, Eigen::Ref<MatrixXd> hessian) { Vector2d grad; (void)geometry::SmoothDistanceToPolyline( polyline_, Vector2d(state[indices_[0]], state[indices_[1]]), &grad); const double update_xy = gain_ * grad[0] * grad[1]; hessian(indices_[0], indices_[0]) += gain_ * grad[0] * grad[0]; hessian(indices_[0], indices_[1]) += update_xy; hessian(indices_[1], indices_[0]) += update_xy; hessian(indices_[1], indices_[1]) += gain_ * grad[1] * grad[1]; } } // namespace planner_cost } // namespace isaac
42.729167
88
0.71136
[ "geometry" ]
333e3ce55c5a6ff1a8d13259f709804c1fcec097
19,492
cpp
C++
libs/wave/samples/waveidl/idl.cpp
cpp-pm/boost
38c6c8c07f2fcc42d573b10807fef27ec14930f8
[ "BSL-1.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
libs/wave/samples/waveidl/idl.cpp
cpp-pm/boost
38c6c8c07f2fcc42d573b10807fef27ec14930f8
[ "BSL-1.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
libs/wave/samples/waveidl/idl.cpp
cpp-pm/boost
38c6c8c07f2fcc42d573b10807fef27ec14930f8
[ "BSL-1.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library Sample: IDL oriented preprocessor http://www.boost.org/ Copyright (c) 2001-2010 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #include "idl.hpp" // global configuration #include <boost/assert.hpp> #include <boost/program_options.hpp> #include <boost/filesystem/path.hpp> /////////////////////////////////////////////////////////////////////////////// // Include Wave itself #include <boost/wave.hpp> /////////////////////////////////////////////////////////////////////////////// // Include the lexer related stuff #include <boost/wave/cpplexer/cpp_lex_token.hpp> // token type #include "idllexer/idl_lex_iterator.hpp" // lexer type /////////////////////////////////////////////////////////////////////////////// // include lexer specifics, import lexer names // #if BOOST_WAVE_SEPARATE_LEXER_INSTANTIATION == 0 #include "idllexer/idl_re2c_lexer.hpp" #endif /////////////////////////////////////////////////////////////////////////////// // include the grammar definitions, if these shouldn't be compiled separately // (ATTENTION: _very_ large compilation times!) // #if BOOST_WAVE_SEPARATE_GRAMMAR_INSTANTIATION == 0 #include <boost/wave/grammars/cpp_intlit_grammar.hpp> #include <boost/wave/grammars/cpp_chlit_grammar.hpp> #include <boost/wave/grammars/cpp_grammar.hpp> #include <boost/wave/grammars/cpp_expression_grammar.hpp> #include <boost/wave/grammars/cpp_predef_macros_grammar.hpp> #include <boost/wave/grammars/cpp_defined_grammar.hpp> #endif /////////////////////////////////////////////////////////////////////////////// // import required names using namespace boost::spirit::classic; using std::string; using std::pair; using std::vector; using std::getline; using std::ifstream; using std::cout; using std::cerr; using std::endl; using std::ostream; using std::istreambuf_iterator; namespace po = boost::program_options; namespace fs = boost::filesystem; /////////////////////////////////////////////////////////////////////////////// // print the current version int print_version() { typedef boost::wave::idllexer::lex_iterator< boost::wave::cpplexer::lex_token<> > lex_iterator_type; typedef boost::wave::context<std::string::iterator, lex_iterator_type> context_type; string version (context_type::get_version_string()); cout << version.substr(1, version.size()-2) // strip quotes << " (" << IDL_VERSION_DATE << ")" // add date << endl; return 0; // exit app } /////////////////////////////////////////////////////////////////////////////// // print the copyright statement int print_copyright() { char const *copyright[] = { "", "Sample: IDL oriented preprocessor", "Based on: Wave, A Standard conformant C++ preprocessor library", "It is hosted by http://www.boost.org/.", "", "Copyright (c) 2001-2010 Hartmut Kaiser, Distributed under the Boost", "Software License, Version 1.0. (See accompanying file", "LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)", 0 }; for (int i = 0; 0 != copyright[i]; ++i) cout << copyright[i] << endl; return 0; // exit app } /////////////////////////////////////////////////////////////////////////////// namespace cmd_line_util { // Additional command line parser which interprets '@something' as an // option "config-file" with the value "something". pair<string, string> at_option_parser(string const&s) { if ('@' == s[0]) return std::make_pair(string("config-file"), s.substr(1)); else return pair<string, string>(); } // class, which keeps include file information read from the command line class include_paths { public: include_paths() : seen_separator(false) {} vector<string> paths; // stores user paths vector<string> syspaths; // stores system paths bool seen_separator; // command line contains a '-I-' option // Function which validates additional tokens from command line. static void validate(boost::any &v, vector<string> const &tokens) { if (v.empty()) v = boost::any(include_paths()); include_paths *p = boost::any_cast<include_paths>(&v); BOOST_ASSERT(p); // Assume only one path per '-I' occurrence. string t = tokens[0]; if (t == "-") { // found -I- option, so switch behaviour p->seen_separator = true; } else if (p->seen_separator) { // store this path as a system path p->syspaths.push_back(t); } else { // store this path as an user path p->paths.push_back(t); } } }; // Read all options from a given config file, parse and add them to the // given variables_map void read_config_file_options(string const &filename, po::options_description const &desc, po::variables_map &vm, bool may_fail = false) { ifstream ifs(filename.c_str()); if (!ifs.is_open()) { if (!may_fail) { cerr << filename << ": command line warning: config file not found" << endl; } return; } vector<string> options; string line; while (std::getline(ifs, line)) { // skip empty lines string::size_type pos = line.find_first_not_of(" \t"); if (pos == string::npos) continue; // skip comment lines if ('#' != line[pos]) options.push_back(line); } if (options.size() > 0) { using namespace boost::program_options::command_line_style; po::store(po::command_line_parser(options) .options(desc).style(unix_style).run(), vm); po::notify(vm); } } // predicate to extract all positional arguments from the command line struct is_argument { bool operator()(po::option const &opt) { return (opt.position_key == -1) ? true : false; } }; /////////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////// // // Special validator overload, which allows to handle the -I- syntax for // switching the semantics of an -I option. // /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace program_options { void validate(boost::any &v, std::vector<std::string> const &s, cmd_line_util::include_paths *, int) { cmd_line_util::include_paths::validate(v, s); } }} // namespace boost::program_options /////////////////////////////////////////////////////////////////////////////// // do the actual preprocessing int do_actual_work (std::string file_name, po::variables_map const &vm) { // current file position is saved for exception handling boost::wave::util::file_position_type current_position; try { // process the given file ifstream instream(file_name.c_str()); string instring; if (!instream.is_open()) { cerr << "waveidl: could not open input file: " << file_name << endl; return -1; } instream.unsetf(std::ios::skipws); #if defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS) // this is known to be very slow for large files on some systems copy (istream_iterator<char>(instream), istream_iterator<char>(), inserter(instring, instring.end())); #else instring = string(istreambuf_iterator<char>(instream.rdbuf()), istreambuf_iterator<char>()); #endif // This sample uses the lex_token type predefined in the Wave library, but // but uses a custom lexer type. typedef boost::wave::idllexer::lex_iterator< boost::wave::cpplexer::lex_token<> > lex_iterator_type; typedef boost::wave::context<std::string::iterator, lex_iterator_type> context_type; // The C++ preprocessor iterators shouldn't be constructed directly. They // are to be generated through a boost::wave::context<> object. This // boost::wave::context object is additionally to be used to initialize and // define different parameters of the actual preprocessing. // The preprocessing of the input stream is done on the fly behind the // scenes during iteration over the context_type::iterator_type stream. context_type ctx (instring.begin(), instring.end(), file_name.c_str()); // add include directories to the system include search paths if (vm.count("sysinclude")) { vector<string> const &syspaths = vm["sysinclude"].as<vector<string> >(); vector<string>::const_iterator end = syspaths.end(); for (vector<string>::const_iterator cit = syspaths.begin(); cit != end; ++cit) { ctx.add_sysinclude_path((*cit).c_str()); } } // add include directories to the include search paths if (vm.count("include")) { cmd_line_util::include_paths const &ip = vm["include"].as<cmd_line_util::include_paths>(); vector<string>::const_iterator end = ip.paths.end(); for (vector<string>::const_iterator cit = ip.paths.begin(); cit != end; ++cit) { ctx.add_include_path((*cit).c_str()); } // if on the command line was given -I- , this has to be propagated if (ip.seen_separator) ctx.set_sysinclude_delimiter(); // add system include directories to the include path vector<string>::const_iterator sysend = ip.syspaths.end(); for (vector<string>::const_iterator syscit = ip.syspaths.begin(); syscit != sysend; ++syscit) { ctx.add_sysinclude_path((*syscit).c_str()); } } // add additional defined macros if (vm.count("define")) { vector<string> const &macros = vm["define"].as<vector<string> >(); vector<string>::const_iterator end = macros.end(); for (vector<string>::const_iterator cit = macros.begin(); cit != end; ++cit) { ctx.add_macro_definition(*cit); } } // add additional predefined macros if (vm.count("predefine")) { vector<string> const &predefmacros = vm["predefine"].as<vector<string> >(); vector<string>::const_iterator end = predefmacros.end(); for (vector<string>::const_iterator cit = predefmacros.begin(); cit != end; ++cit) { ctx.add_macro_definition(*cit, true); } } // undefine specified macros if (vm.count("undefine")) { vector<string> const &undefmacros = vm["undefine"].as<vector<string> >(); vector<string>::const_iterator end = undefmacros.end(); for (vector<string>::const_iterator cit = undefmacros.begin(); cit != end; ++cit) { ctx.remove_macro_definition((*cit).c_str(), true); } } // open the output file std::ofstream output; if (vm.count("output")) { // try to open the file, where to put the preprocessed output string out_file (vm["output"].as<string>()); output.open(out_file.c_str()); if (!output.is_open()) { cerr << "waveidl: could not open output file: " << out_file << endl; return -1; } } else { // output the preprocessed result to std::cout output.copyfmt(cout); output.clear(cout.rdstate()); static_cast<std::basic_ios<char> &>(output).rdbuf(cout.rdbuf()); } // analyze the input file context_type::iterator_type first = ctx.begin(); context_type::iterator_type last = ctx.end(); // loop over all generated tokens outputing the generated text while (first != last) { // print out the string representation of this token (skip comments) using namespace boost::wave; // store the last known good token position current_position = (*first).get_position(); token_id id = token_id(*first); if (T_CPPCOMMENT == id || T_NEWLINE == id) { // C++ comment tokens contain the trailing newline output << endl; } else if (id != T_CCOMMENT) { // print out the current token value output << (*first).get_value(); } ++first; // advance to the next token } } catch (boost::wave::cpp_exception const& e) { // some preprocessing error cerr << e.file_name() << "(" << e.line_no() << "): " << e.description() << endl; return 1; } catch (boost::wave::cpplexer::lexing_exception const& e) { // some lexing error cerr << e.file_name() << "(" << e.line_no() << "): " << e.description() << endl; return 2; } catch (std::exception const& e) { // use last recognized token to retrieve the error position cerr << current_position.get_file() << "(" << current_position.get_line() << "): " << "exception caught: " << e.what() << endl; return 3; } catch (...) { // use last recognized token to retrieve the error position cerr << current_position.get_file() << "(" << current_position.get_line() << "): " << "unexpected exception caught." << endl; return 4; } return 0; } /////////////////////////////////////////////////////////////////////////////// // main entry point int main (int argc, char *argv[]) { try { // analyze the command line options and arguments // declare the options allowed from the command line only po::options_description desc_cmdline ("Options allowed on the command line only"); desc_cmdline.add_options() ("help,h", "print out program usage (this message)") ("version,v", "print the version number") ("copyright,c", "print out the copyright statement") ("config-file", po::value<vector<string> >(), "specify a config file (alternatively: @filepath)") ; // declare the options allowed on command line and in config files po::options_description desc_generic ("Options allowed additionally in a config file"); desc_generic.add_options() ("output,o", po::value<string>()->composing(), "specify a file to use for output instead of stdout") ("include,I", po::value<cmd_line_util::include_paths>()->composing(), "specify an additional include directory") ("sysinclude,S", po::value<vector<string> >()->composing(), "specify an additional system include directory") ("define,D", po::value<vector<string> >()->composing(), "specify a macro to define (as macro[=[value]])") ("predefine,P", po::value<vector<string> >()->composing(), "specify a macro to predefine (as macro[=[value]])") ("undefine,U", po::value<vector<string> >()->composing(), "specify a macro to undefine") ; // combine the options for the different usage schemes po::options_description desc_overall_cmdline; po::options_description desc_overall_cfgfile; desc_overall_cmdline.add(desc_cmdline).add(desc_generic); desc_overall_cfgfile.add(desc_generic); // parse command line and store results using namespace boost::program_options::command_line_style; po::parsed_options opts = po::parse_command_line(argc, argv, desc_overall_cmdline, unix_style, cmd_line_util::at_option_parser); po::variables_map vm; po::store(opts, vm); po::notify(vm); // Try to find a waveidl.cfg in the same directory as the executable was // started from. If this exists, treat it as a wave config file fs::path filename(argv[0], fs::native); filename = filename.branch_path() / "waveidl.cfg"; cmd_line_util::read_config_file_options(filename.string(), desc_overall_cfgfile, vm, true); // if there is specified at least one config file, parse it and add the // options to the main variables_map if (vm.count("config-file")) { vector<string> const &cfg_files = vm["config-file"].as<vector<string> >(); vector<string>::const_iterator end = cfg_files.end(); for (vector<string>::const_iterator cit = cfg_files.begin(); cit != end; ++cit) { // parse a single config file and store the results cmd_line_util::read_config_file_options(*cit, desc_overall_cfgfile, vm); } } // ... act as required if (vm.count("help")) { po::options_description desc_help ( "Usage: waveidl [options] [@config-file(s)] file"); desc_help.add(desc_cmdline).add(desc_generic); cout << desc_help << endl; return 1; } if (vm.count("version")) { return print_version(); } if (vm.count("copyright")) { return print_copyright(); } // extract the arguments from the parsed command line vector<po::option> arguments; std::remove_copy_if(opts.options.begin(), opts.options.end(), inserter(arguments, arguments.end()), cmd_line_util::is_argument()); // if there is no input file given, then exit if (0 == arguments.size() || 0 == arguments[0].value.size()) { cerr << "waveidl: no input file given, " << "use --help to get a hint." << endl; return 5; } // preprocess the given input file return do_actual_work(arguments[0].value[0], vm); } catch (std::exception const& e) { cout << "waveidl: exception caught: " << e.what() << endl; return 6; } catch (...) { cerr << "waveidl: unexpected exception caught." << endl; return 7; } }
36.163265
91
0.540324
[ "object", "vector" ]
33421030610a782f5e67b62222a2f65fd8eee6a8
6,658
cc
C++
L1Trigger/RPCTrigger/src/RPCConeBuilderFromES.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
L1Trigger/RPCTrigger/src/RPCConeBuilderFromES.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
L1Trigger/RPCTrigger/src/RPCConeBuilderFromES.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
// -*- C++ -*- // // Package: RPCTrigger // Class : RPCConeBuilderFromES // // Implementation: // <Notes on implementation> // // Original Author: // Created: Mon Mar 3 13:34:20 CET 2008 // // system include files // user include files #include "L1Trigger/RPCTrigger/interface/RPCConeBuilderFromES.h" // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // RPCConeBuilderFromES::RPCConeBuilderFromES() {} // RPCConeBuilderFromES::RPCConeBuilderFromES(const RPCConeBuilderFromES& rhs) // { // // do actual copying here; // } RPCConeBuilderFromES::~RPCConeBuilderFromES() {} L1RpcLogConesVec RPCConeBuilderFromES::getConesFromES(edm::Handle<RPCDigiCollection> rpcDigis, edm::ESHandle<L1RPCConeBuilder> coneBuilder, edm::ESHandle<L1RPCConeDefinition> coneDef, edm::ESHandle<L1RPCBxOrConfig> bxOrDef, edm::ESHandle<L1RPCHwConfig> hwConfig, int bx) { std::vector<RPCLogHit> logHits; std::vector<RPCLogHit> logHitsFromUncomp; // Build cones from digis // first build loghits short int digiIndex = 0; RPCDigiCollection::DigiRangeIterator detUnitIt; for (detUnitIt = rpcDigis->begin(); detUnitIt != rpcDigis->end(); ++detUnitIt) { const RPCDetId& id = (*detUnitIt).first; uint32_t rawId = id.rawId(); const RPCDigiCollection::Range& range = (*detUnitIt).second; std::pair<L1RPCConeBuilder::TCompressedConVec::const_iterator, L1RPCConeBuilder::TCompressedConVec::const_iterator> compressedConnPair = coneBuilder->getCompConVec(rawId); // iterate over strips for (RPCDigiCollection::const_iterator digiIt = range.first; digiIt != range.second; ++digiIt) { ++digiIndex; if (digiIt->bx() < bxOrDef->getFirstBX() + bx || digiIt->bx() > bxOrDef->getLastBX() + bx) { //if ( digiIt->bx() < hwConfig->getFirstBX() + bx || digiIt->bx() > hwConfig->getLastBX() +bx ){ continue; } //std::cout << digiIt->bx() << " D " << rawId << " " << id << " S " << digiIt->strip() << std::endl; // for uncompressed connections std::pair<L1RPCConeBuilder::TStripConVec::const_iterator, L1RPCConeBuilder::TStripConVec::const_iterator> itPair = coneBuilder->getConVec(rawId, digiIt->strip()); L1RPCConeBuilder::TStripConVec::const_iterator it = itPair.first; // Iterate over uncompressed connections, convert digis to logHits for (; it != itPair.second; ++it) { //std::cout << " Not empty!" << std::endl; if (hwConfig->isActive(it->m_tower, it->m_PAC)) { RPCLogHit lh(it->m_tower, it->m_PAC, it->m_logplane, it->m_logstrip); lh.setDigiIdx(digiIndex); logHitsFromUncomp.push_back(lh); } } /* bool printOut = false; if (digiIt->strip() == 62 || digiIt->strip() == 63 ){ std::cout << "Strip " << digiIt->strip() << std::endl; printOut = true; } */ L1RPCConeBuilder::TCompressedConVec::const_iterator itComp = compressedConnPair.first; for (; itComp != compressedConnPair.second; ++itComp) { if (hwConfig->isActive(itComp->m_tower, itComp->m_PAC)) { int logstrip = itComp->getLogStrip(digiIt->strip(), coneDef->getLPSizeVec()); if (logstrip != -1) { RPCLogHit lh(itComp->m_tower, itComp->m_PAC, itComp->m_logplane, logstrip); lh.setDigiIdx(digiIndex); logHits.push_back(lh); } /* if (printOut){ std::cout << "T " << (int)itComp->m_tower << " P " << (int)itComp->m_PAC << " LP " << (int)itComp->m_logplane << " LS " << (int)logstrip << std::endl; }*/ } } } // strip iteration ends } // check if we dont have any preferable uncompressed loghits std::vector<RPCLogHit>::iterator itLHitUncomp = logHitsFromUncomp.begin(); std::vector<RPCLogHit>::iterator itLHitComp; // overwrite uncompressed with those coming from compressed for (; itLHitUncomp != logHitsFromUncomp.end(); ++itLHitUncomp) { for (itLHitComp = logHits.begin(); itLHitComp != logHits.end(); ++itLHitComp) { if (itLHitComp->getTower() == itLHitUncomp->getTower() && itLHitComp->getLogSector() == itLHitUncomp->getLogSector() && itLHitComp->getLogSegment() == itLHitUncomp->getLogSegment() && itLHitComp->getlogPlaneNumber() == itLHitUncomp->getlogPlaneNumber()) { // std::cout<< "Overwrite " << std::endl; //std::cout.flush(); *itLHitUncomp = *itLHitComp; } } } // copy missing from compressed to uncompressed for (; itLHitUncomp != logHitsFromUncomp.end(); ++itLHitUncomp) { bool present = false; for (unsigned int i = 0; i < logHits.size(); ++i) { if (logHits[i].getTower() == itLHitUncomp->getTower() && logHits[i].getLogSector() == itLHitUncomp->getLogSector() && logHits[i].getLogSegment() == itLHitUncomp->getLogSegment() && logHits[i].getlogPlaneNumber() == itLHitUncomp->getlogPlaneNumber()) { present = true; } } if (!present) { // std::cout<< "Copy " << std::endl; //std::cout.flush(); logHits.push_back(*itLHitUncomp); } } // build cones L1RpcLogConesVec ActiveCones; std::vector<RPCLogHit>::iterator p_lhit; for (p_lhit = logHits.begin(); p_lhit != logHits.end(); ++p_lhit) { bool hitTaken = false; L1RpcLogConesVec::iterator p_cone; for (p_cone = ActiveCones.begin(); p_cone != ActiveCones.end(); p_cone++) { hitTaken = p_cone->addLogHit(*p_lhit); if (hitTaken) break; } if (!hitTaken) { RPCLogCone newcone(*p_lhit); newcone.setIdx(ActiveCones.size()); ActiveCones.push_back(newcone); } } // for loghits /* for (int tower = -16; tower<17;++tower) { for (int sector = 0; sector<12;++sector) { for (int segment = 0; segment<12;++segment) { for (L1RpcLogConesVec::iterator it = ActiveCones.begin(); it!=ActiveCones.end(); ++it) { if (it->getTower()==tower && it->getLogSector()==sector && it->getLogSegment()==segment) { std::cout << it->toString() << std::endl; } } } } } // */ return ActiveCones; }
33.969388
120
0.58471
[ "vector" ]
33425f398991913e94c702ef29d7da5db75d1958
4,504
hpp
C++
src/ngraph/runtime/cpu/op/max_pool_with_indices.hpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/cpu/op/max_pool_with_indices.hpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/cpu/op/max_pool_with_indices.hpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include "ngraph/graph_util.hpp" #include "ngraph/op/op.hpp" #include "ngraph/runtime/cpu/cpu_backend_visibility.h" namespace ngraph { namespace op { // MaxPoolWithIndices produces two outputs. // The first output is equivalent to what MaxPool produces // The second one contains the indices of the maximum numbers // for each window in input (arg) // These indices are used by MKLDNN for a back propagation pass class MaxPoolWithIndices : public Op { public: static constexpr NodeTypeInfo type_info{"MaxPoolWithIndices", 0}; const NodeTypeInfo& get_type_info() const override { return type_info; } CPU_BACKEND_API MaxPoolWithIndices(const Output<Node>& arg, const Shape& window_shape, const Strides& window_movement_strides, const Shape& padding_below, const Shape& padding_above); virtual std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const override; const Shape& get_window_shape() const { return m_window_shape; } const Strides& get_window_movement_strides() const { return m_window_movement_strides; } const Shape& get_padding_below() const { return m_padding_below; } const Shape& get_padding_above() const { return m_padding_above; } virtual std::shared_ptr<Node> get_default_value() const override { return ngraph::make_constant_from_string("0", get_element_type(), get_shape()); } protected: virtual void generate_adjoints(autodiff::Adjoints& adjoints, const NodeVector& deltas) override; Shape m_window_shape; Strides m_window_movement_strides; Shape m_padding_below; Shape m_padding_above; }; // MaxPoolWithIndicesBackprop takes MaxPoolWithIndices' outputs and // pass the indices directly to MKLDNN to avoid max indices recomputation class MaxPoolWithIndicesBackprop : public Op { public: static constexpr NodeTypeInfo type_info{"MaxPoolWithIndicesBackprop", 0}; const NodeTypeInfo& get_type_info() const override { return type_info; } CPU_BACKEND_API MaxPoolWithIndicesBackprop(const Output<Node>& arg_forward, const Output<Node>& delta, const Output<Node>& indices, const Shape& window_shape, const Strides& window_movement_strides, const Shape& padding_below, const Shape& padding_above); virtual std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const override; const Shape& get_window_shape() const { return m_window_shape; } const Strides& get_window_movement_strides() const { return m_window_movement_strides; } const Shape& get_padding_below() const { return m_padding_below; } const Shape& get_padding_above() const { return m_padding_above; } protected: Shape m_window_shape; Strides m_window_movement_strides; Shape m_padding_below; Shape m_padding_above; }; } }
47.410526
100
0.577487
[ "shape" ]
3343f5592f7ad137650c3b3f9f0d17079001d02e
3,891
cpp
C++
Algorithm/arcsim/adaptiveCloth/nearobs.cpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
32
2016-12-13T05:49:12.000Z
2022-02-04T06:15:47.000Z
Algorithm/arcsim/adaptiveCloth/nearobs.cpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
2
2019-07-30T02:01:16.000Z
2020-03-12T15:06:51.000Z
Algorithm/arcsim/adaptiveCloth/nearobs.cpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
18
2017-11-16T13:37:06.000Z
2022-03-11T08:13:46.000Z
/* Copyright ©2013 The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and not-for-profit purposes, without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-7201, for commercial licensing opportunities. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include "nearobs.hpp" #include "collisionutil.hpp" #include "geometry.hpp" #include "magic.hpp" #include "simulation.hpp" #include <vector> using namespace std; namespace arcsim { template <typename T> struct Min { double key; T val; Min() : key(infinity), val() {} void add(double key, T val) { if (key < this->key) { this->key = key; this->val = val; } } }; Vec3 nearest_point(const Vec3 &x, const vector<AccelStruct*> &accs, double dmin); vector<Plane> nearest_obstacle_planes(const Mesh &mesh, const vector<Mesh*> &obs_meshes) { const double dmin = 10 * arcsim::magic.repulsion_thickness; vector<AccelStruct*> obs_accs = create_accel_structs(obs_meshes, false); vector<Plane> planes(mesh.nodes.size(), make_pair(Vec3(0), Vec3(0))); #pragma omp parallel for for (int n = 0; n < mesh.nodes.size(); n++) { Vec3 x = mesh.nodes[n]->x; Vec3 p = nearest_point(x, obs_accs, dmin); if (p != x) planes[n] = make_pair(p, normalize(x - p)); } destroy_accel_structs(obs_accs); return planes; } struct NearPoint { double d; Vec3 x; NearPoint(double d, const Vec3 &x) : d(d), x(x) {} }; void update_nearest_point(const Vec3 &x, BVHNode *node, NearPoint &p); Vec3 nearest_point(const Vec3 &x, const vector<AccelStruct*> &accs, double dmin) { NearPoint p(dmin, x); for (int a = 0; a < accs.size(); a++) if (accs[a]->root) update_nearest_point(x, accs[a]->root, p); return p.x; } void update_nearest_point(const Vec3 &x, const Face *face, NearPoint &p); double point_box_distance(const Vec3 &x, const BOX &box); void update_nearest_point(const Vec3 &x, BVHNode *node, NearPoint &p) { if (node->isLeaf()) update_nearest_point(x, node->getFace(), p); else { double d = point_box_distance(x, node->_box); if (d >= p.d) return; update_nearest_point(x, node->getLeftChild(), p); update_nearest_point(x, node->getRightChild(), p); } } double point_box_distance(const Vec3 &x, const BOX &box) { Vec3 xp = Vec3(clamp(x[0], (double)box._dist[0], (double)box._dist[9]), clamp(x[1], (double)box._dist[1], (double)box._dist[10]), clamp(x[2], (double)box._dist[2], (double)box._dist[11])); return norm(x - xp); } void update_nearest_point(const Vec3 &x, const Face *face, NearPoint &p) { Vec3 n; double w[4]; double d = unsigned_vf_distance(x, face->v[0]->node->x, face->v[1]->node->x, face->v[2]->node->x, &n, w); if (d < p.d) { p.d = d; p.x = -(w[1] * face->v[0]->node->x + w[2] * face->v[1]->node->x + w[3] * face->v[2]->node->x); } } }
29.255639
78
0.685685
[ "mesh", "geometry", "vector" ]
33488a2959c688417addc06d94c7011fb335dabb
13,104
cpp
C++
startalk_ui/FriendsSearcher.cpp
xuepingiw/open_source_startalk
44d962b04039f5660ec47a10313876a0754d3e72
[ "MIT" ]
34
2019-03-18T08:09:24.000Z
2022-03-15T02:03:25.000Z
startalk_ui/FriendsSearcher.cpp
venliong/open_source_startalk
51fda091a932a8adea626c312692836555753a9a
[ "MIT" ]
5
2019-05-29T09:32:05.000Z
2019-08-29T03:01:33.000Z
startalk_ui/FriendsSearcher.cpp
venliong/open_source_startalk
51fda091a932a8adea626c312692836555753a9a
[ "MIT" ]
32
2019-03-15T09:43:22.000Z
2021-08-10T08:26:02.000Z
#include "FriendsSearcher.h" #include "Session.h" #include "Account.h" #include "SystemConfigData.h" #include "CallbackReceiver.h" #include "RosterList.h" #include "UIFrame.h" #include "NotifyCenterController.h" #include "animationreactor.h" #include "ui_FriendsSearcher.h" #include "diywidgit/customviews/qimdroplistview.h" #include "diywidgit/customviews/qframelayout.h" #include "jsonobject/domainlist.h" #include "ConfigureHelper.h" #include "ListWidgetBaseAdapter.h" class DomainDropListUserData : public QIMDropListViewUserData { public: QSharedPointer<Biz::DomainInfo> m_spRawDomainInfo; }; class FriendSearchItem : public QWidget { public: enum FriendsSearchStatus { FriendsSearchStatusBase = 0, FriendsSearchStatusToBeAdd = FriendsSearchStatusBase, FriendsSearchStatusToBeDelete = FriendsSearchStatusBase +1 }; FriendSearchItem(QWidget* parent):QWidget(parent) { QLabel* headerImage = new QLabel(this); headerImage->setPixmap(QPixmap(":/Images/mainpanel_buddy_down.png")); headerImage->setFixedSize (QSize(28,28)); itemName = new QLabel(this); actionBtn = new QPushButton(this); actionBtn->setText(QStringLiteral("加为好友")); actionBtn->setMinimumSize(QSize(72, 24)); actionBtn->setMaximumSize(QSize(72, 24)); QFrameLayout* pRootLayout = new QFrameLayout(this); pRootLayout->appendWidget (headerImage,ALINE_VCENTER|ALINE_LEFT,QMargins(0,0,0,0)); pRootLayout->appendWidget (itemName,ALINE_VCENTER|ALINE_LEFT,QMargins(30,0,0,0)); pRootLayout->appendWidget (actionBtn,ALINE_VCENTER|ALINE_RIGHT,QMargins(0,0,0,0)); this->setLayout (pRootLayout); } ~FriendSearchItem() { }; void setStatus(FriendsSearchStatus status){ if (FriendSearchItem::FriendsSearchStatus::FriendsSearchStatusToBeDelete == status) { actionBtn->setText (QStringLiteral("删除好友")); actionBtn->setEnabled (true); actionBtn->setStyleSheet ("border:1px solid #1BA9BA;border-radius:3px;background:#00000000;color:#1BA9BA;"); actionBtn->disconnect (); connect (actionBtn,&QPushButton::clicked,this,&FriendSearchItem::onDeleteFriend); } if (FriendSearchItem::FriendsSearchStatus::FriendsSearchStatusToBeAdd == status) { actionBtn->setText (QStringLiteral("加为好友")); actionBtn->setEnabled (true); actionBtn->setStyleSheet ("border:1px solid #CCCCCC;border-radius:3px;background:#1BA9BA;color:#FFFFFF;"); actionBtn->disconnect (); connect (actionBtn,&QPushButton::clicked,this,&FriendSearchItem::onAddFriend); } }; void onAddFriend(){ if ( !userInfo.isNull()) { QString qchatJid = userInfo->strUserId; if (Biz::Session::getFriendManager()->isAlreadyFriend(qchatJid)) { MainApp::UIFrame::getNotifyCenterController ()->popupNotice (QStringLiteral("%1已经是好友了").arg(qchatJid)); return; } Biz::Session::getFriendManager()->getUserVerifyMode(qchatJid); } }; void onDeleteFriend(){ if ( !userInfo.isNull()) { QString jid = userInfo->strUserId; Biz::Session::getFriendManager()->getDeleteFriend(jid, E_DELETE_FRIEND_MODE::DELETE_MODE_SINGLE); } }; public: QLabel* itemName; QPushButton* actionBtn; QSharedPointer<Biz::ImSelfPerson> userInfo; }; class FriendSearchResultListAdapter : public ListWidgetBaseAdapter { enum DataKey { DataKeyBase = ListWidgetBaseAdapterUserRoleBase, DataKeyId = DataKeyBase+1 }; public: FriendSearchResultListAdapter(QListView* listview):ListWidgetBaseAdapter(listview){}; ~FriendSearchResultListAdapter(){}; virtual QWidget* CreateNewWidget(const QModelIndex& index) { QListWidget* pWidgetList = dynamic_cast<QListWidget*>(getListView ()); if (NULL!=pWidgetList) { } QString key = index.data(DataKeyId).toString (); FriendSearchItem* pItemview = new FriendSearchItem(NULL); QSharedPointer<Biz::ImSelfPerson> spData = userInfoDatas.value (key); if (!spData.isNull ()) { pItemview->itemName->setText (spData->strNickName); pItemview->userInfo = spData; if (Biz::Session::getFriendManager ()->isAlreadyFriend (key)) pItemview->setStatus (FriendSearchItem::FriendsSearchStatus::FriendsSearchStatusToBeDelete); else pItemview->setStatus (FriendSearchItem::FriendsSearchStatus::FriendsSearchStatusToBeAdd); } return pItemview; } virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(36,36); } virtual int count (){return userInfoDatas.count ();} public: void setData(const QList<QSharedPointer<Biz::ImSelfPerson>>& datas) { userInfoDatas.clear (); QListWidget* pListWidget = dynamic_cast<QListWidget*>(getListView ()); if (NULL!=pListWidget) { pListWidget->clear (); for (QSharedPointer<Biz::ImSelfPerson> boy : datas) { if (boy.isNull ()) continue; QListWidgetItem* pItem = new QListWidgetItem(pListWidget); pItem->setData (DataKeyId,boy->strUserId); pItem->setText (boy->strUserId); pListWidget->addItem (pItem); userInfoDatas.insert (boy->strUserId,boy); } } } public: private: QMap<QString, QSharedPointer<Biz::ImSelfPerson>> userInfoDatas; }; FriendsSearcher::FriendsSearcher(QWidget *parent) : LocalManWidget(parent) , receiver(new Biz::CallbackReceiver(this)) { ui = new Ui::FriendsSearcher(); ui->setupUi(this); using namespace Qt; auto remove = WindowTitleHint; // WindowStaysOnTopHint add by wangchao 2018.08.30 auto add = FramelessWindowHint | WindowMinMaxButtonsHint | WindowStaysOnTopHint; setAttribute(Qt::WA_AlwaysShowToolTips, true); setAttribute(Qt::WA_TranslucentBackground, true); overrideWindowFlags( (Qt::WindowFlags)((windowFlags() & ~remove) | add)); this->setSizeGripEnabled(false); ui->titlebar->setMinable(false); ui->titlebar->setMaxable(false); connect(ui->titlebar,&TitlebarWidget::sgCloseOnClicked,this,&FriendsSearcher::onClose); setWindowTitle(QStringLiteral("添加朋友")); #ifdef QCHAT setWindowIcon(QIcon(":/Images/Deal_chat.ico")); #else setWindowIcon(QIcon(":/Images/Deal.ico")); #endif ui->levelStacked->setCurrentWidget(ui->empty); connect(ui->goSearch,&QPushButton::clicked,this,&FriendsSearcher::onGoSearchClicked); connect(ui->lineEdit,&QLineEdit::returnPressed,[this]{ ui->goSearch->clicked(); }); ui->dropView->setContentViewParent(this); FriendSearchResultListAdapter* pAdapter = new FriendSearchResultListAdapter(ui->listWidget); ui->listWidget->setItemDelegate(pAdapter); connect (ui->dropView,&QIMDropListView::currentTextChanged,this,&FriendsSearcher::onDomainListSelectChange); connect(Biz::Session::getFriendManager(), &Biz::FriendsManager::sgDelFriendRecieve ,this, &FriendsSearcher::onFriendDeletedReceive); connect(Biz::Session::getFriendManager(), &Biz::FriendsManager::sgFriendVerifyResultReceive, this, &FriendsSearcher::onFriendVerifyResponceReceive); } FriendsSearcher::~FriendsSearcher() { } void FriendsSearcher::onGoSearchClicked(bool b) { QString searchText = ui->lineEdit->text().trimmed(); if (searchText.isEmpty()) { ui->levelStacked->setCurrentWidget(ui->empty); return; } QSharedPointer<QIMDropListViewUserData> domaindata = ui->dropView->getCurrentUserData(); DomainDropListUserData* pDomainListData = (DomainDropListUserData*)domaindata.data (); if (NULL!=pDomainListData && !pDomainListData->m_spRawDomainInfo.isNull ()) { QString domainid = pDomainListData->m_spRawDomainInfo->id (); Biz::UnitCallback<QList<QSharedPointer<Biz::ImSelfPerson>>>* callback = receiver->createCallback<QList<QSharedPointer<Biz::ImSelfPerson>>>( [this](const QList<QSharedPointer<Biz::ImSelfPerson>>& personList){ buildSearchResult(personList); },[](){} ); Biz::Session::getFriendManager()->searchFriendInfo(searchText,domainid,0,callback); } } void FriendsSearcher::buildSearchResult(const QList<QSharedPointer<Biz::ImSelfPerson>>& retList) { FriendSearchResultListAdapter* pAdater = dynamic_cast<FriendSearchResultListAdapter*>(ui->listWidget->itemDelegate()); if (NULL!=pAdater) { pAdater->setData(retList); if (0<pAdater->count()) ui->levelStacked->setCurrentWidget(ui->listpage); else ui->levelStacked->setCurrentWidget(ui->empty); } } void FriendsSearcher::onClose() { this->hide(); ui->lineEdit->setText(""); FriendSearchResultListAdapter* pAdater = dynamic_cast<FriendSearchResultListAdapter*>(ui->listWidget->itemDelegate()); if (NULL!=pAdater) { pAdater->setData(QList<QSharedPointer<Biz::ImSelfPerson>>()); ui->levelStacked->setCurrentWidget(ui->empty); } } void FriendsSearcher::showEvent(QShowEvent *event) { AnimationReactorSingleton::getInstance ()->opacityInWidget (this,100); initDomainListData(); return LocalManWidget::showEvent (event); } void FriendsSearcher::initDomainListData() { auto setDropData = [this](const QSharedPointer<Biz::DomainListInfo>& spInfo){ if (NULL == spInfo->domains ()) return; QList<QSharedPointer<QIMDropListViewUserData>> dropItems; for (IJsonSerializeable* pjsonItem : ((Biz::DomainList*)spInfo->domains ())->domains()) { Biz::DomainInfo* pInfo = (Biz::DomainInfo*)pjsonItem; if (pInfo->id ().isEmpty () || pInfo->name ().isEmpty ()) continue; DomainDropListUserData* pDomainUserData = new DomainDropListUserData; pDomainUserData->m_text = pInfo->name (); pDomainUserData->m_hoverText = pInfo->description (); pDomainUserData->m_spRawDomainInfo = QSharedPointer<Biz::DomainInfo>(new Biz::DomainInfo(*pInfo)); QSharedPointer<QIMDropListViewUserData> userdata (pDomainUserData); dropItems.append (userdata); } ui->dropView->setData(dropItems); if (!spInfo->currentSelectId ().isEmpty ()) { ui->dropView->setCurrentText(spInfo->currentSelectId()); } else if (!dropItems.isEmpty()) { ui->dropView->setCurrentText(dropItems.at (0)->m_text); } else { ui->dropView->setCurrentText(""); } }; QSharedPointer<Biz::DomainListInfo> spInfo (Biz::ConfigureHelper::loadDomainListConfigData ()); if (!spInfo.isNull () && (QDateTime::currentMSecsSinceEpoch ()-spInfo->lastupdate ()) < 60*60*24) { setDropData(spInfo); return; } // 事实获取 auto callback = receiver->createCallback<QSharedPointer<Biz::DomainList>> ([this,setDropData](const QSharedPointer<Biz::DomainList>& dl){ if (!dl->domains ().empty ()) { QSharedPointer<Biz::DomainListInfo> spInfo (Biz::ConfigureHelper::loadDomainListConfigData ()); spInfo->domains (dl.data ()); spInfo->lastupdate (QDateTime::currentMSecsSinceEpoch ()); Biz::ConfigureHelper::saveDomainListConfigData (*spInfo.data ()); setDropData(spInfo); } },[]{}); Biz::Session::getFriendManager ()->getDomainList (callback); } void FriendsSearcher::onDomainListSelectChange(const QString& selectid) { QSharedPointer<Biz::DomainListInfo> spInfo (Biz::ConfigureHelper::loadDomainListConfigData ()); spInfo->currentSelectId(selectid); Biz::ConfigureHelper::saveDomainListConfigData (*spInfo.data ()); } void FriendsSearcher::onFriendDeletedReceive(const QString&reson , const QString& jid, int ntype) { QList<QListWidgetItem*> matchedItem = ui->listWidget->findItems(jid,Qt::MatchExactly); for (QListWidgetItem* pItem : matchedItem) { int nR = ui->listWidget->row (pItem); pItem = ui->listWidget->takeItem(nR); delete pItem; } } void FriendsSearcher::onFriendVerifyResponceReceive(const QString& result, const QString& reason, const QString& jid) { QList<QListWidgetItem*> matchedItem = ui->listWidget->findItems(jid,Qt::MatchExactly); for (QListWidgetItem* pItem : matchedItem) { QWidget* pView = ui->listWidget->itemWidget(pItem); if (NULL!=pView) { FriendSearchItem* pItem = (FriendSearchItem*)pView; pItem->setStatus (FriendSearchItem::FriendsSearchStatusToBeDelete); } } }
34.393701
152
0.663614
[ "solid" ]
3348abb19b3339b2b3e8b50485133b15a1973a32
2,910
cc
C++
paddle/fluid/framework/ir/fc_fuse_pass.cc
xuezhong/Paddle
be9ec5208160bfed02e767bdb23db5aba9cf5eb0
[ "Apache-2.0" ]
null
null
null
paddle/fluid/framework/ir/fc_fuse_pass.cc
xuezhong/Paddle
be9ec5208160bfed02e767bdb23db5aba9cf5eb0
[ "Apache-2.0" ]
null
null
null
paddle/fluid/framework/ir/fc_fuse_pass.cc
xuezhong/Paddle
be9ec5208160bfed02e767bdb23db5aba9cf5eb0
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/ir/fc_fuse_pass.h" #include <string> #include <vector> #include "paddle/fluid/platform/enforce.h" namespace paddle { namespace framework { namespace ir { std::unique_ptr<ir::Graph> FCFusePass::ApplyImpl( std::unique_ptr<ir::Graph> graph) const { PADDLE_ENFORCE(graph.get()); FusePassBase::Init("fc_fuse", graph.get()); std::unordered_set<Node*> nodes2delete; GraphPatternDetector gpd; auto* x = gpd.mutable_pattern() ->NewNode("fc_fuse/x") ->AsInput() ->assert_is_op_input("mul", "X"); patterns::FC fc_pattern(gpd.mutable_pattern(), "fc_fuse"); fc_pattern(x, true /*with bias*/); int found_fc_count = 0; auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* g) { VLOG(40) << "handle FC fuse"; GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(fc_bias, bias, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(fc_out, Out, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add, elementwise_add, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(mul_out, mul_out, fc_pattern); // Create an FC Node. OpDesc desc; std::string fc_x_in = subgraph.at(x)->Name(); std::string fc_Y_in = w->Name(); std::string fc_bias_in = fc_bias->Name(); std::string fc_out_out = fc_out->Name(); desc.SetInput("Input", std::vector<std::string>({fc_x_in})); desc.SetInput("W", std::vector<std::string>({fc_Y_in})); desc.SetInput("Bias", std::vector<std::string>({fc_bias_in})); desc.SetOutput("Out", std::vector<std::string>({fc_out_out})); desc.SetType("fc"); auto fc_node = g->CreateOpNode(&desc); // OpDesc will be copied. GraphSafeRemoveNodes(graph.get(), {mul, elementwise_add, mul_out}); PADDLE_ENFORCE(subgraph.count(x)); IR_NODE_LINK_TO(subgraph.at(x), fc_node); IR_NODE_LINK_TO(w, fc_node); IR_NODE_LINK_TO(fc_bias, fc_node); IR_NODE_LINK_TO(fc_node, fc_out); found_fc_count++; }; gpd(graph.get(), handler); AddStatis(found_fc_count); return graph; } } // namespace ir } // namespace framework } // namespace paddle REGISTER_PASS(fc_fuse_pass, paddle::framework::ir::FCFusePass);
34.642857
76
0.694158
[ "vector" ]
334a4d52c4bea7b7b84bbb4cefbd69277cfc513c
5,160
cpp
C++
node.cpp
mkellydevv/vector_graphics_animator
fc46ec710138bd2220f7602e1aa6991d0153980e
[ "MIT" ]
null
null
null
node.cpp
mkellydevv/vector_graphics_animator
fc46ec710138bd2220f7602e1aa6991d0153980e
[ "MIT" ]
null
null
null
node.cpp
mkellydevv/vector_graphics_animator
fc46ec710138bd2220f7602e1aa6991d0153980e
[ "MIT" ]
null
null
null
#include "node.h" #define PI 3.14159265 node::node() { nodeShape = Root; name = "Root"; children = new std::vector<node*>; treeDepth = 0; } node::node(std::vector<gVector3> verts, gVector3 col, int mode) { children = new std::vector<node*>; vertices = verts; currentVertices = verts; centroid = findCentroid(); if (vertices.size() == 3) { nodeShape = Tri; name = "Tri"; } else if (vertices.size() == 4) { nodeShape = Quad; name = "Quad"; } else { nodeShape = Poly; name = "Poly"; } drawMode = mode; originalColor = col; currentColor = col; } node::node(std::vector<gVector3> verts, gVector3 col, int mode, std::string n) { children = new std::vector<node*>; vertices = verts; currentVertices = verts; centroid = findCentroid(); name = n; if (vertices.size() == 3) nodeShape = Tri; else if (vertices.size() == 4) nodeShape = Quad; else nodeShape = Poly; drawMode = mode; originalColor = col; currentColor = col; } node::~node() { delete children; } gVector3 node::findCentroid() { // Formula for centroid of a polygon from en.wikipedia.org/wiki/Centroid#Centroid_of_polygon gVector3 newCentroid; float partialArea; float signedArea = 0; for (int i = 0; i < vertices.size() - 1; i++) { partialArea = (vertices[i][0] * vertices[i + 1][1]) - (vertices[i + 1][0] * vertices[i][1]); newCentroid[0] += (vertices[i][0] + vertices[i + 1][0]) * partialArea; newCentroid[1] += (vertices[i][1] + vertices[i + 1][1]) * partialArea; signedArea += partialArea; } int i = vertices.size() - 1; partialArea = (vertices[i][0] * vertices[0][1]) - (vertices[0][0] * vertices[i][1]); newCentroid[0] += (vertices[i][0] + vertices[0][0]) * partialArea; newCentroid[1] += (vertices[i][1] + vertices[0][1]) * partialArea; signedArea += partialArea; signedArea /= 2; newCentroid[0] /= signedArea * 6; newCentroid[1] /= signedArea * 6; return newCentroid; } void node::normalizeVertices() { currentVertices = vertices; for (int i = 0; i < children->size(); i++) children->operator[](i)->normalizeVertices(); } void node::applyTransforms(transform tran, gVector3 cent, bool first) { // Clear current vertices std::vector<gVector3> tempVertices = currentVertices; currentVertices.clear(); // Transform each vertex and readd it to currentVertices for (int i = 0; i < tempVertices.size(); i++) { gVector3 vertex = tempVertices[i]; vertex = tran.scale * vertex; // Scale the vertex vertex[0] = vertex[0] - cent[0]; // Translate vertex to make sure rotation happens around polygon's center vertex[1] = vertex[1] - cent[1]; vertex = tran.rotation * vertex; // Rotate the vertex vertex[0] = vertex[0] + cent[0]; // Translate vertex back to its original position vertex[1] = vertex[1] + cent[1]; vertex = tran.translation * vertex; // Translate the vertex currentVertices.push_back(vertex); } // Color transformation not applied to children if (tran.color != gVector3::nullVector() && first == true) currentColor = tran.color; // Recursively transform all children on this section of the tree for (int i = 0; i < children->size(); i++) children->operator[](i)->applyTransforms(tran, cent, false); } void node::addChild(node* child) { children->push_back(child); child->setParent(this); child->setTreeDepth(this->getTreeDepth() + 1); } void node::deleteNode() { if (nodeShape != Root) { // Erase this child from its parent for (int i = 0; i < parent->children->size(); i++) { if (parent->children->operator[](i) == this) parent->children->erase(parent->children->begin() + i); } // Recursively delete all children on this section of the tree while (children->size() > 0) children->front()->deleteNode(); delete this; } else { // Recursively delete all children starting at root while (children->size() > 0) children->front()->deleteNode(); } } node* node::getParent() { return parent; } std::vector<node*>* node::getChildren() { return children; } std::vector<gVector3> node::getVertices() { return vertices; } std::vector<gVector3> node::getCurrentVertices() { return currentVertices; } gVector3 node::getCentroid() { return centroid; } std::string node::getName() { return name; } int node::getID() { return ID; } int node::getParentID() { return parentID; } shape node::getShape() { return nodeShape; } int node::getDrawMode() { return drawMode; } int node::getTreeDepth() { return treeDepth; } gVector3 node::getOriginalColor() { return originalColor; } gVector3 node::getCurrentColor() { return currentColor; } void node::setParent(node* par) { parent = par; } void node::setVertices(std::vector<gVector3> verts) { vertices = verts; } void node::setCentroid(gVector3 newCentroid) { centroid = newCentroid; } void node::setName(std::string n) { name = n; } void node::setID(int i) { ID = i; } void node::setParentID(int i) { parentID = i; } void node::setDrawMode(int m) { drawMode = m; } void node::setTreeDepth(int d) { treeDepth = d; } void node::setOriginalColor(gVector3 col) { originalColor = col; } void node::setCurrentColor(gVector3 col) { currentColor = col; }
17.142857
108
0.665504
[ "shape", "vector", "transform" ]
334a9a45601184c128ef7576e80c072a10f01ed1
4,468
cpp
C++
codeforces/1108e2.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
codeforces/1108e2.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
codeforces/1108e2.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; template <typename M, typename D> struct SegLazy { using Op = function<M(const M&, const M&)>; using D2M = function<void(M&, const D&)>; using D2D = function<void(D&, const D&)>; M ID; D UN; Op op; D2M d2m; D2D d2d; int N, L; vector<M> a; // tree vector<D> d; // lazy SegLazy(int n, M leaf_default, M _ID, D _UN, Op _op, D2M _d2m, D2D _d2d) : ID(_ID), UN(_UN), op(_op), d2m(_d2m), d2d(_d2d) { init_space(n); fill(a.begin() + N, a.begin() + N + n, leaf_default); build(); } SegLazy(const vector<M>& leaves, M _ID, D _UN, Op _op, D2M _d2m, D2D _d2d) : ID(_ID), UN(_UN), op(_op), d2m(_d2m), d2d(_d2d) { int n = leaves.size(); init_space(n); copy(leaves.begin(), leaves.end(), a.begin() + N); build(); } void init_space(int n) { N = 1; L = 0; while (N < n) N <<= 1, L++; a.assign(N<<1, ID); d.assign(N, UN); } inline void pull(int i) { a[i] = op(a[i<<1], a[i<<1|1]); } void build() { for (int i = N-1; i >= 1; i--) pull(i); } inline int len(int i) { return 1 << (L + __builtin_clz(i) - 31); } inline void apply(int i, const D& dval) { d2m(a[i], dval); if (i < N) d2d(d[i], dval); } inline void push(int i) { apply(i<<1, d[i]); apply(i<<1|1, d[i]); d[i] = UN; } void update(int l, int r, const D& dval, int i, int sl, int sr) { if (r <= sl || sr <= l) return; if (l <= sl && sr <= r) return apply(i, dval); int sm = (sl+sr)>>1, il = i<<1, ir = i<<1|1; push(i); update(l, r, dval, il, sl, sm); update(l, r, dval, ir, sm, sr); pull(i); } M query(int l, int r, int i, int sl, int sr) { if (r <= sl || sr <= l) return ID; if (l <= sl && sr <= r) return a[i]; push(i); int sm = (sl+sr)>>1, il = i<<1, ir = i<<1|1; return op(query(l, r, il, sl, sm), query(l, r, ir, sm, sr)); } void update(int l, int r, const D& dval) { assert(0 <= l && r <= N); update(l, r, dval, 1, 0, N); } void assign(int p, const M& x) { assert(0 <= p && p < N); p += N; for (int k = L; k >= 1; k--) push(p >> k); for (a[p] = x; p >>= 1; ) pull(p); } M query(int l, int r) { assert(0 <= l && r <= N); return query(l, r, 1, 0, N); } M query_point(int p) { assert(0 <= p && p < N); p += N; for (int k = L; k >= 1; k--) push(p >> k); return a[p]; } M query_all() const { return a[1]; } }; void solve() { int n,q; cin >> n >> q; vector<int> a(n); for (auto& x: a) { cin >> x; } SegLazy<int,int> rmi (a, 1e9, 0, [](int u, int v){ return min(u,v); }, [](int& u, int x){ u += x; }, [](int& x, int y){ x += y; } ); auto rmi2 = rmi; vector<vector<pair<int,int>>> evs(n+1); vector<vector<pair<int,int>>> evs2(n+1); for (int _ = 0; _ < q; _++) { int x,y; cin >> x >> y; x--; evs[y].emplace_back(x, _); evs2[x].emplace_back(y, _); } int res = 0; vector<int> certi; {// fix r as max, use all seg before to min before vector<int> que; for (int r = 1; r < n; r++) { for (auto& _: evs[r]) { int l, k; tie(l, k) = _; que.push_back(k); rmi.update(l, r, -1); } int mi = rmi.query(0, r); int d = a[r] - mi; if (d > res) { res = d; certi = que; } } } {// other side vector<int> que; for (int l = n-1; l >= 1; l--) { for (auto& _: evs2[l]) { int r, k; tie(r, k) = _; que.push_back(k); rmi2.update(l, r, -1); } int mi = rmi2.query(l, n); int d = a[l-1] - mi; if (d > res) { res = d; certi = que; } } } cout << res << "\n"; cout << certi.size() << "\n"; for (auto& x: certi) { cout << x+1 << ' '; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
26.915663
81
0.409355
[ "vector" ]
33501c00fc62325261fe5636a848cb1002325402
651
cpp
C++
src/sysex/getmixerinputcontrol.cpp
dehnhardt/mioconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
16
2018-07-16T14:13:10.000Z
2021-02-07T06:43:57.000Z
src/sysex/getmixerinputcontrol.cpp
dehnhardt/iconnconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
16
2017-09-06T19:38:15.000Z
2021-01-04T17:54:02.000Z
src/sysex/getmixerinputcontrol.cpp
dehnhardt/mioconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
10
2018-03-03T14:50:03.000Z
2020-09-30T18:08:55.000Z
#include "getmixerinputcontrol.h" #include "retmixerinputcontrol.h" GetMixerInputControl::GetMixerInputControl(Device *device) : PortSysExMessage(GET_MIXER_INPUT_CONTROL, SysExMessage::QUERY, device) {} GetMixerInputControl::~GetMixerInputControl() {} void GetMixerInputControl::createAnswer(Command m_Command, std::vector<unsigned char> *message, Device *m_pDevice) { m_pAnswer = std::make_shared<RetMixerInputControl>(m_Command, message, m_pDevice); if (debug) m_pAnswer->setDebug(true); m_pAnswer->parseAnswerData(); } std::vector<unsigned char> *GetMixerInputControl::getMessageData() { return getPortIdBytes(); }
29.590909
76
0.768049
[ "vector" ]
33507e50979941c756c5b38c370f7aa6a889817a
2,633
cpp
C++
src/ioDataProvider/Array.cpp
peramic/OPC-UA.Server
ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97
[ "Apache-2.0" ]
null
null
null
src/ioDataProvider/Array.cpp
peramic/OPC-UA.Server
ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97
[ "Apache-2.0" ]
null
null
null
src/ioDataProvider/Array.cpp
peramic/OPC-UA.Server
ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97
[ "Apache-2.0" ]
null
null
null
#include <ioDataProvider/Array.h> #include <sstream> // std::ostringstream #ifdef DEBUG #include <CppUTest/MemoryLeakDetectorNewMacros.h> #endif namespace IODataProviderNamespace { class ArrayPrivate { friend class Array; private: int arrayType; const std::vector<const Variant*>* elements; bool hasAttachedValues; }; Array::Array(int arrayType, const std::vector<const Variant*>* elements, bool attachValues) { d = new ArrayPrivate(); d->arrayType = arrayType; d->elements = elements; d->hasAttachedValues = attachValues; } Array::Array(const Array& array) { // avoid self-assignment if (this == &array) { return; } d = new ArrayPrivate(); d->arrayType = array.d->arrayType; std::vector<const Variant*>* newElements = NULL; if (array.d->elements != NULL) { newElements = new std::vector<const Variant*>(); for (std::vector<const Variant*>::const_iterator i = array.d->elements->begin(); i != array.d->elements->end(); i++) { newElements->push_back((*i)->copy()); } } d->elements = newElements; d->hasAttachedValues = true; } Array::~Array() { if (d->hasAttachedValues) { if (d->elements != NULL) { for (std::vector<const Variant*>::const_iterator i = d->elements->begin(); i != d->elements->end(); i++) { delete *i; } delete d->elements; } } delete d; } int Array::getArrayType() const { return d->arrayType; } const std::vector<const Variant*>* Array::getElements() const { return d->elements; } Variant* Array::copy() const { return new Array(*this); } Variant::Type Array::getVariantType() const { return ARRAY; } std::string Array::toString() const { std::ostringstream msg; msg << "IODataProviderNamespace::Array[type=" << d->arrayType << ",elements="; if (d->elements == NULL) { msg << "<NULL>"; } else { for (std::vector<const Variant*>::const_iterator i = d->elements->begin(); i != d->elements->end(); i++) { if (i != d->elements->begin()) { msg << ","; } msg << (*i)->toString(); } } msg << "]"; return msg.str(); } } // namespace IODataProviderNamespace
28.934066
97
0.510824
[ "vector" ]
335298eaef456cd052e1aed3e668a0fa34728060
1,517
cpp
C++
depth_breadth_search/leetcode_dfs/105_construct_binary_tree_from_preorder_and_inorder_traversal.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
depth_breadth_search/leetcode_dfs/105_construct_binary_tree_from_preorder_and_inorder_traversal.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
depth_breadth_search/leetcode_dfs/105_construct_binary_tree_from_preorder_and_inorder_traversal.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:04.000Z
2020-10-12T19:18:04.000Z
// // 105_construct_binary_tree_from_preorder_and_inorder_traversal.cpp // leetcode_dfs // // Created by Hadley on 25.08.20. // Copyright © 2020 Hadley. All rights reserved. // #include <iostream> #include <fstream> #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <stack> #include <cstring> #include <queue> #include <functional> #include <numeric> #include <map> #include <filesystem> #include <dirent.h> using namespace std; //Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: TreeNode* treeBuild(vector<int>& inorder, vector<int>& preorder, int l, int r){ if(l>r)return nullptr; TreeNode* t=new TreeNode(preorder[index]); int j=find(inorder.begin(),inorder.end(),preorder[index])-inorder.begin(); // cout<<index<<" "<<t->val<<" "<<j<<endl; index++; if(l==r)return t; t->left=treeBuild(inorder, preorder, l, j-1); t->right=treeBuild(inorder, preorder, j+1, r); return t; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return treeBuild(inorder, preorder, 0, preorder.size()-1); } private: int index=0; };
26.614035
91
0.649308
[ "vector" ]
335347b6c9cb25fcd5fca13e96988af81cf5fcb1
4,469
cc
C++
src/thread_test.cc
mohantypunit/trainc
0a8e42bdf86ea26d30cfc47376a8b285458d706a
[ "Apache-2.0" ]
2
2015-06-06T13:22:33.000Z
2015-06-07T03:45:04.000Z
src/thread_test.cc
edobashira/trainc
41ccbd1e79753b6db25eb5d3d318400a1c3e0fca
[ "Apache-2.0" ]
null
null
null
src/thread_test.cc
edobashira/trainc
41ccbd1e79753b6db25eb5d3d318400a1c3e0fca
[ "Apache-2.0" ]
null
null
null
// thread_test.cc // // 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. // // Copyright 2011 RWTH Aachen University. All Rights Reserved. // Author: rybach@cs.rwth-aachen.de (David Rybach) // // \file // Test functions for multi-threading functions #include <unistd.h> #include "thread.h" #include "unittest.h" namespace threads { class Shared { private: mutable Mutex lock_; int a_; public: Shared() : a_(0) {} void Inc() { lock_.Lock(); ++a_; lock_.Release(); } int Get() const { int r; lock_.Lock(); r = a_; lock_.Release(); return r; } }; class TestThread : public Thread { public: public: TestThread(Shared *data) : data_(data) {} protected: virtual void Run() { timeval now; gettimeofday(&now, 0); ::usleep(now.tv_usec); data_->Inc(); } Shared *data_; }; TEST(ThreadTest, Simple) { const int num_thread = 10; std::vector<TestThread*> threads; Shared data; for (int t = 0; t < num_thread; ++t) threads.push_back(new TestThread(&data)); for (int t = 0; t < num_thread; ++t) threads[t]->Start(); for (int t = 0; t < num_thread; ++t) threads[t]->Wait(); for (int t = 0; t < num_thread; ++t) delete threads[t]; EXPECT_EQ(data.Get(), num_thread); } class TestTask { public: explicit TestTask(int v = 0) { value = v; } int value; void Set(int v) { value = v; } }; class TestMapper { public: TestMapper* Clone() const { return new TestMapper(); } void Map(const TestTask &task) { sum += task.value; } void Reset() { sum = 0; } int sum; }; class TestPtrMapper { public: TestPtrMapper* Clone() const { return new TestPtrMapper(); } void Map(const TestTask *task) { sum += task->value; delete task; } void Reset() { sum = 0; } int sum; }; class TestPtrModifyMapper { public: TestPtrModifyMapper* Clone() const { return new TestPtrModifyMapper(); } void Map(TestTask *task) { task->Set(1); sum += task->value; } void Reset() { sum = 0; } int sum; }; class TestReducer { public: TestReducer() { sum = 0; } void Reduce(TestMapper *mapper) { sum += mapper->sum; } void Reduce(TestPtrMapper *mapper) { sum += mapper->sum; } void Reduce(TestPtrModifyMapper *mapper) { sum += mapper->sum; } int sum; }; TEST(ThreadPoolTest, Simple) { ThreadPool<TestTask, TestMapper, TestReducer> pool; TestMapper mapper; pool.Init(10, mapper); const int num_task = 100; for (int t = 0; t < num_task; ++t) { pool.Submit(TestTask(t)); } TestReducer reducer; pool.Combine(&reducer); VLOG(2) << "sum_: " << reducer.sum; EXPECT_EQ(reducer.sum, num_task*(num_task - 1)/2); } TEST(ThreadPoolTest, Pointer) { ThreadPool<TestTask*, TestPtrMapper, TestReducer> pool; TestPtrMapper mapper; pool.Init(10, mapper); const int num_task = 100; for (int t = 0; t < num_task; ++t) { pool.Submit(new TestTask(t)); } TestReducer reducer; pool.Combine(&reducer); VLOG(2) << "sum_: " << reducer.sum; EXPECT_EQ(reducer.sum, num_task*(num_task - 1)/2); } TEST(ThreadPoolTest, Modify) { ThreadPool<TestTask*, TestPtrModifyMapper, TestReducer> pool; TestPtrModifyMapper mapper; pool.Init(10, mapper); const int num_task = 100; for (int t = 0; t < num_task; ++t) { pool.Submit(new TestTask(t)); } TestReducer reducer; pool.Combine(&reducer); VLOG(2) << "sum_: " << reducer.sum; EXPECT_EQ(reducer.sum, num_task); } TEST(ThreadPoolTest, Reset) { ThreadPool<TestTask, TestMapper, TestReducer> pool; TestMapper mapper; pool.Init(10, mapper); int num_task = 100; for (int t = 0; t < num_task; ++t) { pool.Submit(TestTask(t)); } pool.Wait(); pool.Reset(); num_task = 10; for (int t = 0; t < num_task; ++t) { pool.Submit(TestTask(t)); } TestReducer reducer; pool.Combine(&reducer); VLOG(2) << "sum_: " << reducer.sum; EXPECT_EQ(reducer.sum, num_task*(num_task - 1)/2); } } // namespace threads
22.123762
75
0.642873
[ "vector" ]
33548b2cf5bd31a970f26bf99c93687c8b0bb423
8,655
cpp
C++
CesiumUtility/src/Tracing.cpp
zrkcode/cesium-native
5265a65053542fe02928c272762c6b89fa2b29bb
[ "Apache-2.0" ]
null
null
null
CesiumUtility/src/Tracing.cpp
zrkcode/cesium-native
5265a65053542fe02928c272762c6b89fa2b29bb
[ "Apache-2.0" ]
null
null
null
CesiumUtility/src/Tracing.cpp
zrkcode/cesium-native
5265a65053542fe02928c272762c6b89fa2b29bb
[ "Apache-2.0" ]
null
null
null
#include "CesiumUtility/Tracing.h" #include <algorithm> #include <cassert> #if CESIUM_TRACING_ENABLED namespace CesiumUtility { namespace Impl { Tracer& Tracer::instance() { static Tracer instance; return instance; } Tracer::~Tracer() { endTracing(); } void Tracer::startTracing(const std::string& filePath) { this->_output.open(filePath); this->_output << "{\"otherData\": {},\"traceEvents\":["; } void Tracer::endTracing() { this->_output << "]}"; this->_output.close(); } void Tracer::writeCompleteEvent(const Trace& trace) { std::lock_guard<std::mutex> lock(_lock); if (!this->_output) { return; } // Chrome tracing wants the text like this if (this->_numTraces++ > 0) { this->_output << ","; } this->_output << "{"; this->_output << "\"cat\":\"cesium\","; this->_output << "\"dur\":" << trace.duration << ','; this->_output << "\"name\":\"" << trace.name << "\","; this->_output << "\"ph\":\"X\","; this->_output << "\"pid\":0,"; this->_output << "\"tid\":" << trace.threadID << ","; this->_output << "\"ts\":" << trace.start; this->_output << "}"; } void Tracer::writeAsyncEventBegin(const char* name, int64_t id) { this->writeAsyncEvent("cesium", name, 'b', id); } void Tracer::writeAsyncEventBegin(const char* name) { this->writeAsyncEventBegin(name, this->getCurrentThreadTrackID()); } void Tracer::writeAsyncEventEnd(const char* name, int64_t id) { this->writeAsyncEvent("cesium", name, 'e', id); } void Tracer::writeAsyncEventEnd(const char* name) { this->writeAsyncEventEnd(name, this->getCurrentThreadTrackID()); } int64_t Tracer::allocateTrackID() { return ++this->_lastAllocatedID; } Tracer::Tracer() : _output{}, _numTraces{0}, _lock{}, _lastAllocatedID(0) {} int64_t Tracer::getCurrentThreadTrackID() const { const TrackReference* pTrack = TrackReference::current(); return pTrack->getTracingID(); } void Tracer::writeAsyncEvent( const char* category, const char* name, char type, int64_t id) { bool isAsync = true; if (id < 0) { // Use a standard Duration event for slices without an async ID. isAsync = false; if (type == 'b') { type = 'B'; } else if (type == 'e') { type = 'E'; } } std::chrono::steady_clock::time_point time = std::chrono::steady_clock::now(); int64_t microseconds = std::chrono::time_point_cast<std::chrono::microseconds>(time) .time_since_epoch() .count(); std::lock_guard<std::mutex> lock(_lock); if (!this->_output) { return; } // Chrome tracing wants the text like this if (this->_numTraces++ > 0) { this->_output << ","; } this->_output << "{"; this->_output << "\"cat\":\"" << category << "\","; if (isAsync) { this->_output << "\"id\":" << id << ","; } else { this->_output << "\"tid\":" << std::this_thread::get_id() << ","; } this->_output << "\"name\":\"" << name << "\","; this->_output << "\"ph\":\"" << type << "\","; this->_output << "\"pid\":0,"; this->_output << "\"ts\":" << microseconds; this->_output << "}"; } ScopedTrace::ScopedTrace(const std::string& message) : _name{message}, _startTime{std::chrono::steady_clock::now()}, _threadId{std::this_thread::get_id()}, _reset{false} { CESIUM_TRACE_BEGIN_IN_TRACK(_name.c_str()); } ScopedTrace::~ScopedTrace() { if (!this->_reset) { this->reset(); } } void ScopedTrace::reset() { this->_reset = true; if (TrackReference::current() != nullptr) { CESIUM_TRACE_END(_name.c_str()); } else { auto endTimePoint = std::chrono::steady_clock::now(); int64_t start = std::chrono::time_point_cast<std::chrono::microseconds>( this->_startTime) .time_since_epoch() .count(); int64_t end = std::chrono::time_point_cast<std::chrono::microseconds>(endTimePoint) .time_since_epoch() .count(); Tracer::instance().writeCompleteEvent( {this->_name, start, end - start, this->_threadId}); } } TrackSet::TrackSet(const char* name_) : name(name_) {} TrackSet::~TrackSet() { std::scoped_lock lock(this->mutex); for (auto& track : this->tracks) { assert(!track.inUse); Tracer::instance().writeAsyncEventEnd( (this->name + " " + std::to_string(track.id)).c_str(), track.id); } } size_t TrackSet::acquireTrack() { std::scoped_lock lock(this->mutex); auto it = std::find_if(this->tracks.begin(), this->tracks.end(), [](auto& track) { return track.inUse == false; }); if (it != this->tracks.end()) { it->inUse = true; return size_t(it - this->tracks.begin()); } else { Track track{Tracer::instance().allocateTrackID(), true}; Tracer::instance().writeAsyncEventBegin( (this->name + " " + std::to_string(track.id)).c_str(), track.id); size_t index = this->tracks.size(); this->tracks.emplace_back(track); return index; } } void TrackSet::addReference(size_t trackIndex) noexcept { std::scoped_lock lock(this->mutex); ++this->tracks[trackIndex].referenceCount; } void TrackSet::releaseReference(size_t trackIndex) noexcept { std::scoped_lock lock(this->mutex); Track& track = this->tracks[trackIndex]; assert(track.referenceCount > 0); --track.referenceCount; if (track.referenceCount == 0) { track.inUse = false; } } int64_t TrackSet::getTracingID(size_t trackIndex) noexcept { std::scoped_lock lock(this->mutex); if (trackIndex >= this->tracks.size()) { return -1; } return this->tracks[trackIndex].id; } LambdaCaptureTrack::LambdaCaptureTrack() : pSet(nullptr), index(0) { const TrackReference* pTrack = TrackReference::current(); if (pTrack) { this->pSet = pTrack->pSet; this->index = pTrack->index; if (this->pSet) { this->pSet->addReference(this->index); } } } LambdaCaptureTrack::LambdaCaptureTrack(const LambdaCaptureTrack& rhs) noexcept : pSet(rhs.pSet), index(rhs.index) { if (this->pSet) { this->pSet->addReference(this->index); } } LambdaCaptureTrack::LambdaCaptureTrack(LambdaCaptureTrack&& rhs) noexcept : pSet(rhs.pSet), index(rhs.index) { rhs.pSet = nullptr; rhs.index = 0; } LambdaCaptureTrack::~LambdaCaptureTrack() { if (this->pSet) { this->pSet->releaseReference(this->index); } } LambdaCaptureTrack& LambdaCaptureTrack::operator=(const LambdaCaptureTrack& rhs) noexcept { if (rhs.pSet) { rhs.pSet->addReference(rhs.index); } if (this->pSet) { this->pSet->releaseReference(this->index); } this->pSet = rhs.pSet; this->index = rhs.index; return *this; } LambdaCaptureTrack& LambdaCaptureTrack::operator=(LambdaCaptureTrack&& rhs) noexcept { if (this->pSet) { this->pSet->releaseReference(this->index); } this->pSet = rhs.pSet; this->index = rhs.index; rhs.pSet = nullptr; rhs.index = 0; return *this; } /*static*/ thread_local std::vector<TrackReference*> TrackReference::_threadEnlistedTracks{}; /*static*/ TrackReference* TrackReference::current() { return TrackReference::_threadEnlistedTracks.empty() ? nullptr : TrackReference::_threadEnlistedTracks.back(); } TrackReference::TrackReference(TrackSet& set) noexcept : TrackReference(set, set.acquireTrack()) {} TrackReference::TrackReference(TrackSet& set, size_t index_) noexcept : pSet(&set), index(index_) { this->pSet->addReference(this->index); this->enlistCurrentThread(); } TrackReference::TrackReference(const LambdaCaptureTrack& lambdaCapture) noexcept : pSet(lambdaCapture.pSet), index(lambdaCapture.index) { if (this->pSet) { this->pSet->addReference(this->index); this->enlistCurrentThread(); } } TrackReference::~TrackReference() noexcept { if (this->pSet) { this->dismissCurrentThread(); this->pSet->releaseReference(this->index); } } TrackReference::operator bool() const noexcept { return this->pSet != nullptr; } int64_t TrackReference::getTracingID() const noexcept { if (this->pSet) { return this->pSet->getTracingID(this->index); } else { return -1; } } void TrackReference::enlistCurrentThread() { if (!this->pSet) { return; } TrackReference::_threadEnlistedTracks.emplace_back(this); } void TrackReference::dismissCurrentThread() { if (!this->pSet) { return; } assert( TrackReference::_threadEnlistedTracks.size() > 0 && TrackReference::_threadEnlistedTracks.back() == this); TrackReference::_threadEnlistedTracks.pop_back(); } } // namespace Impl } // namespace CesiumUtility #endif // CESIUM_TRACING_ENABLED
25.530973
80
0.640901
[ "vector" ]
335929b932271355d4bc3fdd7e58849cfb8cebe9
8,330
cpp
C++
src/test/upgrade_test/upgrade_testor.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
1,352
2017-10-16T03:24:54.000Z
2020-08-18T04:44:23.000Z
src/test/upgrade_test/upgrade_testor.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
299
2017-10-19T05:33:32.000Z
2020-08-17T09:03:39.000Z
src/test/upgrade_test/upgrade_testor.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
240
2017-10-16T05:57:04.000Z
2020-08-18T10:02:36.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 <list> #include <dsn/c/api_utilities.h> #include <dsn/service_api_cpp.h> #include "upgrade_testor.h" namespace pegasus { namespace test { // 在[a,b]之间生成cnt个不同的随机数到res void upgrade_testor::generate_random(std::vector<int> &res, int cnt, int a, int b) { res.clear(); if (a > b) std::swap(a, b); cnt = std::min(cnt, b - a + 1); std::unordered_set<int> numbers; int tvalue; for (int i = 0; i < cnt; i++) { tvalue = (rand() % (b - a + 1)) + a; while (numbers.find(tvalue) != numbers.end()) { tvalue = (rand() % (b - a + 1)) + a; } numbers.insert(tvalue); res.emplace_back(tvalue); } } int upgrade_testor::generate_one_number(int a, int b) { if (a > b) std::swap(a, b); return ((rand() % (b - a + 1)) + a); } upgrade_testor::upgrade_testor() { const char *section = "pegasus.upgradetest"; upgrade_round = 0; // initialize upgrader_handler std::string upgrader_name = dsn_config_get_value_string(section, "upgrade_handler", "", "upgrade handler"); dassert(upgrader_name.size() > 0, ""); _upgrader_handler.reset(upgrader_handler::new_handler(upgrader_name.c_str())); dassert(_upgrader_handler.get() != nullptr, "invalid upgrader_name(%s)", upgrader_name.c_str()); _job_types = {META, REPLICA, ZOOKEEPER}; _job_index_to_upgrade.resize(JOB_LENGTH); _sleep_time_before_recover_seconds = (uint32_t)dsn_config_get_value_uint64( section, "sleep_time_before_recover_seconds", 30, "sleep time before recover seconds"); _total_meta_count = (int32_t)dsn_config_get_value_uint64(section, "total_meta_count", 0, "total meta count"); _total_replica_count = (int32_t)dsn_config_get_value_uint64( section, "total_replica_count", 0, "total replica count"); _total_zookeeper_count = (int32_t)dsn_config_get_value_uint64( section, "total_zookeeper_count", 0, "total zookeeper count"); if (_total_meta_count == 0 && _total_replica_count == 0 && _total_zookeeper_count == 0) { dassert(false, "total number of meta/replica/zookeeper is 0"); } _upgrade_replica_max_count = (int32_t)dsn_config_get_value_uint64( section, "upgrade_replica_max_count", _total_replica_count, "replica upgradeed max count"); _upgrade_meta_max_count = (int32_t)dsn_config_get_value_uint64( section, "upgrade_meta_max_count", _total_meta_count, "meta upgradeed max count"); _upgrade_zk_max_count = (int32_t)dsn_config_get_value_uint64(section, "upgrade_zookeeper_max_count", _total_zookeeper_count, "zookeeper upgradeed max count"); srand((unsigned)time(nullptr)); } upgrade_testor::~upgrade_testor() {} void upgrade_testor::stop_verifier_and_exit(const char *msg) { system("ps aux | grep verifier | grep -v grep| awk '{print $2}' | xargs kill -9"); dassert(false, "%s", msg); } bool upgrade_testor::check_coredump() { bool has_core = false; // make sure all generated core are logged for (int i = 1; i <= _total_meta_count; ++i) { if (_upgrader_handler->has_meta_dumped_core(i)) { derror("meta server %d generate core dump", i); has_core = true; } } for (int i = 1; i <= _total_replica_count; ++i) { if (_upgrader_handler->has_replica_dumped_core(i)) { derror("replica server %d generate core dump", i); has_core = true; } } return has_core; } void upgrade_testor::run() { if (check_coredump()) { stop_verifier_and_exit("detect core dump in pegasus cluster"); } if (upgrade_round == 0) { ddebug("Number of meta-server: %d", _total_meta_count); ddebug("Number of replica-server: %d", _total_replica_count); ddebug("Number of zookeeper: %d", _total_zookeeper_count); } upgrade_round += 1; int meta_cnt = 0; int replica_cnt = 0; int zk_cnt = 0; while (replica_cnt == 0) { replica_cnt = generate_one_number(1, _upgrade_replica_max_count); } ddebug("************************"); ddebug("Round [%d]", upgrade_round); ddebug("start upgrade..."); ddebug( "upgrade meta number=%d, replica number=%d, zk number=%d", meta_cnt, replica_cnt, zk_cnt); if (!upgrade(replica_cnt)) { stop_verifier_and_exit("upgrade jobs failed"); } auto sleep_time_random_seconds = generate_one_number(1, _sleep_time_before_recover_seconds); ddebug("sleep %d seconds before downgrade", sleep_time_random_seconds); sleep(sleep_time_random_seconds); ddebug("start downgrade..."); if (!downgrade()) { stop_verifier_and_exit("downgrade jobs failed"); } ddebug("after downgrade..."); ddebug("************************"); } bool upgrade_testor::upgrade(int replica_cnt) { std::vector<int> upgrade_counts = {0, replica_cnt, 0}; std::vector<int> total_count = { _total_meta_count, _total_replica_count, _total_zookeeper_count}; std::vector<int> random_idxs; generate_random(random_idxs, 1 /*REPLICA - REPLICA + 1*/, REPLICA, REPLICA); // 生成type列表 for (auto id : random_idxs) { std::vector<int> &job_index_to_upgrade = _job_index_to_upgrade[_job_types[id]]; job_index_to_upgrade.clear(); generate_random(job_index_to_upgrade, upgrade_counts[id], 1, total_count[id]); // 生成该type需要upgrade的index列表 for (auto index : job_index_to_upgrade) { ddebug("start to upgrade %s@%d", job_type_str(_job_types[id]), index); if (!upgrade_job_by_index(_job_types[id], index)) { ddebug("upgrade %s@%d failed", job_type_str(_job_types[id]), index); return false; } ddebug("upgrade %s@%d succeed", job_type_str(_job_types[id]), index); } } return true; } bool upgrade_testor::downgrade() { std::vector<int> random_idxs; generate_random(random_idxs, JOB_LENGTH, META, ZOOKEEPER); for (auto id : random_idxs) { std::vector<int> &job_index_to_upgrade = _job_index_to_upgrade[_job_types[id]]; for (auto index : job_index_to_upgrade) { ddebug("start to downgrade %s@%d", job_type_str(_job_types[id]), index); if (!downgrade_job_by_index(_job_types[id], index)) { ddebug("downgrade %s@%d failed", job_type_str(_job_types[id]), index); return false; } ddebug("downgrade %s@%d succeed", job_type_str(_job_types[id]), index); } } return true; } bool upgrade_testor::upgrade_job_by_index(job_type type, int index) { if (type == META) return _upgrader_handler->upgrade_meta(index); if (type == REPLICA) return _upgrader_handler->upgrade_replica(index); if (type == ZOOKEEPER) return _upgrader_handler->upgrade_zookeeper(index); return false; } bool upgrade_testor::downgrade_job_by_index(job_type type, int index) { if (type == META) return _upgrader_handler->downgrade_meta(index); if (type == REPLICA) return _upgrader_handler->downgrade_replica(index); if (type == ZOOKEEPER) return _upgrader_handler->downgrade_zookeeper(index); return false; } } } // end namespace
36.060606
100
0.642377
[ "vector" ]
335be79220599c119ddb494bd3f5851deb1707e0
1,554
cpp
C++
Test/main.cpp
lc8882972/c
8f7594b70f756c8ff0887fd79527f6d4548b85a8
[ "MIT" ]
null
null
null
Test/main.cpp
lc8882972/c
8f7594b70f756c8ff0887fd79527f6d4548b85a8
[ "MIT" ]
null
null
null
Test/main.cpp
lc8882972/c
8f7594b70f756c8ff0887fd79527f6d4548b85a8
[ "MIT" ]
null
null
null
// Test.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "string" #include <iostream> #include <algorithm> #include <functional> #include <fstream> #include "student.h" using namespace std; //一、一维数组 //静态 int array[100];   定义了数组array,并未对数组进行初始化 //静态 int array[100] = { 1,2 };  定义并初始化了数组array //动态 int* array = new int[100];  delete[]array;  分配了长度为100的数组array  //动态 int* array = new int[100](1,2);  delete[]array; 为长度为100的数组array初始化前两个元素 int main() { string s = ""; string s1[] = { "1","2" }; //string* s2 = new string[5]; cout << "11"; char a; cin >> a; cout << a; int arr[] = { 1,2,3,4,5 }; reverse(arr, arr + 5); for (int i = 0; i < 5; i++) { cout << arr[i]; } cin >> a; ofstream of; char ch[15], * p = "abcdefg"; of.open("my.txt"); of << p; of << "Goodbye!"; of.close(); ifstream * iftream =new ifstream(); iftream ->open("my.txt",ios_base::in); iftream->close(); delete iftream; vector<int> ivec(10,1); for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter) { *iter = 2; //使用 * 访问迭代器所指向的元素 } return 0; } class MyClass { public: MyClass(); ~MyClass(); private: }; MyClass::MyClass() { } MyClass::~MyClass() { } struct list { double salary; char name[20]; friend ostream &operator <<(ostream &os, list&ob); friend istream &operator >>(istream &is, list&ob); }; ostream &operator <<(ostream &os, list&ob) { os << ob.name << ' '; os << ob.salary << ' '; return os; } istream &operator >>(istream &is, list&ob) { is >> ob.name; is >> ob.salary; return is; }
15.69697
76
0.595238
[ "vector" ]
336480e8b9d9904dddc59ddfc0ebbcbbad70a373
59,997
cpp
C++
llvm/lib/Analysis/TargetLibraryInfo.cpp
tiwaria1/llvm
616a396db0610ae0c1992361af005a869ef81897
[ "Apache-2.0" ]
1
2020-09-10T01:00:18.000Z
2020-09-10T01:00:18.000Z
llvm/lib/Analysis/TargetLibraryInfo.cpp
coolstar/llvm-project
e21ccdd5b5667de50de65ee8903a89a21020e89a
[ "Apache-2.0" ]
null
null
null
llvm/lib/Analysis/TargetLibraryInfo.cpp
coolstar/llvm-project
e21ccdd5b5667de50de65ee8903a89a21020e89a
[ "Apache-2.0" ]
null
null
null
//===-- TargetLibraryInfo.cpp - Runtime library information ----------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the TargetLibraryInfo class. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/ADT/Triple.h" #include "llvm/IR/Constants.h" #include "llvm/InitializePasses.h" #include "llvm/Support/CommandLine.h" using namespace llvm; static cl::opt<TargetLibraryInfoImpl::VectorLibrary> ClVectorLibrary( "vector-library", cl::Hidden, cl::desc("Vector functions library"), cl::init(TargetLibraryInfoImpl::NoLibrary), cl::values(clEnumValN(TargetLibraryInfoImpl::NoLibrary, "none", "No vector functions library"), clEnumValN(TargetLibraryInfoImpl::Accelerate, "Accelerate", "Accelerate framework"), clEnumValN(TargetLibraryInfoImpl::MASSV, "MASSV", "IBM MASS vector library"), clEnumValN(TargetLibraryInfoImpl::SVML, "SVML", "Intel SVML library"))); StringLiteral const TargetLibraryInfoImpl::StandardNames[LibFunc::NumLibFuncs] = { #define TLI_DEFINE_STRING #include "llvm/Analysis/TargetLibraryInfo.def" }; static bool hasSinCosPiStret(const Triple &T) { // Only Darwin variants have _stret versions of combined trig functions. if (!T.isOSDarwin()) return false; // The ABI is rather complicated on x86, so don't do anything special there. if (T.getArch() == Triple::x86) return false; if (T.isMacOSX() && T.isMacOSXVersionLT(10, 9)) return false; if (T.isiOS() && T.isOSVersionLT(7, 0)) return false; return true; } static bool hasBcmp(const Triple &TT) { // Posix removed support from bcmp() in 2001, but the glibc and several // implementations of the libc still have it. if (TT.isOSLinux()) return TT.isGNUEnvironment() || TT.isMusl(); // Both NetBSD and OpenBSD are planning to remove the function. Windows does // not have it. return TT.isOSFreeBSD() || TT.isOSSolaris(); } /// Initialize the set of available library functions based on the specified /// target triple. This should be carefully written so that a missing target /// triple gets a sane set of defaults. static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, ArrayRef<StringLiteral> StandardNames) { // Verify that the StandardNames array is in alphabetical order. assert( llvm::is_sorted(StandardNames, [](StringRef LHS, StringRef RHS) { return LHS < RHS; }) && "TargetLibraryInfoImpl function names must be sorted"); // Set IO unlocked variants as unavailable // Set them as available per system below TLI.setUnavailable(LibFunc_getchar_unlocked); TLI.setUnavailable(LibFunc_putc_unlocked); TLI.setUnavailable(LibFunc_putchar_unlocked); TLI.setUnavailable(LibFunc_fputc_unlocked); TLI.setUnavailable(LibFunc_fgetc_unlocked); TLI.setUnavailable(LibFunc_fread_unlocked); TLI.setUnavailable(LibFunc_fwrite_unlocked); TLI.setUnavailable(LibFunc_fputs_unlocked); TLI.setUnavailable(LibFunc_fgets_unlocked); bool ShouldExtI32Param = false, ShouldExtI32Return = false, ShouldSignExtI32Param = false; // PowerPC64, Sparc64, SystemZ need signext/zeroext on i32 parameters and // returns corresponding to C-level ints and unsigned ints. if (T.isPPC64() || T.getArch() == Triple::sparcv9 || T.getArch() == Triple::systemz) { ShouldExtI32Param = true; ShouldExtI32Return = true; } // Mips, on the other hand, needs signext on i32 parameters corresponding // to both signed and unsigned ints. if (T.isMIPS()) { ShouldSignExtI32Param = true; } TLI.setShouldExtI32Param(ShouldExtI32Param); TLI.setShouldExtI32Return(ShouldExtI32Return); TLI.setShouldSignExtI32Param(ShouldSignExtI32Param); if (T.isAMDGPU()) TLI.disableAllFunctions(); // There are no library implementations of memcpy and memset for AMD gpus and // these can be difficult to lower in the backend. if (T.isAMDGPU()) { TLI.setUnavailable(LibFunc_memcpy); TLI.setUnavailable(LibFunc_memset); TLI.setUnavailable(LibFunc_memset_pattern16); return; } // memset_pattern16 is only available on iOS 3.0 and Mac OS X 10.5 and later. // All versions of watchOS support it. if (T.isMacOSX()) { // available IO unlocked variants on Mac OS X TLI.setAvailable(LibFunc_getc_unlocked); TLI.setAvailable(LibFunc_getchar_unlocked); TLI.setAvailable(LibFunc_putc_unlocked); TLI.setAvailable(LibFunc_putchar_unlocked); if (T.isMacOSXVersionLT(10, 5)) TLI.setUnavailable(LibFunc_memset_pattern16); } else if (T.isiOS()) { if (T.isOSVersionLT(3, 0)) TLI.setUnavailable(LibFunc_memset_pattern16); } else if (!T.isWatchOS()) { TLI.setUnavailable(LibFunc_memset_pattern16); } if (!hasSinCosPiStret(T)) { TLI.setUnavailable(LibFunc_sinpi); TLI.setUnavailable(LibFunc_sinpif); TLI.setUnavailable(LibFunc_cospi); TLI.setUnavailable(LibFunc_cospif); TLI.setUnavailable(LibFunc_sincospi_stret); TLI.setUnavailable(LibFunc_sincospif_stret); } if (!hasBcmp(T)) TLI.setUnavailable(LibFunc_bcmp); if (T.isMacOSX() && T.getArch() == Triple::x86 && !T.isMacOSXVersionLT(10, 7)) { // x86-32 OSX has a scheme where fwrite and fputs (and some other functions // we don't care about) have two versions; on recent OSX, the one we want // has a $UNIX2003 suffix. The two implementations are identical except // for the return value in some edge cases. However, we don't want to // generate code that depends on the old symbols. TLI.setAvailableWithName(LibFunc_fwrite, "fwrite$UNIX2003"); TLI.setAvailableWithName(LibFunc_fputs, "fputs$UNIX2003"); } // iprintf and friends are only available on XCore, TCE, and Emscripten. if (T.getArch() != Triple::xcore && T.getArch() != Triple::tce && T.getOS() != Triple::Emscripten) { TLI.setUnavailable(LibFunc_iprintf); TLI.setUnavailable(LibFunc_siprintf); TLI.setUnavailable(LibFunc_fiprintf); } // __small_printf and friends are only available on Emscripten. if (T.getOS() != Triple::Emscripten) { TLI.setUnavailable(LibFunc_small_printf); TLI.setUnavailable(LibFunc_small_sprintf); TLI.setUnavailable(LibFunc_small_fprintf); } if (T.isOSWindows() && !T.isOSCygMing()) { // XXX: The earliest documentation available at the moment is for VS2015/VC19: // https://docs.microsoft.com/en-us/cpp/c-runtime-library/floating-point-support?view=vs-2015 // XXX: In order to use an MSVCRT older than VC19, // the specific library version must be explicit in the target triple, // e.g., x86_64-pc-windows-msvc18. bool hasPartialC99 = true; if (T.isKnownWindowsMSVCEnvironment()) { unsigned Major, Minor, Micro; T.getEnvironmentVersion(Major, Minor, Micro); hasPartialC99 = (Major == 0 || Major >= 19); } // Latest targets support C89 math functions, in part. bool isARM = (T.getArch() == Triple::aarch64 || T.getArch() == Triple::arm); bool hasPartialFloat = (isARM || T.getArch() == Triple::x86_64); // Win32 does not support float C89 math functions, in general. if (!hasPartialFloat) { TLI.setUnavailable(LibFunc_acosf); TLI.setUnavailable(LibFunc_asinf); TLI.setUnavailable(LibFunc_atan2f); TLI.setUnavailable(LibFunc_atanf); TLI.setUnavailable(LibFunc_ceilf); TLI.setUnavailable(LibFunc_cosf); TLI.setUnavailable(LibFunc_coshf); TLI.setUnavailable(LibFunc_expf); TLI.setUnavailable(LibFunc_floorf); TLI.setUnavailable(LibFunc_fmodf); TLI.setUnavailable(LibFunc_log10f); TLI.setUnavailable(LibFunc_logf); TLI.setUnavailable(LibFunc_modff); TLI.setUnavailable(LibFunc_powf); TLI.setUnavailable(LibFunc_remainderf); TLI.setUnavailable(LibFunc_sinf); TLI.setUnavailable(LibFunc_sinhf); TLI.setUnavailable(LibFunc_sqrtf); TLI.setUnavailable(LibFunc_tanf); TLI.setUnavailable(LibFunc_tanhf); } if (!isARM) TLI.setUnavailable(LibFunc_fabsf); TLI.setUnavailable(LibFunc_frexpf); TLI.setUnavailable(LibFunc_ldexpf); // Win32 does not support long double C89 math functions. TLI.setUnavailable(LibFunc_acosl); TLI.setUnavailable(LibFunc_asinl); TLI.setUnavailable(LibFunc_atan2l); TLI.setUnavailable(LibFunc_atanl); TLI.setUnavailable(LibFunc_ceill); TLI.setUnavailable(LibFunc_cosl); TLI.setUnavailable(LibFunc_coshl); TLI.setUnavailable(LibFunc_expl); TLI.setUnavailable(LibFunc_fabsl); TLI.setUnavailable(LibFunc_floorl); TLI.setUnavailable(LibFunc_fmodl); TLI.setUnavailable(LibFunc_frexpl); TLI.setUnavailable(LibFunc_ldexpl); TLI.setUnavailable(LibFunc_log10l); TLI.setUnavailable(LibFunc_logl); TLI.setUnavailable(LibFunc_modfl); TLI.setUnavailable(LibFunc_powl); TLI.setUnavailable(LibFunc_remainderl); TLI.setUnavailable(LibFunc_sinl); TLI.setUnavailable(LibFunc_sinhl); TLI.setUnavailable(LibFunc_sqrtl); TLI.setUnavailable(LibFunc_tanl); TLI.setUnavailable(LibFunc_tanhl); // Win32 does not fully support C99 math functions. if (!hasPartialC99) { TLI.setUnavailable(LibFunc_acosh); TLI.setUnavailable(LibFunc_acoshf); TLI.setUnavailable(LibFunc_asinh); TLI.setUnavailable(LibFunc_asinhf); TLI.setUnavailable(LibFunc_atanh); TLI.setUnavailable(LibFunc_atanhf); TLI.setAvailableWithName(LibFunc_cabs, "_cabs"); TLI.setUnavailable(LibFunc_cabsf); TLI.setUnavailable(LibFunc_cbrt); TLI.setUnavailable(LibFunc_cbrtf); TLI.setAvailableWithName(LibFunc_copysign, "_copysign"); TLI.setAvailableWithName(LibFunc_copysignf, "_copysignf"); TLI.setUnavailable(LibFunc_exp2); TLI.setUnavailable(LibFunc_exp2f); TLI.setUnavailable(LibFunc_expm1); TLI.setUnavailable(LibFunc_expm1f); TLI.setUnavailable(LibFunc_fmax); TLI.setUnavailable(LibFunc_fmaxf); TLI.setUnavailable(LibFunc_fmin); TLI.setUnavailable(LibFunc_fminf); TLI.setUnavailable(LibFunc_log1p); TLI.setUnavailable(LibFunc_log1pf); TLI.setUnavailable(LibFunc_log2); TLI.setUnavailable(LibFunc_log2f); TLI.setAvailableWithName(LibFunc_logb, "_logb"); if (hasPartialFloat) TLI.setAvailableWithName(LibFunc_logbf, "_logbf"); else TLI.setUnavailable(LibFunc_logbf); TLI.setUnavailable(LibFunc_rint); TLI.setUnavailable(LibFunc_rintf); TLI.setUnavailable(LibFunc_round); TLI.setUnavailable(LibFunc_roundf); TLI.setUnavailable(LibFunc_trunc); TLI.setUnavailable(LibFunc_truncf); } // Win32 does not support long double C99 math functions. TLI.setUnavailable(LibFunc_acoshl); TLI.setUnavailable(LibFunc_asinhl); TLI.setUnavailable(LibFunc_atanhl); TLI.setUnavailable(LibFunc_cabsl); TLI.setUnavailable(LibFunc_cbrtl); TLI.setUnavailable(LibFunc_copysignl); TLI.setUnavailable(LibFunc_exp2l); TLI.setUnavailable(LibFunc_expm1l); TLI.setUnavailable(LibFunc_fmaxl); TLI.setUnavailable(LibFunc_fminl); TLI.setUnavailable(LibFunc_log1pl); TLI.setUnavailable(LibFunc_log2l); TLI.setUnavailable(LibFunc_logbl); TLI.setUnavailable(LibFunc_nearbyintl); TLI.setUnavailable(LibFunc_rintl); TLI.setUnavailable(LibFunc_roundl); TLI.setUnavailable(LibFunc_truncl); // Win32 does not support these functions, but // they are generally available on POSIX-compliant systems. TLI.setUnavailable(LibFunc_access); TLI.setUnavailable(LibFunc_bcmp); TLI.setUnavailable(LibFunc_bcopy); TLI.setUnavailable(LibFunc_bzero); TLI.setUnavailable(LibFunc_chmod); TLI.setUnavailable(LibFunc_chown); TLI.setUnavailable(LibFunc_closedir); TLI.setUnavailable(LibFunc_ctermid); TLI.setUnavailable(LibFunc_fdopen); TLI.setUnavailable(LibFunc_ffs); TLI.setUnavailable(LibFunc_fileno); TLI.setUnavailable(LibFunc_flockfile); TLI.setUnavailable(LibFunc_fseeko); TLI.setUnavailable(LibFunc_fstat); TLI.setUnavailable(LibFunc_fstatvfs); TLI.setUnavailable(LibFunc_ftello); TLI.setUnavailable(LibFunc_ftrylockfile); TLI.setUnavailable(LibFunc_funlockfile); TLI.setUnavailable(LibFunc_getitimer); TLI.setUnavailable(LibFunc_getlogin_r); TLI.setUnavailable(LibFunc_getpwnam); TLI.setUnavailable(LibFunc_gettimeofday); TLI.setUnavailable(LibFunc_htonl); TLI.setUnavailable(LibFunc_htons); TLI.setUnavailable(LibFunc_lchown); TLI.setUnavailable(LibFunc_lstat); TLI.setUnavailable(LibFunc_memccpy); TLI.setUnavailable(LibFunc_mkdir); TLI.setUnavailable(LibFunc_ntohl); TLI.setUnavailable(LibFunc_ntohs); TLI.setUnavailable(LibFunc_open); TLI.setUnavailable(LibFunc_opendir); TLI.setUnavailable(LibFunc_pclose); TLI.setUnavailable(LibFunc_popen); TLI.setUnavailable(LibFunc_pread); TLI.setUnavailable(LibFunc_pwrite); TLI.setUnavailable(LibFunc_read); TLI.setUnavailable(LibFunc_readlink); TLI.setUnavailable(LibFunc_realpath); TLI.setUnavailable(LibFunc_rmdir); TLI.setUnavailable(LibFunc_setitimer); TLI.setUnavailable(LibFunc_stat); TLI.setUnavailable(LibFunc_statvfs); TLI.setUnavailable(LibFunc_stpcpy); TLI.setUnavailable(LibFunc_stpncpy); TLI.setUnavailable(LibFunc_strcasecmp); TLI.setUnavailable(LibFunc_strncasecmp); TLI.setUnavailable(LibFunc_times); TLI.setUnavailable(LibFunc_uname); TLI.setUnavailable(LibFunc_unlink); TLI.setUnavailable(LibFunc_unsetenv); TLI.setUnavailable(LibFunc_utime); TLI.setUnavailable(LibFunc_utimes); TLI.setUnavailable(LibFunc_write); } switch (T.getOS()) { case Triple::MacOSX: // exp10 and exp10f are not available on OS X until 10.9 and iOS until 7.0 // and their names are __exp10 and __exp10f. exp10l is not available on // OS X or iOS. TLI.setUnavailable(LibFunc_exp10l); if (T.isMacOSXVersionLT(10, 9)) { TLI.setUnavailable(LibFunc_exp10); TLI.setUnavailable(LibFunc_exp10f); } else { TLI.setAvailableWithName(LibFunc_exp10, "__exp10"); TLI.setAvailableWithName(LibFunc_exp10f, "__exp10f"); } break; case Triple::IOS: case Triple::TvOS: case Triple::WatchOS: TLI.setUnavailable(LibFunc_exp10l); if (!T.isWatchOS() && (T.isOSVersionLT(7, 0) || (T.isOSVersionLT(9, 0) && T.isX86()))) { TLI.setUnavailable(LibFunc_exp10); TLI.setUnavailable(LibFunc_exp10f); } else { TLI.setAvailableWithName(LibFunc_exp10, "__exp10"); TLI.setAvailableWithName(LibFunc_exp10f, "__exp10f"); } break; case Triple::Linux: // exp10, exp10f, exp10l is available on Linux (GLIBC) but are extremely // buggy prior to glibc version 2.18. Until this version is widely deployed // or we have a reasonable detection strategy, we cannot use exp10 reliably // on Linux. // // Fall through to disable all of them. LLVM_FALLTHROUGH; default: TLI.setUnavailable(LibFunc_exp10); TLI.setUnavailable(LibFunc_exp10f); TLI.setUnavailable(LibFunc_exp10l); } // ffsl is available on at least Darwin, Mac OS X, iOS, FreeBSD, and // Linux (GLIBC): // http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/ffsl.3.html // http://svn.freebsd.org/base/head/lib/libc/string/ffsl.c // http://www.gnu.org/software/gnulib/manual/html_node/ffsl.html switch (T.getOS()) { case Triple::Darwin: case Triple::MacOSX: case Triple::IOS: case Triple::TvOS: case Triple::WatchOS: case Triple::FreeBSD: case Triple::Linux: break; default: TLI.setUnavailable(LibFunc_ffsl); } // ffsll is available on at least FreeBSD and Linux (GLIBC): // http://svn.freebsd.org/base/head/lib/libc/string/ffsll.c // http://www.gnu.org/software/gnulib/manual/html_node/ffsll.html switch (T.getOS()) { case Triple::Darwin: case Triple::MacOSX: case Triple::IOS: case Triple::TvOS: case Triple::WatchOS: case Triple::FreeBSD: case Triple::Linux: break; default: TLI.setUnavailable(LibFunc_ffsll); } // The following functions are available on at least FreeBSD: // http://svn.freebsd.org/base/head/lib/libc/string/fls.c // http://svn.freebsd.org/base/head/lib/libc/string/flsl.c // http://svn.freebsd.org/base/head/lib/libc/string/flsll.c if (!T.isOSFreeBSD()) { TLI.setUnavailable(LibFunc_fls); TLI.setUnavailable(LibFunc_flsl); TLI.setUnavailable(LibFunc_flsll); } // The following functions are only available on GNU/Linux (using glibc). // Linux variants without glibc (eg: bionic, musl) may have some subset. if (!T.isOSLinux() || !T.isGNUEnvironment()) { TLI.setUnavailable(LibFunc_dunder_strdup); TLI.setUnavailable(LibFunc_dunder_strtok_r); TLI.setUnavailable(LibFunc_dunder_isoc99_scanf); TLI.setUnavailable(LibFunc_dunder_isoc99_sscanf); TLI.setUnavailable(LibFunc_under_IO_getc); TLI.setUnavailable(LibFunc_under_IO_putc); // But, Android and musl have memalign. if (!T.isAndroid() && !T.isMusl()) TLI.setUnavailable(LibFunc_memalign); TLI.setUnavailable(LibFunc_fopen64); TLI.setUnavailable(LibFunc_fseeko64); TLI.setUnavailable(LibFunc_fstat64); TLI.setUnavailable(LibFunc_fstatvfs64); TLI.setUnavailable(LibFunc_ftello64); TLI.setUnavailable(LibFunc_lstat64); TLI.setUnavailable(LibFunc_open64); TLI.setUnavailable(LibFunc_stat64); TLI.setUnavailable(LibFunc_statvfs64); TLI.setUnavailable(LibFunc_tmpfile64); // Relaxed math functions are included in math-finite.h on Linux (GLIBC). // Note that math-finite.h is no longer supported by top-of-tree GLIBC, // so we keep these functions around just so that they're recognized by // the ConstantFolder. TLI.setUnavailable(LibFunc_acos_finite); TLI.setUnavailable(LibFunc_acosf_finite); TLI.setUnavailable(LibFunc_acosl_finite); TLI.setUnavailable(LibFunc_acosh_finite); TLI.setUnavailable(LibFunc_acoshf_finite); TLI.setUnavailable(LibFunc_acoshl_finite); TLI.setUnavailable(LibFunc_asin_finite); TLI.setUnavailable(LibFunc_asinf_finite); TLI.setUnavailable(LibFunc_asinl_finite); TLI.setUnavailable(LibFunc_atan2_finite); TLI.setUnavailable(LibFunc_atan2f_finite); TLI.setUnavailable(LibFunc_atan2l_finite); TLI.setUnavailable(LibFunc_atanh_finite); TLI.setUnavailable(LibFunc_atanhf_finite); TLI.setUnavailable(LibFunc_atanhl_finite); TLI.setUnavailable(LibFunc_cosh_finite); TLI.setUnavailable(LibFunc_coshf_finite); TLI.setUnavailable(LibFunc_coshl_finite); TLI.setUnavailable(LibFunc_exp10_finite); TLI.setUnavailable(LibFunc_exp10f_finite); TLI.setUnavailable(LibFunc_exp10l_finite); TLI.setUnavailable(LibFunc_exp2_finite); TLI.setUnavailable(LibFunc_exp2f_finite); TLI.setUnavailable(LibFunc_exp2l_finite); TLI.setUnavailable(LibFunc_exp_finite); TLI.setUnavailable(LibFunc_expf_finite); TLI.setUnavailable(LibFunc_expl_finite); TLI.setUnavailable(LibFunc_log10_finite); TLI.setUnavailable(LibFunc_log10f_finite); TLI.setUnavailable(LibFunc_log10l_finite); TLI.setUnavailable(LibFunc_log2_finite); TLI.setUnavailable(LibFunc_log2f_finite); TLI.setUnavailable(LibFunc_log2l_finite); TLI.setUnavailable(LibFunc_log_finite); TLI.setUnavailable(LibFunc_logf_finite); TLI.setUnavailable(LibFunc_logl_finite); TLI.setUnavailable(LibFunc_pow_finite); TLI.setUnavailable(LibFunc_powf_finite); TLI.setUnavailable(LibFunc_powl_finite); TLI.setUnavailable(LibFunc_sinh_finite); TLI.setUnavailable(LibFunc_sinhf_finite); TLI.setUnavailable(LibFunc_sinhl_finite); } if ((T.isOSLinux() && T.isGNUEnvironment()) || (T.isAndroid() && !T.isAndroidVersionLT(28))) { // available IO unlocked variants on GNU/Linux and Android P or later TLI.setAvailable(LibFunc_getc_unlocked); TLI.setAvailable(LibFunc_getchar_unlocked); TLI.setAvailable(LibFunc_putc_unlocked); TLI.setAvailable(LibFunc_putchar_unlocked); TLI.setAvailable(LibFunc_fputc_unlocked); TLI.setAvailable(LibFunc_fgetc_unlocked); TLI.setAvailable(LibFunc_fread_unlocked); TLI.setAvailable(LibFunc_fwrite_unlocked); TLI.setAvailable(LibFunc_fputs_unlocked); TLI.setAvailable(LibFunc_fgets_unlocked); } // As currently implemented in clang, NVPTX code has no standard library to // speak of. Headers provide a standard-ish library implementation, but many // of the signatures are wrong -- for example, many libm functions are not // extern "C". // // libdevice, an IR library provided by nvidia, is linked in by the front-end, // but only used functions are provided to llvm. Moreover, most of the // functions in libdevice don't map precisely to standard library functions. // // FIXME: Having no standard library prevents e.g. many fastmath // optimizations, so this situation should be fixed. if (T.isNVPTX()) { TLI.disableAllFunctions(); TLI.setAvailable(LibFunc_nvvm_reflect); } else { TLI.setUnavailable(LibFunc_nvvm_reflect); } TLI.addVectorizableFunctionsFromVecLib(ClVectorLibrary); } TargetLibraryInfoImpl::TargetLibraryInfoImpl() { // Default to everything being available. memset(AvailableArray, -1, sizeof(AvailableArray)); initialize(*this, Triple(), StandardNames); } TargetLibraryInfoImpl::TargetLibraryInfoImpl(const Triple &T) { // Default to everything being available. memset(AvailableArray, -1, sizeof(AvailableArray)); initialize(*this, T, StandardNames); } TargetLibraryInfoImpl::TargetLibraryInfoImpl(const TargetLibraryInfoImpl &TLI) : CustomNames(TLI.CustomNames), ShouldExtI32Param(TLI.ShouldExtI32Param), ShouldExtI32Return(TLI.ShouldExtI32Return), ShouldSignExtI32Param(TLI.ShouldSignExtI32Param) { memcpy(AvailableArray, TLI.AvailableArray, sizeof(AvailableArray)); VectorDescs = TLI.VectorDescs; ScalarDescs = TLI.ScalarDescs; } TargetLibraryInfoImpl::TargetLibraryInfoImpl(TargetLibraryInfoImpl &&TLI) : CustomNames(std::move(TLI.CustomNames)), ShouldExtI32Param(TLI.ShouldExtI32Param), ShouldExtI32Return(TLI.ShouldExtI32Return), ShouldSignExtI32Param(TLI.ShouldSignExtI32Param) { std::move(std::begin(TLI.AvailableArray), std::end(TLI.AvailableArray), AvailableArray); VectorDescs = TLI.VectorDescs; ScalarDescs = TLI.ScalarDescs; } TargetLibraryInfoImpl &TargetLibraryInfoImpl::operator=(const TargetLibraryInfoImpl &TLI) { CustomNames = TLI.CustomNames; ShouldExtI32Param = TLI.ShouldExtI32Param; ShouldExtI32Return = TLI.ShouldExtI32Return; ShouldSignExtI32Param = TLI.ShouldSignExtI32Param; memcpy(AvailableArray, TLI.AvailableArray, sizeof(AvailableArray)); return *this; } TargetLibraryInfoImpl &TargetLibraryInfoImpl::operator=(TargetLibraryInfoImpl &&TLI) { CustomNames = std::move(TLI.CustomNames); ShouldExtI32Param = TLI.ShouldExtI32Param; ShouldExtI32Return = TLI.ShouldExtI32Return; ShouldSignExtI32Param = TLI.ShouldSignExtI32Param; std::move(std::begin(TLI.AvailableArray), std::end(TLI.AvailableArray), AvailableArray); return *this; } static StringRef sanitizeFunctionName(StringRef funcName) { // Filter out empty names and names containing null bytes, those can't be in // our table. if (funcName.empty() || funcName.find('\0') != StringRef::npos) return StringRef(); // Check for \01 prefix that is used to mangle __asm declarations and // strip it if present. return GlobalValue::dropLLVMManglingEscape(funcName); } bool TargetLibraryInfoImpl::getLibFunc(StringRef funcName, LibFunc &F) const { funcName = sanitizeFunctionName(funcName); if (funcName.empty()) return false; const auto *Start = std::begin(StandardNames); const auto *End = std::end(StandardNames); const auto *I = std::lower_bound(Start, End, funcName); if (I != End && *I == funcName) { F = (LibFunc)(I - Start); return true; } return false; } bool TargetLibraryInfoImpl::isValidProtoForLibFunc(const FunctionType &FTy, LibFunc F, const DataLayout *DL) const { LLVMContext &Ctx = FTy.getContext(); Type *PCharTy = Type::getInt8PtrTy(Ctx); Type *SizeTTy = DL ? DL->getIntPtrType(Ctx, /*AS=*/0) : nullptr; auto IsSizeTTy = [SizeTTy](Type *Ty) { return SizeTTy ? Ty == SizeTTy : Ty->isIntegerTy(); }; unsigned NumParams = FTy.getNumParams(); switch (F) { case LibFunc_execl: case LibFunc_execlp: case LibFunc_execle: return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy() && FTy.getReturnType()->isIntegerTy(32)); case LibFunc_execv: case LibFunc_execvp: return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy() && FTy.getReturnType()->isIntegerTy(32)); case LibFunc_execvP: case LibFunc_execvpe: case LibFunc_execve: return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy() && FTy.getParamType(2)->isPointerTy() && FTy.getReturnType()->isIntegerTy(32)); case LibFunc_strlen_chk: --NumParams; if (!IsSizeTTy(FTy.getParamType(NumParams))) return false; LLVM_FALLTHROUGH; case LibFunc_strlen: return (NumParams == 1 && FTy.getParamType(0)->isPointerTy() && FTy.getReturnType()->isIntegerTy()); case LibFunc_strchr: case LibFunc_strrchr: return (NumParams == 2 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(0) == FTy.getReturnType() && FTy.getParamType(1)->isIntegerTy()); case LibFunc_strtol: case LibFunc_strtod: case LibFunc_strtof: case LibFunc_strtoul: case LibFunc_strtoll: case LibFunc_strtold: case LibFunc_strtoull: return ((NumParams == 2 || NumParams == 3) && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_strcat_chk: --NumParams; if (!IsSizeTTy(FTy.getParamType(NumParams))) return false; LLVM_FALLTHROUGH; case LibFunc_strcat: return (NumParams == 2 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(0) == FTy.getReturnType() && FTy.getParamType(1) == FTy.getReturnType()); case LibFunc_strncat_chk: --NumParams; if (!IsSizeTTy(FTy.getParamType(NumParams))) return false; LLVM_FALLTHROUGH; case LibFunc_strncat: return (NumParams == 3 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(0) == FTy.getReturnType() && FTy.getParamType(1) == FTy.getReturnType() && IsSizeTTy(FTy.getParamType(2))); case LibFunc_strcpy_chk: case LibFunc_stpcpy_chk: --NumParams; if (!IsSizeTTy(FTy.getParamType(NumParams))) return false; LLVM_FALLTHROUGH; case LibFunc_strcpy: case LibFunc_stpcpy: return (NumParams == 2 && FTy.getReturnType() == FTy.getParamType(0) && FTy.getParamType(0) == FTy.getParamType(1) && FTy.getParamType(0) == PCharTy); case LibFunc_strlcat_chk: case LibFunc_strlcpy_chk: --NumParams; if (!IsSizeTTy(FTy.getParamType(NumParams))) return false; LLVM_FALLTHROUGH; case LibFunc_strlcat: case LibFunc_strlcpy: return NumParams == 3 && IsSizeTTy(FTy.getReturnType()) && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy() && IsSizeTTy(FTy.getParamType(2)); case LibFunc_strncpy_chk: case LibFunc_stpncpy_chk: --NumParams; if (!IsSizeTTy(FTy.getParamType(NumParams))) return false; LLVM_FALLTHROUGH; case LibFunc_strncpy: case LibFunc_stpncpy: return (NumParams == 3 && FTy.getReturnType() == FTy.getParamType(0) && FTy.getParamType(0) == FTy.getParamType(1) && FTy.getParamType(0) == PCharTy && IsSizeTTy(FTy.getParamType(2))); case LibFunc_strxfrm: return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_strcmp: return (NumParams == 2 && FTy.getReturnType()->isIntegerTy(32) && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(0) == FTy.getParamType(1)); case LibFunc_strncmp: return (NumParams == 3 && FTy.getReturnType()->isIntegerTy(32) && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(0) == FTy.getParamType(1) && IsSizeTTy(FTy.getParamType(2))); case LibFunc_strspn: case LibFunc_strcspn: return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(0) == FTy.getParamType(1) && FTy.getReturnType()->isIntegerTy()); case LibFunc_strcoll: case LibFunc_strcasecmp: case LibFunc_strncasecmp: return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_strstr: return (NumParams == 2 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_strpbrk: return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() && FTy.getReturnType() == FTy.getParamType(0) && FTy.getParamType(0) == FTy.getParamType(1)); case LibFunc_strtok: case LibFunc_strtok_r: return (NumParams >= 2 && FTy.getParamType(1)->isPointerTy()); case LibFunc_scanf: case LibFunc_setbuf: case LibFunc_setvbuf: return (NumParams >= 1 && FTy.getParamType(0)->isPointerTy()); case LibFunc_strdup: case LibFunc_strndup: return (NumParams >= 1 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(0)->isPointerTy()); case LibFunc_sscanf: case LibFunc_stat: case LibFunc_statvfs: case LibFunc_siprintf: case LibFunc_small_sprintf: case LibFunc_sprintf: return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy() && FTy.getReturnType()->isIntegerTy(32)); case LibFunc_sprintf_chk: return NumParams == 4 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isIntegerTy(32) && IsSizeTTy(FTy.getParamType(2)) && FTy.getParamType(3)->isPointerTy() && FTy.getReturnType()->isIntegerTy(32); case LibFunc_snprintf: return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(2)->isPointerTy() && FTy.getReturnType()->isIntegerTy(32)); case LibFunc_snprintf_chk: return NumParams == 5 && FTy.getParamType(0)->isPointerTy() && IsSizeTTy(FTy.getParamType(1)) && FTy.getParamType(2)->isIntegerTy(32) && IsSizeTTy(FTy.getParamType(3)) && FTy.getParamType(4)->isPointerTy() && FTy.getReturnType()->isIntegerTy(32); case LibFunc_setitimer: return (NumParams == 3 && FTy.getParamType(1)->isPointerTy() && FTy.getParamType(2)->isPointerTy()); case LibFunc_system: return (NumParams == 1 && FTy.getParamType(0)->isPointerTy()); case LibFunc_malloc: return (NumParams == 1 && FTy.getReturnType()->isPointerTy()); case LibFunc_memcmp: return (NumParams == 3 && FTy.getReturnType()->isIntegerTy(32) && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_memchr: case LibFunc_memrchr: return (NumParams == 3 && FTy.getReturnType()->isPointerTy() && FTy.getReturnType() == FTy.getParamType(0) && FTy.getParamType(1)->isIntegerTy(32) && IsSizeTTy(FTy.getParamType(2))); case LibFunc_modf: case LibFunc_modff: case LibFunc_modfl: return (NumParams >= 2 && FTy.getParamType(1)->isPointerTy()); case LibFunc_memcpy_chk: case LibFunc_memmove_chk: --NumParams; if (!IsSizeTTy(FTy.getParamType(NumParams))) return false; LLVM_FALLTHROUGH; case LibFunc_memcpy: case LibFunc_mempcpy: case LibFunc_memmove: return (NumParams == 3 && FTy.getReturnType() == FTy.getParamType(0) && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy() && IsSizeTTy(FTy.getParamType(2))); case LibFunc_memset_chk: --NumParams; if (!IsSizeTTy(FTy.getParamType(NumParams))) return false; LLVM_FALLTHROUGH; case LibFunc_memset: return (NumParams == 3 && FTy.getReturnType() == FTy.getParamType(0) && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isIntegerTy() && IsSizeTTy(FTy.getParamType(2))); case LibFunc_memccpy_chk: --NumParams; if (!IsSizeTTy(FTy.getParamType(NumParams))) return false; LLVM_FALLTHROUGH; case LibFunc_memccpy: return (NumParams >= 2 && FTy.getParamType(1)->isPointerTy()); case LibFunc_memalign: return (FTy.getReturnType()->isPointerTy()); case LibFunc_realloc: case LibFunc_reallocf: return (NumParams == 2 && FTy.getReturnType() == PCharTy && FTy.getParamType(0) == FTy.getReturnType() && IsSizeTTy(FTy.getParamType(1))); case LibFunc_read: return (NumParams == 3 && FTy.getParamType(1)->isPointerTy()); case LibFunc_rewind: case LibFunc_rmdir: case LibFunc_remove: case LibFunc_realpath: return (NumParams >= 1 && FTy.getParamType(0)->isPointerTy()); case LibFunc_rename: return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_readlink: return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_write: return (NumParams == 3 && FTy.getParamType(1)->isPointerTy()); case LibFunc_aligned_alloc: return (NumParams == 2 && FTy.getReturnType()->isPointerTy()); case LibFunc_bcopy: case LibFunc_bcmp: return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_bzero: return (NumParams == 2 && FTy.getParamType(0)->isPointerTy()); case LibFunc_calloc: return (NumParams == 2 && FTy.getReturnType()->isPointerTy()); case LibFunc_atof: case LibFunc_atoi: case LibFunc_atol: case LibFunc_atoll: case LibFunc_ferror: case LibFunc_getenv: case LibFunc_getpwnam: case LibFunc_iprintf: case LibFunc_small_printf: case LibFunc_pclose: case LibFunc_perror: case LibFunc_printf: case LibFunc_puts: case LibFunc_uname: case LibFunc_under_IO_getc: case LibFunc_unlink: case LibFunc_unsetenv: return (NumParams == 1 && FTy.getParamType(0)->isPointerTy()); case LibFunc_access: case LibFunc_chmod: case LibFunc_chown: case LibFunc_clearerr: case LibFunc_closedir: case LibFunc_ctermid: case LibFunc_fclose: case LibFunc_feof: case LibFunc_fflush: case LibFunc_fgetc: case LibFunc_fgetc_unlocked: case LibFunc_fileno: case LibFunc_flockfile: case LibFunc_free: case LibFunc_fseek: case LibFunc_fseeko64: case LibFunc_fseeko: case LibFunc_fsetpos: case LibFunc_ftell: case LibFunc_ftello64: case LibFunc_ftello: case LibFunc_ftrylockfile: case LibFunc_funlockfile: case LibFunc_getc: case LibFunc_getc_unlocked: case LibFunc_getlogin_r: case LibFunc_mkdir: case LibFunc_mktime: case LibFunc_times: return (NumParams != 0 && FTy.getParamType(0)->isPointerTy()); case LibFunc_fopen: return (NumParams == 2 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_fork: return (NumParams == 0 && FTy.getReturnType()->isIntegerTy(32)); case LibFunc_fdopen: return (NumParams == 2 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_fputc: case LibFunc_fputc_unlocked: case LibFunc_fstat: case LibFunc_frexp: case LibFunc_frexpf: case LibFunc_frexpl: case LibFunc_fstatvfs: return (NumParams == 2 && FTy.getParamType(1)->isPointerTy()); case LibFunc_fgets: case LibFunc_fgets_unlocked: return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(2)->isPointerTy()); case LibFunc_fread: case LibFunc_fread_unlocked: return (NumParams == 4 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(3)->isPointerTy()); case LibFunc_fwrite: case LibFunc_fwrite_unlocked: return (NumParams == 4 && FTy.getReturnType()->isIntegerTy() && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isIntegerTy() && FTy.getParamType(2)->isIntegerTy() && FTy.getParamType(3)->isPointerTy()); case LibFunc_fputs: case LibFunc_fputs_unlocked: return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_fscanf: case LibFunc_fiprintf: case LibFunc_small_fprintf: case LibFunc_fprintf: return (NumParams >= 2 && FTy.getReturnType()->isIntegerTy() && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_fgetpos: return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_getchar: case LibFunc_getchar_unlocked: return (NumParams == 0 && FTy.getReturnType()->isIntegerTy()); case LibFunc_gets: return (NumParams == 1 && FTy.getParamType(0) == PCharTy); case LibFunc_getitimer: return (NumParams == 2 && FTy.getParamType(1)->isPointerTy()); case LibFunc_ungetc: return (NumParams == 2 && FTy.getParamType(1)->isPointerTy()); case LibFunc_utime: case LibFunc_utimes: return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_putc: case LibFunc_putc_unlocked: return (NumParams == 2 && FTy.getParamType(1)->isPointerTy()); case LibFunc_pread: case LibFunc_pwrite: return (NumParams == 4 && FTy.getParamType(1)->isPointerTy()); case LibFunc_popen: return (NumParams == 2 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_vscanf: return (NumParams == 2 && FTy.getParamType(1)->isPointerTy()); case LibFunc_vsscanf: return (NumParams == 3 && FTy.getParamType(1)->isPointerTy() && FTy.getParamType(2)->isPointerTy()); case LibFunc_vfscanf: return (NumParams == 3 && FTy.getParamType(1)->isPointerTy() && FTy.getParamType(2)->isPointerTy()); case LibFunc_valloc: return (FTy.getReturnType()->isPointerTy()); case LibFunc_vprintf: return (NumParams == 2 && FTy.getParamType(0)->isPointerTy()); case LibFunc_vfprintf: case LibFunc_vsprintf: return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_vsprintf_chk: return NumParams == 5 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isIntegerTy(32) && IsSizeTTy(FTy.getParamType(2)) && FTy.getParamType(3)->isPointerTy(); case LibFunc_vsnprintf: return (NumParams == 4 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(2)->isPointerTy()); case LibFunc_vsnprintf_chk: return NumParams == 6 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(2)->isIntegerTy(32) && IsSizeTTy(FTy.getParamType(3)) && FTy.getParamType(4)->isPointerTy(); case LibFunc_open: return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy()); case LibFunc_opendir: return (NumParams == 1 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(0)->isPointerTy()); case LibFunc_tmpfile: return (FTy.getReturnType()->isPointerTy()); case LibFunc_htonl: case LibFunc_ntohl: return (NumParams == 1 && FTy.getReturnType()->isIntegerTy(32) && FTy.getReturnType() == FTy.getParamType(0)); case LibFunc_htons: case LibFunc_ntohs: return (NumParams == 1 && FTy.getReturnType()->isIntegerTy(16) && FTy.getReturnType() == FTy.getParamType(0)); case LibFunc_lstat: return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_lchown: return (NumParams == 3 && FTy.getParamType(0)->isPointerTy()); case LibFunc_qsort: return (NumParams == 4 && FTy.getParamType(3)->isPointerTy()); case LibFunc_dunder_strdup: case LibFunc_dunder_strndup: return (NumParams >= 1 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(0)->isPointerTy()); case LibFunc_dunder_strtok_r: return (NumParams == 3 && FTy.getParamType(1)->isPointerTy()); case LibFunc_under_IO_putc: return (NumParams == 2 && FTy.getParamType(1)->isPointerTy()); case LibFunc_dunder_isoc99_scanf: return (NumParams >= 1 && FTy.getParamType(0)->isPointerTy()); case LibFunc_stat64: case LibFunc_lstat64: case LibFunc_statvfs64: return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_dunder_isoc99_sscanf: return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_fopen64: return (NumParams == 2 && FTy.getReturnType()->isPointerTy() && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); case LibFunc_tmpfile64: return (FTy.getReturnType()->isPointerTy()); case LibFunc_fstat64: case LibFunc_fstatvfs64: return (NumParams == 2 && FTy.getParamType(1)->isPointerTy()); case LibFunc_open64: return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy()); case LibFunc_gettimeofday: return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy()); // new(unsigned int); case LibFunc_Znwj: // new(unsigned long); case LibFunc_Znwm: // new[](unsigned int); case LibFunc_Znaj: // new[](unsigned long); case LibFunc_Znam: // new(unsigned int); case LibFunc_msvc_new_int: // new(unsigned long long); case LibFunc_msvc_new_longlong: // new[](unsigned int); case LibFunc_msvc_new_array_int: // new[](unsigned long long); case LibFunc_msvc_new_array_longlong: return (NumParams == 1 && FTy.getReturnType()->isPointerTy()); // new(unsigned int, nothrow); case LibFunc_ZnwjRKSt9nothrow_t: // new(unsigned long, nothrow); case LibFunc_ZnwmRKSt9nothrow_t: // new[](unsigned int, nothrow); case LibFunc_ZnajRKSt9nothrow_t: // new[](unsigned long, nothrow); case LibFunc_ZnamRKSt9nothrow_t: // new(unsigned int, nothrow); case LibFunc_msvc_new_int_nothrow: // new(unsigned long long, nothrow); case LibFunc_msvc_new_longlong_nothrow: // new[](unsigned int, nothrow); case LibFunc_msvc_new_array_int_nothrow: // new[](unsigned long long, nothrow); case LibFunc_msvc_new_array_longlong_nothrow: // new(unsigned int, align_val_t) case LibFunc_ZnwjSt11align_val_t: // new(unsigned long, align_val_t) case LibFunc_ZnwmSt11align_val_t: // new[](unsigned int, align_val_t) case LibFunc_ZnajSt11align_val_t: // new[](unsigned long, align_val_t) case LibFunc_ZnamSt11align_val_t: return (NumParams == 2 && FTy.getReturnType()->isPointerTy()); // new(unsigned int, align_val_t, nothrow) case LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t: // new(unsigned long, align_val_t, nothrow) case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t: // new[](unsigned int, align_val_t, nothrow) case LibFunc_ZnajSt11align_val_tRKSt9nothrow_t: // new[](unsigned long, align_val_t, nothrow) case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t: return (NumParams == 3 && FTy.getReturnType()->isPointerTy()); // void operator delete[](void*); case LibFunc_ZdaPv: // void operator delete(void*); case LibFunc_ZdlPv: // void operator delete[](void*); case LibFunc_msvc_delete_array_ptr32: // void operator delete[](void*); case LibFunc_msvc_delete_array_ptr64: // void operator delete(void*); case LibFunc_msvc_delete_ptr32: // void operator delete(void*); case LibFunc_msvc_delete_ptr64: return (NumParams == 1 && FTy.getParamType(0)->isPointerTy()); // void operator delete[](void*, nothrow); case LibFunc_ZdaPvRKSt9nothrow_t: // void operator delete[](void*, unsigned int); case LibFunc_ZdaPvj: // void operator delete[](void*, unsigned long); case LibFunc_ZdaPvm: // void operator delete(void*, nothrow); case LibFunc_ZdlPvRKSt9nothrow_t: // void operator delete(void*, unsigned int); case LibFunc_ZdlPvj: // void operator delete(void*, unsigned long); case LibFunc_ZdlPvm: // void operator delete(void*, align_val_t) case LibFunc_ZdlPvSt11align_val_t: // void operator delete[](void*, align_val_t) case LibFunc_ZdaPvSt11align_val_t: // void operator delete[](void*, unsigned int); case LibFunc_msvc_delete_array_ptr32_int: // void operator delete[](void*, nothrow); case LibFunc_msvc_delete_array_ptr32_nothrow: // void operator delete[](void*, unsigned long long); case LibFunc_msvc_delete_array_ptr64_longlong: // void operator delete[](void*, nothrow); case LibFunc_msvc_delete_array_ptr64_nothrow: // void operator delete(void*, unsigned int); case LibFunc_msvc_delete_ptr32_int: // void operator delete(void*, nothrow); case LibFunc_msvc_delete_ptr32_nothrow: // void operator delete(void*, unsigned long long); case LibFunc_msvc_delete_ptr64_longlong: // void operator delete(void*, nothrow); case LibFunc_msvc_delete_ptr64_nothrow: return (NumParams == 2 && FTy.getParamType(0)->isPointerTy()); // void operator delete(void*, align_val_t, nothrow) case LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t: // void operator delete[](void*, align_val_t, nothrow) case LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t: return (NumParams == 3 && FTy.getParamType(0)->isPointerTy()); case LibFunc_memset_pattern16: return (!FTy.isVarArg() && NumParams == 3 && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy() && FTy.getParamType(2)->isIntegerTy()); case LibFunc_cxa_guard_abort: case LibFunc_cxa_guard_acquire: case LibFunc_cxa_guard_release: case LibFunc_nvvm_reflect: return (NumParams == 1 && FTy.getParamType(0)->isPointerTy()); case LibFunc_sincospi_stret: case LibFunc_sincospif_stret: return (NumParams == 1 && FTy.getParamType(0)->isFloatingPointTy()); case LibFunc_acos: case LibFunc_acos_finite: case LibFunc_acosf: case LibFunc_acosf_finite: case LibFunc_acosh: case LibFunc_acosh_finite: case LibFunc_acoshf: case LibFunc_acoshf_finite: case LibFunc_acoshl: case LibFunc_acoshl_finite: case LibFunc_acosl: case LibFunc_acosl_finite: case LibFunc_asin: case LibFunc_asin_finite: case LibFunc_asinf: case LibFunc_asinf_finite: case LibFunc_asinh: case LibFunc_asinhf: case LibFunc_asinhl: case LibFunc_asinl: case LibFunc_asinl_finite: case LibFunc_atan: case LibFunc_atanf: case LibFunc_atanh: case LibFunc_atanh_finite: case LibFunc_atanhf: case LibFunc_atanhf_finite: case LibFunc_atanhl: case LibFunc_atanhl_finite: case LibFunc_atanl: case LibFunc_cbrt: case LibFunc_cbrtf: case LibFunc_cbrtl: case LibFunc_ceil: case LibFunc_ceilf: case LibFunc_ceill: case LibFunc_cos: case LibFunc_cosf: case LibFunc_cosh: case LibFunc_cosh_finite: case LibFunc_coshf: case LibFunc_coshf_finite: case LibFunc_coshl: case LibFunc_coshl_finite: case LibFunc_cosl: case LibFunc_exp10: case LibFunc_exp10_finite: case LibFunc_exp10f: case LibFunc_exp10f_finite: case LibFunc_exp10l: case LibFunc_exp10l_finite: case LibFunc_exp2: case LibFunc_exp2_finite: case LibFunc_exp2f: case LibFunc_exp2f_finite: case LibFunc_exp2l: case LibFunc_exp2l_finite: case LibFunc_exp: case LibFunc_exp_finite: case LibFunc_expf: case LibFunc_expf_finite: case LibFunc_expl: case LibFunc_expl_finite: case LibFunc_expm1: case LibFunc_expm1f: case LibFunc_expm1l: case LibFunc_fabs: case LibFunc_fabsf: case LibFunc_fabsl: case LibFunc_floor: case LibFunc_floorf: case LibFunc_floorl: case LibFunc_log10: case LibFunc_log10_finite: case LibFunc_log10f: case LibFunc_log10f_finite: case LibFunc_log10l: case LibFunc_log10l_finite: case LibFunc_log1p: case LibFunc_log1pf: case LibFunc_log1pl: case LibFunc_log2: case LibFunc_log2_finite: case LibFunc_log2f: case LibFunc_log2f_finite: case LibFunc_log2l: case LibFunc_log2l_finite: case LibFunc_log: case LibFunc_log_finite: case LibFunc_logb: case LibFunc_logbf: case LibFunc_logbl: case LibFunc_logf: case LibFunc_logf_finite: case LibFunc_logl: case LibFunc_logl_finite: case LibFunc_nearbyint: case LibFunc_nearbyintf: case LibFunc_nearbyintl: case LibFunc_rint: case LibFunc_rintf: case LibFunc_rintl: case LibFunc_round: case LibFunc_roundf: case LibFunc_roundl: case LibFunc_roundeven: case LibFunc_roundevenf: case LibFunc_roundevenl: case LibFunc_sin: case LibFunc_sinf: case LibFunc_sinh: case LibFunc_sinh_finite: case LibFunc_sinhf: case LibFunc_sinhf_finite: case LibFunc_sinhl: case LibFunc_sinhl_finite: case LibFunc_sinl: case LibFunc_sqrt: case LibFunc_sqrt_finite: case LibFunc_sqrtf: case LibFunc_sqrtf_finite: case LibFunc_sqrtl: case LibFunc_sqrtl_finite: case LibFunc_tan: case LibFunc_tanf: case LibFunc_tanh: case LibFunc_tanhf: case LibFunc_tanhl: case LibFunc_tanl: case LibFunc_trunc: case LibFunc_truncf: case LibFunc_truncl: return (NumParams == 1 && FTy.getReturnType()->isFloatingPointTy() && FTy.getReturnType() == FTy.getParamType(0)); case LibFunc_atan2: case LibFunc_atan2_finite: case LibFunc_atan2f: case LibFunc_atan2f_finite: case LibFunc_atan2l: case LibFunc_atan2l_finite: case LibFunc_fmin: case LibFunc_fminf: case LibFunc_fminl: case LibFunc_fmax: case LibFunc_fmaxf: case LibFunc_fmaxl: case LibFunc_fmod: case LibFunc_fmodf: case LibFunc_fmodl: case LibFunc_remainder: case LibFunc_remainderf: case LibFunc_remainderl: case LibFunc_copysign: case LibFunc_copysignf: case LibFunc_copysignl: case LibFunc_pow: case LibFunc_pow_finite: case LibFunc_powf: case LibFunc_powf_finite: case LibFunc_powl: case LibFunc_powl_finite: return (NumParams == 2 && FTy.getReturnType()->isFloatingPointTy() && FTy.getReturnType() == FTy.getParamType(0) && FTy.getReturnType() == FTy.getParamType(1)); case LibFunc_ldexp: case LibFunc_ldexpf: case LibFunc_ldexpl: return (NumParams == 2 && FTy.getReturnType()->isFloatingPointTy() && FTy.getReturnType() == FTy.getParamType(0) && FTy.getParamType(1)->isIntegerTy(32)); case LibFunc_ffs: case LibFunc_ffsl: case LibFunc_ffsll: case LibFunc_fls: case LibFunc_flsl: case LibFunc_flsll: return (NumParams == 1 && FTy.getReturnType()->isIntegerTy(32) && FTy.getParamType(0)->isIntegerTy()); case LibFunc_isdigit: case LibFunc_isascii: case LibFunc_toascii: case LibFunc_putchar: case LibFunc_putchar_unlocked: return (NumParams == 1 && FTy.getReturnType()->isIntegerTy(32) && FTy.getReturnType() == FTy.getParamType(0)); case LibFunc_abs: case LibFunc_labs: case LibFunc_llabs: return (NumParams == 1 && FTy.getReturnType()->isIntegerTy() && FTy.getReturnType() == FTy.getParamType(0)); case LibFunc_cxa_atexit: return (NumParams == 3 && FTy.getReturnType()->isIntegerTy() && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1)->isPointerTy() && FTy.getParamType(2)->isPointerTy()); case LibFunc_sinpi: case LibFunc_cospi: return (NumParams == 1 && FTy.getReturnType()->isDoubleTy() && FTy.getReturnType() == FTy.getParamType(0)); case LibFunc_sinpif: case LibFunc_cospif: return (NumParams == 1 && FTy.getReturnType()->isFloatTy() && FTy.getReturnType() == FTy.getParamType(0)); case LibFunc_strnlen: return (NumParams == 2 && FTy.getReturnType() == FTy.getParamType(1) && FTy.getParamType(0) == PCharTy && FTy.getParamType(1) == SizeTTy); case LibFunc_posix_memalign: return (NumParams == 3 && FTy.getReturnType()->isIntegerTy(32) && FTy.getParamType(0)->isPointerTy() && FTy.getParamType(1) == SizeTTy && FTy.getParamType(2) == SizeTTy); case LibFunc_wcslen: return (NumParams == 1 && FTy.getParamType(0)->isPointerTy() && FTy.getReturnType()->isIntegerTy()); case LibFunc_cabs: case LibFunc_cabsf: case LibFunc_cabsl: { Type* RetTy = FTy.getReturnType(); if (!RetTy->isFloatingPointTy()) return false; // NOTE: These prototypes are target specific and currently support // "complex" passed as an array or discrete real & imaginary parameters. // Add other calling conventions to enable libcall optimizations. if (NumParams == 1) return (FTy.getParamType(0)->isArrayTy() && FTy.getParamType(0)->getArrayNumElements() == 2 && FTy.getParamType(0)->getArrayElementType() == RetTy); else if (NumParams == 2) return (FTy.getParamType(0) == RetTy && FTy.getParamType(1) == RetTy); else return false; } case LibFunc::NumLibFuncs: case LibFunc::NotLibFunc: break; } llvm_unreachable("Invalid libfunc"); } bool TargetLibraryInfoImpl::getLibFunc(const Function &FDecl, LibFunc &F) const { // Intrinsics don't overlap w/libcalls; if our module has a large number of // intrinsics, this ends up being an interesting compile time win since we // avoid string normalization and comparison. if (FDecl.isIntrinsic()) return false; const DataLayout *DL = FDecl.getParent() ? &FDecl.getParent()->getDataLayout() : nullptr; return getLibFunc(FDecl.getName(), F) && isValidProtoForLibFunc(*FDecl.getFunctionType(), F, DL); } void TargetLibraryInfoImpl::disableAllFunctions() { memset(AvailableArray, 0, sizeof(AvailableArray)); } static bool compareByScalarFnName(const VecDesc &LHS, const VecDesc &RHS) { return LHS.ScalarFnName < RHS.ScalarFnName; } static bool compareByVectorFnName(const VecDesc &LHS, const VecDesc &RHS) { return LHS.VectorFnName < RHS.VectorFnName; } static bool compareWithScalarFnName(const VecDesc &LHS, StringRef S) { return LHS.ScalarFnName < S; } static bool compareWithVectorFnName(const VecDesc &LHS, StringRef S) { return LHS.VectorFnName < S; } void TargetLibraryInfoImpl::addVectorizableFunctions(ArrayRef<VecDesc> Fns) { VectorDescs.insert(VectorDescs.end(), Fns.begin(), Fns.end()); llvm::sort(VectorDescs, compareByScalarFnName); ScalarDescs.insert(ScalarDescs.end(), Fns.begin(), Fns.end()); llvm::sort(ScalarDescs, compareByVectorFnName); } void TargetLibraryInfoImpl::addVectorizableFunctionsFromVecLib( enum VectorLibrary VecLib) { switch (VecLib) { case Accelerate: { const VecDesc VecFuncs[] = { #define TLI_DEFINE_ACCELERATE_VECFUNCS #include "llvm/Analysis/VecFuncs.def" }; addVectorizableFunctions(VecFuncs); break; } case MASSV: { const VecDesc VecFuncs[] = { #define TLI_DEFINE_MASSV_VECFUNCS #include "llvm/Analysis/VecFuncs.def" }; addVectorizableFunctions(VecFuncs); break; } case SVML: { const VecDesc VecFuncs[] = { #define TLI_DEFINE_SVML_VECFUNCS #include "llvm/Analysis/VecFuncs.def" }; addVectorizableFunctions(VecFuncs); break; } case NoLibrary: break; } } bool TargetLibraryInfoImpl::isFunctionVectorizable(StringRef funcName) const { funcName = sanitizeFunctionName(funcName); if (funcName.empty()) return false; std::vector<VecDesc>::const_iterator I = llvm::lower_bound(VectorDescs, funcName, compareWithScalarFnName); return I != VectorDescs.end() && StringRef(I->ScalarFnName) == funcName; } StringRef TargetLibraryInfoImpl::getVectorizedFunction(StringRef F, unsigned VF) const { F = sanitizeFunctionName(F); if (F.empty()) return F; std::vector<VecDesc>::const_iterator I = llvm::lower_bound(VectorDescs, F, compareWithScalarFnName); while (I != VectorDescs.end() && StringRef(I->ScalarFnName) == F) { if (I->VectorizationFactor == VF) return I->VectorFnName; ++I; } return StringRef(); } StringRef TargetLibraryInfoImpl::getScalarizedFunction(StringRef F, unsigned &VF) const { F = sanitizeFunctionName(F); if (F.empty()) return F; std::vector<VecDesc>::const_iterator I = llvm::lower_bound(ScalarDescs, F, compareWithVectorFnName); if (I == VectorDescs.end() || StringRef(I->VectorFnName) != F) return StringRef(); VF = I->VectorizationFactor; return I->ScalarFnName; } TargetLibraryInfo TargetLibraryAnalysis::run(const Function &F, FunctionAnalysisManager &) { if (!BaselineInfoImpl) BaselineInfoImpl = TargetLibraryInfoImpl(Triple(F.getParent()->getTargetTriple())); return TargetLibraryInfo(*BaselineInfoImpl, &F); } unsigned TargetLibraryInfoImpl::getWCharSize(const Module &M) const { if (auto *ShortWChar = cast_or_null<ConstantAsMetadata>( M.getModuleFlag("wchar_size"))) return cast<ConstantInt>(ShortWChar->getValue())->getZExtValue(); return 0; } TargetLibraryInfoWrapperPass::TargetLibraryInfoWrapperPass() : ImmutablePass(ID), TLA(TargetLibraryInfoImpl()) { initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry()); } TargetLibraryInfoWrapperPass::TargetLibraryInfoWrapperPass(const Triple &T) : ImmutablePass(ID), TLA(TargetLibraryInfoImpl(T)) { initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry()); } TargetLibraryInfoWrapperPass::TargetLibraryInfoWrapperPass( const TargetLibraryInfoImpl &TLIImpl) : ImmutablePass(ID), TLA(TLIImpl) { initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry()); } AnalysisKey TargetLibraryAnalysis::Key; // Register the basic pass. INITIALIZE_PASS(TargetLibraryInfoWrapperPass, "targetlibinfo", "Target Library Information", false, true) char TargetLibraryInfoWrapperPass::ID = 0; void TargetLibraryInfoWrapperPass::anchor() {} unsigned TargetLibraryInfoImpl::getWidestVF(StringRef ScalarF) const { ScalarF = sanitizeFunctionName(ScalarF); if (ScalarF.empty()) return 1; unsigned VF = 1; std::vector<VecDesc>::const_iterator I = llvm::lower_bound(VectorDescs, ScalarF, compareWithScalarFnName); while (I != VectorDescs.end() && StringRef(I->ScalarFnName) == ScalarF) { if (I->VectorizationFactor > VF) VF = I->VectorizationFactor; ++I; } return VF; }
36.164557
101
0.704285
[ "vector" ]
3369840e4c9b9ca42dd310951442a55fc778fb3d
25,895
cc
C++
mediapipe/calculators/tflite/tflite_tensors_to_segmentation_calculator.cc
Yuuraa/mediapipe-gesture-recognition
e2444cedbfcedf2b242ad025ceac39359c945db2
[ "Apache-2.0" ]
47
2019-12-29T02:52:48.000Z
2022-02-21T08:39:14.000Z
mediapipe/calculators/tflite/tflite_tensors_to_segmentation_calculator.cc
Yuuraa/mediapipe-gesture-recognition
e2444cedbfcedf2b242ad025ceac39359c945db2
[ "Apache-2.0" ]
2
2020-12-24T06:35:19.000Z
2021-01-04T08:44:25.000Z
mediapipe/calculators/tflite/tflite_tensors_to_segmentation_calculator.cc
Yuuraa/mediapipe-gesture-recognition
e2444cedbfcedf2b242ad025ceac39359c945db2
[ "Apache-2.0" ]
16
2020-07-21T06:28:25.000Z
2022-02-02T13:40:36.000Z
// Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <vector> #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "mediapipe/calculators/tflite/tflite_tensors_to_segmentation_calculator.pb.h" #include "mediapipe/framework/calculator_context.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/image_frame.h" #include "mediapipe/framework/formats/image_frame_opencv.h" #include "mediapipe/framework/port/opencv_imgcodecs_inc.h" #include "mediapipe/framework/port/opencv_imgproc_inc.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/util/resource_util.h" #include "tensorflow/lite/interpreter.h" #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) #include "mediapipe/gpu/gl_calculator_helper.h" #include "mediapipe/gpu/gl_simple_shaders.h" #include "mediapipe/gpu/shader_util.h" #include "tensorflow/lite/delegates/gpu/gl/gl_buffer.h" #include "tensorflow/lite/delegates/gpu/gl/gl_program.h" #include "tensorflow/lite/delegates/gpu/gl/gl_shader.h" #include "tensorflow/lite/delegates/gpu/gl/gl_texture.h" #include "tensorflow/lite/delegates/gpu/gl_delegate.h" #endif // !MEDIAPIPE_DISABLE_GPU namespace { constexpr int kWorkgroupSize = 8; // Block size for GPU shader. enum { ATTRIB_VERTEX, ATTRIB_TEXTURE_POSITION, NUM_ATTRIBUTES }; // Commonly used to compute the number of blocks to launch in a kernel. int NumGroups(const int size, const int group_size) { // NOLINT return (size + group_size - 1) / group_size; } float Clamp(float val, float min, float max) { return std::min(std::max(val, min), max); } constexpr char kTensorsTag[] = "TENSORS"; constexpr char kTensorsGpuTag[] = "TENSORS_GPU"; constexpr char kSizeImageTag[] = "REFERENCE_IMAGE"; constexpr char kSizeImageGpuTag[] = "REFERENCE_IMAGE_GPU"; constexpr char kMaskTag[] = "MASK"; constexpr char kMaskGpuTag[] = "MASK_GPU"; constexpr char kPrevMaskTag[] = "PREV_MASK"; constexpr char kPrevMaskGpuTag[] = "PREV_MASK_GPU"; } // namespace namespace mediapipe { #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) using ::tflite::gpu::gl::CopyBuffer; using ::tflite::gpu::gl::CreateReadWriteRgbaImageTexture; using ::tflite::gpu::gl::CreateReadWriteShaderStorageBuffer; using ::tflite::gpu::gl::GlBuffer; using ::tflite::gpu::gl::GlProgram; using ::tflite::gpu::gl::GlShader; #endif // !MEDIAPIPE_DISABLE_GPU // Converts TFLite tensors from a tflite segmentation model to an image mask. // // Performs optional upscale to REFERENCE_IMAGE dimensions if provided, // otherwise the mask is the same size as input tensor. // // Produces result as an RGBA image, with the mask in both R & A channels. The // value of each pixel is the probability of the specified class after softmax, // scaled to 255 on CPU. The class can be specified through the // |output_layer_index| option. // // Inputs: // One of the following TENSORS tags: // TENSORS: Vector of TfLiteTensor of type kTfLiteFloat32. // The tensor dimensions are specified in this calculator's options. // TENSORS_GPU: Vector of GlBuffer. // One of the following REFERENCE_IMAGE tags: // REFERENCE_IMAGE (optional): An ImageFrame input image, // used only for output dimensions. // REFERENCE_IMAGE_GPU (optional): A GpuBuffer input image, // used only for output dimensions. // One of the following PREV_MASK tags: // PREV_MASK (optional): An ImageFrame input mask, Gray, RGB or RGBA, [0-255]. // PREV_MASK_GPU (optional): A GpuBuffer input mask, RGBA, [0-1]. // Output: // One of the following MASK tags: // MASK: An ImageFrame output mask, RGBA. // MASK_GPU: A GpuBuffer output mask, RGBA. // // Options: // See tflite_segmentation_calculator.proto // // Usage example: // node { // calculator: "TfLiteTensorsToSegmentationCalculator" // input_stream: "TENSORS_GPU:tensors" // input_stream: "IMAGE_GPU:input_video" // output_stream: "MASK_GPU:hair_mask" // node_options: { // [mediapipe.TfLiteTensorsToSegmentationCalculatorOptions] { // tensor_in_width: 512 // tensor_in_height: 512 // tensor_in_channels: 2 // combine_with_previous_ratio: 1.0 // output_layer_index: 1 // } // } // } // class TfLiteTensorsToSegmentationCalculator : public CalculatorBase { public: static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Open(CalculatorContext* cc) override; ::mediapipe::Status Process(CalculatorContext* cc) override; ::mediapipe::Status Close(CalculatorContext* cc) override; private: ::mediapipe::Status LoadOptions(CalculatorContext* cc); ::mediapipe::Status InitGpu(CalculatorContext* cc); ::mediapipe::Status ProcessGpu(CalculatorContext* cc); ::mediapipe::Status ProcessCpu(CalculatorContext* cc); void GlRender(); ::mediapipe::TfLiteTensorsToSegmentationCalculatorOptions options_; int tensor_width_ = 0; int tensor_height_ = 0; int tensor_channels_ = 0; bool use_gpu_ = false; #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) mediapipe::GlCalculatorHelper gpu_helper_; std::unique_ptr<GlProgram> mask_program_with_prev_; std::unique_ptr<GlProgram> mask_program_no_prev_; std::unique_ptr<GlBuffer> tensor_buffer_; GLuint upsample_program_; #endif // !MEDIAPIPE_DISABLE_GPU }; REGISTER_CALCULATOR(TfLiteTensorsToSegmentationCalculator); // static ::mediapipe::Status TfLiteTensorsToSegmentationCalculator::GetContract( CalculatorContract* cc) { RET_CHECK(!cc->Inputs().GetTags().empty()); RET_CHECK(!cc->Outputs().GetTags().empty()); bool use_gpu = false; // Inputs CPU. if (cc->Inputs().HasTag(kTensorsTag)) { cc->Inputs().Tag(kTensorsTag).Set<std::vector<TfLiteTensor>>(); } if (cc->Inputs().HasTag(kPrevMaskTag)) { cc->Inputs().Tag(kPrevMaskTag).Set<ImageFrame>(); } if (cc->Inputs().HasTag(kSizeImageTag)) { cc->Inputs().Tag(kSizeImageTag).Set<ImageFrame>(); } // Inputs GPU. #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) if (cc->Inputs().HasTag(kTensorsGpuTag)) { cc->Inputs().Tag(kTensorsGpuTag).Set<std::vector<GlBuffer>>(); use_gpu |= true; } if (cc->Inputs().HasTag(kPrevMaskGpuTag)) { cc->Inputs().Tag(kPrevMaskGpuTag).Set<mediapipe::GpuBuffer>(); use_gpu |= true; } if (cc->Inputs().HasTag(kSizeImageGpuTag)) { cc->Inputs().Tag(kSizeImageGpuTag).Set<mediapipe::GpuBuffer>(); use_gpu |= true; } #endif // !MEDIAPIPE_DISABLE_GPU // Outputs. if (cc->Outputs().HasTag(kMaskTag)) { cc->Outputs().Tag(kMaskTag).Set<ImageFrame>(); } #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) if (cc->Outputs().HasTag(kMaskGpuTag)) { cc->Outputs().Tag(kMaskGpuTag).Set<mediapipe::GpuBuffer>(); use_gpu |= true; } #endif // !MEDIAPIPE_DISABLE_GPU if (use_gpu) { #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) MP_RETURN_IF_ERROR(mediapipe::GlCalculatorHelper::UpdateContract(cc)); #endif // !MEDIAPIPE_DISABLE_GPU } return ::mediapipe::OkStatus(); } ::mediapipe::Status TfLiteTensorsToSegmentationCalculator::Open( CalculatorContext* cc) { cc->SetOffset(TimestampDiff(0)); if (cc->Inputs().HasTag(kTensorsGpuTag)) { use_gpu_ = true; #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) MP_RETURN_IF_ERROR(gpu_helper_.Open(cc)); #endif // !MEDIAPIPE_DISABLE_GPU } MP_RETURN_IF_ERROR(LoadOptions(cc)); if (use_gpu_) { #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) MP_RETURN_IF_ERROR( gpu_helper_.RunInGlContext([this, cc]() -> ::mediapipe::Status { MP_RETURN_IF_ERROR(InitGpu(cc)); return ::mediapipe::OkStatus(); })); #else RET_CHECK_FAIL() << "GPU processing not enabled."; #endif // !MEDIAPIPE_DISABLE_GPU } return ::mediapipe::OkStatus(); } ::mediapipe::Status TfLiteTensorsToSegmentationCalculator::Process( CalculatorContext* cc) { if (use_gpu_) { #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) MP_RETURN_IF_ERROR( gpu_helper_.RunInGlContext([this, cc]() -> ::mediapipe::Status { MP_RETURN_IF_ERROR(ProcessGpu(cc)); return ::mediapipe::OkStatus(); })); #endif // !MEDIAPIPE_DISABLE_GPU } else { MP_RETURN_IF_ERROR(ProcessCpu(cc)); } return ::mediapipe::OkStatus(); } ::mediapipe::Status TfLiteTensorsToSegmentationCalculator::Close( CalculatorContext* cc) { #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) gpu_helper_.RunInGlContext([this] { if (upsample_program_) glDeleteProgram(upsample_program_); upsample_program_ = 0; mask_program_with_prev_.reset(); mask_program_no_prev_.reset(); tensor_buffer_.reset(); }); #endif // !MEDIAPIPE_DISABLE_GPU return ::mediapipe::OkStatus(); } ::mediapipe::Status TfLiteTensorsToSegmentationCalculator::ProcessCpu( CalculatorContext* cc) { if (cc->Inputs().Tag(kTensorsTag).IsEmpty()) { return ::mediapipe::OkStatus(); } // Get input streams. const auto& input_tensors = cc->Inputs().Tag(kTensorsTag).Get<std::vector<TfLiteTensor>>(); const bool has_prev_mask = cc->Inputs().HasTag(kPrevMaskTag) && !cc->Inputs().Tag(kPrevMaskTag).IsEmpty(); const ImageFrame placeholder; const auto& input_mask = has_prev_mask ? cc->Inputs().Tag(kPrevMaskTag).Get<ImageFrame>() : placeholder; int output_width = tensor_width_, output_height = tensor_height_; if (cc->Inputs().HasTag(kSizeImageTag)) { const auto& input_image = cc->Inputs().Tag(kSizeImageTag).Get<ImageFrame>(); output_width = input_image.Width(); output_height = input_image.Height(); } RET_CHECK_EQ(input_tensors.size(), 1); // Create initial working mask. cv::Mat small_mask_mat(cv::Size(tensor_width_, tensor_height_), CV_8UC4); // Get input previous mask. cv::Mat input_mask_mat; if (has_prev_mask) { cv::Mat temp_mask_mat = formats::MatView(&input_mask); if (temp_mask_mat.channels() != 4) { cv::Mat converted_mat; cv::cvtColor(temp_mask_mat, converted_mat, temp_mask_mat.channels() == 1 ? cv::COLOR_GRAY2RGBA : cv::COLOR_RGB2RGBA); temp_mask_mat = converted_mat.clone(); } cv::resize(temp_mask_mat, input_mask_mat, small_mask_mat.size()); } // Copy input tensor. const TfLiteTensor* raw_input_tensor = &input_tensors[0]; const float* raw_input_data = raw_input_tensor->data.f; cv::Mat tensor_mat(cv::Size(tensor_width_, tensor_height_), CV_MAKETYPE(CV_32F, tensor_channels_)); float* tensor_mat_ptr = tensor_mat.ptr<float>(); memcpy(tensor_mat_ptr, raw_input_data, raw_input_tensor->bytes); // Process mask tensor. // Run softmax over tensor output and blend with previous mask. const int output_layer_index = options_.output_layer_index(); const float combine_with_prev_ratio = options_.combine_with_previous_ratio(); for (int i = 0; i < tensor_height_; ++i) { for (int j = 0; j < tensor_width_; ++j) { // Only two channel input tensor is supported. const cv::Vec2f input_pix = tensor_mat.at<cv::Vec2f>(i, j); const float shift = std::max(input_pix[0], input_pix[1]); const float softmax_denom = std::exp(input_pix[0] - shift) + std::exp(input_pix[1] - shift); float new_mask_value = std::exp(input_pix[output_layer_index] - shift) / softmax_denom; // Combine previous value with current using uncertainty^2 as mixing coeff if (has_prev_mask) { const float prev_mask_value = input_mask_mat.at<cv::Vec4b>(i, j)[0] / 255.0f; const float eps = 0.001; float uncertainty_alpha = 1.0 + (new_mask_value * std::log(new_mask_value + eps) + (1.0 - new_mask_value) * std::log(1.0 - new_mask_value + eps)) / std::log(2.0f); uncertainty_alpha = Clamp(uncertainty_alpha, 0.0f, 1.0f); // Equivalent to: a = 1 - (1 - a) * (1 - a); (squaring the uncertainty) uncertainty_alpha *= 2.0 - uncertainty_alpha; const float mixed_mask_value = new_mask_value * uncertainty_alpha + prev_mask_value * (1.0f - uncertainty_alpha); new_mask_value = mixed_mask_value * combine_with_prev_ratio + (1.0f - combine_with_prev_ratio) * new_mask_value; } const uchar mask_value = static_cast<uchar>(new_mask_value * 255); // Set both R and A channels for convenience. const cv::Vec4b out_value = {mask_value, 0, 0, mask_value}; small_mask_mat.at<cv::Vec4b>(i, j) = out_value; } } if (options_.flip_vertically()) cv::flip(small_mask_mat, small_mask_mat, 0); // Upsample small mask into output. cv::Mat large_mask_mat; cv::resize(small_mask_mat, large_mask_mat, cv::Size(output_width, output_height)); // Send out image as CPU packet. std::unique_ptr<ImageFrame> output_mask = absl::make_unique<ImageFrame>( ImageFormat::SRGBA, output_width, output_height); cv::Mat output_mat = formats::MatView(output_mask.get()); large_mask_mat.copyTo(output_mat); cc->Outputs().Tag(kMaskTag).Add(output_mask.release(), cc->InputTimestamp()); return ::mediapipe::OkStatus(); } // Steps: // 1. receive tensor and optional previous mask // 2. process segmentation tensor into small mask // 3. upsample small mask into output mask to be same size as input image ::mediapipe::Status TfLiteTensorsToSegmentationCalculator::ProcessGpu( CalculatorContext* cc) { if (cc->Inputs().Tag(kTensorsGpuTag).IsEmpty()) { return ::mediapipe::OkStatus(); } #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) // Get input streams. const auto& input_tensors = cc->Inputs().Tag(kTensorsGpuTag).Get<std::vector<GlBuffer>>(); const bool has_prev_mask = cc->Inputs().HasTag(kPrevMaskGpuTag) && !cc->Inputs().Tag(kPrevMaskGpuTag).IsEmpty(); const auto& input_mask = has_prev_mask ? cc->Inputs().Tag(kPrevMaskGpuTag).Get<mediapipe::GpuBuffer>() : mediapipe::GpuBuffer(); int output_width = tensor_width_, output_height = tensor_height_; if (cc->Inputs().HasTag(kSizeImageGpuTag)) { const auto& input_image = cc->Inputs().Tag(kSizeImageGpuTag).Get<mediapipe::GpuBuffer>(); output_width = input_image.width(); output_height = input_image.height(); } RET_CHECK_EQ(input_tensors.size(), 1); // Create initial working mask texture. ::tflite::gpu::gl::GlTexture small_mask_texture; MP_RETURN_IF_ERROR(CreateReadWriteRgbaImageTexture( tflite::gpu::DataType::UINT8, // GL_RGBA8 {tensor_width_, tensor_height_}, &small_mask_texture)); // Get input previous mask. auto input_mask_texture = has_prev_mask ? gpu_helper_.CreateSourceTexture(input_mask) : mediapipe::GlTexture(); // Copy input tensor. MP_RETURN_IF_ERROR(CopyBuffer(input_tensors[0], *tensor_buffer_)); // Run shader, process mask tensor. // Run softmax over tensor output and blend with previous mask. { const int output_index = 0; glBindImageTexture(output_index, small_mask_texture.id(), 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA8); MP_RETURN_IF_ERROR(tensor_buffer_->BindToIndex(2)); const tflite::gpu::uint3 workgroups = { NumGroups(tensor_width_, kWorkgroupSize), NumGroups(tensor_height_, kWorkgroupSize), 1}; if (!has_prev_mask) { MP_RETURN_IF_ERROR(mask_program_no_prev_->Dispatch(workgroups)); } else { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, input_mask_texture.name()); MP_RETURN_IF_ERROR(mask_program_with_prev_->Dispatch(workgroups)); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); } } // Upsample small mask into output. mediapipe::GlTexture output_texture = gpu_helper_.CreateDestinationTexture( output_width, output_height, mediapipe::GpuBufferFormat::kBGRA32); // actually GL_RGBA8 // Run shader, upsample result. { gpu_helper_.BindFramebuffer(output_texture); // GL_TEXTURE0 glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, small_mask_texture.id()); GlRender(); glBindTexture(GL_TEXTURE_2D, 0); glFlush(); } // Send out image as GPU packet. auto output_image = output_texture.GetFrame<mediapipe::GpuBuffer>(); cc->Outputs() .Tag(kMaskGpuTag) .Add(output_image.release(), cc->InputTimestamp()); // Cleanup input_mask_texture.Release(); output_texture.Release(); #endif // !MEDIAPIPE_DISABLE_GPU return ::mediapipe::OkStatus(); } void TfLiteTensorsToSegmentationCalculator::GlRender() { #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) static const GLfloat square_vertices[] = { -1.0f, -1.0f, // bottom left 1.0f, -1.0f, // bottom right -1.0f, 1.0f, // top left 1.0f, 1.0f, // top right }; static const GLfloat texture_vertices[] = { 0.0f, 0.0f, // bottom left 1.0f, 0.0f, // bottom right 0.0f, 1.0f, // top left 1.0f, 1.0f, // top right }; // program glUseProgram(upsample_program_); // vertex storage GLuint vbo[2]; glGenBuffers(2, vbo); GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // vbo 0 glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(GLfloat), square_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(ATTRIB_VERTEX); glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, 0, 0, nullptr); // vbo 1 glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(GLfloat), texture_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(ATTRIB_TEXTURE_POSITION); glVertexAttribPointer(ATTRIB_TEXTURE_POSITION, 2, GL_FLOAT, 0, 0, nullptr); // draw glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // cleanup glDisableVertexAttribArray(ATTRIB_VERTEX); glDisableVertexAttribArray(ATTRIB_TEXTURE_POSITION); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glDeleteVertexArrays(1, &vao); glDeleteBuffers(2, vbo); #endif // !MEDIAPIPE_DISABLE_GPU } ::mediapipe::Status TfLiteTensorsToSegmentationCalculator::LoadOptions( CalculatorContext* cc) { // Get calculator options specified in the graph. options_ = cc->Options<::mediapipe::TfLiteTensorsToSegmentationCalculatorOptions>(); if (!options_.has_tensor_width() || !options_.has_tensor_height() || !options_.has_tensor_channels()) RET_CHECK_FAIL() << "Missing tensor dimensions in options."; tensor_width_ = options_.tensor_width(); tensor_height_ = options_.tensor_height(); tensor_channels_ = options_.tensor_channels(); RET_CHECK_EQ(tensor_channels_, 2) << "Only 2 channel segmentation tensor currently supported"; return ::mediapipe::OkStatus(); } ::mediapipe::Status TfLiteTensorsToSegmentationCalculator::InitGpu( CalculatorContext* cc) { #if !defined(MEDIAPIPE_DISABLE_GL_COMPUTE) MP_RETURN_IF_ERROR(gpu_helper_.RunInGlContext([this]() -> ::mediapipe::Status { // A shader to process a segmentation tensor into an output mask, // and use an optional previous mask as input. // Currently uses 4 channels for output, // and sets both R and A channels as mask value. const std::string shader_src_template = R"( #version 310 es layout(local_size_x = $0, local_size_y = $0, local_size_z = 1) in; precision highp float; layout(std430, binding = 2) readonly buffer B0 { vec2 elements[]; } input_data; // data tensor layout(binding = 1) uniform sampler2D input_texture; // previous mask layout(rgba8, binding = 0) writeonly uniform highp image2D output_texture; uniform ivec2 out_size; const int output_layer_index = int($1); const float combine_with_previous_ratio = float($2); // Will be replaced with either '#define READ_PREVIOUS' or empty std::string $3 //DEFINE_READ_PREVIOUS void main() { int out_width = out_size.x; int out_height = out_size.y; ivec2 gid = ivec2(gl_GlobalInvocationID.xy); if (gid.x >= out_width || gid.y >= out_height) { return; } int linear_index = gid.y * out_width + gid.x; vec2 input_value = input_data.elements[linear_index]; // Only two channel input tensor is supported. vec2 input_px = input_value.rg; float shift = max(input_px.r, input_px.g); float softmax_denom = exp(input_px.r - shift) + exp(input_px.g - shift); float new_mask_value = exp(input_px[output_layer_index] - shift) / softmax_denom; // Combine previous value with current using uncertainty^2 as mixing parameter #ifdef READ_PREVIOUS vec2 normalized_gid = vec2(gid) / vec2(out_width - 1, out_height - 1); float prev_mask_value = texture(input_texture, normalized_gid).r; float eps = 0.001; float uncertainty_alpha = 1.0 + (new_mask_value * log(new_mask_value + eps) + (1.0 - new_mask_value) * log(1.0 - new_mask_value + eps)) / log(2.0f); uncertainty_alpha = clamp(uncertainty_alpha, 0.0, 1.0); // equivalent to a = 1 - (1 - a) * (1 - a); (squaring the uncertainty) uncertainty_alpha *= 2.0 - uncertainty_alpha; float mixed_mask_value = new_mask_value * uncertainty_alpha + prev_mask_value * (1.0f - uncertainty_alpha); // Use user provided value to mix raw value & a value mixed with previous mask new_mask_value = mixed_mask_value * combine_with_previous_ratio + (1.0f - combine_with_previous_ratio) * new_mask_value; #endif // READ_PREVIOUS int y_coord = int($4); ivec2 output_coordinate = ivec2(gid.x, y_coord); // Set both R and A channels for convenience. vec4 out_value = vec4(new_mask_value, 0.0, 0.0, new_mask_value); imageStore(output_texture, output_coordinate, out_value); })"; const std::string shader_src_no_previous = absl::Substitute( shader_src_template, kWorkgroupSize, options_.output_layer_index(), options_.combine_with_previous_ratio(), "", options_.flip_vertically() ? "out_height - gid.y - 1" : "gid.y"); const std::string shader_src_with_previous = absl::Substitute( shader_src_template, kWorkgroupSize, options_.output_layer_index(), options_.combine_with_previous_ratio(), "#define READ_PREVIOUS", options_.flip_vertically() ? "out_height - gid.y - 1" : "gid.y"); // Shader programs. GlShader shader_without_previous; MP_RETURN_IF_ERROR(GlShader::CompileShader( GL_COMPUTE_SHADER, shader_src_no_previous, &shader_without_previous)); mask_program_no_prev_ = absl::make_unique<GlProgram>(); MP_RETURN_IF_ERROR(GlProgram::CreateWithShader( shader_without_previous, mask_program_no_prev_.get())); GlShader shader_with_previous; MP_RETURN_IF_ERROR(GlShader::CompileShader( GL_COMPUTE_SHADER, shader_src_with_previous, &shader_with_previous)); mask_program_with_prev_ = absl::make_unique<GlProgram>(); MP_RETURN_IF_ERROR(GlProgram::CreateWithShader( shader_with_previous, mask_program_with_prev_.get())); // Buffer storage for input tensor. size_t tensor_length = tensor_width_ * tensor_height_ * tensor_channels_; tensor_buffer_ = absl::make_unique<GlBuffer>(); MP_RETURN_IF_ERROR(CreateReadWriteShaderStorageBuffer<float>( tensor_length, tensor_buffer_.get())); // Parameters. glUseProgram(mask_program_with_prev_->id()); glUniform2i(glGetUniformLocation(mask_program_with_prev_->id(), "out_size"), tensor_width_, tensor_height_); glUniform1i( glGetUniformLocation(mask_program_with_prev_->id(), "input_texture"), 1); glUseProgram(mask_program_no_prev_->id()); glUniform2i(glGetUniformLocation(mask_program_no_prev_->id(), "out_size"), tensor_width_, tensor_height_); glUniform1i( glGetUniformLocation(mask_program_no_prev_->id(), "input_texture"), 1); // Vertex shader attributes. const GLint attr_location[NUM_ATTRIBUTES] = { ATTRIB_VERTEX, ATTRIB_TEXTURE_POSITION, }; const GLchar* attr_name[NUM_ATTRIBUTES] = { "position", "texture_coordinate", }; // Simple pass-through shader, used for hardware upsampling. std::string upsample_shader_base = R"( #if __VERSION__ < 130 #define in varying #endif // __VERSION__ < 130 #ifdef GL_ES #define fragColor gl_FragColor precision highp float; #else #define lowp #define mediump #define highp #define texture2D texture out vec4 fragColor; #endif // defined(GL_ES) in vec2 sample_coordinate; uniform sampler2D input_data; void main() { vec4 pix = texture2D(input_data, sample_coordinate); fragColor = pix; } )"; // Program mediapipe::GlhCreateProgram( mediapipe::kBasicVertexShader, upsample_shader_base.c_str(), NUM_ATTRIBUTES, &attr_name[0], attr_location, &upsample_program_); RET_CHECK(upsample_program_) << "Problem initializing the program."; // Parameters glUseProgram(upsample_program_); glUniform1i(glGetUniformLocation(upsample_program_, "input_data"), 1); return ::mediapipe::OkStatus(); })); #endif // !MEDIAPIPE_DISABLE_GPU return ::mediapipe::OkStatus(); } } // namespace mediapipe
36.523272
86
0.702336
[ "vector", "model" ]
336b6bb43e015ebf34371b1599b241d1d0967bd5
11,169
cpp
C++
src/World.cpp
lukawarren/Sludge
7f0d1cfe90adb8626c9e28c91af7ddc2434ac853
[ "MIT" ]
null
null
null
src/World.cpp
lukawarren/Sludge
7f0d1cfe90adb8626c9e28c91af7ddc2434ac853
[ "MIT" ]
null
null
null
src/World.cpp
lukawarren/Sludge
7f0d1cfe90adb8626c9e28c91af7ddc2434ac853
[ "MIT" ]
null
null
null
#include "World.h" #include "Common.h" #include "PerlinNoise.hpp" #include "Game.h" #include "Cave.h" #include "Town.h" World::World(const int width, const int height, const unsigned int seed) : Area(seed), width(width), height(height) { tiles = new Tile[width * height]; memset(tiles, ' ', sizeof tiles[0] * width * height); // Make Perlin generator with specified seed siv::BasicPerlinNoise<float> perlinNoise(seed); // At every set of integer coordinates, Perlin noise will // always return 0, and even if we just added a constant // value, results just wouldn't "flow", so we need some // sort of scale to fix this. The larger the scale, the // more "zoomed out" we become. const float scale = (1.0f / 5.0f); const int octaves = 8; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { // Generate initial nosie for landmass(es) auto heightMap = perlinNoise.normalizedOctaveNoise2D_0_1(x * scale, y * scale, octaves); // Make values further from the centre lower to promote an island-ish look const float distanceX = std::pow(float(x) - float(width / 2), 2); const float distanceY = std::pow(float(y) - float(height / 2), 2); const float distance = std::sqrt(distanceX + distanceY) / float(width); heightMap -= distance * 2.0f; // Roughly "re-normalise" to 0.1 scale heightMap *= 5.0f; auto* tile = &tiles[y * width + x]; if (heightMap > 2.0f) *tile = Tile::Rock; else if (heightMap > 0.5f) *tile = Tile::Grass; else *tile = Tile::Water; } } } void World::LoadAreas() { const int nCaves = width * height / 512; const int nTowns = 4; unsigned int caveSeed = rand(); unsigned int townSeed = rand(); const auto OnRandomPosition = [&](const int count, const int minDistanceFromCentre, const std::function<Area*(const Portal)> f) { for (int i = 0; i < count; ++i) { // Pick valid cell auto cellX = rand() % width; auto cellY = rand() % height; while (GetTile(cellY * width + cellX) == Tile::Water || sqrtf(cellX*cellX + cellY*cellY) < minDistanceFromCentre) { cellX = rand() % width; cellY = rand() % height; } // Add portal const Portal portal = { Game::Get().GetAreaID(this), // Exit area cellY * width + cellX // Exit cell }; portals[cellY * width + cellX] = { Game::Get().AddArea(f(portal)) }; } }; // Generate caves OnRandomPosition(nCaves, 0, [&](const Portal portal) { return new Cave ( 10, // Width 10, // Height ++caveSeed, // Seed portal ); }); // Generate towns std::vector<Cell> towns; OnRandomPosition(nTowns, 5, [&](const Portal portal) { towns.emplace_back(portal.cell.value()); return new Town(++townSeed, portal); }); // Generate paths Cell centre = height / 2 * width + width / 2; for (size_t i = 0; i < towns.size(); ++i) CreatePath(towns[i], centre); } /* Uses A* path-finding https://en.wikipedia.org/wiki/A*_search_algorithm */ void World::CreatePath(const Cell startCell, const Cell endCell) { // Make nodes struct Node { int x; int y; std::vector<Node*> neighbours; bool walkable; bool visited = false; Node* parent = nullptr; float localGoal = std::numeric_limits<float>::max(); float globalGoal = std::numeric_limits<float>::max(); }; std::vector<Node> nodes(width * height, Node {}); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { nodes[y * width + x].x = x, nodes[y * width + x].y = y; nodes[y * width + x].walkable = tiles[y * width + x] != Tile::Water; } } // Work out neighbours for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { auto& node = nodes[y * width + x]; if (y > 0) node.neighbours.push_back(&nodes[(y - 1) * width + (x + 0)]); if (y < height-1) node.neighbours.push_back(&nodes[(y + 1) * width + (x + 0)]); if (x > 0) node.neighbours.push_back(&nodes[(y + 0) * width + (x - 1)]); if (x < width-1) node.neighbours.push_back(&nodes[(y + 0) * width + (x + 1)]); } } const auto Distance = [](Node* a, Node* b) { // Normally, we would just use pythagoras but on terminal screens, characters are // twice as tall as they are long, and so this makes for weird results! To solve this, // make all vertical measurements twice as large. return sqrtf((a->x - b->x) * (a->x - b->x) + (a->y - b->y) * (a->y - b->y)); }; // Starting conditions Node* start = &nodes[startCell]; Node* end = &nodes[endCell]; Node* current = start; current->localGoal = 0.0f; current->globalGoal = Distance(start, end); // Have "not tested" list for processing std::list<Node*> untestedNodes = { start }; // Continue until *a* path is found - not necessarily the absolute best path, but a path nonetheless while (!untestedNodes.empty() && current != end) { // Sort nodes by global goal, with lowest first untestedNodes.sort([](const Node* lhs, const Node* rhs) { return lhs->globalGoal < rhs->globalGoal; }); // Ditch nodes already visited at front of the list.... while (!untestedNodes.empty() && untestedNodes.front()->visited) untestedNodes.pop_front(); // ...then if we're in trouble, abandon ship if (untestedNodes.empty()) break; // Node chosen, proceed current = untestedNodes.front(); current->visited = true; for (auto neighbour : current->neighbours) { // If not visited, duly note down for later use if (!neighbour->visited && neighbour->walkable) untestedNodes.push_back(neighbour); // Work out potential lowest parent distance float possibleLowestGoal = current->localGoal + Distance(current, neighbour); // Update local goal of neighbour if value can be pushed lower by way of our parent if (possibleLowestGoal < neighbour->localGoal) { neighbour->parent = current; neighbour->localGoal = possibleLowestGoal; neighbour->globalGoal = neighbour->localGoal + Distance(neighbour, end); } } } // Walk from end node to start node, following parents and creating paths if (end != nullptr) { Node* n = end; while (n->parent != nullptr) { tiles[n->y * width + n->x] = Tile::Path; n = n->parent; } } } Cell World::GetStartingCell() const { // Centre return (height / 2) * width + (width/2); } void World::Look(Player& player) const { const int worldX = player.cell % width; const int worldY = player.cell / width; player << "- Glancing at your map you determine your position to be [" << worldX << "," << worldY << "]\n"; // Notify player of portals const auto portal = GetPortal(player.cell); if (portal.has_value()) player << "- " << Game::Get().areas[portal->area]->GetPortalText() << "\n"; const int viewWidth = 10; const int viewHeight = 5; // Top and bottom borders const auto DrawEdge = [&]() { for (int i = 0; i < viewWidth+1; ++i) player << "#"; player << "\n"; }; player << "\n"; DrawEdge(); for (int viewY = -viewHeight/2+1; viewY < viewHeight/2; ++viewY) { player << "#"; for (int viewX = -viewWidth/2+1; viewX < viewWidth/2; ++viewX) { const int x = worldX+viewX; const int y = worldY+viewY; if (viewY == 0 && viewX == 0) player << "X"; // Print player else if (x >= 0 && y >= 0 && x < width && y < height && GetPortal(y * width + x).has_value()) { // Tile is a portal, render as such player << "?"; } else { // Tile is normal, render as such const auto tile = GetTile(x, y); const char buffer[2] = { TileToChar(tile), '\0' }; player << buffer; } } player << "#\n"; } DrawEdge(); } void World::Move(Player& player, const Direction direction, const int distance) const { Area::Move(player, direction, distance, width, height, [&](const int x, const int y) { const auto tile = GetTile(x, y); return tile != Tile::None && tile != Tile::Water; }); } std::vector<ItemStack>& World::GetItems(const Cell cell) { static std::vector<ItemStack> nullVector; return nullVector; } std::string World::GetPortalText() const { return ""; } World::Tile World::GetTile(Cell cell) const { bool validPosition = (cell >= 0 && cell < width*height); if (!validPosition) return Tile::None; return tiles[cell]; } World::Tile World::GetTile(const int x, const int y) const { if (x < 0 || x > width) return Tile::None; if (y < 0 || y > height) return Tile::None; return tiles[y * width + x]; } char World::TileToChar(const Tile t) const { switch (t) { case Tile::Grass: return '/'; case Tile::Rock: return '+'; case Tile::Water: return '~'; case Tile::Path: return '#'; default: return ' '; } } void World::Render() const { // Top and bottom borders; add 2 to account for left and right borders below const auto DrawEdge = [&]() { for (int i = 0; i < width+2; ++i) std::cout << "#"; std::cout << std::endl; }; DrawEdge(); for (int y = 0; y < height; ++y) { std::cout << "#"; for (int x = 0; x < width; ++x) { const auto cell = y * width + x; const auto portal = GetPortal(cell); if (portal.has_value()) { // Tile is a portal std::cout << "?"; } else { // Tile is normal, render as per usual const auto tile = tiles[cell]; std::cout << TileToChar(tile); } } std::cout << "#" << std::endl; } DrawEdge(); } World::~World() { delete[] tiles; }
29.23822
131
0.516429
[ "render", "vector" ]
336fcc023154e0e4195f3bb703ddc39aacfa1179
70,645
cc
C++
src/ray/core_worker/reference_count_test.cc
matthewearl/ray
e29f2ef788dc399832240ae17fb9464515374eb7
[ "Apache-2.0" ]
1
2020-07-21T22:31:11.000Z
2020-07-21T22:31:11.000Z
src/ray/core_worker/reference_count_test.cc
matthewearl/ray
e29f2ef788dc399832240ae17fb9464515374eb7
[ "Apache-2.0" ]
1
2019-03-16T07:08:57.000Z
2019-03-16T07:08:57.000Z
src/ray/core_worker/reference_count_test.cc
gehring/ray
d8eeb9641314740572e81f9836cbce3e5b8f2b73
[ "Apache-2.0" ]
null
null
null
#include "ray/core_worker/reference_count.h" #include <vector> #include "gtest/gtest.h" #include "ray/common/ray_object.h" #include "ray/core_worker/store_provider/memory_store/memory_store.h" namespace ray { static const rpc::Address empty_borrower; static const ReferenceCounter::ReferenceTableProto empty_refs; class ReferenceCountTest : public ::testing::Test { protected: std::unique_ptr<ReferenceCounter> rc; virtual void SetUp() { rpc::Address addr; rc = std::unique_ptr<ReferenceCounter>(new ReferenceCounter(addr)); } virtual void TearDown() {} }; class MockWorkerClient : public rpc::CoreWorkerClientInterface { public: // Helper function to generate a random address. rpc::Address CreateRandomAddress(const std::string &addr) { rpc::Address address; address.set_ip_address(addr); address.set_raylet_id(ClientID::FromRandom().Binary()); address.set_worker_id(WorkerID::FromRandom().Binary()); return address; } MockWorkerClient(const std::string &addr, rpc::ClientFactoryFn client_factory = nullptr) : task_id_(TaskID::ForFakeTask()), address_(CreateRandomAddress(addr)), rc_(rpc::WorkerAddress(address_), /*distributed_ref_counting_enabled=*/true, client_factory) {} ray::Status WaitForRefRemoved( const rpc::WaitForRefRemovedRequest &request, const rpc::ClientCallback<rpc::WaitForRefRemovedReply> &callback) override { auto r = num_requests_; requests_[r] = { std::make_shared<rpc::WaitForRefRemovedReply>(), callback, }; auto send_reply_callback = [this, r](Status status, std::function<void()> success, std::function<void()> failure) { requests_[r].second(status, *requests_[r].first); }; auto borrower_callback = [=]() { const ObjectID &object_id = ObjectID::FromBinary(request.reference().object_id()); ObjectID contained_in_id = ObjectID::FromBinary(request.contained_in_id()); const auto owner_id = TaskID::FromBinary(request.reference().owner_id()); const auto owner_address = request.reference().owner_address(); auto ref_removed_callback = boost::bind(&ReferenceCounter::HandleRefRemoved, &rc_, _1, requests_[r].first.get(), send_reply_callback); rc_.SetRefRemovedCallback(object_id, contained_in_id, owner_id, owner_address, ref_removed_callback); }; borrower_callbacks_[r] = borrower_callback; num_requests_++; return Status::OK(); } bool FlushBorrowerCallbacks() { if (borrower_callbacks_.empty()) { return false; } else { for (auto &callback : borrower_callbacks_) { callback.second(); } borrower_callbacks_.clear(); return true; } } // The below methods mirror a core worker's operations, e.g., `Put` simulates // a ray.put(). void Put(const ObjectID &object_id) { rc_.AddOwnedObject(object_id, {}, task_id_, address_); rc_.AddLocalReference(object_id); } void PutWrappedId(const ObjectID outer_id, const ObjectID &inner_id) { rc_.AddOwnedObject(outer_id, {inner_id}, task_id_, address_); rc_.AddLocalReference(outer_id); } void GetSerializedObjectId(const ObjectID outer_id, const ObjectID &inner_id, const TaskID &owner_id, const rpc::Address &owner_address) { rc_.AddLocalReference(inner_id); rc_.AddBorrowedObject(inner_id, outer_id, owner_id, owner_address); } void ExecuteTaskWithArg(const ObjectID &arg_id, const ObjectID &inner_id, const TaskID &owner_id, const rpc::Address &owner_address) { // Add a sentinel reference to keep the argument ID in scope even though // the frontend won't have a reference. rc_.AddLocalReference(arg_id); GetSerializedObjectId(arg_id, inner_id, owner_id, owner_address); } ObjectID SubmitTaskWithArg(const ObjectID &arg_id) { rc_.UpdateSubmittedTaskReferences({arg_id}); ObjectID return_id = ObjectID::FromRandom(); rc_.AddOwnedObject(return_id, {}, task_id_, address_); // Add a sentinel reference to keep all nested object IDs in scope. rc_.AddLocalReference(return_id); return return_id; } ReferenceCounter::ReferenceTableProto FinishExecutingTask( const ObjectID &arg_id, const ObjectID &return_id, const ObjectID *return_wrapped_id = nullptr, const rpc::WorkerAddress *owner_address = nullptr) { if (return_wrapped_id) { rc_.AddNestedObjectIds(return_id, {*return_wrapped_id}, *owner_address); } ReferenceCounter::ReferenceTableProto refs; if (!arg_id.IsNil()) { rc_.GetAndClearLocalBorrowers({arg_id}, &refs); // Remove the sentinel reference. rc_.RemoveLocalReference(arg_id, nullptr); } return refs; } void HandleSubmittedTaskFinished( const ObjectID &arg_id, const std::unordered_map<ObjectID, std::vector<ObjectID>> &nested_return_ids = {}, const rpc::Address &borrower_address = empty_borrower, const ReferenceCounter::ReferenceTableProto &borrower_refs = empty_refs) { std::vector<ObjectID> arguments; if (!arg_id.IsNil()) { arguments.push_back(arg_id); } rc_.UpdateFinishedTaskReferences(arguments, borrower_address, borrower_refs, nullptr); } // Global map from Worker ID -> MockWorkerClient. // Global map from Object ID -> owner worker ID, list of objects that it depends on, // worker address that it's scheduled on. Worker map of pending return IDs. TaskID task_id_; rpc::Address address_; // The ReferenceCounter at the "client". ReferenceCounter rc_; std::unordered_map<int, std::function<void()>> borrower_callbacks_; std::unordered_map<int, std::pair<std::shared_ptr<rpc::WaitForRefRemovedReply>, rpc::ClientCallback<rpc::WaitForRefRemovedReply>>> requests_; int num_requests_ = 0; }; // Tests basic incrementing/decrementing of direct/submitted task reference counts. An // entry should only be removed once both of its reference counts reach zero. TEST_F(ReferenceCountTest, TestBasic) { std::vector<ObjectID> out; ObjectID id1 = ObjectID::FromRandom(); ObjectID id2 = ObjectID::FromRandom(); // Local references. rc->AddLocalReference(id1); rc->AddLocalReference(id1); rc->AddLocalReference(id2); ASSERT_EQ(rc->NumObjectIDsInScope(), 2); rc->RemoveLocalReference(id1, &out); ASSERT_EQ(rc->NumObjectIDsInScope(), 2); ASSERT_EQ(out.size(), 0); rc->RemoveLocalReference(id2, &out); ASSERT_EQ(rc->NumObjectIDsInScope(), 1); ASSERT_EQ(out.size(), 1); rc->RemoveLocalReference(id1, &out); ASSERT_EQ(rc->NumObjectIDsInScope(), 0); ASSERT_EQ(out.size(), 2); out.clear(); // Submitted task references. rc->UpdateSubmittedTaskReferences({id1}); rc->UpdateSubmittedTaskReferences({id1, id2}); ASSERT_EQ(rc->NumObjectIDsInScope(), 2); rc->UpdateFinishedTaskReferences({id1}, empty_borrower, empty_refs, &out); ASSERT_EQ(rc->NumObjectIDsInScope(), 2); ASSERT_EQ(out.size(), 0); rc->UpdateFinishedTaskReferences({id2}, empty_borrower, empty_refs, &out); ASSERT_EQ(rc->NumObjectIDsInScope(), 1); ASSERT_EQ(out.size(), 1); rc->UpdateFinishedTaskReferences({id1}, empty_borrower, empty_refs, &out); ASSERT_EQ(rc->NumObjectIDsInScope(), 0); ASSERT_EQ(out.size(), 2); out.clear(); // Local & submitted task references. rc->AddLocalReference(id1); rc->UpdateSubmittedTaskReferences({id1, id2}); rc->AddLocalReference(id2); ASSERT_EQ(rc->NumObjectIDsInScope(), 2); rc->RemoveLocalReference(id1, &out); ASSERT_EQ(rc->NumObjectIDsInScope(), 2); ASSERT_EQ(out.size(), 0); rc->UpdateFinishedTaskReferences({id2}, empty_borrower, empty_refs, &out); ASSERT_EQ(rc->NumObjectIDsInScope(), 2); ASSERT_EQ(out.size(), 0); rc->UpdateFinishedTaskReferences({id1}, empty_borrower, empty_refs, &out); ASSERT_EQ(rc->NumObjectIDsInScope(), 1); ASSERT_EQ(out.size(), 1); rc->RemoveLocalReference(id2, &out); ASSERT_EQ(rc->NumObjectIDsInScope(), 0); ASSERT_EQ(out.size(), 2); out.clear(); } // Tests that we can get the owner address correctly for objects that we own, // objects that we borrowed via a serialized object ID, and objects whose // origin we do not know. TEST_F(ReferenceCountTest, TestOwnerAddress) { auto object_id = ObjectID::FromRandom(); TaskID task_id = TaskID::ForFakeTask(); rpc::Address address; address.set_ip_address("1234"); rc->AddOwnedObject(object_id, {}, task_id, address); TaskID added_id; rpc::Address added_address; ASSERT_TRUE(rc->GetOwner(object_id, &added_id, &added_address)); ASSERT_EQ(task_id, added_id); ASSERT_EQ(address.ip_address(), added_address.ip_address()); auto object_id2 = ObjectID::FromRandom(); task_id = TaskID::ForFakeTask(); address.set_ip_address("5678"); rc->AddOwnedObject(object_id2, {}, task_id, address); ASSERT_TRUE(rc->GetOwner(object_id2, &added_id, &added_address)); ASSERT_EQ(task_id, added_id); ASSERT_EQ(address.ip_address(), added_address.ip_address()); auto object_id3 = ObjectID::FromRandom(); ASSERT_FALSE(rc->GetOwner(object_id3, &added_id, &added_address)); rc->AddLocalReference(object_id3); ASSERT_FALSE(rc->GetOwner(object_id3, &added_id, &added_address)); } // Tests that the ref counts are properly integrated into the local // object memory store. TEST(MemoryStoreIntegrationTest, TestSimple) { ObjectID id1 = ObjectID::FromRandom().WithDirectTransportType(); ObjectID id2 = ObjectID::FromRandom().WithDirectTransportType(); uint8_t data[] = {1, 2, 3, 4, 5, 6, 7, 8}; RayObject buffer(std::make_shared<LocalMemoryBuffer>(data, sizeof(data)), nullptr, {}); auto rc = std::shared_ptr<ReferenceCounter>( new ReferenceCounter(rpc::WorkerAddress(rpc::Address()))); CoreWorkerMemoryStore store(nullptr, rc); // Tests putting an object with no references is ignored. RAY_CHECK_OK(store.Put(buffer, id2)); ASSERT_EQ(store.Size(), 0); // Tests ref counting overrides remove after get option. rc->AddLocalReference(id1); RAY_CHECK_OK(store.Put(buffer, id1)); ASSERT_EQ(store.Size(), 1); std::vector<std::shared_ptr<RayObject>> results; WorkerContext ctx(WorkerType::WORKER, JobID::Nil()); RAY_CHECK_OK(store.Get({id1}, /*num_objects*/ 1, /*timeout_ms*/ -1, ctx, /*remove_after_get*/ true, &results)); ASSERT_EQ(results.size(), 1); ASSERT_EQ(store.Size(), 1); } // A borrower is given a reference to an object ID, submits a task, waits for // it to finish, then returns. // // @ray.remote // def borrower(inner_ids): // inner_id = inner_ids[0] // ray.get(foo.remote(inner_id)) // // inner_id = ray.put(1) // outer_id = ray.put([inner_id]) // res = borrower.remote(outer_id) TEST(DistributedReferenceCountTest, TestNoBorrow) { auto borrower = std::make_shared<MockWorkerClient>("1"); auto owner = std::make_shared<MockWorkerClient>( "2", [&](const rpc::Address &addr) { return borrower; }); // The owner creates an inner object and wraps it. auto inner_id = ObjectID::FromRandom(); auto outer_id = ObjectID::FromRandom(); owner->Put(inner_id); owner->PutWrappedId(outer_id, inner_id); // The owner submits a task that depends on the outer object. The task will // be given a reference to inner_id. owner->SubmitTaskWithArg(outer_id); // The owner's references go out of scope. owner->rc_.RemoveLocalReference(outer_id, nullptr); owner->rc_.RemoveLocalReference(inner_id, nullptr); // The owner's ref count > 0 for both objects. ASSERT_TRUE(owner->rc_.HasReference(outer_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower is given a reference to the inner object. borrower->ExecuteTaskWithArg(outer_id, inner_id, owner->task_id_, owner->address_); // The borrower submits a task that depends on the inner object. borrower->SubmitTaskWithArg(inner_id); borrower->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // The borrower waits for the task to finish before returning to the owner. borrower->HandleSubmittedTaskFinished(inner_id); auto borrower_refs = borrower->FinishExecutingTask(outer_id, ObjectID::Nil()); // Check that the borrower's ref count is now 0 for all objects. ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); ASSERT_FALSE(borrower->rc_.HasReference(outer_id)); // The owner receives the borrower's reply and merges the borrower's ref // count into its own. owner->HandleSubmittedTaskFinished(outer_id, {}, borrower->address_, borrower_refs); borrower->FlushBorrowerCallbacks(); // Check that owner's ref count is now 0 for all objects. ASSERT_FALSE(owner->rc_.HasReference(inner_id)); ASSERT_FALSE(owner->rc_.HasReference(outer_id)); } // A borrower is given a reference to an object ID, submits a task, does not // wait for it to finish. // // @ray.remote // def borrower(inner_ids): // inner_id = inner_ids[0] // foo.remote(inner_id) // // inner_id = ray.put(1) // outer_id = ray.put([inner_id]) // res = borrower.remote(outer_id) TEST(DistributedReferenceCountTest, TestSimpleBorrower) { auto borrower = std::make_shared<MockWorkerClient>("1"); auto owner = std::make_shared<MockWorkerClient>( "2", [&](const rpc::Address &addr) { return borrower; }); // The owner creates an inner object and wraps it. auto inner_id = ObjectID::FromRandom(); auto outer_id = ObjectID::FromRandom(); owner->Put(inner_id); owner->PutWrappedId(outer_id, inner_id); // The owner submits a task that depends on the outer object. The task will // be given a reference to inner_id. owner->SubmitTaskWithArg(outer_id); // The owner's references go out of scope. owner->rc_.RemoveLocalReference(outer_id, nullptr); owner->rc_.RemoveLocalReference(inner_id, nullptr); // The owner's ref count > 0 for both objects. ASSERT_TRUE(owner->rc_.HasReference(outer_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower is given a reference to the inner object. borrower->ExecuteTaskWithArg(outer_id, inner_id, owner->task_id_, owner->address_); // The borrower submits a task that depends on the inner object. borrower->SubmitTaskWithArg(inner_id); borrower->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // The borrower task returns to the owner without waiting for its submitted // task to finish. auto borrower_refs = borrower->FinishExecutingTask(outer_id, ObjectID::Nil()); // ASSERT_FALSE(borrower->rc_.HasReference(outer_id)); // Check that the borrower's ref count for inner_id > 0 because of the // pending task. ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // The owner receives the borrower's reply and merges the borrower's ref // count into its own. owner->HandleSubmittedTaskFinished(outer_id, {}, borrower->address_, borrower_refs); borrower->FlushBorrowerCallbacks(); // Check that owner now has borrower in inner's borrowers list. ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Check that owner's ref count for outer == 0 since the borrower task // returned and there were no local references to outer_id. ASSERT_FALSE(owner->rc_.HasReference(outer_id)); // The task submitted by the borrower returns. Everyone's ref count should go // to 0. borrower->HandleSubmittedTaskFinished(inner_id); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); ASSERT_FALSE(borrower->rc_.HasReference(outer_id)); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); ASSERT_FALSE(owner->rc_.HasReference(outer_id)); } // A borrower is given a reference to an object ID, keeps the reference past // the task's lifetime, then deletes the reference before it hears from the // owner. // // @ray.remote // class Borrower: // def __init__(self, inner_ids): // self.inner_id = inner_ids[0] // // inner_id = ray.put(1) // outer_id = ray.put([inner_id]) // res = Borrower.remote(outer_id) TEST(DistributedReferenceCountTest, TestSimpleBorrowerReferenceRemoved) { auto borrower = std::make_shared<MockWorkerClient>("1"); auto owner = std::make_shared<MockWorkerClient>( "2", [&](const rpc::Address &addr) { return borrower; }); // The owner creates an inner object and wraps it. auto inner_id = ObjectID::FromRandom(); auto outer_id = ObjectID::FromRandom(); owner->Put(inner_id); owner->PutWrappedId(outer_id, inner_id); // The owner submits a task that depends on the outer object. The task will // be given a reference to inner_id. owner->SubmitTaskWithArg(outer_id); // The owner's references go out of scope. owner->rc_.RemoveLocalReference(outer_id, nullptr); owner->rc_.RemoveLocalReference(inner_id, nullptr); // The owner's ref count > 0 for both objects. ASSERT_TRUE(owner->rc_.HasReference(outer_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower is given a reference to the inner object. borrower->ExecuteTaskWithArg(outer_id, inner_id, owner->task_id_, owner->address_); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // The borrower task returns to the owner while still using inner_id. auto borrower_refs = borrower->FinishExecutingTask(outer_id, ObjectID::Nil()); ASSERT_FALSE(borrower->rc_.HasReference(outer_id)); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // The owner receives the borrower's reply and merges the borrower's ref // count into its own. owner->HandleSubmittedTaskFinished(outer_id, {}, borrower->address_, borrower_refs); // Check that owner now has borrower in inner's borrowers list. ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Check that owner's ref count for outer == 0 since the borrower task // returned and there were no local references to outer_id. ASSERT_FALSE(owner->rc_.HasReference(outer_id)); // The borrower is no longer using inner_id, but it hasn't received the // message from the owner yet. borrower->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower receives the owner's wait message. It should return a reply // to the owner immediately saying that it is no longer using inner_id. borrower->FlushBorrowerCallbacks(); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); } // A borrower is given a reference to an object ID, passes the reference to // another borrower by submitting a task, and does not wait for it to finish. // // @ray.remote // def borrower2(inner_ids): // pass // // @ray.remote // def borrower(inner_ids): // borrower2.remote(inner_ids) // // inner_id = ray.put(1) // outer_id = ray.put([inner_id]) // res = borrower.remote(outer_id) TEST(DistributedReferenceCountTest, TestBorrowerTree) { auto borrower1 = std::make_shared<MockWorkerClient>("1"); auto borrower2 = std::make_shared<MockWorkerClient>("2"); auto owner = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { if (addr.ip_address() == borrower1->address_.ip_address()) { return borrower1; } else { return borrower2; } }); // The owner creates an inner object and wraps it. auto inner_id = ObjectID::FromRandom(); auto outer_id = ObjectID::FromRandom(); owner->Put(inner_id); owner->PutWrappedId(outer_id, inner_id); // The owner submits a task that depends on the outer object. The task will // be given a reference to inner_id. owner->SubmitTaskWithArg(outer_id); // The owner's references go out of scope. owner->rc_.RemoveLocalReference(outer_id, nullptr); owner->rc_.RemoveLocalReference(inner_id, nullptr); // The owner's ref count > 0 for both objects. ASSERT_TRUE(owner->rc_.HasReference(outer_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Borrower 1 is given a reference to the inner object. borrower1->ExecuteTaskWithArg(outer_id, inner_id, owner->task_id_, owner->address_); // The borrower submits a task that depends on the inner object. auto outer_id2 = ObjectID::FromRandom(); borrower1->PutWrappedId(outer_id2, inner_id); borrower1->SubmitTaskWithArg(outer_id2); borrower1->rc_.RemoveLocalReference(inner_id, nullptr); borrower1->rc_.RemoveLocalReference(outer_id2, nullptr); ASSERT_TRUE(borrower1->rc_.HasReference(inner_id)); ASSERT_TRUE(borrower1->rc_.HasReference(outer_id2)); // The borrower task returns to the owner without waiting for its submitted // task to finish. auto borrower_refs = borrower1->FinishExecutingTask(outer_id, ObjectID::Nil()); ASSERT_TRUE(borrower1->rc_.HasReference(inner_id)); ASSERT_TRUE(borrower1->rc_.HasReference(outer_id2)); ASSERT_FALSE(borrower1->rc_.HasReference(outer_id)); // The owner receives the borrower's reply and merges the borrower's ref // count into its own. owner->HandleSubmittedTaskFinished(outer_id, {}, borrower1->address_, borrower_refs); borrower1->FlushBorrowerCallbacks(); // Check that owner now has borrower in inner's borrowers list. ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Check that owner's ref count for outer == 0 since the borrower task // returned and there were no local references to outer_id. ASSERT_FALSE(owner->rc_.HasReference(outer_id)); // Borrower 2 starts executing. It is given a reference to the inner object // when it gets outer_id2 as an argument. borrower2->ExecuteTaskWithArg(outer_id2, inner_id, owner->task_id_, owner->address_); ASSERT_TRUE(borrower2->rc_.HasReference(inner_id)); // Borrower 2 finishes but it is still using inner_id. borrower_refs = borrower2->FinishExecutingTask(outer_id2, ObjectID::Nil()); ASSERT_TRUE(borrower2->rc_.HasReference(inner_id)); ASSERT_FALSE(borrower2->rc_.HasReference(outer_id2)); ASSERT_FALSE(borrower2->rc_.HasReference(outer_id)); borrower1->HandleSubmittedTaskFinished(outer_id2, {}, borrower2->address_, borrower_refs); borrower2->FlushBorrowerCallbacks(); // Borrower 1 no longer has a reference to any objects. ASSERT_FALSE(borrower1->rc_.HasReference(inner_id)); ASSERT_FALSE(borrower1->rc_.HasReference(outer_id2)); // The owner should now have borrower 2 in its count. ASSERT_TRUE(owner->rc_.HasReference(inner_id)); borrower2->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_FALSE(borrower2->rc_.HasReference(inner_id)); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); } // A task is given a reference to an object ID, whose value contains another // object ID. The task gets a reference to the innermost object ID, but deletes // it by the time the task finishes. // // @ray.remote // def borrower(mid_ids): // inner_id = ray.get(mid_ids[0]) // del inner_id // // inner_id = ray.put(1) // mid_id = ray.put([inner_id]) // outer_id = ray.put([mid_id]) // res = borrower.remote(outer_id) TEST(DistributedReferenceCountTest, TestNestedObjectNoBorrow) { auto borrower = std::make_shared<MockWorkerClient>("1"); auto owner = std::make_shared<MockWorkerClient>( "2", [&](const rpc::Address &addr) { return borrower; }); // The owner creates an inner object and wraps it. auto inner_id = ObjectID::FromRandom(); auto mid_id = ObjectID::FromRandom(); auto outer_id = ObjectID::FromRandom(); owner->Put(inner_id); owner->PutWrappedId(mid_id, inner_id); owner->PutWrappedId(outer_id, mid_id); // The owner submits a task that depends on the outer object. The task will // be given a reference to mid_id. owner->SubmitTaskWithArg(outer_id); // The owner's references go out of scope. owner->rc_.RemoveLocalReference(outer_id, nullptr); owner->rc_.RemoveLocalReference(mid_id, nullptr); owner->rc_.RemoveLocalReference(inner_id, nullptr); // The owner's ref count > 0 for all objects. ASSERT_TRUE(owner->rc_.HasReference(outer_id)); ASSERT_TRUE(owner->rc_.HasReference(mid_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower is given a reference to the middle object. borrower->ExecuteTaskWithArg(outer_id, mid_id, owner->task_id_, owner->address_); ASSERT_TRUE(borrower->rc_.HasReference(mid_id)); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); // The borrower unwraps the inner object with ray.get. borrower->GetSerializedObjectId(mid_id, inner_id, owner->task_id_, owner->address_); borrower->rc_.RemoveLocalReference(mid_id, nullptr); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // The borrower's reference to inner_id goes out of scope. borrower->rc_.RemoveLocalReference(inner_id, nullptr); // The borrower task returns to the owner. auto borrower_refs = borrower->FinishExecutingTask(outer_id, ObjectID::Nil()); ASSERT_FALSE(borrower->rc_.HasReference(outer_id)); ASSERT_FALSE(borrower->rc_.HasReference(mid_id)); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); // The owner receives the borrower's reply and merges the borrower's ref // count into its own. owner->HandleSubmittedTaskFinished(outer_id, {}, borrower->address_, borrower_refs); // Check that owner now has nothing in scope. ASSERT_FALSE(owner->rc_.HasReference(outer_id)); ASSERT_FALSE(owner->rc_.HasReference(mid_id)); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); } // A task is given a reference to an object ID, whose value contains another // object ID. The task gets a reference to the innermost object ID, and is // still borrowing it by the time the task finishes. // // @ray.remote // def borrower(mid_ids): // inner_id = ray.get(mid_ids[0]) // foo.remote(inner_id) // // inner_id = ray.put(1) // mid_id = ray.put([inner_id]) // outer_id = ray.put([mid_id]) // res = borrower.remote(outer_id) TEST(DistributedReferenceCountTest, TestNestedObject) { auto borrower = std::make_shared<MockWorkerClient>("1"); auto owner = std::make_shared<MockWorkerClient>( "2", [&](const rpc::Address &addr) { return borrower; }); // The owner creates an inner object and wraps it. auto inner_id = ObjectID::FromRandom(); auto mid_id = ObjectID::FromRandom(); auto outer_id = ObjectID::FromRandom(); owner->Put(inner_id); owner->PutWrappedId(mid_id, inner_id); owner->PutWrappedId(outer_id, mid_id); // The owner submits a task that depends on the outer object. The task will // be given a reference to mid_id. owner->SubmitTaskWithArg(outer_id); // The owner's references go out of scope. owner->rc_.RemoveLocalReference(outer_id, nullptr); owner->rc_.RemoveLocalReference(mid_id, nullptr); owner->rc_.RemoveLocalReference(inner_id, nullptr); // The owner's ref count > 0 for all objects. ASSERT_TRUE(owner->rc_.HasReference(outer_id)); ASSERT_TRUE(owner->rc_.HasReference(mid_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower is given a reference to the middle object. borrower->ExecuteTaskWithArg(outer_id, mid_id, owner->task_id_, owner->address_); ASSERT_TRUE(borrower->rc_.HasReference(mid_id)); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); // The borrower unwraps the inner object with ray.get. borrower->GetSerializedObjectId(mid_id, inner_id, owner->task_id_, owner->address_); borrower->rc_.RemoveLocalReference(mid_id, nullptr); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // The borrower task returns to the owner while still using inner_id. auto borrower_refs = borrower->FinishExecutingTask(outer_id, ObjectID::Nil()); ASSERT_FALSE(borrower->rc_.HasReference(outer_id)); ASSERT_FALSE(borrower->rc_.HasReference(mid_id)); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // The owner receives the borrower's reply and merges the borrower's ref // count into its own. owner->HandleSubmittedTaskFinished(outer_id, {}, borrower->address_, borrower_refs); // Check that owner now has borrower in inner's borrowers list. ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Check that owner's ref count for outer and mid are 0 since the borrower // task returned and there were no local references to outer_id. ASSERT_FALSE(owner->rc_.HasReference(outer_id)); ASSERT_FALSE(owner->rc_.HasReference(mid_id)); // The borrower receives the owner's wait message. It should return a reply // to the owner immediately saying that it is no longer using inner_id. borrower->FlushBorrowerCallbacks(); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower is no longer using inner_id, but it hasn't received the // message from the owner yet. borrower->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); } // A borrower is given a reference to an object ID, whose value contains // another object ID. The borrower passes the reference again to another // borrower and waits for it to finish. The nested borrower unwraps the outer // object and gets a reference to the innermost ID. // // @ray.remote // def borrower2(owner_id2): // owner_id1 = ray.get(owner_id2[0])[0] // foo.remote(owner_id1) // // @ray.remote // def borrower1(owner_id2): // ray.get(borrower2.remote(owner_id2)) // // owner_id1 = ray.put(1) // owner_id2 = ray.put([owner_id1]) // owner_id3 = ray.put([owner_id2]) // res = borrower1.remote(owner_id3) TEST(DistributedReferenceCountTest, TestNestedObjectDifferentOwners) { auto borrower1 = std::make_shared<MockWorkerClient>("1"); auto borrower2 = std::make_shared<MockWorkerClient>("2"); auto owner = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { if (addr.ip_address() == borrower1->address_.ip_address()) { return borrower1; } else { return borrower2; } }); // The owner creates an inner object and wraps it. auto owner_id1 = ObjectID::FromRandom(); auto owner_id2 = ObjectID::FromRandom(); auto owner_id3 = ObjectID::FromRandom(); owner->Put(owner_id1); owner->PutWrappedId(owner_id2, owner_id1); owner->PutWrappedId(owner_id3, owner_id2); // The owner submits a task that depends on the outer object. The task will // be given a reference to owner_id2. owner->SubmitTaskWithArg(owner_id3); // The owner's references go out of scope. owner->rc_.RemoveLocalReference(owner_id1, nullptr); owner->rc_.RemoveLocalReference(owner_id2, nullptr); owner->rc_.RemoveLocalReference(owner_id3, nullptr); // The borrower is given a reference to the middle object. borrower1->ExecuteTaskWithArg(owner_id3, owner_id2, owner->task_id_, owner->address_); ASSERT_TRUE(borrower1->rc_.HasReference(owner_id2)); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id1)); // The borrower wraps the object ID again. auto borrower_id = ObjectID::FromRandom(); borrower1->PutWrappedId(borrower_id, owner_id2); borrower1->rc_.RemoveLocalReference(owner_id2, nullptr); // Borrower 1 submits a task that depends on the wrapped object. The task // will be given a reference to owner_id2. borrower1->SubmitTaskWithArg(borrower_id); borrower1->rc_.RemoveLocalReference(borrower_id, nullptr); borrower2->ExecuteTaskWithArg(borrower_id, owner_id2, owner->task_id_, owner->address_); // The nested task returns while still using owner_id1. borrower2->GetSerializedObjectId(owner_id2, owner_id1, owner->task_id_, owner->address_); borrower2->rc_.RemoveLocalReference(owner_id2, nullptr); auto borrower_refs = borrower2->FinishExecutingTask(borrower_id, ObjectID::Nil()); ASSERT_TRUE(borrower2->rc_.HasReference(owner_id1)); ASSERT_FALSE(borrower2->rc_.HasReference(owner_id2)); // Borrower 1 should now know that borrower 2 is borrowing the inner object // ID. borrower1->HandleSubmittedTaskFinished(borrower_id, {}, borrower2->address_, borrower_refs); ASSERT_TRUE(borrower1->rc_.HasReference(owner_id1)); // Borrower 1 finishes. It should not have any references now because all // state has been merged into the owner. borrower_refs = borrower1->FinishExecutingTask(owner_id3, ObjectID::Nil()); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id1)); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id2)); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id3)); ASSERT_FALSE(borrower1->rc_.HasReference(borrower_id)); // The owner receives the borrower's reply and merges the borrower's ref // count into its own. owner->HandleSubmittedTaskFinished(owner_id3, {}, borrower1->address_, borrower_refs); // Check that owner now has borrower2 in inner's borrowers list. ASSERT_TRUE(owner->rc_.HasReference(owner_id1)); ASSERT_FALSE(owner->rc_.HasReference(owner_id2)); ASSERT_FALSE(owner->rc_.HasReference(owner_id3)); // The borrower receives the owner's wait message. borrower2->FlushBorrowerCallbacks(); ASSERT_TRUE(owner->rc_.HasReference(owner_id1)); borrower2->rc_.RemoveLocalReference(owner_id1, nullptr); ASSERT_FALSE(borrower2->rc_.HasReference(owner_id1)); ASSERT_FALSE(owner->rc_.HasReference(owner_id1)); } // A borrower is given a reference to an object ID, whose value contains // another object ID. The borrower passes the reference again to another // borrower but does not wait for it to finish. The nested borrower unwraps the // outer object and gets a reference to the innermost ID. // // @ray.remote // def borrower2(owner_id2): // owner_id1 = ray.get(owner_id2[0])[0] // foo.remote(owner_id1) // // @ray.remote // def borrower1(owner_id2): // borrower2.remote(owner_id2) // // owner_id1 = ray.put(1) // owner_id2 = ray.put([owner_id1]) // owner_id3 = ray.put([owner_id2]) // res = borrower1.remote(owner_id3) TEST(DistributedReferenceCountTest, TestNestedObjectDifferentOwners2) { auto borrower1 = std::make_shared<MockWorkerClient>("1"); auto borrower2 = std::make_shared<MockWorkerClient>("2"); auto owner = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { if (addr.ip_address() == borrower1->address_.ip_address()) { return borrower1; } else { return borrower2; } }); // The owner creates an inner object and wraps it. auto owner_id1 = ObjectID::FromRandom(); auto owner_id2 = ObjectID::FromRandom(); auto owner_id3 = ObjectID::FromRandom(); owner->Put(owner_id1); owner->PutWrappedId(owner_id2, owner_id1); owner->PutWrappedId(owner_id3, owner_id2); // The owner submits a task that depends on the outer object. The task will // be given a reference to owner_id2. owner->SubmitTaskWithArg(owner_id3); // The owner's references go out of scope. owner->rc_.RemoveLocalReference(owner_id1, nullptr); owner->rc_.RemoveLocalReference(owner_id2, nullptr); owner->rc_.RemoveLocalReference(owner_id3, nullptr); // The borrower is given a reference to the middle object. borrower1->ExecuteTaskWithArg(owner_id3, owner_id2, owner->task_id_, owner->address_); ASSERT_TRUE(borrower1->rc_.HasReference(owner_id2)); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id1)); // The borrower wraps the object ID again. auto borrower_id = ObjectID::FromRandom(); borrower1->PutWrappedId(borrower_id, owner_id2); borrower1->rc_.RemoveLocalReference(owner_id2, nullptr); // Borrower 1 submits a task that depends on the wrapped object. The task // will be given a reference to owner_id2. borrower1->SubmitTaskWithArg(borrower_id); borrower2->ExecuteTaskWithArg(borrower_id, owner_id2, owner->task_id_, owner->address_); // The nested task returns while still using owner_id1. borrower2->GetSerializedObjectId(owner_id2, owner_id1, owner->task_id_, owner->address_); borrower2->rc_.RemoveLocalReference(owner_id2, nullptr); auto borrower_refs = borrower2->FinishExecutingTask(borrower_id, ObjectID::Nil()); ASSERT_TRUE(borrower2->rc_.HasReference(owner_id1)); ASSERT_FALSE(borrower2->rc_.HasReference(owner_id2)); // Borrower 1 should now know that borrower 2 is borrowing the inner object // ID. borrower1->HandleSubmittedTaskFinished(borrower_id, {}, borrower2->address_, borrower_refs); ASSERT_TRUE(borrower1->rc_.HasReference(owner_id1)); ASSERT_TRUE(borrower1->rc_.HasReference(owner_id2)); // Borrower 1 finishes. It should only have its reference to owner_id2 now. borrower_refs = borrower1->FinishExecutingTask(owner_id3, ObjectID::Nil()); ASSERT_TRUE(borrower1->rc_.HasReference(owner_id2)); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id3)); // The owner receives the borrower's reply and merges the borrower's ref // count into its own. owner->HandleSubmittedTaskFinished(owner_id3, {}, borrower1->address_, borrower_refs); // Check that owner now has borrower2 in inner's borrowers list. ASSERT_TRUE(owner->rc_.HasReference(owner_id1)); ASSERT_TRUE(owner->rc_.HasReference(owner_id2)); ASSERT_FALSE(owner->rc_.HasReference(owner_id3)); // The borrower receives the owner's wait message. borrower2->FlushBorrowerCallbacks(); ASSERT_TRUE(owner->rc_.HasReference(owner_id1)); borrower2->rc_.RemoveLocalReference(owner_id1, nullptr); ASSERT_FALSE(borrower2->rc_.HasReference(owner_id1)); ASSERT_TRUE(owner->rc_.HasReference(owner_id1)); // The borrower receives the owner's wait message. borrower1->FlushBorrowerCallbacks(); ASSERT_TRUE(owner->rc_.HasReference(owner_id2)); borrower1->rc_.RemoveLocalReference(borrower_id, nullptr); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id2)); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id1)); ASSERT_FALSE(owner->rc_.HasReference(owner_id2)); } // A borrower is given a reference to an object ID and passes the reference to // another task. The nested task executes on the object's owner. // // @ray.remote // def executes_on_owner(inner_ids): // inner_id = inner_ids[0] // // @ray.remote // def borrower(inner_ids): // outer_id2 = ray.put(inner_ids) // executes_on_owner.remote(outer_id2) // // inner_id = ray.put(1) // outer_id = ray.put([inner_id]) // res = borrower.remote(outer_id) TEST(DistributedReferenceCountTest, TestBorrowerPingPong) { auto borrower = std::make_shared<MockWorkerClient>("1"); auto owner = std::make_shared<MockWorkerClient>("2", [&](const rpc::Address &addr) { RAY_CHECK(addr.ip_address() == borrower->address_.ip_address()); return borrower; }); // The owner creates an inner object and wraps it. auto inner_id = ObjectID::FromRandom(); auto outer_id = ObjectID::FromRandom(); owner->Put(inner_id); owner->PutWrappedId(outer_id, inner_id); // The owner submits a task that depends on the outer object. The task will // be given a reference to inner_id. owner->SubmitTaskWithArg(outer_id); // The owner's references go out of scope. owner->rc_.RemoveLocalReference(outer_id, nullptr); owner->rc_.RemoveLocalReference(inner_id, nullptr); // Borrower 1 is given a reference to the inner object. borrower->ExecuteTaskWithArg(outer_id, inner_id, owner->task_id_, owner->address_); // The borrower submits a task that depends on the inner object. auto outer_id2 = ObjectID::FromRandom(); borrower->PutWrappedId(outer_id2, inner_id); borrower->SubmitTaskWithArg(outer_id2); borrower->rc_.RemoveLocalReference(inner_id, nullptr); borrower->rc_.RemoveLocalReference(outer_id2, nullptr); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); ASSERT_TRUE(borrower->rc_.HasReference(outer_id2)); // The borrower task returns to the owner without waiting for its submitted // task to finish. auto borrower_refs = borrower->FinishExecutingTask(outer_id, ObjectID::Nil()); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); ASSERT_TRUE(borrower->rc_.HasReference(outer_id2)); ASSERT_FALSE(borrower->rc_.HasReference(outer_id)); // The owner receives the borrower's reply and merges the borrower's ref // count into its own. owner->HandleSubmittedTaskFinished(outer_id, {}, borrower->address_, borrower_refs); borrower->FlushBorrowerCallbacks(); // Check that owner now has a borrower for inner. ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Check that owner's ref count for outer == 0 since the borrower task // returned and there were no local references to outer_id. ASSERT_FALSE(owner->rc_.HasReference(outer_id)); // Owner starts executing the submitted task. It is given a second reference // to the inner object when it gets outer_id2 as an argument. owner->ExecuteTaskWithArg(outer_id2, inner_id, owner->task_id_, owner->address_); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Owner finishes but it is still using inner_id. borrower_refs = owner->FinishExecutingTask(outer_id2, ObjectID::Nil()); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); borrower->HandleSubmittedTaskFinished(outer_id2, {}, owner->address_, borrower_refs); borrower->FlushBorrowerCallbacks(); // Borrower no longer has a reference to any objects. ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); ASSERT_FALSE(borrower->rc_.HasReference(outer_id2)); // The owner should now have borrower 2 in its count. ASSERT_TRUE(owner->rc_.HasReference(inner_id)); owner->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); } // A borrower is given two references to the same object ID. `task` and `Actor` // execute on the same process. // // @ray.remote // def task(inner_ids): // foo.remote(inner_ids[0]) // // @ray.remote // class Actor: // def __init__(self, inner_ids): // self.inner_id = inner_ids[0] // // inner_id = ray.put(1) // outer_id = ray.put([inner_id]) // res = task.remote(outer_id) // Actor.remote(outer_id) TEST(DistributedReferenceCountTest, TestDuplicateBorrower) { auto borrower = std::make_shared<MockWorkerClient>("1"); auto owner = std::make_shared<MockWorkerClient>( "2", [&](const rpc::Address &addr) { return borrower; }); // The owner creates an inner object and wraps it. auto inner_id = ObjectID::FromRandom(); auto outer_id = ObjectID::FromRandom(); owner->Put(inner_id); owner->PutWrappedId(outer_id, inner_id); // The owner submits a task that depends on the outer object. The task will // be given a reference to inner_id. owner->SubmitTaskWithArg(outer_id); // The owner's references go out of scope. owner->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower is given a reference to the inner object. borrower->ExecuteTaskWithArg(outer_id, inner_id, owner->task_id_, owner->address_); // The borrower submits a task that depends on the inner object. borrower->SubmitTaskWithArg(inner_id); borrower->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // The borrower task returns to the owner without waiting for its submitted // task to finish. auto borrower_refs1 = borrower->FinishExecutingTask(outer_id, ObjectID::Nil()); // Check that the borrower's ref count for inner_id > 0 because of the // pending task. ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // The borrower is given a 2nd reference to the inner object. owner->SubmitTaskWithArg(outer_id); owner->rc_.RemoveLocalReference(outer_id, nullptr); borrower->ExecuteTaskWithArg(outer_id, inner_id, owner->task_id_, owner->address_); auto borrower_refs2 = borrower->FinishExecutingTask(outer_id, ObjectID::Nil()); // The owner receives the borrower's replies and merges the borrower's ref // count into its own. owner->HandleSubmittedTaskFinished(outer_id, {}, borrower->address_, borrower_refs1); owner->HandleSubmittedTaskFinished(outer_id, {}, borrower->address_, borrower_refs2); borrower->FlushBorrowerCallbacks(); // Check that owner now has borrower in inner's borrowers list. ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Check that owner's ref count for outer == 0 since the borrower task // returned and there were no local references to outer_id. ASSERT_FALSE(owner->rc_.HasReference(outer_id)); // The task submitted by the borrower returns and its second reference goes // out of scope. Everyone's ref count should go to 0. borrower->HandleSubmittedTaskFinished(inner_id); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); borrower->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); ASSERT_FALSE(borrower->rc_.HasReference(outer_id)); ASSERT_FALSE(owner->rc_.HasReference(outer_id)); } // A borrower is given references to 2 different objects, which each contain a // reference to an object ID. The borrower unwraps both objects and receives a // duplicate reference to the inner ID. TEST(DistributedReferenceCountTest, TestDuplicateNestedObject) { auto borrower1 = std::make_shared<MockWorkerClient>("1"); auto borrower2 = std::make_shared<MockWorkerClient>("2"); auto owner = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { if (addr.ip_address() == borrower1->address_.ip_address()) { return borrower1; } else { return borrower2; } }); // The owner creates an inner object and wraps it. auto owner_id1 = ObjectID::FromRandom(); auto owner_id2 = ObjectID::FromRandom(); auto owner_id3 = ObjectID::FromRandom(); owner->Put(owner_id1); owner->PutWrappedId(owner_id2, owner_id1); owner->PutWrappedId(owner_id3, owner_id2); owner->SubmitTaskWithArg(owner_id3); owner->SubmitTaskWithArg(owner_id2); owner->rc_.RemoveLocalReference(owner_id1, nullptr); owner->rc_.RemoveLocalReference(owner_id2, nullptr); owner->rc_.RemoveLocalReference(owner_id3, nullptr); borrower2->ExecuteTaskWithArg(owner_id3, owner_id2, owner->task_id_, owner->address_); borrower2->GetSerializedObjectId(owner_id2, owner_id1, owner->task_id_, owner->address_); borrower2->rc_.RemoveLocalReference(owner_id2, nullptr); // The nested task returns while still using owner_id1. auto borrower_refs = borrower2->FinishExecutingTask(owner_id3, ObjectID::Nil()); owner->HandleSubmittedTaskFinished(owner_id3, {}, borrower2->address_, borrower_refs); ASSERT_TRUE(borrower2->FlushBorrowerCallbacks()); // The owner submits a task that is given a reference to owner_id1. borrower1->ExecuteTaskWithArg(owner_id2, owner_id1, owner->task_id_, owner->address_); // The borrower wraps the object ID again. auto borrower_id = ObjectID::FromRandom(); borrower1->PutWrappedId(borrower_id, owner_id1); borrower1->rc_.RemoveLocalReference(owner_id1, nullptr); // Borrower 1 submits a task that depends on the wrapped object. The task // will be given a reference to owner_id1. borrower1->SubmitTaskWithArg(borrower_id); borrower1->rc_.RemoveLocalReference(borrower_id, nullptr); borrower2->ExecuteTaskWithArg(borrower_id, owner_id1, owner->task_id_, owner->address_); // The nested task returns while still using owner_id1. // It should now have 2 local references to owner_id1, one from the owner and // one from the borrower. borrower_refs = borrower2->FinishExecutingTask(borrower_id, ObjectID::Nil()); borrower1->HandleSubmittedTaskFinished(borrower_id, {}, borrower2->address_, borrower_refs); // Borrower 1 finishes. It should not have any references now because all // state has been merged into the owner. borrower_refs = borrower1->FinishExecutingTask(owner_id2, ObjectID::Nil()); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id1)); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id2)); ASSERT_FALSE(borrower1->rc_.HasReference(owner_id3)); ASSERT_FALSE(borrower1->rc_.HasReference(borrower_id)); // Borrower 1 should not have merge any refs into the owner because borrower 2's ref was // already merged into the owner. owner->HandleSubmittedTaskFinished(owner_id2, {}, borrower1->address_, borrower_refs); // The borrower receives the owner's wait message. borrower2->FlushBorrowerCallbacks(); ASSERT_TRUE(owner->rc_.HasReference(owner_id1)); borrower2->rc_.RemoveLocalReference(owner_id1, nullptr); ASSERT_TRUE(owner->rc_.HasReference(owner_id1)); borrower2->rc_.RemoveLocalReference(owner_id1, nullptr); ASSERT_FALSE(borrower2->rc_.HasReference(owner_id1)); ASSERT_FALSE(owner->rc_.HasReference(owner_id1)); } // We submit a task and immediately delete the reference to the return ID. The // submitted task returns an object ID. // // @ray.remote // def returns_id(): // inner_id = ray.put() // return inner_id // // returns_id.remote() TEST(DistributedReferenceCountTest, TestReturnObjectIdNoBorrow) { auto caller = std::make_shared<MockWorkerClient>("1"); auto owner = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { RAY_CHECK(addr.ip_address() == caller->address_.ip_address()); return caller; }); // Caller submits a task. auto return_id = caller->SubmitTaskWithArg(ObjectID::Nil()); // Task returns inner_id as its return value. auto inner_id = ObjectID::FromRandom(); owner->Put(inner_id); rpc::WorkerAddress addr(caller->address_); auto refs = owner->FinishExecutingTask(ObjectID::Nil(), return_id, &inner_id, &addr); owner->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(refs.empty()); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Caller's ref to the task's return ID goes out of scope before it hears // from the owner of inner_id. caller->HandleSubmittedTaskFinished(ObjectID::Nil(), {{return_id, {inner_id}}}); caller->rc_.RemoveLocalReference(return_id, nullptr); ASSERT_FALSE(caller->rc_.HasReference(return_id)); ASSERT_FALSE(caller->rc_.HasReference(inner_id)); // Caller should respond to the owner's message immediately. ASSERT_TRUE(caller->FlushBorrowerCallbacks()); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); } // We submit a task and keep the reference to the return ID. The submitted task // returns an object ID. // // @ray.remote // def returns_id(): // inner_id = ray.put() // return inner_id // // return_id = returns_id.remote() TEST(DistributedReferenceCountTest, TestReturnObjectIdBorrow) { auto caller = std::make_shared<MockWorkerClient>("1"); auto owner = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { RAY_CHECK(addr.ip_address() == caller->address_.ip_address()); return caller; }); // Caller submits a task. auto return_id = caller->SubmitTaskWithArg(ObjectID::Nil()); // Task returns inner_id as its return value. auto inner_id = ObjectID::FromRandom(); owner->Put(inner_id); rpc::WorkerAddress addr(caller->address_); auto refs = owner->FinishExecutingTask(ObjectID::Nil(), return_id, &inner_id, &addr); owner->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(refs.empty()); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Caller receives the owner's message, but inner_id is still in scope // because caller has a reference to return_id. caller->HandleSubmittedTaskFinished(ObjectID::Nil(), {{return_id, {inner_id}}}); ASSERT_TRUE(caller->FlushBorrowerCallbacks()); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Caller's reference to return_id goes out of scope. The caller should // respond to the owner of inner_id so that inner_id can be deleted. caller->rc_.RemoveLocalReference(return_id, nullptr); ASSERT_FALSE(caller->rc_.HasReference(return_id)); ASSERT_FALSE(caller->rc_.HasReference(inner_id)); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); } // We submit a task and submit another task that depends on the return ID. The // submitted task returns an object ID, which will get borrowed by the second // task. // // @ray.remote // def returns_id(): // inner_id = ray.put() // return inner_id // // return_id = returns_id.remote() // borrow.remote(return_id) TEST(DistributedReferenceCountTest, TestReturnObjectIdBorrowChain) { auto caller = std::make_shared<MockWorkerClient>("1"); auto borrower = std::make_shared<MockWorkerClient>("2"); auto owner = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { if (addr.ip_address() == caller->address_.ip_address()) { return caller; } else { return borrower; } }); // Caller submits a task. auto return_id = caller->SubmitTaskWithArg(ObjectID::Nil()); // Task returns inner_id as its return value. auto inner_id = ObjectID::FromRandom(); owner->Put(inner_id); rpc::WorkerAddress addr(caller->address_); auto refs = owner->FinishExecutingTask(ObjectID::Nil(), return_id, &inner_id, &addr); owner->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(refs.empty()); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Caller receives the owner's message, but inner_id is still in scope // because caller has a reference to return_id. caller->HandleSubmittedTaskFinished(ObjectID::Nil(), {{return_id, {inner_id}}}); caller->SubmitTaskWithArg(return_id); caller->rc_.RemoveLocalReference(return_id, nullptr); ASSERT_TRUE(caller->FlushBorrowerCallbacks()); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Borrower receives a reference to inner_id. It still has a reference when // the task returns. borrower->ExecuteTaskWithArg(return_id, inner_id, owner->task_id_, owner->address_); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); auto borrower_refs = borrower->FinishExecutingTask(return_id, return_id); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // Borrower merges ref count into the caller. caller->HandleSubmittedTaskFinished(return_id, {}, borrower->address_, borrower_refs); // The caller should not have a ref count anymore because it was merged into // the owner. ASSERT_FALSE(caller->rc_.HasReference(return_id)); ASSERT_FALSE(caller->rc_.HasReference(inner_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower's receives the owner's message and its reference goes out of // scope. ASSERT_TRUE(borrower->FlushBorrowerCallbacks()); borrower->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_FALSE(borrower->rc_.HasReference(return_id)); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); } // We submit a task and submit another task that depends on the return ID. The // first submitted task returns an object ID, which will get borrowed by the second // task. The second task returns the borrowed ID. // // @ray.remote // def returns_id(): // inner_id = ray.put() // return inner_id // // @ray.remote // def returns_borrowed_id(inner_ids): // return inner_ids // // return_id = returns_id.remote() // returns_borrowed_id.remote(return_id) TEST(DistributedReferenceCountTest, TestReturnBorrowedId) { auto caller = std::make_shared<MockWorkerClient>("1"); auto borrower = std::make_shared<MockWorkerClient>("2"); auto owner = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { if (addr.ip_address() == caller->address_.ip_address()) { return caller; } else { return borrower; } }); // Caller submits a task. auto return_id = caller->SubmitTaskWithArg(ObjectID::Nil()); // Task returns inner_id as its return value. auto inner_id = ObjectID::FromRandom(); owner->Put(inner_id); rpc::WorkerAddress addr(caller->address_); auto refs = owner->FinishExecutingTask(ObjectID::Nil(), return_id, &inner_id, &addr); owner->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(refs.empty()); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Caller receives the owner's message, but inner_id is still in scope // because caller has a reference to return_id. caller->HandleSubmittedTaskFinished(ObjectID::Nil(), {{return_id, {inner_id}}}); auto borrower_return_id = caller->SubmitTaskWithArg(return_id); caller->rc_.RemoveLocalReference(return_id, nullptr); ASSERT_TRUE(caller->FlushBorrowerCallbacks()); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Borrower receives a reference to inner_id. It returns the inner_id as its // return value. borrower->ExecuteTaskWithArg(return_id, inner_id, owner->task_id_, owner->address_); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); auto borrower_refs = borrower->FinishExecutingTask(return_id, borrower_return_id, &inner_id, &addr); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // Borrower merges ref count into the caller. caller->HandleSubmittedTaskFinished(return_id, {{borrower_return_id, {inner_id}}}, borrower->address_, borrower_refs); // The caller should still have a ref count because it has a reference to // borrower_return_id. ASSERT_FALSE(caller->rc_.HasReference(return_id)); ASSERT_TRUE(caller->rc_.HasReference(borrower_return_id)); ASSERT_TRUE(caller->rc_.HasReference(inner_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower's receives the owner's message and its reference goes out of // scope. borrower->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_FALSE(borrower->rc_.HasReference(borrower_return_id)); ASSERT_FALSE(borrower->rc_.HasReference(return_id)); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); // The caller's reference to the borrower's return value goes out of scope. caller->rc_.RemoveLocalReference(borrower_return_id, nullptr); ASSERT_FALSE(caller->rc_.HasReference(borrower_return_id)); ASSERT_FALSE(caller->rc_.HasReference(inner_id)); // The owner should still have the object ID in scope because it hasn't heard // from borrower yet. ASSERT_TRUE(owner->rc_.HasReference(inner_id)); ASSERT_TRUE(borrower->FlushBorrowerCallbacks()); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); } // We submit a task and submit another task that depends on the return ID. The // first submitted task returns an object ID, which will get borrowed by the second // task. The second task returns the borrowed ID. The driver gets the value of // the second task and now has a reference to the inner object ID. // // @ray.remote // def returns_id(): // inner_id = ray.put() // return inner_id // // @ray.remote // def returns_borrowed_id(inner_ids): // return inner_ids // // return_id = returns_id.remote() // inner_id = ray.get(returns_borrowed_id.remote(return_id))[0] TEST(DistributedReferenceCountTest, TestReturnBorrowedIdDeserialize) { auto caller = std::make_shared<MockWorkerClient>("1"); auto borrower = std::make_shared<MockWorkerClient>("2"); auto owner = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { if (addr.ip_address() == caller->address_.ip_address()) { return caller; } else { return borrower; } }); // Caller submits a task. auto return_id = caller->SubmitTaskWithArg(ObjectID::Nil()); // Task returns inner_id as its return value. auto inner_id = ObjectID::FromRandom(); owner->Put(inner_id); rpc::WorkerAddress addr(caller->address_); auto refs = owner->FinishExecutingTask(ObjectID::Nil(), return_id, &inner_id, &addr); owner->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(refs.empty()); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Caller receives the owner's message, but inner_id is still in scope // because caller has a reference to return_id. caller->HandleSubmittedTaskFinished(ObjectID::Nil(), {{return_id, {inner_id}}}); auto borrower_return_id = caller->SubmitTaskWithArg(return_id); caller->rc_.RemoveLocalReference(return_id, nullptr); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // Borrower receives a reference to inner_id. It returns the inner_id as its // return value. borrower->ExecuteTaskWithArg(return_id, inner_id, owner->task_id_, owner->address_); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); auto borrower_refs = borrower->FinishExecutingTask(return_id, borrower_return_id, &inner_id, &addr); ASSERT_TRUE(borrower->rc_.HasReference(inner_id)); // Borrower merges ref count into the caller. caller->HandleSubmittedTaskFinished(return_id, {{borrower_return_id, {inner_id}}}, borrower->address_, borrower_refs); // The caller should still have a ref count because it has a reference to // borrower_return_id. ASSERT_FALSE(caller->rc_.HasReference(return_id)); ASSERT_TRUE(caller->rc_.HasReference(borrower_return_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); caller->GetSerializedObjectId(borrower_return_id, inner_id, owner->task_id_, owner->address_); caller->rc_.RemoveLocalReference(borrower_return_id, nullptr); ASSERT_TRUE(caller->FlushBorrowerCallbacks()); caller->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_FALSE(caller->rc_.HasReference(return_id)); ASSERT_FALSE(caller->rc_.HasReference(borrower_return_id)); ASSERT_FALSE(caller->rc_.HasReference(inner_id)); ASSERT_TRUE(owner->rc_.HasReference(inner_id)); // The borrower's receives the owner's message and its reference goes out of // scope. ASSERT_TRUE(borrower->FlushBorrowerCallbacks()); borrower->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_FALSE(borrower->rc_.HasReference(borrower_return_id)); ASSERT_FALSE(borrower->rc_.HasReference(return_id)); ASSERT_FALSE(borrower->rc_.HasReference(inner_id)); ASSERT_FALSE(owner->rc_.HasReference(inner_id)); } // Recursively returning IDs. We submit a task, which submits another task and // returns the submitted task's return ID. The nested task creates an object // and returns that ID. // // @ray.remote // def nested_worker(): // inner_id = ray.put() // return inner_id // // @ray.remote // def worker(): // return nested_worker.remote() // // return_id = worker.remote() // nested_return_id = ray.get(return_id) // inner_id = ray.get(nested_return_id) TEST(DistributedReferenceCountTest, TestReturnIdChain) { auto root = std::make_shared<MockWorkerClient>("1"); auto worker = std::make_shared<MockWorkerClient>("2", [&](const rpc::Address &addr) { RAY_CHECK(addr.ip_address() == root->address_.ip_address()); return root; }); auto nested_worker = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { RAY_CHECK(addr.ip_address() == worker->address_.ip_address()); return worker; }); // Root submits a task. auto return_id = root->SubmitTaskWithArg(ObjectID::Nil()); // Task submits a nested task and returns the return ID. auto nested_return_id = worker->SubmitTaskWithArg(ObjectID::Nil()); rpc::WorkerAddress addr(root->address_); auto refs = worker->FinishExecutingTask(ObjectID::Nil(), return_id, &nested_return_id, &addr); // The nested task returns an ObjectID that it owns. auto inner_id = ObjectID::FromRandom(); nested_worker->Put(inner_id); rpc::WorkerAddress worker_addr(worker->address_); auto nested_refs = nested_worker->FinishExecutingTask(ObjectID::Nil(), nested_return_id, &inner_id, &worker_addr); nested_worker->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(nested_worker->rc_.HasReference(inner_id)); // All task execution replies are received. root->HandleSubmittedTaskFinished(ObjectID::Nil(), {{return_id, {nested_return_id}}}); worker->HandleSubmittedTaskFinished(ObjectID::Nil(), {{nested_return_id, {inner_id}}}); root->FlushBorrowerCallbacks(); worker->FlushBorrowerCallbacks(); // The reference only goes out of scope once the other workers' references to // their submitted tasks' return ID go out of scope. ASSERT_TRUE(nested_worker->rc_.HasReference(inner_id)); worker->rc_.RemoveLocalReference(nested_return_id, nullptr); ASSERT_TRUE(nested_worker->rc_.HasReference(inner_id)); root->rc_.RemoveLocalReference(return_id, nullptr); ASSERT_FALSE(nested_worker->rc_.HasReference(inner_id)); } // Recursively returning a borrowed object ID. We submit a task, which submits // another task, calls ray.get() on the return ID and returns the value. The // nested task creates an object and returns that ID. // // @ray.remote // def nested_worker(): // inner_id = ray.put() // return inner_id // // @ray.remote // def worker(): // return ray.get(nested_worker.remote()) // // return_id = worker.remote() // inner_id = ray.get(return_id) TEST(DistributedReferenceCountTest, TestReturnBorrowedIdChain) { auto root = std::make_shared<MockWorkerClient>("1"); auto worker = std::make_shared<MockWorkerClient>("2", [&](const rpc::Address &addr) { RAY_CHECK(addr.ip_address() == root->address_.ip_address()); return root; }); auto nested_worker = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { if (addr.ip_address() == root->address_.ip_address()) { return root; } else { return worker; } }); // Root submits a task. auto return_id = root->SubmitTaskWithArg(ObjectID::Nil()); // Task submits a nested task. auto nested_return_id = worker->SubmitTaskWithArg(ObjectID::Nil()); // The nested task returns an ObjectID that it owns. auto inner_id = ObjectID::FromRandom(); nested_worker->Put(inner_id); rpc::WorkerAddress worker_addr(worker->address_); auto nested_refs = nested_worker->FinishExecutingTask(ObjectID::Nil(), nested_return_id, &inner_id, &worker_addr); nested_worker->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(nested_worker->rc_.HasReference(inner_id)); // Worker receives the reply from the nested task. worker->HandleSubmittedTaskFinished(ObjectID::Nil(), {{nested_return_id, {inner_id}}}); worker->FlushBorrowerCallbacks(); // Worker deserializes the inner_id and returns it. worker->GetSerializedObjectId(nested_return_id, inner_id, nested_worker->task_id_, nested_worker->address_); rpc::WorkerAddress addr(root->address_); auto refs = worker->FinishExecutingTask(ObjectID::Nil(), return_id, &inner_id, &addr); // Worker no longer borrowers the inner ID. worker->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(worker->rc_.HasReference(inner_id)); worker->rc_.RemoveLocalReference(nested_return_id, nullptr); ASSERT_FALSE(worker->rc_.HasReference(inner_id)); ASSERT_TRUE(nested_worker->rc_.HasReference(inner_id)); // Root receives worker's reply, then the WaitForRefRemovedRequest from // nested_worker. root->HandleSubmittedTaskFinished(ObjectID::Nil(), {{return_id, {inner_id}}}); root->FlushBorrowerCallbacks(); // Object is still in scope because root now knows that return_id contains // inner_id. ASSERT_TRUE(nested_worker->rc_.HasReference(inner_id)); root->rc_.RemoveLocalReference(return_id, nullptr); ASSERT_FALSE(root->rc_.HasReference(return_id)); ASSERT_FALSE(root->rc_.HasReference(inner_id)); ASSERT_FALSE(nested_worker->rc_.HasReference(inner_id)); } // Recursively returning a borrowed object ID. We submit a task, which submits // another task, calls ray.get() on the return ID and returns the value. The // nested task creates an object and returns that ID. // // This test is the same as above, except that it reorders messages so that the // driver receives the WaitForRefRemovedRequest from nested_worker BEFORE it // receives the reply from worker indicating that return_id contains inner_id. // // @ray.remote // def nested_worker(): // inner_id = ray.put() // return inner_id // // @ray.remote // def worker(): // return ray.get(nested_worker.remote()) // // return_id = worker.remote() // inner_id = ray.get(return_id) TEST(DistributedReferenceCountTest, TestReturnBorrowedIdChainOutOfOrder) { auto root = std::make_shared<MockWorkerClient>("1"); auto worker = std::make_shared<MockWorkerClient>("2", [&](const rpc::Address &addr) { RAY_CHECK(addr.ip_address() == root->address_.ip_address()); return root; }); auto nested_worker = std::make_shared<MockWorkerClient>("3", [&](const rpc::Address &addr) { if (addr.ip_address() == root->address_.ip_address()) { return root; } else { return worker; } }); // Root submits a task. auto return_id = root->SubmitTaskWithArg(ObjectID::Nil()); // Task submits a nested task. auto nested_return_id = worker->SubmitTaskWithArg(ObjectID::Nil()); // The nested task returns an ObjectID that it owns. auto inner_id = ObjectID::FromRandom(); nested_worker->Put(inner_id); rpc::WorkerAddress worker_addr(worker->address_); auto nested_refs = nested_worker->FinishExecutingTask(ObjectID::Nil(), nested_return_id, &inner_id, &worker_addr); nested_worker->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(nested_worker->rc_.HasReference(inner_id)); // Worker receives the reply from the nested task. worker->HandleSubmittedTaskFinished(ObjectID::Nil(), {{nested_return_id, {inner_id}}}); worker->FlushBorrowerCallbacks(); // Worker deserializes the inner_id and returns it. worker->GetSerializedObjectId(nested_return_id, inner_id, nested_worker->task_id_, nested_worker->address_); rpc::WorkerAddress addr(root->address_); auto refs = worker->FinishExecutingTask(ObjectID::Nil(), return_id, &inner_id, &addr); // Worker no longer borrowers the inner ID. worker->rc_.RemoveLocalReference(inner_id, nullptr); ASSERT_TRUE(worker->rc_.HasReference(inner_id)); worker->rc_.RemoveLocalReference(nested_return_id, nullptr); ASSERT_FALSE(worker->rc_.HasReference(inner_id)); ASSERT_TRUE(nested_worker->rc_.HasReference(inner_id)); // Root receives the WaitForRefRemovedRequest from nested_worker BEFORE the // reply from worker. root->FlushBorrowerCallbacks(); ASSERT_TRUE(nested_worker->rc_.HasReference(inner_id)); root->HandleSubmittedTaskFinished(ObjectID::Nil(), {{return_id, {inner_id}}}); root->rc_.RemoveLocalReference(return_id, nullptr); ASSERT_FALSE(root->rc_.HasReference(return_id)); ASSERT_FALSE(root->rc_.HasReference(inner_id)); ASSERT_FALSE(nested_worker->rc_.HasReference(inner_id)); } // TODO: Test Pop and Merge individually. } // namespace ray int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
42.251794
90
0.732635
[ "object", "vector" ]
33709fdedb5dde028996d08bdcba45d59632e82a
5,187
cpp
C++
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMClientRectList.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMClientRectList.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMClientRectList.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017 Aidan Holm <aidanholm@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "WebKitDOMClientRectList.h" #include "ConvertToUTF8String.h" #include "DOMObjectCache.h" #include "WebKitDOMClientRectListPrivate.h" #include "WebKitDOMClientRectPrivate.h" #include "WebKitDOMPrivate.h" #include <WebCore/CSSImportRule.h> #include <WebCore/Document.h> #include <WebCore/ExceptionCodeDescription.h> #include <WebCore/ExceptionCode.h> #include <WebCore/JSMainThreadExecState.h> #include <wtf/GetPtr.h> #include <wtf/RefPtr.h> #define WEBKIT_DOM_CLIENT_RECT_LIST_GET_PRIVATE(obj) G_TYPE_INSTANCE_GET_PRIVATE(obj, WEBKIT_DOM_TYPE_CLIENT_RECT_LIST, WebKitDOMClientRectListPrivate) typedef struct _WebKitDOMClientRectListPrivate { RefPtr<WebCore::DOMRectList> coreObject; } WebKitDOMClientRectListPrivate; namespace WebKit { WebKitDOMClientRectList* kit(WebCore::DOMRectList* obj) { if (!obj) return nullptr; if (gpointer ret = DOMObjectCache::get(obj)) return WEBKIT_DOM_CLIENT_RECT_LIST(ret); return wrapDOMRectList(obj); } WebCore::DOMRectList* core(WebKitDOMClientRectList* request) { return request ? static_cast<WebCore::DOMRectList*>(WEBKIT_DOM_OBJECT(request)->coreObject) : nullptr; } WebKitDOMClientRectList* wrapDOMRectList(WebCore::DOMRectList* coreObject) { return WEBKIT_DOM_CLIENT_RECT_LIST(g_object_new(WEBKIT_DOM_TYPE_CLIENT_RECT_LIST, "core-object", coreObject, nullptr)); } } // namespace WebKit G_DEFINE_TYPE(WebKitDOMClientRectList, webkit_dom_client_rect_list, WEBKIT_DOM_TYPE_OBJECT) enum { PROP_0, PROP_LENGTH, }; static void webkit_dom_client_rect_list_finalize(GObject* object) { WebKitDOMClientRectListPrivate* priv = WEBKIT_DOM_CLIENT_RECT_LIST_GET_PRIVATE(object); WebKit::DOMObjectCache::forget(priv->coreObject.get()); priv->~WebKitDOMClientRectListPrivate(); G_OBJECT_CLASS(webkit_dom_client_rect_list_parent_class)->finalize(object); } static void webkit_dom_client_rect_list_get_property(GObject* object, guint propertyId, GValue* value, GParamSpec* pspec) { WebKitDOMClientRectList* self = WEBKIT_DOM_CLIENT_RECT_LIST(object); switch (propertyId) { case PROP_LENGTH: g_value_set_ulong(value, webkit_dom_client_rect_list_get_length(self)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec); break; } } static void webkit_dom_client_rect_list_constructed(GObject* object) { G_OBJECT_CLASS(webkit_dom_client_rect_list_parent_class)->constructed(object); WebKitDOMClientRectListPrivate* priv = WEBKIT_DOM_CLIENT_RECT_LIST_GET_PRIVATE(object); priv->coreObject = static_cast<WebCore::DOMRectList*>(WEBKIT_DOM_OBJECT(object)->coreObject); WebKit::DOMObjectCache::put(priv->coreObject.get(), object); } static void webkit_dom_client_rect_list_class_init(WebKitDOMClientRectListClass* requestClass) { GObjectClass* gobjectClass = G_OBJECT_CLASS(requestClass); g_type_class_add_private(gobjectClass, sizeof(WebKitDOMClientRectListPrivate)); gobjectClass->constructed = webkit_dom_client_rect_list_constructed; gobjectClass->finalize = webkit_dom_client_rect_list_finalize; gobjectClass->get_property = webkit_dom_client_rect_list_get_property; g_object_class_install_property( gobjectClass, PROP_LENGTH, g_param_spec_ulong( "length", "ClientRectList:length", "read-only gulong ClientRectList:length", 0, G_MAXULONG, 0, WEBKIT_PARAM_READABLE)); } static void webkit_dom_client_rect_list_init(WebKitDOMClientRectList* request) { WebKitDOMClientRectListPrivate* priv = WEBKIT_DOM_CLIENT_RECT_LIST_GET_PRIVATE(request); new (priv) WebKitDOMClientRectListPrivate(); } WebKitDOMClientRect* webkit_dom_client_rect_list_item(WebKitDOMClientRectList* self, gulong index) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_CLIENT_RECT_LIST(self), nullptr); auto* list = WebKit::core(self); RefPtr<WebCore::DOMRect> gobjectResult = WTF::getPtr(list->item(index)); return WebKit::kit(gobjectResult.get()); } gulong webkit_dom_client_rect_list_get_length(WebKitDOMClientRectList* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_CLIENT_RECT_LIST(self), 0); return WebKit::core(self)->length(); }
35.047297
151
0.774629
[ "object" ]
3373bf81c1bd9bd5876146d9050e204363c2581c
4,161
cpp
C++
src/ngraph/runtime/cpu/builder/pad.cpp
huningxin/ngraph
28622bdea4b4ad84405b8484b31673ae7d31cf76
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/cpu/builder/pad.cpp
huningxin/ngraph
28622bdea4b4ad84405b8484b31673ae7d31cf76
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/cpu/builder/pad.cpp
huningxin/ngraph
28622bdea4b4ad84405b8484b31673ae7d31cf76
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <cstring> #include "ngraph/op/pad.hpp" #include "ngraph/runtime/cpu/cpu_builder.hpp" #include "ngraph/runtime/cpu/kernel/pad.hpp" #include "ngraph/shape.hpp" using namespace std; using namespace ngraph; namespace ngraph { namespace runtime { namespace cpu { template <> void Builder::BUILDER_DECL(ngraph::op::Pad) { auto& functors = external_function->get_functors(); auto& arg_tensor = external_function->get_tensor_data(args[0].get_name()); auto& padding_value = external_function->get_tensor_data(args[1].get_name()); auto& out_tensor = external_function->get_tensor_data(out[0].get_name()); auto pad = static_cast<const ngraph::op::Pad*>(node); auto arg_shape = args[0].get_shape(); auto out_shape = out[0].get_shape(); auto padding_below = pad->get_padding_below(); auto padding_above = pad->get_padding_above(); if (pad->get_padding_interior() == Shape(arg_shape.size())) { std::function<decltype(runtime::cpu::kernel::pad<float, 1>)> kernel; SELECT_KERNEL_BY_RANK(kernel, args[0].get_element_type(), arg_shape.size(), runtime::cpu::kernel::pad); auto functor = [&, kernel, arg_shape, out_shape, padding_below, padding_above]( CPURuntimeContext* ctx, CPUExecutionContext* ectx) { kernel(arg_tensor, out_tensor, padding_value, arg_shape, out_shape, padding_below, padding_above, ectx->arena); }; functors.emplace_back(functor); } else { auto padding_interior = pad->get_padding_interior(); std::function<decltype(runtime::cpu::kernel::pad<float>)> kernel; SELECT_KERNEL(kernel, args[0].get_element_type(), runtime::cpu::kernel::pad); auto functor = [&, kernel, arg_shape, out_shape, padding_below, padding_above, padding_interior](CPURuntimeContext* ctx, CPUExecutionContext* ectx) { kernel(arg_tensor, padding_value, out_tensor, arg_shape, out_shape, padding_below, padding_above, padding_interior, ectx->arena); }; functors.emplace_back(functor); } } REGISTER_OP_BUILDER(Pad); } } }
39.628571
99
0.459505
[ "shape" ]
337488fb8c2c46068da42e7e5cea3224fcb10d13
22,425
cpp
C++
src/ConEmu/BaseDragDrops.cpp
Replica-/ConEmu
9ec323e3ebafd87fe56b5ccedff2b165bcd7f2a6
[ "BSD-3-Clause" ]
null
null
null
src/ConEmu/BaseDragDrops.cpp
Replica-/ConEmu
9ec323e3ebafd87fe56b5ccedff2b165bcd7f2a6
[ "BSD-3-Clause" ]
null
null
null
src/ConEmu/BaseDragDrops.cpp
Replica-/ConEmu
9ec323e3ebafd87fe56b5ccedff2b165bcd7f2a6
[ "BSD-3-Clause" ]
null
null
null
 #define HIDE_USE_EXCEPTION_INFO #define SHOWDEBUGSTR #include "header.h" #pragma warning(disable: 4091) #include <shlobj.h> #pragma warning(default: 4091) #if defined(__GNUC__) && !defined(__MINGW64_VERSION_MAJOR) #include "ShObjIdl_Part.h" #endif // __GNUC__ #include "BaseDragDrops.h" #include "ConEmu.h" #include "DragDrop.h" #include "resource.h" #define DEBUGSTRDATA(s) DEBUGSTR(s) extern HINSTANCE g_hInstance; /* [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface\{000214E4-0000-0000-C000-000000000046}] @="IContextMenu" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface\{000214F4-0000-0000-C000-000000000046}] @="IContextMenu2" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface\{0811AEBE-0B87-4C54-9E72-548CF649016B}] @="IContextMenuSite" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface\{15F936F5-A3FA-11D2-AEC3-00C04F79D1EB}] @="IContextNotify" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface\{15F936F6-A3FA-11D2-AEC3-00C04F79D1EB}] @="IContextRegisterNotify" */ //CBaseDropTarget::CBaseDropTarget(/*HWND hwnd*/) //{ // //m_hWnd = hwnd; // m_lRefCount = 1; //} CBaseDropTarget::CBaseDropTarget() { m_lRefCount = 1; } CBaseDropTarget::~CBaseDropTarget() { } HRESULT STDMETHODCALLTYPE CBaseDropTarget::DragEnter(IDataObject * pDataObject, DWORD grfKeyState, POINTL pt, DWORD * pdwEffect) { return 0; } HRESULT STDMETHODCALLTYPE CBaseDropTarget::DragOver(DWORD grfKeyState, POINTL pt, DWORD * pdwEffect) { return 0; } HRESULT STDMETHODCALLTYPE CBaseDropTarget::Drop(IDataObject * pDataObject, DWORD grfKeyState, POINTL pt, DWORD * pdwEffect) { //gpConEmu->SetDragCursor(NULL); return 0; } HRESULT STDMETHODCALLTYPE CBaseDropTarget::DragLeave(void) { return 0; } HRESULT __stdcall CBaseDropTarget::QueryInterface(REFIID iid, void ** ppvObject) { if (iid == IID_IDropTarget || iid == IID_IUnknown) { AddRef(); *ppvObject = this; return S_OK; } else { *ppvObject = 0; return E_NOINTERFACE; } } ULONG __stdcall CBaseDropTarget::AddRef(void) { return InterlockedIncrement(&m_lRefCount); } ULONG __stdcall CBaseDropTarget::Release(void) { LONG count = InterlockedDecrement(&m_lRefCount); if (count == 0) { delete this; return 0; } else { return count; } } //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// // // Constructor // CDropSource::CDropSource(CDragDropData* pCallback) { m_lRefCount = 1; mh_CurCopy = NULL; mh_CurMove = NULL; mh_CurLink = NULL; mp_Callback = pCallback; } // // Destructor // CDropSource::~CDropSource() { } // // IUnknown::AddRef // ULONG __stdcall CDropSource::AddRef(void) { // increment object reference count return InterlockedIncrement(&m_lRefCount); } // // IUnknown::Release // ULONG __stdcall CDropSource::Release(void) { // decrement object reference count LONG count = InterlockedDecrement(&m_lRefCount); if (count == 0) { delete this; return 0; } else { return count; } } // // IUnknown::QueryInterface // HRESULT __stdcall CDropSource::QueryInterface(REFIID iid, void **ppvObject) { // check to see what interface has been requested if (iid == IID_IDropSource || iid == IID_IUnknown) { AddRef(); *ppvObject = this; return S_OK; } else { *ppvObject = 0; return E_NOINTERFACE; } } // // CDropSource::QueryContinueDrag // // Called by OLE whenever Escape/Control/Shift/Mouse buttons have changed // HRESULT __stdcall CDropSource::QueryContinueDrag(BOOL fEscapePressed, DWORD grfKeyState) { // if the <Escape> key has been pressed since the last call, cancel the drop if (fEscapePressed == TRUE) { if (mp_Callback) mp_Callback->DragFeedBack(DROPEFFECT_STOP_INTERNAL); return DRAGDROP_S_CANCEL; } DWORD nDragKey = ((gpConEmu->mouse.state & DRAG_L_STARTED) == DRAG_L_STARTED) ? MK_LBUTTON : MK_RBUTTON; DWORD nOtherKey = ((nDragKey & MK_LBUTTON) == MK_LBUTTON) ? (MK_RBUTTON|MK_MBUTTON) : (MK_LBUTTON|MK_MBUTTON); // if the <LeftMouse> button has been released, then do the drop! if ((grfKeyState & nDragKey) == 0) { if (mp_Callback) mp_Callback->DragFeedBack((DWORD)-1); return DRAGDROP_S_DROP; } // Если юзер нажимает другую мышиную кнопку if ((grfKeyState & nOtherKey) == nOtherKey) { if (mp_Callback) mp_Callback->DragFeedBack((DWORD)-1); return DRAGDROP_S_CANCEL; } // continue with the drag-drop return S_OK; } // // CDropSource::GiveFeedback // // Return either S_OK, or DRAGDROP_S_USEDEFAULTCURSORS to instruct OLE to use the // default mouse cursor images // HRESULT __stdcall CDropSource::GiveFeedback(DWORD dwEffect) { HRESULT hr = DRAGDROP_S_USEDEFAULTCURSORS; HCURSOR hCur = NULL; DEBUGTEST(HRESULT hrTest = S_FALSE); //-- пока CFSTR_DROPDESCRIPTION не заводится... //if ((gOSVer.dwMajorVersion < 6) || !mp_Callback) { if (dwEffect != DROPEFFECT_NONE) { if (dwEffect & DROPEFFECT_COPY) { if (!mh_CurCopy) mh_CurCopy = LoadCursor(g_hInstance, MAKEINTRESOURCE(IDC_COPY)); hCur = mh_CurCopy; } else if (dwEffect & DROPEFFECT_MOVE) { if (!mh_CurMove) mh_CurMove = LoadCursor(g_hInstance, MAKEINTRESOURCE(IDC_MOVE)); hCur = mh_CurMove; } else if (dwEffect & DROPEFFECT_LINK) { if (!mh_CurLink) mh_CurLink = LoadCursor(g_hInstance, MAKEINTRESOURCE(IDC_LINK)); hCur = mh_CurLink; } } else { hCur = LoadCursor(NULL, IDC_NO); } } gpConEmu->SetDragCursor(hCur); //if (hCur) { //SetCursor(hCur); hr = S_OK; //} if (mp_Callback) mp_Callback->DragFeedBack(dwEffect); return hr; } // // Helper routine to create an IDropSource object // HRESULT CreateDropSource(IDropSource **ppDropSource, CDragDropData* pCallback) { if (ppDropSource == 0) return E_INVALIDARG; *ppDropSource = new CDropSource(pCallback); return (*ppDropSource) ? S_OK : E_OUTOFMEMORY; } //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// // // Constructor // CDataObject::CDataObject(FORMATETC *fmtetc, STGMEDIUM *stgmed, int count) { m_lRefCount = 1; m_Data.alloc(32+std::max(count, 32)); for (int i = 0; i < count; i++) { _ASSERTE(fmtetc && stgmed); m_Data[i].fUsed = TRUE; m_Data[i].fRelease = TRUE; m_Data[i].FormatEtc = fmtetc[i]; m_Data[i].StgMedium = stgmed[i]; } } // // Destructor // CDataObject::~CDataObject() { // Освобождать данные в m_pStgMedium.hGlobal for (int i = 0; i < m_Data.size(); i++) { if (m_Data[i].fUsed && m_Data[i].fRelease) { ReleaseStgMedium(&(m_Data[i].StgMedium)); m_Data[i].fRelease = FALSE; } } // cleanup m_Data.clear(); DEBUGSTR(L"CDataObject::~CDataObject()\n"); } // // IUnknown::AddRef // ULONG __stdcall CDataObject::AddRef(void) { // increment object reference count return InterlockedIncrement(&m_lRefCount); } // // IUnknown::Release // ULONG __stdcall CDataObject::Release(void) { // decrement object reference count LONG count = InterlockedDecrement(&m_lRefCount); if (count == 0) { delete this; return 0; } else { return count; } } // // IUnknown::QueryInterface // HRESULT __stdcall CDataObject::QueryInterface(REFIID iid, void **ppvObject) { // check to see what interface has been requested if (iid == IID_IDataObject || iid == IID_IUnknown) { AddRef(); *ppvObject = this; return S_OK; } else { *ppvObject = 0; return E_NOINTERFACE; } } HGLOBAL DupMem(HGLOBAL hMem) { // lock the source memory object SIZE_T len = GlobalSize(hMem); PVOID source = GlobalLock(hMem); if (!source) return NULL; // create a fixed "global" block - i.e. just // a regular lump of our process heap PVOID dest = GlobalAlloc(GMEM_FIXED, len); if (dest) memcpy(dest, source, len); GlobalUnlock(hMem); return dest; } int CDataObject::LookupFormatEtc(FORMATETC *pFormatEtc) { for (int i = 0; i < m_Data.size(); i++) { if (m_Data[i].fUsed && (pFormatEtc->tymed & m_Data[i].FormatEtc.tymed) && (pFormatEtc->cfFormat == m_Data[i].FormatEtc.cfFormat) && (pFormatEtc->dwAspect == m_Data[i].FormatEtc.dwAspect)) { return i; } } return -1; } LPCWSTR CDataObject::GetFormatName(CLIPFORMAT cfFormat, bool bRaw) { static wchar_t szName[128]; szName[0] = bRaw ? 0 : L'\''; if (GetClipboardFormatName(cfFormat, szName+(bRaw?0:1), 80) >= 1) { if (!bRaw) { wcscat_c(szName, L"',"); } } else { szName[0] = 0; } if (!bRaw || (szName[0] == 0)) { int nLen = lstrlen(szName); swprintf_c(szName+nLen, countof(szName)-nLen/*#SECURELEN*/, L"x%04X(%u)", cfFormat, cfFormat); } return szName; } // // IDataObject::GetData // HRESULT __stdcall CDataObject::GetData(FORMATETC *pFormatEtc, STGMEDIUM *pMedium) { int idx; #ifdef _DEBUG wchar_t szDbg[200]; #endif // // try to match the requested FORMATETC with one of our supported formats // if ((idx = LookupFormatEtc(pFormatEtc)) == -1) { #ifdef _DEBUG swprintf_c(szDbg, L"!!! CDataObject::LookupFormatEtc(%s) failed\n", GetFormatName(pFormatEtc->cfFormat)); DEBUGSTRDATA(szDbg); #endif return DV_E_FORMATETC; } #ifdef _DEBUG swprintf_c(szDbg, L"CDataObject::GetData {cfFormat=%s, lindex=%i, tymed=x%02X(%u)})", GetFormatName(pFormatEtc->cfFormat), pFormatEtc->lindex, pFormatEtc->tymed, pFormatEtc->tymed); LPCWSTR pszName = GetFormatName(pFormatEtc->cfFormat, true); DWORD nData = (DWORD)-1; if (lstrcmp(pszName, L"IsShowingLayered")==0 || lstrcmp(pszName, L"IsShowingText")==0 || lstrcmp(pszName, L"DragContext")==0 || lstrcmp(pszName, L"UsingDefaultDragImage")==0 || lstrcmp(pszName, L"DragSourceHelperFlags")==0 || lstrcmp(pszName, L"DragWindow")==0 || lstrcmp(pszName, L"DisableDragText")==0 ) { LPDWORD pdw = (LPDWORD)GlobalLock(m_Data[idx].StgMedium.hGlobal); if (pdw) { nData = *pdw; int nLen = lstrlen(szDbg); swprintf_c(szDbg+nLen, countof(szDbg)-nLen/*#SECURELEN*/, L", Data=x%02X(%u)", nData, nData); } GlobalUnlock(m_Data[idx].StgMedium.hGlobal); } wcscat_c(szDbg, L"\n"); DEBUGSTRDATA(szDbg); #endif HRESULT hr = DV_E_FORMATETC; switch (m_Data[idx].FormatEtc.tymed) { case TYMED_HGLOBAL: //ReleaseStgMedium(pMedium); pMedium->hGlobal = DupMem(m_Data[idx].StgMedium.hGlobal); pMedium->pUnkForRelease = NULL; // m_Data[idx].StgMedium.pUnkForRelease; hr = S_OK; break; case TYMED_ISTREAM: _ASSERTE(pMedium->pstm != m_Data[idx].StgMedium.pstm); //ReleaseStgMedium(pMedium); pMedium->pstm = m_Data[idx].StgMedium.pstm; if (m_Data[idx].StgMedium.pstm) m_Data[idx].StgMedium.pstm->AddRef(); pMedium->pUnkForRelease = m_Data[idx].StgMedium.pUnkForRelease; hr = S_OK; break; case TYMED_ISTORAGE: _ASSERTE(pMedium->pstg != m_Data[idx].StgMedium.pstg); //ReleaseStgMedium(pMedium); pMedium->pstg = m_Data[idx].StgMedium.pstg; if (m_Data[idx].StgMedium.pstg) m_Data[idx].StgMedium.pstg->AddRef(); pMedium->pUnkForRelease = m_Data[idx].StgMedium.pUnkForRelease; hr = S_OK; break; default: AssertMsg(L"Unsupported value in m_Data[idx].FormatEtc.tymed"); } if (hr == S_OK) { // // found a match! transfer the data into the supplied storage-medium // pMedium->tymed = m_Data[idx].FormatEtc.tymed; //Assert(pMedium->pUnkForRelease==NULL && m_Data[idx].StgMedium.pUnkForRelease==NULL); //pMedium->pUnkForRelease = NULL; } else { #ifdef _DEBUG swprintf_c(szDbg, L"!!! CDataObject::GetData(tymed=%u) failed", m_Data[idx].FormatEtc.tymed); DEBUGSTRDATA(szDbg); //_ASSERTE(FALSE && "Unsupported tymed!"); #endif } return hr; } // // IDataObject::GetDataHere // HRESULT __stdcall CDataObject::GetDataHere(FORMATETC *pFormatEtc, STGMEDIUM *pMedium) { #ifdef _DEBUG wchar_t szDbg[200]; swprintf_c(szDbg, L"CDataObject::GetDataHere({cfFormat=x%04X(%u), lindex=%i, tymed=x%02X(%u)}, {tymed=x%02X})\n", pFormatEtc->cfFormat, pFormatEtc->cfFormat, pFormatEtc->lindex, pFormatEtc->tymed, pFormatEtc->tymed, pMedium->tymed); DEBUGSTRDATA(szDbg); #endif _ASSERTE(FALSE && "CDataObject::GetDataHere not impemented!"); // GetDataHere is only required for IStream and IStorage mediums // It is an error to call GetDataHere for things like HGLOBAL and other clipboard formats // // OleFlushClipboard // return DATA_E_FORMATETC; } // // IDataObject::QueryGetData // // Called to see if the IDataObject supports the specified format of data // HRESULT __stdcall CDataObject::QueryGetData(FORMATETC *pFormatEtc) { #ifdef _DEBUG wchar_t szDbg[200]; swprintf_c(szDbg, L"CDataObject::LookupFormatEtc({cfFormat=x%04X(%u), lindex=%i, tymed=x%02X(%u)})\n", pFormatEtc->cfFormat, pFormatEtc->cfFormat, pFormatEtc->lindex, pFormatEtc->tymed, pFormatEtc->tymed); DEBUGSTRDATA(szDbg); #endif return (LookupFormatEtc(pFormatEtc) == -1) ? DV_E_FORMATETC : S_OK; } // // IDataObject::GetCanonicalFormatEtc // HRESULT __stdcall CDataObject::GetCanonicalFormatEtc(FORMATETC *pFormatEct, FORMATETC *pFormatEtcOut) { // Apparently we have to set this field to NULL even though we don't do anything else pFormatEtcOut->ptd = NULL; return E_NOTIMPL; } HRESULT CDataObject::SetDataInt(LPCWSTR sFmtName, const void* hData, DWORD nDataSize /*= 0*/) { HRESULT hr; FORMATETC fmtetc[] = { { (CLIPFORMAT)RegisterClipboardFormat(sFmtName), 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }, }; STGMEDIUM stgmed[] = { { TYMED_HGLOBAL }, }; if (nDataSize == 0) { stgmed[0].hGlobal = (HGLOBAL)hData; } else { stgmed[0].hGlobal = GlobalAlloc(GPTR, nDataSize); memmove(stgmed[0].hGlobal, hData, nDataSize); } hr = SetData(fmtetc, stgmed, TRUE); return hr; } // // IDataObject::SetData // HRESULT __stdcall CDataObject::SetData(FORMATETC *pFormatEtc, STGMEDIUM *pMedium, BOOL fRelease) { _ASSERTE(pMedium && pMedium->pUnkForRelease==NULL); #ifdef _DEBUG LPCWSTR pszName = GetFormatName(pFormatEtc->cfFormat, true); DWORD nData = (DWORD)-1; if (lstrcmp(pszName, L"IsShowingLayered")==0 || lstrcmp(pszName, L"IsShowingText")==0 || lstrcmp(pszName, L"DragContext")==0 || lstrcmp(pszName, L"UsingDefaultDragImage")==0 || lstrcmp(pszName, L"DragSourceHelperFlags")==0 || lstrcmp(pszName, L"DragWindow")==0 || lstrcmp(pszName, L"DisableDragText")==0 ) { LPDWORD pdw = (LPDWORD)GlobalLock(pMedium->hGlobal); if (pdw) { nData = *pdw; } GlobalUnlock(pMedium->hGlobal); } wchar_t szDbg[255]; swprintf_c(szDbg, L"CDataObject::SetData {cfFormat=%s, lindex=%i, tymed=x%02X(%u)}, {tymed=x%02X}", GetFormatName(pFormatEtc->cfFormat), pFormatEtc->lindex, pFormatEtc->tymed, pFormatEtc->tymed, pMedium->tymed); if (nData != (DWORD)-1) { int nLen = lstrlen(szDbg); swprintf_c(szDbg+nLen, countof(szDbg)-nLen/*#SECURELEN*/, L", Data=x%02X(%u)", nData, nData); } wcscat_c(szDbg, L"\n"); DEBUGSTRDATA(szDbg); #endif DEBUGTEST(bool bNew = false); LONG nIndex = LookupFormatEtc(pFormatEtc); if (nIndex >= 0) { if ((pMedium != &(m_Data[nIndex].StgMedium)) && (pMedium->hGlobal != &(m_Data[nIndex].StgMedium))) { if (m_Data[nIndex].fRelease) { ReleaseStgMedium(&m_Data[nIndex].StgMedium); } else { ZeroStruct(m_Data[nIndex].StgMedium); } } else { Assert((pMedium != &(m_Data[nIndex].StgMedium)) && (pMedium->hGlobal != &(m_Data[nIndex].StgMedium))); } } else // if (nIndex < 0) { DEBUGTEST(bNew = true); _ASSERTE(nIndex < 0); DragData newItem = {}; newItem.FormatEtc = *pFormatEtc; nIndex = m_Data.push_back(newItem); } m_Data[nIndex].fUsed = TRUE; m_Data[nIndex].fRelease = fRelease; m_Data[nIndex].StgMedium = *pMedium; return S_OK; } // // IDataObject::EnumFormatEtc // HRESULT __stdcall CDataObject::EnumFormatEtc(DWORD dwDirection, IEnumFORMATETC **ppEnumFormatEtc) { HRESULT hr = E_NOTIMPL; if (dwDirection == DATADIR_GET) { // for Win2k+ you can use the SHCreateStdEnumFmtEtc API call, however // to support all Windows platforms we need to implement IEnumFormatEtc ourselves. UINT nNumFormats = m_Data.size(); FORMATETC *pFormats = nNumFormats ? (FORMATETC*)calloc(nNumFormats, sizeof(*pFormats)) : NULL; if (!pFormats) { return E_OUTOFMEMORY; } for (UINT i = 0; i < nNumFormats; i++) { pFormats[i] = m_Data[i].FormatEtc; } hr = CreateEnumFormatEtc(nNumFormats, pFormats, ppEnumFormatEtc); SafeFree(pFormats); } else { // the direction specified is not support for drag+drop } return hr; } // // IDataObject::DAdvise // HRESULT __stdcall CDataObject::DAdvise(FORMATETC *pFormatEtc, DWORD advf, IAdviseSink *pAdvSink, DWORD *pdwConnection) { return OLE_E_ADVISENOTSUPPORTED; } // // IDataObject::DUnadvise // HRESULT __stdcall CDataObject::DUnadvise(DWORD dwConnection) { return OLE_E_ADVISENOTSUPPORTED; } // // IDataObject::EnumDAdvise // HRESULT __stdcall CDataObject::EnumDAdvise(IEnumSTATDATA **ppEnumAdvise) { return OLE_E_ADVISENOTSUPPORTED; } // // Helper function // HRESULT CreateDataObject(FORMATETC *fmtetc, STGMEDIUM *stgmeds, UINT count, CDataObject **ppDataObject) { if (ppDataObject == 0) return E_INVALIDARG; *ppDataObject = new CDataObject(fmtetc, stgmeds, count); return (*ppDataObject) ? S_OK : E_OUTOFMEMORY; } //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// // // "Drop-in" replacement for SHCreateStdEnumFmtEtc. Called by CDataObject::EnumFormatEtc // HRESULT CreateEnumFormatEtc(UINT nNumFormats, FORMATETC *pFormatEtc, IEnumFORMATETC **ppEnumFormatEtc) { if (nNumFormats == 0 || pFormatEtc == 0 || ppEnumFormatEtc == 0) return E_INVALIDARG; *ppEnumFormatEtc = new CEnumFormatEtc(pFormatEtc, nNumFormats); return (*ppEnumFormatEtc) ? S_OK : E_OUTOFMEMORY; } // // Helper function to perform a "deep" copy of a FORMATETC // static void DeepCopyFormatEtc(FORMATETC *dest, FORMATETC *source) { // copy the source FORMATETC into dest *dest = *source; if (source->ptd) { // allocate memory for the DVTARGETDEVICE if necessary dest->ptd = (DVTARGETDEVICE*)CoTaskMemAlloc(sizeof(DVTARGETDEVICE)); // copy the contents of the source DVTARGETDEVICE into dest->ptd if (dest->ptd) *(dest->ptd) = *(source->ptd); } } // // Constructor // CEnumFormatEtc::CEnumFormatEtc(FORMATETC *pFormatEtc, int nNumFormats) { m_lRefCount = 1; m_nIndex = 0; m_nNumFormats = nNumFormats; m_pFormatEtc = nNumFormats ? (FORMATETC*)calloc(nNumFormats, sizeof(FORMATETC)) : NULL; // copy the FORMATETC structures for (int i = 0; i < nNumFormats; i++) { DeepCopyFormatEtc(&m_pFormatEtc[i], &pFormatEtc[i]); } } // // Destructor // CEnumFormatEtc::~CEnumFormatEtc() { if (m_pFormatEtc) { for (ULONG i = 0; i < m_nNumFormats; i++) { if (m_pFormatEtc[i].ptd) CoTaskMemFree(m_pFormatEtc[i].ptd); } SafeFree(m_pFormatEtc); } } // // IUnknown::AddRef // ULONG __stdcall CEnumFormatEtc::AddRef(void) { // increment object reference count return InterlockedIncrement(&m_lRefCount); } // // IUnknown::Release // ULONG __stdcall CEnumFormatEtc::Release(void) { // decrement object reference count LONG count = InterlockedDecrement(&m_lRefCount); if (count == 0) { delete this; return 0; } else { return count; } } // // IUnknown::QueryInterface // HRESULT __stdcall CEnumFormatEtc::QueryInterface(REFIID iid, void **ppvObject) { // check to see what interface has been requested if (iid == IID_IEnumFORMATETC || iid == IID_IUnknown) { AddRef(); *ppvObject = this; return S_OK; } else { *ppvObject = 0; return E_NOINTERFACE; } } // // IEnumFORMATETC::Next // // If the returned FORMATETC structure contains a non-null "ptd" member, then // the caller must free this using CoTaskMemFree (stated in the COM documentation) // HRESULT __stdcall CEnumFormatEtc::Next(ULONG celt, FORMATETC *pFormatEtc, ULONG * pceltFetched) { ULONG copied = 0; // validate arguments if (celt == 0 || pFormatEtc == 0) return E_INVALIDARG; // copy FORMATETC structures into caller's buffer while (m_nIndex < m_nNumFormats && copied < celt) { DeepCopyFormatEtc(&pFormatEtc[copied], &m_pFormatEtc[m_nIndex]); copied++; m_nIndex++; } // store result if (pceltFetched != 0) *pceltFetched = copied; // did we copy all that was requested? return (copied == celt) ? S_OK : S_FALSE; } // // IEnumFORMATETC::Skip // HRESULT __stdcall CEnumFormatEtc::Skip(ULONG celt) { m_nIndex += celt; return (m_nIndex <= m_nNumFormats) ? S_OK : S_FALSE; } // // IEnumFORMATETC::Reset // HRESULT __stdcall CEnumFormatEtc::Reset(void) { m_nIndex = 0; return S_OK; } // // IEnumFORMATETC::Clone // HRESULT __stdcall CEnumFormatEtc::Clone(IEnumFORMATETC ** ppEnumFormatEtc) { HRESULT hResult; // make a duplicate enumerator hResult = CreateEnumFormatEtc(m_nNumFormats, m_pFormatEtc, ppEnumFormatEtc); if (hResult == S_OK) { // manually set the index state ((CEnumFormatEtc *) *ppEnumFormatEtc)->m_nIndex = m_nIndex; } return hResult; } //HANDLE StringToHandle(LPCWSTR szText, int nTextLen) //{ // void *ptr; // // // if text length is -1 then treat as a nul-terminated string // if (nTextLen <= 0) // nTextLen = _tcslen(szText) + 1; // // // allocate and lock a global memory buffer. Make it fixed // // data so we don't have to use GlobalLock // ptr = (void *)GlobalAlloc(GMEM_FIXED, nTextLen+1); // // copy the string into the buffer // if (ptr) // memcpy(ptr, szText, nTextLen); // return ptr; //}
22.313433
128
0.655429
[ "object" ]
338004da736f28117a62cdc91b653b6785bc01c5
4,677
cc
C++
vpc/src/model/DescribeSslVpnServersResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
vpc/src/model/DescribeSslVpnServersResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
vpc/src/model/DescribeSslVpnServersResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
1
2020-11-27T09:13:12.000Z
2020-11-27T09:13:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/vpc/model/DescribeSslVpnServersResult.h> #include <json/json.h> using namespace AlibabaCloud::Vpc; using namespace AlibabaCloud::Vpc::Model; DescribeSslVpnServersResult::DescribeSslVpnServersResult() : ServiceResult() {} DescribeSslVpnServersResult::DescribeSslVpnServersResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeSslVpnServersResult::~DescribeSslVpnServersResult() {} void DescribeSslVpnServersResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allSslVpnServersNode = value["SslVpnServers"]["SslVpnServer"]; for (auto valueSslVpnServersSslVpnServer : allSslVpnServersNode) { SslVpnServer sslVpnServersObject; if(!valueSslVpnServersSslVpnServer["RegionId"].isNull()) sslVpnServersObject.regionId = valueSslVpnServersSslVpnServer["RegionId"].asString(); if(!valueSslVpnServersSslVpnServer["SslVpnServerId"].isNull()) sslVpnServersObject.sslVpnServerId = valueSslVpnServersSslVpnServer["SslVpnServerId"].asString(); if(!valueSslVpnServersSslVpnServer["VpnGatewayId"].isNull()) sslVpnServersObject.vpnGatewayId = valueSslVpnServersSslVpnServer["VpnGatewayId"].asString(); if(!valueSslVpnServersSslVpnServer["Name"].isNull()) sslVpnServersObject.name = valueSslVpnServersSslVpnServer["Name"].asString(); if(!valueSslVpnServersSslVpnServer["LocalSubnet"].isNull()) sslVpnServersObject.localSubnet = valueSslVpnServersSslVpnServer["LocalSubnet"].asString(); if(!valueSslVpnServersSslVpnServer["ClientIpPool"].isNull()) sslVpnServersObject.clientIpPool = valueSslVpnServersSslVpnServer["ClientIpPool"].asString(); if(!valueSslVpnServersSslVpnServer["CreateTime"].isNull()) sslVpnServersObject.createTime = std::stol(valueSslVpnServersSslVpnServer["CreateTime"].asString()); if(!valueSslVpnServersSslVpnServer["Cipher"].isNull()) sslVpnServersObject.cipher = valueSslVpnServersSslVpnServer["Cipher"].asString(); if(!valueSslVpnServersSslVpnServer["Proto"].isNull()) sslVpnServersObject.proto = valueSslVpnServersSslVpnServer["Proto"].asString(); if(!valueSslVpnServersSslVpnServer["Port"].isNull()) sslVpnServersObject.port = std::stoi(valueSslVpnServersSslVpnServer["Port"].asString()); if(!valueSslVpnServersSslVpnServer["Compress"].isNull()) sslVpnServersObject.compress = valueSslVpnServersSslVpnServer["Compress"].asString() == "true"; if(!valueSslVpnServersSslVpnServer["Connections"].isNull()) sslVpnServersObject.connections = std::stoi(valueSslVpnServersSslVpnServer["Connections"].asString()); if(!valueSslVpnServersSslVpnServer["MaxConnections"].isNull()) sslVpnServersObject.maxConnections = std::stoi(valueSslVpnServersSslVpnServer["MaxConnections"].asString()); if(!valueSslVpnServersSslVpnServer["InternetIp"].isNull()) sslVpnServersObject.internetIp = valueSslVpnServersSslVpnServer["InternetIp"].asString(); if(!valueSslVpnServersSslVpnServer["EnableMultiFactorAuth"].isNull()) sslVpnServersObject.enableMultiFactorAuth = valueSslVpnServersSslVpnServer["EnableMultiFactorAuth"].asString() == "true"; if(!valueSslVpnServersSslVpnServer["IDaaSInstanceId"].isNull()) sslVpnServersObject.iDaaSInstanceId = valueSslVpnServersSslVpnServer["IDaaSInstanceId"].asString(); sslVpnServers_.push_back(sslVpnServersObject); } if(!value["TotalCount"].isNull()) totalCount_ = std::stoi(value["TotalCount"].asString()); if(!value["PageNumber"].isNull()) pageNumber_ = std::stoi(value["PageNumber"].asString()); if(!value["PageSize"].isNull()) pageSize_ = std::stoi(value["PageSize"].asString()); } int DescribeSslVpnServersResult::getTotalCount()const { return totalCount_; } int DescribeSslVpnServersResult::getPageSize()const { return pageSize_; } std::vector<DescribeSslVpnServersResult::SslVpnServer> DescribeSslVpnServersResult::getSslVpnServers()const { return sslVpnServers_; } int DescribeSslVpnServersResult::getPageNumber()const { return pageNumber_; }
42.908257
124
0.788753
[ "vector", "model" ]
3380fa641791877ecf44d1cc919be22a360f15be
800
cpp
C++
test/verify/test_add_broadcast5.cpp
sjw36/AMDMIGraphX
c310bc5cf9b3f8ea44823a386a1b8bd72014bf09
[ "MIT" ]
null
null
null
test/verify/test_add_broadcast5.cpp
sjw36/AMDMIGraphX
c310bc5cf9b3f8ea44823a386a1b8bd72014bf09
[ "MIT" ]
1
2022-02-10T07:11:54.000Z
2022-02-10T07:11:54.000Z
test/verify/test_add_broadcast5.cpp
sjw36/AMDMIGraphX
c310bc5cf9b3f8ea44823a386a1b8bd72014bf09
[ "MIT" ]
null
null
null
#include "verify_program.hpp" #include <migraphx/program.hpp> #include <migraphx/generate.hpp> #include <migraphx/make_op.hpp> #include <migraphx/instruction.hpp> struct test_add_broadcast5 : verify_program<test_add_broadcast5> { migraphx::program create_program() const { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto x = mm->add_parameter("x", {migraphx::shape::float_type, {2, 4, 8}}); auto y = mm->add_parameter("y", {migraphx::shape::float_type, {4}}); auto by = mm->add_instruction( migraphx::make_op("broadcast", {{"axis", 1}, {"dims", x->get_shape().lens()}}), y); mm->add_instruction(migraphx::make_op("add"), x, by); return p; } };
33.333333
95
0.63125
[ "shape" ]
3383c1f5502df6dadd634ccbeb63944f506c38fc
5,235
cpp
C++
TAO/tests/Objref_Sequence_Test/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tests/Objref_Sequence_Test/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tests/Objref_Sequence_Test/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
//$Id: server.cpp 91825 2010-09-17 09:10:22Z johnnyw $ #include "TestS.h" #include "ace/Get_Opt.h" #include "ace/OS_NS_stdio.h" /// Implement the Server Interface class ServerServant : public POA_Server { public: /// Ctor ServerServant (PortableServer::POA_ptr poa, CORBA::ORB_ptr orb); void CreateExtra (CORBA::ULong length, ServerSequence_out seq); void DeleteExtra (const ServerSequence &seq); //FUZZ: disable check_for_lack_ACE_OS void shutdown (void); //FUZZ: enable check_for_lack_ACE_OS private: /// Our root POA PortableServer::POA_var root_poa_; /// The ORB on which we are running CORBA::ORB_var orb_; }; /// Ctor ServerServant::ServerServant (PortableServer::POA_ptr poa, CORBA::ORB_ptr orb) :root_poa_ (PortableServer::POA::_duplicate (poa)), orb_ (CORBA::ORB::_duplicate (orb)) { } /// Servant implementations void ServerServant::CreateExtra (CORBA::ULong len, ServerSequence_out seq) { ACE_DEBUG ((LM_DEBUG, "(%P|%t) Create extra called with " " length [%d]\n", len)); ACE_NEW_THROW_EX (seq, ServerSequence (len), CORBA::NO_MEMORY ()); seq->length (len); for (CORBA::ULong cnt = 0 ; cnt < len ; cnt ++) { ServerServant *servant = 0; ACE_NEW_THROW_EX (servant, ServerServant (this->root_poa_.in (), this->orb_.in ()), CORBA::NO_MEMORY ()); // PortableServer::ServantBase_var owner_transfer(servant); (*seq) [cnt] = servant->_this (); } ACE_DEBUG ((LM_DEBUG, "(%P|%t) Returned from CreateExtra ()\n")); } void ServerServant::DeleteExtra (const ServerSequence &seq) { ACE_DEBUG ((LM_DEBUG, "(%P|%t) Deleting sequences\n")); PortableServer::ObjectId_var oid; PortableServer::ServantBase *servant = 0; for (CORBA::ULong cnt = 0; cnt < seq.length (); cnt++) { oid = this->root_poa_->reference_to_id (seq [cnt]); servant = this->root_poa_->reference_to_servant (seq [cnt]); this->root_poa_->deactivate_object (oid.in ()); servant->_remove_ref (); servant->_remove_ref (); } ACE_DEBUG ((LM_DEBUG, "(%P|%t) Returned after deleting sequences\n")); } void ServerServant::shutdown (void) { this->orb_->shutdown (0); } /******************************************************/ const ACE_TCHAR *ior_output_file = ACE_TEXT("test.ior"); int parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("o:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'o': ior_output_file = get_opts.opt_arg (); break; case '?': default: ACE_ERROR_RETURN ((LM_ERROR, "usage: %s " "-o <iorfile>" "\n", argv [0]), -1); } // Indicates successful parsing of the command line return 0; } int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { // Initialize the broker CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); if (parse_args (argc, argv) == -1) return -1; CORBA::Object_var vRootPOABase = orb->resolve_initial_references ("RootPOA"); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (vRootPOABase.in ()); if (CORBA::is_nil (root_poa.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Panic: nil RootPOA\n"), 1); PortableServer::POAManager_ptr pRootPOAManager = root_poa->the_POAManager (); // Instantiate the server ServerServant *servant = 0; ACE_NEW_RETURN (servant, ServerServant (root_poa.in (), orb.in ()), 1); PortableServer::ServantBase_var owner_transfer(servant); PortableServer::ObjectId_var id = root_poa->activate_object (servant); CORBA::Object_var object = root_poa->id_to_reference (id.in ()); Server_var server = Server::_narrow (object.in ()); // Announce the server CORBA::String_var obj_ref = orb->object_to_string (server.in ()); // Output the IOR to the <ior_output_file> FILE *output_file= ACE_OS::fopen (ior_output_file, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", ior_output_file), 1); ACE_OS::fprintf (output_file, "%s", obj_ref.in ()); ACE_OS::fclose (output_file); pRootPOAManager->activate (); orb->run (); ACE_DEBUG ((LM_DEBUG, "(%P|%t) server - event loop finished\n")); root_poa->destroy (1, 1); orb->destroy (); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); return 1; } return 0; }
24.348837
73
0.548615
[ "object" ]
33840cc9b865a369b89528cfe293bea773bd4707
85,411
cpp
C++
src/runtime/threads/threadmanager.cpp
akemp/hpx
1ddf7282e322c30d82f2be044071aed14807ebe1
[ "BSL-1.0" ]
null
null
null
src/runtime/threads/threadmanager.cpp
akemp/hpx
1ddf7282e322c30d82f2be044071aed14807ebe1
[ "BSL-1.0" ]
null
null
null
src/runtime/threads/threadmanager.cpp
akemp/hpx
1ddf7282e322c30d82f2be044071aed14807ebe1
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2015 Patricia Grubel // Copyright (c) 2007-2014 Hartmut Kaiser // Copyright (c) 2011 Bryce Lelbach, Katelyn Kufahl // Copyright (c) 2008-2009 Chirag Dekate, Anshul Tandon // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <hpx/hpx_fwd.hpp> #include <hpx/exception.hpp> #include <hpx/runtime/applier/applier.hpp> #include <hpx/runtime/threads/topology.hpp> #include <hpx/runtime/threads/threadmanager_impl.hpp> #include <hpx/runtime/threads/thread_data.hpp> #include <hpx/runtime/threads/thread_helpers.hpp> #include <hpx/runtime/threads/detail/scheduling_loop.hpp> #include <hpx/runtime/threads/detail/create_thread.hpp> #include <hpx/runtime/threads/detail/create_work.hpp> #include <hpx/runtime/threads/detail/set_thread_state.hpp> #include <hpx/runtime/threads/executors/generic_thread_pool_executor.hpp> #include <hpx/include/performance_counters.hpp> #include <hpx/performance_counters/counter_creators.hpp> #include <hpx/runtime/actions/continuation.hpp> #include <hpx/util/assert.hpp> #include <hpx/util/scoped_unlock.hpp> #include <hpx/util/logging.hpp> #include <hpx/util/block_profiler.hpp> #include <hpx/util/itt_notify.hpp> #include <hpx/util/hardware/timestamp.hpp> #include <hpx/util/runtime_configuration.hpp> #include <boost/make_shared.hpp> #include <boost/bind.hpp> #include <boost/cstdint.hpp> #include <boost/format.hpp> #include <numeric> #include <sstream> #ifdef HPX_HAVE_THREAD_QUEUE_WAITTIME /////////////////////////////////////////////////////////////////////////////// namespace hpx { namespace threads { namespace policies { /////////////////////////////////////////////////////////////////////////// // We control whether to collect queue wait times using this global bool. // It will be set by any of the related performance counters. Once set it // stays set, thus no race conditions will occur. bool maintain_queue_wait_times = false; }}} #endif /////////////////////////////////////////////////////////////////////////////// namespace hpx { namespace threads { /////////////////////////////////////////////////////////////////////////// namespace strings { char const* const thread_state_names[] = { "unknown", "active", "pending", "suspended", "depleted", "terminated", "staged" }; } char const* get_thread_state_name(thread_state_enum state) { if (state < unknown || state > staged) return "unknown"; return strings::thread_state_names[state]; } /////////////////////////////////////////////////////////////////////////// namespace strings { char const* const thread_priority_names[] = { "default", "low", "normal", "critical", "boost" }; } char const* get_thread_priority_name(thread_priority priority) { if (priority < thread_priority_default || priority > thread_priority_boost) return "unknown"; return strings::thread_priority_names[priority]; } namespace strings { char const* const stack_size_names[] = { "small", "medium", "large", "huge", "stack-less" }; } char const* get_stack_size_name(std::ptrdiff_t size) { if (size == thread_stacksize_unknown) return "unknown"; util::runtime_configuration const& rtcfg = hpx::get_config(); if (rtcfg.get_stack_size(thread_stacksize_small) == size) size = thread_stacksize_small; else if (rtcfg.get_stack_size(thread_stacksize_medium) == size) size = thread_stacksize_medium; else if (rtcfg.get_stack_size(thread_stacksize_large) == size) size = thread_stacksize_large; else if (rtcfg.get_stack_size(thread_stacksize_huge) == size) size = thread_stacksize_huge; else if (rtcfg.get_stack_size(thread_stacksize_nostack) == size) size = thread_stacksize_nostack; if (size < thread_stacksize_small || size > thread_stacksize_nostack) return "custom"; return strings::stack_size_names[size-1]; } /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> threadmanager_impl<SchedulingPolicy, NotificationPolicy>::threadmanager_impl( util::io_service_pool& timer_pool, scheduling_policy_type& scheduler, notification_policy_type& notifier, std::size_t num_threads) : startup_(NULL), num_threads_(num_threads), thread_count_(0), #if defined(HPX_HAVE_THREAD_CUMULATIVE_COUNTS) && defined(HPX_HAVE_THREAD_IDLE_RATES) timestamp_scale_(1.), #endif state_(starting), timer_pool_(timer_pool), thread_logger_("threadmanager_impl::register_thread"), work_logger_("threadmanager_impl::register_work"), set_state_logger_("threadmanager_impl::set_state"), scheduler_(scheduler), notifier_(notifier), used_processing_units_() {} template <typename SchedulingPolicy, typename NotificationPolicy> threadmanager_impl<SchedulingPolicy, NotificationPolicy>::~threadmanager_impl() { //LTM_(debug) << "~threadmanager_impl"; if (!threads_.empty()) { if (state_.load() == running) stop(); threads_.clear(); } delete startup_; } template <typename SchedulingPolicy, typename NotificationPolicy> std::size_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>::init( policies::init_affinity_data const& data) { topology const& topology_ = get_topology(); std::size_t cores_used = scheduler_.init(data, topology_); resize(used_processing_units_, hardware_concurrency()); for (std::size_t i = 0; i != num_threads_; ++i) used_processing_units_ |= scheduler_.get_pu_mask(topology_, i); return cores_used; } /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_thread_count(thread_state_enum state, thread_priority priority) const { mutex_type::scoped_lock lk(mtx_); return scheduler_.get_thread_count(state, priority); } /////////////////////////////////////////////////////////////////////////// // \brief Abort all threads which are in suspended state. This will set // the state of all suspended threads to \a pending while // supplying the wait_abort extended state flag template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: abort_all_suspended_threads() { mutex_type::scoped_lock lk(mtx_); scheduler_.abort_all_suspended_threads(); } /////////////////////////////////////////////////////////////////////////// // \brief Clean up terminated threads. This deletes all threads which // have been terminated but which are still held in the queue // of terminated threads. Some schedulers might not do anything // here. template <typename SchedulingPolicy, typename NotificationPolicy> bool threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: cleanup_terminated(bool delete_all) { mutex_type::scoped_lock lk(mtx_); return scheduler_.cleanup_terminated(delete_all); } /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: register_thread(thread_init_data& data, thread_id_type& id, thread_state_enum initial_state, bool run_now, error_code& ec) { util::block_profiler_wrapper<register_thread_tag> bp(thread_logger_); // verify state if ((thread_count_ == 0 && state_ != running)) { // thread-manager is not currently running HPX_THROWS_IF(ec, invalid_status, "threadmanager_impl::register_thread", "invalid state: thread manager is not running"); return; } detail::create_thread(&scheduler_, data, id, initial_state, run_now, ec); //-V601 } /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>::register_work( thread_init_data& data, thread_state_enum initial_state, error_code& ec) { util::block_profiler_wrapper<register_work_tag> bp(work_logger_); // verify state if ((thread_count_ == 0 && state_ != running)) { // thread-manager is not currently running HPX_THROWS_IF(ec, invalid_status, "threadmanager_impl::register_work", "invalid state: thread manager is not running"); return; } detail::create_work(&scheduler_, data, initial_state, ec); } /////////////////////////////////////////////////////////////////////////// /// The set_state function is part of the thread related API and allows /// to change the state of one of the threads managed by this threadmanager_impl template <typename SchedulingPolicy, typename NotificationPolicy> thread_state threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: set_state(thread_id_type const& id, thread_state_enum new_state, thread_state_ex_enum new_state_ex, thread_priority priority, error_code& ec) { return detail::set_thread_state(id, new_state, //-V107 new_state_ex, priority, get_worker_thread_num(), ec); } /// The get_state function is part of the thread related API. It /// queries the state of one of the threads known to the threadmanager_impl template <typename SchedulingPolicy, typename NotificationPolicy> thread_state threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_state(thread_id_type const& thrd) const { return thrd ? thrd->get_state() : thread_state(terminated); } /// The get_phase function is part of the thread related API. It /// queries the phase of one of the threads known to the threadmanager_impl template <typename SchedulingPolicy, typename NotificationPolicy> std::size_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_phase(thread_id_type const& thrd) const { return thrd ? thrd->get_thread_phase() : std::size_t(~0); } /// The get_priority function is part of the thread related API. It /// queries the priority of one of the threads known to the threadmanager_impl template <typename SchedulingPolicy, typename NotificationPolicy> thread_priority threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_priority(thread_id_type const& thrd) const { return thrd ? thrd->get_priority() : thread_priority_unknown; } template <typename SchedulingPolicy, typename NotificationPolicy> std::ptrdiff_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_stack_size(thread_id_type const& thrd) const { return thrd ? thrd->get_stack_size() : static_cast<std::ptrdiff_t>(thread_stacksize_unknown); } /// The get_description function is part of the thread related API and /// allows to query the description of one of the threads known to the /// threadmanager_impl template <typename SchedulingPolicy, typename NotificationPolicy> char const* threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_description(thread_id_type const& thrd) const { return thrd ? thrd->get_description() : "<unknown>"; } template <typename SchedulingPolicy, typename NotificationPolicy> char const* threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: set_description(thread_id_type const& thrd, char const* desc) { if (HPX_UNLIKELY(!thrd)) { HPX_THROW_EXCEPTION(null_thread_id, "threadmanager_impl::set_description", "NULL thread id encountered"); return NULL; } if (thrd) return thrd->set_description(desc); return NULL; } template <typename SchedulingPolicy, typename NotificationPolicy> char const* threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_lco_description(thread_id_type const& thrd) const { if (HPX_UNLIKELY(!thrd)) { HPX_THROW_EXCEPTION(null_thread_id, "threadmanager_impl::get_lco_description", "NULL thread id encountered"); return NULL; } return thrd ? thrd->get_lco_description() : "<unknown>"; } template <typename SchedulingPolicy, typename NotificationPolicy> char const* threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: set_lco_description(thread_id_type const& thrd, char const* desc) { if (HPX_UNLIKELY(!thrd)) { HPX_THROW_EXCEPTION(null_thread_id, "threadmanager_impl::set_lco_description", "NULL thread id encountered"); return NULL; } if (thrd) return thrd->set_lco_description(desc); return NULL; } /////////////////////////////////////////////////////////////////////////// #ifdef HPX_HAVE_THREAD_FULLBACKTRACE_ON_SUSPENSION template <typename SchedulingPolicy, typename NotificationPolicy> char const* threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_backtrace(thread_id_type const& thrd) const #else template <typename SchedulingPolicy, typename NotificationPolicy> util::backtrace const* threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_backtrace(thread_id_type const& thrd) const #endif { if (HPX_UNLIKELY(!thrd)) { HPX_THROW_EXCEPTION(null_thread_id, "threadmanager_impl::get_backtrace", "NULL thread id encountered"); return NULL; } return thrd ? thrd->get_backtrace() : 0; } #ifdef HPX_HAVE_THREAD_FULLBACKTRACE_ON_SUSPENSION template <typename SchedulingPolicy, typename NotificationPolicy> char const* threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: set_backtrace(thread_id_type const& thrd, char const* bt) #else template <typename SchedulingPolicy, typename NotificationPolicy> util::backtrace const* threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: set_backtrace(thread_id_type const& thrd, util::backtrace const* bt) #endif { if (HPX_UNLIKELY(!thrd)) { HPX_THROW_EXCEPTION(null_thread_id, "threadmanager_impl::set_backtrace", "NULL thread id encountered"); return NULL; } return thrd ? thrd->set_backtrace(bt) : 0; } /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> bool threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_interruption_enabled(thread_id_type const& thrd, error_code& ec) { if (HPX_UNLIKELY(!thrd)) { HPX_THROW_EXCEPTION(null_thread_id, "threadmanager_impl::get_interruption_enabled", "NULL thread id encountered"); return false; } if (&ec != &throws) ec = make_success_code(); return thrd ? thrd->interruption_enabled() : false; } template <typename SchedulingPolicy, typename NotificationPolicy> bool threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: set_interruption_enabled(thread_id_type const& thrd, bool enable, error_code& ec) { if (HPX_UNLIKELY(!thrd)) { HPX_THROW_EXCEPTION(null_thread_id, "threadmanager_impl::set_interruption_enabled", "NULL thread id encountered"); } if (&ec != &throws) ec = make_success_code(); if (thrd) return thrd->set_interruption_enabled(enable); return false; } template <typename SchedulingPolicy, typename NotificationPolicy> bool threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_interruption_requested(thread_id_type const& thrd, error_code& ec) { if (HPX_UNLIKELY(!thrd)) { HPX_THROWS_IF(ec, null_thread_id, "threadmanager_impl::get_interruption_requested", "NULL thread id encountered"); return false; } if (&ec != &throws) ec = make_success_code(); return thrd ? thrd->interruption_requested() : false; } template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: interrupt(thread_id_type const& thrd, bool flag, error_code& ec) { if (HPX_UNLIKELY(!thrd)) { HPX_THROWS_IF(ec, null_thread_id, "threadmanager_impl::interrupt", "NULL thread id encountered"); return; } if (&ec != &throws) ec = make_success_code(); if (thrd) { thrd->interrupt(flag); // notify thread // set thread state to pending, if the thread is currently active, // this will be rescheduled until it calls an interruption point set_thread_state(thrd, pending, wait_abort, thread_priority_normal, ec); } } template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: interruption_point(thread_id_type const& thrd, error_code& ec) { if (HPX_UNLIKELY(!thrd)) { HPX_THROWS_IF(ec, null_thread_id, "threadmanager_impl::interruption_point", "NULL thread id encountered"); return; } if (&ec != &throws) ec = make_success_code(); if (thrd) thrd->interruption_point(); // notify thread } #ifdef HPX_HAVE_THREAD_LOCAL_STORAGE /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> std::size_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_thread_data(thread_id_type const& thrd, error_code& ec) const { if (HPX_UNLIKELY(!thrd)) { HPX_THROWS_IF(ec, null_thread_id, "threadmanager_impl::get_thread_data", "NULL thread id encountered"); return 0; } return thrd ? thrd->get_thread_data() : 0; } template <typename SchedulingPolicy, typename NotificationPolicy> std::size_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: set_thread_data(thread_id_type const& thrd, std::size_t data, error_code& ec) { if (HPX_UNLIKELY(!thrd)) { HPX_THROWS_IF(ec, null_thread_id, "threadmanager_impl::set_thread_data", "NULL thread id encountered"); return 0; } return thrd ? thrd->set_thread_data(data) : 0; } #endif /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: run_thread_exit_callbacks(thread_id_type const& thrd, error_code& ec) { if (HPX_UNLIKELY(!thrd)) { HPX_THROWS_IF(ec, null_thread_id, "threadmanager_impl::run_thread_exit_callbacks", "NULL thread id encountered"); return; } if (&ec != &throws) ec = make_success_code(); if (thrd) thrd->run_thread_exit_callbacks(); } template <typename SchedulingPolicy, typename NotificationPolicy> bool threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: add_thread_exit_callback(thread_id_type const& thrd, util::function_nonser<void()> const& f, error_code& ec) { if (HPX_UNLIKELY(!thrd)) { HPX_THROWS_IF(ec, null_thread_id, "threadmanager_impl::add_thread_exit_callback", "NULL thread id encountered"); return false; } if (&ec != &throws) ec = make_success_code(); return (0 != thrd) ? thrd->add_thread_exit_callback(f) : false; } template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: free_thread_exit_callbacks(thread_id_type const& thrd, error_code& ec) { if (HPX_UNLIKELY(!thrd)) { HPX_THROWS_IF(ec, null_thread_id, "threadmanager_impl::free_thread_exit_callbacks", "NULL thread id encountered"); return; } if (&ec != &throws) ec = make_success_code(); if (0 != thrd) thrd->free_thread_exit_callbacks(); } // Return the executor associated with th egiven thread template <typename SchedulingPolicy, typename NotificationPolicy> executor threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_executor(thread_id_type const& thrd, error_code& ec) const { if (HPX_UNLIKELY(!thrd)) { HPX_THROWS_IF(ec, null_thread_id, "threadmanager_impl::get_executor", "NULL thread id encountered"); return default_executor(); } if (&ec != &throws) ec = make_success_code(); if (0 == thrd) return default_executor(); return executors::generic_thread_pool_executor(thrd->get_scheduler_base()); } /////////////////////////////////////////////////////////////////////////// /// Set a timer to set the state of the given \a thread to the given /// new value after it expired (at the given time) template <typename SchedulingPolicy, typename NotificationPolicy> thread_id_type threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: set_state(util::steady_time_point const& abs_time, thread_id_type const& id, thread_state_enum newstate, thread_state_ex_enum newstate_ex, thread_priority priority, error_code& ec) { return detail::set_thread_state_timed(scheduler_, abs_time, id, newstate, newstate_ex, priority, get_worker_thread_num(), ec); } /////////////////////////////////////////////////////////////////////////// // main function executed by all OS threads managed by this threadmanager_impl template <typename SP, typename NP> struct init_tss_helper { typedef threadmanager_impl<SP, NP> threadmanager_type; init_tss_helper(threadmanager_type& tm, std::size_t thread_num, bool numa_sensitive) : tm_(tm) { tm_.init_tss(thread_num, numa_sensitive); } ~init_tss_helper() { tm_.deinit_tss(); } threadmanager_type& tm_; }; struct manage_active_thread_count { manage_active_thread_count(boost::atomic<long>& counter) : counter_(counter) { ++counter_; } ~manage_active_thread_count() { --counter_; } boost::atomic<long>& counter_; }; template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: tfunc(std::size_t num_thread, topology const& topology_) { // Set the affinity for the current thread. threads::mask_cref_type mask = get_pu_mask(topology_, num_thread); if (LHPX_ENABLED(debug)) topology_.write_to_log(); error_code ec(lightweight); if (any(mask)) { topology_.set_thread_affinity_mask(mask, ec); if (ec) { LTM_(warning) << "run: setting thread affinity on OS thread " //-V128 << num_thread << " failed with: " << ec.get_message(); } } else { LTM_(debug) << "run: setting thread affinity on OS thread " //-V128 << num_thread << " was explicitly disabled."; } // Setting priority of worker threads to a lower priority, this needs to // be done in order to give the parcel pool threads higher priority if (any(mask & get_used_processing_units())) { topology_.reduce_thread_priority(ec); if (ec) { LTM_(warning) << "run: reducing thread priority on OS thread " //-V128 << num_thread << " failed with: " << ec.get_message(); } } // manage the number of this thread in its TSS init_tss_helper<SchedulingPolicy, NotificationPolicy> tss_helper(*this, num_thread, scheduler_.numa_sensitive()); // needs to be done as the first thing, otherwise logging won't work notifier_.on_start_thread(num_thread); // notify runtime system of started thread scheduler_.on_start_thread(num_thread); // wait for all threads to start up before before starting HPX work startup_->wait(); { LTM_(info) << "tfunc(" << num_thread << "): starting OS thread"; //-V128 try { try { tfunc_impl(num_thread); } catch (hpx::exception const& e) { LFATAL_ << "tfunc(" << num_thread //-V128 << "): caught hpx::exception: " << e.what() << ", aborted thread execution"; report_error(num_thread, boost::current_exception()); return; } catch (boost::system::system_error const& e) { LFATAL_ << "tfunc(" << num_thread //-V128 << "): caught boost::system::system_error: " << e.what() << ", aborted thread execution"; report_error(num_thread, boost::current_exception()); return; } catch (std::exception const& e) { // Repackage exceptions to avoid slicing. boost::throw_exception(boost::enable_error_info( hpx::exception(unhandled_exception, e.what()))); } } catch (...) { LFATAL_ << "tfunc(" << num_thread << "): caught unexpected " //-V128 "exception, aborted thread execution"; report_error(num_thread, boost::current_exception()); return; } LTM_(info) << "tfunc(" << num_thread << "): ending OS thread, " //-V128 "executed " << executed_threads_[num_thread] << " HPX threads"; } notifier_.on_stop_thread(num_thread); scheduler_.on_stop_thread(num_thread); } /////////////////////////////////////////////////////////////////////////// // counter creator and discovery functions // queue length(s) counter creation function template <typename SchedulingPolicy, typename NotificationPolicy> naming::gid_type threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: queue_length_counter_creator( performance_counters::counter_info const& info, error_code& ec) { // verify the validity of the counter instance name performance_counters::counter_path_elements paths; performance_counters::get_counter_path_elements(info.fullname_, paths, ec); if (ec) return naming::invalid_gid; // /threadqueue{locality#%d/total}/length // /threadqueue{locality#%d/worker-thread%d}/length if (paths.parentinstance_is_basename_) { HPX_THROWS_IF(ec, bad_parameter, "queue_length_counter_creator", "invalid counter instance parent name: " + paths.parentinstancename_); return naming::invalid_gid; } typedef scheduling_policy_type spt; using util::placeholders::_1; if (paths.instancename_ == "total" && paths.instanceindex_ == -1) { // overall counter using performance_counters::detail::create_raw_counter; util::function_nonser<boost::int64_t()> f = util::bind(&spt::get_queue_length, &scheduler_, -1); return create_raw_counter(info, std::move(f), ec); } else if (paths.instancename_ == "worker-thread" && paths.instanceindex_ >= 0 && std::size_t(paths.instanceindex_) < threads_.size()) { // specific counter using performance_counters::detail::create_raw_counter; util::function_nonser<boost::int64_t()> f = util::bind(&spt::get_queue_length, &scheduler_, static_cast<std::size_t>(paths.instanceindex_)); return create_raw_counter(info, std::move(f), ec); } HPX_THROWS_IF(ec, bad_parameter, "queue_length_counter_creator", "invalid counter instance name: " + paths.instancename_); return naming::invalid_gid; } #ifdef HPX_HAVE_THREAD_QUEUE_WAITTIME // average pending thread wait time template <typename SchedulingPolicy, typename NotificationPolicy> naming::gid_type threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: thread_wait_time_counter_creator( performance_counters::counter_info const& info, error_code& ec) { // verify the validity of the counter instance name performance_counters::counter_path_elements paths; performance_counters::get_counter_path_elements(info.fullname_, paths, ec); if (ec) return naming::invalid_gid; // /threads{locality#%d/total}/wait-time/pending // /threads{locality#%d/worker-thread%d}/wait-time/pending if (paths.parentinstance_is_basename_) { HPX_THROWS_IF(ec, bad_parameter, "thread_wait_time_counter_creator", "invalid counter instance parent name: " + paths.parentinstancename_); return naming::invalid_gid; } typedef scheduling_policy_type spt; using util::placeholders::_1; if (paths.instancename_ == "total" && paths.instanceindex_ == -1) { policies::maintain_queue_wait_times = true; // overall counter using performance_counters::detail::create_raw_counter; util::function_nonser<boost::int64_t()> f = util::bind(&spt::get_average_thread_wait_time, &scheduler_, -1); return create_raw_counter(info, std::move(f), ec); } else if (paths.instancename_ == "worker-thread" && paths.instanceindex_ >= 0 && std::size_t(paths.instanceindex_) < threads_.size()) { policies::maintain_queue_wait_times = true; // specific counter using performance_counters::detail::create_raw_counter; util::function_nonser<boost::int64_t()> f = util::bind(&spt::get_average_thread_wait_time, &scheduler_, static_cast<std::size_t>(paths.instanceindex_)); return create_raw_counter(info, std::move(f), ec); } HPX_THROWS_IF(ec, bad_parameter, "thread_wait_time_counter_creator", "invalid counter instance name: " + paths.instancename_); return naming::invalid_gid; } // average pending task wait time template <typename SchedulingPolicy, typename NotificationPolicy> naming::gid_type threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: task_wait_time_counter_creator( performance_counters::counter_info const& info, error_code& ec) { // verify the validity of the counter instance name performance_counters::counter_path_elements paths; performance_counters::get_counter_path_elements(info.fullname_, paths, ec); if (ec) return naming::invalid_gid; // /threads{locality#%d/total}/wait-time/pending // /threads{locality#%d/worker-thread%d}/wait-time/pending if (paths.parentinstance_is_basename_) { HPX_THROWS_IF(ec, bad_parameter, "task_wait_time_counter_creator", "invalid counter instance parent name: " + paths.parentinstancename_); return naming::invalid_gid; } typedef scheduling_policy_type spt; using util::placeholders::_1; if (paths.instancename_ == "total" && paths.instanceindex_ == -1) { policies::maintain_queue_wait_times = true; // overall counter using performance_counters::detail::create_raw_counter; util::function_nonser<boost::int64_t()> f = util::bind(&spt::get_average_task_wait_time, &scheduler_, -1); return create_raw_counter(info, std::move(f), ec); } else if (paths.instancename_ == "worker-thread" && paths.instanceindex_ >= 0 && std::size_t(paths.instanceindex_) < threads_.size()) { policies::maintain_queue_wait_times = true; // specific counter using performance_counters::detail::create_raw_counter; util::function_nonser<boost::int64_t()> f = util::bind(&spt::get_average_task_wait_time, &scheduler_, static_cast<std::size_t>(paths.instanceindex_)); return create_raw_counter(info, std::move(f), ec); } HPX_THROWS_IF(ec, bad_parameter, "task_wait_time_counter_creator", "invalid counter instance name: " + paths.instancename_); return naming::invalid_gid; } #endif bool locality_allocator_counter_discoverer( performance_counters::counter_info const& info, performance_counters::discover_counter_func const& f, performance_counters::discover_counters_mode mode, error_code& ec) { performance_counters::counter_info i = info; // compose the counter name templates performance_counters::counter_path_elements p; performance_counters::counter_status status = get_counter_path_elements(info.fullname_, p, ec); if (!status_is_valid(status)) return false; if (mode == performance_counters::discover_counters_minimal || p.parentinstancename_.empty() || p.instancename_.empty()) { if (p.parentinstancename_.empty()) { p.parentinstancename_ = "locality#*"; p.parentinstanceindex_ = -1; } if (p.instancename_.empty()) { p.instancename_ = "total"; p.instanceindex_ = -1; } status = get_counter_name(p, i.fullname_, ec); if (!status_is_valid(status) || !f(i, ec) || ec) return false; p.instancename_ = "allocator#*"; p.instanceindex_ = -1; if (mode == performance_counters::discover_counters_full) { for (std::size_t t = 0; t != HPX_COROUTINE_NUM_ALL_HEAPS; ++t) { p.instancename_ = "allocator"; p.instanceindex_ = static_cast<boost::int32_t>(t); status = get_counter_name(p, i.fullname_, ec); if (!status_is_valid(status) || !f(i, ec) || ec) return false; } } else { status = get_counter_name(p, i.fullname_, ec); if (!status_is_valid(status) || !f(i, ec) || ec) return false; } } else if (p.instancename_ == "total" && p.instanceindex_ == -1) { // overall counter status = get_counter_name(p, i.fullname_, ec); if (!status_is_valid(status) || !f(i, ec) || ec) return false; } else if (p.instancename_ == "allocator#*") { for (std::size_t t = 0; t != HPX_COROUTINE_NUM_ALL_HEAPS; ++t) { p.instancename_ = "allocator"; p.instanceindex_ = static_cast<boost::int32_t>(t); status = get_counter_name(p, i.fullname_, ec); if (!status_is_valid(status) || !f(i, ec) || ec) return false; } } else if (!f(i, ec) || ec) { return false; } if (&ec != &throws) ec = make_success_code(); return true; } #ifdef HPX_HAVE_THREAD_IDLE_RATES /////////////////////////////////////////////////////////////////////////// // idle rate counter creation function template <typename SchedulingPolicy, typename NotificationPolicy> naming::gid_type threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: idle_rate_counter_creator( performance_counters::counter_info const& info, error_code& ec) { // verify the validity of the counter instance name performance_counters::counter_path_elements paths; performance_counters::get_counter_path_elements(info.fullname_, paths, ec); if (ec) return naming::invalid_gid; // /threads{locality#%d/total}/idle-rate // /threads{locality#%d/worker-thread%d}/idle-rate if (paths.parentinstance_is_basename_) { HPX_THROWS_IF(ec, bad_parameter, "idle_rate_counter_creator", "invalid counter instance parent name: " + paths.parentinstancename_); return naming::invalid_gid; } typedef threadmanager_impl ti; using util::placeholders::_1; if (paths.instancename_ == "total" && paths.instanceindex_ == -1) { // overall counter using performance_counters::detail::create_raw_counter; boost::int64_t (threadmanager_impl::*avg_idle_rate_ptr)( bool ) = &ti::avg_idle_rate; util::function_nonser<boost::int64_t(bool)> f = util::bind(avg_idle_rate_ptr, this, _1); return create_raw_counter(info, std::move(f), ec); } else if (paths.instancename_ == "worker-thread" && paths.instanceindex_ >= 0 && std::size_t(paths.instanceindex_) < threads_.size()) { // specific counter using performance_counters::detail::create_raw_counter; boost::int64_t (threadmanager_impl::*avg_idle_rate_ptr)( std::size_t, bool ) = &ti::avg_idle_rate; using performance_counters::detail::create_raw_counter; util::function_nonser<boost::int64_t(bool)> f = util::bind(avg_idle_rate_ptr, this, static_cast<std::size_t>(paths.instanceindex_), _1); return create_raw_counter(info, std::move(f), ec); } HPX_THROWS_IF(ec, bad_parameter, "idle_rate_counter_creator", "invalid counter instance name: " + paths.instancename_); return naming::invalid_gid; } #endif /////////////////////////////////////////////////////////////////////////// naming::gid_type counter_creator(performance_counters::counter_info const& info, performance_counters::counter_path_elements const& paths, util::function_nonser<boost::int64_t(bool)> const& total_creator, util::function_nonser<boost::int64_t(bool)> const& individual_creator, char const* individual_name, std::size_t individual_count, error_code& ec) { if (paths.parentinstance_is_basename_) { HPX_THROWS_IF(ec, bad_parameter, "counter_creator", "invalid counter instance parent name: " + paths.parentinstancename_); return naming::invalid_gid; } if (!total_creator.empty() && paths.instancename_ == "total" && paths.instanceindex_ == -1) { // overall counter using performance_counters::detail::create_raw_counter; return create_raw_counter(info, total_creator, ec); } else if (!individual_creator.empty() && paths.instancename_ == individual_name && paths.instanceindex_ >= 0 && std::size_t(paths.instanceindex_) < individual_count) { // specific counter using performance_counters::detail::create_raw_counter; return create_raw_counter(info, individual_creator, ec); } HPX_THROWS_IF(ec, bad_parameter, "counter_creator", "invalid counter instance name: " + paths.instancename_); return naming::invalid_gid; } /////////////////////////////////////////////////////////////////////////// // thread counts counter creation function template <typename SchedulingPolicy, typename NotificationPolicy> naming::gid_type threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: thread_counts_counter_creator( performance_counters::counter_info const& info, error_code& ec) { // verify the validity of the counter instance name performance_counters::counter_path_elements paths; performance_counters::get_counter_path_elements(info.fullname_, paths, ec); if (ec) return naming::invalid_gid; struct creator_data { char const* const countername; util::function_nonser<boost::int64_t(bool)> total_func; util::function_nonser<boost::int64_t(bool)> individual_func; char const* const individual_name; std::size_t individual_count; }; typedef scheduling_policy_type spt; typedef threadmanager_impl ti; using util::placeholders::_1; std::size_t shepherd_count = threads_.size(); creator_data data[] = { #if defined(HPX_HAVE_THREAD_IDLE_RATES) && defined(HPX_HAVE_THREAD_CREATION_AND_CLEANUP_RATES) // /threads{locality#%d/total}/creation-idle-rate // /threads{locality#%d/worker-thread%d}/creation-idle-rate { "creation-idle-rate", util::bind(&ti::avg_creation_idle_rate, this, _1), util::function_nonser<boost::uint64_t(bool)>(), "", 0 }, // /threads{locality#%d/total}/cleanup-idle-rate // /threads{locality#%d/worker-thread%d}/cleanup-idle-rate { "cleanup-idle-rate", util::bind(&ti::avg_cleanup_idle_rate, this, _1), util::function_nonser<boost::uint64_t(bool)>(), "", 0 }, #endif #ifdef HPX_HAVE_THREAD_CUMULATIVE_COUNTS // /threads{locality#%d/total}/count/cumulative // /threads{locality#%d/worker-thread%d}/count/cumulative { "count/cumulative", util::bind(&ti::get_executed_threads, this, -1, _1), util::bind(&ti::get_executed_threads, this, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/cumulative-phases // /threads{locality#%d/worker-thread%d}/count/cumulative-phases { "count/cumulative-phases", util::bind(&ti::get_executed_thread_phases, this, -1, _1), util::bind(&ti::get_executed_thread_phases, this, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, #ifdef HPX_HAVE_THREAD_IDLE_RATES // /threads{locality#%d/total}/time/average // /threads{locality#%d/worker-thread%d}/time/average { "time/average", util::bind(&ti::get_thread_duration, this, -1, _1), util::bind(&ti::get_thread_duration, this, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/time/average-phase // /threads{locality#%d/worker-thread%d}/time/average-phase { "time/average-phase", util::bind(&ti::get_thread_phase_duration, this, -1, _1), util::bind(&ti::get_thread_phase_duration, this, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/time/average-overhead // /threads{locality#%d/worker-thread%d}/time/average-overhead { "time/average-overhead", util::bind(&ti::get_thread_overhead, this, -1, _1), util::bind(&ti::get_thread_overhead, this, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/time/average-phase-overhead // /threads{locality#%d/worker-thread%d}/time/average-phase-overhead { "time/average-phase-overhead", util::bind(&ti::get_thread_phase_overhead, this, -1, _1), util::bind(&ti::get_thread_phase_overhead, this, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, #endif #endif // /threads{locality#%d/total}/count/instantaneous/all // /threads{locality#%d/worker-thread%d}/count/instantaneous/all { "count/instantaneous/all", util::bind(&spt::get_thread_count, &scheduler_, unknown, thread_priority_default, std::size_t(-1), _1), util::bind(&spt::get_thread_count, &scheduler_, unknown, thread_priority_default, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/instantaneous/active // /threads{locality#%d/worker-thread%d}/count/instantaneous/active { "count/instantaneous/active", util::bind(&spt::get_thread_count, &scheduler_, active, thread_priority_default, std::size_t(-1), _1), util::bind(&spt::get_thread_count, &scheduler_, active, thread_priority_default, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/instantaneous/pending // /threads{locality#%d/worker-thread%d}/count/instantaneous/pending { "count/instantaneous/pending", util::bind(&spt::get_thread_count, &scheduler_, pending, thread_priority_default, std::size_t(-1), _1), util::bind(&spt::get_thread_count, &scheduler_, pending, thread_priority_default, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/instantaneous/suspended // /threads{locality#%d/worker-thread%d}/count/instantaneous/suspended { "count/instantaneous/suspended", util::bind(&spt::get_thread_count, &scheduler_, suspended, thread_priority_default, std::size_t(-1), _1), util::bind(&spt::get_thread_count, &scheduler_, suspended, thread_priority_default, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads(locality#%d/total}/count/instantaneous/terminated // /threads(locality#%d/worker-thread%d}/count/instantaneous/terminated { "count/instantaneous/terminated", util::bind(&spt::get_thread_count, &scheduler_, terminated, thread_priority_default, std::size_t(-1), _1), util::bind(&spt::get_thread_count, &scheduler_, terminated, thread_priority_default, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/instantaneous/staged // /threads{locality#%d/worker-thread%d}/count/instantaneous/staged { "count/instantaneous/staged", util::bind(&spt::get_thread_count, &scheduler_, staged, thread_priority_default, std::size_t(-1), _1), util::bind(&spt::get_thread_count, &scheduler_, staged, thread_priority_default, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/stack-recycles { "count/stack-recycles", util::bind(&coroutine_type::impl_type::get_stack_recycle_count, _1), util::function_nonser<boost::uint64_t(bool)>(), "", 0 }, #if !defined(BOOST_WINDOWS) && !defined(HPX_HAVE_GENERIC_CONTEXT_COROUTINES) // /threads{locality#%d/total}/count/stack-unbinds { "count/stack-unbinds", util::bind(&coroutine_type::impl_type::get_stack_unbind_count, _1), util::function_nonser<boost::uint64_t(bool)>(), "", 0 }, #endif // /threads{locality#%d/total}/count/objects // /threads{locality#%d/allocator%d}/count/objects { "count/objects", &coroutine_type::impl_type::get_allocation_count_all, util::bind(&coroutine_type::impl_type::get_allocation_count, static_cast<std::size_t>(paths.instanceindex_), _1), "allocator", HPX_COROUTINE_NUM_ALL_HEAPS }, #ifdef HPX_HAVE_THREAD_STEALING_COUNTS // /threads{locality#%d/total}/count/pending-misses // /threads{locality#%d/worker-thread%d}/count/pending-misses { "count/pending-misses", util::bind(&spt::get_num_pending_misses, &scheduler_, std::size_t(-1), _1), util::bind(&spt::get_num_pending_misses, &scheduler_, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/pending-accesses // /threads{locality#%d/worker-thread%d}/count/pending-accesses { "count/pending-accesses", util::bind(&spt::get_num_pending_accesses, &scheduler_, std::size_t(-1), _1), util::bind(&spt::get_num_pending_accesses, &scheduler_, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/stolen-from-pending // /threads{locality#%d/worker-thread%d}/count/stolen-from-pending { "count/stolen-from-pending", util::bind(&spt::get_num_stolen_from_pending, &scheduler_, std::size_t(-1), _1), util::bind(&spt::get_num_stolen_from_pending, &scheduler_, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/stolen-from-staged // /threads{locality#%d/worker-thread%d}/count/stolen-from-staged { "count/stolen-from-staged", util::bind(&spt::get_num_stolen_from_staged, &scheduler_, std::size_t(-1), _1), util::bind(&spt::get_num_stolen_from_staged, &scheduler_, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/stolen-to-pending // /threads{locality#%d/worker-thread%d}/count/stolen-to-pending { "count/stolen-to-pending", util::bind(&spt::get_num_stolen_to_pending, &scheduler_, std::size_t(-1), _1), util::bind(&spt::get_num_stolen_to_pending, &scheduler_, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count }, // /threads{locality#%d/total}/count/stolen-to-staged // /threads{locality#%d/worker-thread%d}/count/stolen-to-staged { "count/stolen-to-staged", util::bind(&spt::get_num_stolen_to_staged, &scheduler_, std::size_t(-1), _1), util::bind(&spt::get_num_stolen_to_staged, &scheduler_, static_cast<std::size_t>(paths.instanceindex_), _1), "worker-thread", shepherd_count } #endif }; std::size_t const data_size = sizeof(data)/sizeof(data[0]); for (creator_data const* d = data; d < &d[data_size]; ++d) { if (paths.countername_ == d->countername) { return counter_creator(info, paths, d->total_func, d->individual_func, d->individual_name, d->individual_count, ec); } } HPX_THROWS_IF(ec, bad_parameter, "thread_counts_counter_creator", "invalid counter instance name: " + paths.instancename_); return naming::invalid_gid; } /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: register_counter_types() { typedef threadmanager_impl ti; performance_counters::create_counter_func counts_creator( boost::bind(&ti::thread_counts_counter_creator, this, _1, _2)); performance_counters::generic_counter_type_data counter_types[] = { // length of thread queue(s) { "/threadqueue/length", performance_counters::counter_raw, "returns the current queue length for the referenced queue", HPX_PERFORMANCE_COUNTER_V1, boost::bind(&ti::queue_length_counter_creator, this, _1, _2), &performance_counters::locality_thread_counter_discoverer, "" }, #ifdef HPX_HAVE_THREAD_QUEUE_WAITTIME // average thread wait time for queue(s) { "/threads/wait-time/pending", performance_counters::counter_raw, "returns the average wait time of pending threads for the referenced queue", HPX_PERFORMANCE_COUNTER_V1, boost::bind(&ti::thread_wait_time_counter_creator, this, _1, _2), &performance_counters::locality_thread_counter_discoverer, "ns" }, // average task wait time for queue(s) { "/threads/wait-time/staged", performance_counters::counter_raw, "returns the average wait time of staged threads (task descriptions) " "for the referenced queue", HPX_PERFORMANCE_COUNTER_V1, boost::bind(&ti::task_wait_time_counter_creator, this, _1, _2), &performance_counters::locality_thread_counter_discoverer, "ns" }, #endif #ifdef HPX_HAVE_THREAD_IDLE_RATES // idle rate { "/threads/idle-rate", performance_counters::counter_raw, "returns the idle rate for the referenced object", HPX_PERFORMANCE_COUNTER_V1, boost::bind(&ti::idle_rate_counter_creator, this, _1, _2), &performance_counters::locality_thread_counter_discoverer, "0.01%" }, #ifdef HPX_HAVE_THREAD_CREATION_AND_CLEANUP_RATES { "/threads/creation-idle-rate", performance_counters::counter_raw, "returns the % of idle-rate spent creating HPX-threads for the " "referenced object", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "0.01%" }, { "/threads/cleanup-idle-rate", performance_counters::counter_raw, "returns the % of time spent cleaning up terminated HPX-threads " "for the referenced object", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "0.01%" }, #endif #endif #ifdef HPX_HAVE_THREAD_CUMULATIVE_COUNTS // thread counts { "/threads/count/cumulative", performance_counters::counter_raw, "returns the overall number of executed (retired) HPX-threads for " "the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/cumulative-phases", performance_counters::counter_raw, "returns the overall number of HPX-thread phases executed for " "the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, #ifdef HPX_HAVE_THREAD_IDLE_RATES { "/threads/time/average", performance_counters::counter_raw, "returns the average time spent executing one HPX-thread", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "ns" }, { "/threads/time/average-phase", performance_counters::counter_raw, "returns the average time spent executing one HPX-thread phase", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "ns" }, { "/threads/time/average-overhead", performance_counters::counter_raw, "returns average overhead time executing one HPX-thread", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "ns" }, { "/threads/time/average-phase-overhead", performance_counters::counter_raw, "returns average overhead time executing one HPX-thread phase", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "ns" }, #endif #endif { "/threads/count/instantaneous/all", performance_counters::counter_raw, "returns the overall current number of HPX-threads instantiated at the " "referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/instantaneous/active", performance_counters::counter_raw, "returns the current number of active HPX-threads at the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/instantaneous/pending", performance_counters::counter_raw, "returns the current number of pending HPX-threads at the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/instantaneous/suspended", performance_counters::counter_raw, "returns the current number of suspended HPX-threads at the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/instantaneous/terminated", performance_counters::counter_raw, "returns the current number of terminated HPX-threads at the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/instantaneous/staged", performance_counters::counter_raw, "returns the current number of staged HPX-threads (task descriptions) " "at the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/stack-recycles", performance_counters::counter_raw, "returns the total number of HPX-thread recycling operations performed " "for the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_counter_discoverer, "" }, #if !defined(BOOST_WINDOWS) && !defined(HPX_HAVE_GENERIC_CONTEXT_COROUTINES) { "/threads/count/stack-unbinds", performance_counters::counter_raw, "returns the total number of HPX-thread unbind (madvise) operations " "performed for the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_counter_discoverer, "" }, #endif { "/threads/count/objects", performance_counters::counter_raw, "returns the overall number of created HPX-thread objects for " "the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &locality_allocator_counter_discoverer, "" }, #ifdef HPX_HAVE_THREAD_STEALING_COUNTS { "/threads/count/pending-misses", performance_counters::counter_raw, "returns the number of times that the referenced worker-thread " "on the referenced locality failed to find pending HPX-threads " "in its associated queue", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/pending-accesses", performance_counters::counter_raw, "returns the number of times that the referenced worker-thread " "on the referenced locality looked for pending HPX-threads " "in its associated queue", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/stolen-from-pending", performance_counters::counter_raw, "returns the overall number of pending HPX-threads stolen by neighboring" "schedulers from this scheduler for the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/stolen-from-staged", performance_counters::counter_raw, "returns the overall number of task descriptions stolen by neighboring" "schedulers from this scheduler for the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/stolen-to-pending", performance_counters::counter_raw, "returns the overall number of pending HPX-threads stolen from neighboring" "schedulers for the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" }, { "/threads/count/stolen-to-staged", performance_counters::counter_raw, "returns the overall number of task descriptions stolen from neighboring" "schedulers for the referenced locality", HPX_PERFORMANCE_COUNTER_V1, counts_creator, &performance_counters::locality_thread_counter_discoverer, "" } #endif }; performance_counters::install_counter_types( counter_types, sizeof(counter_types)/sizeof(counter_types[0])); } template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: idle_callback(std::size_t num_thread) { scheduler_.idle_callback(num_thread); } /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: tfunc_impl(std::size_t num_thread) { manage_active_thread_count count(thread_count_); // run the work queue hpx::util::coroutines::prepare_main_thread main_thread; // run main scheduling loop until terminated detail::scheduling_loop(num_thread, scheduler_, state_, executed_threads_[num_thread], executed_thread_phases_[num_thread], tfunc_times[num_thread], exec_times[num_thread], util::bind(&threadmanager_impl::idle_callback, this, num_thread)); // the OS thread is allowed to exit only if no more HPX threads exist // or if some other thread has terminated HPX_ASSERT(!scheduler_.get_thread_count( unknown, thread_priority_default, num_thread) || state_ == terminating); } /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> bool threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: run(std::size_t num_threads) { LTM_(info) << "run: number of processing units available: " //-V128 << threads::hardware_concurrency(); LTM_(info) << "run: creating " << num_threads << " OS thread(s)"; //-V128 if (0 == num_threads) { HPX_THROW_EXCEPTION(bad_parameter, "threadmanager_impl::run", "number of threads is zero"); } #if defined(HPX_HAVE_THREAD_CUMULATIVE_COUNTS) && defined(HPX_HAVE_THREAD_IDLE_RATES) // scale timestamps to nanoseconds boost::uint64_t base_timestamp = util::hardware::timestamp(); boost::uint64_t base_time = util::high_resolution_clock::now(); boost::uint64_t curr_timestamp = util::hardware::timestamp(); boost::uint64_t curr_time = util::high_resolution_clock::now(); while ((curr_time - base_time) <= 100000) { curr_timestamp = util::hardware::timestamp(); curr_time = util::high_resolution_clock::now(); } if (curr_timestamp - base_timestamp != 0) { timestamp_scale_ = double(curr_time - base_time) / double(curr_timestamp - base_timestamp); } LTM_(info) << "run: timestamp_scale: " << timestamp_scale_; //-V128 #endif mutex_type::scoped_lock lk(mtx_); if (!threads_.empty() || (state_.load() == running)) return true; // do nothing if already running LTM_(info) << "run: running timer pool"; timer_pool_.run(false); executed_threads_.resize(num_threads); executed_thread_phases_.resize(num_threads); tfunc_times.resize(num_threads); exec_times.resize(num_threads); try { // run threads and wait for initialization to complete HPX_ASSERT (NULL == startup_); startup_ = new boost::barrier(static_cast<unsigned>(num_threads+1)); state_.store(running); topology const& topology_ = get_topology(); std::size_t thread_num = num_threads; while (thread_num-- != 0) { threads::mask_cref_type mask = get_pu_mask(topology_, thread_num); LTM_(info) << "run: create OS thread " << thread_num //-V128 << ": will run on processing units within this mask: " #if !defined(HPX_WITH_MORE_THAN_64_THREADS) || (defined(HPX_HAVE_MAX_CPU_COUNT) && HPX_HAVE_MAX_CPU_COUNT <= 64) << std::hex << "0x" << mask; #else << "0b" << mask; #endif // create a new thread threads_.push_back(new boost::thread(boost::bind( &threadmanager_impl::tfunc, this, thread_num, boost::ref(topology_)))); // set the new threads affinity (on Windows systems) if (any(mask)) { error_code ec(lightweight); topology_.set_thread_affinity_mask(threads_.back(), mask, ec); if (ec) { LTM_(warning) << "run: setting thread affinity on OS " //-V128 "thread " << thread_num << " failed with: " << ec.get_message(); } } else { LTM_(debug) << "run: setting thread affinity on OS thread " //-V128 << thread_num << " was explicitly disabled."; } } // start timer pool as well timer_pool_.run(false); // the main thread needs to have a unique thread_num init_tss(thread_num, scheduler_.numa_sensitive()); startup_->wait(); } catch (std::exception const& e) { LTM_(always) << "run: failed with: " << e.what(); // trigger the barrier while (num_threads-- != 0 && !startup_->wait()) ; stop(); threads_.clear(); return false; } LTM_(info) << "run: running"; return true; } template <typename SchedulingPolicy, typename NotificationPolicy> void threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: stop (bool blocking) { LTM_(info) << "stop: blocking(" << std::boolalpha << blocking << ")"; deinit_tss(); mutex_type::scoped_lock l(mtx_); if (!threads_.empty()) { if (state_.load() == running) { state_.store(stopping); do_some_work(); // make sure we're not waiting } if (blocking) { for (std::size_t i = 0; i != threads_.size(); ++i) { // make sure no OS thread is waiting LTM_(info) << "stop: notify_all"; do_some_work(); LTM_(info) << "stop(" << i << "): join"; //-V128 // unlock the lock while joining util::scoped_unlock<mutex_type::scoped_lock> ul(l); threads_[i].join(); } threads_.clear(); LTM_(info) << "stop: stopping timer pool"; timer_pool_.stop(); // stop timer pool as well if (blocking) { timer_pool_.join(); timer_pool_.clear(); } } } delete startup_; startup_ = NULL; } #ifdef HPX_HAVE_THREAD_CUMULATIVE_COUNTS template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_executed_threads(std::size_t num, bool reset) { boost::int64_t result = 0; if (num != std::size_t(-1)) { result = executed_threads_[num]; if (reset) executed_threads_[num] = 0; return result; } result = std::accumulate(executed_threads_.begin(), executed_threads_.end(), 0LL); if (reset) std::fill(executed_threads_.begin(), executed_threads_.end(), 0LL); return result; } template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_executed_thread_phases(std::size_t num, bool reset) { boost::int64_t result = 0; if (num != std::size_t(-1)) { result = executed_thread_phases_[num]; if (reset) executed_thread_phases_[num] = 0; return result; } result = std::accumulate(executed_thread_phases_.begin(), executed_thread_phases_.end(), 0LL); if (reset) { std::fill(executed_thread_phases_.begin(), executed_thread_phases_.end(), 0LL); } return result; } #ifdef HPX_HAVE_THREAD_IDLE_RATES template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_thread_phase_duration(std::size_t num, bool reset) { if (num != std::size_t(-1)) { double exec_total = static_cast<double>(exec_times[num]); double num_phases = static_cast<double>(executed_thread_phases_[num]); if (reset) { executed_thread_phases_[num] = 0; tfunc_times[num] = boost::uint64_t(-1); } return boost::uint64_t((exec_total * timestamp_scale_)/ num_phases); } double exec_total = std::accumulate(exec_times.begin(), exec_times.end(), 0.); double num_phases = std::accumulate(executed_thread_phases_.begin(), executed_thread_phases_.end(), 0.); if (reset) { std::fill(executed_thread_phases_.begin(), executed_thread_phases_.end(), 0LL); std::fill(tfunc_times.begin(), tfunc_times.end(), boost::uint64_t(-1)); } return boost::uint64_t((exec_total * timestamp_scale_)/ num_phases); } template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_thread_duration(std::size_t num, bool reset) { if (num != std::size_t(-1)) { double exec_total = static_cast<double>(exec_times[num]); double num_threads = static_cast<double>(executed_threads_[num]); if (reset) { executed_threads_[num] = 0; tfunc_times[num] = boost::uint64_t(-1); } return boost::uint64_t((exec_total * timestamp_scale_)/ num_threads); } double exec_total = std::accumulate(exec_times.begin(), exec_times.end(), 0.); double num_threads = std::accumulate(executed_threads_.begin(), executed_threads_.end(), 0.); if (reset) { std::fill(executed_threads_.begin(), executed_threads_.end(), 0LL); std::fill(tfunc_times.begin(), tfunc_times.end(), boost::uint64_t(-1)); } return boost::uint64_t((exec_total * timestamp_scale_) / num_threads); } template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_thread_phase_overhead(std::size_t num, bool reset) { if (num != std::size_t(-1)) { double exec_total = static_cast<double>(exec_times[num]); double tfunc_total = static_cast<double>(tfunc_times[num]); double num_phases = static_cast<double>(executed_thread_phases_[num]); if (reset) { executed_thread_phases_[num] = 0; tfunc_times[num] = boost::uint64_t(-1); } return boost::uint64_t(((tfunc_total - exec_total) * timestamp_scale_)/ num_phases); } double exec_total = std::accumulate(exec_times.begin(), exec_times.end(), 0.); double tfunc_total = std::accumulate(tfunc_times.begin(), tfunc_times.end(), 0.); double num_phases = std::accumulate(executed_thread_phases_.begin(), executed_thread_phases_.end(), 0.); if (reset) { std::fill(executed_thread_phases_.begin(), executed_thread_phases_.end(), 0LL); std::fill(tfunc_times.begin(), tfunc_times.end(), boost::uint64_t(-1)); } return boost::uint64_t(((tfunc_total - exec_total) * timestamp_scale_)/ num_phases); } template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: get_thread_overhead(std::size_t num, bool reset) { if (num != std::size_t(-1)) { double exec_total = static_cast<double>(exec_times[num]); double tfunc_total = static_cast<double>(tfunc_times[num]); double num_threads = static_cast<double>(executed_threads_[num]); if (reset) { executed_threads_[num] = 0; tfunc_times[num] = boost::uint64_t(-1); } return boost::uint64_t(((tfunc_total - exec_total) * timestamp_scale_) / num_threads); } double exec_total = std::accumulate(exec_times.begin(), exec_times.end(), 0.); double tfunc_total = std::accumulate(tfunc_times.begin(), tfunc_times.end(), 0.); double num_threads = std::accumulate(executed_threads_.begin(), executed_threads_.end(), 0.); if (reset) { std::fill(executed_threads_.begin(), executed_threads_.end(), 0LL); std::fill(tfunc_times.begin(), tfunc_times.end(), boost::uint64_t(-1)); } return boost::uint64_t(((tfunc_total - exec_total) * timestamp_scale_) / num_threads); } #endif #endif #ifdef HPX_HAVE_THREAD_IDLE_RATES /////////////////////////////////////////////////////////////////////////// template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: avg_idle_rate(bool reset) { double const exec_total = std::accumulate(exec_times.begin(), exec_times.end(), 0.); double const tfunc_total = std::accumulate(tfunc_times.begin(), tfunc_times.end(), 0.); if (reset) { std::fill(tfunc_times.begin(), tfunc_times.end(), boost::uint64_t(-1)); } if (std::abs(tfunc_total) < 1e-16) // avoid division by zero return 10000LL; HPX_ASSERT(tfunc_total > exec_total); double const percent = 1. - (exec_total / tfunc_total); return boost::int64_t(10000. * percent); // 0.01 percent } template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: avg_idle_rate(std::size_t num_thread, bool reset) { double const exec_time = static_cast<double>(exec_times[num_thread]); double const tfunc_time = static_cast<double>(tfunc_times[num_thread]); if (reset) { tfunc_times[num_thread] = boost::uint64_t(-1); } if (std::abs(tfunc_time) < 1e-16) // avoid division by zero return 10000LL; HPX_ASSERT(tfunc_time > exec_time); double const percent = 1. - (exec_time / tfunc_time); return boost::int64_t(10000. * percent); // 0.01 percent } #endif #if defined(HPX_HAVE_THREAD_IDLE_RATES) && defined(HPX_HAVE_THREAD_CREATION_AND_CLEANUP_RATES) template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: avg_creation_idle_rate(bool reset) { double const creation_total = static_cast<double>(scheduler_.get_creation_time(reset)); double const exec_total = std::accumulate(exec_times.begin(), exec_times.end(), 0.); double const tfunc_total = std::accumulate(tfunc_times.begin(), tfunc_times.end(), 0.); if (reset) { std::fill(tfunc_times.begin(), tfunc_times.end(), boost::uint64_t(-1)); } // avoid division by zero if (std::abs(tfunc_total - exec_total) < 1e-16) return 10000LL; HPX_ASSERT(tfunc_total > exec_total); double const percent = (creation_total / (tfunc_total - exec_total)); return boost::int64_t(10000. * percent); // 0.01 percent } template <typename SchedulingPolicy, typename NotificationPolicy> boost::int64_t threadmanager_impl<SchedulingPolicy, NotificationPolicy>:: avg_cleanup_idle_rate(bool reset) { double const cleanup_total = static_cast<double>(scheduler_.get_cleanup_time(reset)); double const exec_total = std::accumulate(exec_times.begin(), exec_times.end(), 0.); double const tfunc_total = std::accumulate(tfunc_times.begin(), tfunc_times.end(), 0.); if (reset) { std::fill(tfunc_times.begin(), tfunc_times.end(), boost::uint64_t(-1)); } // avoid division by zero if (std::abs(tfunc_total - exec_total) < 1e-16) return 10000LL; HPX_ASSERT(tfunc_total > exec_total); double const percent = (cleanup_total / (tfunc_total - exec_total)); return boost::int64_t(10000. * percent); // 0.01 percent } #endif }} /////////////////////////////////////////////////////////////////////////////// /// explicit template instantiation for the thread manager of our choice #include <hpx/runtime/threads/policies/callback_notifier.hpp> #if defined(HPX_HAVE_LOCAL_SCHEDULER) #include <hpx/runtime/threads/policies/local_queue_scheduler.hpp> template class HPX_EXPORT hpx::threads::threadmanager_impl< hpx::threads::policies::local_queue_scheduler<>, hpx::threads::policies::callback_notifier>; #endif #if defined(HPX_HAVE_STATIC_PRIORITY_SCHEDULER) #include <hpx/runtime/threads/policies/static_priority_queue_scheduler.hpp> template class HPX_EXPORT hpx::threads::threadmanager_impl< hpx::threads::policies::static_priority_queue_scheduler<>, hpx::threads::policies::callback_notifier>; #endif #include <hpx/runtime/threads/policies/local_priority_queue_scheduler.hpp> template class HPX_EXPORT hpx::threads::threadmanager_impl< hpx::threads::policies::local_priority_queue_scheduler<>, hpx::threads::policies::callback_notifier>; #if defined(HPX_HAVE_ABP_SCHEDULER) template class HPX_EXPORT hpx::threads::threadmanager_impl< hpx::threads::policies::abp_fifo_priority_queue_scheduler, hpx::threads::policies::callback_notifier>; #endif #if defined(HPX_HAVE_HIERARCHY_SCHEDULER) #include <hpx/runtime/threads/policies/hierarchy_scheduler.hpp> template class HPX_EXPORT hpx::threads::threadmanager_impl< hpx::threads::policies::hierarchy_scheduler<>, hpx::threads::policies::callback_notifier>; #endif #if defined(HPX_HAVE_PERIODIC_PRIORITY_SCHEDULER) #include <hpx/runtime/threads/policies/periodic_priority_queue_scheduler.hpp> template class HPX_EXPORT hpx::threads::threadmanager_impl< hpx::threads::policies::periodic_priority_queue_scheduler<>, hpx::threads::policies::callback_notifier>; #endif
41.888671
112
0.601574
[ "object" ]
3385a6f802eb0964867f912e5f4115e849ecdaf8
10,920
cxx
C++
Qt/Components/pqComparativeCueWidget.cxx
EvgenyVRN/ParaView
e014337e76cc4e5c51d9377a8ac1e874afd84d64
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Qt/Components/pqComparativeCueWidget.cxx
EvgenyVRN/ParaView
e014337e76cc4e5c51d9377a8ac1e874afd84d64
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Qt/Components/pqComparativeCueWidget.cxx
EvgenyVRN/ParaView
e014337e76cc4e5c51d9377a8ac1e874afd84d64
[ "Apache-2.0", "BSD-3-Clause" ]
2
2019-08-28T09:04:43.000Z
2020-08-18T11:45:17.000Z
/*========================================================================= Program: ParaView Module: pqComparativeCueWidget.cxx Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ========================================================================*/ #include "pqComparativeCueWidget.h" #include "ui_pqComparativeParameterRangeDialog.h" #include <QRegExpValidator> #include "pqQtDeprecated.h" #include "pqUndoStack.h" #include "vtkEventQtSlotConnect.h" #include "vtkPVComparativeAnimationCue.h" #include "vtkSMComparativeAnimationCueProxy.h" #include "vtkSMPropertyHelper.h" #include <cassert> #include <vector> namespace { class pqLock { bool* Var; bool Prev; public: pqLock(bool* var, bool val) { this->Var = var; this->Prev = *this->Var; *this->Var = val; } ~pqLock() { *this->Var = this->Prev; } }; std::vector<double> getValues(const QString& str) { std::vector<double> values; QStringList parts = str.split(',', PV_QT_SKIP_EMPTY_PARTS); foreach (QString part, parts) { values.push_back(QVariant(part).toDouble()); } return values; } }; //----------------------------------------------------------------------------- pqComparativeCueWidget::pqComparativeCueWidget(QWidget* parentObject) : Superclass(parentObject) { this->VTKConnect = vtkEventQtSlotConnect::New(); this->Size = QSize(2, 2); this->IdleUpdateTimer.setInterval(0); this->IdleUpdateTimer.setSingleShot(true); QObject::connect(&this->IdleUpdateTimer, SIGNAL(timeout()), this, SLOT(updateGUI())); QObject::connect(this, SIGNAL(itemSelectionChanged()), this, SLOT(onSelectionChanged())); QObject::connect(this, SIGNAL(cellChanged(int, int)), this, SLOT(onCellChanged(int, int))); this->SelectionChanged = false; this->InUpdateGUI = false; } //----------------------------------------------------------------------------- pqComparativeCueWidget::~pqComparativeCueWidget() { this->VTKConnect->Disconnect(); this->VTKConnect->Delete(); this->VTKConnect = nullptr; } //----------------------------------------------------------------------------- void pqComparativeCueWidget::setCue(vtkSMProxy* _cue) { if (this->Cue.GetPointer() == _cue) { return; } this->VTKConnect->Disconnect(); this->Cue = vtkSMComparativeAnimationCueProxy::SafeDownCast(_cue); if (this->Cue) { this->VTKConnect->Connect(this->Cue, vtkCommand::ModifiedEvent, this, SLOT(updateGUIOnIdle())); this->VTKConnect->Connect( this->Cue, vtkCommand::PropertyModifiedEvent, this, SLOT(updateGUIOnIdle())); } this->updateGUI(); this->setEnabled(this->Cue != nullptr); } //----------------------------------------------------------------------------- vtkSMComparativeAnimationCueProxy* pqComparativeCueWidget::cue() const { return this->Cue; } //----------------------------------------------------------------------------- bool pqComparativeCueWidget::acceptsMultipleValues() const { return (this->Cue && vtkSMPropertyHelper(this->Cue, "AnimatedElement").GetAsInt() == -1); } //----------------------------------------------------------------------------- void pqComparativeCueWidget::updateGUI() { pqLock lock(&this->InUpdateGUI, true); this->clear(); int rows = this->size().height(); int cols = this->size().width(); this->setRowCount(rows); this->setColumnCount(cols); // set header labels. QStringList vlabels, hlabels; for (int cc = 0; cc < rows; cc++) { vlabels.push_back(QString("%1").arg(cc)); } this->setVerticalHeaderLabels(vlabels); for (int cc = 0; cc < cols; cc++) { char a = 'A'; a += cc; hlabels.push_back(QString::fromLocal8Bit(&a, 1)); } this->setHorizontalHeaderLabels(hlabels); vtkSMComparativeAnimationCueProxy* acueProxy = this->cue(); if (!acueProxy) { return; } for (int colno = 0; colno < cols; colno++) { for (int rowno = 0; rowno < rows; rowno++) { QTableWidgetItem* tableitem = new QTableWidgetItem(); unsigned int numvalues = 0; double* values = acueProxy->GetValues(colno, rowno, cols, rows, numvalues); if (numvalues >= 1) { QStringList val_list; for (unsigned int cc = 0; cc < numvalues; cc++) { val_list.push_back(QString("%1").arg(values[cc])); } tableitem->setText(val_list.join(",")); } else { tableitem->setText(""); } this->setItem(rowno, colno, tableitem); } } } //----------------------------------------------------------------------------- void pqComparativeCueWidget::onCellChanged(int rowno, int colno) { if (this->InUpdateGUI) { return; } BEGIN_UNDO_SET("Parameter Changed"); QString text = this->item(rowno, colno)->text(); if (this->acceptsMultipleValues()) { QStringList parts = text.split(',', PV_QT_SKIP_EMPTY_PARTS); if (parts.size() > 0) { double* newvalues = new double[parts.size()]; double* ptr = newvalues; foreach (QString part, parts) { *ptr = QVariant(part).toDouble(); ptr++; } this->cue()->UpdateValue(colno, rowno, newvalues, static_cast<unsigned int>(parts.size())); } } else { double item_data = QVariant(text).toDouble(); this->cue()->UpdateValue(colno, rowno, item_data); } END_UNDO_SET(); Q_EMIT this->valuesChanged(); } //----------------------------------------------------------------------------- void pqComparativeCueWidget::mouseReleaseEvent(QMouseEvent* evt) { this->Superclass::mouseReleaseEvent(evt); if (this->SelectionChanged) { this->editRange(); this->SelectionChanged = false; } } //----------------------------------------------------------------------------- void pqComparativeCueWidget::editRange() { QList<QTableWidgetSelectionRange> ranges = this->selectedRanges(); if (ranges.size() != 1 || (ranges[0].columnCount() <= 1 && ranges[0].rowCount() <= 1)) { // no selection or single item selection. Nothing to do. return; } QTableWidgetSelectionRange range = ranges[0]; QDialog dialog; Ui::pqComparativeParameterRangeDialog ui; ui.setupUi(&dialog); bool csv = this->acceptsMultipleValues(); ui.multivalueHint->setVisible(csv); ui.mode->setVisible(ranges[0].rowCount() > 1 && ranges[0].columnCount() > 1); QRegExp floatNum = QRegExp("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"); QRegExp csvFloatNum = QRegExp(QString("%1(,%1)*").arg(floatNum.pattern())); ui.minValue->setValidator(new QRegExpValidator(csv ? csvFloatNum : floatNum, ui.minValue)); ui.maxValue->setValidator(new QRegExpValidator(csv ? csvFloatNum : floatNum, ui.maxValue)); if (dialog.exec() != QDialog::Accepted) { return; } int parameter_change_mode = ui.mode->currentIndex(); enum { HORZ_FIRST, VERT_FIRST, HORZ_ONLY, VERT_ONLY }; std::vector<double> minvalues = ::getValues(ui.minValue->text()); std::vector<double> maxvalues = ::getValues(ui.maxValue->text()); unsigned int numvalues = static_cast<unsigned int>(qMin(minvalues.size(), maxvalues.size())); if (numvalues == 0) { return; } BEGIN_UNDO_SET("Update Parameter Values"); vtkSMComparativeAnimationCueProxy* acueProxy = this->cue(); if (range.rowCount() == 1 && range.columnCount() == this->size().width()) { // user set an x-range. acueProxy->UpdateXRange(range.topRow(), &minvalues[0], &maxvalues[0], numvalues); } else if (range.columnCount() == 1 && range.rowCount() == this->size().height()) { // user set a y-range. acueProxy->UpdateYRange(range.leftColumn(), &minvalues[0], &maxvalues[0], numvalues); } else if (range.columnCount() == this->size().width() && range.rowCount() == this->size().height()) { // full range was covered. switch (parameter_change_mode) { case HORZ_FIRST: // user set a t-range. acueProxy->UpdateWholeRange(&minvalues[0], &maxvalues[0], numvalues); break; case VERT_FIRST: acueProxy->UpdateWholeRange(&minvalues[0], &maxvalues[0], numvalues, true); break; case HORZ_ONLY: acueProxy->UpdateXRange(-1, &minvalues[0], &maxvalues[0], numvalues); break; case VERT_ONLY: acueProxy->UpdateYRange(-1, &minvalues[0], &maxvalues[0], numvalues); break; default: qCritical("Invalid selection"); } } else { // cannot formulate user chose as a range. Set individual values. int count = range.rowCount() * range.columnCount() - 1; std::vector<double> newvalues; newvalues.resize(minvalues.size(), 0.0); for (int xx = range.leftColumn(); xx <= range.rightColumn(); xx++) { for (int yy = range.topRow(); yy <= range.bottomRow(); yy++) { for (unsigned int cc = 0; cc < numvalues; cc++) { double scale_factor = 1.0; switch (parameter_change_mode) { case HORZ_FIRST: scale_factor = (yy * range.columnCount() + xx) * 1.0 / count; break; case VERT_FIRST: scale_factor = (xx * range.rowCount() + yy) * 1.0 / count; break; case HORZ_ONLY: assert(range.columnCount() > 1); scale_factor = xx * 1.0 / (range.columnCount() - 1); break; case VERT_ONLY: assert(range.rowCount() > 1); scale_factor = yy * 1.0 / (range.rowCount() - 1); break; default: qCritical("Invalid selection"); } newvalues[cc] = minvalues[cc] + scale_factor * (maxvalues[cc] - minvalues[cc]); } acueProxy->UpdateValue(xx, yy, &newvalues[0], numvalues); } } } END_UNDO_SET(); Q_EMIT this->valuesChanged(); this->updateGUIOnIdle(); }
29.673913
100
0.599359
[ "vector" ]
3392a086dcbcd4b00e979f7b5f85edc4f0dbd1c2
1,803
cpp
C++
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fully_connected_transformation.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
1
2021-12-30T05:47:43.000Z
2021-12-30T05:47:43.000Z
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fully_connected_transformation.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
105
2020-06-04T00:23:29.000Z
2022-02-21T13:04:33.000Z
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fully_connected_transformation.cpp
v-Golubev/openvino
26936d1fbb025c503ee43fe74593ee9d7862ab15
[ "Apache-2.0" ]
4
2021-04-02T08:48:38.000Z
2021-07-01T06:59:02.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "low_precision_transformations/fully_connected_transformation.hpp" #include <memory> #include <tuple> #include <vector> #include <string> #include <ie_core.hpp> #include "common_test_utils/common_utils.hpp" #include "functional_test_utils/plugin_cache.hpp" #include "shared_test_classes/base/layer_test_utils.hpp" #include "functional_test_utils/blob_utils.hpp" #include "ngraph_functions/pass/convert_prc.hpp" #include "ngraph_functions/builders.hpp" #include "lpt_ngraph_functions/mat_mul_function.hpp" namespace LayerTestsDefinitions { std::string FullyConnectedTransformation::getTestCaseName(testing::TestParamInfo<FullyConnectedTransformationParams> obj) { ngraph::element::Type precision; MatMulShapes shapes; std::string targetDevice; ngraph::pass::low_precision::LayerTransformation::Params params; std::tie(precision, shapes, targetDevice, params) = obj.param; std::ostringstream result; result << getTestCaseNameByParams(precision, shapes.inputA, targetDevice, params) << shapes.inputB << "_" << shapes.transposeA << "_" << shapes.transposeB; return result.str(); } void FullyConnectedTransformation::SetUp() { ngraph::element::Type precision; MatMulShapes shapes; ngraph::pass::low_precision::LayerTransformation::Params params; std::tie(precision, shapes, targetDevice, params) = this->GetParam(); function = ngraph::builder::subgraph::MatMulFunction::getOriginal( precision, shapes.inputA, shapes.inputB, shapes.transposeA, shapes.transposeB); } TEST_P(FullyConnectedTransformation, CompareWithRefImpl) { Run(); }; } // namespace LayerTestsDefinitions
30.05
123
0.742651
[ "vector" ]
3393ea1dad90e0490704dbf9036c263c4d79ea71
18,448
cc
C++
examples/dynamic_registration/dynamic_registration.cc
brtnfld/legion.stan
8c320e22fb98dc62d4ef6fcf973971bb36078038
[ "Apache-2.0" ]
null
null
null
examples/dynamic_registration/dynamic_registration.cc
brtnfld/legion.stan
8c320e22fb98dc62d4ef6fcf973971bb36078038
[ "Apache-2.0" ]
null
null
null
examples/dynamic_registration/dynamic_registration.cc
brtnfld/legion.stan
8c320e22fb98dc62d4ef6fcf973971bb36078038
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 Stanford University * * 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 <cstdio> #include <cassert> #include <cstdlib> #include "legion.h" using namespace LegionRuntime::HighLevel; using namespace LegionRuntime::Accessor; using namespace LegionRuntime::Arrays; /* * In this example we illustrate how the Legion * programming model supports multiple partitions * of the same logical region and the benefits it * provides by allowing multiple views onto the * same logical region. We compute a simple 5-point * 1D stencil using the standard forumala: * f'(x) = (-f(x+2h) + 8f(x+h) - 8f(x-h) + f(x-2h))/12h * For simplicity we'll assume h=1. */ enum TaskIDs { TOP_LEVEL_TASK_ID, INIT_FIELD_TASK_ID, STENCIL_TASK_ID, CHECK_TASK_ID, }; enum FieldIDs { FID_VAL, FID_DERIV, }; // Forward declarations void init_field_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, HighLevelRuntime *runtime); void stencil_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, HighLevelRuntime *runtime); void check_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, HighLevelRuntime *runtime); void top_level_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, HighLevelRuntime *runtime) { FieldSpace fs = runtime->create_field_space(ctx); { FieldAllocator allocator = runtime->create_field_allocator(ctx, fs); allocator.allocate_field(sizeof(double),FID_VAL); allocator.allocate_field(sizeof(double),FID_DERIV); } // Make an SOA constraint and use it as the layout constraint for // all the different task variants that we are registering LayoutConstraintRegistrar layout_registrar(fs, "SOA layout"); std::vector<DimensionKind> dim_order(2); dim_order[0] = DIM_X; dim_order[1] = DIM_F; // fields go last for SOA layout_registrar.add_constraint(OrderingConstraint(dim_order, false/*contig*/)); LayoutConstraintID soa_layout_id = runtime->register_layout(layout_registrar); // Dynamically register some more tasks TaskVariantRegistrar init_registrar(INIT_FIELD_TASK_ID, true/*global*/, "cpu_init_variant"); // Add our constraints init_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)) .add_layout_constraint_set(0/*index*/, soa_layout_id); runtime->register_task_variant<init_field_task>(init_registrar); TaskVariantRegistrar stencil_registrar(STENCIL_TASK_ID, true/*global*/, "cpu_stencil_variant"); stencil_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)) .add_layout_constraint_set(0/*index*/, soa_layout_id) .add_layout_constraint_set(1/*index*/, soa_layout_id); runtime->register_task_variant<stencil_task>(stencil_registrar); TaskVariantRegistrar check_registrar(CHECK_TASK_ID, true/*global*/, "cpu_check_variant"); check_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)) .add_layout_constraint_set(0/*index*/, soa_layout_id) .add_layout_constraint_set(1/*index*/, soa_layout_id); runtime->register_task_variant<check_task>(check_registrar); // Attach semantic infos to the task names runtime->attach_name(INIT_FIELD_TASK_ID, "init task"); runtime->attach_name(STENCIL_TASK_ID, "stencil task"); runtime->attach_name(CHECK_TASK_ID, "check task"); int num_elements = 1024; int num_subregions = 4; // Check for any command line arguments { const InputArgs &command_args = HighLevelRuntime::get_input_args(); for (int i = 1; i < command_args.argc; i++) { if (!strcmp(command_args.argv[i],"-n")) num_elements = atoi(command_args.argv[++i]); if (!strcmp(command_args.argv[i],"-b")) num_subregions = atoi(command_args.argv[++i]); } } printf("Running stencil computation for %d elements...\n", num_elements); printf("Partitioning data into %d sub-regions...\n", num_subregions); // For this example we'll create a single logical region with two // fields. We'll initialize the field identified by 'FID_VAL' with // our input data and then compute the derivatives stencil values // and write them into the field identified by 'FID_DERIV'. Rect<1> elem_rect(Point<1>(0),Point<1>(num_elements-1)); IndexSpace is = runtime->create_index_space(ctx, Domain::from_rect<1>(elem_rect)); LogicalRegion stencil_lr = runtime->create_logical_region(ctx, is, fs); // Make our color_domain based on the number of subregions // that we want to create. Rect<1> color_bounds(Point<1>(0),Point<1>(num_subregions-1)); Domain color_domain = Domain::from_rect<1>(color_bounds); // In this example we need to create two partitions: one disjoint // partition for describing the output values that are going to // be computed by each sub-task that we launch and a second // aliased partition which will describe the input values needed // for performing each task. Note that for the second partition // each subregion will be a superset of its corresponding region // in the first partition, but will also require two 'ghost' cells // on each side. The need for these ghost cells means that the // subregions in the second partition will be aliased. IndexPartition disjoint_ip, ghost_ip; { const int lower_bound = num_elements/num_subregions; const int upper_bound = lower_bound+1; const int number_small = num_subregions - (num_elements % num_subregions); DomainColoring disjoint_coloring, ghost_coloring; int index = 0; // Iterate over all the colors and compute the entry // for both partitions for each color. for (int color = 0; color < num_subregions; color++) { int num_elmts = color < number_small ? lower_bound : upper_bound; assert((index+num_elmts) <= num_elements); Rect<1> subrect(Point<1>(index),Point<1>(index+num_elmts-1)); disjoint_coloring[color] = Domain::from_rect<1>(subrect); // Now compute the points assigned to this color for // the second partition. Here we need a superset of the // points that we just computed including the two additional // points on each side. We handle the edge cases by clamping // values to their minimum and maximum values. This creates // four cases of clamping both above and below, clamping below, // clamping above, and no clamping. if (index < 2) { if ((index+num_elmts+2) > num_elements) { // Clamp both Rect<1> ghost_rect(Point<1>(0),Point<1>(num_elements-1)); ghost_coloring[color] = Domain::from_rect<1>(ghost_rect); } else { // Clamp below Rect<1> ghost_rect(Point<1>(0),Point<1>(index+num_elmts+1)); ghost_coloring[color] = Domain::from_rect<1>(ghost_rect); } } else { if ((index+num_elmts+2) > num_elements) { // Clamp above Rect<1> ghost_rect(Point<1>(index-2),Point<1>(num_elements-1)); ghost_coloring[color] = Domain::from_rect<1>(ghost_rect); } else { // Normal case Rect<1> ghost_rect(Point<1>(index-2),Point<1>(index+num_elmts+1)); ghost_coloring[color] = Domain::from_rect<1>(ghost_rect); } } index += num_elmts; } // Once we've computed both of our colorings then we can // create our partitions. Note that we tell the runtime // that one is disjoint will the second one is not. disjoint_ip = runtime->create_index_partition(ctx, is, color_domain, disjoint_coloring, true/*disjoint*/); ghost_ip = runtime->create_index_partition(ctx, is, color_domain, ghost_coloring, false/*disjoint*/); } // Once we've created our index partitions, we can get the // corresponding logical partitions for the stencil_lr // logical region. LogicalPartition disjoint_lp = runtime->get_logical_partition(ctx, stencil_lr, disjoint_ip); LogicalPartition ghost_lp = runtime->get_logical_partition(ctx, stencil_lr, ghost_ip); // Our launch domain will again be isomorphic to our coloring domain. Domain launch_domain = color_domain; ArgumentMap arg_map; // First initialize the 'FID_VAL' field with some data IndexLauncher init_launcher(INIT_FIELD_TASK_ID, launch_domain, TaskArgument(NULL, 0), arg_map); init_launcher.add_region_requirement( RegionRequirement(disjoint_lp, 0/*projection ID*/, WRITE_DISCARD, EXCLUSIVE, stencil_lr)); init_launcher.add_field(0, FID_VAL); runtime->execute_index_space(ctx, init_launcher); // Now we're going to launch our stencil computation. We // specify two region requirements for the stencil task. // Each region requirement is upper bounded by one of our // two partitions. The first region requirement requests // read-only privileges on the ghost partition. Note that // because we are only requesting read-only privileges, all // of our sub-tasks in the index space launch will be // non-interfering. The second region requirement asks for // read-write privileges on the disjoint partition for // the 'FID_DERIV' field. Again this meets with the // mandate that all points in our index space task // launch be non-interfering. IndexLauncher stencil_launcher(STENCIL_TASK_ID, launch_domain, TaskArgument(&num_elements, sizeof(num_elements)), arg_map); stencil_launcher.add_region_requirement( RegionRequirement(ghost_lp, 0/*projection ID*/, READ_ONLY, EXCLUSIVE, stencil_lr)); stencil_launcher.add_field(0, FID_VAL); stencil_launcher.add_region_requirement( RegionRequirement(disjoint_lp, 0/*projection ID*/, READ_WRITE, EXCLUSIVE, stencil_lr)); stencil_launcher.add_field(1, FID_DERIV); runtime->execute_index_space(ctx, stencil_launcher); // Finally, we launch a single task to check the results. TaskLauncher check_launcher(CHECK_TASK_ID, TaskArgument(&num_elements, sizeof(num_elements))); check_launcher.add_region_requirement( RegionRequirement(stencil_lr, READ_ONLY, EXCLUSIVE, stencil_lr)); check_launcher.add_field(0, FID_VAL); check_launcher.add_region_requirement( RegionRequirement(stencil_lr, READ_ONLY, EXCLUSIVE, stencil_lr)); check_launcher.add_field(1, FID_DERIV); runtime->execute_task(ctx, check_launcher); // Clean up our region, index space, and field space runtime->destroy_logical_region(ctx, stencil_lr); runtime->destroy_field_space(ctx, fs); runtime->destroy_index_space(ctx, is); } // The standard initialize field task from earlier examples void init_field_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, HighLevelRuntime *runtime) { assert(regions.size() == 1); assert(task->regions.size() == 1); assert(task->regions[0].privilege_fields.size() == 1); FieldID fid = *(task->regions[0].privilege_fields.begin()); const int point = task->index_point.point_data[0]; printf("Initializing field %d for block %d...\n", fid, point); RegionAccessor<AccessorType::Generic, double> acc = regions[0].get_field_accessor(fid).typeify<double>(); Domain dom = runtime->get_index_space_domain(ctx, task->regions[0].region.get_index_space()); Rect<1> rect = dom.get_rect<1>(); for (GenericPointInRectIterator<1> pir(rect); pir; pir++) { acc.write(DomainPoint::from_point<1>(pir.p), drand48()); } } // Our stencil tasks is interesting because it // has both slow and fast versions depending // on whether or not its bounds have been clamped. void stencil_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, HighLevelRuntime *runtime) { assert(regions.size() == 2); assert(task->regions.size() == 2); assert(task->regions[0].privilege_fields.size() == 1); assert(task->regions[1].privilege_fields.size() == 1); assert(task->arglen == sizeof(int)); const int max_elements = *((const int*)task->args); const int point = task->index_point.point_data[0]; FieldID read_fid = *(task->regions[0].privilege_fields.begin()); FieldID write_fid = *(task->regions[1].privilege_fields.begin()); RegionAccessor<AccessorType::Generic, double> read_acc = regions[0].get_field_accessor(read_fid).typeify<double>(); RegionAccessor<AccessorType::Generic, double> write_acc = regions[1].get_field_accessor(write_fid).typeify<double>(); Domain dom = runtime->get_index_space_domain(ctx, task->regions[1].region.get_index_space()); Rect<1> rect = dom.get_rect<1>(); const DomainPoint zero = DomainPoint::from_point<1>(Point<1>(0)); const DomainPoint max = DomainPoint::from_point<1>(Point<1>(max_elements-1)); const Point<1> one(1); const Point<1> two(2); // If we are on the edges of the entire space we are // operating over, then we're going to do the slow // path which checks for clamping when necessary. // If not, then we can do the fast path without // any checks. if ((rect.lo[0] < 2) || (rect.hi[0] > (max_elements-3))) { printf("Running slow stencil path for point %d...\n", point); // Note in the slow path that there are checks which // perform clamps when necessary before reading values. for (GenericPointInRectIterator<1> pir(rect); pir; pir++) { double l2, l1, r1, r2; if (pir.p[0] < 2) l2 = read_acc.read(zero); else l2 = read_acc.read(DomainPoint::from_point<1>(pir.p-two)); if (pir.p[0] < 1) l1 = read_acc.read(zero); else l1 = read_acc.read(DomainPoint::from_point<1>(pir.p-one)); if (pir.p[0] > (max_elements-2)) r1 = read_acc.read(max); else r1 = read_acc.read(DomainPoint::from_point<1>(pir.p+one)); if (pir.p[0] > (max_elements-3)) r2 = read_acc.read(max); else r2 = read_acc.read(DomainPoint::from_point<1>(pir.p+two)); double result = (-l2 + 8.0*l1 - 8.0*r1 + r2) / 12.0; write_acc.write(DomainPoint::from_point<1>(pir.p), result); } } else { printf("Running fast stencil path for point %d...\n", point); // In the fast path, we don't need any checks for (GenericPointInRectIterator<1> pir(rect); pir; pir++) { double l2 = read_acc.read(DomainPoint::from_point<1>(pir.p-two)); double l1 = read_acc.read(DomainPoint::from_point<1>(pir.p-one)); double r1 = read_acc.read(DomainPoint::from_point<1>(pir.p+one)); double r2 = read_acc.read(DomainPoint::from_point<1>(pir.p+two)); double result = (-l2 + 8.0*l1 - 8.0*r1 + r2) / 12.0; write_acc.write(DomainPoint::from_point<1>(pir.p), result); } } } void check_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, HighLevelRuntime *runtime) { assert(regions.size() == 2); assert(task->regions.size() == 2); assert(task->regions[0].privilege_fields.size() == 1); assert(task->regions[1].privilege_fields.size() == 1); assert(task->arglen == sizeof(int)); const int max_elements = *((const int*)task->args); FieldID src_fid = *(task->regions[0].privilege_fields.begin()); FieldID dst_fid = *(task->regions[1].privilege_fields.begin()); RegionAccessor<AccessorType::Generic, double> src_acc = regions[0].get_field_accessor(src_fid).typeify<double>(); RegionAccessor<AccessorType::Generic, double> dst_acc = regions[1].get_field_accessor(dst_fid).typeify<double>(); Domain dom = runtime->get_index_space_domain(ctx, task->regions[1].region.get_index_space()); Rect<1> rect = dom.get_rect<1>(); const DomainPoint zero = DomainPoint::from_point<1>(Point<1>(0)); const DomainPoint max = DomainPoint::from_point<1>(Point<1>(max_elements-1)); const Point<1> one(1); const Point<1> two(2); // This is the checking task so we can just do the slow path bool all_passed = true; for (GenericPointInRectIterator<1> pir(rect); pir; pir++) { double l2, l1, r1, r2; if (pir.p[0] < 2) l2 = src_acc.read(zero); else l2 = src_acc.read(DomainPoint::from_point<1>(pir.p-two)); if (pir.p[0] < 1) l1 = src_acc.read(zero); else l1 = src_acc.read(DomainPoint::from_point<1>(pir.p-one)); if (pir.p[0] > (max_elements-2)) r1 = src_acc.read(max); else r1 = src_acc.read(DomainPoint::from_point<1>(pir.p+one)); if (pir.p[0] > (max_elements-3)) r2 = src_acc.read(max); else r2 = src_acc.read(DomainPoint::from_point<1>(pir.p+two)); double expected = (-l2 + 8.0*l1 - 8.0*r1 + r2) / 12.0; double received = dst_acc.read(DomainPoint::from_point<1>(pir.p)); // Probably shouldn't bitwise compare floating point // numbers but the order of operations are the same so they // should be bitwise equal. if (expected != received) all_passed = false; } if (all_passed) printf("SUCCESS!\n"); else printf("FAILURE!\n"); } int main(int argc, char **argv) { HighLevelRuntime::set_top_level_task_id(TOP_LEVEL_TASK_ID); // We'll only register our top-level task here TaskVariantRegistrar registrar(TOP_LEVEL_TASK_ID, true/*global*/, "top_level_variant"); registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); Runtime::preregister_task_variant<top_level_task>(registrar,"top_level_task"); return HighLevelRuntime::start(argc, argv); }
40.45614
82
0.681158
[ "vector", "model" ]
339414e9066faf45a68f65321dbc821cb7d11cb7
30,956
cpp
C++
tb_jun/src/underlag/global.cpp
ligatos/tords-workspace-2020
11eba9fec3c85600afaf515468f74274f7cb5a68
[ "Apache-2.0" ]
null
null
null
tb_jun/src/underlag/global.cpp
ligatos/tords-workspace-2020
11eba9fec3c85600afaf515468f74274f7cb5a68
[ "Apache-2.0" ]
null
null
null
tb_jun/src/underlag/global.cpp
ligatos/tords-workspace-2020
11eba9fec3c85600afaf515468f74274f7cb5a68
[ "Apache-2.0" ]
null
null
null
#include <ros/ros.h> #include <octomap_msgs/conversions.h> #include <octomap_msgs/Octomap.h> #include <octomap/octomap.h> #include <octomap/OcTree.h> #include <octomap/OcTreeBase.h> #include <octomap/octomap_types.h> #include <tf/transform_datatypes.h> #include <dynamicEDT3D/dynamicEDTOctomap.h> #include <chrono> #include <std_msgs/UInt8.h> #include <std_msgs/Bool.h> #include <std_msgs/Float64.h> #include <std_msgs/Float32.h> #include <std_msgs/String.h> #include <sensor_msgs/LaserScan.h> #include <geometry_msgs/TransformStamped.h> #include <geometry_msgs/Twist.h> #include <tf2/LinearMath/Quaternion.h> #include <tf2_ros/transform_listener.h> #include "tf2_ros/message_filter.h" #include "tf2_ros/transform_broadcaster.h" #include "tf2_geometry_msgs/tf2_geometry_msgs.h" #include <nav_msgs/Path.h> #include <nav_msgs/Odometry.h> #include <nav_msgs/OccupancyGrid.h> #include <map_msgs/OccupancyGridUpdate.h> #include <std_msgs/UInt8.h> #include <visualization_msgs/MarkerArray.h> #include <geometry_msgs/PolygonStamped.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/Point32.h> #include <eigen3/Eigen/Core> #include <geometry_msgs/Vector3Stamped.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <image_transport/image_transport.h> using namespace octomap; using namespace std; shared_ptr<DynamicEDTOctomap> edf_ptr; AbstractOcTree* abs_octree; shared_ptr<OcTree> octree; ros::Publisher img_pub; bool got_map,par_inspect_top; double par_num_levels,par_maprad,par_hiabs,par_loabs,par_lookahead_distance,par_eval_maxrange,par_grid_size,par_zjump,par_area_sidelength,par_takeoffaltitude; tf2_ros::Buffer tfBuffer; int xmin,ymin,zmin,xmax,ymax,zmax,range_x,range_y,range_z,zmin_global,zmax_global; geometry_msgs::PointStamped closest_obstacle,closest_obstacle_plane; float closest_obstacle_plane_dist,closest_obstacle_dist; geometry_msgs::Point pos; geometry_msgs::PointStamped last_pos_check; geometry_msgs::Point bbmin_custom,bbmax_custom,bbmin_octree,bbmax_octree; nav_msgs::Path path_visited_tar01; ros::Publisher pub_tarpose,visited_path_pub,invoke_pub,targetalt_pub; geometry_msgs::PoseStamped last_pose,last_target,target; std_msgs::Float64 cmdarm_msg; std_msgs::Float64 target_alt; float area_range,delta_z; std_msgs::UInt8 state_msg; cv::Mat mapimg(1000,1000,CV_8UC3,cv::Scalar(0, 0, 0)); //create image, set encoding and size, init pixels to default val cv::Mat mapimg_copy(1000,1000,CV_8UC3,cv::Scalar(0, 0, 0)); //create image, set encoding and size, init pixels to default val bool use_mono = true;; float zneg = -10; float zpos = 100; float collision_radius = 1.1; std::string par_workdir; bool idle,par_live; ros::Time last_twist,last_rosinfo; cv::Mat img(1000,1000,CV_8UC3,cv::Scalar(0, 0, 0)); //create image, set encoding and size, init pixels to default val cv::Mat img_copy(1000,1000,CV_8UC3,cv::Scalar(0, 0, 0)); //create image, set encoding and size, init pixels to default val float pos_yaw; bool get_initialscan_from_scan,need_candidates,need_visited; int last_i; nav_msgs::Odometry odom; ros::Time last_scan; std::vector<int> z_lvls; int zlvl; // Define Infinite (Using INT_MAX caused overflow problems) std::vector<geometry_msgs::PolygonStamped> objects_polys; std::vector<geometry_msgs::PolygonStamped> cleared_polys; std::vector<geometry_msgs::PolygonStamped> polygon_grids; std::vector<geometry_msgs::PoseStamped> targetcmds_sent; std::vector<geometry_msgs::Point> grids_centroids; std::vector<std::vector<int>> grids_at_ranges; std::vector<nav_msgs::Path> paths_cand_at_lvl; std::vector<nav_msgs::Path> paths_vstd_at_lvl; std::vector<std::vector<int>> xy; cv::Scalar visited_color,candidate_color,target_color,grid_color,obstacle_color,building_color,cleared_color,path_color; std::vector<int> grids_in_range; geometry_msgs::Point tar0,tar1,tar_01_normalized; int area_sidelength,grid_sidelength,num_gridsprside; sensor_msgs::LaserScan scan_copy; double get_shortest(double target_hdng,double actual_hdng){ double a = target_hdng - actual_hdng; if(a > M_PI)a -= M_PI*2; else if(a < -M_PI)a += M_PI*2; return a; } void octomap_callback(const octomap_msgs::Octomap& msg){ abs_octree=octomap_msgs::fullMsgToMap(msg); octree.reset(dynamic_cast<octomap::OcTree*>(abs_octree)); got_map = true; } float y2r(float y, float rows,float res){ return (rows / 2 - y / res); } float x2c(float x, float cols,float res){ return (x / res + cols/2); } int x2gx(float x){ return int(round((x+area_sidelength/2) / grid_sidelength)); } int y2gy(float y){ return int(round((y+area_sidelength/2) / grid_sidelength)); } int gxgy2gn(int gx, int gy){ return num_gridsprside * gy + gx; } geometry_msgs::Point gn2gxgy(int gn){ int gy = gn / num_gridsprside; int gx = gn - gy * num_gridsprside; geometry_msgs::Point pout; pout.x = gx; pout.y = gy; return pout; } int xy2gn(geometry_msgs::Point pnt){ int gx = x2gx(pnt.x); int gy = y2gy(pnt.y); ROS_INFO("g_x %i, y: %i",gx,gy); return gxgy2gn(gx,gy); } int xy2gn32(geometry_msgs::Point32 pnt){ int gx = x2gx(pnt.x); int gy = y2gy(pnt.y); return gxgy2gn(gx,gy); } int r2y(float r, float rows,float res){ return int((rows / 2 - r) * res); } int c2x(float c, float cols,float res){ return int((c - cols / 2) * res); } float get_dst2d(geometry_msgs::Point p1, geometry_msgs::Point p2){ return(sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2))); } float get_dst3d(geometry_msgs::Point p1, geometry_msgs::Point p2){ return(sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2)+pow(p1.z-p2.z,2))); } float get_hdng(geometry_msgs::Point p1,geometry_msgs::Point p0){ float dx = p1.x - p0.x; float dy = p1.y - p0.y; return atan2(dy,dx); } float get_hdng32(geometry_msgs::Point32 p1,geometry_msgs::Point32 p0){ float dx = p1.x - p0.x; float dy = p1.y - p0.y; return atan2(dy,dx); } cv::Point pnt322cv(geometry_msgs::Point32 pin){ int c = x2c(pin.x,mapimg.cols,1); int r = y2r(pin.y,mapimg.rows,1); return cv::Point(c,r); } cv::Point pnt2cv(geometry_msgs::Point pin){ int c = x2c(pin.x,mapimg.cols,1); int r = y2r(pin.y,mapimg.rows,1); return cv::Point(c,r); } double constrainAngle(double x){ if(x > M_PI) return (x - M_PI*2); else if(x < -M_PI) return (x + M_PI*2); else return x; } bool in_poly(geometry_msgs::PolygonStamped polyin, float x, float y){ int cross = 0; geometry_msgs::Point point; point.x = x; point.y = y; for(int i = 0,j = polyin.polygon.points.size()-1; i < polyin.polygon.points.size(); j=i++){// for (int i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) { if ( ((polyin.polygon.points[i].y > point.y) != (polyin.polygon.points[j].y > point.y)) && (point.x < (polyin.polygon.points[j].x - polyin.polygon.points[i].x) * (point.y - polyin.polygon.points[i].y) / (polyin.polygon.points[j].y - polyin.polygon.points[i].y) + polyin.polygon.points[i].x) ) { cross++; } } return bool(cross % 2); } bool update_edto(geometry_msgs::Point midpoint,float collision_radius,float maprad,float z0,float z1,bool unknownAsOccupied,bool sides){ if(!got_map) return false; int zmid = (z1+z0)/2; octree.get()->getMetricMin(bbmin_octree.x,bbmin_octree.y,bbmin_octree.z); octree.get()->getMetricMax(bbmax_octree.x,bbmax_octree.y,bbmax_octree.z); zmin_global = int(round(bbmin_octree.z)); zmax_global = int(round(bbmax_octree.z)); z0 = fmin(z0,bbmax_octree.z-2); z1 = fmin(z1,bbmax_octree.z); bbmin_custom.x = midpoint.x-maprad; bbmin_custom.y = midpoint.y-maprad; bbmin_custom.z = z0; bbmax_custom.x = midpoint.x+maprad; bbmax_custom.y = midpoint.y+maprad; bbmax_custom.z = z1; float zmin_touse = fmax(bbmin_custom.z,bbmin_octree.z); float zmax_touse = fmin(bbmax_custom.z,bbmax_octree.z); if(zmax_touse < zmin_touse){ zmax_touse = fmax(bbmin_custom.z,bbmin_octree.z); zmin_touse = fmin(bbmax_custom.z,bbmax_octree.z); } octomap::point3d boundary_min(fmax(bbmin_custom.x,bbmin_octree.x),fmax(bbmin_custom.y,bbmin_octree.y),zmin_touse); octomap::point3d boundary_max(fmin(bbmax_custom.x,bbmax_octree.x),fmin(bbmax_custom.y,bbmax_octree.y),zmax_touse); edf_ptr.reset (new DynamicEDTOctomap(collision_radius,octree.get(), boundary_min, boundary_max, unknownAsOccupied)); edf_ptr.get()->update(); xmin = int(round(boundary_min.x()))+1; ymin = int(round(boundary_min.y()))+1; zmin = int(round(boundary_min.z())); xmax = int(round(boundary_max.x()))-1; ymax = int(round(boundary_max.y()))-1; zmax = int(round(boundary_max.z())); range_x = xmax - xmin; range_y = ymax - ymin; range_z = zmax - zmin; int vol = range_x*range_y*range_z; if(vol <= 0){ ROS_INFO("FAILED update_edto FAILED: xmin: %i, ymin: %i, zmin: %i, xmax: %i, ymax: %i, zmax: %i, range_x: %i, range_y: %i, range_z: %i ",xmin,ymin,zmin,xmax,ymax,zmax,range_x,range_y,range_z); return false; } return true; } bool check_if_inside_bb(std::vector<geometry_msgs::Point> l0l1,geometry_msgs::Point p){ if(l0l1[0].x < p.x && l0l1[0].y < p.y && l0l1[1].x > p.x && l0l1[1].y > p.y) return true; else return false; } geometry_msgs::Point32 get_poly_centroid(geometry_msgs::PolygonStamped polyin){ geometry_msgs::Point32 centroid; double signedArea = 0.0; double x0 = 0.0; // Current vertex X double y0 = 0.0; // Current vertex Y double x1 = 0.0; // Next vertex X double y1 = 0.0; // Next vertex Y double a = 0.0; // Partial signed area // For all vertices except last int i=0; if(polyin.polygon.points.size() < 2){ return centroid; } for (i=0; i<polyin.polygon.points.size()-1; ++i) { x0 = polyin.polygon.points[i].x; y0 = polyin.polygon.points[i].y; x1 = polyin.polygon.points[i+1].x; y1 = polyin.polygon.points[i+1].y; a = x0*y1 - x1*y0; signedArea += a; centroid.x += (x0 + x1)*a; centroid.y += (y0 + y1)*a; } // Do last vertex separately to avoid performing an expensive // modulus operation in each iteration. x0 = polyin.polygon.points[i].x; y0 = polyin.polygon.points[i].y; x1 = polyin.polygon.points[0].x; y1 = polyin.polygon.points[0].y; a = x0*y1 - x1*y0; signedArea += a; centroid.x += (x0 + x1)*a; centroid.y += (y0 + y1)*a; signedArea *= 0.5; centroid.x /= (6.0*signedArea); centroid.y /= (6.0*signedArea); return centroid; } geometry_msgs::TransformStamped get_tf(std::string from, std::string to){ geometry_msgs::TransformStamped transformStamped; try{ transformStamped = tfBuffer.lookupTransform(from,to, ros::Time(0)); } catch (tf2::TransformException &ex) { ROS_WARN("%s",ex.what()); ros::Duration(1.0).sleep(); } return transformStamped; } void get_zdown(){ octomap::point3d closestObst; for(int y = ymin; y < ymax; y++){ for(int x = xmin; x < xmax; x++){ int z = zmax; float dst = 1.1; while(dst > (1.1-1) && z > bbmin_octree.z){ octomap::point3d p(x,y,z); edf_ptr.get()->getDistanceAndClosestObstacle(p,dst,closestObst); z--; } int r = y2r(y,mapimg.rows,1); int c = x2c(x,mapimg.cols,1); img.at<cv::Vec3b>(r,c)[2] = (z - bbmin_octree.z); } } ROS_INFO("get_zdown complete"); } geometry_msgs::PolygonStamped poly_addpoint(geometry_msgs::PolygonStamped polyin,geometry_msgs::Point point_to_add){ geometry_msgs::PolygonStamped polyout; polyout.header = polyin.header; geometry_msgs::Point32 pin,centroid; pin.x = point_to_add.x; pin.y = point_to_add.y; pin.z = point_to_add.z; int len = polyin.polygon.points.size(); if(len < 3){ polyin.polygon.points.push_back(pin); return polyin; } centroid = get_poly_centroid(polyin); float centroid_hdng = get_hdng32(centroid,pin); float last_hdng = get_hdng32(centroid,polyin.polygon.points[0]); int index; for(int i = 1; i < len+1; i++){ float hdng = get_hdng32(centroid,polyin.polygon.points[i]); if(last_hdng < centroid_hdng && hdng > centroid_hdng){ polyout.polygon.points.push_back(pin); index = i; i++; ROS_INFO("Polypoint added: %i",i); } else polyout.polygon.points.push_back(polyin.polygon.points[i]); } return polyout; } geometry_msgs::PolygonStamped createpoly_square(geometry_msgs::Point pin, float sides){ geometry_msgs::PolygonStamped poly; poly.polygon.points.resize(5); poly.header.frame_id = "map"; poly.polygon.points[0].x = round(pin.x + sides/2); poly.polygon.points[0].y = round(pin.y + sides/2); poly.polygon.points[1].x = round(pin.x - sides/2); poly.polygon.points[1].y = round(pin.y + sides/2); poly.polygon.points[2].x = round(pin.x - sides/2); poly.polygon.points[2].y = round(pin.y - sides/2); poly.polygon.points[3].x = round(pin.x + sides/2); poly.polygon.points[3].y = round(pin.y - sides/2); poly.polygon.points[4] = poly.polygon.points[0]; // ROS_INFO("x %.2f y %.2f x %.2f y %.2f x %.2f y %.2f x %.2f y %.2f x %.2f y %.2f",poly.polygon.points[0].x,poly.polygon.points[0].y,poly.polygon.points[1].x,poly.polygon.points[1].y,poly.polygon.points[2].x,poly.polygon.points[2].y,poly.polygon.points[3].x,poly.polygon.points[3].y,poly.polygon.points[4].x,poly.polygon.points[4].y); return poly; } void draw_rectangle(geometry_msgs::Point p0,geometry_msgs::Point p1,cv::Scalar color,bool copy){ if(copy) cv::rectangle(img_copy, pnt2cv(p0),pnt2cv(p1),color,1,8,0); else cv::rectangle(img, pnt2cv(p0),pnt2cv(p1),color,1,8,0); } void draw_circle(geometry_msgs::Point pnt,float size,cv::Scalar color,bool copy){ if(copy) cv::circle(img_copy,pnt2cv(pnt),int(round(size)),color,1); else cv::circle(img,pnt2cv(pnt),int(round(size)),color,1); } void draw_line(geometry_msgs::Point pnt0,geometry_msgs::Point pnt1, cv::Scalar color,bool copy){ if(copy) cv::line (img_copy, pnt2cv(pnt0), pnt2cv(pnt1), color,1,cv::LINE_8,0); else cv::line (img, pnt2cv(pnt0), pnt2cv(pnt1), color,1,cv::LINE_8,0); } void draw_rectangle32(geometry_msgs::Point32 p0,geometry_msgs::Point32 p1,cv::Scalar color,bool copy){ if(copy) cv::rectangle(img_copy, pnt322cv(p0),pnt322cv(p1),color,1,8,0); else cv::rectangle(img, pnt322cv(p0),pnt322cv(p1),color,1,8,0); } void draw_circle32(geometry_msgs::Point32 pnt,int size,cv::Scalar color,bool copy){ if(copy) cv::circle(img_copy,pnt322cv(pnt),size,color,1); else cv::circle(img,pnt322cv(pnt),size,color,1); } void draw_line32(geometry_msgs::Point32 pnt0,geometry_msgs::Point32 pnt1, cv::Scalar color,bool copy){ if(copy) cv::line (img_copy, pnt322cv(pnt0), pnt322cv(pnt1), color,1,cv::LINE_8,0); else cv::line (img, pnt322cv(pnt0), pnt322cv(pnt1), color,1,cv::LINE_8,0); } void colorize_grid_dst(int i,cv::Scalar color){ if(polygon_grids.size() < i) return; int rmin = y2r(polygon_grids[i].polygon.points[1].y,img.rows,1); int cmin = x2c(polygon_grids[i].polygon.points[1].x,img.cols,1); int rmax = y2r(polygon_grids[i].polygon.points[3].y,img.rows,1); int cmax = x2c(polygon_grids[i].polygon.points[3].x,img.cols,1); for(int r = rmin+1; r < rmax-1; r++){ for(int c = cmin+1; c < cmax-1; c++){ img.at<cv::Vec3b>(r,c)[0] = color[0]; img.at<cv::Vec3b>(r,c)[1] = color[1]; img.at<cv::Vec3b>(r,c)[2] = color[2]; } } } void draw_polygon(geometry_msgs::PolygonStamped polyin,cv::Scalar color,bool copy){ ROS_INFO("draw_polygond"); if(polyin.polygon.points.size() > 2){ for(int i = 0; i < polyin.polygon.points.size()-1; i++){ draw_line32(polyin.polygon.points[i],polyin.polygon.points[i+1],color,copy); } } ROS_INFO("PolygonToDraw: %i pints",polyin.polygon.points.size()); } void draw_pose2d(geometry_msgs::Point p0,float size,cv::Scalar color,bool copy,double yaw){ geometry_msgs::Point p1; p1.x = p0.x + size*2 * cos(yaw); p1.y = p0.y + size*2 * sin(yaw); draw_circle(p0,size,color,copy); draw_line(p0,p1,color,copy); } void draw_grid(int i,cv::Scalar color,bool copy){ draw_rectangle32(polygon_grids[i].polygon.points[1],polygon_grids[i].polygon.points[3],color,copy); } void draw_grids(std::vector<int> grids_to_draw,cv::Scalar color,bool copy){ if(grids_to_draw.size() < 2) return; for(int i = 0; i < grids_to_draw.size()-1; i++){ draw_rectangle32(polygon_grids[grids_to_draw[i]].polygon.points[1],polygon_grids[grids_to_draw[i]].polygon.points[3],color,copy); } ROS_INFO("GridsToDraw: %i",grids_to_draw.size()); } std::vector<int> grids_in_poly_safe(geometry_msgs::PolygonStamped polyin){ std::vector<int> grids_out; if(polyin.polygon.points.size() == 0) return grids_out; for(int i = 0; i < grids_centroids.size(); i++){ int not_in_poly = 0; for(int k = 0; k < polygon_grids[i].polygon.points.size(); k++){ if(!in_poly(polyin,polygon_grids[i].polygon.points[k].x,polygon_grids[i].polygon.points[k].y)){ not_in_poly++; } } if(not_in_poly == 0) grids_out.push_back(i); } if(grids_out.size() > 2) ROS_INFO("GridsInPoly: %i -> %i, total %i points from %i points large poly",grids_out.size(),grids_out[0],grids_out[grids_out.size()-1],polyin.polygon.points.size()); return grids_out; } std::vector<int> grids_in_poly(geometry_msgs::PolygonStamped polyin){ std::vector<int> grids_out; if(polyin.polygon.points.size() == 0) return grids_out; for(int i = 0; i < grids_centroids.size(); i++){ if(in_poly(polyin,grids_centroids[i].x,grids_centroids[i].y)) grids_out.push_back(i); } if(grids_out.size() > 2) ROS_INFO("GridsInPoly: %i -> %i, total %i points from %i points large poly",grids_out.size(),grids_out[0],grids_out[grids_out.size()-1],polyin.polygon.points.size()); return grids_out; } std::vector<int> grids_on_poly(geometry_msgs::PolygonStamped polyin){ std::vector<int> grids_out; if(polyin.polygon.points.size() == 0) return grids_out; for(int i = 0; i < grids_centroids.size(); i++){ if(in_poly(polyin,grids_centroids[i].x,grids_centroids[i].y)) grids_out.push_back(i); } if(grids_out.size() > 2) ROS_INFO("GridsInPoly: %i -> %i, total %i points from %i points large poly",grids_out.size(),grids_out[0],grids_out[grids_out.size()-1],polyin.polygon.points.size()); return grids_out; } void create_polygon_grids(){ geometry_msgs::Point p; grids_centroids.resize(0); polygon_grids.resize(0); for(int y = 0; y < num_gridsprside; y++){ for(int x = 0; x < num_gridsprside; x++){ p.x = x * grid_sidelength - area_sidelength / 2 + grid_sidelength/2; p.y = y * grid_sidelength - area_sidelength / 2 + grid_sidelength/2; if(p.x > xmin && p.y > ymin && p.x < xmax && p.y < ymax){ grids_centroids.push_back(p); polygon_grids.push_back(createpoly_square(p,grid_sidelength)); } } } } geometry_msgs::PolygonStamped polyCircle(geometry_msgs::Point centroid,float radius, int resolution){ geometry_msgs::PolygonStamped polyout; polyout.header.frame_id = "map"; for(int i = 0; i < resolution; i++){ geometry_msgs::Point32 p; p.x = centroid.x + radius*cos(-M_PI + (M_PI*2/resolution)*i); p.y = centroid.y + radius*sin(-M_PI + (M_PI*2/resolution)*i); polyout.polygon.points.push_back(p); } return polyout; } int get_gridnum(float x, float y){ for(int i = 0; i < grids_centroids.size(); i++){ if(x <= polygon_grids[i].polygon.points[0].x && x >= polygon_grids[i].polygon.points[2].x && y <= polygon_grids[i].polygon.points[0].y && y >= polygon_grids[i].polygon.points[2].y) return i; } ROS_INFO("ERROR; NOT RETURNED GRIDNUMBER FOR POINT %.2f %.2f",x,y); return 0; } geometry_msgs::PolygonStamped scan2poly(sensor_msgs::LaserScan scan,geometry_msgs::Point midpoint){ geometry_msgs::PolygonStamped polyout; polyout.header.frame_id = "map"; polyout.polygon.points.resize(scan.ranges.size()); for(int i = 0; i < scan.ranges.size();i++){ geometry_msgs::Point32 p0,p1,ps; float r = fmin(scan.ranges[i],scan.range_max); float a = constrainAngle(scan.angle_increment * i + scan.angle_min + pos_yaw); polyout.polygon.points[i].x = round(midpoint.x) + r * cos(a); polyout.polygon.points[i].y = round(midpoint.y) + r * sin(a); polyout.polygon.points[i].z = midpoint.z; } return polyout; } void scan_cb(const sensor_msgs::LaserScan::ConstPtr& scan){ scan_copy = *scan; } void scanproc(bool copy){ ROS_INFO("Scan cb %i",scan_copy.ranges.size()); geometry_msgs::Point empty; std::vector<int> possible_grids; std::vector<int> hits; std::vector<int> grids; geometry_msgs::Point32 p0,p1,ps; for(int i = 0; i < scan_copy.ranges.size(); i++){ if(scan_copy.ranges[i] < scan_copy.range_max){ float r = scan_copy.ranges[i]; float a = constrainAngle(scan_copy.angle_increment * i + scan_copy.angle_min + pos_yaw); p0.x = round(pos.x) + r * cos(a); p0.y = round(pos.y) + r * sin(a); int ii = get_gridnum(p0.x,p0.y); draw_grid(ii,obstacle_color,copy); hits.push_back(ii); } }/* sort(hits.begin(),hits.end()); int hitcount = 0; if(hits.size() > 0){ int current_number = hits[0]; for(int i = 0; i < hits.size(); i++){ if(current_number != hits[i]){ hitcount = 0; current_number = hits[i]; } else hitcount++; } } std::vector<int> grids_to_draw; for(int i = 0; i < hits.size(); i++){ if(hitcount > 5){ ROS_INFO("Hits at gridnumber: %i",hits[i]); grids_to_draw.push_back(hits[i]); } } if(grids_to_draw.size() > 1) draw_grids(grids_to_draw,obstacle_color); */ } geometry_msgs::Point get_normalized_dst(geometry_msgs::Point actual,geometry_msgs::Point setpoint){ Eigen::Vector3f pnt1_vec(actual.x,actual.y,actual.z); Eigen::Vector3f pnt2_vec(setpoint.x,setpoint.y,setpoint.z); Eigen::Vector3f cur_vec = pnt1_vec; float error_length = (pnt2_vec - pnt1_vec).norm(); Eigen::Vector3f stride_vec; stride_vec = (pnt2_vec - pnt1_vec).normalized(); geometry_msgs::Point res; res.x = stride_vec.x(); res.y = stride_vec.y(); res.z = stride_vec.z(); return res; } std::vector<int> get_points_not_in_both(std::vector<int> v1,std::vector<int> v2){ std::vector<int> vout; for(int i = 0; i < v1.size(); i++){ bool in_both; for(int k = 0; k < v2.size(); k++){ if(v1[i] == v2[k]){ in_both = true; } } if(!in_both) vout.push_back(v1[i]); } return vout; } void draw_grids_at_ranges(geometry_msgs::Point midpoint){ ROS_INFO("draw_grids_at_ranges"); for(int i = 0; i < par_eval_maxrange/par_grid_size; i++){ //grids_at_ranges_ramge.push_back(par_grid_size*(i+1)); grids_at_ranges.push_back(get_points_not_in_both(grids_in_poly(polyCircle( midpoint,par_grid_size*i,8)),grids_in_poly(polyCircle( midpoint,par_grid_size*i+1,8)))); } for(int i = 0; i < grids_at_ranges.size(); i++){ for(int k = 0; k < grids_at_ranges[i].size(); k++){ draw_grids(grids_at_ranges[i],cv::Scalar(20,20,100),true); } } } void draw_path(nav_msgs::Path pathin,int size, cv::Scalar color,bool copy, bool draw_lines){ for(int k = 0; k < pathin.poses.size(); k++){ if(k < pathin.poses.size()-1 && draw_lines) draw_line(pathin.poses[k].pose.position,pathin.poses[k+1].pose.position,color,copy); draw_pose2d(pathin.poses[k].pose.position,2,target_color,true, tf::getYaw(pathin.poses[k].pose.orientation)); } } void draw_path_vstdcnd(int zn0,int zn1,bool copy){ cv::Scalar color_visited; cv::Scalar color_candidates; color_visited = visited_color; color_candidates = candidate_color; for(int i = zn0; i < zn1; i++){ if(paths_cand_at_lvl[i].poses.size() > 1){ color_visited[2] = i * 10; draw_path(paths_cand_at_lvl[i],2,candidate_color,copy,false); } if(paths_vstd_at_lvl[i].poses.size() > 1){ color_candidates[0] = i * 10; draw_path(paths_vstd_at_lvl[i],3,visited_color,copy,true); } } } void get_zdown_grids(bool copy){ octomap::point3d closestObst; int gn = 0; for(int i = 0; i < grids_centroids.size(); i++){ geometry_msgs::Point xy; xy = grids_centroids[i]; if(xy.x > xmin && xy.y > ymin && xy.x < xmax && xy.y < ymax){ int z = zmax; float dst = 5.0; while(dst > 3 && z > zmin){ octomap::point3d p(grids_centroids[i].x,grids_centroids[i].y,z); edf_ptr.get()->getDistanceAndClosestObstacle(p,dst,closestObst); z--; } int colout = z - zmin; if(z < pos.z) draw_circle(grids_centroids[i],2,cv::Scalar(0,colout*5,0),copy); else draw_circle(grids_centroids[i],2,cv::Scalar(0,colout*5,250),copy); } } // ROS_INFO("get_zdown_grids complete"); } void path01_cb(const nav_msgs::Path::ConstPtr& msg){ ROS_INFO("Pathvstd callback %i",msg->poses.size()); if(msg->poses.size() < path_visited_tar01.poses.size()){ for(int i = 0; i < path_visited_tar01.poses.size(); i++){ paths_vstd_at_lvl[zlvl].poses.push_back(path_visited_tar01.poses[i]); } } path_visited_tar01 = *msg; } void pathcandupd_cb(const nav_msgs::Path::ConstPtr& msg){ ROS_INFO("Pathcand callback %i",msg->poses.size()); if(msg->poses.size() > 0){ for(int i = 0; i < msg->poses.size(); i++){ int zlvl_in = round(msg->poses[i].pose.position.z / par_zjump) + 3; paths_cand_at_lvl[zlvl_in].poses.push_back(msg->poses[i]); } } } void get_and_draw_targets(){ float circle_rad = 2; if(targetcmds_sent.size() > 2){ for(int i = 0; i < targetcmds_sent.size()-2; i++){ draw_line(targetcmds_sent[i+1].pose.position,targetcmds_sent[i].pose.position,target_color,true); draw_pose2d(target.pose.position,circle_rad,target_color,true,tf::getYaw(targetcmds_sent[i].pose.orientation)); } } } void cmd_cb(const geometry_msgs::Point::ConstPtr& msg){ cv::Scalar target_color_alt; target_color_alt = target_color; target_color_alt[0] = msg->z * 5; draw_line(target.pose.position,*msg,target_color,false); last_target = target; target.pose.position = *msg; targetcmds_sent.push_back(target); get_and_draw_targets(); // img.copyTo(img_copy) /* get_normalized_dst(tar0,tar) d.x = posein.pose.position.x - t.x; d.y = posein.pose.position.y - t.y; d.z = posein.pose.position.z - t.z; t.x = posein.pose.position.x; t.y = posein.pose.position.y; t.z = posein.pose.position.z; tyaw = tf::getYaw(posein.pose.orientation); t_yaw_0 = t_yaw_1; t_hdng_0 = t_hdng_1; t_dst_0 = t_dst_1; geometry_msgs::PoseStamped last_target; tardelta_norm = get_normalized_dst(tar,msg->pose.position); t_dst = get_dst3d(tar,msg->pose.position); t_hdng = get_hdng(tar,msg->pose.position); */ ROS_INFO("Resetting image"); } void zlvl_cb(const std_msgs::UInt8::ConstPtr& msg){ zlvl = msg->data; } void define_colors(){ visited_color[0] = 150; visited_color[1] = 50; visited_color[2] = 0; target_color[0] = 0; target_color[1] = 100; target_color[2] = 150; candidate_color[0] = 100; candidate_color[1] = 100; candidate_color[2] = 0; grid_color[0] = 0; grid_color[1] = 20; grid_color[2] = 0; building_color[0] = 0; building_color[1] = 0; building_color[2] = 100; obstacle_color[0] = 0; obstacle_color[1] = 0; obstacle_color[2] = 150; cleared_color[0] = 100; cleared_color[1] = 150; cleared_color[2] = 0; path_color[0] = 150; path_color[1] = 150; path_color[2] = 150; } int main(int argc, char** argv) { ros::init(argc, argv, "tb_global_node"); ros::NodeHandle nh; ros::NodeHandle private_nh("~"); private_nh.getParam("workdir_path", par_workdir); private_nh.param("map_sidelength_min", par_maprad, 50.0); private_nh.param("max_sidelength", par_area_sidelength, 1000.0); private_nh.param("par_zjump", par_zjump, 3.0);//*2.0); private_nh.param("grid_size", par_grid_size, 5.0); private_nh.param("lookahead_distance", par_lookahead_distance, 50.0); private_nh.param("par_eval_maxrange", par_eval_maxrange, 25.0); private_nh.param("inspect_top", par_inspect_top, false); tf2_ros::TransformListener tf2_listener(tfBuffer); area_sidelength = int(round(par_area_sidelength)); grid_sidelength = int(round(par_grid_size)); num_gridsprside = int(round(par_area_sidelength / par_grid_size)); ROS_INFO("par_area_sidelength: %.2f par_grid_size %.2f",par_area_sidelength,par_grid_size); ROS_INFO("Area side: %i grid_side %i num_gridsprside: %i",area_sidelength,grid_sidelength,num_gridsprside); nav_msgs::Path path_template; path_template.header.frame_id = "map"; target.pose.position.z = par_takeoffaltitude; draw_pose2d(target.pose.position,2,target_color,false,tf::getYaw(target.pose.orientation)); for(int i = 0; i < 20; i++){ z_lvls.push_back(int(round(-par_zjump*3 + par_zjump*i))); paths_cand_at_lvl.push_back(path_template); paths_vstd_at_lvl.push_back(path_template); } define_colors(); ros::Subscriber s22 = nh.subscribe("/tb_fsm/altlvl",100,&zlvl_cb); ros::Subscriber s1 = nh.subscribe("/octomap_full",1,octomap_callback); ros::Subscriber s46 = nh.subscribe("/tb_path_filtered",1,&pathcandupd_cb); ros::Subscriber s8 = nh.subscribe("/cmd_pos", 10,&cmd_cb); ros::Subscriber s10 = nh.subscribe("/tb_nav/path_visited", 10,&path01_cb); ros::Subscriber s3 = nh.subscribe("/scan_base_alt", 100,&scan_cb); ros::Rate rate(1); bool done = true; bool everyother; ros::Time start = ros::Time::now(); ros::Time last_check = ros::Time::now(); bool par_get_zdown; bool first = true; int c = 0; while(ros::ok()){ geometry_msgs::TransformStamped transformStamped; try{ transformStamped = tfBuffer.lookupTransform("map","base_stabilized", ros::Time(0)); } catch (tf2::TransformException &ex) { ROS_WARN("%s",ex.what()); ros::Duration(1.0).sleep(); } pos.x = transformStamped.transform.translation.x; pos.y = transformStamped.transform.translation.y; pos.z = transformStamped.transform.translation.z; pos_yaw = tf::getYaw(transformStamped.transform.rotation); if(c == 5) update_edto(pos,5,par_maprad,pos.z-10,pos.z+50,false,false); else if(c > 5) c = 0; else c++; std::vector<int> safe_grids; geometry_msgs::PolygonStamped poly; create_polygon_grids(); img.copyTo(img_copy); scanproc(false); get_zdown_grids(true); draw_path_vstdcnd(2,10,true); poly = scan2poly(scan_copy,pos); safe_grids = grids_in_poly_safe(poly); draw_polygon(poly,obstacle_color,true); draw_grids(safe_grids,cleared_color,false); cv::imwrite(par_workdir+"/global_img_copy.png",img_copy); cv::imwrite(par_workdir+"/global_img.png",img); rate.sleep(); ros::spinOnce(); } return 0; }
35.217292
336
0.686135
[ "vector", "transform" ]
3398eb92031a200978e1f22aa3042f9fd3515c36
611
hpp
C++
inc/valunpak/ue4_udatatable.hpp
Querijn/Valunpak
c1eebe2bd7effc8afa45becfbcf383fe4ad9cdf9
[ "MIT" ]
3
2020-06-07T21:05:11.000Z
2021-03-30T17:50:08.000Z
inc/valunpak/ue4_udatatable.hpp
Querijn/Valunpak
c1eebe2bd7effc8afa45becfbcf383fe4ad9cdf9
[ "MIT" ]
null
null
null
inc/valunpak/ue4_udatatable.hpp
Querijn/Valunpak
c1eebe2bd7effc8afa45becfbcf383fe4ad9cdf9
[ "MIT" ]
1
2021-05-17T08:24:18.000Z
2021-05-17T08:24:18.000Z
#pragma once #include <valunpak/config.hpp> #include <valunpak/ue4_base.hpp> #include <valunpak/ue4_uobject.hpp> #include <valunpak/ue4_bulkdata.hpp> #include <map> #include <string> #include <vector> namespace valunpak { class ue4_uexp; class ue4_ubulk; class ue4_udatatable : public ue4_base { public: bool open(ue4_uexp& a_uexp, ue4_ubulk* a_ubulk, size_t& a_offset) noexcept; private: ue4_uobject m_object; std::string name; std::map<std::string, std::unique_ptr<ue4_uobject>> m_entries; void reset(); bool read_internal(ue4_uexp& a_uexp, ue4_ubulk* a_bulk, size_t& a_offset); }; }
19.709677
77
0.743044
[ "vector" ]
3399e6f32e4a95f0962c593066a15a0a1c7ea976
8,817
cpp
C++
src/DHTMessage.cpp
bittorrent/libbtdht
200b8adf83edeb84f1c81fb82de7e5b8624a5fa4
[ "Apache-2.0" ]
34
2016-07-26T09:40:05.000Z
2021-12-31T04:12:37.000Z
src/DHTMessage.cpp
bittorrent/libbtdht
200b8adf83edeb84f1c81fb82de7e5b8624a5fa4
[ "Apache-2.0" ]
1
2017-05-21T21:55:03.000Z
2017-05-21T21:55:03.000Z
src/DHTMessage.cpp
bittorrent/libbtdht
200b8adf83edeb84f1c81fb82de7e5b8624a5fa4
[ "Apache-2.0" ]
17
2016-06-26T04:22:11.000Z
2020-11-26T03:33:04.000Z
/* Copyright 2016 BitTorrent Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string.h> // for strlen #include <utility> // for std::pair #include "DHTMessage.h" #include "bencoding.h" /** This version of DecodeMessageData() will extract a 'v' region. The region values will be assigned to vBuf once it has been determined that this message is a 'put' query. */ void DHTMessage::DecodeMessageData(byte* bencMessageBytes, int numBytes) { std::vector<const char*> keys; keys.push_back("a\0v\0"); keys.push_back("r\0v\0"); if(!BencEntity::ParseInPlace(bencMessageBytes, *_bDict, bencMessageBytes + numBytes, keys, &region)){ _parseSuccessful = false; dhtMessageType = DHT_UNDEFINED_MESSAGE; return; } _parseSuccessful = true; DecodeMessageData(*_bDict); } DHTMessage::DHTMessage(byte* bencMessageBytes, int numBytes) { Init(); _bDict = new BencodedDict; DecodeMessageData(bencMessageBytes, numBytes); } DHTMessage::~DHTMessage() { delete _bDict; } void DHTMessage::Init() { replyDict = _bDict = NULL; _argumentsAreValid = _parseSuccessful = false; dhtMessageType = DHT_UNDEFINED_MESSAGE; dhtCommand = DHT_QUERY_UNDEFINED; type = command = NULL; id = NULL; args = NULL; read_only = false; region.first = region.second = NULL; portNum = vote = seed = scrape = noseed = sequenceNum = 0; error_code = 0; error_message = NULL; impliedPort = 0; _bDictForUser = NULL; } /** This version of DecodeMessageData() can NOT extract a 'v' region since the original string has already been parsed outside the scope of this object. */ void DHTMessage::DecodeMessageData(BencodedDict &bDict) { _bDictForUser = &bDict; // if not a dictionary, it's not a valid DHT RPC if(bDict.GetType() != BENC_DICT) { _parseSuccessful = false; dhtMessageType = DHT_UNDEFINED_MESSAGE; return; } _parseSuccessful = true; // extract the components common to all DHT messages transactionID.b = (byte*)bDict.GetString("t", &transactionID.len); version.b = (byte*)bDict.GetString("v", &version.len); external_ip.b = (byte*)bDict.GetString("ip", &external_ip.len); read_only = bDict.GetInt("ro", 0) != 0; type = bDict.GetString("y", 1); if (!type) return; switch(*type) { case 'q': { dhtMessageType = DHT_QUERY; DecodeQuery(bDict); break; } case 'r': { // Just extract the reply dictionary. Specific elements can be // extracted further down the call chain once it is known what // specific query this is a reply to. replyDict = bDict.GetDict("r"); if(replyDict){ id = (byte*)replyDict->GetString("id", DHT_ID_SIZE); dhtMessageType = DHT_RESPONSE; sequenceNum = replyDict->GetInt("seq", 1); vBuf.len = region.second - region.first; vBuf.b = region.first; signature.b = (byte*)replyDict->GetString("sig", &signature.len); key.b = (byte*)replyDict->GetString("k", &key.len); } else { dhtMessageType = DHT_UNDEFINED_MESSAGE; } break; } case 'e': { dhtMessageType = DHT_ERROR; DecodeError(bDict); break; } default: dhtMessageType = DHT_UNDEFINED_MESSAGE; } } void DHTMessage::DecodeError(BencodedDict &bDict) { BencodedList* l = bDict.GetList("e"); if (l != NULL) { error_code = l->GetInt(0); error_message = l->GetString(1); } } void DHTMessage::DecodeQuery(BencodedDict &bDict) { // Handle a query from a peer command = bDict.GetString("q"); if (!command) { dhtCommand = DHT_QUERY_UNDEFINED; return; // bad/missing command. } // get the arguments dictionary args = bDict.GetDict("a"); if (!args) { _argumentsAreValid = false; return; // bad/missing argument. } _argumentsAreValid = true; id = (byte*)args->GetString("id", DHT_ID_SIZE); // set the command enum and extract only arguments used by the command if(strcmp(command,"find_node") == 0){ dhtCommand = DHT_QUERY_FIND_NODE; target.b = (byte*)args->GetString("target", &target.len); if (target.len != DHT_ID_SIZE) _argumentsAreValid = false; } else if(strcmp(command,"get_peers") == 0){ dhtCommand = DHT_QUERY_GET_PEERS; infoHash.b = (byte*)args->GetString("info_hash", &infoHash.len); if (infoHash.len != DHT_ID_SIZE) _argumentsAreValid = false; filename.b = (byte*)args->GetString("name", &filename.len); scrape = args->GetInt("scrape", 0); noseed = args->GetInt("noseed", 0); } else if(strcmp(command,"announce_peer") == 0){ dhtCommand = DHT_QUERY_ANNOUNCE_PEER; infoHash.b = (byte*)args->GetString("info_hash", &infoHash.len); if (infoHash.len != DHT_ID_SIZE) _argumentsAreValid = false; portNum = args->GetInt("port", -1); token.b = (byte*)args->GetString("token", &token.len); filename.b = (byte*)args->GetString("name", &filename.len); seed = args->GetInt("seed", 0); impliedPort = args->GetInt("implied_port", 0); } else if(strcmp(command,"vote") == 0){ dhtCommand = DHT_QUERY_VOTE; target.b = (byte*)args->GetString("target", &target.len); if (target.len != DHT_ID_SIZE) _argumentsAreValid = false; token.b = (byte*)args->GetString("token", &token.len); vote = args->GetInt("vote", 0); filename.b = (byte*)args->GetString("name", &filename.len); } else if (strcmp(command,"get") == 0) { dhtCommand = DHT_QUERY_GET; target.b = (byte*)args->GetString("target", &target.len); if (target.len != DHT_ID_SIZE) _argumentsAreValid = false; sequenceNum = args->GetInt64("seq", 0); } else if (strcmp(command,"put") == 0) { dhtCommand = DHT_QUERY_PUT; token.b = (byte*)args->GetString("token", &token.len); vBuf.len = region.second - region.first; vBuf.b = region.first; signature.b = (byte*)args->GetString("sig", &signature.len); // 64 bytes if (signature.b && signature.len != DHT_SIG_SIZE) _argumentsAreValid = false; key.b = (byte*)args->GetString("k", &key.len); // 32 bytes if (key.b && key.len != DHT_KEY_SIZE) _argumentsAreValid = false; salt.b = (byte*)args->GetString("salt", &salt.len); sequenceNum = args->GetInt64("seq", 0); cas = args->GetInt("cas", 0); } else if (strcmp(command,"ping") == 0) { dhtCommand = DHT_QUERY_PING; } #if USE_HOLEPUNCH else if (strcmp(command, "punch") == 0) { dhtCommand = DHT_QUERY_PUNCH; target_ip.b = (byte*)args->GetString("ip", &target_ip.len); if (target_ip.b == NULL || target_ip.len != 6) _argumentsAreValid = false; } #endif else { // unknown messages with either a 'target' // or an 'info-hash' argument are treated // as a find node to not block future extensions dhtCommand = DHT_QUERY_FIND_NODE; // assume find_node... target.b = (byte*)args->GetString("target", &target.len); // check that there is a target; if not... if (target.b) { if (target.len != DHT_ID_SIZE) _argumentsAreValid = false; } else { target.b = (byte*)args->GetString("info_hash", &target.len); if (target.len != DHT_ID_SIZE) _argumentsAreValid = false; // see if there is an info_hash to use as a target; if not... if (!target.b) { // we have an invalid query command dhtCommand = DHT_QUERY_UNDEFINED; } } } } void DHTMessage::CopyFrom(DHTMessage &src) { if (&src == this) return; delete _bDict; // free ours if necessary _bDict = NULL; // If the source _bDict object is not null, then the src object allocated // its own BencodedDict. So this object needs to do its own allocation // before copying. if (src._bDict){ _bDict = new BencodedDict; *_bDict = *src._bDict; } // if _bDict is not null, set to our _bDict, otherwise the consumer provided // a BencodedDict when creating the source object, so point to the consumers dictionary. _bDictForUser = (_bDict)?_bDict:src._bDictForUser; _argumentsAreValid = src._argumentsAreValid; _parseSuccessful = src._parseSuccessful; type = src.type; command = src.command; filename = src.filename; id = src.id; target = src.target; infoHash = src.infoHash; token = src.token; portNum = src.portNum; vote = src.vote; seed = src.seed; scrape = src.scrape; args = src.args; transactionID = src.transactionID; version = src.version; key = src.key; sequenceNum = src.sequenceNum; signature = src.signature; region = src.region; vBuf = src.vBuf; target_ip = src.target_ip; impliedPort = src.impliedPort; cas = src.cas; // Warning: If this was set, it will still point to the dictionary // created by the original _bDict object replyDict = src.replyDict; }
29.686869
102
0.693887
[ "object", "vector" ]
339b2f9bcbc1599d9236b21ecf5cf4d992d34dc3
124,532
cpp
C++
corelib/src/Memory.cpp
GeekLiB/rtabmap
db81b37fda225d597d4cf068c64182b2b79bbed4
[ "BSD-3-Clause" ]
null
null
null
corelib/src/Memory.cpp
GeekLiB/rtabmap
db81b37fda225d597d4cf068c64182b2b79bbed4
[ "BSD-3-Clause" ]
null
null
null
corelib/src/Memory.cpp
GeekLiB/rtabmap
db81b37fda225d597d4cf068c64182b2b79bbed4
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke 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 Universite de Sherbrooke nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <rtabmap/utilite/UEventsManager.h> #include <rtabmap/utilite/ULogger.h> #include <rtabmap/utilite/UTimer.h> #include <rtabmap/utilite/UConversion.h> #include <rtabmap/utilite/UProcessInfo.h> #include <rtabmap/utilite/UMath.h> #include "rtabmap/core/Memory.h" #include "rtabmap/core/Signature.h" #include "rtabmap/core/Parameters.h" #include "rtabmap/core/RtabmapEvent.h" #include "rtabmap/core/VWDictionary.h" #include <rtabmap/core/EpipolarGeometry.h> #include "rtabmap/core/VisualWord.h" #include "rtabmap/core/Features2d.h" #include "rtabmap/core/RegistrationIcp.h" #include "rtabmap/core/Registration.h" #include "rtabmap/core/RegistrationVis.h" #include "rtabmap/core/DBDriver.h" #include "rtabmap/core/util3d_features.h" #include "rtabmap/core/util3d_filtering.h" #include "rtabmap/core/util3d_correspondences.h" #include "rtabmap/core/util3d_registration.h" #include "rtabmap/core/util3d_surface.h" #include "rtabmap/core/util3d_transforms.h" #include "rtabmap/core/util3d_motion_estimation.h" #include "rtabmap/core/util3d.h" #include "rtabmap/core/util2d.h" #include "rtabmap/core/Statistics.h" #include "rtabmap/core/Compression.h" #include "rtabmap/core/Graph.h" #include "rtabmap/core/Stereo.h" #include <pcl/io/pcd_io.h> #include <pcl/common/common.h> #include <rtabmap/core/OccupancyGrid.h> namespace rtabmap { const int Memory::kIdStart = 0; const int Memory::kIdVirtual = -1; const int Memory::kIdInvalid = 0; Memory::Memory(const ParametersMap & parameters) : _dbDriver(0), _similarityThreshold(Parameters::defaultMemRehearsalSimilarity()), _binDataKept(Parameters::defaultMemBinDataKept()), _rawDescriptorsKept(Parameters::defaultMemRawDescriptorsKept()), _saveDepth16Format(Parameters::defaultMemSaveDepth16Format()), _notLinkedNodesKeptInDb(Parameters::defaultMemNotLinkedNodesKept()), _incrementalMemory(Parameters::defaultMemIncrementalMemory()), _reduceGraph(Parameters::defaultMemReduceGraph()), _maxStMemSize(Parameters::defaultMemSTMSize()), _recentWmRatio(Parameters::defaultMemRecentWmRatio()), _transferSortingByWeightId(Parameters::defaultMemTransferSortingByWeightId()), _idUpdatedToNewOneRehearsal(Parameters::defaultMemRehearsalIdUpdatedToNewOne()), _generateIds(Parameters::defaultMemGenerateIds()), _badSignaturesIgnored(Parameters::defaultMemBadSignaturesIgnored()), _mapLabelsAdded(Parameters::defaultMemMapLabelsAdded()), _imagePreDecimation(Parameters::defaultMemImagePreDecimation()), _imagePostDecimation(Parameters::defaultMemImagePostDecimation()), _laserScanDownsampleStepSize(Parameters::defaultMemLaserScanDownsampleStepSize()), _laserScanNormalK(Parameters::defaultMemLaserScanNormalK()), _reextractLoopClosureFeatures(Parameters::defaultRGBDLoopClosureReextractFeatures()), _rehearsalMaxDistance(Parameters::defaultRGBDLinearUpdate()), _rehearsalMaxAngle(Parameters::defaultRGBDAngularUpdate()), _rehearsalWeightIgnoredWhileMoving(Parameters::defaultMemRehearsalWeightIgnoredWhileMoving()), _useOdometryFeatures(Parameters::defaultMemUseOdomFeatures()), _createOccupancyGrid(Parameters::defaultRGBDCreateOccupancyGrid()), _visMaxFeatures(Parameters::defaultVisMaxFeatures()), _idCount(kIdStart), _idMapCount(kIdStart), _lastSignature(0), _lastGlobalLoopClosureId(0), _memoryChanged(false), _linksChanged(false), _signaturesAdded(0), _badSignRatio(Parameters::defaultKpBadSignRatio()), _tfIdfLikelihoodUsed(Parameters::defaultKpTfIdfLikelihoodUsed()), _parallelized(Parameters::defaultKpParallelized()) { _feature2D = Feature2D::create(parameters); _vwd = new VWDictionary(parameters); _registrationPipeline = Registration::create(parameters); _registrationIcp = new RegistrationIcp(parameters); _occupancy = new OccupancyGrid(parameters); this->parseParameters(parameters); } bool Memory::init(const std::string & dbUrl, bool dbOverwritten, const ParametersMap & parameters, bool postInitClosingEvents) { if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(RtabmapEventInit::kInitializing)); UDEBUG(""); this->parseParameters(parameters); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Clearing memory...")); DBDriver * tmpDriver = 0; if((!_memoryChanged && !_linksChanged) || dbOverwritten) { if(_dbDriver) { tmpDriver = _dbDriver; _dbDriver = 0; // HACK for the clear() below to think that there is no db } } else if(!_memoryChanged && _linksChanged) { _dbDriver->setTimestampUpdateEnabled(false); // update links only } this->clear(); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Clearing memory, done!")); if(tmpDriver) { _dbDriver = tmpDriver; } if(_dbDriver) { if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Closing database connection...")); _dbDriver->closeConnection(); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Closing database connection, done!")); } if(_dbDriver == 0) { _dbDriver = DBDriver::create(parameters); } bool success = true; if(_dbDriver) { _dbDriver->setTimestampUpdateEnabled(true); // make sure that timestamp update is enabled (may be disabled above) success = false; if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(std::string("Connecting to database \"") + dbUrl + "\"...")); if(_dbDriver->openConnection(dbUrl, dbOverwritten)) { success = true; if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(std::string("Connecting to database \"") + dbUrl + "\", done!")); } else { if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(RtabmapEventInit::kError, std::string("Connecting to database ") + dbUrl + ", path is invalid!")); } } loadDataFromDb(postInitClosingEvents); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(RtabmapEventInit::kInitialized)); return success; } void Memory::loadDataFromDb(bool postInitClosingEvents) { if(_dbDriver && _dbDriver->isConnected()) { bool loadAllNodesInWM = Parameters::defaultMemInitWMWithAllNodes(); Parameters::parse(parameters_, Parameters::kMemInitWMWithAllNodes(), loadAllNodesInWM); // Load the last working memory... std::list<Signature*> dbSignatures; if(loadAllNodesInWM) { if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(std::string("Loading all nodes to WM..."))); std::set<int> ids; _dbDriver->getAllNodeIds(ids, true); _dbDriver->loadSignatures(std::list<int>(ids.begin(), ids.end()), dbSignatures); } else { // load previous session working memory if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(std::string("Loading last nodes to WM..."))); _dbDriver->loadLastNodes(dbSignatures); } for(std::list<Signature*>::reverse_iterator iter=dbSignatures.rbegin(); iter!=dbSignatures.rend(); ++iter) { // ignore bad signatures if(!((*iter)->isBadSignature() && _badSignaturesIgnored)) { // insert all in WM // Note: it doesn't make sense to keep last STM images // of the last session in the new STM because they can be // only linked with the ones of the current session by // global loop closures. _signatures.insert(std::pair<int, Signature *>((*iter)->id(), *iter)); _workingMem.insert(std::make_pair((*iter)->id(), UTimer::now())); } else { delete *iter; } } if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(std::string("Loading nodes to WM, done! (") + uNumber2Str(int(_workingMem.size() + _stMem.size())) + " loaded)")); // Assign the last signature if(_stMem.size()>0) { _lastSignature = uValue(_signatures, *_stMem.rbegin(), (Signature*)0); } else if(_workingMem.size()>0) { _lastSignature = uValue(_signatures, _workingMem.rbegin()->first, (Signature*)0); } // Last id _dbDriver->getLastNodeId(_idCount); _idMapCount = _lastSignature?_lastSignature->mapId()+1:kIdStart; // Now load the dictionary if we have a connection if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Loading dictionary...")); if(loadAllNodesInWM) { // load all referenced words in working memory std::set<int> wordIds; const std::map<int, Signature *> & signatures = this->getSignatures(); for(std::map<int, Signature *>::const_iterator i=signatures.begin(); i!=signatures.end(); ++i) { const std::multimap<int, cv::KeyPoint> & words = i->second->getWords(); std::list<int> keys = uUniqueKeys(words); for(std::list<int>::iterator iter=keys.begin(); iter!=keys.end();) { if(*iter > 0) { wordIds.insert(*iter); } } } if(wordIds.size()) { std::list<VisualWord*> words; _dbDriver->loadWords(wordIds, words); for(std::list<VisualWord*>::iterator iter = words.begin(); iter!=words.end(); ++iter) { _vwd->addWord(*iter); } // Get Last word id int id = 0; _dbDriver->getLastWordId(id); _vwd->setLastWordId(id); } } else { // load the last dictionary _dbDriver->load(_vwd); } UDEBUG("%d words loaded!", _vwd->getUnusedWordsSize()); _vwd->update(); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(uFormat("Loading dictionary, done! (%d words)", (int)_vwd->getUnusedWordsSize()))); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(std::string("Adding word references..."))); // Enable loaded signatures const std::map<int, Signature *> & signatures = this->getSignatures(); for(std::map<int, Signature *>::const_iterator i=signatures.begin(); i!=signatures.end(); ++i) { Signature * s = this->_getSignature(i->first); UASSERT(s != 0); const std::multimap<int, cv::KeyPoint> & words = s->getWords(); if(words.size()) { UDEBUG("node=%d, word references=%d", s->id(), words.size()); for(std::multimap<int, cv::KeyPoint>::const_iterator iter = words.begin(); iter!=words.end(); ++iter) { if(iter->first > 0) { _vwd->addWordRef(iter->first, i->first); } } s->setEnabled(true); } } if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(uFormat("Adding word references, done! (%d)", _vwd->getTotalActiveReferences()))); if(_vwd->getUnusedWordsSize()) { UWARN("_vwd->getUnusedWordsSize() must be empty... size=%d", _vwd->getUnusedWordsSize()); } UDEBUG("Total word references added = %d", _vwd->getTotalActiveReferences()); } else { _idCount = kIdStart; _idMapCount = kIdStart; } _workingMem.insert(std::make_pair(kIdVirtual, 0)); UDEBUG("ids start with %d", _idCount+1); UDEBUG("map ids start with %d", _idMapCount); } void Memory::close(bool databaseSaved, bool postInitClosingEvents, const std::string & ouputDatabasePath) { UINFO("databaseSaved=%d, postInitClosingEvents=%d", databaseSaved?1:0, postInitClosingEvents?1:0); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(RtabmapEventInit::kClosing)); bool databaseNameChanged = false; if(databaseSaved) { databaseNameChanged = ouputDatabasePath.size() && _dbDriver->getUrl().size() && _dbDriver->getUrl().compare(ouputDatabasePath) != 0?true:false; } if(!databaseSaved || (!_memoryChanged && !_linksChanged && !databaseNameChanged)) { if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(uFormat("No changes added to database."))); UINFO("No changes added to database."); if(_dbDriver) { if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(uFormat("Closing database \"%s\"...", _dbDriver->getUrl().c_str()))); _dbDriver->closeConnection(false, ouputDatabasePath); delete _dbDriver; _dbDriver = 0; if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Closing database, done!")); } if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Clearing memory...")); this->clear(); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Clearing memory, done!")); } else { UINFO("Saving memory..."); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Saving memory...")); if(!_memoryChanged && _linksChanged && _dbDriver) { // don't update the time stamps! UDEBUG(""); _dbDriver->setTimestampUpdateEnabled(false); } this->clear(); if(_dbDriver) { _dbDriver->emptyTrashes(); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Saving memory, done!")); if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(uFormat("Closing database \"%s\"...", _dbDriver->getUrl().c_str()))); _dbDriver->closeConnection(true, ouputDatabasePath); delete _dbDriver; _dbDriver = 0; if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Closing database, done!")); } else { if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit("Saving memory, done!")); } } if(postInitClosingEvents) UEventsManager::post(new RtabmapEventInit(RtabmapEventInit::kClosed)); } Memory::~Memory() { this->close(); if(_dbDriver) { UWARN("Please call Memory::close() before"); } if(_feature2D) { delete _feature2D; } if(_vwd) { delete _vwd; } if(_registrationPipeline) { delete _registrationPipeline; } if(_registrationIcp) { delete _registrationIcp; } if(_occupancy) { delete _occupancy; } } void Memory::parseParameters(const ParametersMap & parameters) { uInsert(parameters_, parameters); UDEBUG(""); ParametersMap::const_iterator iter; Parameters::parse(parameters, Parameters::kMemBinDataKept(), _binDataKept); Parameters::parse(parameters, Parameters::kMemRawDescriptorsKept(), _rawDescriptorsKept); Parameters::parse(parameters, Parameters::kMemSaveDepth16Format(), _saveDepth16Format); Parameters::parse(parameters, Parameters::kMemReduceGraph(), _reduceGraph); Parameters::parse(parameters, Parameters::kMemNotLinkedNodesKept(), _notLinkedNodesKeptInDb); Parameters::parse(parameters, Parameters::kMemRehearsalIdUpdatedToNewOne(), _idUpdatedToNewOneRehearsal); Parameters::parse(parameters, Parameters::kMemGenerateIds(), _generateIds); Parameters::parse(parameters, Parameters::kMemBadSignaturesIgnored(), _badSignaturesIgnored); Parameters::parse(parameters, Parameters::kMemMapLabelsAdded(), _mapLabelsAdded); Parameters::parse(parameters, Parameters::kMemRehearsalSimilarity(), _similarityThreshold); Parameters::parse(parameters, Parameters::kMemRecentWmRatio(), _recentWmRatio); Parameters::parse(parameters, Parameters::kMemTransferSortingByWeightId(), _transferSortingByWeightId); Parameters::parse(parameters, Parameters::kMemSTMSize(), _maxStMemSize); Parameters::parse(parameters, Parameters::kMemImagePreDecimation(), _imagePreDecimation); Parameters::parse(parameters, Parameters::kMemImagePostDecimation(), _imagePostDecimation); Parameters::parse(parameters, Parameters::kMemLaserScanDownsampleStepSize(), _laserScanDownsampleStepSize); Parameters::parse(parameters, Parameters::kMemLaserScanNormalK(), _laserScanNormalK); Parameters::parse(parameters, Parameters::kRGBDLoopClosureReextractFeatures(), _reextractLoopClosureFeatures); Parameters::parse(parameters, Parameters::kRGBDLinearUpdate(), _rehearsalMaxDistance); Parameters::parse(parameters, Parameters::kRGBDAngularUpdate(), _rehearsalMaxAngle); Parameters::parse(parameters, Parameters::kMemRehearsalWeightIgnoredWhileMoving(), _rehearsalWeightIgnoredWhileMoving); Parameters::parse(parameters, Parameters::kMemUseOdomFeatures(), _useOdometryFeatures); Parameters::parse(parameters, Parameters::kRGBDCreateOccupancyGrid(), _createOccupancyGrid); Parameters::parse(parameters, Parameters::kVisMaxFeatures(), _visMaxFeatures); UASSERT_MSG(_maxStMemSize >= 0, uFormat("value=%d", _maxStMemSize).c_str()); UASSERT_MSG(_similarityThreshold >= 0.0f && _similarityThreshold <= 1.0f, uFormat("value=%f", _similarityThreshold).c_str()); UASSERT_MSG(_recentWmRatio >= 0.0f && _recentWmRatio <= 1.0f, uFormat("value=%f", _recentWmRatio).c_str()); if(_imagePreDecimation == 0) { _imagePreDecimation = 1; } if(_imagePostDecimation == 0) { _imagePostDecimation = 1; } UASSERT(_rehearsalMaxDistance >= 0.0f); UASSERT(_rehearsalMaxAngle >= 0.0f); if(_dbDriver) { _dbDriver->parseParameters(parameters); } // Keypoint stuff if(_vwd) { _vwd->parseParameters(parameters); } Parameters::parse(parameters, Parameters::kKpTfIdfLikelihoodUsed(), _tfIdfLikelihoodUsed); Parameters::parse(parameters, Parameters::kKpParallelized(), _parallelized); Parameters::parse(parameters, Parameters::kKpBadSignRatio(), _badSignRatio); //Keypoint detector UASSERT(_feature2D != 0); Feature2D::Type detectorStrategy = Feature2D::kFeatureUndef; if((iter=parameters.find(Parameters::kKpDetectorStrategy())) != parameters.end()) { detectorStrategy = (Feature2D::Type)std::atoi((*iter).second.c_str()); } if(detectorStrategy!=Feature2D::kFeatureUndef && detectorStrategy!=_feature2D->getType()) { if(_vwd->getVisualWords().size()) { UWARN("new detector strategy %d while the vocabulary is already created. This may give problems if feature descriptors are not the same type than the one used in the current vocabulary (a memory reset would be required if so).", int(detectorStrategy)); } else { UINFO("new detector strategy %d.", int(detectorStrategy)); } if(_feature2D) { delete _feature2D; _feature2D = 0; } _feature2D = Feature2D::create(detectorStrategy, parameters_); } else if(_feature2D) { _feature2D->parseParameters(parameters); } Registration::Type regStrategy = Registration::kTypeUndef; if((iter=parameters.find(Parameters::kRegStrategy())) != parameters.end()) { regStrategy = (Registration::Type)std::atoi((*iter).second.c_str()); } if(regStrategy!=Registration::kTypeUndef) { UDEBUG("new registration strategy %d", int(regStrategy)); if(_registrationPipeline) { delete _registrationPipeline; _registrationPipeline = 0; } _registrationPipeline = Registration::create(regStrategy, parameters_); } else if(_registrationPipeline) { _registrationPipeline->parseParameters(parameters); } if(_registrationIcp) { _registrationIcp->parseParameters(parameters); } if(_occupancy) { _occupancy->parseParameters(parameters); } // do this after all parameters are parsed // SLAM mode vs Localization mode iter = parameters.find(Parameters::kMemIncrementalMemory()); if(iter != parameters.end()) { bool value = uStr2Bool(iter->second.c_str()); if(value == false && _incrementalMemory) { // From SLAM to localization, change map id this->incrementMapId(); // The easiest way to make sure that the mapping session is saved // is to save the memory in the database and reload it. if((_memoryChanged || _linksChanged) && _dbDriver) { UWARN("Switching from Mapping to Localization mode, the database will be saved and reloaded."); bool memoryChanged = _memoryChanged; bool linksChanged = _linksChanged; this->clear(); _memoryChanged = memoryChanged; _linksChanged = linksChanged; this->loadDataFromDb(false); UWARN("Switching from Mapping to Localization mode, the database is reloaded!"); } } _incrementalMemory = value; } } void Memory::preUpdate() { _signaturesAdded = 0; this->cleanUnusedWords(); if(_vwd && !_parallelized) { //When parallelized, it is done in CreateSignature _vwd->update(); } } bool Memory::update( const SensorData & data, Statistics * stats) { return update(data, Transform(), cv::Mat(), stats); } bool Memory::update( const SensorData & data, const Transform & pose, const cv::Mat & covariance, Statistics * stats) { UDEBUG(""); UTimer timer; UTimer totalTimer; timer.start(); float t; //============================================================ // Pre update... //============================================================ UDEBUG("pre-updating..."); this->preUpdate(); t=timer.ticks()*1000; if(stats) stats->addStatistic(Statistics::kTimingMemPre_update(), t); UDEBUG("time preUpdate=%f ms", t); //============================================================ // Create a signature with the image received. //============================================================ Signature * signature = this->createSignature(data, pose, stats); if (signature == 0) { UERROR("Failed to create a signature..."); return false; } t=timer.ticks()*1000; if(stats) stats->addStatistic(Statistics::kTimingMemSignature_creation(), t); UDEBUG("time creating signature=%f ms", t); // It will be added to the short-term memory, no need to delete it... this->addSignatureToStm(signature, covariance); _lastSignature = signature; //============================================================ // Rehearsal step... // Compare with the X last signatures. If different, add this // signature like a parent to the memory tree, otherwise add // it as a child to the similar signature. //============================================================ if(_incrementalMemory) { if(_similarityThreshold < 1.0f) { this->rehearsal(signature, stats); } t=timer.ticks()*1000; if(stats) stats->addStatistic(Statistics::kTimingMemRehearsal(), t); UDEBUG("time rehearsal=%f ms", t); } else { if(_workingMem.size() <= 1) { UWARN("The working memory is empty and the memory is not " "incremental (Mem/IncrementalMemory=False), no loop closure " "can be detected! Please set Mem/IncrementalMemory=true to increase " "the memory with new images or decrease the STM size (which is %d " "including the new one added).", (int)_stMem.size()); } } //============================================================ // Transfer the oldest signature of the short-term memory to the working memory //============================================================ int notIntermediateNodesCount = 0; for(std::set<int>::iterator iter=_stMem.begin(); iter!=_stMem.end(); ++iter) { const Signature * s = this->getSignature(*iter); UASSERT(s != 0); if(s->getWeight() >= 0) { ++notIntermediateNodesCount; } } std::map<int, int> reducedIds; while(_stMem.size() && _maxStMemSize>0 && notIntermediateNodesCount > _maxStMemSize) { int id = *_stMem.begin(); Signature * s = this->_getSignature(id); UASSERT(s != 0); if(s->getWeight() >= 0) { --notIntermediateNodesCount; } int reducedTo = 0; moveSignatureToWMFromSTM(id, &reducedTo); if(reducedTo > 0) { reducedIds.insert(std::make_pair(id, reducedTo)); } } if(stats) stats->setReducedIds(reducedIds); if(!_memoryChanged && _incrementalMemory) { _memoryChanged = true; } UDEBUG("totalTimer = %fs", totalTimer.ticks()); return true; } void Memory::addSignatureToStm(Signature * signature, const cv::Mat & covariance) { UTimer timer; // add signature on top of the short-term memory if(signature) { UDEBUG("adding %d", signature->id()); // Update neighbors if(_stMem.size()) { if(_signatures.at(*_stMem.rbegin())->mapId() == signature->mapId()) { Transform motionEstimate; if(!signature->getPose().isNull() && !_signatures.at(*_stMem.rbegin())->getPose().isNull()) { cv::Mat infMatrix = covariance.inv(); motionEstimate = _signatures.at(*_stMem.rbegin())->getPose().inverse() * signature->getPose(); _signatures.at(*_stMem.rbegin())->addLink(Link(*_stMem.rbegin(), signature->id(), Link::kNeighbor, motionEstimate, infMatrix)); signature->addLink(Link(signature->id(), *_stMem.rbegin(), Link::kNeighbor, motionEstimate.inverse(), infMatrix)); } else { _signatures.at(*_stMem.rbegin())->addLink(Link(*_stMem.rbegin(), signature->id(), Link::kNeighbor, Transform())); signature->addLink(Link(signature->id(), *_stMem.rbegin(), Link::kNeighbor, Transform())); } UDEBUG("Min STM id = %d", *_stMem.begin()); } else { UDEBUG("Ignoring neighbor link between %d and %d because they are not in the same map! (%d vs %d)", *_stMem.rbegin(), signature->id(), _signatures.at(*_stMem.rbegin())->mapId(), signature->mapId()); //Tag the first node of the map std::string tag = uFormat("map%d", signature->mapId()); if(getSignatureIdByLabel(tag, false) == 0) { UINFO("Tagging node %d with label \"%s\"", signature->id(), tag.c_str()); signature->setLabel(tag); } } } else if(_mapLabelsAdded) { //Tag the first node of the map std::string tag = uFormat("map%d", signature->mapId()); if(getSignatureIdByLabel(tag, false) == 0) { UINFO("Tagging node %d with label \"%s\"", signature->id(), tag.c_str()); signature->setLabel(tag); } } _signatures.insert(_signatures.end(), std::pair<int, Signature *>(signature->id(), signature)); _stMem.insert(_stMem.end(), signature->id()); ++_signaturesAdded; if(_vwd) { UDEBUG("%d words ref for the signature %d", signature->getWords().size(), signature->id()); } if(signature->getWords().size()) { signature->setEnabled(true); } } UDEBUG("time = %fs", timer.ticks()); } void Memory::addSignatureToWmFromLTM(Signature * signature) { if(signature) { UDEBUG("Inserting node %d in WM...", signature->id()); _workingMem.insert(std::make_pair(signature->id(), UTimer::now())); _signatures.insert(std::pair<int, Signature*>(signature->id(), signature)); ++_signaturesAdded; } else { UERROR("Signature is null ?!?"); } } void Memory::moveSignatureToWMFromSTM(int id, int * reducedTo) { UDEBUG("Inserting node %d from STM in WM...", id); UASSERT(_stMem.find(id) != _stMem.end()); Signature * s = this->_getSignature(id); UASSERT(s!=0); if(_reduceGraph) { bool merge = false; const std::map<int, Link> & links = s->getLinks(); std::map<int, Link> neighbors; for(std::map<int, Link>::const_iterator iter=links.begin(); iter!=links.end(); ++iter) { if(!merge) { merge = iter->second.to() < s->id() && // should be a parent->child link iter->second.type() != Link::kNeighbor && iter->second.type() != Link::kNeighborMerged && iter->second.userDataCompressed().empty() && iter->second.type() != Link::kUndef && iter->second.type() != Link::kVirtualClosure; if(merge) { UDEBUG("Reduce %d to %d", s->id(), iter->second.to()); if(reducedTo) { *reducedTo = iter->second.to(); } } } if(iter->second.type() == Link::kNeighbor) { neighbors.insert(*iter); } } if(merge) { if(s->getLabel().empty()) { for(std::map<int, Link>::const_iterator iter=links.begin(); iter!=links.end(); ++iter) { merge = true; Signature * sTo = this->_getSignature(iter->first); UASSERT(sTo!=0); sTo->removeLink(s->id()); if(iter->second.type() != Link::kNeighbor && iter->second.type() != Link::kNeighborMerged && iter->second.type() != Link::kUndef) { // link to all neighbors for(std::map<int, Link>::iterator jter=neighbors.begin(); jter!=neighbors.end(); ++jter) { if(!sTo->hasLink(jter->second.to())) { Link l = iter->second.inverse().merge( jter->second, iter->second.userDataCompressed().empty() && iter->second.type() != Link::kVirtualClosure?Link::kNeighborMerged:iter->second.type()); sTo->addLink(l); Signature * sB = this->_getSignature(l.to()); UASSERT(sB!=0); UASSERT(!sB->hasLink(l.to())); sB->addLink(l.inverse()); } } } } //remove neighbor links std::map<int, Link> linksCopy = links; for(std::map<int, Link>::iterator iter=linksCopy.begin(); iter!=linksCopy.end(); ++iter) { if(iter->second.type() == Link::kNeighbor || iter->second.type() == Link::kNeighborMerged) { s->removeLink(iter->first); if(iter->second.type() == Link::kNeighbor) { if(_lastGlobalLoopClosureId == s->id()) { _lastGlobalLoopClosureId = iter->first; } } } } this->moveToTrash(s, _notLinkedNodesKeptInDb); s = 0; } } } if(s != 0) { _workingMem.insert(_workingMem.end(), std::make_pair(*_stMem.begin(), UTimer::now())); _stMem.erase(*_stMem.begin()); } // else already removed from STM/WM in moveToTrash() } const Signature * Memory::getSignature(int id) const { return _getSignature(id); } Signature * Memory::_getSignature(int id) const { return uValue(_signatures, id, (Signature*)0); } const VWDictionary * Memory::getVWDictionary() const { return _vwd; } std::map<int, Link> Memory::getNeighborLinks( int signatureId, bool lookInDatabase) const { std::map<int, Link> links; Signature * s = uValue(_signatures, signatureId, (Signature*)0); if(s) { const std::map<int, Link> & allLinks = s->getLinks(); for(std::map<int, Link>::const_iterator iter = allLinks.begin(); iter!=allLinks.end(); ++iter) { if(iter->second.type() == Link::kNeighbor || iter->second.type() == Link::kNeighborMerged) { links.insert(*iter); } } } else if(lookInDatabase && _dbDriver) { std::map<int, Link> neighbors; _dbDriver->loadLinks(signatureId, neighbors); for(std::map<int, Link>::iterator iter=neighbors.begin(); iter!=neighbors.end();) { if(iter->second.type() != Link::kNeighbor && iter->second.type() != Link::kNeighborMerged) { neighbors.erase(iter++); } else { ++iter; } } } else { UWARN("Cannot find signature %d in memory", signatureId); } return links; } std::map<int, Link> Memory::getLoopClosureLinks( int signatureId, bool lookInDatabase) const { const Signature * s = this->getSignature(signatureId); std::map<int, Link> loopClosures; if(s) { const std::map<int, Link> & allLinks = s->getLinks(); for(std::map<int, Link>::const_iterator iter = allLinks.begin(); iter!=allLinks.end(); ++iter) { if(iter->second.type() != Link::kNeighbor && iter->second.type() != Link::kNeighborMerged && iter->second.type() != Link::kUndef) { loopClosures.insert(*iter); } } } else if(lookInDatabase && _dbDriver) { _dbDriver->loadLinks(signatureId, loopClosures); for(std::map<int, Link>::iterator iter=loopClosures.begin(); iter!=loopClosures.end();) { if(iter->second.type() == Link::kNeighbor || iter->second.type() == Link::kNeighborMerged || iter->second.type() == Link::kUndef ) { loopClosures.erase(iter++); } else { ++iter; } } } return loopClosures; } std::map<int, Link> Memory::getLinks( int signatureId, bool lookInDatabase) const { std::map<int, Link> links; Signature * s = uValue(_signatures, signatureId, (Signature*)0); if(s) { links = s->getLinks(); } else if(lookInDatabase && _dbDriver) { _dbDriver->loadLinks(signatureId, links, Link::kUndef); } else { UWARN("Cannot find signature %d in memory", signatureId); } return links; } std::multimap<int, Link> Memory::getAllLinks(bool lookInDatabase, bool ignoreNullLinks) const { std::multimap<int, Link> links; if(lookInDatabase && _dbDriver) { _dbDriver->getAllLinks(links, ignoreNullLinks); } for(std::map<int, Signature*>::const_iterator iter=_signatures.begin(); iter!=_signatures.end(); ++iter) { links.erase(iter->first); for(std::map<int, Link>::const_iterator jter=iter->second->getLinks().begin(); jter!=iter->second->getLinks().end(); ++jter) { if(!ignoreNullLinks || jter->second.isValid()) { links.insert(std::make_pair(iter->first, jter->second)); } } } return links; } // return map<Id,Margin>, including signatureId // maxCheckedInDatabase = -1 means no limit to check in database (default) // maxCheckedInDatabase = 0 means don't check in database std::map<int, int> Memory::getNeighborsId( int signatureId, int maxGraphDepth, // 0 means infinite margin int maxCheckedInDatabase, // default -1 (no limit) bool incrementMarginOnLoop, // default false bool ignoreLoopIds, // default false bool ignoreIntermediateNodes, // default false double * dbAccessTime ) const { UASSERT(maxGraphDepth >= 0); //UDEBUG("signatureId=%d, neighborsMargin=%d", signatureId, margin); if(dbAccessTime) { *dbAccessTime = 0; } std::map<int, int> ids; if(signatureId<=0) { return ids; } int nbLoadedFromDb = 0; std::list<int> curentMarginList; std::set<int> currentMargin; std::set<int> nextMargin; nextMargin.insert(signatureId); int m = 0; std::set<int> ignoredIds; while((maxGraphDepth == 0 || m < maxGraphDepth) && nextMargin.size()) { // insert more recent first (priority to be loaded first from the database below if set) curentMarginList = std::list<int>(nextMargin.rbegin(), nextMargin.rend()); nextMargin.clear(); for(std::list<int>::iterator jter = curentMarginList.begin(); jter!=curentMarginList.end(); ++jter) { if(ids.find(*jter) == ids.end()) { //UDEBUG("Added %d with margin %d", *jter, m); // Look up in STM/WM if all ids are here, if not... load them from the database const Signature * s = this->getSignature(*jter); std::map<int, Link> tmpLinks; const std::map<int, Link> * links = &tmpLinks; if(s) { if(!ignoreIntermediateNodes || s->getWeight() != -1) { ids.insert(std::pair<int, int>(*jter, m)); } else { ignoredIds.insert(*jter); } links = &s->getLinks(); } else if(maxCheckedInDatabase == -1 || (maxCheckedInDatabase > 0 && _dbDriver && nbLoadedFromDb < maxCheckedInDatabase)) { ++nbLoadedFromDb; ids.insert(std::pair<int, int>(*jter, m)); UTimer timer; _dbDriver->loadLinks(*jter, tmpLinks); if(dbAccessTime) { *dbAccessTime += timer.getElapsedTime(); } } // links for(std::map<int, Link>::const_iterator iter=links->begin(); iter!=links->end(); ++iter) { if( !uContains(ids, iter->first) && ignoredIds.find(iter->first) == ignoredIds.end()) { UASSERT(iter->second.type() != Link::kUndef); if(iter->second.type() == Link::kNeighbor || iter->second.type() == Link::kNeighborMerged) { if(ignoreIntermediateNodes && s->getWeight()==-1) { // stay on the same margin if(currentMargin.insert(iter->first).second) { curentMarginList.push_back(iter->first); } } else { nextMargin.insert(iter->first); } } else if(!ignoreLoopIds) { if(incrementMarginOnLoop) { nextMargin.insert(iter->first); } else { if(currentMargin.insert(iter->first).second) { curentMarginList.push_back(iter->first); } } } } } } } ++m; } return ids; } // return map<Id,sqrdDistance>, including signatureId std::map<int, float> Memory::getNeighborsIdRadius( int signatureId, float radius, // 0 means ignore radius const std::map<int, Transform> & optimizedPoses, int maxGraphDepth // 0 means infinite margin ) const { UASSERT(maxGraphDepth >= 0); UASSERT(uContains(optimizedPoses, signatureId)); UASSERT(signatureId > 0); std::map<int, float> ids; std::list<int> curentMarginList; std::set<int> currentMargin; std::set<int> nextMargin; nextMargin.insert(signatureId); int m = 0; Transform referential = optimizedPoses.at(signatureId); UASSERT(!referential.isNull()); float radiusSqrd = radius*radius; std::map<int, float> savedRadius; savedRadius.insert(std::make_pair(signatureId, 0)); while((maxGraphDepth == 0 || m < maxGraphDepth) && nextMargin.size()) { curentMarginList = std::list<int>(nextMargin.begin(), nextMargin.end()); nextMargin.clear(); for(std::list<int>::iterator jter = curentMarginList.begin(); jter!=curentMarginList.end(); ++jter) { if(ids.find(*jter) == ids.end()) { //UDEBUG("Added %d with margin %d", *jter, m); // Look up in STM/WM if all ids are here, if not... load them from the database const Signature * s = this->getSignature(*jter); std::map<int, Link> tmpLinks; const std::map<int, Link> * links = &tmpLinks; if(s) { ids.insert(std::pair<int, float>(*jter, savedRadius.at(*jter))); links = &s->getLinks(); } // links for(std::map<int, Link>::const_iterator iter=links->begin(); iter!=links->end(); ++iter) { if(!uContains(ids, iter->first) && uContains(optimizedPoses, iter->first) && iter->second.type()!=Link::kVirtualClosure) { const Transform & t = optimizedPoses.at(iter->first); UASSERT(!t.isNull()); float distanceSqrd = referential.getDistanceSquared(t); if(radiusSqrd == 0 || distanceSqrd<radiusSqrd) { savedRadius.insert(std::make_pair(iter->first, distanceSqrd)); nextMargin.insert(iter->first); } } } } } ++m; } return ids; } int Memory::getNextId() { return ++_idCount; } int Memory::incrementMapId(std::map<int, int> * reducedIds) { //don't increment if there is no location in the current map const Signature * s = getLastWorkingSignature(); if(s && s->mapId() == _idMapCount) { // New session! move all signatures from the STM to WM while(_stMem.size()) { int reducedId = 0; int id = *_stMem.begin(); moveSignatureToWMFromSTM(id, &reducedId); if(reducedIds && reducedId > 0) { reducedIds->insert(std::make_pair(id, reducedId)); } } return ++_idMapCount; } return _idMapCount; } void Memory::updateAge(int signatureId) { std::map<int, double>::iterator iter=_workingMem.find(signatureId); if(iter!=_workingMem.end()) { iter->second = UTimer::now(); } } int Memory::getDatabaseMemoryUsed() const { int memoryUsed = 0; if(_dbDriver) { memoryUsed = _dbDriver->getMemoryUsed()/(1024*1024); //Byte to MB } return memoryUsed; } std::string Memory::getDatabaseVersion() const { std::string version = "0.0.0"; if(_dbDriver) { version = _dbDriver->getDatabaseVersion(); } return version; } double Memory::getDbSavingTime() const { return _dbDriver?_dbDriver->getEmptyTrashesTime():0; } std::set<int> Memory::getAllSignatureIds() const { std::set<int> ids; if(_dbDriver) { _dbDriver->getAllNodeIds(ids); } for(std::map<int, Signature*>::const_iterator iter = _signatures.begin(); iter!=_signatures.end(); ++iter) { ids.insert(iter->first); } return ids; } void Memory::clear() { UDEBUG(""); // empty the STM while(_stMem.size()) { moveSignatureToWMFromSTM(*_stMem.begin()); } if(_stMem.size() != 0) { ULOGGER_ERROR("_stMem must be empty here, size=%d", _stMem.size()); } _stMem.clear(); this->cleanUnusedWords(); if(_dbDriver) { _dbDriver->emptyTrashes(); _dbDriver->join(); } if(_dbDriver) { // make sure time_enter in database is at least 1 second // after for the next stuf added to database uSleep(1500); } // Save some stats to the db, save only when the mem is not empty if(_dbDriver && (_stMem.size() || _workingMem.size())) { unsigned int memSize = (unsigned int)(_workingMem.size() + _stMem.size()); if(_workingMem.size() && _workingMem.begin()->first < 0) { --memSize; } // this is only a safe check...not supposed to occur. UASSERT_MSG(memSize == _signatures.size(), uFormat("The number of signatures don't match! _workingMem=%d, _stMem=%d, _signatures=%d", _workingMem.size(), _stMem.size(), _signatures.size()).c_str()); UDEBUG("Adding statistics after run..."); if(_memoryChanged) { ParametersMap parameters = Parameters::getDefaultParameters(); uInsert(parameters, parameters_); UDEBUG(""); _dbDriver->addInfoAfterRun(memSize, _lastSignature?_lastSignature->id():0, UProcessInfo::getMemoryUsage(), _dbDriver->getMemoryUsed(), (int)_vwd->getVisualWords().size(), parameters); } } UDEBUG(""); //Get the tree root (parents) std::map<int, Signature*> mem = _signatures; for(std::map<int, Signature *>::iterator i=mem.begin(); i!=mem.end(); ++i) { if(i->second) { UDEBUG("deleting from the working and the short-term memory: %d", i->first); this->moveToTrash(i->second); } } if(_workingMem.size() != 0 && !(_workingMem.size() == 1 && _workingMem.begin()->first == kIdVirtual)) { ULOGGER_ERROR("_workingMem must be empty here, size=%d", _workingMem.size()); } _workingMem.clear(); if(_signatures.size()!=0) { ULOGGER_ERROR("_signatures must be empty here, size=%d", _signatures.size()); } _signatures.clear(); UDEBUG(""); // Wait until the db trash has finished cleaning the memory if(_dbDriver) { _dbDriver->emptyTrashes(); } UDEBUG(""); _lastSignature = 0; _lastGlobalLoopClosureId = 0; _idCount = kIdStart; _idMapCount = kIdStart; _memoryChanged = false; _linksChanged = false; if(_dbDriver) { _dbDriver->join(true); cleanUnusedWords(); _dbDriver->emptyTrashes(); } else { cleanUnusedWords(); } if(_vwd) { _vwd->clear(); } UDEBUG(""); } /** * Compute the likelihood of the signature with some others in the memory. * Important: Assuming that all other ids are under 'signature' id. * If an error occurs, the result is empty. */ std::map<int, float> Memory::computeLikelihood(const Signature * signature, const std::list<int> & ids) { if(!_tfIdfLikelihoodUsed) { UTimer timer; timer.start(); std::map<int, float> likelihood; if(!signature) { ULOGGER_ERROR("The signature is null"); return likelihood; } else if(ids.empty()) { UWARN("ids list is empty"); return likelihood; } for(std::list<int>::const_iterator iter = ids.begin(); iter!=ids.end(); ++iter) { float sim = 0.0f; if(*iter > 0) { const Signature * sB = this->getSignature(*iter); if(!sB) { UFATAL("Signature %d not found in WM ?!?", *iter); } sim = signature->compareTo(*sB); } likelihood.insert(likelihood.end(), std::pair<int, float>(*iter, sim)); } UDEBUG("compute likelihood (similarity)... %f s", timer.ticks()); return likelihood; } else { UTimer timer; timer.start(); std::map<int, float> likelihood; std::map<int, float> calculatedWordsRatio; if(!signature) { ULOGGER_ERROR("The signature is null"); return likelihood; } else if(ids.empty()) { UWARN("ids list is empty"); return likelihood; } for(std::list<int>::const_iterator iter = ids.begin(); iter!=ids.end(); ++iter) { likelihood.insert(likelihood.end(), std::pair<int, float>(*iter, 0.0f)); } const std::list<int> & wordIds = uUniqueKeys(signature->getWords()); float nwi; // nwi is the number of a specific word referenced by a place float ni; // ni is the total of words referenced by a place float nw; // nw is the number of places referenced by a specific word float N; // N is the total number of places float logNnw; const VisualWord * vw; N = this->getSignatures().size(); if(N) { UDEBUG("processing... "); // Pour chaque mot dans la signature SURF for(std::list<int>::const_iterator i=wordIds.begin(); i!=wordIds.end(); ++i) { if(*i>0) { // "Inverted index" - Pour chaque endroit contenu dans chaque mot vw = _vwd->getWord(*i); UASSERT(vw!=0); const std::map<int, int> & refs = vw->getReferences(); nw = refs.size(); if(nw) { logNnw = log10(N/nw); if(logNnw) { for(std::map<int, int>::const_iterator j=refs.begin(); j!=refs.end(); ++j) { std::map<int, float>::iterator iter = likelihood.find(j->first); if(iter != likelihood.end()) { nwi = j->second; ni = this->getNi(j->first); if(ni != 0) { //UDEBUG("%d, %f %f %f %f", vw->id(), logNnw, nwi, ni, ( nwi * logNnw ) / ni); iter->second += ( nwi * logNnw ) / ni; } } } } } } } } UDEBUG("compute likelihood (tf-idf) %f s", timer.ticks()); return likelihood; } } // Weights of the signatures in the working memory <signature id, weight> std::map<int, int> Memory::getWeights() const { std::map<int, int> weights; for(std::map<int, double>::const_iterator iter=_workingMem.begin(); iter!=_workingMem.end(); ++iter) { if(iter->first > 0) { const Signature * s = this->getSignature(iter->first); if(!s) { UFATAL("Location %d must exist in memory", iter->first); } weights.insert(weights.end(), std::make_pair(iter->first, s->getWeight())); } else { weights.insert(weights.end(), std::make_pair(iter->first, -1)); } } return weights; } std::list<int> Memory::forget(const std::set<int> & ignoredIds) { UDEBUG(""); std::list<int> signaturesRemoved; if(this->isIncremental() && _vwd->isIncremental() && _vwd->getVisualWords().size() && !_vwd->isIncrementalFlann()) { // Note that when using incremental FLANN, the number of words // is not the biggest issue, so use the number of signatures instead // of the number of words int newWords = 0; int wordsRemoved = 0; // Get how many new words added for the last run... newWords = _vwd->getNotIndexedWordsCount(); // So we need to remove at least "newWords" words from the // dictionary to respect the limit. while(wordsRemoved < newWords) { std::list<Signature *> signatures = this->getRemovableSignatures(1, ignoredIds); if(signatures.size()) { Signature * s = dynamic_cast<Signature *>(signatures.front()); if(s) { signaturesRemoved.push_back(s->id()); this->moveToTrash(s); wordsRemoved = _vwd->getUnusedWordsSize(); } else { break; } } else { break; } } UDEBUG("newWords=%d, wordsRemoved=%d", newWords, wordsRemoved); } else { UDEBUG(""); // Remove one more than total added during the iteration int signaturesAdded = _signaturesAdded; std::list<Signature *> signatures = getRemovableSignatures(signaturesAdded+1, ignoredIds); for(std::list<Signature *>::iterator iter=signatures.begin(); iter!=signatures.end(); ++iter) { signaturesRemoved.push_back((*iter)->id()); // When a signature is deleted, it notifies the memory // and it is removed from the memory list this->moveToTrash(*iter); } if((int)signatures.size() < signaturesAdded) { UWARN("Less signatures transferred (%d) than added (%d)! The working memory cannot decrease in size.", (int)signatures.size(), signaturesAdded); } else { UDEBUG("signaturesRemoved=%d, _signaturesAdded=%d", (int)signatures.size(), signaturesAdded); } } return signaturesRemoved; } int Memory::cleanup() { UDEBUG(""); int signatureRemoved = 0; // bad signature if(_lastSignature && ((_lastSignature->isBadSignature() && _badSignaturesIgnored) || !_incrementalMemory)) { if(_lastSignature->isBadSignature()) { UDEBUG("Bad signature! %d", _lastSignature->id()); } signatureRemoved = _lastSignature->id(); moveToTrash(_lastSignature, _incrementalMemory); } return signatureRemoved; } void Memory::saveStatistics(const Statistics & statistics) { if(_dbDriver) { _dbDriver->addStatistics(statistics); } } void Memory::emptyTrash() { if(_dbDriver) { _dbDriver->emptyTrashes(true); } } void Memory::joinTrashThread() { if(_dbDriver) { UDEBUG(""); _dbDriver->join(); UDEBUG(""); } } class WeightAgeIdKey { public: WeightAgeIdKey(int w, double a, int i) : weight(w), age(a), id(i){} bool operator<(const WeightAgeIdKey & k) const { if(weight < k.weight) { return true; } else if(weight == k.weight) { if(age < k.age) { return true; } else if(age == k.age) { if(id < k.id) { return true; } } } return false; } int weight, age, id; }; std::list<Signature *> Memory::getRemovableSignatures(int count, const std::set<int> & ignoredIds) { //UDEBUG(""); std::list<Signature *> removableSignatures; std::map<WeightAgeIdKey, Signature *> weightAgeIdMap; // Find the last index to check... UDEBUG("mem.size()=%d, ignoredIds.size()=%d", (int)_workingMem.size(), (int)ignoredIds.size()); if(_workingMem.size()) { int recentWmMaxSize = _recentWmRatio * float(_workingMem.size()); bool recentWmImmunized = false; // look for the position of the lastLoopClosureId in WM int currentRecentWmSize = 0; if(_lastGlobalLoopClosureId > 0 && _stMem.find(_lastGlobalLoopClosureId) == _stMem.end()) { // If set, it must be in WM std::map<int, double>::const_iterator iter = _workingMem.find(_lastGlobalLoopClosureId); while(iter != _workingMem.end()) { ++currentRecentWmSize; ++iter; } if(currentRecentWmSize>1 && currentRecentWmSize < recentWmMaxSize) { recentWmImmunized = true; } else if(currentRecentWmSize == 0 && _workingMem.size() > 1) { UERROR("Last loop closure id not found in WM (%d)", _lastGlobalLoopClosureId); } UDEBUG("currentRecentWmSize=%d, recentWmMaxSize=%d, _recentWmRatio=%f, end recent wM = %d", currentRecentWmSize, recentWmMaxSize, _recentWmRatio, _lastGlobalLoopClosureId); } // Ignore neighbor of the last location in STM (for neighbor links redirection issue during Rehearsal). Signature * lastInSTM = 0; if(_stMem.size()) { lastInSTM = _signatures.at(*_stMem.begin()); } for(std::map<int, double>::const_iterator memIter = _workingMem.begin(); memIter != _workingMem.end(); ++memIter) { if( (recentWmImmunized && memIter->first > _lastGlobalLoopClosureId) || memIter->first == _lastGlobalLoopClosureId) { // ignore recent memory } else if(memIter->first > 0 && ignoredIds.find(memIter->first) == ignoredIds.end() && (!lastInSTM || !lastInSTM->hasLink(memIter->first))) { Signature * s = this->_getSignature(memIter->first); if(s) { // Links must not be in STM to be removable, rehearsal issue bool foundInSTM = false; for(std::map<int, Link>::const_iterator iter = s->getLinks().begin(); iter!=s->getLinks().end(); ++iter) { if(_stMem.find(iter->first) != _stMem.end()) { UDEBUG("Ignored %d because it has a link (%d) to STM", s->id(), iter->first); foundInSTM = true; break; } } if(!foundInSTM) { // less weighted signature priority to be transferred weightAgeIdMap.insert(std::make_pair(WeightAgeIdKey(s->getWeight(), _transferSortingByWeightId?0.0:memIter->second, s->id()), s)); } } else { ULOGGER_ERROR("Not supposed to occur!!!"); } } else { //UDEBUG("Ignoring id %d", memIter->first); } } int recentWmCount = 0; // make the list of removable signatures // Criteria : Weight -> ID UDEBUG("signatureMap.size()=%d _lastGlobalLoopClosureId=%d currentRecentWmSize=%d recentWmMaxSize=%d", (int)weightAgeIdMap.size(), _lastGlobalLoopClosureId, currentRecentWmSize, recentWmMaxSize); for(std::map<WeightAgeIdKey, Signature*>::iterator iter=weightAgeIdMap.begin(); iter!=weightAgeIdMap.end(); ++iter) { if(!recentWmImmunized) { UDEBUG("weight=%d, id=%d", iter->second->getWeight(), iter->second->id()); removableSignatures.push_back(iter->second); if(_lastGlobalLoopClosureId && iter->second->id() > _lastGlobalLoopClosureId) { ++recentWmCount; if(currentRecentWmSize - recentWmCount < recentWmMaxSize) { UDEBUG("switched recentWmImmunized"); recentWmImmunized = true; } } } else if(_lastGlobalLoopClosureId == 0 || iter->second->id() < _lastGlobalLoopClosureId) { UDEBUG("weight=%d, id=%d", iter->second->getWeight(), iter->second->id()); removableSignatures.push_back(iter->second); } if(removableSignatures.size() >= (unsigned int)count) { break; } } } else { ULOGGER_WARN("not enough signatures to get an old one..."); } return removableSignatures; } /** * If saveToDatabase=false, deleted words are filled in deletedWords. */ void Memory::moveToTrash(Signature * s, bool keepLinkedToGraph, std::list<int> * deletedWords) { UDEBUG("id=%d", s?s->id():0); if(s) { // If not saved to database or it is a bad signature (not saved), remove links! if(!keepLinkedToGraph || (!s->isSaved() && s->isBadSignature() && _badSignaturesIgnored)) { UASSERT_MSG(this->isInSTM(s->id()), uFormat("Deleting location (%d) outside the " "STM is not implemented!", s->id()).c_str()); const std::map<int, Link> & links = s->getLinks(); for(std::map<int, Link>::const_iterator iter=links.begin(); iter!=links.end(); ++iter) { Signature * sTo = this->_getSignature(iter->first); // neighbor to s UASSERT_MSG(sTo!=0, uFormat("A neighbor (%d) of the deleted location %d is " "not found in WM/STM! Are you deleting a location " "outside the STM?", iter->first, s->id()).c_str()); if(iter->first > s->id() && links.size()>1 && sTo->hasLink(s->id())) { UWARN("Link %d of %d is newer, removing neighbor link " "may split the map!", iter->first, s->id()); } // child if(iter->second.type() == Link::kGlobalClosure && s->id() > sTo->id()) { sTo->setWeight(sTo->getWeight() + s->getWeight()); // copy weight } sTo->removeLink(s->id()); } s->removeLinks(); // remove all links s->setWeight(0); s->setLabel(""); // reset label } else { // Make sure that virtual links are removed. // It should be called before the signature is // removed from _signatures below. removeVirtualLinks(s->id()); } this->disableWordsRef(s->id()); if(!keepLinkedToGraph) { std::list<int> keys = uUniqueKeys(s->getWords()); for(std::list<int>::const_iterator i=keys.begin(); i!=keys.end(); ++i) { // assume just removed word doesn't have any other references VisualWord * w = _vwd->getUnusedWord(*i); if(w) { std::vector<VisualWord*> wordToDelete; wordToDelete.push_back(w); _vwd->removeWords(wordToDelete); if(deletedWords) { deletedWords->push_back(w->id()); } delete w; } } } _workingMem.erase(s->id()); _stMem.erase(s->id()); _signatures.erase(s->id()); if(_signaturesAdded>0) { --_signaturesAdded; } if(_lastSignature == s) { _lastSignature = 0; if(_stMem.size()) { _lastSignature = this->_getSignature(*_stMem.rbegin()); } else if(_workingMem.size()) { _lastSignature = this->_getSignature(_workingMem.rbegin()->first); } } if(_lastGlobalLoopClosureId == s->id()) { _lastGlobalLoopClosureId = 0; } if( (_notLinkedNodesKeptInDb || keepLinkedToGraph) && _dbDriver && s->id()>0 && (_incrementalMemory || s->isSaved())) { _dbDriver->asyncSave(s); } else { delete s; } } } int Memory::getLastSignatureId() const { return _idCount; } const Signature * Memory::getLastWorkingSignature() const { UDEBUG(""); return _lastSignature; } int Memory::getSignatureIdByLabel(const std::string & label, bool lookInDatabase) const { UDEBUG("label=%s", label.c_str()); int id = 0; if(label.size()) { for(std::map<int, Signature*>::const_iterator iter=_signatures.begin(); iter!=_signatures.end(); ++iter) { UASSERT(iter->second != 0); if(iter->second->getLabel().compare(label) == 0) { id = iter->second->id(); break; } } if(id == 0 && _dbDriver && lookInDatabase) { _dbDriver->getNodeIdByLabel(label, id); } } return id; } bool Memory::labelSignature(int id, const std::string & label) { // verify that this label is not used int idFound=getSignatureIdByLabel(label); if(idFound == 0 || idFound == id) { Signature * s = this->_getSignature(id); if(s) { s->setLabel(label); _linksChanged = s->isSaved(); // HACK to get label updated in Localization mode UWARN("Label \"%s\" set to node %d", label.c_str(), id); return true; } else if(_dbDriver) { std::list<int> ids; ids.push_back(id); std::list<Signature *> signatures; _dbDriver->loadSignatures(ids,signatures); if(signatures.size()) { signatures.front()->setLabel(label); UWARN("Label \"%s\" set to node %d", label.c_str(), id); _dbDriver->asyncSave(signatures.front()); // move it again to trash return true; } } else { UERROR("Node %d not found, failed to set label \"%s\"!", id, label.c_str()); } } else if(idFound) { UWARN("Node %d has already label \"%s\"", idFound, label.c_str()); } return false; } std::map<int, std::string> Memory::getAllLabels() const { std::map<int, std::string> labels; for(std::map<int, Signature*>::const_iterator iter = _signatures.begin(); iter!=_signatures.end(); ++iter) { if(!iter->second->getLabel().empty()) { labels.insert(std::make_pair(iter->first, iter->second->getLabel())); } } if(_dbDriver) { _dbDriver->getAllLabels(labels); } return labels; } bool Memory::setUserData(int id, const cv::Mat & data) { Signature * s = this->_getSignature(id); if(s) { s->sensorData().setUserData(data); return true; } else { UERROR("Node %d not found in RAM, failed to set user data (size=%d)!", id, data.total()); } return false; } void Memory::deleteLocation(int locationId, std::list<int> * deletedWords) { UDEBUG("Deleting location %d", locationId); Signature * location = _getSignature(locationId); if(location) { this->moveToTrash(location, false, deletedWords); } } void Memory::removeLink(int oldId, int newId) { //this method assumes receiving oldId < newId, if not switch them Signature * oldS = this->_getSignature(oldId<newId?oldId:newId); Signature * newS = this->_getSignature(oldId<newId?newId:oldId); if(oldS && newS) { UINFO("removing link between location %d and %d", oldS->id(), newS->id()); if(oldS->hasLink(newS->id()) && newS->hasLink(oldS->id())) { Link::Type type = oldS->getLinks().at(newS->id()).type(); if(type == Link::kGlobalClosure && newS->getWeight() > 0) { // adjust the weight oldS->setWeight(oldS->getWeight()+1); newS->setWeight(newS->getWeight()>0?newS->getWeight()-1:0); } oldS->removeLink(newS->id()); newS->removeLink(oldS->id()); if(type!=Link::kVirtualClosure) { _linksChanged = true; } bool noChildrenAnymore = true; for(std::map<int, Link>::const_iterator iter=newS->getLinks().begin(); iter!=newS->getLinks().end(); ++iter) { if(iter->second.type() != Link::kNeighbor && iter->second.type() != Link::kNeighborMerged && iter->first < newS->id()) { noChildrenAnymore = false; break; } } if(noChildrenAnymore && newS->id() == _lastGlobalLoopClosureId) { _lastGlobalLoopClosureId = 0; } } else { UERROR("Signatures %d and %d don't have bidirectional link!", oldS->id(), newS->id()); } } else { if(!newS) { UERROR("Signature %d is not in working memory... cannot remove link.", newS->id()); } if(!oldS) { UERROR("Signature %d is not in working memory... cannot remove link.", oldS->id()); } } } void Memory::removeRawData(int id, bool image, bool scan, bool userData) { Signature * s = this->_getSignature(id); if(s) { if(image && (!_reextractLoopClosureFeatures || !_registrationPipeline->isImageRequired())) { s->sensorData().setImageRaw(cv::Mat()); s->sensorData().setDepthOrRightRaw(cv::Mat()); } if(scan && !_registrationPipeline->isScanRequired()) { s->sensorData().setLaserScanRaw(cv::Mat(), s->sensorData().laserScanInfo()); } if(userData && !_registrationPipeline->isUserDataRequired()) { s->sensorData().setUserDataRaw(cv::Mat()); } } } // compute transform fromId -> toId Transform Memory::computeTransform( int fromId, int toId, Transform guess, RegistrationInfo * info, bool useKnownCorrespondencesIfPossible) { Signature * fromS = this->_getSignature(fromId); Signature * toS = this->_getSignature(toId); Transform transform; if(fromS && toS) { return computeTransform(*fromS, *toS, guess, info, useKnownCorrespondencesIfPossible); } else { std::string msg = uFormat("Did not find nodes %d and/or %d", fromId, toId); if(info) { info->rejectedMsg = msg; } UWARN(msg.c_str()); } return transform; } // compute transform fromId -> toId Transform Memory::computeTransform( Signature & fromS, Signature & toS, Transform guess, RegistrationInfo * info, bool useKnownCorrespondencesIfPossible) const { Transform transform; // make sure we have all data needed // load binary data from database if not in RAM (if image is already here, scan and userData should be or they are null) if(((_reextractLoopClosureFeatures && _registrationPipeline->isImageRequired()) && fromS.sensorData().imageCompressed().empty()) || (_registrationPipeline->isScanRequired() && fromS.sensorData().imageCompressed().empty() && fromS.sensorData().laserScanCompressed().empty()) || (_registrationPipeline->isUserDataRequired() && fromS.sensorData().imageCompressed().empty() && fromS.sensorData().userDataCompressed().empty())) { fromS.sensorData() = getNodeData(fromS.id()); } if(((_reextractLoopClosureFeatures && _registrationPipeline->isImageRequired()) && toS.sensorData().imageCompressed().empty()) || (_registrationPipeline->isScanRequired() && toS.sensorData().imageCompressed().empty() && toS.sensorData().laserScanCompressed().empty()) || (_registrationPipeline->isUserDataRequired() && toS.sensorData().imageCompressed().empty() && toS.sensorData().userDataCompressed().empty())) { toS.sensorData() = getNodeData(toS.id()); } // uncompress only what we need cv::Mat imgBuf, depthBuf, laserBuf, userBuf; fromS.sensorData().uncompressData( (_reextractLoopClosureFeatures && _registrationPipeline->isImageRequired())?&imgBuf:0, (_reextractLoopClosureFeatures && _registrationPipeline->isImageRequired())?&depthBuf:0, _registrationPipeline->isScanRequired()?&laserBuf:0, _registrationPipeline->isUserDataRequired()?&userBuf:0); toS.sensorData().uncompressData( (_reextractLoopClosureFeatures && _registrationPipeline->isImageRequired())?&imgBuf:0, (_reextractLoopClosureFeatures && _registrationPipeline->isImageRequired())?&depthBuf:0, _registrationPipeline->isScanRequired()?&laserBuf:0, _registrationPipeline->isUserDataRequired()?&userBuf:0); // compute transform fromId -> toId std::vector<int> inliersV; if((_reextractLoopClosureFeatures && _registrationPipeline->isImageRequired()) || (fromS.getWords().size() && toS.getWords().size()) || (!guess.isNull() && !_registrationPipeline->isImageRequired())) { Signature tmpFrom = fromS; Signature tmpTo = toS; if(_reextractLoopClosureFeatures && _registrationPipeline->isImageRequired()) { UDEBUG(""); tmpFrom.setWords(std::multimap<int, cv::KeyPoint>()); tmpFrom.setWords3(std::multimap<int, cv::Point3f>()); tmpFrom.setWordsDescriptors(std::multimap<int, cv::Mat>()); tmpFrom.sensorData().setFeatures(std::vector<cv::KeyPoint>(), std::vector<cv::Point3f>(), cv::Mat()); tmpTo.setWords(std::multimap<int, cv::KeyPoint>()); tmpTo.setWords3(std::multimap<int, cv::Point3f>()); tmpTo.setWordsDescriptors(std::multimap<int, cv::Mat>()); tmpTo.sensorData().setFeatures(std::vector<cv::KeyPoint>(), std::vector<cv::Point3f>(), cv::Mat()); } else if(useKnownCorrespondencesIfPossible) { // This will make RegistrationVis bypassing the correspondences computation tmpFrom.setWordsDescriptors(std::multimap<int, cv::Mat>()); tmpTo.setWordsDescriptors(std::multimap<int, cv::Mat>()); } if(guess.isNull() && !_registrationPipeline->isImageRequired()) { UDEBUG(""); // no visual in the pipeline, make visual registration for guess RegistrationVis regVis(parameters_); guess = regVis.computeTransformation(tmpFrom, tmpTo, guess, info); if(!guess.isNull()) { transform = _registrationPipeline->computeTransformationMod(tmpFrom, tmpTo, guess, info); } } else { transform = _registrationPipeline->computeTransformationMod(tmpFrom, tmpTo, guess, info); } if(!transform.isNull()) { UDEBUG(""); // verify if it is a 180 degree transform, well verify > 90 float x,y,z, roll,pitch,yaw; transform.getTranslationAndEulerAngles(x,y,z, roll,pitch,yaw); if(fabs(pitch) > CV_PI/2 || fabs(yaw) > CV_PI/2) { transform.setNull(); std::string msg = uFormat("Too large rotation detected! (pitch=%f, yaw=%f) max is %f", roll, pitch, yaw, CV_PI/2); UINFO(msg.c_str()); if(info) { info->rejectedMsg = msg; } } else if(info && !transform.isIdentity()) { //normalize variance info->varianceLin *= transform.getNorm(); info->varianceAng *= transform.getAngle(); info->varianceLin = info->varianceLin>0.0f?info->varianceLin:0.0001f; // epsilon if exact transform info->varianceAng = info->varianceAng>0.0f?info->varianceAng:0.0001f; // epsilon if exact transform } } } return transform; } // compute transform fromId -> toId Transform Memory::computeIcpTransform( int fromId, int toId, Transform guess, RegistrationInfo * info) { Signature * fromS = this->_getSignature(fromId); Signature * toS = this->_getSignature(toId); if(fromS && toS && _dbDriver) { std::list<Signature*> depthsToLoad; //if image is already here, scan should be or it is null if(fromS->sensorData().imageCompressed().empty() && fromS->sensorData().laserScanCompressed().empty()) { depthsToLoad.push_back(fromS); } if(toS->sensorData().imageCompressed().empty() && toS->sensorData().laserScanCompressed().empty()) { depthsToLoad.push_back(toS); } if(depthsToLoad.size()) { _dbDriver->loadNodeData(depthsToLoad); } } Transform t; if(fromS && toS) { //make sure data are uncompressed cv::Mat tmp1, tmp2; fromS->sensorData().uncompressData(0, 0, &tmp1); toS->sensorData().uncompressData(0, 0, &tmp2); // compute transform fromId -> toId std::vector<int> inliersV; t = _registrationIcp->computeTransformation(fromS->sensorData(), toS->sensorData(), guess, info); if(!t.isNull() && !t.isIdentity() && info) { // normalize variance info->varianceLin *= t.getNorm(); info->varianceAng *= t.getAngle(); info->varianceLin = info->varianceLin>0.0f?info->varianceLin:0.0001f; // epsilon if exact transform info->varianceAng = info->varianceAng>0.0f?info->varianceAng:0.0001f; // epsilon if exact transform } } else { std::string msg = uFormat("Did not find nodes %d and/or %d", fromId, toId); if(info) { info->rejectedMsg = msg; } UWARN(msg.c_str()); } return t; } // compute transform fromId -> multiple toId Transform Memory::computeIcpTransformMulti( int fromId, int toId, const std::map<int, Transform> & poses, RegistrationInfo * info) { UASSERT(uContains(poses, fromId) && uContains(_signatures, fromId)); UASSERT(uContains(poses, toId) && uContains(_signatures, toId)); UDEBUG("Guess=%s", (poses.at(fromId).inverse() * poses.at(toId)).prettyPrint().c_str()); // make sure that all laser scans are loaded std::list<Signature*> depthToLoad; for(std::map<int, Transform>::const_iterator iter = poses.begin(); iter!=poses.end(); ++iter) { Signature * s = _getSignature(iter->first); UASSERT(s != 0); //if image is already here, scan should be or it is null if(s->sensorData().imageCompressed().empty() && s->sensorData().laserScanCompressed().empty()) { depthToLoad.push_back(s); } } if(depthToLoad.size() && _dbDriver) { _dbDriver->loadNodeData(depthToLoad); } Signature * fromS = _getSignature(fromId); cv::Mat fromScan; fromS->sensorData().uncompressData(0, 0, &fromScan); Transform t; if(!fromScan.empty()) { // Create a fake signature with all scans merged in oldId referential SensorData assembledData; Transform toPose = poses.at(toId); std::string msg; int maxPoints = fromScan.cols; pcl::PointCloud<pcl::PointXYZ>::Ptr assembledToClouds(new pcl::PointCloud<pcl::PointXYZ>); for(std::map<int, Transform>::const_iterator iter = poses.begin(); iter!=poses.end(); ++iter) { if(iter->first != fromId) { Signature * s = this->_getSignature(iter->first); if(!s->sensorData().laserScanCompressed().empty()) { cv::Mat scan; s->sensorData().uncompressData(0, 0, &scan); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud = util3d::laserScanToPointCloud( scan, s->sensorData().laserScanInfo().localTransform() * toPose.inverse() * iter->second); if(scan.cols > maxPoints) { maxPoints = scan.cols; } *assembledToClouds += *cloud; } else { UWARN("Depth2D not found for signature %d", iter->first); } } } if(assembledToClouds->size()) { assembledData.setLaserScanRaw( util3d::laserScanFromPointCloud(*assembledToClouds), LaserScanInfo( fromS->sensorData().laserScanInfo().maxPoints()?fromS->sensorData().laserScanInfo().maxPoints():maxPoints, fromS->sensorData().laserScanInfo().maxRange(), Transform::getIdentity())); // scans are in base frame } Transform guess = poses.at(fromId).inverse() * poses.at(toId); std::vector<int> inliersV; t = _registrationIcp->computeTransformation(fromS->sensorData(), assembledData, guess, info); } return t; } bool Memory::addLink(const Link & link, bool addInDatabase) { UASSERT(link.type() > Link::kNeighbor && link.type() != Link::kUndef); ULOGGER_INFO("to=%d, from=%d transform: %s var=%f", link.to(), link.from(), link.transform().prettyPrint().c_str(), link.transVariance()); Signature * toS = _getSignature(link.to()); Signature * fromS = _getSignature(link.from()); if(toS && fromS) { if(toS->hasLink(link.from())) { // do nothing, already merged UINFO("already linked! to=%d, from=%d", link.to(), link.from()); return true; } UDEBUG("Add link between %d and %d", toS->id(), fromS->id()); toS->addLink(link.inverse()); fromS->addLink(link); if(_incrementalMemory) { if(link.type()!=Link::kVirtualClosure) { _linksChanged = true; // update weight // ignore scan matching loop closures if(link.type() != Link::kLocalSpaceClosure || link.userDataCompressed().empty()) { _lastGlobalLoopClosureId = fromS->id()>toS->id()?fromS->id():toS->id(); // update weights only if the memory is incremental // When reducing the graph, transfer weight to the oldest signature UASSERT(fromS->getWeight() >= 0 && toS->getWeight() >=0); if((_reduceGraph && fromS->id() < toS->id()) || (!_reduceGraph && fromS->id() > toS->id())) { fromS->setWeight(fromS->getWeight() + toS->getWeight()); toS->setWeight(0); } else { toS->setWeight(toS->getWeight() + fromS->getWeight()); fromS->setWeight(0); } } } } } else if(!addInDatabase) { if(!fromS) { UERROR("from=%d, to=%d, Signature %d not found in working/st memories", link.from(), link.to(), link.from()); } if(!toS) { UERROR("from=%d, to=%d, Signature %d not found in working/st memories", link.from(), link.to(), link.to()); } return false; } else if(fromS) { UDEBUG("Add link between %d and %d (db)", link.from(), link.to()); fromS->addLink(link); _dbDriver->addLink(link.inverse()); } else if(toS) { UDEBUG("Add link between %d (db) and %d", link.from(), link.to()); _dbDriver->addLink(link); toS->addLink(link.inverse()); } else { UDEBUG("Add link between %d (db) and %d (db)", link.from(), link.to()); _dbDriver->addLink(link); _dbDriver->addLink(link.inverse()); } return true; } void Memory::updateLink(const Link & link, bool updateInDatabase) { Signature * fromS = this->_getSignature(link.from()); Signature * toS = this->_getSignature(link.to()); if(fromS && toS) { if(fromS->hasLink(link.to()) && toS->hasLink(link.from())) { Link::Type oldType = fromS->getLinks().at(link.to()).type(); fromS->removeLink(link.to()); toS->removeLink(link.from()); fromS->addLink(link); toS->addLink(link.inverse()); if(oldType!=Link::kVirtualClosure || link.type()!=Link::kVirtualClosure) { _linksChanged = true; } } else { UERROR("fromId=%d and toId=%d are not linked!", link.from(), link.to()); } } else if(!updateInDatabase) { if(!fromS) { UERROR("from=%d, to=%d, Signature %d not found in working/st memories", link.from(), link.to(), link.from()); } if(!toS) { UERROR("from=%d, to=%d, Signature %d not found in working/st memories", link.from(), link.to(), link.to()); } } else if(fromS) { UDEBUG("Update link between %d and %d (db)", link.from(), link.to()); fromS->removeLink(link.to()); fromS->addLink(link); _dbDriver->updateLink(link.inverse()); } else if(toS) { UDEBUG("Update link between %d (db) and %d", link.from(), link.to()); toS->removeLink(link.from()); toS->addLink(link.inverse()); _dbDriver->updateLink(link); } else { UDEBUG("Update link between %d (db) and %d (db)", link.from(), link.to()); _dbDriver->updateLink(link); _dbDriver->updateLink(link.inverse()); } } void Memory::removeAllVirtualLinks() { UDEBUG(""); for(std::map<int, Signature*>::iterator iter=_signatures.begin(); iter!=_signatures.end(); ++iter) { iter->second->removeVirtualLinks(); } } void Memory::removeVirtualLinks(int signatureId) { UDEBUG(""); Signature * s = this->_getSignature(signatureId); if(s) { const std::map<int, Link> & links = s->getLinks(); for(std::map<int, Link>::const_iterator iter=links.begin(); iter!=links.end(); ++iter) { if(iter->second.type() == Link::kVirtualClosure) { Signature * sTo = this->_getSignature(iter->first); if(sTo) { sTo->removeLink(s->id()); } else { UERROR("Link %d of %d not in WM/STM?!?", iter->first, s->id()); } } } s->removeVirtualLinks(); } else { UERROR("Signature %d not in WM/STM?!?", signatureId); } } void Memory::dumpMemory(std::string directory) const { UINFO("Dumping memory to directory \"%s\"", directory.c_str()); this->dumpDictionary((directory+"/DumpMemoryWordRef.txt").c_str(), (directory+"/DumpMemoryWordDesc.txt").c_str()); this->dumpSignatures((directory + "/DumpMemorySign.txt").c_str(), false); this->dumpSignatures((directory + "/DumpMemorySign3.txt").c_str(), true); this->dumpMemoryTree((directory + "/DumpMemoryTree.txt").c_str()); } void Memory::dumpDictionary(const char * fileNameRef, const char * fileNameDesc) const { if(_vwd) { _vwd->exportDictionary(fileNameRef, fileNameDesc); } } void Memory::dumpSignatures(const char * fileNameSign, bool words3D) const { UDEBUG(""); FILE* foutSign = 0; #ifdef _MSC_VER fopen_s(&foutSign, fileNameSign, "w"); #else foutSign = fopen(fileNameSign, "w"); #endif if(foutSign) { fprintf(foutSign, "SignatureID WordsID...\n"); const std::map<int, Signature *> & signatures = this->getSignatures(); for(std::map<int, Signature *>::const_iterator iter=signatures.begin(); iter!=signatures.end(); ++iter) { fprintf(foutSign, "%d ", iter->first); const Signature * ss = dynamic_cast<const Signature *>(iter->second); if(ss) { if(words3D) { const std::multimap<int, cv::Point3f> & ref = ss->getWords3(); for(std::multimap<int, cv::Point3f>::const_iterator jter=ref.begin(); jter!=ref.end(); ++jter) { //show only valid point according to current parameters if(pcl::isFinite(jter->second) && (jter->second.x != 0 || jter->second.y != 0 || jter->second.z != 0)) { fprintf(foutSign, "%d ", (*jter).first); } } } else { const std::multimap<int, cv::KeyPoint> & ref = ss->getWords(); for(std::multimap<int, cv::KeyPoint>::const_iterator jter=ref.begin(); jter!=ref.end(); ++jter) { fprintf(foutSign, "%d ", (*jter).first); } } } fprintf(foutSign, "\n"); } fclose(foutSign); } } void Memory::dumpMemoryTree(const char * fileNameTree) const { UDEBUG(""); FILE* foutTree = 0; #ifdef _MSC_VER fopen_s(&foutTree, fileNameTree, "w"); #else foutTree = fopen(fileNameTree, "w"); #endif if(foutTree) { fprintf(foutTree, "SignatureID Weight NbLoopClosureIds LoopClosureIds... NbChildLoopClosureIds ChildLoopClosureIds...\n"); for(std::map<int, Signature *>::const_iterator i=_signatures.begin(); i!=_signatures.end(); ++i) { fprintf(foutTree, "%d %d", i->first, i->second->getWeight()); std::map<int, Link> loopIds, childIds; for(std::map<int, Link>::const_iterator iter = i->second->getLinks().begin(); iter!=i->second->getLinks().end(); ++iter) { if(iter->second.type() != Link::kNeighbor && iter->second.type() != Link::kNeighborMerged) { if(iter->first < i->first) { childIds.insert(*iter); } else { loopIds.insert(*iter); } } } fprintf(foutTree, " %d", (int)loopIds.size()); for(std::map<int, Link>::const_iterator j=loopIds.begin(); j!=loopIds.end(); ++j) { fprintf(foutTree, " %d", j->first); } fprintf(foutTree, " %d", (int)childIds.size()); for(std::map<int, Link>::const_iterator j=childIds.begin(); j!=childIds.end(); ++j) { fprintf(foutTree, " %d", j->first); } fprintf(foutTree, "\n"); } fclose(foutTree); } } void Memory::rehearsal(Signature * signature, Statistics * stats) { UTimer timer; if(signature->getLinks().size() != 1 || signature->isBadSignature()) { return; } //============================================================ // Compare with the last (not intermediate node) //============================================================ Signature * sB = 0; for(std::set<int>::reverse_iterator iter=_stMem.rbegin(); iter!=_stMem.rend(); ++iter) { Signature * s = this->_getSignature(*iter); UASSERT(s!=0); if(s->getWeight() >= 0 && s->id() != signature->id()) { sB = s; break; } } if(sB) { int id = sB->id(); UDEBUG("Comparing with signature (%d)...", id); float sim = signature->compareTo(*sB); int merged = 0; if(sim >= _similarityThreshold) { if(_incrementalMemory) { if(this->rehearsalMerge(id, signature->id())) { merged = id; } } else { signature->setWeight(signature->getWeight() + 1 + sB->getWeight()); } } if(stats) stats->addStatistic(Statistics::kMemoryRehearsal_merged(), merged); if(stats) stats->addStatistic(Statistics::kMemoryRehearsal_sim(), sim); if(stats) stats->addStatistic(Statistics::kMemoryRehearsal_id(), sim >= _similarityThreshold?id:0); UDEBUG("merged=%d, sim=%f t=%fs", merged, sim, timer.ticks()); } else { if(stats) stats->addStatistic(Statistics::kMemoryRehearsal_merged(), 0); if(stats) stats->addStatistic(Statistics::kMemoryRehearsal_sim(), 0); } } bool Memory::rehearsalMerge(int oldId, int newId) { ULOGGER_INFO("old=%d, new=%d", oldId, newId); Signature * oldS = _getSignature(oldId); Signature * newS = _getSignature(newId); if(oldS && newS && _incrementalMemory) { UASSERT_MSG(oldS->getWeight() >= 0 && newS->getWeight() >= 0, uFormat("%d %d", oldS->getWeight(), newS->getWeight()).c_str()); std::map<int, Link>::const_iterator iter = oldS->getLinks().find(newS->id()); if(iter != oldS->getLinks().end() && iter->second.type() != Link::kNeighbor && iter->second.type() != Link::kNeighborMerged) { // do nothing, already merged UWARN("already merged, old=%d, new=%d", oldId, newId); return false; } UASSERT(!newS->isSaved()); UINFO("Rehearsal merging %d (w=%d) and %d (w=%d)", oldS->id(), oldS->getWeight(), newS->id(), newS->getWeight()); bool fullMerge; bool intermediateMerge = false; if(!newS->getLinks().begin()->second.transform().isNull()) { // we are in metric SLAM mode: // 1) Normal merge if not moving AND has direct link // 2) Transform to intermediate node (weight = -1) if not moving AND hasn't direct link. float x,y,z, roll,pitch,yaw; newS->getLinks().begin()->second.transform().getTranslationAndEulerAngles(x,y,z, roll,pitch,yaw); bool isMoving = fabs(x) > _rehearsalMaxDistance || fabs(y) > _rehearsalMaxDistance || fabs(z) > _rehearsalMaxDistance || fabs(roll) > _rehearsalMaxAngle || fabs(pitch) > _rehearsalMaxAngle || fabs(yaw) > _rehearsalMaxAngle; if(isMoving && _rehearsalWeightIgnoredWhileMoving) { UINFO("Rehearsal ignored because the robot has moved more than %f m or %f rad (\"Mem/RehearsalWeightIgnoredWhileMoving\"=true)", _rehearsalMaxDistance, _rehearsalMaxAngle); return false; } fullMerge = !isMoving && newS->hasLink(oldS->id()); intermediateMerge = !isMoving && !newS->hasLink(oldS->id()); } else { fullMerge = newS->hasLink(oldS->id()) && newS->getLinks().begin()->second.transform().isNull(); } if(fullMerge) { //remove mutual links Link newToOldLink = newS->getLinks().at(oldS->id()); oldS->removeLink(newId); newS->removeLink(oldId); if(_idUpdatedToNewOneRehearsal) { // redirect neighbor links const std::map<int, Link> & links = oldS->getLinks(); for(std::map<int, Link>::const_iterator iter = links.begin(); iter!=links.end(); ++iter) { Link link = iter->second; Link mergedLink = newToOldLink.merge(link, link.type()); UASSERT(mergedLink.from() == newS->id() && mergedLink.to() == link.to()); Signature * s = this->_getSignature(link.to()); if(s) { // modify neighbor "from" s->removeLink(oldS->id()); s->addLink(mergedLink.inverse()); newS->addLink(mergedLink); } else { UERROR("Didn't find neighbor %d of %d in RAM...", link.to(), oldS->id()); } } newS->setLabel(oldS->getLabel()); oldS->setLabel(""); oldS->removeLinks(); // remove all links oldS->addLink(Link(oldS->id(), newS->id(), Link::kGlobalClosure, Transform(), 1, 1)); // to keep track of the merged location // Set old image to new signature this->copyData(oldS, newS); // update weight newS->setWeight(newS->getWeight() + 1 + oldS->getWeight()); if(_lastGlobalLoopClosureId == oldS->id()) { _lastGlobalLoopClosureId = newS->id(); } } else { newS->addLink(Link(newS->id(), oldS->id(), Link::kGlobalClosure, Transform() , 1, 1)); // to keep track of the merged location // update weight oldS->setWeight(newS->getWeight() + 1 + oldS->getWeight()); if(_lastSignature == newS) { _lastSignature = oldS; } } // remove location moveToTrash(_idUpdatedToNewOneRehearsal?oldS:newS, _notLinkedNodesKeptInDb); return true; } else { // update only weights if(_idUpdatedToNewOneRehearsal) { // just update weight int w = oldS->getWeight()>=0?oldS->getWeight():0; newS->setWeight(w + newS->getWeight() + 1); oldS->setWeight(intermediateMerge?-1:0); // convert to intermediate node if(_lastGlobalLoopClosureId == oldS->id()) { _lastGlobalLoopClosureId = newS->id(); } } else // !_idUpdatedToNewOneRehearsal { int w = newS->getWeight()>=0?newS->getWeight():0; oldS->setWeight(w + oldS->getWeight() + 1); newS->setWeight(intermediateMerge?-1:0); // convert to intermediate node } } } else { if(!newS) { UERROR("newId=%d, oldId=%d, Signature %d not found in working/st memories", newId, oldId, newId); } if(!oldS) { UERROR("newId=%d, oldId=%d, Signature %d not found in working/st memories", newId, oldId, oldId); } } return false; } Transform Memory::getOdomPose(int signatureId, bool lookInDatabase) const { Transform pose, groundTruth; int mapId, weight; std::string label; double stamp; getNodeInfo(signatureId, pose, mapId, weight, label, stamp, groundTruth, lookInDatabase); return pose; } Transform Memory::getGroundTruthPose(int signatureId, bool lookInDatabase) const { Transform pose, groundTruth; int mapId, weight; std::string label; double stamp; getNodeInfo(signatureId, pose, mapId, weight, label, stamp, groundTruth, lookInDatabase); return groundTruth; } bool Memory::getNodeInfo(int signatureId, Transform & odomPose, int & mapId, int & weight, std::string & label, double & stamp, Transform & groundTruth, bool lookInDatabase) const { const Signature * s = this->getSignature(signatureId); if(s) { odomPose = s->getPose(); mapId = s->mapId(); weight = s->getWeight(); label = s->getLabel(); stamp = s->getStamp(); groundTruth = s->getGroundTruthPose(); return true; } else if(lookInDatabase && _dbDriver) { return _dbDriver->getNodeInfo(signatureId, odomPose, mapId, weight, label, stamp, groundTruth); } return false; } cv::Mat Memory::getImageCompressed(int signatureId) const { cv::Mat image; const Signature * s = this->getSignature(signatureId); if(s) { image = s->sensorData().imageCompressed(); } if(image.empty() && this->isBinDataKept() && _dbDriver) { SensorData data; _dbDriver->getNodeData(signatureId, data); image = data.imageCompressed(); } return image; } SensorData Memory::getNodeData(int nodeId, bool uncompressedData) const { UDEBUG("nodeId=%d", nodeId); SensorData r; Signature * s = this->_getSignature(nodeId); if(s && !s->sensorData().imageCompressed().empty()) { r = s->sensorData(); } else if(_dbDriver) { // load from database _dbDriver->getNodeData(nodeId, r); } if(uncompressedData) { r.uncompressData(); } return r; } void Memory::getNodeWords(int nodeId, std::multimap<int, cv::KeyPoint> & words, std::multimap<int, cv::Point3f> & words3, std::multimap<int, cv::Mat> & wordsDescriptors) { UDEBUG("nodeId=%d", nodeId); Signature * s = this->_getSignature(nodeId); if(s) { words = s->getWords(); words3 = s->getWords3(); wordsDescriptors = s->getWordsDescriptors(); } else if(_dbDriver) { // load from database std::list<Signature*> signatures; std::list<int> ids; ids.push_back(nodeId); std::set<int> loadedFromTrash; _dbDriver->loadSignatures(ids, signatures, &loadedFromTrash); if(signatures.size()) { words = signatures.front()->getWords(); words3 = signatures.front()->getWords3(); wordsDescriptors = signatures.front()->getWordsDescriptors(); if(loadedFromTrash.size()) { //put back _dbDriver->asyncSave(signatures.front()); } else { delete signatures.front(); } } } } void Memory::getNodeCalibration(int nodeId, std::vector<CameraModel> & models, StereoCameraModel & stereoModel) { UDEBUG("nodeId=%d", nodeId); Signature * s = this->_getSignature(nodeId); if(s) { models = s->sensorData().cameraModels(); stereoModel = s->sensorData().stereoCameraModel(); } else if(_dbDriver) { // load from database _dbDriver->getCalibration(nodeId, models, stereoModel); } } SensorData Memory::getSignatureDataConst(int locationId, bool images, bool scan, bool userData, bool occupancyGrid) const { UDEBUG(""); SensorData r; const Signature * s = this->getSignature(locationId); if(s && (!s->sensorData().imageCompressed().empty() || !s->sensorData().laserScanCompressed().empty() || !s->sensorData().userDataCompressed().empty() || s->sensorData().gridCellSize() != 0.0f)) { r = s->sensorData(); } else if(_dbDriver) { // load from database _dbDriver->getNodeData(locationId, r, images, scan, userData, occupancyGrid); } return r; } void Memory::generateGraph(const std::string & fileName, const std::set<int> & ids) { if(!_dbDriver) { UERROR("A database must must loaded first..."); return; } _dbDriver->generateGraph(fileName, ids, _signatures); } int Memory::getNi(int signatureId) const { int ni = 0; const Signature * s = this->getSignature(signatureId); if(s) { ni = (int)((Signature *)s)->getWords().size(); } else { _dbDriver->getInvertedIndexNi(signatureId, ni); } return ni; } void Memory::copyData(const Signature * from, Signature * to) { UTimer timer; timer.start(); if(from && to) { // words 2d this->disableWordsRef(to->id()); to->setWords(from->getWords()); std::list<int> id; id.push_back(to->id()); this->enableWordsRef(id); if(from->isSaved() && _dbDriver) { _dbDriver->getNodeData(from->id(), to->sensorData()); UDEBUG("Loaded image data from database"); } else { to->sensorData() = (SensorData)from->sensorData(); } to->sensorData().setId(to->id()); to->setPose(from->getPose()); to->setWords3(from->getWords3()); to->setWordsDescriptors(from->getWordsDescriptors()); } else { ULOGGER_ERROR("Can't merge the signatures because there are not same type."); } UDEBUG("Merging time = %fs", timer.ticks()); } class PreUpdateThread : public UThreadNode { public: PreUpdateThread(VWDictionary * vwp) : _vwp(vwp) {} virtual ~PreUpdateThread() {} private: void mainLoop() { if(_vwp) { _vwp->update(); } this->kill(); } VWDictionary * _vwp; }; Signature * Memory::createSignature(const SensorData & data, const Transform & pose, Statistics * stats) { UDEBUG(""); UASSERT(data.imageRaw().empty() || data.imageRaw().type() == CV_8UC1 || data.imageRaw().type() == CV_8UC3); UASSERT_MSG(data.depthOrRightRaw().empty() || ( ( data.depthOrRightRaw().type() == CV_16UC1 || data.depthOrRightRaw().type() == CV_32FC1 || data.depthOrRightRaw().type() == CV_8UC1) && ( (data.imageRaw().empty() && data.depthOrRightRaw().type() != CV_8UC1) || (data.imageRaw().rows % data.depthOrRightRaw().rows == 0 && data.imageRaw().cols % data.depthOrRightRaw().cols == 0))), uFormat("image=(%d/%d) depth=(%d/%d, type=%d [accepted=%d,%d,%d])", data.imageRaw().cols, data.imageRaw().rows, data.depthOrRightRaw().cols, data.depthOrRightRaw().rows, data.depthOrRightRaw().type(), CV_16UC1, CV_32FC1, CV_8UC1).c_str()); UASSERT(data.laserScanRaw().empty() || data.laserScanRaw().type() == CV_32FC2 || data.laserScanRaw().type() == CV_32FC3 || data.laserScanRaw().type() == CV_32FC(4) || data.laserScanRaw().type() == CV_32FC(6)); if(!data.depthOrRightRaw().empty() && data.cameraModels().size() == 0 && !data.stereoCameraModel().isValidForProjection()) { UERROR("Rectified images required! Calibrate your camera."); return 0; } UASSERT(_feature2D != 0); PreUpdateThread preUpdateThread(_vwd); UTimer timer; timer.start(); float t; std::vector<cv::KeyPoint> keypoints; cv::Mat descriptors; bool isIntermediateNode = data.id() < 0 || data.imageRaw().empty(); int id = data.id(); if(_generateIds) { id = this->getNextId(); } else { if(id <= 0) { UERROR("Received image ID is null. " "Please set parameter Mem/GenerateIds to \"true\" or " "make sure the input source provides image ids (seq)."); return 0; } else if(id > _idCount) { _idCount = id; } else { UERROR("Id of acquired image (%d) is smaller than the last in memory (%d). " "Please set parameter Mem/GenerateIds to \"true\" or " "make sure the input source provides image ids (seq) over the last in " "memory, which is %d.", id, _idCount, _idCount); return 0; } } int treeSize= int(_workingMem.size() + _stMem.size()); int meanWordsPerLocation = 0; if(treeSize > 0) { meanWordsPerLocation = _vwd->getTotalActiveReferences() / treeSize; } if(_parallelized) { UDEBUG("Start dictionary update thread"); preUpdateThread.start(); } int preDecimation = 1; std::vector<cv::Point3f> keypoints3D; if(!_useOdometryFeatures || data.keypoints().empty() || (int)data.keypoints().size() != data.descriptors().rows) { if(_feature2D->getMaxFeatures() >= 0 && !data.imageRaw().empty() && !isIntermediateNode) { SensorData decimatedData = data; if(_imagePreDecimation > 1) { preDecimation = _imagePreDecimation; if(!decimatedData.rightRaw().empty() || (decimatedData.depthRaw().rows == decimatedData.imageRaw().rows && decimatedData.depthRaw().cols == decimatedData.imageRaw().cols)) { decimatedData.setDepthOrRightRaw(util2d::decimate(decimatedData.depthOrRightRaw(), _imagePreDecimation)); } decimatedData.setImageRaw(util2d::decimate(decimatedData.imageRaw(), _imagePreDecimation)); std::vector<CameraModel> cameraModels = decimatedData.cameraModels(); for(unsigned int i=0; i<cameraModels.size(); ++i) { cameraModels[i] = cameraModels[i].scaled(1.0/double(_imagePreDecimation)); } decimatedData.setCameraModels(cameraModels); StereoCameraModel stereoModel = decimatedData.stereoCameraModel(); if(stereoModel.isValidForProjection()) { stereoModel.scale(1.0/double(_imagePreDecimation)); } decimatedData.setStereoCameraModel(stereoModel); } UINFO("Extract features"); cv::Mat imageMono; if(decimatedData.imageRaw().channels() == 3) { cv::cvtColor(decimatedData.imageRaw(), imageMono, CV_BGR2GRAY); } else { imageMono = decimatedData.imageRaw(); } cv::Mat depthMask; if(!decimatedData.depthRaw().empty()) { if(imageMono.rows % decimatedData.depthRaw().rows == 0 && imageMono.cols % decimatedData.depthRaw().cols == 0 && imageMono.rows/decimatedData.depthRaw().rows == imageMono.cols/decimatedData.depthRaw().cols) { depthMask = util2d::interpolate(decimatedData.depthRaw(), imageMono.rows/decimatedData.depthRaw().rows, 0.1f); } } int oldMaxFeatures = _feature2D->getMaxFeatures(); UDEBUG("rawDescriptorsKept=%d, pose=%d, maxFeatures=%d, visMaxFeatures=%d", _rawDescriptorsKept?1:0, pose.isNull()?0:1, _feature2D->getMaxFeatures(), _visMaxFeatures); ParametersMap tmpMaxFeatureParameter; if(_rawDescriptorsKept&&!pose.isNull()&&_feature2D->getMaxFeatures()>0&&_feature2D->getMaxFeatures()<_visMaxFeatures) { // The total extracted features should match the number of features used for transformation estimation UDEBUG("Changing temporary max features from %d to %d", _feature2D->getMaxFeatures(), _visMaxFeatures); tmpMaxFeatureParameter.insert(ParametersPair(Parameters::kKpMaxFeatures(), uNumber2Str(_visMaxFeatures))); _feature2D->parseParameters(tmpMaxFeatureParameter); } keypoints = _feature2D->generateKeypoints( imageMono, depthMask); if(tmpMaxFeatureParameter.size()) { tmpMaxFeatureParameter.at(Parameters::kKpMaxFeatures()) = uNumber2Str(oldMaxFeatures); _feature2D->parseParameters(tmpMaxFeatureParameter); // reset back } t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemKeypoints_detection(), t*1000.0f); UDEBUG("time keypoints (%d) = %fs", (int)keypoints.size(), t); descriptors = _feature2D->generateDescriptors(imageMono, keypoints); t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemDescriptors_extraction(), t*1000.0f); UDEBUG("time descriptors (%d) = %fs", descriptors.rows, t); UDEBUG("ratio=%f, meanWordsPerLocation=%d", _badSignRatio, meanWordsPerLocation); if(descriptors.rows && descriptors.rows < _badSignRatio * float(meanWordsPerLocation)) { descriptors = cv::Mat(); } else if((!decimatedData.depthRaw().empty() && decimatedData.cameraModels().size() && decimatedData.cameraModels()[0].isValidForProjection()) || (!decimatedData.rightRaw().empty() && decimatedData.stereoCameraModel().isValidForProjection())) { keypoints3D = _feature2D->generateKeypoints3D(decimatedData, keypoints); t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemKeypoints_3D(), t*1000.0f); UDEBUG("time keypoints 3D (%d) = %fs", (int)keypoints3D.size(), t); } } else if(data.imageRaw().empty()) { UDEBUG("Empty image, cannot extract features..."); } else if(_feature2D->getMaxFeatures() < 0) { UDEBUG("_feature2D->getMaxFeatures()(%d<0) so don't extract any features...", _feature2D->getMaxFeatures()); } else { UDEBUG("Intermediate node detected, don't extract features!"); } } else if(_feature2D->getMaxFeatures() >= 0 && !isIntermediateNode) { UINFO("Use odometry features"); keypoints = data.keypoints(); keypoints3D = data.keypoints3D(); descriptors = data.descriptors().clone(); UASSERT(descriptors.empty() || descriptors.rows == (int)keypoints.size()); UASSERT(keypoints3D.empty() || keypoints3D.size() == keypoints.size()); int maxFeatures = _rawDescriptorsKept&&!pose.isNull()&&_feature2D->getMaxFeatures()>0&&_feature2D->getMaxFeatures()<_visMaxFeatures?_visMaxFeatures:_feature2D->getMaxFeatures(); if((int)keypoints.size() > maxFeatures) { _feature2D->limitKeypoints(keypoints, keypoints3D, descriptors, maxFeatures); } t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemKeypoints_detection(), t*1000.0f); UDEBUG("time keypoints (%d) = %fs", (int)keypoints.size(), t); if(descriptors.empty()) { cv::Mat imageMono; if(data.imageRaw().channels() == 3) { cv::cvtColor(data.imageRaw(), imageMono, CV_BGR2GRAY); } else { imageMono = data.imageRaw(); } descriptors = _feature2D->generateDescriptors(imageMono, keypoints); } t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemDescriptors_extraction(), t*1000.0f); UDEBUG("time descriptors (%d) = %fs", descriptors.rows, t); if(keypoints3D.empty() && ((!data.depthRaw().empty() && data.cameraModels().size() && data.cameraModels()[0].isValidForProjection()) || (!data.rightRaw().empty() && data.stereoCameraModel().isValidForProjection()))) { keypoints3D = _feature2D->generateKeypoints3D(data, keypoints); if(_feature2D->getMinDepth() > 0.0f || _feature2D->getMaxDepth() > 0.0f) { UDEBUG(""); //remove all keypoints/descriptors with no valid 3D points UASSERT((int)keypoints.size() == descriptors.rows && keypoints3D.size() == keypoints.size()); std::vector<cv::KeyPoint> validKeypoints(keypoints.size()); std::vector<cv::Point3f> validKeypoints3D(keypoints.size()); cv::Mat validDescriptors(descriptors.size(), descriptors.type()); int oi=0; for(unsigned int i=0; i<keypoints3D.size(); ++i) { if(util3d::isFinite(keypoints3D[i])) { validKeypoints[oi] = keypoints[i]; validKeypoints3D[oi] = keypoints3D[i]; descriptors.row(i).copyTo(validDescriptors.row(oi)); ++oi; } } UDEBUG("Removed %d invalid 3D points", (int)keypoints3D.size()-oi); validKeypoints.resize(oi); validKeypoints3D.resize(oi); keypoints = validKeypoints; keypoints3D = validKeypoints3D; descriptors = validDescriptors.rowRange(0, oi).clone(); } } t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemKeypoints_3D(), t*1000.0f); UDEBUG("time keypoints 3D (%d) = %fs", (int)keypoints3D.size(), t); UDEBUG("ratio=%f, meanWordsPerLocation=%d", _badSignRatio, meanWordsPerLocation); if(descriptors.rows && descriptors.rows < _badSignRatio * float(meanWordsPerLocation)) { descriptors = cv::Mat(); } } if(_parallelized) { UDEBUG("Joining dictionary update thread..."); preUpdateThread.join(); // Wait the dictionary to be updated UDEBUG("Joining dictionary update thread... thread finished!"); } std::list<int> wordIds; if(descriptors.rows) { t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemJoining_dictionary_update(), t*1000.0f); if(_parallelized) { UDEBUG("time descriptor and memory update (%d of size=%d) = %fs", descriptors.rows, descriptors.cols, t); } else { UDEBUG("time descriptor (%d of size=%d) = %fs", descriptors.rows, descriptors.cols, t); } // In case the number of features we want to do quantization is lower // than extracted ones (that would be used for transform estimation) std::vector<bool> inliers; cv::Mat descriptorsForQuantization = descriptors; std::vector<int> quantizedToRawIndices; if(_feature2D->getMaxFeatures()>0 && descriptors.rows > _feature2D->getMaxFeatures()) { UASSERT((int)keypoints.size() == descriptors.rows); Feature2D::limitKeypoints(keypoints, inliers, _feature2D->getMaxFeatures()); descriptorsForQuantization = cv::Mat(_feature2D->getMaxFeatures(), descriptors.cols, descriptors.type()); quantizedToRawIndices.resize(_feature2D->getMaxFeatures()); unsigned int oi=0; UASSERT((int)inliers.size() == descriptors.rows); for(int k=0; k < descriptors.rows; ++k) { if(inliers[k]) { UASSERT(oi < quantizedToRawIndices.size()); if(descriptors.type() == CV_32FC1) { memcpy(descriptorsForQuantization.ptr<float>(oi), descriptors.ptr<float>(k), descriptors.cols*sizeof(float)); } else { memcpy(descriptorsForQuantization.ptr<char>(oi), descriptors.ptr<char>(k), descriptors.cols*sizeof(char)); } quantizedToRawIndices[oi] = k; ++oi; } } UASSERT((int)oi == _feature2D->getMaxFeatures()); } // Quantization to vocabulary wordIds = _vwd->addNewWords(descriptorsForQuantization, id); // Set ID -1 to features not used for quantization if(wordIds.size() < keypoints.size()) { std::vector<int> allWordIds; allWordIds.resize(keypoints.size(),-1); int i=0; for(std::list<int>::iterator iter=wordIds.begin(); iter!=wordIds.end(); ++iter) { allWordIds[quantizedToRawIndices[i]] = *iter; ++i; } wordIds = uVectorToList(allWordIds); } t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemAdd_new_words(), t*1000.0f); UDEBUG("time addNewWords %fs indexed=%d not=%d", t, _vwd->getIndexedWordsCount(), _vwd->getNotIndexedWordsCount()); } else if(id>0) { UDEBUG("id %d is a bad signature", id); } std::multimap<int, cv::KeyPoint> words; std::multimap<int, cv::Point3f> words3D; std::multimap<int, cv::Mat> wordsDescriptors; if(wordIds.size() > 0) { UASSERT(wordIds.size() == keypoints.size()); UASSERT(keypoints3D.size() == 0 || keypoints3D.size() == wordIds.size()); unsigned int i=0; float decimationRatio = preDecimation / _imagePostDecimation; double log2value = log(double(preDecimation))/log(2.0); for(std::list<int>::iterator iter=wordIds.begin(); iter!=wordIds.end() && i < keypoints.size(); ++iter, ++i) { cv::KeyPoint kpt = keypoints[i]; if(preDecimation != _imagePostDecimation) { // remap keypoints to final image size kpt.pt.x *= decimationRatio; kpt.pt.y *= decimationRatio; kpt.size *= decimationRatio; kpt.octave += log2value; } words.insert(std::pair<int, cv::KeyPoint>(*iter, kpt)); if(keypoints3D.size()) { words3D.insert(std::pair<int, cv::Point3f>(*iter, keypoints3D.at(i))); } if(_rawDescriptorsKept) { wordsDescriptors.insert(std::pair<int, cv::Mat>(*iter, descriptors.row(i).clone())); } } } if(!pose.isNull() && data.cameraModels().size() == 1 && words.size() && words3D.size() == 0 && _signatures.size() && _signatures.rbegin()->second->mapId() == _idMapCount) // same map { UDEBUG("Generate 3D words using odometry"); Signature * previousS = _signatures.rbegin()->second; if(previousS->getWords().size() > 8 && words.size() > 8 && !previousS->getPose().isNull()) { Transform cameraTransform = pose.inverse() * previousS->getPose(); // compute 3D words by epipolar geometry with the previous signature std::map<int, cv::Point3f> inliers = util3d::generateWords3DMono( uMultimapToMapUnique(words), uMultimapToMapUnique(previousS->getWords()), data.cameraModels()[0], cameraTransform); // words3D should have the same size than words float bad_point = std::numeric_limits<float>::quiet_NaN (); for(std::multimap<int, cv::KeyPoint>::const_iterator iter=words.begin(); iter!=words.end(); ++iter) { std::map<int, cv::Point3f>::iterator jter=inliers.find(iter->first); if(jter != inliers.end()) { words3D.insert(std::make_pair(iter->first, jter->second)); } else { words3D.insert(std::make_pair(iter->first, cv::Point3f(bad_point,bad_point,bad_point))); } } t = timer.ticks(); UASSERT(words3D.size() == words.size()); if(stats) stats->addStatistic(Statistics::kTimingMemKeypoints_3D(), t*1000.0f); UDEBUG("time keypoints 3D (%d) = %fs", (int)words3D.size(), t); } } cv::Mat image = data.imageRaw(); cv::Mat depthOrRightImage = data.depthOrRightRaw(); std::vector<CameraModel> cameraModels = data.cameraModels(); StereoCameraModel stereoCameraModel = data.stereoCameraModel(); // apply decimation? if(_imagePostDecimation > 1 && !isIntermediateNode) { if(!data.rightRaw().empty() || (data.depthRaw().rows == image.rows && data.depthRaw().cols == image.cols)) { depthOrRightImage = util2d::decimate(depthOrRightImage, _imagePostDecimation); } image = util2d::decimate(image, _imagePostDecimation); for(unsigned int i=0; i<cameraModels.size(); ++i) { cameraModels[i] = cameraModels[i].scaled(1.0/double(_imagePostDecimation)); } if(stereoCameraModel.isValidForProjection()) { stereoCameraModel.scale(1.0/double(_imagePostDecimation)); } t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemPost_decimation(), t*1000.0f); UDEBUG("time post-decimation = %fs", t); } // downsampling the laser scan? cv::Mat laserScan = data.laserScanRaw(); int maxLaserScanMaxPts = data.laserScanInfo().maxPoints(); if(!laserScan.empty() && _laserScanDownsampleStepSize > 1 && !isIntermediateNode) { laserScan = util3d::downsample(laserScan, _laserScanDownsampleStepSize); maxLaserScanMaxPts /= _laserScanDownsampleStepSize; t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemScan_downsampling(), t*1000.0f); UDEBUG("time downsampling scan = %fs", t); } if(!laserScan.empty() && _laserScanNormalK > 0 && laserScan.channels() == 3 && !isIntermediateNode) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud = util3d::laserScanToPointCloud(laserScan); float x,y,z; data.laserScanInfo().localTransform().getTranslation(x,y,z); pcl::PointCloud<pcl::Normal>::Ptr normals = util3d::computeNormals(cloud, _laserScanNormalK, Eigen::Vector3f(x,y,z)); laserScan = util3d::laserScanFromPointCloud(*cloud, *normals); t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemScan_normals(), t*1000.0f); UDEBUG("time normals scan = %fs", t); } Signature * s; if(this->isBinDataKept() && !isIntermediateNode) { UDEBUG("Bin data kept: rgb=%d, depth=%d, scan=%d, userData=%d", image.empty()?0:1, depthOrRightImage.empty()?0:1, laserScan.empty()?0:1, data.userDataRaw().empty()?0:1); std::vector<unsigned char> imageBytes; std::vector<unsigned char> depthBytes; if(_saveDepth16Format && !depthOrRightImage.empty() && depthOrRightImage.type() == CV_32FC1) { UWARN("Save depth data to 16 bits format: depth type detected is 32FC1, use 16UC1 depth format to avoid this conversion (or set parameter \"Mem/SaveDepth16Format\"=false to use 32bits format)."); depthOrRightImage = util2d::cvtDepthFromFloat(depthOrRightImage); } rtabmap::CompressionThread ctImage(image, std::string(".jpg")); rtabmap::CompressionThread ctDepth(depthOrRightImage, std::string(".png")); rtabmap::CompressionThread ctLaserScan(laserScan); rtabmap::CompressionThread ctUserData(data.userDataRaw()); if(!image.empty()) { ctImage.start(); } if(!depthOrRightImage.empty()) { ctDepth.start(); } if(!laserScan.empty()) { ctLaserScan.start(); } if(!data.userDataRaw().empty()) { ctUserData.start(); } ctImage.join(); ctDepth.join(); ctLaserScan.join(); ctUserData.join(); s = new Signature(id, _idMapCount, isIntermediateNode?-1:0, // tag intermediate nodes as weight=-1 data.stamp(), "", pose, data.groundTruth(), stereoCameraModel.isValidForProjection()? SensorData( ctLaserScan.getCompressedData(), LaserScanInfo(maxLaserScanMaxPts, data.laserScanInfo().maxRange(), data.laserScanInfo().localTransform()), ctImage.getCompressedData(), ctDepth.getCompressedData(), stereoCameraModel, id, 0, ctUserData.getCompressedData()): SensorData( ctLaserScan.getCompressedData(), LaserScanInfo(maxLaserScanMaxPts, data.laserScanInfo().maxRange(), data.laserScanInfo().localTransform()), ctImage.getCompressedData(), ctDepth.getCompressedData(), cameraModels, id, 0, ctUserData.getCompressedData())); } else { UDEBUG("Bin data kept: scan=%d, userData=%d", laserScan.empty()?0:1, data.userDataRaw().empty()?0:1); // just compress user data and laser scan (scans can be used for local scan matching) rtabmap::CompressionThread ctUserData(data.userDataRaw()); rtabmap::CompressionThread ctLaserScan(laserScan); if(!data.userDataRaw().empty() && !isIntermediateNode) { ctUserData.start(); } if(!laserScan.empty() && !isIntermediateNode) { ctLaserScan.start(); } ctUserData.join(); ctLaserScan.join(); s = new Signature(id, _idMapCount, isIntermediateNode?-1:0, // tag intermediate nodes as weight=-1 data.stamp(), "", pose, data.groundTruth(), stereoCameraModel.isValidForProjection()? SensorData( ctLaserScan.getCompressedData(), LaserScanInfo(maxLaserScanMaxPts, data.laserScanInfo().maxRange(), data.laserScanInfo().localTransform()), cv::Mat(), cv::Mat(), stereoCameraModel, id, 0, ctUserData.getCompressedData()): SensorData( ctLaserScan.getCompressedData(), LaserScanInfo(maxLaserScanMaxPts, data.laserScanInfo().maxRange(), data.laserScanInfo().localTransform()), cv::Mat(), cv::Mat(), cameraModels, id, 0, ctUserData.getCompressedData())); } s->setWords(words); s->setWords3(words3D); s->setWordsDescriptors(wordsDescriptors); // set raw data s->sensorData().setImageRaw(image); s->sensorData().setDepthOrRightRaw(depthOrRightImage); s->sensorData().setLaserScanRaw(laserScan, LaserScanInfo(maxLaserScanMaxPts, data.laserScanInfo().maxRange(), data.laserScanInfo().localTransform())); s->sensorData().setUserDataRaw(data.userDataRaw()); s->sensorData().setGroundTruth(data.groundTruth()); t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemCompressing_data(), t*1000.0f); UDEBUG("time compressing data (id=%d) %fs", id, t); if(words.size()) { s->setEnabled(true); // All references are already activated in the dictionary at this point (see _vwd->addNewWords()) } // Occupancy grid map stuff cv::Mat ground, obstacles; float cellSize = 0.0f; cv::Point3f viewPoint(0,0,0); if(_createOccupancyGrid && !data.depthOrRightRaw().empty() && !isIntermediateNode) { _occupancy->createLocalMap(*s, ground, obstacles, viewPoint); cellSize = _occupancy->getCellSize(); t = timer.ticks(); if(stats) stats->addStatistic(Statistics::kTimingMemOccupancy_grid(), t*1000.0f); UDEBUG("time grid map = %fs", t); } s->sensorData().setOccupancyGrid(ground, obstacles, cellSize, viewPoint); return s; } void Memory::disableWordsRef(int signatureId) { UDEBUG("id=%d", signatureId); Signature * ss = this->_getSignature(signatureId); if(ss && ss->isEnabled()) { const std::multimap<int, cv::KeyPoint> & words = ss->getWords(); const std::list<int> & keys = uUniqueKeys(words); int count = _vwd->getTotalActiveReferences(); // First remove all references for(std::list<int>::const_iterator i=keys.begin(); i!=keys.end(); ++i) { _vwd->removeAllWordRef(*i, signatureId); } count -= _vwd->getTotalActiveReferences(); ss->setEnabled(false); UDEBUG("%d words total ref removed from signature %d... (total active ref = %d)", count, ss->id(), _vwd->getTotalActiveReferences()); } } void Memory::cleanUnusedWords() { if(_vwd->isIncremental()) { std::vector<VisualWord*> removedWords = _vwd->getUnusedWords(); UDEBUG("Removing %d words (dictionary size=%d)...", removedWords.size(), _vwd->getVisualWords().size()); if(removedWords.size()) { // remove them from the dictionary _vwd->removeWords(removedWords); for(unsigned int i=0; i<removedWords.size(); ++i) { if(_dbDriver) { _dbDriver->asyncSave(removedWords[i]); } else { delete removedWords[i]; } } } } } void Memory::enableWordsRef(const std::list<int> & signatureIds) { UDEBUG("size=%d", signatureIds.size()); UTimer timer; timer.start(); std::map<int, int> refsToChange; //<oldWordId, activeWordId> std::set<int> oldWordIds; std::list<Signature *> surfSigns; for(std::list<int>::const_iterator i=signatureIds.begin(); i!=signatureIds.end(); ++i) { Signature * ss = dynamic_cast<Signature *>(this->_getSignature(*i)); if(ss && !ss->isEnabled()) { surfSigns.push_back(ss); std::list<int> uniqueKeys = uUniqueKeys(ss->getWords()); //Find words in the signature which they are not in the current dictionary for(std::list<int>::const_iterator k=uniqueKeys.begin(); k!=uniqueKeys.end(); ++k) { if(*k>0 && _vwd->getWord(*k) == 0 && _vwd->getUnusedWord(*k) == 0) { oldWordIds.insert(oldWordIds.end(), *k); } } } } UDEBUG("oldWordIds.size()=%d, getOldIds time=%fs", oldWordIds.size(), timer.ticks()); // the words were deleted, so try to math it with an active word std::list<VisualWord *> vws; if(oldWordIds.size() && _dbDriver) { // get the descriptors _dbDriver->loadWords(oldWordIds, vws); } UDEBUG("loading words(%d) time=%fs", oldWordIds.size(), timer.ticks()); if(vws.size()) { //Search in the dictionary std::vector<int> vwActiveIds = _vwd->findNN(vws); UDEBUG("find active ids (number=%d) time=%fs", vws.size(), timer.ticks()); int i=0; for(std::list<VisualWord *>::iterator iterVws=vws.begin(); iterVws!=vws.end(); ++iterVws) { if(vwActiveIds[i] > 0) { //UDEBUG("Match found %d with %d", (*iterVws)->id(), vwActiveIds[i]); refsToChange.insert(refsToChange.end(), std::pair<int, int>((*iterVws)->id(), vwActiveIds[i])); if((*iterVws)->isSaved()) { delete (*iterVws); } else if(_dbDriver) { _dbDriver->asyncSave(*iterVws); } } else { //add to dictionary _vwd->addWord(*iterVws); // take ownership } ++i; } UDEBUG("Added %d to dictionary, time=%fs", vws.size()-refsToChange.size(), timer.ticks()); //update the global references map and update the signatures reactivated for(std::map<int, int>::const_iterator iter=refsToChange.begin(); iter != refsToChange.end(); ++iter) { //uInsert(_wordRefsToChange, (const std::pair<int, int>)*iter); // This will be used to change references in the database for(std::list<Signature *>::iterator j=surfSigns.begin(); j!=surfSigns.end(); ++j) { (*j)->changeWordsRef(iter->first, iter->second); } } UDEBUG("changing ref, total=%d, time=%fs", refsToChange.size(), timer.ticks()); } int count = _vwd->getTotalActiveReferences(); // Reactivate references and signatures for(std::list<Signature *>::iterator j=surfSigns.begin(); j!=surfSigns.end(); ++j) { const std::vector<int> & keys = uKeys((*j)->getWords()); if(keys.size()) { // Add all references for(unsigned int i=0; i<keys.size(); ++i) { if(keys.at(i)>0) { _vwd->addWordRef(keys.at(i), (*j)->id()); } } (*j)->setEnabled(true); } } count = _vwd->getTotalActiveReferences() - count; UDEBUG("%d words total ref added from %d signatures, time=%fs...", count, surfSigns.size(), timer.ticks()); } std::set<int> Memory::reactivateSignatures(const std::list<int> & ids, unsigned int maxLoaded, double & timeDbAccess) { // get the signatures, if not in the working memory, they // will be loaded from the database in an more efficient way // than how it is done in the Memory UDEBUG(""); UTimer timer; std::list<int> idsToLoad; std::map<int, int>::iterator wmIter; for(std::list<int>::const_iterator i=ids.begin(); i!=ids.end(); ++i) { if(!this->getSignature(*i) && !uContains(idsToLoad, *i)) { if(!maxLoaded || idsToLoad.size() < maxLoaded) { idsToLoad.push_back(*i); UINFO("Loading location %d from database...", *i); } } } UDEBUG("idsToLoad = %d", idsToLoad.size()); std::list<Signature *> reactivatedSigns; if(_dbDriver) { _dbDriver->loadSignatures(idsToLoad, reactivatedSigns); } timeDbAccess = timer.getElapsedTime(); std::list<int> idsLoaded; for(std::list<Signature *>::iterator i=reactivatedSigns.begin(); i!=reactivatedSigns.end(); ++i) { idsLoaded.push_back((*i)->id()); //append to working memory this->addSignatureToWmFromLTM(*i); } this->enableWordsRef(idsLoaded); UDEBUG("time = %fs", timer.ticks()); return std::set<int>(idsToLoad.begin(), idsToLoad.end()); } // return all non-null poses // return unique links between nodes (for neighbors: old->new, for loops: parent->child) void Memory::getMetricConstraints( const std::set<int> & ids, std::map<int, Transform> & poses, std::multimap<int, Link> & links, bool lookInDatabase) { UDEBUG(""); for(std::set<int>::const_iterator iter=ids.begin(); iter!=ids.end(); ++iter) { Transform pose = getOdomPose(*iter, lookInDatabase); if(!pose.isNull()) { poses.insert(std::make_pair(*iter, pose)); } } for(std::set<int>::const_iterator iter=ids.begin(); iter!=ids.end(); ++iter) { if(uContains(poses, *iter)) { std::map<int, Link> tmpLinks = getLinks(*iter, lookInDatabase); for(std::map<int, Link>::iterator jter=tmpLinks.begin(); jter!=tmpLinks.end(); ++jter) { if( jter->second.isValid() && uContains(poses, jter->first) && graph::findLink(links, *iter, jter->first) == links.end()) { if(!lookInDatabase && (jter->second.type() == Link::kNeighbor || jter->second.type() == Link::kNeighborMerged)) { Link link = jter->second; const Signature * s = this->getSignature(jter->first); UASSERT(s!=0); while(s && s->getWeight() == -1) { // skip to next neighbor, well we assume that bad signatures // are only linked by max 2 neighbor links. std::map<int, Link> n = this->getNeighborLinks(s->id(), false); UASSERT(n.size() <= 2); std::map<int, Link>::iterator uter = n.upper_bound(s->id()); if(uter != n.end()) { const Signature * s2 = this->getSignature(uter->first); if(s2) { link = link.merge(uter->second, uter->second.type()); poses.erase(s->id()); s = s2; } } else { break; } } links.insert(std::make_pair(*iter, link)); } else { links.insert(std::make_pair(*iter, jter->second)); } } } } } } } // namespace rtabmap
30.455368
256
0.644549
[ "geometry", "vector", "transform", "3d" ]
339caee1626de57ff71e94d7ef388ff09a9abbe9
203,018
cc
C++
src/validator/strata_support.cc
AlexShypula/stoke
d68dc566d8db5ebd304cbda09710eb7f7d6457e3
[ "ECL-2.0", "Apache-2.0" ]
645
2016-02-10T19:14:21.000Z
2022-03-20T15:19:08.000Z
src/validator/strata_support.cc
AlexShypula/stoke
d68dc566d8db5ebd304cbda09710eb7f7d6457e3
[ "ECL-2.0", "Apache-2.0" ]
191
2016-02-10T00:45:50.000Z
2021-02-21T19:18:32.000Z
src/validator/strata_support.cc
AlexShypula/stoke
d68dc566d8db5ebd304cbda09710eb7f7d6457e3
[ "ECL-2.0", "Apache-2.0" ]
67
2016-02-09T15:15:28.000Z
2022-03-02T16:33:31.000Z
// Copyright 2013-2015 Stanford University // // 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 <chrono> #include <fstream> #include <iostream> #include <random> #include <string> #include <vector> #include <algorithm> #include <set> #include <regex> #include "src/ext/x64asm/src/opcode.h" #include "src/ext/x64asm/src/instruction.h" #include "src/validator/strata_support.h" using namespace std; using namespace x64asm; namespace stoke { vector<Opcode> instr_cat_imm8_ = { BLENDPD_XMM_XMM_IMM8 // BLENDPD xmm, xmm, imm8 , BLENDPS_XMM_XMM_IMM8 // BLENDPS xmm, xmm, imm8 , CMPPD_XMM_XMM_IMM8 // CMPPD xmm, xmm, imm8 , CMPPS_XMM_XMM_IMM8 // CMPPS xmm, xmm, imm8 , CMPSD_XMM_XMM_IMM8 // CMPSD xmm, xmm, imm8 , CMPSS_XMM_XMM_IMM8 // CMPSS xmm, xmm, imm8 , DPPD_XMM_XMM_IMM8 // DPPD xmm, xmm, imm8 , DPPS_XMM_XMM_IMM8 // DPPS xmm, xmm, imm8 , EXTRACTPS_R32_XMM_IMM8 // EXTRACTPS r32, xmm, imm8 , EXTRACTPS_R64_XMM_IMM8 // EXTRACTPS r64, xmm, imm8 , INSERTPS_XMM_XMM_IMM8 // INSERTPS xmm, xmm, imm8 , MPSADBW_XMM_XMM_IMM8 // MPSADBW xmm, xmm, imm8 // , PALIGNR_MM_MM_IMM8 // PALIGNR mm, mm, imm8 , PALIGNR_XMM_XMM_IMM8 // PALIGNR xmm, xmm, imm8 , PBLENDW_XMM_XMM_IMM8 // PBLENDW xmm, xmm, imm8 , PCLMULQDQ_XMM_XMM_IMM8 // PCLMULQDQ xmm, xmm, imm8 , PCMPESTRI_XMM_XMM_IMM8 // PCMPESTRI xmm, xmm, imm8 , PCMPESTRM_XMM_XMM_IMM8 // PCMPESTRM xmm, xmm, imm8 , PCMPISTRI_XMM_XMM_IMM8 // PCMPISTRI xmm, xmm, imm8 , PCMPISTRM_XMM_XMM_IMM8 // PCMPISTRM xmm, xmm, imm8 , PEXTRB_R32_XMM_IMM8 // PEXTRB r32, xmm, imm8 , PEXTRB_R64_XMM_IMM8 // PEXTRB r64, xmm, imm8 , PEXTRD_R32_XMM_IMM8 // PEXTRD r32, xmm, imm8 , PEXTRQ_R64_XMM_IMM8 // PEXTRQ r64, xmm, imm8 // , PEXTRW_R32_MM_IMM8 // PEXTRW r32, mm, imm8 , PEXTRW_R32_XMM_IMM8 // PEXTRW r32, xmm, imm8 // , PEXTRW_R64_MM_IMM8 // PEXTRW r64, mm, imm8 , PEXTRW_R64_XMM_IMM8 // PEXTRW r64, xmm, imm8 , PINSRB_XMM_R32_IMM8 // PINSRB xmm, r32, imm8 , PINSRD_XMM_R32_IMM8 // PINSRD xmm, r32, imm8 // , PINSRW_MM_R32_IMM8 // PINSRW mm, r32, imm8 , PINSRW_XMM_R32_IMM8 // PINSRW xmm, r32, imm8 , PSHUFD_XMM_XMM_IMM8 // PSHUFD xmm, xmm, imm8 , PSHUFHW_XMM_XMM_IMM8 // PSHUFHW xmm, xmm, imm8 , PSHUFLW_XMM_XMM_IMM8 // PSHUFLW xmm, xmm, imm8 // , PSHUFW_MM_MM_IMM8 // PSHUFW mm, mm, imm8 // , PSLLD_MM_IMM8 // PSLLD mm, imm8 , PSLLD_XMM_IMM8 // PSLLD xmm, imm8 , PSLLDQ_XMM_IMM8 // PSLLDQ xmm, imm8 // , PSLLQ_MM_IMM8 // PSLLQ mm, imm8 , PSLLQ_XMM_IMM8 // PSLLQ xmm, imm8 // , PSLLW_MM_IMM8 // PSLLW mm, imm8 , PSLLW_XMM_IMM8 // PSLLW xmm, imm8 // , PSRAD_MM_IMM8 // PSRAD mm, imm8 , PSRAD_XMM_IMM8 // PSRAD xmm, imm8 // , PSRAW_MM_IMM8 // PSRAW mm, imm8 , PSRAW_XMM_IMM8 // PSRAW xmm, imm8 // , PSRLD_MM_IMM8 // PSRLD mm, imm8 , PSRLD_XMM_IMM8 // PSRLD xmm, imm8 , PSRLDQ_XMM_IMM8 // PSRLDQ xmm, imm8 // , PSRLQ_MM_IMM8 // PSRLQ mm, imm8 , PSRLQ_XMM_IMM8 // PSRLQ xmm, imm8 // , PSRLW_MM_IMM8 // PSRLW mm, imm8 , PSRLW_XMM_IMM8 // PSRLW xmm, imm8 , ROUNDPD_XMM_XMM_IMM8 // ROUNDPD xmm, xmm, imm8 , ROUNDPS_XMM_XMM_IMM8 // ROUNDPS xmm, xmm, imm8 , ROUNDSD_XMM_XMM_IMM8 // ROUNDSD xmm, xmm, imm8 , ROUNDSS_XMM_XMM_IMM8 // ROUNDSS xmm, xmm, imm8 , SHUFPD_XMM_XMM_IMM8 // SHUFPD xmm, xmm, imm8 , SHUFPS_XMM_XMM_IMM8 // SHUFPS xmm, xmm, imm8 , VBLENDPD_XMM_XMM_XMM_IMM8 // VBLENDPD xmm, xmm, xmm, imm8 , VBLENDPD_YMM_YMM_YMM_IMM8 // VBLENDPD ymm, ymm, ymm, imm8 , VBLENDPS_XMM_XMM_XMM_IMM8 // VBLENDPS xmm, xmm, xmm, imm8 , VBLENDPS_YMM_YMM_YMM_IMM8 // VBLENDPS ymm, ymm, ymm, imm8 , VCMPPD_XMM_XMM_XMM_IMM8 // VCMPPD xmm, xmm, xmm, imm8 , VCMPPD_YMM_YMM_YMM_IMM8 // VCMPPD ymm, ymm, ymm, imm8 , VCMPPS_XMM_XMM_XMM_IMM8 // VCMPPS xmm, xmm, xmm, imm8 , VCMPPS_YMM_YMM_YMM_IMM8 // VCMPPS ymm, ymm, ymm, imm8 , VCMPSD_XMM_XMM_XMM_IMM8 // VCMPSD xmm, xmm, xmm, imm8 , VCMPSS_XMM_XMM_XMM_IMM8 // VCMPSS xmm, xmm, xmm, imm8 , VCVTPS2PH_XMM_XMM_IMM8 // VCVTPS2PH xmm, xmm, imm8 , VCVTPS2PH_XMM_YMM_IMM8 // VCVTPS2PH xmm, ymm, imm8 , VDPPD_XMM_XMM_XMM_IMM8 // VDPPD xmm, xmm, xmm, imm8 , VDPPS_XMM_XMM_XMM_IMM8 // VDPPS xmm, xmm, xmm, imm8 , VDPPS_YMM_YMM_YMM_IMM8 // VDPPS ymm, ymm, ymm, imm8 , VEXTRACTF128_XMM_YMM_IMM8 // VEXTRACTF128 xmm, ymm, imm8 , VEXTRACTI128_XMM_YMM_IMM8 // VEXTRACTI128 xmm, ymm, imm8 , VEXTRACTPS_R32_XMM_IMM8 // VEXTRACTPS r32, xmm, imm8 , VINSERTF128_YMM_YMM_XMM_IMM8 // VINSERTF128 ymm, ymm, xmm, imm8 , VINSERTI128_YMM_YMM_XMM_IMM8 // VINSERTI128 ymm, ymm, xmm, imm8 , VINSERTPS_XMM_XMM_XMM_IMM8 // VINSERTPS xmm, xmm, xmm, imm8 , VMPSADBW_XMM_XMM_XMM_IMM8 // VMPSADBW xmm, xmm, xmm, imm8 , VMPSADBW_YMM_YMM_YMM_IMM8 // VMPSADBW ymm, ymm, ymm, imm8 , VPALIGNR_XMM_XMM_XMM_IMM8 // VPALIGNR xmm, xmm, xmm, imm8 , VPALIGNR_YMM_YMM_YMM_IMM8 // VPALIGNR ymm, ymm, ymm, imm8 , VPBLENDD_XMM_XMM_XMM_IMM8 // VPBLENDD xmm, xmm, xmm, imm8 , VPBLENDD_YMM_YMM_YMM_IMM8 // VPBLENDD ymm, ymm, ymm, imm8 , VPBLENDW_XMM_XMM_XMM_IMM8 // VPBLENDW xmm, xmm, xmm, imm8 , VPBLENDW_YMM_YMM_YMM_IMM8 // VPBLENDW ymm, ymm, ymm, imm8 , VPCLMULQDQ_XMM_XMM_XMM_IMM8 // VPCLMULQDQ xmm, xmm, xmm, imm8 , VPCMPESTRI_XMM_XMM_IMM8 // VPCMPESTRI xmm, xmm, imm8 , VPCMPESTRM_XMM_XMM_IMM8 // VPCMPESTRM xmm, xmm, imm8 , VPCMPISTRI_XMM_XMM_IMM8 // VPCMPISTRI xmm, xmm, imm8 , VPCMPISTRM_XMM_XMM_IMM8 // VPCMPISTRM xmm, xmm, imm8 , VPERM2F128_YMM_YMM_YMM_IMM8 // VPERM2F128 ymm, ymm, ymm, imm8 , VPERM2I128_YMM_YMM_YMM_IMM8 // VPERM2I128 ymm, ymm, ymm, imm8 , VPERMILPD_XMM_XMM_IMM8 // VPERMILPD xmm, xmm, imm8 , VPERMILPD_YMM_YMM_IMM8 // VPERMILPD ymm, ymm, imm8 , VPERMILPS_XMM_XMM_IMM8 // VPERMILPS xmm, xmm, imm8 , VPERMILPS_YMM_YMM_IMM8 // VPERMILPS ymm, ymm, imm8 , VPERMPD_YMM_YMM_IMM8 // VPERMPD ymm, ymm, imm8 , VPERMQ_YMM_YMM_IMM8 // VPERMQ ymm, ymm, imm8 , VPEXTRB_R32_XMM_IMM8 // VPEXTRB r32, xmm, imm8 , VPEXTRB_R64_XMM_IMM8 // VPEXTRB r64, xmm, imm8 , VPEXTRD_R32_XMM_IMM8 // VPEXTRD r32, xmm, imm8 , VPEXTRQ_R64_XMM_IMM8 // VPEXTRQ r64, xmm, imm8 , VPEXTRW_R32_XMM_IMM8 // VPEXTRW r32, xmm, imm8 , VPEXTRW_R64_XMM_IMM8 // VPEXTRW r64, xmm, imm8 , VPINSRB_XMM_XMM_R32_IMM8 // VPINSRB xmm, xmm, r32, imm8 , VPINSRD_XMM_XMM_R32_IMM8 // VPINSRD xmm, xmm, r32, imm8 , VPINSRQ_XMM_XMM_R64_IMM8 // VPINSRQ xmm, xmm, r64, imm8 , VPINSRW_XMM_XMM_R32_IMM8 // VPINSRW xmm, xmm, r32, imm8 , VPSHUFD_XMM_XMM_IMM8 // VPSHUFD xmm, xmm, imm8 , VPSHUFD_YMM_YMM_IMM8 // VPSHUFD ymm, ymm, imm8 , VPSHUFHW_XMM_XMM_IMM8 // VPSHUFHW xmm, xmm, imm8 , VPSHUFHW_YMM_YMM_IMM8 // VPSHUFHW ymm, ymm, imm8 , VPSHUFLW_XMM_XMM_IMM8 // VPSHUFLW xmm, xmm, imm8 , VPSHUFLW_YMM_YMM_IMM8 // VPSHUFLW ymm, ymm, imm8 , VPSLLD_XMM_XMM_IMM8 // VPSLLD xmm, xmm, imm8 , VPSLLD_YMM_YMM_IMM8 // VPSLLD ymm, ymm, imm8 , VPSLLDQ_XMM_XMM_IMM8 // VPSLLDQ xmm, xmm, imm8 , VPSLLDQ_YMM_YMM_IMM8 // VPSLLDQ ymm, ymm, imm8 , VPSLLQ_XMM_XMM_IMM8 // VPSLLQ xmm, xmm, imm8 , VPSLLQ_YMM_YMM_IMM8 // VPSLLQ ymm, ymm, imm8 , VPSLLW_XMM_XMM_IMM8 // VPSLLW xmm, xmm, imm8 , VPSLLW_YMM_YMM_IMM8 // VPSLLW ymm, ymm, imm8 , VPSRAD_XMM_XMM_IMM8 // VPSRAD xmm, xmm, imm8 , VPSRAD_YMM_YMM_IMM8 // VPSRAD ymm, ymm, imm8 , VPSRAW_XMM_XMM_IMM8 // VPSRAW xmm, xmm, imm8 , VPSRAW_YMM_YMM_IMM8 // VPSRAW ymm, ymm, imm8 , VPSRLD_XMM_XMM_IMM8 // VPSRLD xmm, xmm, imm8 , VPSRLD_YMM_YMM_IMM8 // VPSRLD ymm, ymm, imm8 , VPSRLDQ_XMM_XMM_IMM8 // VPSRLDQ xmm, xmm, imm8 , VPSRLDQ_YMM_YMM_IMM8 // VPSRLDQ ymm, ymm, imm8 , VPSRLQ_XMM_XMM_IMM8 // VPSRLQ xmm, xmm, imm8 , VPSRLQ_YMM_YMM_IMM8 // VPSRLQ ymm, ymm, imm8 , VPSRLW_XMM_XMM_IMM8 // VPSRLW xmm, xmm, imm8 , VPSRLW_YMM_YMM_IMM8 // VPSRLW ymm, ymm, imm8 , VROUNDPD_XMM_XMM_IMM8 // VROUNDPD xmm, xmm, imm8 , VROUNDPD_YMM_YMM_IMM8 // VROUNDPD ymm, ymm, imm8 , VROUNDPS_XMM_XMM_IMM8 // VROUNDPS xmm, xmm, imm8 , VROUNDPS_YMM_YMM_IMM8 // VROUNDPS ymm, ymm, imm8 , VROUNDSD_XMM_XMM_XMM_IMM8 // VROUNDSD xmm, xmm, xmm, imm8 , VROUNDSS_XMM_XMM_XMM_IMM8 // VROUNDSS xmm, xmm, xmm, imm8 , VSHUFPD_XMM_XMM_XMM_IMM8 // VSHUFPD xmm, xmm, xmm, imm8 , VSHUFPD_YMM_YMM_YMM_IMM8 // VSHUFPD ymm, ymm, ymm, imm8 , VSHUFPS_XMM_XMM_XMM_IMM8 // VSHUFPS xmm, xmm, xmm, imm8 , VSHUFPS_YMM_YMM_YMM_IMM8 // VSHUFPS ymm, ymm, ymm, imm8 }; vector<Opcode> instr_cat_crypto_ = { AESDEC_XMM_M128 // AESDEC xmm, m128 , AESDEC_XMM_XMM // AESDEC xmm, xmm , AESDECLAST_XMM_M128 // AESDECLAST xmm, m128 , AESDECLAST_XMM_XMM // AESDECLAST xmm, xmm , AESENC_XMM_M128 // AESENC xmm, m128 , AESENC_XMM_XMM // AESENC xmm, xmm , AESENCLAST_XMM_M128 // AESENCLAST xmm, m128 , AESENCLAST_XMM_XMM // AESENCLAST xmm, xmm , AESIMC_XMM_M128 // AESIMC xmm, m128 , AESIMC_XMM_XMM // AESIMC xmm, xmm , AESKEYGENASSIST_XMM_M128_IMM8 // AESKEYGENASSIST xmm, m128, imm8 , AESKEYGENASSIST_XMM_XMM_IMM8 // AESKEYGENASSIST xmm, xmm, imm8 , CRC32_R32_M16 // CRC32 r32, m16 , CRC32_R32_M32 // CRC32 r32, m32 , CRC32_R32_M8 // CRC32 r32, m8 , CRC32_R32_R16 // CRC32 r32, r16 , CRC32_R32_R32 // CRC32 r32, r32 , CRC32_R32_R8 // CRC32 r32, r8 , CRC32_R32_RH // CRC32 r32, rh , CRC32_R64_M64 // CRC32 r64, m64 , CRC32_R64_M8 // CRC32 r64, m8 , CRC32_R64_R64 // CRC32 r64, r64 , CRC32_R64_R8 // CRC32 r64, r8 , VAESDEC_XMM_XMM_M128 // VAESDEC xmm, xmm, m128 , VAESDEC_XMM_XMM_XMM // VAESDEC xmm, xmm, xmm , VAESDECLAST_XMM_XMM_M128 // VAESDECLAST xmm, xmm, m128 , VAESDECLAST_XMM_XMM_XMM // VAESDECLAST xmm, xmm, xmm , VAESENC_XMM_XMM_M128 // VAESENC xmm, xmm, m128 , VAESENC_XMM_XMM_XMM // VAESENC xmm, xmm, xmm , VAESENCLAST_XMM_XMM_M128 // VAESENCLAST xmm, xmm, m128 , VAESENCLAST_XMM_XMM_XMM // VAESENCLAST xmm, xmm, xmm , VAESIMC_XMM_M128 // VAESIMC xmm, m128 , VAESIMC_XMM_XMM // VAESIMC xmm, xmm , VAESKEYGENASSIST_XMM_M128_IMM8 // VAESKEYGENASSIST xmm, m128, imm8 , VAESKEYGENASSIST_XMM_XMM_IMM8 // VAESKEYGENASSIST xmm, xmm, imm8 }; vector<Opcode> instr_cat_duplicates_ = { ADC_R16_R16_1 // ADC r16, r16 , ADC_R32_R32_1 // ADC r32, r32 , ADC_R64_R64_1 // ADC r64, r64 , ADC_R8_R8_1 // ADC r8, r8 , ADC_R8_RH_1 // ADC r8, rh , ADC_RH_R8_1 // ADC rh, r8 , ADC_RH_RH_1 // ADC rh, rh , ADD_R16_R16_1 // ADD r16, r16 , ADD_R32_R32_1 // ADD r32, r32 , ADD_R64_R64_1 // ADD r64, r64 , ADD_R8_R8_1 // ADD r8, r8 , ADD_R8_RH_1 // ADD r8, rh , ADD_RH_R8_1 // ADD rh, r8 , ADD_RH_RH_1 // ADD rh, rh , AND_R16_R16_1 // AND r16, r16 , AND_R32_R32_1 // AND r32, r32 , AND_R64_R64_1 // AND r64, r64 , AND_R8_R8_1 // AND r8, r8 , AND_R8_RH_1 // AND r8, rh , AND_RH_R8_1 // AND rh, r8 , AND_RH_RH_1 // AND rh, rh , CMP_R16_R16_1 // CMP r16, r16 , CMP_R32_R32_1 // CMP r32, r32 , CMP_R64_R64_1 // CMP r64, r64 , CMP_R8_R8_1 // CMP r8, r8 , CMP_R8_RH_1 // CMP r8, rh , CMP_RH_R8_1 // CMP rh, r8 , CMP_RH_RH_1 // CMP rh, rh , JA_LABEL_1 // JA label32 , JA_LABEL_HINT_1 // JA label32, hint , JAE_LABEL_1 // JAE label32 , JAE_LABEL_HINT_1 // JAE label32, hint , JB_LABEL_1 // JB label32 , JB_LABEL_HINT_1 // JB label32, hint , JBE_LABEL_1 // JBE label32 , JBE_LABEL_HINT_1 // JBE label32, hint , JC_LABEL_1 // JC label32 , JC_LABEL_HINT_1 // JC label32, hint , JE_LABEL_1 // JE label32 , JE_LABEL_HINT_1 // JE label32, hint , JG_LABEL_1 // JG label32 , JG_LABEL_HINT_1 // JG label32, hint , JGE_LABEL_1 // JGE label32 , JGE_LABEL_HINT_1 // JGE label32, hint , JL_LABEL_1 // JL label32 , JL_LABEL_HINT_1 // JL label32, hint , JLE_LABEL_1 // JLE label32 , JLE_LABEL_HINT_1 // JLE label32, hint , JMP_LABEL_1 // JMP label32 , JNA_LABEL_1 // JNA label32 , JNA_LABEL_HINT_1 // JNA label32, hint , JNAE_LABEL_1 // JNAE label32 , JNAE_LABEL_HINT_1 // JNAE label32, hint , JNB_LABEL_1 // JNB label32 , JNB_LABEL_HINT_1 // JNB label32, hint , JNBE_LABEL_1 // JNBE label32 , JNBE_LABEL_HINT_1 // JNBE label32, hint , JNC_LABEL_1 // JNC label32 , JNC_LABEL_HINT_1 // JNC label32, hint , JNE_LABEL_1 // JNE label32 , JNE_LABEL_HINT_1 // JNE label32, hint , JNG_LABEL_1 // JNG label32 , JNG_LABEL_HINT_1 // JNG label32, hint , JNGE_LABEL_1 // JNGE label32 , JNGE_LABEL_HINT_1 // JNGE label32, hint , JNL_LABEL_1 // JNL label32 , JNL_LABEL_HINT_1 // JNL label32, hint , JNLE_LABEL_1 // JNLE label32 , JNLE_LABEL_HINT_1 // JNLE label32, hint , JNO_LABEL_1 // JNO label32 , JNO_LABEL_HINT_1 // JNO label32, hint , JNP_LABEL_1 // JNP label32 , JNP_LABEL_HINT_1 // JNP label32, hint , JNS_LABEL_1 // JNS label32 , JNS_LABEL_HINT_1 // JNS label32, hint , JNZ_LABEL_1 // JNZ label32 , JNZ_LABEL_HINT_1 // JNZ label32, hint , JO_LABEL_1 // JO label32 , JO_LABEL_HINT_1 // JO label32, hint , JP_LABEL_1 // JP label32 , JP_LABEL_HINT_1 // JP label32, hint , JPE_LABEL_1 // JPE label32 , JPE_LABEL_HINT_1 // JPE label32, hint , JPO_LABEL_1 // JPO label32 , JPO_LABEL_HINT_1 // JPO label32, hint , JS_LABEL_1 // JS label32 , JS_LABEL_HINT_1 // JS label32, hint , JZ_LABEL_1 // JZ label32 , JZ_LABEL_HINT_1 // JZ label32, hint , MOV_R16_IMM16_1 // MOV r16, imm16 , MOV_R16_R16_1 // MOV r16, r16 , MOV_R32_IMM32_1 // MOV r32, imm32 , MOV_R32_R32_1 // MOV r32, r32 , MOV_R64_R64_1 // MOV r64, r64 , MOV_R8_IMM8_1 // MOV r8, imm8 , MOV_R8_R8_1 // MOV r8, r8 , MOV_R8_RH_1 // MOV r8, rh , MOV_RH_IMM8_1 // MOV rh, imm8 , MOV_RH_R8_1 // MOV rh, r8 , MOV_RH_RH_1 // MOV rh, rh , MOVAPD_XMM_XMM_1 // MOVAPD xmm, xmm , MOVAPS_XMM_XMM_1 // MOVAPS xmm, xmm , MOVDQA_XMM_XMM_1 // MOVDQA xmm, xmm , MOVDQU_XMM_XMM_1 // MOVDQU xmm, xmm , MOVQ_M64_MM_1 // MOVQ m64, mm , MOVQ_M64_XMM_1 // MOVQ m64, xmm , MOVQ_MM_M64_1 // MOVQ mm, m64 , MOVQ_MM_MM_1 // MOVQ mm, mm , MOVQ_XMM_M64_1 // MOVQ xmm, m64 , MOVQ_XMM_XMM_1 // MOVQ xmm, xmm , MOVSD_XMM_XMM_1 // MOVSD xmm, xmm , MOVSS_XMM_XMM_1 // MOVSS xmm, xmm , MOVUPD_XMM_XMM_1 // MOVUPD xmm, xmm , MOVUPS_XMM_XMM_1 // MOVUPS xmm, xmm , OR_R16_R16_1 // OR r16, r16 , OR_R32_R32_1 // OR r32, r32 , OR_R64_R64_1 // OR r64, r64 , OR_R8_R8_1 // OR r8, r8 , OR_R8_RH_1 // OR r8, rh , OR_RH_R8_1 // OR rh, r8 , OR_RH_RH_1 // OR rh, rh , PEXTRW_R32_XMM_IMM8_1 // PEXTRW r32, xmm, imm8 , PEXTRW_R64_XMM_IMM8_1 // PEXTRW r64, xmm, imm8 , POP_R16_1 // POP r16 , POP_R64_1 // POP r64 , PUSH_R16_1 // PUSH r16 , PUSH_R64_1 // PUSH r64 , REP_INS_M8_DX_1 // REP_INS m8, DX , REP_LODS_AL_1 // REP_LODS AL , REP_MOVS_M8_M8_1 // REP_MOVS m8, m8 , REP_OUTS_DX_M8_1 // REP_OUTS DX, m8 , REP_STOS_M8_1 // REP_STOS m8 , REPE_CMPS_M8_M8_1 // REPE_CMPS m8, m8 , REPE_SCAS_M8_1 // REPE_SCAS m8 , REPNE_CMPS_M8_M8_1 // REPNE_CMPS m8, m8 , REPNE_SCAS_M8_1 // REPNE_SCAS m8 , SBB_R16_R16_1 // SBB r16, r16 , SBB_R32_R32_1 // SBB r32, r32 , SBB_R64_R64_1 // SBB r64, r64 , SBB_R8_R8_1 // SBB r8, r8 , SBB_R8_RH_1 // SBB r8, rh , SBB_RH_R8_1 // SBB rh, r8 , SBB_RH_RH_1 // SBB rh, rh , SUB_R16_R16_1 // SUB r16, r16 , SUB_R32_R32_1 // SUB r32, r32 , SUB_R64_R64_1 // SUB r64, r64 , SUB_R8_R8_1 // SUB r8, r8 , SUB_R8_RH_1 // SUB r8, rh , SUB_RH_R8_1 // SUB rh, r8 , SUB_RH_RH_1 // SUB rh, rh , VGATHERQPS_XMM_M64_XMM_1 // VGATHERQPS xmm, m64, xmm , VMOVAPD_XMM_XMM_1 // VMOVAPD xmm, xmm , VMOVAPD_YMM_YMM_1 // VMOVAPD ymm, ymm , VMOVAPS_XMM_XMM_1 // VMOVAPS xmm, xmm , VMOVAPS_YMM_YMM_1 // VMOVAPS ymm, ymm , VMOVDQA_XMM_XMM_1 // VMOVDQA xmm, xmm , VMOVDQA_YMM_YMM_1 // VMOVDQA ymm, ymm , VMOVDQU_XMM_XMM_1 // VMOVDQU xmm, xmm , VMOVDQU_YMM_YMM_1 // VMOVDQU ymm, ymm , VMOVQ_M64_XMM_1 // VMOVQ m64, xmm , VMOVQ_XMM_M64_1 // VMOVQ xmm, m64 , VMOVQ_XMM_XMM_1 // VMOVQ xmm, xmm , VMOVSD_XMM_XMM_XMM_1 // VMOVSD xmm, xmm, xmm , VMOVSS_XMM_XMM_XMM_1 // VMOVSS xmm, xmm, xmm , VMOVUPD_XMM_XMM_1 // VMOVUPD xmm, xmm , VMOVUPD_YMM_YMM_1 // VMOVUPD ymm, ymm , VMOVUPS_XMM_XMM_1 // VMOVUPS xmm, xmm , VMOVUPS_YMM_YMM_1 // VMOVUPS ymm, ymm , VPEXTRW_R32_XMM_IMM8_1 // VPEXTRW r32, xmm, imm8 , VPEXTRW_R64_XMM_IMM8_1 // VPEXTRW r64, xmm, imm8 , VPGATHERQD_XMM_M64_XMM_1 // VPGATHERQD xmm, m64, xmm , XCHG_R16_R16_1 // XCHG r16, r16 , XCHG_R32_R32_1 // XCHG r32, r32 , XCHG_R64_R64_1 // XCHG r64, r64 , XCHG_R8_R8_1 // XCHG r8, r8 , XCHG_R8_RH_1 // XCHG r8, rh , XCHG_RH_R8_1 // XCHG rh, r8 , XCHG_RH_RH_1 // XCHG rh, rh , XLATB_1 // XLATB , XOR_R16_R16_1 // XOR r16, r16 , XOR_R32_R32_1 // XOR r32, r32 , XOR_R64_R64_1 // XOR r64, r64 , XOR_R8_R8_1 // XOR r8, r8 , XOR_R8_RH_1 // XOR r8, rh , XOR_RH_R8_1 // XOR rh, r8 , XOR_RH_RH_1 // XOR rh, rh }; vector<Opcode> instr_cat_float_ = { F2XM1 // F2XM1 , FABS // FABS , FADD_M32FP // FADD m32fp , FADD_M64FP // FADD m64fp , FADD_ST_ST0 // FADD ST(i), ST , FADD_ST0_ST // FADD ST, ST(i) , FADDP // FADDP , FADDP_ST_ST0 // FADDP ST(i), ST , FBLD_M80BCD // FBLD m80bcd , FBSTP_M80BCD // FBSTP m80bcd , FCHS // FCHS , FCLEX // FCLEX , FCMOVB_ST0_ST // FCMOVB ST, ST(i) , FCMOVBE_ST0_ST // FCMOVBE ST, ST(i) , FCMOVE_ST0_ST // FCMOVE ST, ST(i) , FCMOVNB_ST0_ST // FCMOVNB ST, ST(i) , FCMOVNBE_ST0_ST // FCMOVNBE ST, ST(i) , FCMOVNE_ST0_ST // FCMOVNE ST, ST(i) , FCMOVNU_ST0_ST // FCMOVNU ST, ST(i) , FCMOVU_ST0_ST // FCMOVU ST, ST(i) , FCOM // FCOM , FCOM_M32FP // FCOM m32fp , FCOM_M64FP // FCOM m64fp , FCOM_ST // FCOM ST(i) , FCOMI_ST0_ST // FCOMI ST, ST(i) , FCOMIP_ST0_ST // FCOMIP ST, ST(i) , FCOMP // FCOMP , FCOMP_M32FP // FCOMP m32fp , FCOMP_M64FP // FCOMP m64fp , FCOMP_ST // FCOMP ST(i) , FCOMPP // FCOMPP , FCOS // FCOS , FDECSTP // FDECSTP , FDIV_M32FP // FDIV m32fp , FDIV_M64FP // FDIV m64fp , FDIV_ST_ST0 // FDIV ST(i), ST , FDIV_ST0_ST // FDIV ST, ST(i) , FDIVP // FDIVP , FDIVP_ST_ST0 // FDIVP ST(i), ST , FDIVR_M32FP // FDIVR m32fp , FDIVR_M64FP // FDIVR m64fp , FDIVR_ST_ST0 // FDIVR ST(i), ST , FDIVR_ST0_ST // FDIVR ST, ST(i) , FDIVRP // FDIVRP , FDIVRP_ST_ST0 // FDIVRP ST(i), ST , FFREE_ST // FFREE ST(i) , FIADD_M16INT // FIADD m16int , FIADD_M32INT // FIADD m32int , FICOM_M16INT // FICOM m16int , FICOM_M32INT // FICOM m32int , FICOMP_M16INT // FICOMP m16int , FICOMP_M32INT // FICOMP m32int , FIDIV_M16INT // FIDIV m16int , FIDIV_M32INT // FIDIV m32int , FIDIVR_M16INT // FIDIVR m16int , FIDIVR_M32INT // FIDIVR m32int , FILD_M16INT // FILD m16int , FILD_M32INT // FILD m32int , FILD_M64INT // FILD m64int , FIMUL_M16INT // FIMUL m16int , FIMUL_M32INT // FIMUL m32int , FINCSTP // FINCSTP , FINIT // FINIT , FIST_M16INT // FIST m16int , FIST_M32INT // FIST m32int , FISTP_M16INT // FISTP m16int , FISTP_M32INT // FISTP m32int , FISTP_M64INT // FISTP m64int , FISTTP_M16INT // FISTTP m16int , FISTTP_M32INT // FISTTP m32int , FISTTP_M64INT // FISTTP m64int , FISUB_M16INT // FISUB m16int , FISUB_M32INT // FISUB m32int , FISUBR_M16INT // FISUBR m16int , FISUBR_M32INT // FISUBR m32int , FLD_M32FP // FLD m32fp , FLD_M64FP // FLD m64fp , FLD_M80FP // FLD m80fp , FLD_ST // FLD ST(i) , FLD1 // FLD1 , FLDCW_M2BYTE // FLDCW m2byte , FLDENV_M28BYTE // FLDENV m28byte , FLDL2E // FLDL2E , FLDL2T // FLDL2T , FLDLG2 // FLDLG2 , FLDLN2 // FLDLN2 , FLDPI // FLDPI , FLDZ // FLDZ , FMUL_M32FP // FMUL m32fp , FMUL_M64FP // FMUL m64fp , FMUL_ST_ST0 // FMUL ST(i), ST , FMUL_ST0_ST // FMUL ST, ST(i) , FMULP // FMULP , FMULP_ST_ST0 // FMULP ST(i), ST , FNCLEX // FNCLEX , FNINIT // FNINIT , FNOP // FNOP , FNSAVE_M108BYTE // FNSAVE m108byte , FNSTCW_M2BYTE // FNSTCW m2byte , FNSTENV_M28BYTE // FNSTENV m28byte , FNSTSW_AX // FNSTSW AX , FNSTSW_M2BYTE // FNSTSW m2byte , FPATAN // FPATAN , FPREM // FPREM , FPREM1 // FPREM1 , FPTAN // FPTAN , FRNDINT // FRNDINT , FRSTOR_M108BYTE // FRSTOR m108byte , FSAVE_M108BYTE // FSAVE m108byte , FSCALE // FSCALE , FSIN // FSIN , FSINCOS // FSINCOS , FSQRT // FSQRT , FST_M32FP // FST m32fp , FST_M64FP // FST m64fp , FST_ST // FST ST(i) , FSTCW_M2BYTE // FSTCW m2byte , FSTENV_M28BYTE // FSTENV m28byte , FSTP_M32FP // FSTP m32fp , FSTP_M64FP // FSTP m64fp , FSTP_M80FP // FSTP m80fp , FSTP_ST // FSTP ST(i) , FSTSW_AX // FSTSW AX , FSTSW_M2BYTE // FSTSW m2byte , FSUB_M32FP // FSUB m32fp , FSUB_M64FP // FSUB m64fp , FSUB_ST_ST0 // FSUB ST(i), ST , FSUB_ST0_ST // FSUB ST, ST(i) , FSUBP // FSUBP , FSUBP_ST_ST0 // FSUBP ST(i), ST , FSUBR_M32FP // FSUBR m32fp , FSUBR_M64FP // FSUBR m64fp , FSUBR_ST_ST0 // FSUBR ST(i), ST , FSUBR_ST0_ST // FSUBR ST, ST(i) , FSUBRP // FSUBRP , FSUBRP_ST_ST0 // FSUBRP ST(i), ST , FTST // FTST , FUCOM // FUCOM , FUCOM_ST // FUCOM ST(i) , FUCOMI_ST0_ST // FUCOMI ST, ST(i) , FUCOMIP_ST0_ST // FUCOMIP ST, ST(i) , FUCOMP // FUCOMP , FUCOMP_ST // FUCOMP ST(i) , FUCOMPP // FUCOMPP , FWAIT // FWAIT , FXAM // FXAM , FXCH // FXCH , FXCH_ST // FXCH ST(i) , FXRSTOR_M512BYTE // FXRSTOR m512byte , FXRSTOR64_M512BYTE // FXRSTOR64 m512byte , FXSAVE_M512BYTE // FXSAVE m512byte , FXSAVE64_M512BYTE // FXSAVE64 m512byte , FXTRACT // FXTRACT , FYL2X // FYL2X , FYL2XP1 // FYL2XP1 }; vector<Opcode> instr_cat_system_ = { CALL_FARPTR1616 // CALL m16:16 , CALL_FARPTR1632 // CALL m16:32 , CALL_FARPTR1664 // CALL m16:64 , CALL_M64 // CALL m64 , CALL_R64 // CALL r64 , CALL_REL32 // CALL rel32 , CALL_LABEL // CALL label , BSF_R32_M32 // BSF r32, m32 , BSF_R32_R32 // BSF r32, r32 , BSF_R64_M64 // BSF r64, m64 , BSF_R64_R64 // BSF r64, r64 , BSR_R16_M16 // BSR r16, m16 , BSR_R16_R16 // BSR r16, r16 , BSR_R32_M32 // BSR r32, m32 , BSR_R32_R32 // BSR r32, r32 , BSR_R64_M64 // BSR r64, m64 , BSR_R64_R64 // BSR r64, r64 , CLFLUSH_M8 // CLFLUSH m8 , CLI // CLI , CPUID // CPUID , ENTER_IMM8_IMM16 // ENTER imm8, imm16 , ENTER_ONE_IMM16 // ENTER 1, imm16 , ENTER_ZERO_IMM16 // ENTER 0, imm16 , EMMS // EMMS , IN_AL_DX // IN AL, DX , IN_AL_IMM8 // IN AL, imm8 , IN_AX_DX // IN AX, DX , IN_AX_IMM8 // IN AX, imm8 , IN_EAX_DX // IN EAX, DX , IN_EAX_IMM8 // IN EAX, imm8 , INS_M16_DX // INS m16, DX , INS_M32_DX // INS m32, DX , INS_M8_DX // INS m8, DX , INSB // INSB , INSD // INSD , INSW // INSW , INT_IMM8 // INT imm8 , INT_THREE // INT 3 , INVPCID_R64_M128 // INVPCID r64, m128 , IRET // IRET , IRETD // IRETD , IRETQ // IRETQ , LAR_R16_M16 // LAR r16, m16 , LAR_R16_R16 // LAR r16, r16 , LAR_R32_M16 // LAR r32, m16 , LAR_R32_R32 // LAR r32, r32 , LAR_R64_M16 // LAR r64, m16 , LAR_R64_R32 // LAR r64, r32 , LAHF // LAHF , SAHF // SAHF , POPF // POPF , POPFQ // POPFQ , PUSHF // PUSHF , PUSHFQ // PUSHFQ , STI // STI , POP_R16 // POP r16 , POP_R64 // POP r64 , PUSH_R16 // PUSH r16 , PUSH_R64 // PUSH r64 , POP_R16_1 // POP r16 , POP_R64_1 // POP r64 , PUSH_R16_1 // PUSH r16 , PUSH_R64_1 // PUSH r64 , LDMXCSR_M32 // LDMXCSR m32 , LEAVE // LEAVE , LEAVE_PREF66 // LEAVE p66 , LFENCE // LFENCE , LFS_R16_FARPTR1616 // LFS r16, m16:16 , LFS_R32_FARPTR1632 // LFS r32, m16:32 , LFS_R64_FARPTR1664 // LFS r64, m16:64 , LGS_R16_FARPTR1616 // LGS r16, m16:16 , LGS_R32_FARPTR1632 // LGS r32, m16:32 , LGS_R64_FARPTR1664 // LGS r64, m16:64 , LOCK // LOCK , LSL_R16_M16 // LSL r16, m16 , LSL_R16_R16 // LSL r16, r16 , LSL_R32_M16 // LSL r32, m16 , LSL_R32_R32 // LSL r32, r32 , LSL_R64_M16 // LSL r64, m16 , LSL_R64_R32 // LSL r64, r32 , LSS_R16_FARPTR1616 // LSS r16, m16:16 , LSS_R32_FARPTR1632 // LSS r32, m16:32 , LSS_R64_FARPTR1664 // LSS r64, m16:64 , MFENCE // MFENCE , MONITOR // MONITOR , MWAIT // MWAIT , OUT_DX_AL // OUT DX, AL , OUT_DX_AX // OUT DX, AX , OUT_DX_EAX // OUT DX, EAX , OUT_IMM8_AL // OUT imm8, AL , OUT_IMM8_AX // OUT imm8, AX , OUT_IMM8_EAX // OUT imm8, EAX , OUTS_DX_M16 // OUTS DX, m16 , OUTS_DX_M32 // OUTS DX, m32 , OUTS_DX_M8 // OUTS DX, m8 , OUTSB // OUTSB , OUTSD // OUTSD , OUTSW // OUTSW , PAUSE // PAUSE , PREFETCHNTA_M8 // PREFETCHNTA m8 , PREFETCHT0_M8 // PREFETCHT0 m8 , PREFETCHT1_M8 // PREFETCHT1 m8 , PREFETCHT2_M8 // PREFETCHT2 m8 , RDFSBASE_R32 // RDFSBASE r32 , RDFSBASE_R64 // RDFSBASE r64 , RDGSBASE_R32 // RDGSBASE r32 , RDGSBASE_R64 // RDGSBASE r64 , RDRAND_R16 // RDRAND r16 , RDRAND_R32 // RDRAND r32 , RDRAND_R64 // RDRAND r64 , REP_INS_M16_DX // REP_INS m16, DX , REP_INS_M32_DX // REP_INS m32, DX , REP_INS_M64_DX // REP_INS m64, DX , REP_INS_M8_DX // REP_INS m8, DX , REP_OUTS_DX_M16 // REP_OUTS DX, m16 , REP_OUTS_DX_M32 // REP_OUTS DX, m32 , REP_OUTS_DX_M64 // REP_OUTS DX, m64 , REP_OUTS_DX_M8 // REP_OUTS DX, m8 , RET // RET , RET_FAR // RET far , RET_IMM16 // RET imm16 , RET_IMM16_FAR // RET imm16, far , SFENCE // SFENCE , STMXCSR_M32 // STMXCSR m32 , SWAPGS // SWAPGS , SYSCALL // SYSCALL , SYSENTER // SYSENTER , SYSEXIT // SYSEXIT , SYSEXIT_PREFREXW // SYSEXIT pw , SYSRET // SYSRET , SYSRET_PREFREXW // SYSRET pw , UD2 // UD2 , VERR_M16 // VERR m16 , VERR_R16 // VERR r16 , VERW_M16 // VERW m16 , VERW_R16 // VERW r16 , WAIT // WAIT , WRFSBASE_R32 // WRFSBASE r32 , WRFSBASE_R64 // WRFSBASE r64 , WRGSBASE_R32 // WRGSBASE r32 , WRGSBASE_R64 // WRGSBASE r64 , XABORT_IMM8 // XABORT imm8 , XACQUIRE // XACQUIRE , XBEGIN_REL32 // XBEGIN rel32 , XBEGIN_LABEL // XBEGIN label , XEND // XEND , XGETBV // XGETBV , XLAT_M8 // XLAT m8 , XLATB // XLATB , XLATB_1 // XLATB , XRELEASE // XRELEASE , XRSTOR_M16 // XRSTOR m16 , XRSTOR_M32 // XRSTOR m32 , XRSTOR_M64 // XRSTOR m64 , XRSTOR64_M16 // XRSTOR64 m16 , XRSTOR64_M32 // XRSTOR64 m32 , XRSTOR64_M64 // XRSTOR64 m64 , XSAVE_M16 // XSAVE m16 , XSAVE_M32 // XSAVE m32 , XSAVE_M64 // XSAVE m64 , XSAVE64_M16 // XSAVE64 m16 , XSAVE64_M32 // XSAVE64 m32 , XSAVE64_M64 // XSAVE64 m64 , XSAVEOPT_M16 // XSAVEOPT m16 , XSAVEOPT_M32 // XSAVEOPT m32 , XSAVEOPT_M64 // XSAVEOPT m64 , XSAVEOPT64_M16 // XSAVEOPT64 m16 , XSAVEOPT64_M32 // XSAVEOPT64 m32 , XSAVEOPT64_M64 // XSAVEOPT64 m64 , XTEST // XTEST // these have problems with the maybe_undef_set being too large , SHRD_M16_R16_CL // SHRD m16, r16, CL , SHRD_M16_R16_IMM8 // SHRD m16, r16, imm8 , SHRD_M32_R32_CL // SHRD m32, r32, CL , SHRD_M32_R32_IMM8 // SHRD m32, r32, imm8 , SHRD_M64_R64_CL // SHRD m64, r64, CL , SHRD_M64_R64_IMM8 // SHRD m64, r64, imm8 , SHRD_R16_R16_CL // SHRD r16, r16, CL , SHRD_R16_R16_IMM8 // SHRD r16, r16, imm8 , SHRD_R32_R32_CL // SHRD r32, r32, CL , SHRD_R32_R32_IMM8 // SHRD r32, r32, imm8 , SHRD_R64_R64_CL // SHRD r64, r64, CL , SHRD_R64_R64_IMM8 // SHRD r64, r64, imm8 , SHLD_M16_R16_CL // SHLD m16, r16, CL , SHLD_M16_R16_IMM8 // SHLD m16, r16, imm8 , SHLD_M32_R32_CL // SHLD m32, r32, CL , SHLD_M32_R32_IMM8 // SHLD m32, r32, imm8 , SHLD_M64_R64_CL // SHLD m64, r64, CL , SHLD_M64_R64_IMM8 // SHLD m64, r64, imm8 , SHLD_R16_R16_CL // SHLD r16, r16, CL , SHLD_R16_R16_IMM8 // SHLD r16, r16, imm8 , SHLD_R32_R32_CL // SHLD r32, r32, CL , SHLD_R32_R32_IMM8 // SHLD r32, r32, imm8 , SHLD_R64_R64_CL // SHLD r64, r64, CL , SHLD_R64_R64_IMM8 // SHLD r64, r64, imm8 }; vector<Opcode> instr_cat_jump_ = { JA_LABEL // JA label8 , JA_LABEL_1 // JA label32 , JA_LABEL_HINT // JA label8, hint , JA_LABEL_HINT_1 // JA label32, hint , JA_REL32 // JA rel32 , JA_REL32_HINT // JA rel32, hint , JA_REL8 // JA rel8 , JA_REL8_HINT // JA rel8, hint , JAE_LABEL // JAE label8 , JAE_LABEL_1 // JAE label32 , JAE_LABEL_HINT // JAE label8, hint , JAE_LABEL_HINT_1 // JAE label32, hint , JAE_REL32 // JAE rel32 , JAE_REL32_HINT // JAE rel32, hint , JAE_REL8 // JAE rel8 , JAE_REL8_HINT // JAE rel8, hint , JB_LABEL // JB label8 , JB_LABEL_1 // JB label32 , JB_LABEL_HINT // JB label8, hint , JB_LABEL_HINT_1 // JB label32, hint , JB_REL32 // JB rel32 , JB_REL32_HINT // JB rel32, hint , JB_REL8 // JB rel8 , JB_REL8_HINT // JB rel8, hint , JBE_LABEL // JBE label8 , JBE_LABEL_1 // JBE label32 , JBE_LABEL_HINT // JBE label8, hint , JBE_LABEL_HINT_1 // JBE label32, hint , JBE_REL32 // JBE rel32 , JBE_REL32_HINT // JBE rel32, hint , JBE_REL8 // JBE rel8 , JBE_REL8_HINT // JBE rel8, hint , JC_LABEL // JC label8 , JC_LABEL_1 // JC label32 , JC_LABEL_HINT // JC label8, hint , JC_LABEL_HINT_1 // JC label32, hint , JC_REL32 // JC rel32 , JC_REL32_HINT // JC rel32, hint , JC_REL8 // JC rel8 , JC_REL8_HINT // JC rel8, hint , JE_LABEL // JE label8 , JE_LABEL_1 // JE label32 , JE_LABEL_HINT // JE label8, hint , JE_LABEL_HINT_1 // JE label32, hint , JE_REL32 // JE rel32 , JE_REL32_HINT // JE rel32, hint , JE_REL8 // JE rel8 , JE_REL8_HINT // JE rel8, hint , JECXZ_LABEL // JECXZ label8 , JECXZ_LABEL_HINT // JECXZ label8, hint , JECXZ_REL8 // JECXZ rel8 , JECXZ_REL8_HINT // JECXZ rel8, hint , JG_LABEL // JG label8 , JG_LABEL_1 // JG label32 , JG_LABEL_HINT // JG label8, hint , JG_LABEL_HINT_1 // JG label32, hint , JG_REL32 // JG rel32 , JG_REL32_HINT // JG rel32, hint , JG_REL8 // JG rel8 , JG_REL8_HINT // JG rel8, hint , JGE_LABEL // JGE label8 , JGE_LABEL_1 // JGE label32 , JGE_LABEL_HINT // JGE label8, hint , JGE_LABEL_HINT_1 // JGE label32, hint , JGE_REL32 // JGE rel32 , JGE_REL32_HINT // JGE rel32, hint , JGE_REL8 // JGE rel8 , JGE_REL8_HINT // JGE rel8, hint , JL_LABEL // JL label8 , JL_LABEL_1 // JL label32 , JL_LABEL_HINT // JL label8, hint , JL_LABEL_HINT_1 // JL label32, hint , JL_REL32 // JL rel32 , JL_REL32_HINT // JL rel32, hint , JL_REL8 // JL rel8 , JL_REL8_HINT // JL rel8, hint , JLE_LABEL // JLE label8 , JLE_LABEL_1 // JLE label32 , JLE_LABEL_HINT // JLE label8, hint , JLE_LABEL_HINT_1 // JLE label32, hint , JLE_REL32 // JLE rel32 , JLE_REL32_HINT // JLE rel32, hint , JLE_REL8 // JLE rel8 , JLE_REL8_HINT // JLE rel8, hint , JMP_FARPTR1616 // JMP m16:16 , JMP_FARPTR1632 // JMP m16:32 , JMP_FARPTR1664 // JMP m16:64 , JMP_LABEL // JMP label8 , JMP_LABEL_1 // JMP label32 , JMP_M64 // JMP m64 , JMP_R64 // JMP r64 , JMP_REL32 // JMP rel32 , JMP_REL8 // JMP rel8 , JNA_LABEL // JNA label8 , JNA_LABEL_1 // JNA label32 , JNA_LABEL_HINT // JNA label8, hint , JNA_LABEL_HINT_1 // JNA label32, hint , JNA_REL32 // JNA rel32 , JNA_REL32_HINT // JNA rel32, hint , JNA_REL8 // JNA rel8 , JNA_REL8_HINT // JNA rel8, hint , JNAE_LABEL // JNAE label8 , JNAE_LABEL_1 // JNAE label32 , JNAE_LABEL_HINT // JNAE label8, hint , JNAE_LABEL_HINT_1 // JNAE label32, hint , JNAE_REL32 // JNAE rel32 , JNAE_REL32_HINT // JNAE rel32, hint , JNAE_REL8 // JNAE rel8 , JNAE_REL8_HINT // JNAE rel8, hint , JNB_LABEL // JNB label8 , JNB_LABEL_1 // JNB label32 , JNB_LABEL_HINT // JNB label8, hint , JNB_LABEL_HINT_1 // JNB label32, hint , JNB_REL32 // JNB rel32 , JNB_REL32_HINT // JNB rel32, hint , JNB_REL8 // JNB rel8 , JNB_REL8_HINT // JNB rel8, hint , JNBE_LABEL // JNBE label8 , JNBE_LABEL_1 // JNBE label32 , JNBE_LABEL_HINT // JNBE label8, hint , JNBE_LABEL_HINT_1 // JNBE label32, hint , JNBE_REL32 // JNBE rel32 , JNBE_REL32_HINT // JNBE rel32, hint , JNBE_REL8 // JNBE rel8 , JNBE_REL8_HINT // JNBE rel8, hint , JNC_LABEL // JNC label8 , JNC_LABEL_1 // JNC label32 , JNC_LABEL_HINT // JNC label8, hint , JNC_LABEL_HINT_1 // JNC label32, hint , JNC_REL32 // JNC rel32 , JNC_REL32_HINT // JNC rel32, hint , JNC_REL8 // JNC rel8 , JNC_REL8_HINT // JNC rel8, hint , JNE_LABEL // JNE label8 , JNE_LABEL_1 // JNE label32 , JNE_LABEL_HINT // JNE label8, hint , JNE_LABEL_HINT_1 // JNE label32, hint , JNE_REL32 // JNE rel32 , JNE_REL32_HINT // JNE rel32, hint , JNE_REL8 // JNE rel8 , JNE_REL8_HINT // JNE rel8, hint , JNG_LABEL // JNG label8 , JNG_LABEL_1 // JNG label32 , JNG_LABEL_HINT // JNG label8, hint , JNG_LABEL_HINT_1 // JNG label32, hint , JNG_REL32 // JNG rel32 , JNG_REL32_HINT // JNG rel32, hint , JNG_REL8 // JNG rel8 , JNG_REL8_HINT // JNG rel8, hint , JNGE_LABEL // JNGE label8 , JNGE_LABEL_1 // JNGE label32 , JNGE_LABEL_HINT // JNGE label8, hint , JNGE_LABEL_HINT_1 // JNGE label32, hint , JNGE_REL32 // JNGE rel32 , JNGE_REL32_HINT // JNGE rel32, hint , JNGE_REL8 // JNGE rel8 , JNGE_REL8_HINT // JNGE rel8, hint , JNL_LABEL // JNL label8 , JNL_LABEL_1 // JNL label32 , JNL_LABEL_HINT // JNL label8, hint , JNL_LABEL_HINT_1 // JNL label32, hint , JNL_REL32 // JNL rel32 , JNL_REL32_HINT // JNL rel32, hint , JNL_REL8 // JNL rel8 , JNL_REL8_HINT // JNL rel8, hint , JNLE_LABEL // JNLE label8 , JNLE_LABEL_1 // JNLE label32 , JNLE_LABEL_HINT // JNLE label8, hint , JNLE_LABEL_HINT_1 // JNLE label32, hint , JNLE_REL32 // JNLE rel32 , JNLE_REL32_HINT // JNLE rel32, hint , JNLE_REL8 // JNLE rel8 , JNLE_REL8_HINT // JNLE rel8, hint , JNO_LABEL // JNO label8 , JNO_LABEL_1 // JNO label32 , JNO_LABEL_HINT // JNO label8, hint , JNO_LABEL_HINT_1 // JNO label32, hint , JNO_REL32 // JNO rel32 , JNO_REL32_HINT // JNO rel32, hint , JNO_REL8 // JNO rel8 , JNO_REL8_HINT // JNO rel8, hint , JNP_LABEL // JNP label8 , JNP_LABEL_1 // JNP label32 , JNP_LABEL_HINT // JNP label8, hint , JNP_LABEL_HINT_1 // JNP label32, hint , JNP_REL32 // JNP rel32 , JNP_REL32_HINT // JNP rel32, hint , JNP_REL8 // JNP rel8 , JNP_REL8_HINT // JNP rel8, hint , JNS_LABEL // JNS label8 , JNS_LABEL_1 // JNS label32 , JNS_LABEL_HINT // JNS label8, hint , JNS_LABEL_HINT_1 // JNS label32, hint , JNS_REL32 // JNS rel32 , JNS_REL32_HINT // JNS rel32, hint , JNS_REL8 // JNS rel8 , JNS_REL8_HINT // JNS rel8, hint , JNZ_LABEL // JNZ label8 , JNZ_LABEL_1 // JNZ label32 , JNZ_LABEL_HINT // JNZ label8, hint , JNZ_LABEL_HINT_1 // JNZ label32, hint , JNZ_REL32 // JNZ rel32 , JNZ_REL32_HINT // JNZ rel32, hint , JNZ_REL8 // JNZ rel8 , JNZ_REL8_HINT // JNZ rel8, hint , JO_LABEL // JO label8 , JO_LABEL_1 // JO label32 , JO_LABEL_HINT // JO label8, hint , JO_LABEL_HINT_1 // JO label32, hint , JO_REL32 // JO rel32 , JO_REL32_HINT // JO rel32, hint , JO_REL8 // JO rel8 , JO_REL8_HINT // JO rel8, hint , JP_LABEL // JP label8 , JP_LABEL_1 // JP label32 , JP_LABEL_HINT // JP label8, hint , JP_LABEL_HINT_1 // JP label32, hint , JP_REL32 // JP rel32 , JP_REL32_HINT // JP rel32, hint , JP_REL8 // JP rel8 , JP_REL8_HINT // JP rel8, hint , JPE_LABEL // JPE label8 , JPE_LABEL_1 // JPE label32 , JPE_LABEL_HINT // JPE label8, hint , JPE_LABEL_HINT_1 // JPE label32, hint , JPE_REL32 // JPE rel32 , JPE_REL32_HINT // JPE rel32, hint , JPE_REL8 // JPE rel8 , JPE_REL8_HINT // JPE rel8, hint , JPO_LABEL // JPO label8 , JPO_LABEL_1 // JPO label32 , JPO_LABEL_HINT // JPO label8, hint , JPO_LABEL_HINT_1 // JPO label32, hint , JPO_REL32 // JPO rel32 , JPO_REL32_HINT // JPO rel32, hint , JPO_REL8 // JPO rel8 , JPO_REL8_HINT // JPO rel8, hint , JRCXZ_LABEL // JRCXZ label8 , JRCXZ_LABEL_HINT // JRCXZ label8, hint , JRCXZ_REL8 // JRCXZ rel8 , JRCXZ_REL8_HINT // JRCXZ rel8, hint , JS_LABEL // JS label8 , JS_LABEL_1 // JS label32 , JS_LABEL_HINT // JS label8, hint , JS_LABEL_HINT_1 // JS label32, hint , JS_REL32 // JS rel32 , JS_REL32_HINT // JS rel32, hint , JS_REL8 // JS rel8 , JS_REL8_HINT // JS rel8, hint , JZ_LABEL // JZ label8 , JZ_LABEL_1 // JZ label32 , JZ_LABEL_HINT // JZ label8, hint , JZ_LABEL_HINT_1 // JZ label32, hint , JZ_REL32 // JZ rel32 , JZ_REL32_HINT // JZ rel32, hint , JZ_REL8 // JZ rel8 , JZ_REL8_HINT // JZ rel8, hint , LOOP_LABEL // LOOP label8 , LOOP_REL8 // LOOP rel8 , LOOPE_LABEL // LOOPE label8 , LOOPE_REL8 // LOOPE rel8 , LOOPNE_LABEL // LOOPNE label8 , LOOPNE_REL8 // LOOPNE rel8 }; vector<Opcode> instr_cat_base_ = { // CALL_LABEL // , ADC_AL_IMM8 // ADC AL, imm8 // , ADC_AX_IMM16 // ADC AX, imm16 // , ADC_EAX_IMM32 // ADC EAX, imm32 // , ADC_M16_IMM16 // ADC m16, imm16 // , ADC_M16_IMM8 // ADC m16, imm8 // , ADC_M16_R16 // ADC m16, r16 // , ADC_M32_IMM32 // ADC m32, imm32 // , ADC_M32_IMM8 // ADC m32, imm8 // , ADC_M32_R32 // ADC m32, r32 // , ADC_M64_IMM32 // ADC m64, imm32 // , ADC_M64_IMM8 // ADC m64, imm8 // , ADC_M64_R64 // ADC m64, r64 // , ADC_M8_IMM8 // ADC m8, imm8 // , ADC_M8_R8 // ADC m8, r8 // , ADC_M8_RH // ADC m8, rh // , ADC_R16_IMM16 // ADC r16, imm16 // , ADC_R16_IMM8 // ADC r16, imm8 // , ADC_R16_M16 // ADC r16, m16 ADC_R16_R16 // ADC r16, r16 // , ADC_R32_IMM32 // ADC r32, imm32 // , ADC_R32_IMM8 // ADC r32, imm8 // , ADC_R32_M32 // ADC r32, m32 , ADC_R32_R32 // ADC r32, r32 // , ADC_R64_IMM32 // ADC r64, imm32 // , ADC_R64_IMM8 // ADC r64, imm8 // , ADC_R64_M64 // ADC r64, m64 , ADC_R64_R64 // ADC r64, r64 // , ADC_R8_IMM8 // ADC r8, imm8 // , ADC_R8_M8 // ADC r8, m8 , ADC_R8_R8 // ADC r8, r8 // , ADC_R8_RH // ADC r8, rh // , ADC_RAX_IMM32 // ADC RAX, imm32 // , ADC_RH_IMM8 // ADC rh, imm8 // , ADC_RH_M8 // ADC rh, m8 // , ADC_RH_R8 // ADC rh, r8 // , ADC_RH_RH // ADC rh, rh // , ADD_AL_IMM8 // ADD AL, imm8 // , ADD_AX_IMM16 // ADD AX, imm16 // , ADD_EAX_IMM32 // ADD EAX, imm32 // , ADD_M16_IMM16 // ADD m16, imm16 // , ADD_M16_IMM8 // ADD m16, imm8 // , ADD_M16_R16 // ADD m16, r16 // , ADD_M32_IMM32 // ADD m32, imm32 // , ADD_M32_IMM8 // ADD m32, imm8 // , ADD_M32_R32 // ADD m32, r32 // , ADD_M64_IMM32 // ADD m64, imm32 // , ADD_M64_IMM8 // ADD m64, imm8 // , ADD_M64_R64 // ADD m64, r64 // , ADD_M8_IMM8 // ADD m8, imm8 // , ADD_M8_R8 // ADD m8, r8 // , ADD_M8_RH // ADD m8, rh // , ADD_R16_IMM16 // ADD r16, imm16 // , ADD_R16_IMM8 // ADD r16, imm8 // , ADD_R16_M16 // ADD r16, m16 // , ADD_R16_R16 // ADD r16, r16 // , ADD_R32_IMM32 // ADD r32, imm32 // , ADD_R32_IMM8 // ADD r32, imm8 // , ADD_R32_M32 // ADD r32, m32 // , ADD_R32_R32 // ADD r32, r32 // , ADD_R64_IMM32 // ADD r64, imm32 // , ADD_R64_IMM8 // ADD r64, imm8 // , ADD_R64_M64 // ADD r64, m64 // , ADD_R64_R64 // ADD r64, r64 // , ADD_R8_IMM8 // ADD r8, imm8 // , ADD_R8_M8 // ADD r8, m8 // , ADD_R8_R8 // ADD r8, r8 // , ADD_R8_RH // ADD r8, rh // , ADD_RAX_IMM32 // ADD RAX, imm32 // , ADD_RH_IMM8 // ADD rh, imm8 // , ADD_RH_M8 // ADD rh, m8 // , ADD_RH_R8 // ADD rh, r8 // , ADD_RH_RH // ADD rh, rh // , ADDPD_XMM_M128 // ADDPD xmm, m128 // , ADDPD_XMM_XMM // ADDPD xmm, xmm // , ADDPS_XMM_M128 // ADDPS xmm, m128 // , ADDPS_XMM_XMM // ADDPS xmm, xmm // , ADDSD_XMM_M64 // ADDSD xmm, m64 // , ADDSD_XMM_XMM // ADDSD xmm, xmm // , ADDSS_XMM_M32 // ADDSS xmm, m32 // , ADDSS_XMM_XMM // ADDSS xmm, xmm // , ADDSUBPD_XMM_M128 // ADDSUBPD xmm, m128 // , ADDSUBPD_XMM_XMM // ADDSUBPD xmm, xmm // , ADDSUBPS_XMM_M128 // ADDSUBPS xmm, m128 // , ADDSUBPS_XMM_XMM // ADDSUBPS xmm, xmm // , AESDEC_XMM_M128 // AESDEC xmm, m128 // , AESDEC_XMM_XMM // AESDEC xmm, xmm // , AESDECLAST_XMM_M128 // AESDECLAST xmm, m128 // , AESDECLAST_XMM_XMM // AESDECLAST xmm, xmm // , AESENC_XMM_M128 // AESENC xmm, m128 // , AESENC_XMM_XMM // AESENC xmm, xmm // , AESENCLAST_XMM_M128 // AESENCLAST xmm, m128 // , AESENCLAST_XMM_XMM // AESENCLAST xmm, xmm // , AESIMC_XMM_M128 // AESIMC xmm, m128 // , AESIMC_XMM_XMM // AESIMC xmm, xmm // , AESKEYGENASSIST_XMM_M128_IMM8 // AESKEYGENASSIST xmm, m128, imm8 // , AESKEYGENASSIST_XMM_XMM_IMM8 // AESKEYGENASSIST xmm, xmm, imm8 // , AND_AL_IMM8 // AND AL, imm8 // , AND_AX_IMM16 // AND AX, imm16 // , AND_EAX_IMM32 // AND EAX, imm32 // , AND_M16_IMM16 // AND m16, imm16 // , AND_M16_IMM8 // AND m16, imm8 // , AND_M16_R16 // AND m16, r16 // , AND_M32_IMM32 // AND m32, imm32 // , AND_M32_IMM8 // AND m32, imm8 // , AND_M32_R32 // AND m32, r32 // , AND_M64_IMM32 // AND m64, imm32 // , AND_M64_IMM8 // AND m64, imm8 // , AND_M64_R64 // AND m64, r64 // , AND_M8_IMM8 // AND m8, imm8 // , AND_M8_R8 // AND m8, r8 // , AND_M8_RH // AND m8, rh // , AND_R16_IMM16 // AND r16, imm16 // , AND_R16_IMM8 // AND r16, imm8 // , AND_R16_M16 // AND r16, m16 // , AND_R16_R16 // AND r16, r16 // , AND_R32_IMM32 // AND r32, imm32 // , AND_R32_IMM8 // AND r32, imm8 // , AND_R32_M32 // AND r32, m32 // , AND_R32_R32 // AND r32, r32 // , AND_R64_IMM32 // AND r64, imm32 // , AND_R64_IMM8 // AND r64, imm8 // , AND_R64_M64 // AND r64, m64 // , AND_R64_R64 // AND r64, r64 // , AND_R8_IMM8 // AND r8, imm8 // , AND_R8_M8 // AND r8, m8 // , AND_R8_R8 // AND r8, r8 // , AND_R8_RH // AND r8, rh // , AND_RAX_IMM32 // AND RAX, imm32 // , AND_RH_IMM8 // AND rh, imm8 // , AND_RH_M8 // AND rh, m8 // , AND_RH_R8 // AND rh, r8 // , AND_RH_RH // AND rh, rh // , ANDN_R32_R32_M32 // ANDN r32, r32, m32 // , ANDN_R32_R32_R32 // ANDN r32, r32, r32 // , ANDN_R64_R64_M64 // ANDN r64, r64, m64 // , ANDN_R64_R64_R64 // ANDN r64, r64, r64 // , ANDNPD_XMM_M128 // ANDNPD xmm, m128 // , ANDNPD_XMM_XMM // ANDNPD xmm, xmm // , ANDNPS_XMM_M128 // ANDNPS xmm, m128 // , ANDNPS_XMM_XMM // ANDNPS xmm, xmm // , ANDPD_XMM_M128 // ANDPD xmm, m128 // , ANDPD_XMM_XMM // ANDPD xmm, xmm // , ANDPS_XMM_M128 // ANDPS xmm, m128 // , ANDPS_XMM_XMM // ANDPS xmm, xmm // , BEXTR_R32_M32_R32 // BEXTR r32, m32, r32 // , BEXTR_R32_R32_R32 // BEXTR r32, r32, r32 // , BEXTR_R64_M64_R64 // BEXTR r64, m64, r64 // , BEXTR_R64_R64_R64 // BEXTR r64, r64, r64 // , BLENDPD_XMM_M128_IMM8 // BLENDPD xmm, m128, imm8 // , BLENDPD_XMM_XMM_IMM8 // BLENDPD xmm, xmm, imm8 // , BLENDPS_XMM_M128_IMM8 // BLENDPS xmm, m128, imm8 // , BLENDPS_XMM_XMM_IMM8 // BLENDPS xmm, xmm, imm8 // , BLENDVPD_XMM_M128_XMM0 // BLENDVPD xmm, m128, <XMM0> // , BLENDVPD_XMM_XMM_XMM0 // BLENDVPD xmm, xmm, <XMM0> // , BLENDVPS_XMM_M128_XMM0 // BLENDVPS xmm, m128, <XMM0> // , BLENDVPS_XMM_XMM_XMM0 // BLENDVPS xmm, xmm, <XMM0> // , BLSI_R32_M32 // BLSI r32, m32 // , BLSI_R32_R32 // BLSI r32, r32 // , BLSI_R64_M64 // BLSI r64, m64 // , BLSI_R64_R64 // BLSI r64, r64 // , BLSMSK_R32_M32 // BLSMSK r32, m32 // , BLSMSK_R32_R32 // BLSMSK r32, r32 // , BLSMSK_R64_M64 // BLSMSK r64, m64 // , BLSMSK_R64_R64 // BLSMSK r64, r64 // , BLSR_R32_M32 // BLSR r32, m32 // , BLSR_R32_R32 // BLSR r32, r32 // , BLSR_R64_M64 // BLSR r64, m64 // , BLSR_R64_R64 // BLSR r64, r64 // , BSF_R32_M32 // BSF r32, m32 // , BSF_R32_R32 // BSF r32, r32 // , BSF_R64_M64 // BSF r64, m64 // , BSF_R64_R64 // BSF r64, r64 // , BSR_R16_M16 // BSR r16, m16 // , BSR_R16_R16 // BSR r16, r16 // , BSR_R32_M32 // BSR r32, m32 // , BSR_R32_R32 // BSR r32, r32 // , BSR_R64_M64 // BSR r64, m64 // , BSR_R64_R64 // BSR r64, r64 // , BSWAP_R32 // BSWAP r32 // , BSWAP_R64 // BSWAP r64 // , BT_M16_IMM8 // BT m16, imm8 // , BT_M16_R16 // BT m16, r16 // , BT_M32_IMM8 // BT m32, imm8 // , BT_M32_R32 // BT m32, r32 // , BT_M64_IMM8 // BT m64, imm8 // , BT_M64_R64 // BT m64, r64 // , BT_R16_IMM8 // BT r16, imm8 // , BT_R16_R16 // BT r16, r16 // , BT_R32_IMM8 // BT r32, imm8 // , BT_R32_R32 // BT r32, r32 // , BT_R64_IMM8 // BT r64, imm8 // , BT_R64_R64 // BT r64, r64 // , BTC_M16_IMM8 // BTC m16, imm8 // , BTC_M16_R16 // BTC m16, r16 // , BTC_M32_IMM8 // BTC m32, imm8 // , BTC_M32_R32 // BTC m32, r32 // , BTC_M64_IMM8 // BTC m64, imm8 // , BTC_M64_R64 // BTC m64, r64 // , BTC_R16_IMM8 // BTC r16, imm8 // , BTC_R16_R16 // BTC r16, r16 // , BTC_R32_IMM8 // BTC r32, imm8 // , BTC_R32_R32 // BTC r32, r32 // , BTC_R64_IMM8 // BTC r64, imm8 // , BTC_R64_R64 // BTC r64, r64 // , BTR_M16_IMM8 // BTR m16, imm8 // , BTR_M16_R16 // BTR m16, r16 // , BTR_M32_IMM8 // BTR m32, imm8 // , BTR_M32_R32 // BTR m32, r32 // , BTR_M64_IMM8 // BTR m64, imm8 // , BTR_M64_R64 // BTR m64, r64 // , BTR_R16_IMM8 // BTR r16, imm8 // , BTR_R16_R16 // BTR r16, r16 // , BTR_R32_IMM8 // BTR r32, imm8 // , BTR_R32_R32 // BTR r32, r32 // , BTR_R64_IMM8 // BTR r64, imm8 // , BTR_R64_R64 // BTR r64, r64 // , BTS_M16_IMM8 // BTS m16, imm8 // , BTS_M16_R16 // BTS m16, r16 // , BTS_M32_IMM8 // BTS m32, imm8 // , BTS_M32_R32 // BTS m32, r32 // , BTS_M64_IMM8 // BTS m64, imm8 // , BTS_M64_R64 // BTS m64, r64 // , BTS_R16_IMM8 // BTS r16, imm8 // , BTS_R16_R16 // BTS r16, r16 // , BTS_R32_IMM8 // BTS r32, imm8 // , BTS_R32_R32 // BTS r32, r32 // , BTS_R64_IMM8 // BTS r64, imm8 // , BTS_R64_R64 // BTS r64, r64 // , BZHI_R32_M32_R32 // BZHI r32, m32, r32 // , BZHI_R32_R32_R32 // BZHI r32, r32, r32 // , BZHI_R64_M64_R64 // BZHI r64, m64, r64 // , BZHI_R64_R64_R64 // BZHI r64, r64, r64 // , CALL_FARPTR1616 // CALL m16:16 // , CALL_FARPTR1632 // CALL m16:32 // , CALL_FARPTR1664 // CALL m16:64 // , CALL_M64 // CALL m64 // , CALL_R64 // CALL r64 // , CALL_REL32 // CALL rel32 // , CALL_LABEL // CALL label // , CBW // CBW // , CDQ // CDQ // , CDQE // CDQE // , CLC // CLC // , CLD // CLD // , CLFLUSH_M8 // CLFLUSH m8 // , CLI // CLI // , CMC // CMC // , CMOVA_R16_M16 // CMOVA r16, m16 // , CMOVA_R16_R16 // CMOVA r16, r16 // , CMOVA_R32_M32 // CMOVA r32, m32 // , CMOVA_R32_R32 // CMOVA r32, r32 // , CMOVA_R64_M64 // CMOVA r64, m64 // , CMOVA_R64_R64 // CMOVA r64, r64 // , CMOVAE_R16_M16 // CMOVAE r16, m16 // , CMOVAE_R16_R16 // CMOVAE r16, r16 // , CMOVAE_R32_M32 // CMOVAE r32, m32 // , CMOVAE_R32_R32 // CMOVAE r32, r32 // , CMOVAE_R64_M64 // CMOVAE r64, m64 // , CMOVAE_R64_R64 // CMOVAE r64, r64 // , CMOVB_R16_M16 // CMOVB r16, m16 // , CMOVB_R16_R16 // CMOVB r16, r16 // , CMOVB_R32_M32 // CMOVB r32, m32 // , CMOVB_R32_R32 // CMOVB r32, r32 // , CMOVB_R64_M64 // CMOVB r64, m64 // , CMOVB_R64_R64 // CMOVB r64, r64 // , CMOVBE_R16_M16 // CMOVBE r16, m16 // , CMOVBE_R16_R16 // CMOVBE r16, r16 // , CMOVBE_R32_M32 // CMOVBE r32, m32 // , CMOVBE_R32_R32 // CMOVBE r32, r32 // , CMOVBE_R64_M64 // CMOVBE r64, m64 // , CMOVBE_R64_R64 // CMOVBE r64, r64 // , CMOVC_R16_M16 // CMOVC r16, m16 // , CMOVC_R16_R16 // CMOVC r16, r16 // , CMOVC_R32_M32 // CMOVC r32, m32 // , CMOVC_R32_R32 // CMOVC r32, r32 // , CMOVC_R64_M64 // CMOVC r64, m64 // , CMOVC_R64_R64 // CMOVC r64, r64 // , CMOVE_R16_M16 // CMOVE r16, m16 // , CMOVE_R16_R16 // CMOVE r16, r16 // , CMOVE_R32_M32 // CMOVE r32, m32 // , CMOVE_R32_R32 // CMOVE r32, r32 // , CMOVE_R64_M64 // CMOVE r64, m64 , CMOVE_R64_R64 // CMOVE r64, r64 // , CMOVG_R16_M16 // CMOVG r16, m16 // , CMOVG_R16_R16 // CMOVG r16, r16 // , CMOVG_R32_M32 // CMOVG r32, m32 // , CMOVG_R32_R32 // CMOVG r32, r32 // , CMOVG_R64_M64 // CMOVG r64, m64 // , CMOVG_R64_R64 // CMOVG r64, r64 // , CMOVGE_R16_M16 // CMOVGE r16, m16 // , CMOVGE_R16_R16 // CMOVGE r16, r16 // , CMOVGE_R32_M32 // CMOVGE r32, m32 // , CMOVGE_R32_R32 // CMOVGE r32, r32 // , CMOVGE_R64_M64 // CMOVGE r64, m64 // , CMOVGE_R64_R64 // CMOVGE r64, r64 // , CMOVL_R16_M16 // CMOVL r16, m16 // , CMOVL_R16_R16 // CMOVL r16, r16 // , CMOVL_R32_M32 // CMOVL r32, m32 // , CMOVL_R32_R32 // CMOVL r32, r32 // , CMOVL_R64_M64 // CMOVL r64, m64 // , CMOVL_R64_R64 // CMOVL r64, r64 // , CMOVLE_R16_M16 // CMOVLE r16, m16 // , CMOVLE_R16_R16 // CMOVLE r16, r16 // , CMOVLE_R32_M32 // CMOVLE r32, m32 // , CMOVLE_R32_R32 // CMOVLE r32, r32 // , CMOVLE_R64_M64 // CMOVLE r64, m64 // , CMOVLE_R64_R64 // CMOVLE r64, r64 // , CMOVNA_R16_M16 // CMOVNA r16, m16 // , CMOVNA_R16_R16 // CMOVNA r16, r16 // , CMOVNA_R32_M32 // CMOVNA r32, m32 // , CMOVNA_R32_R32 // CMOVNA r32, r32 // , CMOVNA_R64_M64 // CMOVNA r64, m64 // , CMOVNA_R64_R64 // CMOVNA r64, r64 // , CMOVNAE_R16_M16 // CMOVNAE r16, m16 // , CMOVNAE_R16_R16 // CMOVNAE r16, r16 // , CMOVNAE_R32_M32 // CMOVNAE r32, m32 // , CMOVNAE_R32_R32 // CMOVNAE r32, r32 // , CMOVNAE_R64_M64 // CMOVNAE r64, m64 // , CMOVNAE_R64_R64 // CMOVNAE r64, r64 // , CMOVNB_R16_M16 // CMOVNB r16, m16 // , CMOVNB_R16_R16 // CMOVNB r16, r16 // , CMOVNB_R32_M32 // CMOVNB r32, m32 // , CMOVNB_R32_R32 // CMOVNB r32, r32 // , CMOVNB_R64_M64 // CMOVNB r64, m64 // , CMOVNB_R64_R64 // CMOVNB r64, r64 // , CMOVNBE_R16_M16 // CMOVNBE r16, m16 // , CMOVNBE_R16_R16 // CMOVNBE r16, r16 // , CMOVNBE_R32_M32 // CMOVNBE r32, m32 // , CMOVNBE_R32_R32 // CMOVNBE r32, r32 // , CMOVNBE_R64_M64 // CMOVNBE r64, m64 // , CMOVNBE_R64_R64 // CMOVNBE r64, r64 // , CMOVNC_R16_M16 // CMOVNC r16, m16 // , CMOVNC_R16_R16 // CMOVNC r16, r16 // , CMOVNC_R32_M32 // CMOVNC r32, m32 // , CMOVNC_R32_R32 // CMOVNC r32, r32 // , CMOVNC_R64_M64 // CMOVNC r64, m64 // , CMOVNC_R64_R64 // CMOVNC r64, r64 // , CMOVNE_R16_M16 // CMOVNE r16, m16 // , CMOVNE_R16_R16 // CMOVNE r16, r16 // , CMOVNE_R32_M32 // CMOVNE r32, m32 // , CMOVNE_R32_R32 // CMOVNE r32, r32 // , CMOVNE_R64_M64 // CMOVNE r64, m64 // , CMOVNE_R64_R64 // CMOVNE r64, r64 // , CMOVNG_R16_M16 // CMOVNG r16, m16 // , CMOVNG_R16_R16 // CMOVNG r16, r16 // , CMOVNG_R32_M32 // CMOVNG r32, m32 // , CMOVNG_R32_R32 // CMOVNG r32, r32 // , CMOVNG_R64_M64 // CMOVNG r64, m64 // , CMOVNG_R64_R64 // CMOVNG r64, r64 // , CMOVNGE_R16_M16 // CMOVNGE r16, m16 // , CMOVNGE_R16_R16 // CMOVNGE r16, r16 // , CMOVNGE_R32_M32 // CMOVNGE r32, m32 // , CMOVNGE_R32_R32 // CMOVNGE r32, r32 // , CMOVNGE_R64_M64 // CMOVNGE r64, m64 // , CMOVNGE_R64_R64 // CMOVNGE r64, r64 // , CMOVNL_R16_M16 // CMOVNL r16, m16 // , CMOVNL_R16_R16 // CMOVNL r16, r16 // , CMOVNL_R32_M32 // CMOVNL r32, m32 // , CMOVNL_R32_R32 // CMOVNL r32, r32 // , CMOVNL_R64_M64 // CMOVNL r64, m64 // , CMOVNL_R64_R64 // CMOVNL r64, r64 // , CMOVNLE_R16_M16 // CMOVNLE r16, m16 // , CMOVNLE_R16_R16 // CMOVNLE r16, r16 // , CMOVNLE_R32_M32 // CMOVNLE r32, m32 // , CMOVNLE_R32_R32 // CMOVNLE r32, r32 // , CMOVNLE_R64_M64 // CMOVNLE r64, m64 // , CMOVNLE_R64_R64 // CMOVNLE r64, r64 // , CMOVNO_R16_M16 // CMOVNO r16, m16 // , CMOVNO_R16_R16 // CMOVNO r16, r16 // , CMOVNO_R32_M32 // CMOVNO r32, m32 // , CMOVNO_R32_R32 // CMOVNO r32, r32 // , CMOVNO_R64_M64 // CMOVNO r64, m64 // , CMOVNO_R64_R64 // CMOVNO r64, r64 // , CMOVNP_R16_M16 // CMOVNP r16, m16 // , CMOVNP_R16_R16 // CMOVNP r16, r16 // , CMOVNP_R32_M32 // CMOVNP r32, m32 // , CMOVNP_R32_R32 // CMOVNP r32, r32 // , CMOVNP_R64_M64 // CMOVNP r64, m64 // , CMOVNP_R64_R64 // CMOVNP r64, r64 // , CMOVNS_R16_M16 // CMOVNS r16, m16 // , CMOVNS_R16_R16 // CMOVNS r16, r16 // , CMOVNS_R32_M32 // CMOVNS r32, m32 // , CMOVNS_R32_R32 // CMOVNS r32, r32 // , CMOVNS_R64_M64 // CMOVNS r64, m64 // , CMOVNS_R64_R64 // CMOVNS r64, r64 // , CMOVNZ_R16_M16 // CMOVNZ r16, m16 // , CMOVNZ_R16_R16 // CMOVNZ r16, r16 // , CMOVNZ_R32_M32 // CMOVNZ r32, m32 // , CMOVNZ_R32_R32 // CMOVNZ r32, r32 // , CMOVNZ_R64_M64 // CMOVNZ r64, m64 // , CMOVNZ_R64_R64 // CMOVNZ r64, r64 // , CMOVO_R16_M16 // CMOVO r16, m16 // , CMOVO_R16_R16 // CMOVO r16, r16 // , CMOVO_R32_M32 // CMOVO r32, m32 // , CMOVO_R32_R32 // CMOVO r32, r32 // , CMOVO_R64_M64 // CMOVO r64, m64 // , CMOVO_R64_R64 // CMOVO r64, r64 // , CMOVP_R16_M16 // CMOVP r16, m16 // , CMOVP_R16_R16 // CMOVP r16, r16 // , CMOVP_R32_M32 // CMOVP r32, m32 // , CMOVP_R32_R32 // CMOVP r32, r32 // , CMOVP_R64_M64 // CMOVP r64, m64 // , CMOVP_R64_R64 // CMOVP r64, r64 // , CMOVPE_R16_M16 // CMOVPE r16, m16 // , CMOVPE_R16_R16 // CMOVPE r16, r16 // , CMOVPE_R32_M32 // CMOVPE r32, m32 // , CMOVPE_R32_R32 // CMOVPE r32, r32 // , CMOVPE_R64_M64 // CMOVPE r64, m64 // , CMOVPE_R64_R64 // CMOVPE r64, r64 // , CMOVPO_R16_M16 // CMOVPO r16, m16 // , CMOVPO_R16_R16 // CMOVPO r16, r16 // , CMOVPO_R32_M32 // CMOVPO r32, m32 // , CMOVPO_R32_R32 // CMOVPO r32, r32 // , CMOVPO_R64_M64 // CMOVPO r64, m64 // , CMOVPO_R64_R64 // CMOVPO r64, r64 // , CMOVS_R16_M16 // CMOVS r16, m16 // , CMOVS_R16_R16 // CMOVS r16, r16 // , CMOVS_R32_M32 // CMOVS r32, m32 // , CMOVS_R32_R32 // CMOVS r32, r32 // , CMOVS_R64_M64 // CMOVS r64, m64 // , CMOVS_R64_R64 // CMOVS r64, r64 // , CMOVZ_R16_M16 // CMOVZ r16, m16 // , CMOVZ_R16_R16 // CMOVZ r16, r16 // , CMOVZ_R32_M32 // CMOVZ r32, m32 // , CMOVZ_R32_R32 // CMOVZ r32, r32 // , CMOVZ_R64_M64 // CMOVZ r64, m64 // , CMOVZ_R64_R64 // CMOVZ r64, r64 // , CMP_AL_IMM8 // CMP AL, imm8 // , CMP_AX_IMM16 // CMP AX, imm16 // , CMP_EAX_IMM32 // CMP EAX, imm32 // , CMP_M16_IMM16 // CMP m16, imm16 // , CMP_M16_IMM8 // CMP m16, imm8 // , CMP_M16_R16 // CMP m16, r16 // , CMP_M32_IMM32 // CMP m32, imm32 // , CMP_M32_IMM8 // CMP m32, imm8 // , CMP_M32_R32 // CMP m32, r32 // , CMP_M64_IMM32 // CMP m64, imm32 // , CMP_M64_IMM8 // CMP m64, imm8 // , CMP_M64_R64 // CMP m64, r64 // , CMP_M8_IMM8 // CMP m8, imm8 // , CMP_M8_R8 // CMP m8, r8 // , CMP_M8_RH // CMP m8, rh // , CMP_R16_IMM16 // CMP r16, imm16 // , CMP_R16_IMM8 // CMP r16, imm8 // , CMP_R16_M16 // CMP r16, m16 // , CMP_R16_R16 // CMP r16, r16 // , CMP_R32_IMM32 // CMP r32, imm32 // , CMP_R32_IMM8 // CMP r32, imm8 // , CMP_R32_M32 // CMP r32, m32 // , CMP_R32_R32 // CMP r32, r32 // , CMP_R64_IMM32 // CMP r64, imm32 // , CMP_R64_IMM8 // CMP r64, imm8 // , CMP_R64_M64 // CMP r64, m64 // , CMP_R64_R64 // CMP r64, r64 // , CMP_R8_IMM8 // CMP r8, imm8 // , CMP_R8_M8 // CMP r8, m8 // , CMP_R8_R8 // CMP r8, r8 // , CMP_R8_RH // CMP r8, rh // , CMP_RAX_IMM32 // CMP RAX, imm32 // , CMP_RH_IMM8 // CMP rh, imm8 // , CMP_RH_M8 // CMP rh, m8 // , CMP_RH_R8 // CMP rh, r8 // , CMP_RH_RH // CMP rh, rh // , CMPPD_XMM_M128_IMM8 // CMPPD xmm, m128, imm8 // , CMPPD_XMM_XMM_IMM8 // CMPPD xmm, xmm, imm8 // , CMPPS_XMM_M128_IMM8 // CMPPS xmm, m128, imm8 // , CMPPS_XMM_XMM_IMM8 // CMPPS xmm, xmm, imm8 // , CMPS_M16_M16 // CMPS m16, m16 // , CMPS_M32_M32 // CMPS m32, m32 // , CMPS_M64_M64 // CMPS m64, m64 // , CMPS_M8_M8 // CMPS m8, m8 // , CMPSB // CMPSB // , CMPSD // CMPSD // , CMPSD_XMM_M64_IMM8 // CMPSD xmm, m64, imm8 // , CMPSD_XMM_XMM_IMM8 // CMPSD xmm, xmm, imm8 // , CMPSQ // CMPSQ // , CMPSS_XMM_M32_IMM8 // CMPSS xmm, m32, imm8 // , CMPSS_XMM_XMM_IMM8 // CMPSS xmm, xmm, imm8 // , CMPSW // CMPSW // , CMPXCHG_M16_R16 // CMPXCHG m16, r16 // , CMPXCHG_M32_R32 // CMPXCHG m32, r32 // , CMPXCHG_M64_R64 // CMPXCHG m64, r64 // , CMPXCHG_M8_R8 // CMPXCHG m8, r8 // , CMPXCHG_M8_RH // CMPXCHG m8, rh // , CMPXCHG_R16_R16 // CMPXCHG r16, r16 // , CMPXCHG_R32_R32 // CMPXCHG r32, r32 // , CMPXCHG_R64_R64 // CMPXCHG r64, r64 // , CMPXCHG_R8_R8 // CMPXCHG r8, r8 // , CMPXCHG_R8_RH // CMPXCHG r8, rh // , CMPXCHG_RH_R8 // CMPXCHG rh, r8 // , CMPXCHG_RH_RH // CMPXCHG rh, rh // , CMPXCHG16B_M128 // CMPXCHG16B m128 // , CMPXCHG8B_M64 // CMPXCHG8B m64 // , COMISD_XMM_M64 // COMISD xmm, m64 // , COMISD_XMM_XMM // COMISD xmm, xmm // , COMISS_XMM_M32 // COMISS xmm, m32 // , COMISS_XMM_XMM // COMISS xmm, xmm // , CPUID // CPUID // , CQO // CQO // , CRC32_R32_M16 // CRC32 r32, m16 // , CRC32_R32_M32 // CRC32 r32, m32 // , CRC32_R32_M8 // CRC32 r32, m8 // , CRC32_R32_R16 // CRC32 r32, r16 // , CRC32_R32_R32 // CRC32 r32, r32 // , CRC32_R32_R8 // CRC32 r32, r8 // , CRC32_R32_RH // CRC32 r32, rh // , CRC32_R64_M64 // CRC32 r64, m64 // , CRC32_R64_M8 // CRC32 r64, m8 // , CRC32_R64_R64 // CRC32 r64, r64 // , CRC32_R64_R8 // CRC32 r64, r8 // , CRC32_R64_RH // CRC32 r64, rh // , CVTDQ2PD_XMM_M64 // CVTDQ2PD xmm, m64 // , CVTDQ2PD_XMM_XMM // CVTDQ2PD xmm, xmm // , CVTDQ2PS_XMM_M128 // CVTDQ2PS xmm, m128 // , CVTDQ2PS_XMM_XMM // CVTDQ2PS xmm, xmm // , CVTPD2DQ_XMM_M128 // CVTPD2DQ xmm, m128 // , CVTPD2DQ_XMM_XMM // CVTPD2DQ xmm, xmm // , CVTPD2PI_MM_M128 // CVTPD2PI mm, m128 // , CVTPD2PI_MM_XMM // CVTPD2PI mm, xmm // , CVTPD2PS_XMM_M128 // CVTPD2PS xmm, m128 // , CVTPD2PS_XMM_XMM // CVTPD2PS xmm, xmm // , CVTPI2PD_XMM_M64 // CVTPI2PD xmm, m64 // , CVTPI2PD_XMM_MM // CVTPI2PD xmm, mm // , CVTPI2PS_XMM_M64 // CVTPI2PS xmm, m64 // , CVTPI2PS_XMM_MM // CVTPI2PS xmm, mm // , CVTPS2DQ_XMM_M128 // CVTPS2DQ xmm, m128 // , CVTPS2DQ_XMM_XMM // CVTPS2DQ xmm, xmm // , CVTPS2PD_XMM_M64 // CVTPS2PD xmm, m64 // , CVTPS2PD_XMM_XMM // CVTPS2PD xmm, xmm // , CVTPS2PI_MM_M64 // CVTPS2PI mm, m64 // , CVTPS2PI_MM_XMM // CVTPS2PI mm, xmm // , CVTSD2SI_R32_M64 // CVTSD2SI r32, m64 // , CVTSD2SI_R32_XMM // CVTSD2SI r32, xmm cvt_double_to_int32 // , CVTSD2SI_R64_M64 // CVTSD2SI r64, m64 // , CVTSD2SI_R64_XMM // CVTSD2SI r64, xmm cvt_double_to_int64 // , CVTSD2SS_XMM_M64 // CVTSD2SS xmm, m64 // , CVTSD2SS_XMM_XMM // CVTSD2SS xmm, xmm cvt_double_to_single // , CVTSI2SD_XMM_M32 // CVTSI2SD xmm, m32 // , CVTSI2SD_XMM_M64 // CVTSI2SD xmm, m64 // , CVTSI2SD_XMM_R32 // CVTSI2SD xmm, r32 cvt_int32_to_double // , CVTSI2SD_XMM_R64 // CVTSI2SD xmm, r64 cvt_int64_to_double // , CVTSI2SS_XMM_M32 // CVTSI2SS xmm, m32 // , CVTSI2SS_XMM_M64 // CVTSI2SS xmm, m64 // , CVTSI2SS_XMM_R32 // CVTSI2SS xmm, r32 cvt_int32_to_single // , CVTSI2SS_XMM_R64 // CVTSI2SS xmm, r64 cvt_int64_to_single // , CVTSS2SD_XMM_M32 // CVTSS2SD xmm, m32 // , CVTSS2SD_XMM_XMM // CVTSS2SD xmm, xmm cvt_single_to_double // , CVTSS2SI_R32_M32 // CVTSS2SI r32, m32 // , CVTSS2SI_R32_XMM // CVTSS2SI r32, xmm cvt_single_to_int32 // , CVTSS2SI_R64_M32 // CVTSS2SI r64, m32 // , CVTSS2SI_R64_XMM // CVTSS2SI r64, xmm cvt_single_to_int64 // , CVTTPD2DQ_XMM_M128 // CVTTPD2DQ xmm, m128 // , CVTTPD2DQ_XMM_XMM // CVTTPD2DQ xmm, xmm // , CVTTPD2PI_MM_M128 // CVTTPD2PI mm, m128 // , CVTTPD2PI_MM_XMM // CVTTPD2PI mm, xmm // , CVTTPS2DQ_XMM_M128 // CVTTPS2DQ xmm, m128 // , CVTTPS2DQ_XMM_XMM // CVTTPS2DQ xmm, xmm // , CVTTPS2PI_MM_M64 // CVTTPS2PI mm, m64 // , CVTTPS2PI_MM_XMM // CVTTPS2PI mm, xmm // , CVTTSD2SI_R32_M64 // CVTTSD2SI r32, m64 // , CVTTSD2SI_R32_XMM // CVTTSD2SI r32, xmm cvt_double_to_int32_truncate // , CVTTSD2SI_R64_M64 // CVTTSD2SI r64, m64 // , CVTTSD2SI_R64_XMM // CVTTSD2SI r64, xmm cvt_double_to_int64_truncate // , CVTTSS2SI_R32_M32 // CVTTSS2SI r32, m32 // , CVTTSS2SI_R32_XMM // CVTTSS2SI r32, xmm cvt_single_to_int32_truncate // , CVTTSS2SI_R64_M32 // CVTTSS2SI r64, m32 // , CVTTSS2SI_R64_XMM // CVTTSS2SI r64, xmm cvt_single_to_int64_truncate // , CWD // CWD // , CWDE // CWDE // , DEC_M16 // DEC m16 // , DEC_M32 // DEC m32 // , DEC_M64 // DEC m64 // , DEC_M8 // DEC m8 // , DEC_R16 // DEC r16 // , DEC_R32 // DEC r32 // , DEC_R64 // DEC r64 // , DEC_R8 // DEC r8 // , DEC_RH // DEC rh // , DIV_M16 // DIV m16 // , DIV_M32 // DIV m32 // , DIV_M64 // DIV m64 // , DIV_M8 // DIV m8 // , DIV_R16 // DIV r16 // , DIV_R32 // DIV r32 // , DIV_R64 // DIV r64 // , DIV_R8 // DIV r8 // , DIV_RH // DIV rh // , DIVPD_XMM_M128 // DIVPD xmm, m128 // , DIVPD_XMM_XMM // DIVPD xmm, xmm // , DIVPS_XMM_M128 // DIVPS xmm, m128 // , DIVPS_XMM_XMM // DIVPS xmm, xmm // , DIVSD_XMM_M64 // DIVSD xmm, m64 // , DIVSD_XMM_XMM // DIVSD xmm, xmm // , DIVSS_XMM_M32 // DIVSS xmm, m32 // , DIVSS_XMM_XMM // DIVSS xmm, xmm // , DPPD_XMM_M128_IMM8 // DPPD xmm, m128, imm8 // , DPPD_XMM_XMM_IMM8 // DPPD xmm, xmm, imm8 // , DPPS_XMM_M128_IMM8 // DPPS xmm, m128, imm8 // , DPPS_XMM_XMM_IMM8 // DPPS xmm, xmm, imm8 // , EMMS // EMMS // , ENTER_IMM8_IMM16 // ENTER imm8, imm16 // , ENTER_ONE_IMM16 // ENTER 1, imm16 // , ENTER_ZERO_IMM16 // ENTER 0, imm16 // , EXTRACTPS_M32_XMM_IMM8 // EXTRACTPS m32, xmm, imm8 // , EXTRACTPS_R32_XMM_IMM8 // EXTRACTPS r32, xmm, imm8 // , EXTRACTPS_R64_XMM_IMM8 // EXTRACTPS r64, xmm, imm8 // , F2XM1 // F2XM1 // , FABS // FABS // , FADD_M32FP // FADD m32fp // , FADD_M64FP // FADD m64fp // , FADD_ST_ST0 // FADD ST(i), ST // , FADD_ST0_ST // FADD ST, ST(i) // , FADDP // FADDP // , FADDP_ST_ST0 // FADDP ST(i), ST // , FBLD_M80BCD // FBLD m80bcd // , FBSTP_M80BCD // FBSTP m80bcd // , FCHS // FCHS // , FCLEX // FCLEX // , FCMOVB_ST0_ST // FCMOVB ST, ST(i) // , FCMOVBE_ST0_ST // FCMOVBE ST, ST(i) // , FCMOVE_ST0_ST // FCMOVE ST, ST(i) // , FCMOVNB_ST0_ST // FCMOVNB ST, ST(i) // , FCMOVNBE_ST0_ST // FCMOVNBE ST, ST(i) // , FCMOVNE_ST0_ST // FCMOVNE ST, ST(i) // , FCMOVNU_ST0_ST // FCMOVNU ST, ST(i) // , FCMOVU_ST0_ST // FCMOVU ST, ST(i) // , FCOM // FCOM // , FCOM_M32FP // FCOM m32fp // , FCOM_M64FP // FCOM m64fp // , FCOM_ST // FCOM ST(i) // , FCOMI_ST0_ST // FCOMI ST, ST(i) // , FCOMIP_ST0_ST // FCOMIP ST, ST(i) // , FCOMP // FCOMP // , FCOMP_M32FP // FCOMP m32fp // , FCOMP_M64FP // FCOMP m64fp // , FCOMP_ST // FCOMP ST(i) // , FCOMPP // FCOMPP // , FCOS // FCOS // , FDECSTP // FDECSTP // , FDIV_M32FP // FDIV m32fp // , FDIV_M64FP // FDIV m64fp // , FDIV_ST_ST0 // FDIV ST(i), ST // , FDIV_ST0_ST // FDIV ST, ST(i) // , FDIVP // FDIVP // , FDIVP_ST_ST0 // FDIVP ST(i), ST // , FDIVR_M32FP // FDIVR m32fp // , FDIVR_M64FP // FDIVR m64fp // , FDIVR_ST_ST0 // FDIVR ST(i), ST // , FDIVR_ST0_ST // FDIVR ST, ST(i) // , FDIVRP // FDIVRP // , FDIVRP_ST_ST0 // FDIVRP ST(i), ST // , FFREE_ST // FFREE ST(i) // , FIADD_M16INT // FIADD m16int // , FIADD_M32INT // FIADD m32int // , FICOM_M16INT // FICOM m16int // , FICOM_M32INT // FICOM m32int // , FICOMP_M16INT // FICOMP m16int // , FICOMP_M32INT // FICOMP m32int // , FIDIV_M16INT // FIDIV m16int // , FIDIV_M32INT // FIDIV m32int // , FIDIVR_M16INT // FIDIVR m16int // , FIDIVR_M32INT // FIDIVR m32int // , FILD_M16INT // FILD m16int // , FILD_M32INT // FILD m32int // , FILD_M64INT // FILD m64int // , FIMUL_M16INT // FIMUL m16int // , FIMUL_M32INT // FIMUL m32int // , FINCSTP // FINCSTP // , FINIT // FINIT // , FIST_M16INT // FIST m16int // , FIST_M32INT // FIST m32int // , FISTP_M16INT // FISTP m16int // , FISTP_M32INT // FISTP m32int // , FISTP_M64INT // FISTP m64int // , FISTTP_M16INT // FISTTP m16int // , FISTTP_M32INT // FISTTP m32int // , FISTTP_M64INT // FISTTP m64int // , FISUB_M16INT // FISUB m16int // , FISUB_M32INT // FISUB m32int // , FISUBR_M16INT // FISUBR m16int // , FISUBR_M32INT // FISUBR m32int // , FLD_M32FP // FLD m32fp // , FLD_M64FP // FLD m64fp // , FLD_M80FP // FLD m80fp // , FLD_ST // FLD ST(i) // , FLD1 // FLD1 // , FLDCW_M2BYTE // FLDCW m2byte // , FLDENV_M28BYTE // FLDENV m28byte // , FLDL2E // FLDL2E // , FLDL2T // FLDL2T // , FLDLG2 // FLDLG2 // , FLDLN2 // FLDLN2 // , FLDPI // FLDPI // , FLDZ // FLDZ // , FMUL_M32FP // FMUL m32fp // , FMUL_M64FP // FMUL m64fp // , FMUL_ST_ST0 // FMUL ST(i), ST // , FMUL_ST0_ST // FMUL ST, ST(i) // , FMULP // FMULP // , FMULP_ST_ST0 // FMULP ST(i), ST // , FNCLEX // FNCLEX // , FNINIT // FNINIT // , FNOP // FNOP // , FNSAVE_M108BYTE // FNSAVE m108byte // , FNSTCW_M2BYTE // FNSTCW m2byte // , FNSTENV_M28BYTE // FNSTENV m28byte // , FNSTSW_AX // FNSTSW AX // , FNSTSW_M2BYTE // FNSTSW m2byte // , FPATAN // FPATAN // , FPREM // FPREM // , FPREM1 // FPREM1 // , FPTAN // FPTAN // , FRNDINT // FRNDINT // , FRSTOR_M108BYTE // FRSTOR m108byte // , FSAVE_M108BYTE // FSAVE m108byte // , FSCALE // FSCALE // , FSIN // FSIN // , FSINCOS // FSINCOS // , FSQRT // FSQRT // , FST_M32FP // FST m32fp // , FST_M64FP // FST m64fp // , FST_ST // FST ST(i) // , FSTCW_M2BYTE // FSTCW m2byte // , FSTENV_M28BYTE // FSTENV m28byte // , FSTP_M32FP // FSTP m32fp // , FSTP_M64FP // FSTP m64fp // , FSTP_M80FP // FSTP m80fp // , FSTP_ST // FSTP ST(i) // , FSTSW_AX // FSTSW AX // , FSTSW_M2BYTE // FSTSW m2byte // , FSUB_M32FP // FSUB m32fp // , FSUB_M64FP // FSUB m64fp // , FSUB_ST_ST0 // FSUB ST(i), ST // , FSUB_ST0_ST // FSUB ST, ST(i) // , FSUBP // FSUBP // , FSUBP_ST_ST0 // FSUBP ST(i), ST // , FSUBR_M32FP // FSUBR m32fp // , FSUBR_M64FP // FSUBR m64fp // , FSUBR_ST_ST0 // FSUBR ST(i), ST // , FSUBR_ST0_ST // FSUBR ST, ST(i) // , FSUBRP // FSUBRP // , FSUBRP_ST_ST0 // FSUBRP ST(i), ST // , FTST // FTST // , FUCOM // FUCOM // , FUCOM_ST // FUCOM ST(i) // , FUCOMI_ST0_ST // FUCOMI ST, ST(i) // , FUCOMIP_ST0_ST // FUCOMIP ST, ST(i) // , FUCOMP // FUCOMP // , FUCOMP_ST // FUCOMP ST(i) // , FUCOMPP // FUCOMPP // , FWAIT // FWAIT // , FXAM // FXAM // , FXCH // FXCH // , FXCH_ST // FXCH ST(i) // , FXRSTOR_M512BYTE // FXRSTOR m512byte // , FXRSTOR64_M512BYTE // FXRSTOR64 m512byte // , FXSAVE_M512BYTE // FXSAVE m512byte // , FXSAVE64_M512BYTE // FXSAVE64 m512byte // , FXTRACT // FXTRACT // , FYL2X // FYL2X // , FYL2XP1 // FYL2XP1 // , HADDPD_XMM_M128 // HADDPD xmm, m128 // , HADDPD_XMM_XMM // HADDPD xmm, xmm // , HADDPS_XMM_M128 // HADDPS xmm, m128 // , HADDPS_XMM_XMM // HADDPS xmm, xmm // , HSUBPD_XMM_M128 // HSUBPD xmm, m128 // , HSUBPD_XMM_XMM // HSUBPD xmm, xmm // , HSUBPS_XMM_M128 // HSUBPS xmm, m128 // , HSUBPS_XMM_XMM // HSUBPS xmm, xmm // , IDIV_M16 // IDIV m16 // , IDIV_M32 // IDIV m32 // , IDIV_M64 // IDIV m64 // , IDIV_M8 // IDIV m8 // , IDIV_R16 // IDIV r16 // , IDIV_R32 // IDIV r32 // , IDIV_R64 // IDIV r64 // , IDIV_R8 // IDIV r8 // , IDIV_RH // IDIV rh // , IMUL_M16 // IMUL m16 // , IMUL_M32 // IMUL m32 // , IMUL_M64 // IMUL m64 // , IMUL_M8 // IMUL m8 // , IMUL_R16 // IMUL r16 // , IMUL_R16_M16 // IMUL r16, m16 // , IMUL_R16_M16_IMM16 // IMUL r16, m16, imm16 // , IMUL_R16_M16_IMM8 // IMUL r16, m16, imm8 // , IMUL_R16_R16 // IMUL r16, r16 // , IMUL_R16_R16_IMM16 // IMUL r16, r16, imm16 // , IMUL_R16_R16_IMM8 // IMUL r16, r16, imm8 // , IMUL_R32 // IMUL r32 // , IMUL_R32_M32 // IMUL r32, m32 // , IMUL_R32_M32_IMM32 // IMUL r32, m32, imm32 // , IMUL_R32_M32_IMM8 // IMUL r32, m32, imm8 // , IMUL_R32_R32 // IMUL r32, r32 // , IMUL_R32_R32_IMM32 // IMUL r32, r32, imm32 // , IMUL_R32_R32_IMM8 // IMUL r32, r32, imm8 // , IMUL_R64 // IMUL r64 // , IMUL_R64_M64 // IMUL r64, m64 // , IMUL_R64_M64_IMM32 // IMUL r64, m64, imm32 // , IMUL_R64_M64_IMM8 // IMUL r64, m64, imm8 // , IMUL_R64_R64 // IMUL r64, r64 // , IMUL_R64_R64_IMM32 // IMUL r64, r64, imm32 // , IMUL_R64_R64_IMM8 // IMUL r64, r64, imm8 // , IMUL_R8 // IMUL r8 // , IMUL_RH // IMUL rh // , IN_AL_DX // IN AL, DX // , IN_AL_IMM8 // IN AL, imm8 // , IN_AX_DX // IN AX, DX // , IN_AX_IMM8 // IN AX, imm8 // , IN_EAX_DX // IN EAX, DX // , IN_EAX_IMM8 // IN EAX, imm8 // , INC_M16 // INC m16 // , INC_M32 // INC m32 // , INC_M64 // INC m64 // , INC_M8 // INC m8 // , INC_R16 // INC r16 // , INC_R32 // INC r32 // , INC_R64 // INC r64 // , INC_R8 // INC r8 // , INC_RH // INC rh // , INS_M16_DX // INS m16, DX // , INS_M32_DX // INS m32, DX // , INS_M8_DX // INS m8, DX // , INSB // INSB // , INSD // INSD // , INSERTPS_XMM_M32_IMM8 // INSERTPS xmm, m32, imm8 // , INSERTPS_XMM_XMM_IMM8 // INSERTPS xmm, xmm, imm8 // , INSW // INSW // , INT_IMM8 // INT imm8 // , INT_THREE // INT 3 // , INVPCID_R64_M128 // INVPCID r64, m128 // , IRET // IRET // , IRETD // IRETD // , IRETQ // IRETQ // , JA_REL32 // JA rel32 // , JA_LABEL // JA label // , JA_REL32_HINT // JA rel32, hint // , JA_LABEL_HINT // JA label, hint // , JA_REL8 // JA rel8 // , JA_REL8_HINT // JA rel8, hint // , JAE_REL32 // JAE rel32 // , JAE_LABEL // JAE label // , JAE_REL32_HINT // JAE rel32, hint // , JAE_LABEL_HINT // JAE label, hint // , JAE_REL8 // JAE rel8 // , JAE_REL8_HINT // JAE rel8, hint // , JB_REL32 // JB rel32 // , JB_LABEL // JB label // , JB_REL32_HINT // JB rel32, hint // , JB_LABEL_HINT // JB label, hint // , JB_REL8 // JB rel8 // , JB_REL8_HINT // JB rel8, hint // , JBE_REL32 // JBE rel32 // , JBE_LABEL // JBE label // , JBE_REL32_HINT // JBE rel32, hint // , JBE_LABEL_HINT // JBE label, hint // , JBE_REL8 // JBE rel8 // , JBE_REL8_HINT // JBE rel8, hint // , JC_REL32 // JC rel32 // , JC_LABEL // JC label // , JC_REL32_HINT // JC rel32, hint // , JC_LABEL_HINT // JC label, hint // , JC_REL8 // JC rel8 // , JC_REL8_HINT // JC rel8, hint // , JE_REL32 // JE rel32 // , JE_LABEL // JE label // , JE_REL32_HINT // JE rel32, hint // , JE_LABEL_HINT // JE label, hint // , JE_REL8 // JE rel8 // , JE_REL8_HINT // JE rel8, hint // , JECXZ_REL8 // JECXZ rel8 // , JECXZ_REL8_HINT // JECXZ rel8, hint // , JG_REL32 // JG rel32 // , JG_LABEL // JG label // , JG_REL32_HINT // JG rel32, hint // , JG_LABEL_HINT // JG label, hint // , JG_REL8 // JG rel8 // , JG_REL8_HINT // JG rel8, hint // , JGE_REL32 // JGE rel32 // , JGE_LABEL // JGE label // , JGE_REL32_HINT // JGE rel32, hint // , JGE_LABEL_HINT // JGE label, hint // , JGE_REL8 // JGE rel8 // , JGE_REL8_HINT // JGE rel8, hint // , JL_REL32 // JL rel32 // , JL_LABEL // JL label // , JL_REL32_HINT // JL rel32, hint // , JL_LABEL_HINT // JL label, hint // , JL_REL8 // JL rel8 // , JL_REL8_HINT // JL rel8, hint // , JLE_REL32 // JLE rel32 // , JLE_LABEL // JLE label // , JLE_REL32_HINT // JLE rel32, hint // , JLE_LABEL_HINT // JLE label, hint // , JLE_REL8 // JLE rel8 // , JLE_REL8_HINT // JLE rel8, hint // , JMP_FARPTR1616 // JMP m16:16 // , JMP_FARPTR1632 // JMP m16:32 // , JMP_FARPTR1664 // JMP m16:64 // , JMP_M64 // JMP m64 // , JMP_R64 // JMP r64 // , JMP_REL32 // JMP rel32 // , JMP_LABEL // JMP label // , JMP_REL8 // JMP rel8 // , JNA_REL32 // JNA rel32 // , JNA_LABEL // JNA label // , JNA_REL32_HINT // JNA rel32, hint // , JNA_LABEL_HINT // JNA label, hint // , JNA_REL8 // JNA rel8 // , JNA_REL8_HINT // JNA rel8, hint // , JNAE_REL32 // JNAE rel32 // , JNAE_LABEL // JNAE label // , JNAE_REL32_HINT // JNAE rel32, hint // , JNAE_LABEL_HINT // JNAE label, hint // , JNAE_REL8 // JNAE rel8 // , JNAE_REL8_HINT // JNAE rel8, hint // , JNB_REL32 // JNB rel32 // , JNB_LABEL // JNB label // , JNB_REL32_HINT // JNB rel32, hint // , JNB_LABEL_HINT // JNB label, hint // , JNB_REL8 // JNB rel8 // , JNB_REL8_HINT // JNB rel8, hint // , JNBE_REL32 // JNBE rel32 // , JNBE_LABEL // JNBE label // , JNBE_REL32_HINT // JNBE rel32, hint // , JNBE_LABEL_HINT // JNBE label, hint // , JNBE_REL8 // JNBE rel8 // , JNBE_REL8_HINT // JNBE rel8, hint // , JNC_REL32 // JNC rel32 // , JNC_LABEL // JNC label // , JNC_REL32_HINT // JNC rel32, hint // , JNC_LABEL_HINT // JNC label, hint // , JNC_REL8 // JNC rel8 // , JNC_REL8_HINT // JNC rel8, hint // , JNE_REL32 // JNE rel32 // , JNE_LABEL // JNE label // , JNE_REL32_HINT // JNE rel32, hint // , JNE_LABEL_HINT // JNE label, hint // , JNE_REL8 // JNE rel8 // , JNE_REL8_HINT // JNE rel8, hint // , JNG_REL32 // JNG rel32 // , JNG_LABEL // JNG label // , JNG_REL32_HINT // JNG rel32, hint // , JNG_LABEL_HINT // JNG label, hint // , JNG_REL8 // JNG rel8 // , JNG_REL8_HINT // JNG rel8, hint // , JNGE_REL32 // JNGE rel32 // , JNGE_LABEL // JNGE label // , JNGE_REL32_HINT // JNGE rel32, hint // , JNGE_LABEL_HINT // JNGE label, hint // , JNGE_REL8 // JNGE rel8 // , JNGE_REL8_HINT // JNGE rel8, hint // , JNL_REL32 // JNL rel32 // , JNL_LABEL // JNL label // , JNL_REL32_HINT // JNL rel32, hint // , JNL_LABEL_HINT // JNL label, hint // , JNL_REL8 // JNL rel8 // , JNL_REL8_HINT // JNL rel8, hint // , JNLE_REL32 // JNLE rel32 // , JNLE_LABEL // JNLE label // , JNLE_REL32_HINT // JNLE rel32, hint // , JNLE_LABEL_HINT // JNLE label, hint // , JNLE_REL8 // JNLE rel8 // , JNLE_REL8_HINT // JNLE rel8, hint // , JNO_REL32 // JNO rel32 // , JNO_LABEL // JNO label // , JNO_REL32_HINT // JNO rel32, hint // , JNO_LABEL_HINT // JNO label, hint // , JNO_REL8 // JNO rel8 // , JNO_REL8_HINT // JNO rel8, hint // , JNP_REL32 // JNP rel32 // , JNP_LABEL // JNP label // , JNP_REL32_HINT // JNP rel32, hint // , JNP_LABEL_HINT // JNP label, hint // , JNP_REL8 // JNP rel8 // , JNP_REL8_HINT // JNP rel8, hint // , JNS_REL32 // JNS rel32 // , JNS_LABEL // JNS label // , JNS_REL32_HINT // JNS rel32, hint // , JNS_LABEL_HINT // JNS label, hint // , JNS_REL8 // JNS rel8 // , JNS_REL8_HINT // JNS rel8, hint // , JNZ_REL32 // JNZ rel32 // , JNZ_LABEL // JNZ label // , JNZ_REL32_HINT // JNZ rel32, hint // , JNZ_LABEL_HINT // JNZ label, hint // , JNZ_REL8 // JNZ rel8 // , JNZ_REL8_HINT // JNZ rel8, hint // , JO_REL32 // JO rel32 // , JO_LABEL // JO label // , JO_REL32_HINT // JO rel32, hint // , JO_LABEL_HINT // JO label, hint // , JO_REL8 // JO rel8 // , JO_REL8_HINT // JO rel8, hint // , JP_REL32 // JP rel32 // , JP_LABEL // JP label // , JP_REL32_HINT // JP rel32, hint // , JP_LABEL_HINT // JP label, hint // , JP_REL8 // JP rel8 // , JP_REL8_HINT // JP rel8, hint // , JPE_REL32 // JPE rel32 // , JPE_LABEL // JPE label // , JPE_REL32_HINT // JPE rel32, hint // , JPE_LABEL_HINT // JPE label, hint // , JPE_REL8 // JPE rel8 // , JPE_REL8_HINT // JPE rel8, hint // , JPO_REL32 // JPO rel32 // , JPO_LABEL // JPO label // , JPO_REL32_HINT // JPO rel32, hint // , JPO_LABEL_HINT // JPO label, hint // , JPO_REL8 // JPO rel8 // , JPO_REL8_HINT // JPO rel8, hint // , JRCXZ_REL8 // JRCXZ rel8 // , JRCXZ_REL8_HINT // JRCXZ rel8, hint // , JS_REL32 // JS rel32 // , JS_LABEL // JS label // , JS_REL32_HINT // JS rel32, hint // , JS_LABEL_HINT // JS label, hint // , JS_REL8 // JS rel8 // , JS_REL8_HINT // JS rel8, hint // , JZ_REL32 // JZ rel32 // , JZ_LABEL // JZ label // , JZ_REL32_HINT // JZ rel32, hint // , JZ_LABEL_HINT // JZ label, hint // , JZ_REL8 // JZ rel8 // , JZ_REL8_HINT // JZ rel8, hint // , LAHF // LAHF // , LAR_R16_M16 // LAR r16, m16 // , LAR_R16_R16 // LAR r16, r16 // , LAR_R32_M16 // LAR r32, m16 // , LAR_R32_R32 // LAR r32, r32 // , LAR_R64_M16 // LAR r64, m16 // , LAR_R64_R32 // LAR r64, r32 // , LDDQU_XMM_M128 // LDDQU xmm, m128 // , LDMXCSR_M32 // LDMXCSR m32 // , LEA_R16_M16 // LEA r16, m16 // , LEA_R16_M32 // LEA r16, m32 // , LEA_R16_M64 // LEA r16, m64 // , LEA_R32_M16 // LEA r32, m16 // , LEA_R32_M32 // LEA r32, m32 // , LEA_R32_M64 // LEA r32, m64 // , LEA_R64_M16 // LEA r64, m16 // , LEA_R64_M32 // LEA r64, m32 // , LEA_R64_M64 // LEA r64, m64 // , LEAVE // LEAVE // , LEAVE_PREF66 // LEAVE p66 // , LFENCE // LFENCE // , LFS_R16_FARPTR1616 // LFS r16, m16:16 // , LFS_R32_FARPTR1632 // LFS r32, m16:32 // , LFS_R64_FARPTR1664 // LFS r64, m16:64 // , LGS_R16_FARPTR1616 // LGS r16, m16:16 // , LGS_R32_FARPTR1632 // LGS r32, m16:32 // , LGS_R64_FARPTR1664 // LGS r64, m16:64 // , LOCK // LOCK // , LODS_M16 // LODS m16 // , LODS_M32 // LODS m32 // , LODS_M64 // LODS m64 // , LODS_M8 // LODS m8 // , LODSB // LODSB // , LODSD // LODSD // , LODSQ // LODSQ // , LODSW // LODSW // , LOOP_REL8 // LOOP rel8 // , LOOPE_REL8 // LOOPE rel8 // , LOOPNE_REL8 // LOOPNE rel8 // , LSL_R16_M16 // LSL r16, m16 // , LSL_R16_R16 // LSL r16, r16 // , LSL_R32_M16 // LSL r32, m16 // , LSL_R32_R32 // LSL r32, r32 // , LSL_R64_M16 // LSL r64, m16 // , LSL_R64_R32 // LSL r64, r32 // , LSS_R16_FARPTR1616 // LSS r16, m16:16 // , LSS_R32_FARPTR1632 // LSS r32, m16:32 // , LSS_R64_FARPTR1664 // LSS r64, m16:64 // , LZCNT_R16_M16 // LZCNT r16, m16 // , LZCNT_R16_R16 // LZCNT r16, r16 // , LZCNT_R32_M32 // LZCNT r32, m32 // , LZCNT_R32_R32 // LZCNT r32, r32 // , LZCNT_R64_M64 // LZCNT r64, m64 // , LZCNT_R64_R64 // LZCNT r64, r64 // , MASKMOVDQU_XMM_XMM // MASKMOVDQU xmm, xmm // , MASKMOVQ_MM_MM // MASKMOVQ mm, mm // , MAXPD_XMM_M128 // MAXPD xmm, m128 // , MAXPD_XMM_XMM // MAXPD xmm, xmm // , MAXPS_XMM_M128 // MAXPS xmm, m128 // , MAXPS_XMM_XMM // MAXPS xmm, xmm // , MAXSD_XMM_M64 // MAXSD xmm, m64 // , MAXSD_XMM_XMM // MAXSD xmm, xmm // , MAXSS_XMM_M32 // MAXSS xmm, m32 // , MAXSS_XMM_XMM // MAXSS xmm, xmm // , MFENCE // MFENCE // , MINPD_XMM_M128 // MINPD xmm, m128 // , MINPD_XMM_XMM // MINPD xmm, xmm // , MINPS_XMM_M128 // MINPS xmm, m128 // , MINPS_XMM_XMM // MINPS xmm, xmm // , MINSD_XMM_M64 // MINSD xmm, m64 // , MINSD_XMM_XMM // MINSD xmm, xmm // , MINSS_XMM_M32 // MINSS xmm, m32 // , MINSS_XMM_XMM // MINSS xmm, xmm // , MONITOR // MONITOR // , MOV_AL_MOFFS8 // MOV AL, moffs8 // , MOV_AL_MOFFS8_PREFREXW // MOV AL, moffs8, pw // , MOV_AX_MOFFS16 // MOV AX, moffs16 // , MOV_EAX_MOFFS32 // MOV EAX, moffs32 // , MOV_M16_IMM16 // MOV m16, imm16 // , MOV_M16_R16 // MOV m16, r16 // , MOV_M16_SREG // MOV m16, Sreg // , MOV_M32_IMM32 // MOV m32, imm32 // , MOV_M32_R32 // MOV m32, r32 // , MOV_M64_IMM32 // MOV m64, imm32 // , MOV_M64_R64 // MOV m64, r64 // , MOV_M64_SREG // MOV m64, Sreg // , MOV_M8_IMM8 // MOV m8, imm8 // , MOV_M8_R8 // MOV m8, r8 // , MOV_M8_RH // MOV m8, rh // , MOV_MOFFS16_AX // MOV moffs16, AX // , MOV_MOFFS32_EAX // MOV moffs32, EAX // , MOV_MOFFS64_RAX // MOV moffs64, RAX // , MOV_MOFFS8_AL // MOV moffs8, AL // , MOV_MOFFS8_AL_PREFREXW // MOV moffs8, AL, pw // , MOV_R16_IMM16 // MOV r16, imm16 // , MOV_R16_M16 // MOV r16, m16 // , MOV_R16_R16 // MOV r16, r16 // , MOV_R16_SREG // MOV r16, Sreg // , MOV_R32_IMM32 // MOV r32, imm32 // , MOV_R32_M32 // MOV r32, m32 // , MOV_R32_R32 // MOV r32, r32 // , MOV_R64_IMM32 // MOV r64, imm32 , MOV_R64_IMM64 // MOV r64, imm64 // , MOV_R64_M64 // MOV r64, m64 , MOV_R64_R64 // MOV r64, r64 // , MOV_R64_SREG // MOV r64, Sreg // , MOV_R8_IMM8 // MOV r8, imm8 // , MOV_R8_M8 // MOV r8, m8 // , MOV_R8_R8 // MOV r8, r8 , MOV_R8_RH // MOV r8, rh // , MOV_RAX_MOFFS64 // MOV RAX, moffs64 // , MOV_RH_IMM8 // MOV rh, imm8 // , MOV_RH_M8 // MOV rh, m8 , MOV_RH_R8 // MOV rh, r8 // , MOV_RH_RH // MOV rh, rh // , MOV_SREG_M16 // MOV Sreg, m16 // , MOV_SREG_M64 // MOV Sreg, m64 // , MOV_SREG_R16 // MOV Sreg, r16 // , MOV_SREG_R64 // MOV Sreg, r64 // , MOVAPD_M128_XMM // MOVAPD m128, xmm // , MOVAPD_XMM_M128 // MOVAPD xmm, m128 // , MOVAPD_XMM_XMM // MOVAPD xmm, xmm // , MOVAPS_M128_XMM // MOVAPS m128, xmm // , MOVAPS_XMM_M128 // MOVAPS xmm, m128 // , MOVAPS_XMM_XMM // MOVAPS xmm, xmm // , MOVBE_M16_R16 // MOVBE m16, r16 // , MOVBE_M32_R32 // MOVBE m32, r32 // , MOVBE_M64_R64 // MOVBE m64, r64 // , MOVBE_R16_M16 // MOVBE r16, m16 // , MOVBE_R32_M32 // MOVBE r32, m32 // , MOVBE_R64_M64 // MOVBE r64, m64 // , MOVD_M32_MM // MOVD m32, mm // , MOVD_M32_XMM // MOVD m32, xmm // , MOVD_MM_M32 // MOVD mm, m32 // , MOVD_MM_R32 // MOVD mm, r32 // , MOVD_R32_MM // MOVD r32, mm // , MOVD_R32_XMM // MOVD r32, xmm // , MOVD_XMM_M32 // MOVD xmm, m32 // , MOVD_XMM_R32 // MOVD xmm, r32 // , MOVDDUP_XMM_M64 // MOVDDUP xmm, m64 // , MOVDDUP_XMM_XMM // MOVDDUP xmm, xmm // , MOVDQ2Q_MM_XMM // MOVDQ2Q mm, xmm // , MOVDQA_M128_XMM // MOVDQA m128, xmm // , MOVDQA_XMM_M128 // MOVDQA xmm, m128 // , MOVDQA_XMM_XMM // MOVDQA xmm, xmm // , MOVDQU_M128_XMM // MOVDQU m128, xmm // , MOVDQU_XMM_M128 // MOVDQU xmm, m128 // , MOVDQU_XMM_XMM // MOVDQU xmm, xmm // , MOVHLPS_XMM_XMM // MOVHLPS xmm, xmm // , MOVHPD_M64_XMM // MOVHPD m64, xmm // , MOVHPD_XMM_M64 // MOVHPD xmm, m64 // , MOVHPS_M64_XMM // MOVHPS m64, xmm // , MOVHPS_XMM_M64 // MOVHPS xmm, m64 // , MOVLHPS_XMM_XMM // MOVLHPS xmm, xmm // , MOVLPD_M64_XMM // MOVLPD m64, xmm // , MOVLPD_XMM_M64 // MOVLPD xmm, m64 // , MOVLPS_M64_XMM // MOVLPS m64, xmm // , MOVLPS_XMM_M64 // MOVLPS xmm, m64 // , MOVMSKPD_R32_XMM // MOVMSKPD r32, xmm // , MOVMSKPD_R64_XMM // MOVMSKPD r64, xmm // , MOVMSKPS_R32_XMM // MOVMSKPS r32, xmm // , MOVMSKPS_R64_XMM // MOVMSKPS r64, xmm // , MOVNTDQ_M128_XMM // MOVNTDQ m128, xmm // , MOVNTDQ_M256_YMM // MOVNTDQ m256, ymm // , MOVNTDQA_XMM_M128 // MOVNTDQA xmm, m128 // , MOVNTI_M32_R32 // MOVNTI m32, r32 // , MOVNTI_M64_R64 // MOVNTI m64, r64 // , MOVNTPD_M128_XMM // MOVNTPD m128, xmm // , MOVNTPS_M128_XMM // MOVNTPS m128, xmm // , MOVNTQ_M64_MM // MOVNTQ m64, mm // , MOVQ_M64_MM // MOVQ m64, mm // , MOVQ_M64_XMM // MOVQ m64, xmm // , MOVQ_MM_M64 // MOVQ mm, m64 // , MOVQ_MM_MM // MOVQ mm, mm // , MOVQ_MM_R64 // MOVQ mm, r64 // , MOVQ_R64_MM // MOVQ r64, mm // , MOVQ_R64_XMM // MOVQ r64, xmm // , MOVQ_XMM_M64 // MOVQ xmm, m64 // , MOVQ_XMM_R64 // MOVQ xmm, r64 // , MOVQ_XMM_XMM // MOVQ xmm, xmm // , MOVQ2DQ_XMM_MM // MOVQ2DQ xmm, mm // , MOVS_M16_M16 // MOVS m16, m16 // , MOVS_M32_M32 // MOVS m32, m32 // , MOVS_M64_M64 // MOVS m64, m64 // , MOVS_M8_M8 // MOVS m8, m8 // , MOVSB // MOVSB // , MOVSD // MOVSD // , MOVSD_M64_XMM // MOVSD m64, xmm // , MOVSD_XMM_M64 // MOVSD xmm, m64 // , MOVSD_XMM_XMM // MOVSD xmm, xmm // , MOVSHDUP_XMM_M128 // MOVSHDUP xmm, m128 // , MOVSHDUP_XMM_XMM // MOVSHDUP xmm, xmm // , MOVSLDUP_XMM_M128 // MOVSLDUP xmm, m128 // , MOVSLDUP_XMM_XMM // MOVSLDUP xmm, xmm // , MOVSQ // MOVSQ // , MOVSS_M32_XMM // MOVSS m32, xmm // , MOVSS_XMM_M32 // MOVSS xmm, m32 // , MOVSS_XMM_XMM // MOVSS xmm, xmm // , MOVSW // MOVSW // , MOVSX_R16_M8 // MOVSX r16, m8 // , MOVSX_R16_R8 // MOVSX r16, r8 // , MOVSX_R16_RH // MOVSX r16, rh // , MOVSX_R32_M16 // MOVSX r32, m16 // , MOVSX_R32_M8 // MOVSX r32, m8 // , MOVSX_R32_R16 // MOVSX r32, r16 // , MOVSX_R32_R8 // MOVSX r32, r8 // , MOVSX_R32_RH // MOVSX r32, rh // , MOVSX_R64_M16 // MOVSX r64, m16 // , MOVSX_R64_M8 // MOVSX r64, m8 , MOVSX_R64_R16 // MOVSX r64, r16 , MOVSX_R64_R8 // MOVSX r64, r8 // , MOVSX_R64_RH // MOVSX r64, rh // , MOVSXD_R64_M32 // MOVSXD r64, m32 , MOVSXD_R64_R32 // MOVSXD r64, r32 // , MOVUPD_M128_XMM // MOVUPD m128, xmm // , MOVUPD_XMM_M128 // MOVUPD xmm, m128 // , MOVUPD_XMM_XMM // MOVUPD xmm, xmm // , MOVUPS_M128_XMM // MOVUPS m128, xmm // , MOVUPS_XMM_M128 // MOVUPS xmm, m128 // , MOVUPS_XMM_XMM // MOVUPS xmm, xmm // , MOVZX_R16_M8 // MOVZX r16, m8 // , MOVZX_R16_R8 // MOVZX r16, r8 // , MOVZX_R16_RH // MOVZX r16, rh // , MOVZX_R32_M16 // MOVZX r32, m16 // , MOVZX_R32_M8 // MOVZX r32, m8 // , MOVZX_R32_R16 // MOVZX r32, r16 // , MOVZX_R32_R8 // MOVZX r32, r8 // , MOVZX_R32_RH // MOVZX r32, rh // , MOVZX_R64_M16 // MOVZX r64, m16 // , MOVZX_R64_M8 // MOVZX r64, m8 // , MOVZX_R64_R16 // MOVZX r64, r16 // , MOVZX_R64_R8 // MOVZX r64, r8 // , MOVZX_R64_RH // MOVZX r64, rh // , MPSADBW_XMM_M128_IMM8 // MPSADBW xmm, m128, imm8 // , MPSADBW_XMM_XMM_IMM8 // MPSADBW xmm, xmm, imm8 // , MUL_M16 // MUL m16 // , MUL_M32 // MUL m32 // , MUL_M64 // MUL m64 // , MUL_M8 // MUL m8 // , MUL_R16 // MUL r16 // , MUL_R32 // MUL r32 // , MUL_R64 // MUL r64 // , MUL_R8 // MUL r8 // , MUL_RH // MUL rh // , MULPD_XMM_M128 // MULPD xmm, m128 // , MULPD_XMM_XMM // MULPD xmm, xmm // , MULPS_XMM_M128 // MULPS xmm, m128 // , MULPS_XMM_XMM // MULPS xmm, xmm // , MULSD_XMM_M64 // MULSD xmm, m64 // , MULSD_XMM_XMM // MULSD xmm, xmm // , MULSS_XMM_M32 // MULSS xmm, m32 // , MULSS_XMM_XMM // MULSS xmm, xmm // , MULX_R32_R32_M32 // MULX r32, r32, m32 // , MULX_R32_R32_R32 // MULX r32, r32, r32 // , MULX_R64_R64_M64 // MULX r64, r64, m64 // , MULX_R64_R64_R64 // MULX r64, r64, r64 // , MWAIT // MWAIT // , NEG_M16 // NEG m16 // , NEG_M32 // NEG m32 // , NEG_M64 // NEG m64 // , NEG_M8 // NEG m8 // , NEG_R16 // NEG r16 // , NEG_R32 // NEG r32 // , NEG_R64 // NEG r64 // , NEG_R8 // NEG r8 // , NEG_RH // NEG rh // , NOP // NOP // , NOP_M16 // NOP m16 // , NOP_M32 // NOP m32 // , NOP_R16 // NOP r16 // , NOP_R32 // NOP r32 // , NOT_M16 // NOT m16 // , NOT_M32 // NOT m32 // , NOT_M64 // NOT m64 // , NOT_M8 // NOT m8 // , NOT_R16 // NOT r16 // , NOT_R32 // NOT r32 // , NOT_R64 // NOT r64 // , NOT_R8 // NOT r8 // , NOT_RH // NOT rh // , OR_AL_IMM8 // OR AL, imm8 // , OR_AX_IMM16 // OR AX, imm16 // , OR_EAX_IMM32 // OR EAX, imm32 // , OR_M16_IMM16 // OR m16, imm16 // , OR_M16_IMM8 // OR m16, imm8 // , OR_M16_R16 // OR m16, r16 // , OR_M32_IMM32 // OR m32, imm32 // , OR_M32_IMM8 // OR m32, imm8 // , OR_M32_R32 // OR m32, r32 // , OR_M64_IMM32 // OR m64, imm32 // , OR_M64_IMM8 // OR m64, imm8 // , OR_M64_R64 // OR m64, r64 // , OR_M8_IMM8 // OR m8, imm8 // , OR_M8_R8 // OR m8, r8 // , OR_M8_RH // OR m8, rh // , OR_R16_IMM16 // OR r16, imm16 // , OR_R16_IMM8 // OR r16, imm8 // , OR_R16_M16 // OR r16, m16 // , OR_R16_R16 // OR r16, r16 // , OR_R32_IMM32 // OR r32, imm32 // , OR_R32_IMM8 // OR r32, imm8 // , OR_R32_M32 // OR r32, m32 // , OR_R32_R32 // OR r32, r32 // , OR_R64_IMM32 // OR r64, imm32 // , OR_R64_IMM8 // OR r64, imm8 // , OR_R64_M64 // OR r64, m64 , OR_R64_R64 // OR r64, r64 // , OR_R8_IMM8 // OR r8, imm8 // , OR_R8_M8 // OR r8, m8 // , OR_R8_R8 // OR r8, r8 // , OR_R8_RH // OR r8, rh // , OR_RAX_IMM32 // OR RAX, imm32 // , OR_RH_IMM8 // OR rh, imm8 // , OR_RH_M8 // OR rh, m8 // , OR_RH_R8 // OR rh, r8 // , OR_RH_RH // OR rh, rh // , ORPD_XMM_M128 // ORPD xmm, m128 // , ORPD_XMM_XMM // ORPD xmm, xmm // , ORPS_XMM_M128 // ORPS xmm, m128 // , ORPS_XMM_XMM // ORPS xmm, xmm // , OUT_DX_AL // OUT DX, AL // , OUT_DX_AX // OUT DX, AX // , OUT_DX_EAX // OUT DX, EAX // , OUT_IMM8_AL // OUT imm8, AL // , OUT_IMM8_AX // OUT imm8, AX // , OUT_IMM8_EAX // OUT imm8, EAX // , OUTS_DX_M16 // OUTS DX, m16 // , OUTS_DX_M32 // OUTS DX, m32 // , OUTS_DX_M8 // OUTS DX, m8 // , OUTSB // OUTSB // , OUTSD // OUTSD // , OUTSW // OUTSW // , PABSB_MM_M64 // PABSB mm, m64 // , PABSB_MM_MM // PABSB mm, mm // , PABSB_XMM_M128 // PABSB xmm, m128 // , PABSB_XMM_XMM // PABSB xmm, xmm // , PABSD_MM_M64 // PABSD mm, m64 // , PABSD_MM_MM // PABSD mm, mm // , PABSD_XMM_M128 // PABSD xmm, m128 // , PABSD_XMM_XMM // PABSD xmm, xmm // , PABSW_MM_M64 // PABSW mm, m64 // , PABSW_MM_MM // PABSW mm, mm // , PABSW_XMM_M128 // PABSW xmm, m128 // , PABSW_XMM_XMM // PABSW xmm, xmm // , PACKSSDW_MM_M64 // PACKSSDW mm, m64 // , PACKSSDW_MM_MM // PACKSSDW mm, mm // , PACKSSDW_XMM_M128 // PACKSSDW xmm, m128 // , PACKSSDW_XMM_XMM // PACKSSDW xmm, xmm // , PACKSSWB_MM_M64 // PACKSSWB mm, m64 // , PACKSSWB_MM_MM // PACKSSWB mm, mm // , PACKSSWB_XMM_M128 // PACKSSWB xmm, m128 // , PACKSSWB_XMM_XMM // PACKSSWB xmm, xmm // , PACKUSDW_XMM_M128 // PACKUSDW xmm, m128 // , PACKUSDW_XMM_XMM // PACKUSDW xmm, xmm // , PACKUSWB_MM_M64 // PACKUSWB mm, m64 // , PACKUSWB_MM_MM // PACKUSWB mm, mm // , PACKUSWB_XMM_M128 // PACKUSWB xmm, m128 // , PACKUSWB_XMM_XMM // PACKUSWB xmm, xmm // , PADDB_MM_M64 // PADDB mm, m64 // , PADDB_MM_MM // PADDB mm, mm // , PADDB_XMM_M128 // PADDB xmm, m128 // , PADDB_XMM_XMM // PADDB xmm, xmm // , PADDD_MM_M64 // PADDD mm, m64 // , PADDD_MM_MM // PADDD mm, mm // , PADDD_XMM_M128 // PADDD xmm, m128 // , PADDD_XMM_XMM // PADDD xmm, xmm // , PADDQ_MM_M64 // PADDQ mm, m64 // , PADDQ_MM_MM // PADDQ mm, mm // , PADDQ_XMM_M128 // PADDQ xmm, m128 // , PADDQ_XMM_XMM // PADDQ xmm, xmm // , PADDSB_MM_M64 // PADDSB mm, m64 // , PADDSB_MM_MM // PADDSB mm, mm // , PADDSB_XMM_M128 // PADDSB xmm, m128 // , PADDSB_XMM_XMM // PADDSB xmm, xmm // , PADDSW_MM_M64 // PADDSW mm, m64 // , PADDSW_MM_MM // PADDSW mm, mm // , PADDSW_XMM_M128 // PADDSW xmm, m128 // , PADDSW_XMM_XMM // PADDSW xmm, xmm // , PADDUSB_MM_M64 // PADDUSB mm, m64 // , PADDUSB_MM_MM // PADDUSB mm, mm // , PADDUSB_XMM_M128 // PADDUSB xmm, m128 // , PADDUSB_XMM_XMM // PADDUSB xmm, xmm // , PADDUSW_MM_M64 // PADDUSW mm, m64 // , PADDUSW_MM_MM // PADDUSW mm, mm // , PADDUSW_XMM_M128 // PADDUSW xmm, m128 // , PADDUSW_XMM_XMM // PADDUSW xmm, xmm // , PADDW_MM_M64 // PADDW mm, m64 // , PADDW_MM_MM // PADDW mm, mm // , PADDW_XMM_M128 // PADDW xmm, m128 // , PADDW_XMM_XMM // PADDW xmm, xmm // , PALIGNR_MM_M64_IMM8 // PALIGNR mm, m64, imm8 // , PALIGNR_MM_MM_IMM8 // PALIGNR mm, mm, imm8 // , PALIGNR_XMM_M128_IMM8 // PALIGNR xmm, m128, imm8 // , PALIGNR_XMM_XMM_IMM8 // PALIGNR xmm, xmm, imm8 // , PAND_MM_M64 // PAND mm, m64 // , PAND_MM_MM // PAND mm, mm // , PAND_XMM_M128 // PAND xmm, m128 // , PAND_XMM_XMM // PAND xmm, xmm // , PANDN_MM_M64 // PANDN mm, m64 // , PANDN_MM_MM // PANDN mm, mm // , PANDN_XMM_M128 // PANDN xmm, m128 // , PANDN_XMM_XMM // PANDN xmm, xmm // , PAUSE // PAUSE // , PAVGB_MM_M64 // PAVGB mm, m64 // , PAVGB_MM_MM // PAVGB mm, mm // , PAVGB_XMM_M128 // PAVGB xmm, m128 // , PAVGB_XMM_XMM // PAVGB xmm, xmm // , PAVGW_MM_M64 // PAVGW mm, m64 // , PAVGW_MM_MM // PAVGW mm, mm // , PAVGW_XMM_M128 // PAVGW xmm, m128 // , PAVGW_XMM_XMM // PAVGW xmm, xmm // , PBLENDVB_XMM_M128_XMM0 // PBLENDVB xmm, m128, <XMM0> // , PBLENDVB_XMM_XMM_XMM0 // PBLENDVB xmm, xmm, <XMM0> // , PBLENDW_XMM_M128_IMM8 // PBLENDW xmm, m128, imm8 // , PBLENDW_XMM_XMM_IMM8 // PBLENDW xmm, xmm, imm8 // , PCLMULQDQ_XMM_M128_IMM8 // PCLMULQDQ xmm, m128, imm8 // , PCLMULQDQ_XMM_XMM_IMM8 // PCLMULQDQ xmm, xmm, imm8 // , PCMPEQB_MM_M64 // PCMPEQB mm, m64 // , PCMPEQB_MM_MM // PCMPEQB mm, mm // , PCMPEQB_XMM_M128 // PCMPEQB xmm, m128 // , PCMPEQB_XMM_XMM // PCMPEQB xmm, xmm // , PCMPEQD_MM_M64 // PCMPEQD mm, m64 // , PCMPEQD_MM_MM // PCMPEQD mm, mm // , PCMPEQD_XMM_M128 // PCMPEQD xmm, m128 // , PCMPEQD_XMM_XMM // PCMPEQD xmm, xmm // , PCMPEQQ_XMM_M128 // PCMPEQQ xmm, m128 // , PCMPEQQ_XMM_XMM // PCMPEQQ xmm, xmm // , PCMPEQW_MM_M64 // PCMPEQW mm, m64 // , PCMPEQW_MM_MM // PCMPEQW mm, mm // , PCMPEQW_XMM_M128 // PCMPEQW xmm, m128 // , PCMPEQW_XMM_XMM // PCMPEQW xmm, xmm // , PCMPESTRI_XMM_M128_IMM8 // PCMPESTRI xmm, m128, imm8 // , PCMPESTRI_XMM_XMM_IMM8 // PCMPESTRI xmm, xmm, imm8 // , PCMPESTRM_XMM_M128_IMM8 // PCMPESTRM xmm, m128, imm8 // , PCMPESTRM_XMM_XMM_IMM8 // PCMPESTRM xmm, xmm, imm8 // , PCMPGTB_MM_M64 // PCMPGTB mm, m64 // , PCMPGTB_MM_MM // PCMPGTB mm, mm // , PCMPGTB_XMM_M128 // PCMPGTB xmm, m128 // , PCMPGTB_XMM_XMM // PCMPGTB xmm, xmm // , PCMPGTD_MM_M64 // PCMPGTD mm, m64 // , PCMPGTD_MM_MM // PCMPGTD mm, mm // , PCMPGTD_XMM_M128 // PCMPGTD xmm, m128 // , PCMPGTD_XMM_XMM // PCMPGTD xmm, xmm // , PCMPGTQ_XMM_M128 // PCMPGTQ xmm, m128 // , PCMPGTQ_XMM_XMM // PCMPGTQ xmm, xmm // , PCMPGTW_MM_M64 // PCMPGTW mm, m64 // , PCMPGTW_MM_MM // PCMPGTW mm, mm // , PCMPGTW_XMM_M128 // PCMPGTW xmm, m128 // , PCMPGTW_XMM_XMM // PCMPGTW xmm, xmm // , PCMPISTRI_XMM_M128_IMM8 // PCMPISTRI xmm, m128, imm8 // , PCMPISTRI_XMM_XMM_IMM8 // PCMPISTRI xmm, xmm, imm8 // , PCMPISTRM_XMM_M128_IMM8 // PCMPISTRM xmm, m128, imm8 // , PCMPISTRM_XMM_XMM_IMM8 // PCMPISTRM xmm, xmm, imm8 // , PDEP_R32_R32_M32 // PDEP r32, r32, m32 // , PDEP_R32_R32_R32 // PDEP r32, r32, r32 // , PDEP_R64_R64_M64 // PDEP r64, r64, m64 // , PDEP_R64_R64_R64 // PDEP r64, r64, r64 // , PEXT_R32_R32_M32 // PEXT r32, r32, m32 // , PEXT_R32_R32_R32 // PEXT r32, r32, r32 // , PEXT_R64_R64_M64 // PEXT r64, r64, m64 // , PEXT_R64_R64_R64 // PEXT r64, r64, r64 // , PEXTRB_M8_XMM_IMM8 // PEXTRB m8, xmm, imm8 // , PEXTRB_R32_XMM_IMM8 // PEXTRB r32, xmm, imm8 // , PEXTRB_R64_XMM_IMM8 // PEXTRB r64, xmm, imm8 // , PEXTRD_M32_XMM_IMM8 // PEXTRD m32, xmm, imm8 // , PEXTRD_R32_XMM_IMM8 // PEXTRD r32, xmm, imm8 // , PEXTRQ_M64_XMM_IMM8 // PEXTRQ m64, xmm, imm8 // , PEXTRQ_R64_XMM_IMM8 // PEXTRQ r64, xmm, imm8 // , PEXTRW_M16_XMM_IMM8 // PEXTRW m16, xmm, imm8 // , PEXTRW_R32_MM_IMM8 // PEXTRW r32, mm, imm8 // , PEXTRW_R32_XMM_IMM8 // PEXTRW r32, xmm, imm8 // , PEXTRW_R64_MM_IMM8 // PEXTRW r64, mm, imm8 // , PEXTRW_R64_XMM_IMM8 // PEXTRW r64, xmm, imm8 // , PHADDD_MM_M64 // PHADDD mm, m64 // , PHADDD_MM_MM // PHADDD mm, mm // , PHADDD_XMM_M128 // PHADDD xmm, m128 // , PHADDD_XMM_XMM // PHADDD xmm, xmm // , PHADDSW_MM_M64 // PHADDSW mm, m64 // , PHADDSW_MM_MM // PHADDSW mm, mm // , PHADDSW_XMM_M128 // PHADDSW xmm, m128 // , PHADDSW_XMM_XMM // PHADDSW xmm, xmm // , PHADDW_MM_M64 // PHADDW mm, m64 // , PHADDW_MM_MM // PHADDW mm, mm // , PHADDW_XMM_M128 // PHADDW xmm, m128 // , PHADDW_XMM_XMM // PHADDW xmm, xmm // , PHMINPOSUW_XMM_M128 // PHMINPOSUW xmm, m128 // , PHMINPOSUW_XMM_XMM // PHMINPOSUW xmm, xmm // , PHSUBD_MM_M64 // PHSUBD mm, m64 // , PHSUBD_MM_MM // PHSUBD mm, mm // , PHSUBD_XMM_M128 // PHSUBD xmm, m128 // , PHSUBD_XMM_XMM // PHSUBD xmm, xmm // , PHSUBSW_MM_M64 // PHSUBSW mm, m64 // , PHSUBSW_MM_MM // PHSUBSW mm, mm // , PHSUBSW_XMM_M128 // PHSUBSW xmm, m128 // , PHSUBSW_XMM_XMM // PHSUBSW xmm, xmm // , PHSUBW_MM_M64 // PHSUBW mm, m64 // , PHSUBW_MM_MM // PHSUBW mm, mm // , PHSUBW_XMM_M128 // PHSUBW xmm, m128 // , PHSUBW_XMM_XMM // PHSUBW xmm, xmm // , PINSRB_XMM_M8_IMM8 // PINSRB xmm, m8, imm8 // , PINSRB_XMM_R32_IMM8 // PINSRB xmm, r32, imm8 // , PINSRD_XMM_M32_IMM8 // PINSRD xmm, m32, imm8 // , PINSRD_XMM_R32_IMM8 // PINSRD xmm, r32, imm8 // , PINSRW_MM_M16_IMM8 // PINSRW mm, m16, imm8 // , PINSRW_MM_R32_IMM8 // PINSRW mm, r32, imm8 // , PINSRW_XMM_M16_IMM8 // PINSRW xmm, m16, imm8 // , PINSRW_XMM_R32_IMM8 // PINSRW xmm, r32, imm8 // , PMADDUBSW_MM_M64 // PMADDUBSW mm, m64 // , PMADDUBSW_MM_MM // PMADDUBSW mm, mm // , PMADDUBSW_XMM_M128 // PMADDUBSW xmm, m128 // , PMADDUBSW_XMM_XMM // PMADDUBSW xmm, xmm // , PMADDWD_MM_M64 // PMADDWD mm, m64 // , PMADDWD_MM_MM // PMADDWD mm, mm // , PMADDWD_XMM_M128 // PMADDWD xmm, m128 // , PMADDWD_XMM_XMM // PMADDWD xmm, xmm // , PMAXSB_XMM_M128 // PMAXSB xmm, m128 // , PMAXSB_XMM_XMM // PMAXSB xmm, xmm // , PMAXSD_XMM_M128 // PMAXSD xmm, m128 // , PMAXSD_XMM_XMM // PMAXSD xmm, xmm // , PMAXSW_MM_M64 // PMAXSW mm, m64 // , PMAXSW_MM_MM // PMAXSW mm, mm // , PMAXSW_XMM_M128 // PMAXSW xmm, m128 // , PMAXSW_XMM_XMM // PMAXSW xmm, xmm // , PMAXUB_MM_M64 // PMAXUB mm, m64 // , PMAXUB_MM_MM // PMAXUB mm, mm // , PMAXUB_XMM_M128 // PMAXUB xmm, m128 // , PMAXUB_XMM_XMM // PMAXUB xmm, xmm // , PMAXUD_XMM_M128 // PMAXUD xmm, m128 // , PMAXUD_XMM_XMM // PMAXUD xmm, xmm // , PMAXUW_XMM_M128 // PMAXUW xmm, m128 // , PMAXUW_XMM_XMM // PMAXUW xmm, xmm // , PMINSB_XMM_M128 // PMINSB xmm, m128 // , PMINSB_XMM_XMM // PMINSB xmm, xmm // , PMINSD_XMM_M128 // PMINSD xmm, m128 // , PMINSD_XMM_XMM // PMINSD xmm, xmm // , PMINSW_MM_M64 // PMINSW mm, m64 // , PMINSW_MM_MM // PMINSW mm, mm // , PMINSW_XMM_M128 // PMINSW xmm, m128 // , PMINSW_XMM_XMM // PMINSW xmm, xmm // , PMINUB_MM_M64 // PMINUB mm, m64 // , PMINUB_MM_MM // PMINUB mm, mm // , PMINUB_XMM_M128 // PMINUB xmm, m128 // , PMINUB_XMM_XMM // PMINUB xmm, xmm // , PMINUD_XMM_M128 // PMINUD xmm, m128 // , PMINUD_XMM_XMM // PMINUD xmm, xmm // , PMINUW_XMM_M128 // PMINUW xmm, m128 // , PMINUW_XMM_XMM // PMINUW xmm, xmm // , PMOVMSKB_R32_MM // PMOVMSKB r32, mm // , PMOVMSKB_R32_XMM // PMOVMSKB r32, xmm // , PMOVMSKB_R64_MM // PMOVMSKB r64, mm // , PMOVMSKB_R64_XMM // PMOVMSKB r64, xmm // , PMOVSXBD_XMM_M32 // PMOVSXBD xmm, m32 // , PMOVSXBD_XMM_XMM // PMOVSXBD xmm, xmm // , PMOVSXBQ_XMM_M16 // PMOVSXBQ xmm, m16 // , PMOVSXBQ_XMM_XMM // PMOVSXBQ xmm, xmm // , PMOVSXBW_XMM_M64 // PMOVSXBW xmm, m64 // , PMOVSXBW_XMM_XMM // PMOVSXBW xmm, xmm // , PMOVSXDQ_XMM_M64 // PMOVSXDQ xmm, m64 // , PMOVSXDQ_XMM_XMM // PMOVSXDQ xmm, xmm // , PMOVSXWD_XMM_M64 // PMOVSXWD xmm, m64 // , PMOVSXWD_XMM_XMM // PMOVSXWD xmm, xmm // , PMOVSXWQ_XMM_M32 // PMOVSXWQ xmm, m32 // , PMOVSXWQ_XMM_XMM // PMOVSXWQ xmm, xmm // , PMOVZXBD_XMM_M32 // PMOVZXBD xmm, m32 // , PMOVZXBD_XMM_XMM // PMOVZXBD xmm, xmm // , PMOVZXBQ_XMM_M16 // PMOVZXBQ xmm, m16 // , PMOVZXBQ_XMM_XMM // PMOVZXBQ xmm, xmm // , PMOVZXBW_XMM_M64 // PMOVZXBW xmm, m64 // , PMOVZXBW_XMM_XMM // PMOVZXBW xmm, xmm // , PMOVZXDQ_XMM_M64 // PMOVZXDQ xmm, m64 // , PMOVZXDQ_XMM_XMM // PMOVZXDQ xmm, xmm // , PMOVZXWD_XMM_M64 // PMOVZXWD xmm, m64 // , PMOVZXWD_XMM_XMM // PMOVZXWD xmm, xmm // , PMOVZXWQ_XMM_M32 // PMOVZXWQ xmm, m32 // , PMOVZXWQ_XMM_XMM // PMOVZXWQ xmm, xmm // , PMULDQ_XMM_M128 // PMULDQ xmm, m128 // , PMULDQ_XMM_XMM // PMULDQ xmm, xmm // , PMULHRSW_MM_M64 // PMULHRSW mm, m64 // , PMULHRSW_MM_MM // PMULHRSW mm, mm // , PMULHRSW_XMM_M128 // PMULHRSW xmm, m128 // , PMULHRSW_XMM_XMM // PMULHRSW xmm, xmm // , PMULHUW_MM_M64 // PMULHUW mm, m64 // , PMULHUW_MM_MM // PMULHUW mm, mm // , PMULHUW_XMM_M128 // PMULHUW xmm, m128 // , PMULHUW_XMM_XMM // PMULHUW xmm, xmm // , PMULHW_MM_M64 // PMULHW mm, m64 // , PMULHW_MM_MM // PMULHW mm, mm // , PMULHW_XMM_M128 // PMULHW xmm, m128 // , PMULHW_XMM_XMM // PMULHW xmm, xmm // , PMULLD_XMM_M128 // PMULLD xmm, m128 // , PMULLD_XMM_XMM // PMULLD xmm, xmm // , PMULLW_MM_M64 // PMULLW mm, m64 // , PMULLW_MM_MM // PMULLW mm, mm // , PMULLW_XMM_M128 // PMULLW xmm, m128 // , PMULLW_XMM_XMM // PMULLW xmm, xmm // , PMULUDQ_MM_M64 // PMULUDQ mm, m64 // , PMULUDQ_MM_MM // PMULUDQ mm, mm // , PMULUDQ_XMM_M128 // PMULUDQ xmm, m128 // , PMULUDQ_XMM_XMM // PMULUDQ xmm, xmm // , POP_FS // POP FS // , POP_FS_PREF66 // POP FS, p66 // , POP_GS // POP GS // , POP_GS_PREF66 // POP GS, p66 // , POP_M16 // POP m16 // , POP_M64 // POP m64 // , POP_R16 // POP r16 // , POP_R64 // POP r64 // , POPCNT_R16_M16 // POPCNT r16, m16 // , POPCNT_R16_R16 // POPCNT r16, r16 // , POPCNT_R32_M32 // POPCNT r32, m32 // , POPCNT_R32_R32 // POPCNT r32, r32 // , POPCNT_R64_M64 // POPCNT r64, m64 , POPCNT_R64_R64 // POPCNT r64, r64 // , POPF // POPF // , POPFQ // POPFQ // , POR_MM_M64 // POR mm, m64 // , POR_MM_MM // POR mm, mm // , POR_XMM_M128 // POR xmm, m128 // , POR_XMM_XMM // POR xmm, xmm // , PREFETCHNTA_M8 // PREFETCHNTA m8 // , PREFETCHT0_M8 // PREFETCHT0 m8 // , PREFETCHT1_M8 // PREFETCHT1 m8 // , PREFETCHT2_M8 // PREFETCHT2 m8 // , PSADBW_MM_M64 // PSADBW mm, m64 // , PSADBW_MM_MM // PSADBW mm, mm // , PSADBW_XMM_M128 // PSADBW xmm, m128 // , PSADBW_XMM_XMM // PSADBW xmm, xmm // , PSHUFB_MM_M64 // PSHUFB mm, m64 // , PSHUFB_MM_MM // PSHUFB mm, mm // , PSHUFB_XMM_M128 // PSHUFB xmm, m128 // , PSHUFB_XMM_XMM // PSHUFB xmm, xmm // , PSHUFD_XMM_M128_IMM8 // PSHUFD xmm, m128, imm8 // , PSHUFD_XMM_XMM_IMM8 // PSHUFD xmm, xmm, imm8 // , PSHUFHW_XMM_M128_IMM8 // PSHUFHW xmm, m128, imm8 // , PSHUFHW_XMM_XMM_IMM8 // PSHUFHW xmm, xmm, imm8 // , PSHUFLW_XMM_M128_IMM8 // PSHUFLW xmm, m128, imm8 // , PSHUFLW_XMM_XMM_IMM8 // PSHUFLW xmm, xmm, imm8 // , PSHUFW_MM_M64_IMM8 // PSHUFW mm, m64, imm8 // , PSHUFW_MM_MM_IMM8 // PSHUFW mm, mm, imm8 // , PSIGNB_MM_M64 // PSIGNB mm, m64 // , PSIGNB_MM_MM // PSIGNB mm, mm // , PSIGNB_XMM_M128 // PSIGNB xmm, m128 // , PSIGNB_XMM_XMM // PSIGNB xmm, xmm // , PSIGND_MM_M64 // PSIGND mm, m64 // , PSIGND_MM_MM // PSIGND mm, mm // , PSIGND_XMM_M128 // PSIGND xmm, m128 // , PSIGND_XMM_XMM // PSIGND xmm, xmm // , PSIGNW_MM_M64 // PSIGNW mm, m64 // , PSIGNW_MM_MM // PSIGNW mm, mm // , PSIGNW_XMM_M128 // PSIGNW xmm, m128 // , PSIGNW_XMM_XMM // PSIGNW xmm, xmm // , PSLLD_MM_IMM8 // PSLLD mm, imm8 // , PSLLD_MM_M64 // PSLLD mm, m64 // , PSLLD_MM_MM // PSLLD mm, mm // , PSLLD_XMM_IMM8 // PSLLD xmm, imm8 // , PSLLD_XMM_M128 // PSLLD xmm, m128 // , PSLLD_XMM_XMM // PSLLD xmm, xmm // , PSLLDQ_XMM_IMM8 // PSLLDQ xmm, imm8 // , PSLLQ_MM_IMM8 // PSLLQ mm, imm8 // , PSLLQ_MM_M64 // PSLLQ mm, m64 // , PSLLQ_MM_MM // PSLLQ mm, mm // , PSLLQ_XMM_IMM8 // PSLLQ xmm, imm8 // , PSLLQ_XMM_M128 // PSLLQ xmm, m128 // , PSLLQ_XMM_XMM // PSLLQ xmm, xmm // , PSLLW_MM_IMM8 // PSLLW mm, imm8 // , PSLLW_MM_M64 // PSLLW mm, m64 // , PSLLW_MM_MM // PSLLW mm, mm // , PSLLW_XMM_IMM8 // PSLLW xmm, imm8 // , PSLLW_XMM_M128 // PSLLW xmm, m128 // , PSLLW_XMM_XMM // PSLLW xmm, xmm // , PSRAD_MM_IMM8 // PSRAD mm, imm8 // , PSRAD_MM_M64 // PSRAD mm, m64 // , PSRAD_MM_MM // PSRAD mm, mm // , PSRAD_XMM_IMM8 // PSRAD xmm, imm8 // , PSRAD_XMM_M128 // PSRAD xmm, m128 // , PSRAD_XMM_XMM // PSRAD xmm, xmm // , PSRAW_MM_IMM8 // PSRAW mm, imm8 // , PSRAW_MM_M64 // PSRAW mm, m64 // , PSRAW_MM_MM // PSRAW mm, mm // , PSRAW_XMM_IMM8 // PSRAW xmm, imm8 // , PSRAW_XMM_M128 // PSRAW xmm, m128 // , PSRAW_XMM_XMM // PSRAW xmm, xmm // , PSRLD_MM_IMM8 // PSRLD mm, imm8 // , PSRLD_MM_M64 // PSRLD mm, m64 // , PSRLD_MM_MM // PSRLD mm, mm // , PSRLD_XMM_IMM8 // PSRLD xmm, imm8 // , PSRLD_XMM_M128 // PSRLD xmm, m128 // , PSRLD_XMM_XMM // PSRLD xmm, xmm // , PSRLDQ_XMM_IMM8 // PSRLDQ xmm, imm8 // , PSRLQ_MM_IMM8 // PSRLQ mm, imm8 // , PSRLQ_MM_M64 // PSRLQ mm, m64 // , PSRLQ_MM_MM // PSRLQ mm, mm // , PSRLQ_XMM_IMM8 // PSRLQ xmm, imm8 // , PSRLQ_XMM_M128 // PSRLQ xmm, m128 // , PSRLQ_XMM_XMM // PSRLQ xmm, xmm // , PSRLW_MM_IMM8 // PSRLW mm, imm8 // , PSRLW_MM_M64 // PSRLW mm, m64 // , PSRLW_MM_MM // PSRLW mm, mm // , PSRLW_XMM_IMM8 // PSRLW xmm, imm8 // , PSRLW_XMM_M128 // PSRLW xmm, m128 // , PSRLW_XMM_XMM // PSRLW xmm, xmm // , PSUBB_MM_M64 // PSUBB mm, m64 // , PSUBB_MM_MM // PSUBB mm, mm // , PSUBB_XMM_M128 // PSUBB xmm, m128 // , PSUBB_XMM_XMM // PSUBB xmm, xmm // , PSUBD_MM_M64 // PSUBD mm, m64 // , PSUBD_MM_MM // PSUBD mm, mm // , PSUBD_XMM_M128 // PSUBD xmm, m128 // , PSUBD_XMM_XMM // PSUBD xmm, xmm // , PSUBQ_MM_M64 // PSUBQ mm, m64 // , PSUBQ_MM_MM // PSUBQ mm, mm // , PSUBQ_XMM_M128 // PSUBQ xmm, m128 // , PSUBQ_XMM_XMM // PSUBQ xmm, xmm // , PSUBSB_MM_M64 // PSUBSB mm, m64 // , PSUBSB_MM_MM // PSUBSB mm, mm // , PSUBSB_XMM_M128 // PSUBSB xmm, m128 // , PSUBSB_XMM_XMM // PSUBSB xmm, xmm // , PSUBSW_MM_M64 // PSUBSW mm, m64 // , PSUBSW_MM_MM // PSUBSW mm, mm // , PSUBSW_XMM_M128 // PSUBSW xmm, m128 // , PSUBSW_XMM_XMM // PSUBSW xmm, xmm // , PSUBUSB_MM_M64 // PSUBUSB mm, m64 // , PSUBUSB_MM_MM // PSUBUSB mm, mm // , PSUBUSB_XMM_M128 // PSUBUSB xmm, m128 // , PSUBUSB_XMM_XMM // PSUBUSB xmm, xmm // , PSUBUSW_MM_M64 // PSUBUSW mm, m64 // , PSUBUSW_MM_MM // PSUBUSW mm, mm // , PSUBUSW_XMM_M128 // PSUBUSW xmm, m128 // , PSUBUSW_XMM_XMM // PSUBUSW xmm, xmm // , PSUBW_MM_M64 // PSUBW mm, m64 // , PSUBW_MM_MM // PSUBW mm, mm // , PSUBW_XMM_M128 // PSUBW xmm, m128 // , PSUBW_XMM_XMM // PSUBW xmm, xmm // , PTEST_XMM_M128 // PTEST xmm, m128 // , PTEST_XMM_XMM // PTEST xmm, xmm // , PUNPCKHBW_MM_M64 // PUNPCKHBW mm, m64 // , PUNPCKHBW_MM_MM // PUNPCKHBW mm, mm // , PUNPCKHBW_XMM_M128 // PUNPCKHBW xmm, m128 // , PUNPCKHBW_XMM_XMM // PUNPCKHBW xmm, xmm // , PUNPCKHDQ_MM_M64 // PUNPCKHDQ mm, m64 // , PUNPCKHDQ_MM_MM // PUNPCKHDQ mm, mm // , PUNPCKHDQ_XMM_M128 // PUNPCKHDQ xmm, m128 // , PUNPCKHDQ_XMM_XMM // PUNPCKHDQ xmm, xmm // , PUNPCKHQDQ_XMM_M128 // PUNPCKHQDQ xmm, m128 // , PUNPCKHQDQ_XMM_XMM // PUNPCKHQDQ xmm, xmm // , PUNPCKHWD_MM_M64 // PUNPCKHWD mm, m64 // , PUNPCKHWD_MM_MM // PUNPCKHWD mm, mm // , PUNPCKHWD_XMM_M128 // PUNPCKHWD xmm, m128 // , PUNPCKHWD_XMM_XMM // PUNPCKHWD xmm, xmm // , PUNPCKLBW_MM_M32 // PUNPCKLBW mm, m32 // , PUNPCKLBW_MM_MM // PUNPCKLBW mm, mm // , PUNPCKLBW_XMM_M128 // PUNPCKLBW xmm, m128 // , PUNPCKLBW_XMM_XMM // PUNPCKLBW xmm, xmm // , PUNPCKLDQ_MM_M32 // PUNPCKLDQ mm, m32 // , PUNPCKLDQ_MM_MM // PUNPCKLDQ mm, mm // , PUNPCKLDQ_XMM_M128 // PUNPCKLDQ xmm, m128 // , PUNPCKLDQ_XMM_XMM // PUNPCKLDQ xmm, xmm // , PUNPCKLQDQ_XMM_M128 // PUNPCKLQDQ xmm, m128 // , PUNPCKLQDQ_XMM_XMM // PUNPCKLQDQ xmm, xmm // , PUNPCKLWD_MM_M32 // PUNPCKLWD mm, m32 // , PUNPCKLWD_MM_MM // PUNPCKLWD mm, mm // , PUNPCKLWD_XMM_M128 // PUNPCKLWD xmm, m128 // , PUNPCKLWD_XMM_XMM // PUNPCKLWD xmm, xmm // , PUSH_FS // PUSH FS // , PUSH_GS // PUSH GS // , PUSH_IMM16 // PUSH imm16 // , PUSH_IMM32 // PUSH imm32 // , PUSH_IMM8 // PUSH imm8 // , PUSH_M16 // PUSH m16 // , PUSH_M64 // PUSH m64 // , PUSH_R16 // PUSH r16 // , PUSH_R64 // PUSH r64 // , PUSHF // PUSHF // , PUSHFQ // PUSHFQ // , PXOR_MM_M64 // PXOR mm, m64 // , PXOR_MM_MM // PXOR mm, mm // , PXOR_XMM_M128 // PXOR xmm, m128 // , PXOR_XMM_XMM // PXOR xmm, xmm // , RCL_M16_CL // RCL m16, CL // , RCL_M16_IMM8 // RCL m16, imm8 // , RCL_M16_ONE // RCL m16, 1 // , RCL_M32_CL // RCL m32, CL // , RCL_M32_IMM8 // RCL m32, imm8 // , RCL_M32_ONE // RCL m32, 1 // , RCL_M64_CL // RCL m64, CL // , RCL_M64_IMM8 // RCL m64, imm8 // , RCL_M64_ONE // RCL m64, 1 // , RCL_M8_CL // RCL m8, CL // , RCL_M8_IMM8 // RCL m8, imm8 // , RCL_M8_ONE // RCL m8, 1 // , RCL_R16_CL // RCL r16, CL // , RCL_R16_IMM8 // RCL r16, imm8 // , RCL_R16_ONE // RCL r16, 1 // , RCL_R32_CL // RCL r32, CL // , RCL_R32_IMM8 // RCL r32, imm8 // , RCL_R32_ONE // RCL r32, 1 // , RCL_R64_CL // RCL r64, CL // , RCL_R64_IMM8 // RCL r64, imm8 // , RCL_R64_ONE // RCL r64, 1 // , RCL_R8_CL // RCL r8, CL // , RCL_R8_IMM8 // RCL r8, imm8 // , RCL_R8_ONE // RCL r8, 1 // , RCL_RH_CL // RCL rh, CL // , RCL_RH_IMM8 // RCL rh, imm8 // , RCL_RH_ONE // RCL rh, 1 // , RCPPS_XMM_M128 // RCPPS xmm, m128 // , RCPPS_XMM_XMM // RCPPS xmm, xmm // , RCPSS_XMM_M32 // RCPSS xmm, m32 // , RCPSS_XMM_XMM // RCPSS xmm, xmm // , RCR_M16_CL // RCR m16, CL // , RCR_M16_IMM8 // RCR m16, imm8 // , RCR_M16_ONE // RCR m16, 1 // , RCR_M32_CL // RCR m32, CL // , RCR_M32_IMM8 // RCR m32, imm8 // , RCR_M32_ONE // RCR m32, 1 // , RCR_M64_CL // RCR m64, CL // , RCR_M64_IMM8 // RCR m64, imm8 // , RCR_M64_ONE // RCR m64, 1 // , RCR_M8_CL // RCR m8, CL // , RCR_M8_IMM8 // RCR m8, imm8 // , RCR_M8_ONE // RCR m8, 1 // , RCR_R16_CL // RCR r16, CL // , RCR_R16_IMM8 // RCR r16, imm8 // , RCR_R16_ONE // RCR r16, 1 // , RCR_R32_CL // RCR r32, CL // , RCR_R32_IMM8 // RCR r32, imm8 // , RCR_R32_ONE // RCR r32, 1 // , RCR_R64_CL // RCR r64, CL // , RCR_R64_IMM8 // RCR r64, imm8 // , RCR_R64_ONE // RCR r64, 1 // , RCR_R8_CL // RCR r8, CL // , RCR_R8_IMM8 // RCR r8, imm8 // , RCR_R8_ONE // RCR r8, 1 // , RCR_RH_CL // RCR rh, CL // , RCR_RH_IMM8 // RCR rh, imm8 // , RCR_RH_ONE // RCR rh, 1 // , RDFSBASE_R32 // RDFSBASE r32 // , RDFSBASE_R64 // RDFSBASE r64 // , RDGSBASE_R32 // RDGSBASE r32 // , RDGSBASE_R64 // RDGSBASE r64 // , RDRAND_R16 // RDRAND r16 // , RDRAND_R32 // RDRAND r32 // , RDRAND_R64 // RDRAND r64 // , REP_INS_M16_DX // REP_INS m16, DX // , REP_INS_M32_DX // REP_INS m32, DX // , REP_INS_M64_DX // REP_INS m64, DX // , REP_INS_M8_DX // REP_INS m8, DX // , REP_LODS_AL // REP_LODS AL // , REP_LODS_AX // REP_LODS AX // , REP_LODS_EAX // REP_LODS EAX // , REP_LODS_RAX // REP_LODS RAX // , REP_MOVS_M16_M16 // REP_MOVS m16, m16 // , REP_MOVS_M32_M32 // REP_MOVS m32, m32 // , REP_MOVS_M64_M64 // REP_MOVS m64, m64 // , REP_MOVS_M8_M8 // REP_MOVS m8, m8 // , REP_OUTS_DX_M16 // REP_OUTS DX, m16 // , REP_OUTS_DX_M32 // REP_OUTS DX, m32 // , REP_OUTS_DX_M64 // REP_OUTS DX, m64 // , REP_OUTS_DX_M8 // REP_OUTS DX, m8 // , REP_STOS_M16 // REP_STOS m16 // , REP_STOS_M32 // REP_STOS m32 // , REP_STOS_M64 // REP_STOS m64 // , REP_STOS_M8 // REP_STOS m8 // , REPE_CMPS_M16_M16 // REPE_CMPS m16, m16 // , REPE_CMPS_M32_M32 // REPE_CMPS m32, m32 // , REPE_CMPS_M64_M64 // REPE_CMPS m64, m64 // , REPE_CMPS_M8_M8 // REPE_CMPS m8, m8 // , REPE_SCAS_M16 // REPE_SCAS m16 // , REPE_SCAS_M32 // REPE_SCAS m32 // , REPE_SCAS_M64 // REPE_SCAS m64 // , REPE_SCAS_M8 // REPE_SCAS m8 // , REPNE_CMPS_M16_M16 // REPNE_CMPS m16, m16 // , REPNE_CMPS_M32_M32 // REPNE_CMPS m32, m32 // , REPNE_CMPS_M64_M64 // REPNE_CMPS m64, m64 // , REPNE_CMPS_M8_M8 // REPNE_CMPS m8, m8 // , REPNE_SCAS_M16 // REPNE_SCAS m16 // , REPNE_SCAS_M32 // REPNE_SCAS m32 // , REPNE_SCAS_M64 // REPNE_SCAS m64 // , REPNE_SCAS_M8 // REPNE_SCAS m8 // , RET // RET // , RET_FAR // RET far // , RET_IMM16 // RET imm16 // , RET_IMM16_FAR // RET imm16, far // , ROL_M16_CL // ROL m16, CL // , ROL_M16_IMM8 // ROL m16, imm8 // , ROL_M16_ONE // ROL m16, 1 // , ROL_M32_CL // ROL m32, CL // , ROL_M32_IMM8 // ROL m32, imm8 // , ROL_M32_ONE // ROL m32, 1 // , ROL_M64_CL // ROL m64, CL // , ROL_M64_IMM8 // ROL m64, imm8 // , ROL_M64_ONE // ROL m64, 1 // , ROL_M8_CL // ROL m8, CL // , ROL_M8_IMM8 // ROL m8, imm8 // , ROL_M8_ONE // ROL m8, 1 // , ROL_R16_CL // ROL r16, CL // , ROL_R16_IMM8 // ROL r16, imm8 // , ROL_R16_ONE // ROL r16, 1 // , ROL_R32_CL // ROL r32, CL // , ROL_R32_IMM8 // ROL r32, imm8 // , ROL_R32_ONE // ROL r32, 1 // , ROL_R64_CL // ROL r64, CL // , ROL_R64_IMM8 // ROL r64, imm8 // , ROL_R64_ONE // ROL r64, 1 // , ROL_R8_CL // ROL r8, CL // , ROL_R8_IMM8 // ROL r8, imm8 // , ROL_R8_ONE // ROL r8, 1 // , ROL_RH_CL // ROL rh, CL // , ROL_RH_IMM8 // ROL rh, imm8 // , ROL_RH_ONE // ROL rh, 1 // , ROR_M16_CL // ROR m16, CL // , ROR_M16_IMM8 // ROR m16, imm8 // , ROR_M16_ONE // ROR m16, 1 // , ROR_M32_CL // ROR m32, CL // , ROR_M32_IMM8 // ROR m32, imm8 // , ROR_M32_ONE // ROR m32, 1 // , ROR_M64_CL // ROR m64, CL // , ROR_M64_IMM8 // ROR m64, imm8 // , ROR_M64_ONE // ROR m64, 1 // , ROR_M8_CL // ROR m8, CL // , ROR_M8_IMM8 // ROR m8, imm8 // , ROR_M8_ONE // ROR m8, 1 // , ROR_R16_CL // ROR r16, CL // , ROR_R16_IMM8 // ROR r16, imm8 // , ROR_R16_ONE // ROR r16, 1 // , ROR_R32_CL // ROR r32, CL // , ROR_R32_IMM8 // ROR r32, imm8 // , ROR_R32_ONE // ROR r32, 1 // , ROR_R64_CL // ROR r64, CL // , ROR_R64_IMM8 // ROR r64, imm8 // , ROR_R64_ONE // ROR r64, 1 // , ROR_R8_CL // ROR r8, CL // , ROR_R8_IMM8 // ROR r8, imm8 // , ROR_R8_ONE // ROR r8, 1 // , ROR_RH_CL // ROR rh, CL // , ROR_RH_IMM8 // ROR rh, imm8 // , ROR_RH_ONE // ROR rh, 1 // , RORX_R32_M32_IMM8 // RORX r32, m32, imm8 // , RORX_R32_R32_IMM8 // RORX r32, r32, imm8 // , RORX_R64_M64_IMM8 // RORX r64, m64, imm8 // , RORX_R64_R64_IMM8 // RORX r64, r64, imm8 // , ROUNDPD_XMM_M128_IMM8 // ROUNDPD xmm, m128, imm8 // , ROUNDPD_XMM_XMM_IMM8 // ROUNDPD xmm, xmm, imm8 // , ROUNDPS_XMM_M128_IMM8 // ROUNDPS xmm, m128, imm8 // , ROUNDPS_XMM_XMM_IMM8 // ROUNDPS xmm, xmm, imm8 // , ROUNDSD_XMM_M64_IMM8 // ROUNDSD xmm, m64, imm8 // , ROUNDSD_XMM_XMM_IMM8 // ROUNDSD xmm, xmm, imm8 // , ROUNDSS_XMM_M32_IMM8 // ROUNDSS xmm, m32, imm8 // , ROUNDSS_XMM_XMM_IMM8 // ROUNDSS xmm, xmm, imm8 // , RSQRTPS_XMM_M128 // RSQRTPS xmm, m128 // , RSQRTPS_XMM_XMM // RSQRTPS xmm, xmm // , RSQRTSS_XMM_M32 // RSQRTSS xmm, m32 // , RSQRTSS_XMM_XMM // RSQRTSS xmm, xmm // , SAHF // SAHF // , SAL_M16_CL // SAL m16, CL // , SAL_M16_IMM8 // SAL m16, imm8 // , SAL_M16_ONE // SAL m16, 1 // , SAL_M32_CL // SAL m32, CL // , SAL_M32_IMM8 // SAL m32, imm8 // , SAL_M32_ONE // SAL m32, 1 // , SAL_M64_CL // SAL m64, CL // , SAL_M64_IMM8 // SAL m64, imm8 // , SAL_M64_ONE // SAL m64, 1 // , SAL_M8_CL // SAL m8, CL // , SAL_M8_IMM8 // SAL m8, imm8 // , SAL_M8_ONE // SAL m8, 1 // , SAL_R16_CL // SAL r16, CL // , SAL_R16_IMM8 // SAL r16, imm8 // , SAL_R16_ONE // SAL r16, 1 // , SAL_R32_CL // SAL r32, CL // , SAL_R32_IMM8 // SAL r32, imm8 // , SAL_R32_ONE // SAL r32, 1 , SAL_R64_CL // SAL r64, CL // , SAL_R64_IMM8 // SAL r64, imm8 // , SAL_R64_ONE // SAL r64, 1 // , SAL_R8_CL // SAL r8, CL // , SAL_R8_IMM8 // SAL r8, imm8 // , SAL_R8_ONE // SAL r8, 1 // , SAL_RH_CL // SAL rh, CL // , SAL_RH_IMM8 // SAL rh, imm8 // , SAL_RH_ONE // SAL rh, 1 // , SAR_M16_CL // SAR m16, CL // , SAR_M16_IMM8 // SAR m16, imm8 // , SAR_M16_ONE // SAR m16, 1 // , SAR_M32_CL // SAR m32, CL // , SAR_M32_IMM8 // SAR m32, imm8 // , SAR_M32_ONE // SAR m32, 1 // , SAR_M64_CL // SAR m64, CL // , SAR_M64_IMM8 // SAR m64, imm8 // , SAR_M64_ONE // SAR m64, 1 // , SAR_M8_CL // SAR m8, CL // , SAR_M8_IMM8 // SAR m8, imm8 // , SAR_M8_ONE // SAR m8, 1 // , SAR_R16_CL // SAR r16, CL // , SAR_R16_IMM8 // SAR r16, imm8 // , SAR_R16_ONE // SAR r16, 1 // , SAR_R32_CL // SAR r32, CL // , SAR_R32_IMM8 // SAR r32, imm8 // , SAR_R32_ONE // SAR r32, 1 , SAR_R64_CL // SAR r64, CL // , SAR_R64_IMM8 // SAR r64, imm8 // , SAR_R64_ONE // SAR r64, 1 // , SAR_R8_CL // SAR r8, CL // , SAR_R8_IMM8 // SAR r8, imm8 // , SAR_R8_ONE // SAR r8, 1 // , SAR_RH_CL // SAR rh, CL // , SAR_RH_IMM8 // SAR rh, imm8 // , SAR_RH_ONE // SAR rh, 1 // , SARX_R32_M32_R32 // SARX r32, m32, r32 // , SARX_R32_R32_R32 // SARX r32, r32, r32 // , SARX_R64_M64_R64 // SARX r64, m64, r64 // , SARX_R64_R64_R64 // SARX r64, r64, r64 // , SBB_AL_IMM8 // SBB AL, imm8 // , SBB_AX_IMM16 // SBB AX, imm16 // , SBB_EAX_IMM32 // SBB EAX, imm32 // , SBB_M16_IMM16 // SBB m16, imm16 // , SBB_M16_IMM8 // SBB m16, imm8 // , SBB_M16_R16 // SBB m16, r16 // , SBB_M32_IMM32 // SBB m32, imm32 // , SBB_M32_IMM8 // SBB m32, imm8 // , SBB_M32_R32 // SBB m32, r32 // , SBB_M64_IMM32 // SBB m64, imm32 // , SBB_M64_IMM8 // SBB m64, imm8 // , SBB_M64_R64 // SBB m64, r64 // , SBB_M8_IMM8 // SBB m8, imm8 // , SBB_M8_R8 // SBB m8, r8 // , SBB_M8_RH // SBB m8, rh // , SBB_R16_IMM16 // SBB r16, imm16 // , SBB_R16_IMM8 // SBB r16, imm8 // , SBB_R16_M16 // SBB r16, m16 // , SBB_R16_R16 // SBB r16, r16 // , SBB_R32_IMM32 // SBB r32, imm32 // , SBB_R32_IMM8 // SBB r32, imm8 // , SBB_R32_M32 // SBB r32, m32 // , SBB_R32_R32 // SBB r32, r32 // , SBB_R64_IMM32 // SBB r64, imm32 // , SBB_R64_IMM8 // SBB r64, imm8 // , SBB_R64_M64 // SBB r64, m64 // , SBB_R64_R64 // SBB r64, r64 // , SBB_R8_IMM8 // SBB r8, imm8 // , SBB_R8_M8 // SBB r8, m8 // , SBB_R8_R8 // SBB r8, r8 // , SBB_R8_RH // SBB r8, rh // , SBB_RAX_IMM32 // SBB RAX, imm32 // , SBB_RH_IMM8 // SBB rh, imm8 // , SBB_RH_M8 // SBB rh, m8 // , SBB_RH_R8 // SBB rh, r8 // , SBB_RH_RH // SBB rh, rh // , SCAS_M16 // SCAS m16 // , SCAS_M32 // SCAS m32 // , SCAS_M64 // SCAS m64 // , SCAS_M8 // SCAS m8 // , SCASB // SCASB // , SCASD // SCASD // , SCASQ // SCASQ // , SCASW // SCASW // , SETA_M8 // SETA m8 // , SETA_R8 // SETA r8 // , SETA_RH // SETA rh // , SETAE_M8 // SETAE m8 // , SETAE_R8 // SETAE r8 // , SETAE_RH // SETAE rh // , SETB_M8 // SETB m8 // , SETB_R8 // SETB r8 // , SETB_RH // SETB rh // , SETBE_M8 // SETBE m8 // , SETBE_R8 // SETBE r8 // , SETBE_RH // SETBE rh // , SETC_M8 // SETC m8 // , SETC_R8 // SETC r8 // , SETC_RH // SETC rh // , SETE_M8 // SETE m8 // , SETE_R8 // SETE r8 // , SETE_RH // SETE rh // , SETG_M8 // SETG m8 // , SETG_R8 // SETG r8 // , SETG_RH // SETG rh // , SETGE_M8 // SETGE m8 // , SETGE_R8 // SETGE r8 // , SETGE_RH // SETGE rh // , SETL_M8 // SETL m8 // , SETL_R8 // SETL r8 // , SETL_RH // SETL rh // , SETLE_M8 // SETLE m8 // , SETLE_R8 // SETLE r8 // , SETLE_RH // SETLE rh // , SETNA_M8 // SETNA m8 // , SETNA_R8 // SETNA r8 // , SETNA_RH // SETNA rh // , SETNAE_M8 // SETNAE m8 // , SETNAE_R8 // SETNAE r8 // , SETNAE_RH // SETNAE rh // , SETNB_M8 // SETNB m8 // , SETNB_R8 // SETNB r8 // , SETNB_RH // SETNB rh // , SETNBE_M8 // SETNBE m8 // , SETNBE_R8 // SETNBE r8 // , SETNBE_RH // SETNBE rh // , SETNC_M8 // SETNC m8 // , SETNC_R8 // SETNC r8 // , SETNC_RH // SETNC rh // , SETNE_M8 // SETNE m8 // , SETNE_R8 // SETNE r8 // , SETNE_RH // SETNE rh // , SETNG_M8 // SETNG m8 // , SETNG_R8 // SETNG r8 // , SETNG_RH // SETNG rh // , SETNGE_M8 // SETNGE m8 // , SETNGE_R8 // SETNGE r8 // , SETNGE_RH // SETNGE rh // , SETNL_M8 // SETNL m8 // , SETNL_R8 // SETNL r8 // , SETNL_RH // SETNL rh // , SETNLE_M8 // SETNLE m8 // , SETNLE_R8 // SETNLE r8 // , SETNLE_RH // SETNLE rh // , SETNO_M8 // SETNO m8 // , SETNO_R8 // SETNO r8 // , SETNO_RH // SETNO rh // , SETNP_M8 // SETNP m8 // , SETNP_R8 // SETNP r8 // , SETNP_RH // SETNP rh // , SETNS_M8 // SETNS m8 // , SETNS_R8 // SETNS r8 // , SETNS_RH // SETNS rh // , SETNZ_M8 // SETNZ m8 // , SETNZ_R8 // SETNZ r8 // , SETNZ_RH // SETNZ rh // , SETO_M8 // SETO m8 // , SETO_R8 // SETO r8 // , SETO_RH // SETO rh // , SETP_M8 // SETP m8 // , SETP_R8 // SETP r8 // , SETP_RH // SETP rh // , SETPE_M8 // SETPE m8 // , SETPE_R8 // SETPE r8 // , SETPE_RH // SETPE rh // , SETPO_M8 // SETPO m8 // , SETPO_R8 // SETPO r8 // , SETPO_RH // SETPO rh // , SETS_M8 // SETS m8 // , SETS_R8 // SETS r8 // , SETS_RH // SETS rh // , SETZ_M8 // SETZ m8 // , SETZ_R8 // SETZ r8 // , SETZ_RH // SETZ rh // , SFENCE // SFENCE // , SHL_M16_CL // SHL m16, CL // , SHL_M16_IMM8 // SHL m16, imm8 // , SHL_M16_ONE // SHL m16, 1 // , SHL_M32_CL // SHL m32, CL // , SHL_M32_IMM8 // SHL m32, imm8 // , SHL_M32_ONE // SHL m32, 1 // , SHL_M64_CL // SHL m64, CL // , SHL_M64_IMM8 // SHL m64, imm8 // , SHL_M64_ONE // SHL m64, 1 // , SHL_M8_CL // SHL m8, CL // , SHL_M8_IMM8 // SHL m8, imm8 // , SHL_M8_ONE // SHL m8, 1 // , SHL_R16_CL // SHL r16, CL // , SHL_R16_IMM8 // SHL r16, imm8 // , SHL_R16_ONE // SHL r16, 1 // , SHL_R32_CL // SHL r32, CL // , SHL_R32_IMM8 // SHL r32, imm8 // , SHL_R32_ONE // SHL r32, 1 // , SHL_R64_CL // SHL r64, CL // , SHL_R64_IMM8 // SHL r64, imm8 // , SHL_R64_ONE // SHL r64, 1 // , SHL_R8_CL // SHL r8, CL // , SHL_R8_IMM8 // SHL r8, imm8 // , SHL_R8_ONE // SHL r8, 1 // , SHL_RH_CL // SHL rh, CL // , SHL_RH_IMM8 // SHL rh, imm8 // , SHL_RH_ONE // SHL rh, 1 // , SHLD_M16_R16_CL // SHLD m16, r16, CL // , SHLD_M16_R16_IMM8 // SHLD m16, r16, imm8 // , SHLD_M32_R32_CL // SHLD m32, r32, CL // , SHLD_M32_R32_IMM8 // SHLD m32, r32, imm8 // , SHLD_M64_R64_CL // SHLD m64, r64, CL // , SHLD_M64_R64_IMM8 // SHLD m64, r64, imm8 // , SHLD_R16_R16_CL // SHLD r16, r16, CL // , SHLD_R16_R16_IMM8 // SHLD r16, r16, imm8 // , SHLD_R32_R32_CL // SHLD r32, r32, CL // , SHLD_R32_R32_IMM8 // SHLD r32, r32, imm8 // , SHLD_R64_R64_CL // SHLD r64, r64, CL // , SHLD_R64_R64_IMM8 // SHLD r64, r64, imm8 // , SHLX_R32_M32_R32 // SHLX r32, m32, r32 // , SHLX_R32_R32_R32 // SHLX r32, r32, r32 // , SHLX_R64_M64_R64 // SHLX r64, m64, r64 // , SHLX_R64_R64_R64 // SHLX r64, r64, r64 // , SHR_M16_CL // SHR m16, CL // , SHR_M16_IMM8 // SHR m16, imm8 // , SHR_M16_ONE // SHR m16, 1 // , SHR_M32_CL // SHR m32, CL // , SHR_M32_IMM8 // SHR m32, imm8 // , SHR_M32_ONE // SHR m32, 1 // , SHR_M64_CL // SHR m64, CL // , SHR_M64_IMM8 // SHR m64, imm8 // , SHR_M64_ONE // SHR m64, 1 // , SHR_M8_CL // SHR m8, CL // , SHR_M8_IMM8 // SHR m8, imm8 // , SHR_M8_ONE // SHR m8, 1 // , SHR_R16_CL // SHR r16, CL // , SHR_R16_IMM8 // SHR r16, imm8 // , SHR_R16_ONE // SHR r16, 1 // , SHR_R32_CL // SHR r32, CL // , SHR_R32_IMM8 // SHR r32, imm8 // , SHR_R32_ONE // SHR r32, 1 , SHR_R64_CL // SHR r64, CL // , SHR_R64_IMM8 // SHR r64, imm8 // , SHR_R64_ONE // SHR r64, 1 // , SHR_R8_CL // SHR r8, CL // , SHR_R8_IMM8 // SHR r8, imm8 // , SHR_R8_ONE // SHR r8, 1 // , SHR_RH_CL // SHR rh, CL // , SHR_RH_IMM8 // SHR rh, imm8 // , SHR_RH_ONE // SHR rh, 1 // , SHRD_M16_R16_CL // SHRD m16, r16, CL // , SHRD_M16_R16_IMM8 // SHRD m16, r16, imm8 // , SHRD_M32_R32_CL // SHRD m32, r32, CL // , SHRD_M32_R32_IMM8 // SHRD m32, r32, imm8 // , SHRD_M64_R64_CL // SHRD m64, r64, CL // , SHRD_M64_R64_IMM8 // SHRD m64, r64, imm8 // , SHRD_R16_R16_CL // SHRD r16, r16, CL // , SHRD_R16_R16_IMM8 // SHRD r16, r16, imm8 // , SHRD_R32_R32_CL // SHRD r32, r32, CL // , SHRD_R32_R32_IMM8 // SHRD r32, r32, imm8 // , SHRD_R64_R64_CL // SHRD r64, r64, CL // , SHRD_R64_R64_IMM8 // SHRD r64, r64, imm8 // , SHRX_R32_M32_R32 // SHRX r32, m32, r32 // , SHRX_R32_R32_R32 // SHRX r32, r32, r32 // , SHRX_R64_M64_R64 // SHRX r64, m64, r64 // , SHRX_R64_R64_R64 // SHRX r64, r64, r64 // , SHUFPD_XMM_M128_IMM8 // SHUFPD xmm, m128, imm8 // , SHUFPD_XMM_XMM_IMM8 // SHUFPD xmm, xmm, imm8 // , SHUFPS_XMM_M128_IMM8 // SHUFPS xmm, m128, imm8 // , SHUFPS_XMM_XMM_IMM8 // SHUFPS xmm, xmm, imm8 // , SQRTPD_XMM_M128 // SQRTPD xmm, m128 // , SQRTPD_XMM_XMM // SQRTPD xmm, xmm // , SQRTPS_XMM_M128 // SQRTPS xmm, m128 // , SQRTPS_XMM_XMM // SQRTPS xmm, xmm // , SQRTSD_XMM_M64 // SQRTSD xmm, m64 // , SQRTSD_XMM_XMM // SQRTSD xmm, xmm // , SQRTSS_XMM_M32 // SQRTSS xmm, m32 // , SQRTSS_XMM_XMM // SQRTSS xmm, xmm // , STC // STC // , STD // STD // , STI // STI // , STMXCSR_M32 // STMXCSR m32 // , STOS_M16 // STOS m16 // , STOS_M32 // STOS m32 // , STOS_M64 // STOS m64 // , STOS_M8 // STOS m8 // , STOSB // STOSB // , STOSD // STOSD // , STOSQ // STOSQ // , STOSW // STOSW // , SUB_AL_IMM8 // SUB AL, imm8 // , SUB_AX_IMM16 // SUB AX, imm16 // , SUB_EAX_IMM32 // SUB EAX, imm32 // , SUB_M16_IMM16 // SUB m16, imm16 // , SUB_M16_IMM8 // SUB m16, imm8 // , SUB_M16_R16 // SUB m16, r16 // , SUB_M32_IMM32 // SUB m32, imm32 // , SUB_M32_IMM8 // SUB m32, imm8 // , SUB_M32_R32 // SUB m32, r32 // , SUB_M64_IMM32 // SUB m64, imm32 // , SUB_M64_IMM8 // SUB m64, imm8 // , SUB_M64_R64 // SUB m64, r64 // , SUB_M8_IMM8 // SUB m8, imm8 // , SUB_M8_R8 // SUB m8, r8 // , SUB_M8_RH // SUB m8, rh // , SUB_R16_IMM16 // SUB r16, imm16 // , SUB_R16_IMM8 // SUB r16, imm8 // , SUB_R16_M16 // SUB r16, m16 // , SUB_R16_R16 // SUB r16, r16 // , SUB_R32_IMM32 // SUB r32, imm32 // , SUB_R32_IMM8 // SUB r32, imm8 // , SUB_R32_M32 // SUB r32, m32 // , SUB_R32_R32 // SUB r32, r32 // , SUB_R64_IMM32 // SUB r64, imm32 // , SUB_R64_IMM8 // SUB r64, imm8 // , SUB_R64_M64 // SUB r64, m64 // , SUB_R64_R64 // SUB r64, r64 // , SUB_R8_IMM8 // SUB r8, imm8 // , SUB_R8_M8 // SUB r8, m8 // , SUB_R8_R8 // SUB r8, r8 // , SUB_R8_RH // SUB r8, rh // , SUB_RAX_IMM32 // SUB RAX, imm32 // , SUB_RH_IMM8 // SUB rh, imm8 // , SUB_RH_M8 // SUB rh, m8 // , SUB_RH_R8 // SUB rh, r8 // , SUB_RH_RH // SUB rh, rh // , SUBPD_XMM_M128 // SUBPD xmm, m128 // , SUBPD_XMM_XMM // SUBPD xmm, xmm // , SUBPS_XMM_M128 // SUBPS xmm, m128 // , SUBPS_XMM_XMM // SUBPS xmm, xmm // , SUBSD_XMM_M64 // SUBSD xmm, m64 // , SUBSD_XMM_XMM // SUBSD xmm, xmm // , SUBSS_XMM_M32 // SUBSS xmm, m32 // , SUBSS_XMM_XMM // SUBSS xmm, xmm // , SWAPGS // SWAPGS // , SYSCALL // SYSCALL // , SYSENTER // SYSENTER // , SYSEXIT // SYSEXIT // , SYSEXIT_PREFREXW // SYSEXIT pw // , SYSRET // SYSRET // , SYSRET_PREFREXW // SYSRET pw // , TEST_AL_IMM8 // TEST AL, imm8 // , TEST_AX_IMM16 // TEST AX, imm16 // , TEST_EAX_IMM32 // TEST EAX, imm32 // , TEST_M16_IMM16 // TEST m16, imm16 // , TEST_M16_R16 // TEST m16, r16 // , TEST_M32_IMM32 // TEST m32, imm32 // , TEST_M32_R32 // TEST m32, r32 // , TEST_M64_IMM32 // TEST m64, imm32 // , TEST_M64_R64 // TEST m64, r64 // , TEST_M8_IMM8 // TEST m8, imm8 // , TEST_M8_R8 // TEST m8, r8 // , TEST_M8_RH // TEST m8, rh // , TEST_R16_IMM16 // TEST r16, imm16 // , TEST_R16_R16 // TEST r16, r16 // , TEST_R32_IMM32 // TEST r32, imm32 // , TEST_R32_R32 // TEST r32, r32 // , TEST_R64_IMM32 // TEST r64, imm32 // , TEST_R64_R64 // TEST r64, r64 // , TEST_R8_IMM8 // TEST r8, imm8 // , TEST_R8_R8 // TEST r8, r8 // , TEST_R8_RH // TEST r8, rh // , TEST_RAX_IMM32 // TEST RAX, imm32 // , TEST_RH_IMM8 // TEST rh, imm8 // , TEST_RH_R8 // TEST rh, r8 // , TEST_RH_RH // TEST rh, rh // , TZCNT_R16_M16 // TZCNT r16, m16 // , TZCNT_R16_R16 // TZCNT r16, r16 // , TZCNT_R32_M32 // TZCNT r32, m32 // , TZCNT_R32_R32 // TZCNT r32, r32 // , TZCNT_R64_M64 // TZCNT r64, m64 // , TZCNT_R64_R64 // TZCNT r64, r64 // , UCOMISD_XMM_M64 // UCOMISD xmm, m64 // , UCOMISD_XMM_XMM // UCOMISD xmm, xmm // , UCOMISS_XMM_M32 // UCOMISS xmm, m32 // , UCOMISS_XMM_XMM // UCOMISS xmm, xmm // , UD2 // UD2 // , UNPCKHPD_XMM_M128 // UNPCKHPD xmm, m128 // , UNPCKHPD_XMM_XMM // UNPCKHPD xmm, xmm // , UNPCKHPS_XMM_M128 // UNPCKHPS xmm, m128 // , UNPCKHPS_XMM_XMM // UNPCKHPS xmm, xmm // , UNPCKLPD_XMM_M128 // UNPCKLPD xmm, m128 // , UNPCKLPD_XMM_XMM // UNPCKLPD xmm, xmm // , UNPCKLPS_XMM_M128 // UNPCKLPS xmm, m128 // , UNPCKLPS_XMM_XMM // UNPCKLPS xmm, xmm // , VADDPD_XMM_XMM_M128 // VADDPD xmm, xmm, m128 // , VADDPD_XMM_XMM_XMM // VADDPD xmm, xmm, xmm // , VADDPD_YMM_YMM_M256 // VADDPD ymm, ymm, m256 , VADDPD_YMM_YMM_YMM // VADDPD ymm, ymm, ymm // , VADDPS_XMM_XMM_M128 // VADDPS xmm, xmm, m128 // , VADDPS_XMM_XMM_XMM // VADDPS xmm, xmm, xmm // , VADDPS_YMM_YMM_M256 // VADDPS ymm, ymm, m256 , VADDPS_YMM_YMM_YMM // VADDPS ymm, ymm, ymm // , VADDSD_XMM_XMM_M64 // VADDSD xmm, xmm, m64 // , VADDSD_XMM_XMM_XMM // VADDSD xmm, xmm, xmm // , VADDSS_XMM_XMM_M32 // VADDSS xmm, xmm, m32 // , VADDSS_XMM_XMM_XMM // VADDSS xmm, xmm, xmm // , VADDSUBPD_XMM_XMM_M128 // VADDSUBPD xmm, xmm, m128 // , VADDSUBPD_XMM_XMM_XMM // VADDSUBPD xmm, xmm, xmm // , VADDSUBPD_YMM_YMM_M256 // VADDSUBPD ymm, ymm, m256 // , VADDSUBPD_YMM_YMM_YMM // VADDSUBPD ymm, ymm, ymm // , VADDSUBPS_XMM_XMM_M128 // VADDSUBPS xmm, xmm, m128 // , VADDSUBPS_XMM_XMM_XMM // VADDSUBPS xmm, xmm, xmm // , VADDSUBPS_YMM_YMM_M256 // VADDSUBPS ymm, ymm, m256 // , VADDSUBPS_YMM_YMM_YMM // VADDSUBPS ymm, ymm, ymm // , VAESDEC_XMM_XMM_M128 // VAESDEC xmm, xmm, m128 // , VAESDEC_XMM_XMM_XMM // VAESDEC xmm, xmm, xmm // , VAESDECLAST_XMM_XMM_M128 // VAESDECLAST xmm, xmm, m128 // , VAESDECLAST_XMM_XMM_XMM // VAESDECLAST xmm, xmm, xmm // , VAESENC_XMM_XMM_M128 // VAESENC xmm, xmm, m128 // , VAESENC_XMM_XMM_XMM // VAESENC xmm, xmm, xmm // , VAESENCLAST_XMM_XMM_M128 // VAESENCLAST xmm, xmm, m128 // , VAESENCLAST_XMM_XMM_XMM // VAESENCLAST xmm, xmm, xmm // , VAESIMC_XMM_M128 // VAESIMC xmm, m128 // , VAESIMC_XMM_XMM // VAESIMC xmm, xmm // , VAESKEYGENASSIST_XMM_M128_IMM8 // VAESKEYGENASSIST xmm, m128, imm8 // , VAESKEYGENASSIST_XMM_XMM_IMM8 // VAESKEYGENASSIST xmm, xmm, imm8 // , VANDNPD_XMM_XMM_M128 // VANDNPD xmm, xmm, m128 // , VANDNPD_XMM_XMM_XMM // VANDNPD xmm, xmm, xmm // , VANDNPD_YMM_YMM_M256 // VANDNPD ymm, ymm, m256 // , VANDNPD_YMM_YMM_YMM // VANDNPD ymm, ymm, ymm // , VANDNPS_XMM_XMM_M128 // VANDNPS xmm, xmm, m128 // , VANDNPS_XMM_XMM_XMM // VANDNPS xmm, xmm, xmm // , VANDNPS_YMM_YMM_M256 // VANDNPS ymm, ymm, m256 // , VANDNPS_YMM_YMM_YMM // VANDNPS ymm, ymm, ymm // , VANDPD_XMM_XMM_M128 // VANDPD xmm, xmm, m128 // , VANDPD_XMM_XMM_XMM // VANDPD xmm, xmm, xmm // , VANDPD_YMM_YMM_M256 // VANDPD ymm, ymm, m256 // , VANDPD_YMM_YMM_YMM // VANDPD ymm, ymm, ymm // , VANDPS_XMM_XMM_M128 // VANDPS xmm, xmm, m128 // , VANDPS_XMM_XMM_XMM // VANDPS xmm, xmm, xmm // , VANDPS_YMM_YMM_M256 // VANDPS ymm, ymm, m256 // , VANDPS_YMM_YMM_YMM // VANDPS ymm, ymm, ymm // , VBLENDPD_XMM_XMM_M128_IMM8 // VBLENDPD xmm, xmm, m128, imm8 // , VBLENDPD_XMM_XMM_XMM_IMM8 // VBLENDPD xmm, xmm, xmm, imm8 // , VBLENDPD_YMM_YMM_M256_IMM8 // VBLENDPD ymm, ymm, m256, imm8 // , VBLENDPD_YMM_YMM_YMM_IMM8 // VBLENDPD ymm, ymm, ymm, imm8 // , VBLENDPS_XMM_XMM_M128_IMM8 // VBLENDPS xmm, xmm, m128, imm8 // , VBLENDPS_XMM_XMM_XMM_IMM8 // VBLENDPS xmm, xmm, xmm, imm8 // , VBLENDPS_YMM_YMM_M256_IMM8 // VBLENDPS ymm, ymm, m256, imm8 // , VBLENDPS_YMM_YMM_YMM_IMM8 // VBLENDPS ymm, ymm, ymm, imm8 // , VBLENDVPD_XMM_XMM_M128_XMM // VBLENDVPD xmm, xmm, m128, xmm // , VBLENDVPD_XMM_XMM_XMM_XMM // VBLENDVPD xmm, xmm, xmm, xmm // , VBLENDVPD_YMM_YMM_M256_YMM // VBLENDVPD ymm, ymm, m256, ymm // , VBLENDVPD_YMM_YMM_YMM_YMM // VBLENDVPD ymm, ymm, ymm, ymm // , VBLENDVPS_XMM_XMM_M128_XMM // VBLENDVPS xmm, xmm, m128, xmm // , VBLENDVPS_XMM_XMM_XMM_XMM // VBLENDVPS xmm, xmm, xmm, xmm // , VBLENDVPS_YMM_YMM_M256_YMM // VBLENDVPS ymm, ymm, m256, ymm // , VBLENDVPS_YMM_YMM_YMM_YMM // VBLENDVPS ymm, ymm, ymm, ymm // , VBROADCASTF128_YMM_M128 // VBROADCASTF128 ymm, m128 // , VBROADCASTI128_YMM_M128 // VBROADCASTI128 ymm, m128 // , VBROADCASTSD_YMM_M64 // VBROADCASTSD ymm, m64 // , VBROADCASTSD_YMM_XMM // VBROADCASTSD ymm, xmm // , VBROADCASTSS_XMM_M32 // VBROADCASTSS xmm, m32 // , VBROADCASTSS_XMM_XMM // VBROADCASTSS xmm, xmm // , VBROADCASTSS_YMM_M32 // VBROADCASTSS ymm, m32 // , VBROADCASTSS_YMM_XMM // VBROADCASTSS ymm, xmm // , VCMPPD_XMM_XMM_M128_IMM8 // VCMPPD xmm, xmm, m128, imm8 // , VCMPPD_XMM_XMM_XMM_IMM8 // VCMPPD xmm, xmm, xmm, imm8 // , VCMPPD_YMM_YMM_M256_IMM8 // VCMPPD ymm, ymm, m256, imm8 // , VCMPPD_YMM_YMM_YMM_IMM8 // VCMPPD ymm, ymm, ymm, imm8 // , VCMPPS_XMM_XMM_M128_IMM8 // VCMPPS xmm, xmm, m128, imm8 // , VCMPPS_XMM_XMM_XMM_IMM8 // VCMPPS xmm, xmm, xmm, imm8 // , VCMPPS_YMM_YMM_M256_IMM8 // VCMPPS ymm, ymm, m256, imm8 // , VCMPPS_YMM_YMM_YMM_IMM8 // VCMPPS ymm, ymm, ymm, imm8 // , VCMPSD_XMM_XMM_M64_IMM8 // VCMPSD xmm, xmm, m64, imm8 // , VCMPSD_XMM_XMM_XMM_IMM8 // VCMPSD xmm, xmm, xmm, imm8 // , VCMPSS_XMM_XMM_M32_IMM8 // VCMPSS xmm, xmm, m32, imm8 // , VCMPSS_XMM_XMM_XMM_IMM8 // VCMPSS xmm, xmm, xmm, imm8 // , VCOMISD_XMM_M64 // VCOMISD xmm, m64 // , VCOMISD_XMM_XMM // VCOMISD xmm, xmm // , VCOMISS_XMM_M32 // VCOMISS xmm, m32 // , VCOMISS_XMM_XMM // VCOMISS xmm, xmm // , VCVTDQ2PD_XMM_M64 // VCVTDQ2PD xmm, m64 // , VCVTDQ2PD_XMM_XMM // VCVTDQ2PD xmm, xmm // , VCVTDQ2PD_YMM_M128 // VCVTDQ2PD ymm, m128 , VCVTDQ2PD_YMM_XMM // VCVTDQ2PD ymm, ymm // , VCVTDQ2PS_XMM_M128 // VCVTDQ2PS xmm, m128 // , VCVTDQ2PS_XMM_XMM // VCVTDQ2PS xmm, xmm // , VCVTDQ2PS_YMM_M256 // VCVTDQ2PS ymm, m256 , VCVTDQ2PS_YMM_YMM // VCVTDQ2PS ymm, ymm // , VCVTPD2DQ_XMM_M128 // VCVTPD2DQ xmm, m128 // , VCVTPD2DQ_XMM_M256 // VCVTPD2DQ xmm, m256 // , VCVTPD2DQ_XMM_XMM // VCVTPD2DQ xmm, xmm , VCVTPD2DQ_XMM_YMM // VCVTPD2DQ xmm, ymm // , VCVTPD2PS_XMM_M128 // VCVTPD2PS xmm, m128 // , VCVTPD2PS_XMM_M256 // VCVTPD2PS xmm, m256 // , VCVTPD2PS_XMM_XMM // VCVTPD2PS xmm, xmm , VCVTPD2PS_XMM_YMM // VCVTPD2PS xmm, ymm // , VCVTPH2PS_XMM_M64 // VCVTPH2PS xmm, m64 // , VCVTPH2PS_XMM_XMM // VCVTPH2PS xmm, xmm // , VCVTPH2PS_YMM_M128 // VCVTPH2PS ymm, m128 // , VCVTPH2PS_YMM_XMM // VCVTPH2PS ymm, xmm // , VCVTPS2DQ_XMM_M128 // VCVTPS2DQ xmm, m128 // , VCVTPS2DQ_XMM_XMM // VCVTPS2DQ xmm, xmm // , VCVTPS2DQ_YMM_M256 // VCVTPS2DQ ymm, m256 , VCVTPS2DQ_YMM_YMM // VCVTPS2DQ ymm, ymm // , VCVTPS2PD_XMM_M64 // VCVTPS2PD xmm, m64 // , VCVTPS2PD_XMM_XMM // VCVTPS2PD xmm, xmm // , VCVTPS2PD_YMM_M128 // VCVTPS2PD ymm, m128 , VCVTPS2PD_YMM_XMM // VCVTPS2PD ymm, xmm // , VCVTPS2PH_M128_YMM_IMM8 // VCVTPS2PH m128, ymm, imm8 // , VCVTPS2PH_M64_XMM_IMM8 // VCVTPS2PH m64, xmm, imm8 // , VCVTPS2PH_XMM_XMM_IMM8 // VCVTPS2PH xmm, xmm, imm8 // , VCVTPS2PH_XMM_YMM_IMM8 // VCVTPS2PH xmm, ymm, imm8 // , VCVTSD2SI_R32_M64 // VCVTSD2SI r32, m64 // , VCVTSD2SI_R32_XMM // VCVTSD2SI r32, xmm // , VCVTSD2SI_R64_M64 // VCVTSD2SI r64, m64 // , VCVTSD2SI_R64_XMM // VCVTSD2SI r64, xmm // , VCVTSD2SS_XMM_XMM_M64 // VCVTSD2SS xmm, xmm, m64 // , VCVTSD2SS_XMM_XMM_XMM // VCVTSD2SS xmm, xmm, xmm // , VCVTSI2SD_XMM_XMM_M32 // VCVTSI2SD xmm, xmm, m32 // , VCVTSI2SD_XMM_XMM_M64 // VCVTSI2SD xmm, xmm, m64 // , VCVTSI2SD_XMM_XMM_R32 // VCVTSI2SD xmm, xmm, r32 // , VCVTSI2SD_XMM_XMM_R64 // VCVTSI2SD xmm, xmm, r64 // , VCVTSI2SS_XMM_XMM_M32 // VCVTSI2SS xmm, xmm, m32 // , VCVTSI2SS_XMM_XMM_M64 // VCVTSI2SS xmm, xmm, m64 // , VCVTSI2SS_XMM_XMM_R32 // VCVTSI2SS xmm, xmm, r32 // , VCVTSI2SS_XMM_XMM_R64 // VCVTSI2SS xmm, xmm, r64 // , VCVTSS2SD_XMM_XMM_M32 // VCVTSS2SD xmm, xmm, m32 // , VCVTSS2SD_XMM_XMM_XMM // VCVTSS2SD xmm, xmm, xmm // , VCVTSS2SI_R32_M32 // VCVTSS2SI r32, m32 // , VCVTSS2SI_R32_XMM // VCVTSS2SI r32, xmm // , VCVTSS2SI_R64_M32 // VCVTSS2SI r64, m32 // , VCVTSS2SI_R64_XMM // VCVTSS2SI r64, xmm // , VCVTTPD2DQ_XMM_M128 // VCVTTPD2DQ xmm, m128 // , VCVTTPD2DQ_XMM_M256 // VCVTTPD2DQ xmm, m256 // , VCVTTPD2DQ_XMM_XMM // VCVTTPD2DQ xmm, xmm , VCVTTPD2DQ_XMM_YMM // VCVTTPD2DQ xmm, ymm // , VCVTTPS2DQ_XMM_M128 // VCVTTPS2DQ xmm, m128 // , VCVTTPS2DQ_XMM_XMM // VCVTTPS2DQ xmm, xmm // , VCVTTPS2DQ_YMM_M256 // VCVTTPS2DQ ymm, m256 , VCVTTPS2DQ_YMM_YMM // VCVTTPS2DQ ymm, ymm // , VCVTTSD2SI_R32_M64 // VCVTTSD2SI r32, m64 // , VCVTTSD2SI_R32_XMM // VCVTTSD2SI r32, xmm // , VCVTTSD2SI_R64_M64 // VCVTTSD2SI r64, m64 // , VCVTTSD2SI_R64_XMM // VCVTTSD2SI r64, xmm // , VCVTTSS2SI_R32_M32 // VCVTTSS2SI r32, m32 // , VCVTTSS2SI_R32_XMM // VCVTTSS2SI r32, xmm // , VCVTTSS2SI_R64_M32 // VCVTTSS2SI r64, m32 // , VCVTTSS2SI_R64_XMM // VCVTTSS2SI r64, xmm // , VDIVPD_XMM_XMM_M128 // VDIVPD xmm, xmm, m128 // , VDIVPD_XMM_XMM_XMM // VDIVPD xmm, xmm, xmm // , VDIVPD_YMM_YMM_M256 // VDIVPD ymm, ymm, m256 , VDIVPD_YMM_YMM_YMM // VDIVPD ymm, ymm, ymm // , VDIVPS_XMM_XMM_M128 // VDIVPS xmm, xmm, m128 // , VDIVPS_XMM_XMM_XMM // VDIVPS xmm, xmm, xmm // , VDIVPS_YMM_YMM_M256 // VDIVPS ymm, ymm, m256 , VDIVPS_YMM_YMM_YMM // VDIVPS ymm, ymm, ymm // , VDIVSD_XMM_XMM_M64 // VDIVSD xmm, xmm, m64 // , VDIVSD_XMM_XMM_XMM // VDIVSD xmm, xmm, xmm // , VDIVSS_XMM_XMM_M32 // VDIVSS xmm, xmm, m32 // , VDIVSS_XMM_XMM_XMM // VDIVSS xmm, xmm, xmm // , VDPPD_XMM_XMM_M128_IMM8 // VDPPD xmm, xmm, m128, imm8 // , VDPPD_XMM_XMM_XMM_IMM8 // VDPPD xmm, xmm, xmm, imm8 // , VDPPS_XMM_XMM_M128_IMM8 // VDPPS xmm, xmm, m128, imm8 // , VDPPS_XMM_XMM_XMM_IMM8 // VDPPS xmm, xmm, xmm, imm8 // , VDPPS_YMM_YMM_M256_IMM8 // VDPPS ymm, ymm, m256, imm8 // , VDPPS_YMM_YMM_YMM_IMM8 // VDPPS ymm, ymm, ymm, imm8 // , VERR_M16 // VERR m16 // , VERR_R16 // VERR r16 // , VERW_M16 // VERW m16 // , VERW_R16 // VERW r16 // , VEXTRACTF128_M128_YMM_IMM8 // VEXTRACTF128 m128, ymm, imm8 // , VEXTRACTF128_XMM_YMM_IMM8 // VEXTRACTF128 xmm, ymm, imm8 // , VEXTRACTI128_M128_YMM_IMM8 // VEXTRACTI128 m128, ymm, imm8 // , VEXTRACTI128_XMM_YMM_IMM8 // VEXTRACTI128 xmm, ymm, imm8 // , VEXTRACTPS_M32_XMM_IMM8 // VEXTRACTPS m32, xmm, imm8 // , VEXTRACTPS_R32_XMM_IMM8 // VEXTRACTPS r32, xmm, imm8 // , VFMADD132PD_XMM_XMM_M128 // VFMADD132PD xmm, xmm, m128 // , VFMADD132PD_XMM_XMM_XMM // VFMADD132PD xmm, xmm, xmm // , VFMADD132PD_YMM_YMM_M256 // VFMADD132PD ymm, ymm, m256 , VFMADD132PD_YMM_YMM_YMM // VFMADD132PD ymm, ymm, ymm // , VFMADD132PS_XMM_XMM_M128 // VFMADD132PS xmm, xmm, m128 // , VFMADD132PS_XMM_XMM_XMM // VFMADD132PS xmm, xmm, xmm // , VFMADD132PS_YMM_YMM_M256 // VFMADD132PS ymm, ymm, m256 , VFMADD132PS_YMM_YMM_YMM // VFMADD132PS ymm, ymm, ymm // , VFMADD132SD_XMM_XMM_M64 // VFMADD132SD xmm, xmm, m64 // , VFMADD132SD_XMM_XMM_XMM // VFMADD132SD xmm, xmm, xmm // , VFMADD132SS_XMM_XMM_M32 // VFMADD132SS xmm, xmm, m32 // , VFMADD132SS_XMM_XMM_XMM // VFMADD132SS xmm, xmm, xmm // , VFMADD213PD_XMM_XMM_M128 // VFMADD213PD xmm, xmm, m128 // , VFMADD213PD_XMM_XMM_XMM // VFMADD213PD xmm, xmm, xmm // , VFMADD213PD_YMM_YMM_M256 // VFMADD213PD ymm, ymm, m256 // , VFMADD213PD_YMM_YMM_YMM // VFMADD213PD ymm, ymm, ymm // , VFMADD213PS_XMM_XMM_M128 // VFMADD213PS xmm, xmm, m128 // , VFMADD213PS_XMM_XMM_XMM // VFMADD213PS xmm, xmm, xmm // , VFMADD213PS_YMM_YMM_M256 // VFMADD213PS ymm, ymm, m256 // , VFMADD213PS_YMM_YMM_YMM // VFMADD213PS ymm, ymm, ymm // , VFMADD213SD_XMM_XMM_M64 // VFMADD213SD xmm, xmm, m64 // , VFMADD213SD_XMM_XMM_XMM // VFMADD213SD xmm, xmm, xmm // , VFMADD213SS_XMM_XMM_M32 // VFMADD213SS xmm, xmm, m32 // , VFMADD213SS_XMM_XMM_XMM // VFMADD213SS xmm, xmm, xmm // , VFMADD231PD_XMM_XMM_M128 // VFMADD231PD xmm, xmm, m128 // , VFMADD231PD_XMM_XMM_XMM // VFMADD231PD xmm, xmm, xmm // , VFMADD231PD_YMM_YMM_M256 // VFMADD231PD ymm, ymm, m256 // , VFMADD231PD_YMM_YMM_YMM // VFMADD231PD ymm, ymm, ymm // , VFMADD231PS_XMM_XMM_M128 // VFMADD231PS xmm, xmm, m128 // , VFMADD231PS_XMM_XMM_XMM // VFMADD231PS xmm, xmm, xmm // , VFMADD231PS_YMM_YMM_M256 // VFMADD231PS ymm, ymm, m256 // , VFMADD231PS_YMM_YMM_YMM // VFMADD231PS ymm, ymm, ymm // , VFMADD231SD_XMM_XMM_M64 // VFMADD231SD xmm, xmm, m64 // , VFMADD231SD_XMM_XMM_XMM // VFMADD231SD xmm, xmm, xmm // , VFMADD231SS_XMM_XMM_M32 // VFMADD231SS xmm, xmm, m32 // , VFMADD231SS_XMM_XMM_XMM // VFMADD231SS xmm, xmm, xmm // , VFMADDSUB132PD_XMM_XMM_M128 // VFMADDSUB132PD xmm, xmm, m128 // , VFMADDSUB132PD_XMM_XMM_XMM // VFMADDSUB132PD xmm, xmm, xmm // , VFMADDSUB132PD_YMM_YMM_M256 // VFMADDSUB132PD ymm, ymm, m256 // , VFMADDSUB132PD_YMM_YMM_YMM // VFMADDSUB132PD ymm, ymm, ymm // , VFMADDSUB132PS_XMM_XMM_M128 // VFMADDSUB132PS xmm, xmm, m128 // , VFMADDSUB132PS_XMM_XMM_XMM // VFMADDSUB132PS xmm, xmm, xmm // , VFMADDSUB132PS_YMM_YMM_M256 // VFMADDSUB132PS ymm, ymm, m256 // , VFMADDSUB132PS_YMM_YMM_YMM // VFMADDSUB132PS ymm, ymm, ymm // , VFMADDSUB213PD_XMM_XMM_M128 // VFMADDSUB213PD xmm, xmm, m128 // , VFMADDSUB213PD_XMM_XMM_XMM // VFMADDSUB213PD xmm, xmm, xmm // , VFMADDSUB213PD_YMM_YMM_M256 // VFMADDSUB213PD ymm, ymm, m256 // , VFMADDSUB213PD_YMM_YMM_YMM // VFMADDSUB213PD ymm, ymm, ymm // , VFMADDSUB213PS_XMM_XMM_M128 // VFMADDSUB213PS xmm, xmm, m128 // , VFMADDSUB213PS_XMM_XMM_XMM // VFMADDSUB213PS xmm, xmm, xmm // , VFMADDSUB213PS_YMM_YMM_M256 // VFMADDSUB213PS ymm, ymm, m256 // , VFMADDSUB213PS_YMM_YMM_YMM // VFMADDSUB213PS ymm, ymm, ymm // , VFMADDSUB231PD_XMM_XMM_M128 // VFMADDSUB231PD xmm, xmm, m128 // , VFMADDSUB231PD_XMM_XMM_XMM // VFMADDSUB231PD xmm, xmm, xmm // , VFMADDSUB231PD_YMM_YMM_M256 // VFMADDSUB231PD ymm, ymm, m256 // , VFMADDSUB231PD_YMM_YMM_YMM // VFMADDSUB231PD ymm, ymm, ymm // , VFMADDSUB231PS_XMM_XMM_M128 // VFMADDSUB231PS xmm, xmm, m128 // , VFMADDSUB231PS_XMM_XMM_XMM // VFMADDSUB231PS xmm, xmm, xmm // , VFMADDSUB231PS_YMM_YMM_M256 // VFMADDSUB231PS ymm, ymm, m256 // , VFMADDSUB231PS_YMM_YMM_YMM // VFMADDSUB231PS ymm, ymm, ymm // , VFMSUB132PD_XMM_XMM_M128 // VFMSUB132PD xmm, xmm, m128 // , VFMSUB132PD_XMM_XMM_XMM // VFMSUB132PD xmm, xmm, xmm // , VFMSUB132PD_YMM_YMM_M256 // VFMSUB132PD ymm, ymm, m256 , VFMSUB132PD_YMM_YMM_YMM // VFMSUB132PD ymm, ymm, ymm // , VFMSUB132PS_XMM_XMM_M128 // VFMSUB132PS xmm, xmm, m128 // , VFMSUB132PS_XMM_XMM_XMM // VFMSUB132PS xmm, xmm, xmm // , VFMSUB132PS_YMM_YMM_M256 // VFMSUB132PS ymm, ymm, m256 , VFMSUB132PS_YMM_YMM_YMM // VFMSUB132PS ymm, ymm, ymm // , VFMSUB132SD_XMM_XMM_M64 // VFMSUB132SD xmm, xmm, m64 // , VFMSUB132SD_XMM_XMM_XMM // VFMSUB132SD xmm, xmm, xmm // , VFMSUB132SS_XMM_XMM_M32 // VFMSUB132SS xmm, xmm, m32 // , VFMSUB132SS_XMM_XMM_XMM // VFMSUB132SS xmm, xmm, xmm // , VFMSUB213PD_XMM_XMM_M128 // VFMSUB213PD xmm, xmm, m128 // , VFMSUB213PD_XMM_XMM_XMM // VFMSUB213PD xmm, xmm, xmm // , VFMSUB213PD_YMM_YMM_M256 // VFMSUB213PD ymm, ymm, m256 // , VFMSUB213PD_YMM_YMM_YMM // VFMSUB213PD ymm, ymm, ymm // , VFMSUB213PS_XMM_XMM_M128 // VFMSUB213PS xmm, xmm, m128 // , VFMSUB213PS_XMM_XMM_XMM // VFMSUB213PS xmm, xmm, xmm // , VFMSUB213PS_YMM_YMM_M256 // VFMSUB213PS ymm, ymm, m256 // , VFMSUB213PS_YMM_YMM_YMM // VFMSUB213PS ymm, ymm, ymm // , VFMSUB213SD_XMM_XMM_M64 // VFMSUB213SD xmm, xmm, m64 // , VFMSUB213SD_XMM_XMM_XMM // VFMSUB213SD xmm, xmm, xmm // , VFMSUB213SS_XMM_XMM_M32 // VFMSUB213SS xmm, xmm, m32 // , VFMSUB213SS_XMM_XMM_XMM // VFMSUB213SS xmm, xmm, xmm // , VFMSUB231PD_XMM_XMM_M128 // VFMSUB231PD xmm, xmm, m128 // , VFMSUB231PD_XMM_XMM_XMM // VFMSUB231PD xmm, xmm, xmm // , VFMSUB231PD_YMM_YMM_M256 // VFMSUB231PD ymm, ymm, m256 // , VFMSUB231PD_YMM_YMM_YMM // VFMSUB231PD ymm, ymm, ymm // , VFMSUB231PS_XMM_XMM_M128 // VFMSUB231PS xmm, xmm, m128 // , VFMSUB231PS_XMM_XMM_XMM // VFMSUB231PS xmm, xmm, xmm // , VFMSUB231PS_YMM_YMM_M256 // VFMSUB231PS ymm, ymm, m256 // , VFMSUB231PS_YMM_YMM_YMM // VFMSUB231PS ymm, ymm, ymm // , VFMSUB231SD_XMM_XMM_M64 // VFMSUB231SD xmm, xmm, m64 // , VFMSUB231SD_XMM_XMM_XMM // VFMSUB231SD xmm, xmm, xmm // , VFMSUB231SS_XMM_XMM_M32 // VFMSUB231SS xmm, xmm, m32 // , VFMSUB231SS_XMM_XMM_XMM // VFMSUB231SS xmm, xmm, xmm // , VFMSUBADD132PD_XMM_XMM_M128 // VFMSUBADD132PD xmm, xmm, m128 // , VFMSUBADD132PD_XMM_XMM_XMM // VFMSUBADD132PD xmm, xmm, xmm // , VFMSUBADD132PD_YMM_YMM_M256 // VFMSUBADD132PD ymm, ymm, m256 // , VFMSUBADD132PD_YMM_YMM_YMM // VFMSUBADD132PD ymm, ymm, ymm // , VFMSUBADD132PS_XMM_XMM_M128 // VFMSUBADD132PS xmm, xmm, m128 // , VFMSUBADD132PS_XMM_XMM_XMM // VFMSUBADD132PS xmm, xmm, xmm // , VFMSUBADD132PS_YMM_YMM_M256 // VFMSUBADD132PS ymm, ymm, m256 // , VFMSUBADD132PS_YMM_YMM_YMM // VFMSUBADD132PS ymm, ymm, ymm // , VFMSUBADD213PD_XMM_XMM_M128 // VFMSUBADD213PD xmm, xmm, m128 // , VFMSUBADD213PD_XMM_XMM_XMM // VFMSUBADD213PD xmm, xmm, xmm // , VFMSUBADD213PD_YMM_YMM_M256 // VFMSUBADD213PD ymm, ymm, m256 // , VFMSUBADD213PD_YMM_YMM_YMM // VFMSUBADD213PD ymm, ymm, ymm // , VFMSUBADD213PS_XMM_XMM_M128 // VFMSUBADD213PS xmm, xmm, m128 // , VFMSUBADD213PS_XMM_XMM_XMM // VFMSUBADD213PS xmm, xmm, xmm // , VFMSUBADD213PS_YMM_YMM_M256 // VFMSUBADD213PS ymm, ymm, m256 // , VFMSUBADD213PS_YMM_YMM_YMM // VFMSUBADD213PS ymm, ymm, ymm // , VFMSUBADD231PD_XMM_XMM_M128 // VFMSUBADD231PD xmm, xmm, m128 // , VFMSUBADD231PD_XMM_XMM_XMM // VFMSUBADD231PD xmm, xmm, xmm // , VFMSUBADD231PD_YMM_YMM_M256 // VFMSUBADD231PD ymm, ymm, m256 // , VFMSUBADD231PD_YMM_YMM_YMM // VFMSUBADD231PD ymm, ymm, ymm // , VFMSUBADD231PS_XMM_XMM_M128 // VFMSUBADD231PS xmm, xmm, m128 // , VFMSUBADD231PS_XMM_XMM_XMM // VFMSUBADD231PS xmm, xmm, xmm // , VFMSUBADD231PS_YMM_YMM_M256 // VFMSUBADD231PS ymm, ymm, m256 // , VFMSUBADD231PS_YMM_YMM_YMM // VFMSUBADD231PS ymm, ymm, ymm // , VFNMADD132PD_XMM_XMM_M128 // VFNMADD132PD xmm, xmm, m128 // , VFNMADD132PD_XMM_XMM_XMM // VFNMADD132PD xmm, xmm, xmm // , VFNMADD132PD_YMM_YMM_M256 // VFNMADD132PD ymm, ymm, m256 , VFNMADD132PD_YMM_YMM_YMM // VFNMADD132PD ymm, ymm, ymm // , VFNMADD132PS_XMM_XMM_M128 // VFNMADD132PS xmm, xmm, m128 // , VFNMADD132PS_XMM_XMM_XMM // VFNMADD132PS xmm, xmm, xmm // , VFNMADD132PS_YMM_YMM_M256 // VFNMADD132PS ymm, ymm, m256 , VFNMADD132PS_YMM_YMM_YMM // VFNMADD132PS ymm, ymm, ymm // , VFNMADD132SD_XMM_XMM_M64 // VFNMADD132SD xmm, xmm, m64 // , VFNMADD132SD_XMM_XMM_XMM // VFNMADD132SD xmm, xmm, xmm // , VFNMADD132SS_XMM_XMM_M32 // VFNMADD132SS xmm, xmm, m32 // , VFNMADD132SS_XMM_XMM_XMM // VFNMADD132SS xmm, xmm, xmm // , VFNMADD213PD_XMM_XMM_M128 // VFNMADD213PD xmm, xmm, m128 // , VFNMADD213PD_XMM_XMM_XMM // VFNMADD213PD xmm, xmm, xmm // , VFNMADD213PD_YMM_YMM_M256 // VFNMADD213PD ymm, ymm, m256 // , VFNMADD213PD_YMM_YMM_YMM // VFNMADD213PD ymm, ymm, ymm // , VFNMADD213PS_XMM_XMM_M128 // VFNMADD213PS xmm, xmm, m128 // , VFNMADD213PS_XMM_XMM_XMM // VFNMADD213PS xmm, xmm, xmm // , VFNMADD213PS_YMM_YMM_M256 // VFNMADD213PS ymm, ymm, m256 // , VFNMADD213PS_YMM_YMM_YMM // VFNMADD213PS ymm, ymm, ymm // , VFNMADD213SD_XMM_XMM_M64 // VFNMADD213SD xmm, xmm, m64 // , VFNMADD213SD_XMM_XMM_XMM // VFNMADD213SD xmm, xmm, xmm // , VFNMADD213SS_XMM_XMM_M32 // VFNMADD213SS xmm, xmm, m32 // , VFNMADD213SS_XMM_XMM_XMM // VFNMADD213SS xmm, xmm, xmm // , VFNMADD231PD_XMM_XMM_M128 // VFNMADD231PD xmm, xmm, m128 // , VFNMADD231PD_XMM_XMM_XMM // VFNMADD231PD xmm, xmm, xmm // , VFNMADD231PD_YMM_YMM_M256 // VFNMADD231PD ymm, ymm, m256 // , VFNMADD231PD_YMM_YMM_YMM // VFNMADD231PD ymm, ymm, ymm // , VFNMADD231PS_XMM_XMM_M128 // VFNMADD231PS xmm, xmm, m128 // , VFNMADD231PS_XMM_XMM_XMM // VFNMADD231PS xmm, xmm, xmm // , VFNMADD231PS_YMM_YMM_M256 // VFNMADD231PS ymm, ymm, m256 // , VFNMADD231PS_YMM_YMM_YMM // VFNMADD231PS ymm, ymm, ymm // , VFNMADD231SD_XMM_XMM_M64 // VFNMADD231SD xmm, xmm, m64 // , VFNMADD231SD_XMM_XMM_XMM // VFNMADD231SD xmm, xmm, xmm // , VFNMADD231SS_XMM_XMM_M32 // VFNMADD231SS xmm, xmm, m32 // , VFNMADD231SS_XMM_XMM_XMM // VFNMADD231SS xmm, xmm, xmm // , VFNMSUB132PD_XMM_XMM_M128 // VFNMSUB132PD xmm, xmm, m128 // , VFNMSUB132PD_XMM_XMM_XMM // VFNMSUB132PD xmm, xmm, xmm // , VFNMSUB132PD_YMM_YMM_M256 // VFNMSUB132PD ymm, ymm, m256 , VFNMSUB132PD_YMM_YMM_YMM // VFNMSUB132PD ymm, ymm, ymm // , VFNMSUB132PS_XMM_XMM_M128 // VFNMSUB132PS xmm, xmm, m128 // , VFNMSUB132PS_XMM_XMM_XMM // VFNMSUB132PS xmm, xmm, xmm // , VFNMSUB132PS_YMM_YMM_M256 // VFNMSUB132PS ymm, ymm, m256 , VFNMSUB132PS_YMM_YMM_YMM // VFNMSUB132PS ymm, ymm, ymm // , VFNMSUB132SD_XMM_XMM_M64 // VFNMSUB132SD xmm, xmm, m64 // , VFNMSUB132SD_XMM_XMM_XMM // VFNMSUB132SD xmm, xmm, xmm // , VFNMSUB132SS_XMM_XMM_M32 // VFNMSUB132SS xmm, xmm, m32 // , VFNMSUB132SS_XMM_XMM_XMM // VFNMSUB132SS xmm, xmm, xmm // , VFNMSUB213PD_XMM_XMM_M128 // VFNMSUB213PD xmm, xmm, m128 // , VFNMSUB213PD_XMM_XMM_XMM // VFNMSUB213PD xmm, xmm, xmm // , VFNMSUB213PD_YMM_YMM_M256 // VFNMSUB213PD ymm, ymm, m256 // , VFNMSUB213PD_YMM_YMM_YMM // VFNMSUB213PD ymm, ymm, ymm // , VFNMSUB213PS_XMM_XMM_M128 // VFNMSUB213PS xmm, xmm, m128 // , VFNMSUB213PS_XMM_XMM_XMM // VFNMSUB213PS xmm, xmm, xmm // , VFNMSUB213PS_YMM_YMM_M256 // VFNMSUB213PS ymm, ymm, m256 // , VFNMSUB213PS_YMM_YMM_YMM // VFNMSUB213PS ymm, ymm, ymm // , VFNMSUB213SD_XMM_XMM_M64 // VFNMSUB213SD xmm, xmm, m64 // , VFNMSUB213SD_XMM_XMM_XMM // VFNMSUB213SD xmm, xmm, xmm // , VFNMSUB213SS_XMM_XMM_M32 // VFNMSUB213SS xmm, xmm, m32 // , VFNMSUB213SS_XMM_XMM_XMM // VFNMSUB213SS xmm, xmm, xmm // , VFNMSUB231PD_XMM_XMM_M128 // VFNMSUB231PD xmm, xmm, m128 // , VFNMSUB231PD_XMM_XMM_XMM // VFNMSUB231PD xmm, xmm, xmm // , VFNMSUB231PD_YMM_YMM_M256 // VFNMSUB231PD ymm, ymm, m256 // , VFNMSUB231PD_YMM_YMM_YMM // VFNMSUB231PD ymm, ymm, ymm // , VFNMSUB231PS_XMM_XMM_M128 // VFNMSUB231PS xmm, xmm, m128 // , VFNMSUB231PS_XMM_XMM_XMM // VFNMSUB231PS xmm, xmm, xmm // , VFNMSUB231PS_YMM_YMM_M256 // VFNMSUB231PS ymm, ymm, m256 // , VFNMSUB231PS_YMM_YMM_YMM // VFNMSUB231PS ymm, ymm, ymm // , VFNMSUB231SD_XMM_XMM_M64 // VFNMSUB231SD xmm, xmm, m64 // , VFNMSUB231SD_XMM_XMM_XMM // VFNMSUB231SD xmm, xmm, xmm // , VFNMSUB231SS_XMM_XMM_M32 // VFNMSUB231SS xmm, xmm, m32 // , VFNMSUB231SS_XMM_XMM_XMM // VFNMSUB231SS xmm, xmm, xmm // , VGATHERDPD_XMM_M32_XMM // VGATHERDPD xmm, m32, xmm // , VGATHERDPD_YMM_M32_YMM // VGATHERDPD ymm, m32, ymm // , VGATHERDPS_XMM_M32_XMM // VGATHERDPS xmm, m32, xmm // , VGATHERDPS_YMM_M32_YMM // VGATHERDPS ymm, m32, ymm // , VGATHERQPD_XMM_M64_XMM // VGATHERQPD xmm, m64, xmm // , VGATHERQPD_YMM_M64_YMM // VGATHERQPD ymm, m64, ymm // , VGATHERQPS_XMM_M64_XMM // VGATHERQPS xmm, m64, xmm // , VHADDPD_XMM_XMM_M128 // VHADDPD xmm, xmm, m128 // , VHADDPD_XMM_XMM_XMM // VHADDPD xmm, xmm, xmm // , VHADDPD_YMM_YMM_M256 // VHADDPD ymm, ymm, m256 // , VHADDPD_YMM_YMM_YMM // VHADDPD ymm, ymm, ymm // , VHADDPS_XMM_XMM_M128 // VHADDPS xmm, xmm, m128 // , VHADDPS_XMM_XMM_XMM // VHADDPS xmm, xmm, xmm // , VHADDPS_YMM_YMM_M256 // VHADDPS ymm, ymm, m256 // , VHADDPS_YMM_YMM_YMM // VHADDPS ymm, ymm, ymm // , VHSUBPD_XMM_XMM_M128 // VHSUBPD xmm, xmm, m128 // , VHSUBPD_XMM_XMM_XMM // VHSUBPD xmm, xmm, xmm // , VHSUBPD_YMM_YMM_M256 // VHSUBPD ymm, ymm, m256 // , VHSUBPD_YMM_YMM_YMM // VHSUBPD ymm, ymm, ymm // , VHSUBPS_XMM_XMM_M128 // VHSUBPS xmm, xmm, m128 // , VHSUBPS_XMM_XMM_XMM // VHSUBPS xmm, xmm, xmm // , VHSUBPS_YMM_YMM_M256 // VHSUBPS ymm, ymm, m256 // , VHSUBPS_YMM_YMM_YMM // VHSUBPS ymm, ymm, ymm // , VINSERTF128_YMM_YMM_M128_IMM8 // VINSERTF128 ymm, ymm, m128, imm8 // , VINSERTF128_YMM_YMM_XMM_IMM8 // VINSERTF128 ymm, ymm, xmm, imm8 // , VINSERTI128_YMM_YMM_M128_IMM8 // VINSERTI128 ymm, ymm, m128, imm8 // , VINSERTI128_YMM_YMM_XMM_IMM8 // VINSERTI128 ymm, ymm, xmm, imm8 // , VINSERTPS_XMM_XMM_M32_IMM8 // VINSERTPS xmm, xmm, m32, imm8 // , VINSERTPS_XMM_XMM_XMM_IMM8 // VINSERTPS xmm, xmm, xmm, imm8 // , VLDDQU_XMM_M128 // VLDDQU xmm, m128 // , VLDDQU_YMM_M256 // VLDDQU ymm, m256 // , VLDMXCSR_M32 // VLDMXCSR m32 // , VMASKMOVDQU_XMM_XMM // VMASKMOVDQU xmm, xmm // , VMASKMOVPD_M128_XMM_XMM // VMASKMOVPD m128, xmm, xmm // , VMASKMOVPD_M256_YMM_YMM // VMASKMOVPD m256, ymm, ymm // , VMASKMOVPD_XMM_XMM_M128 // VMASKMOVPD xmm, xmm, m128 // , VMASKMOVPD_YMM_YMM_M256 // VMASKMOVPD ymm, ymm, m256 // , VMASKMOVPS_M128_XMM_XMM // VMASKMOVPS m128, xmm, xmm // , VMASKMOVPS_M256_YMM_YMM // VMASKMOVPS m256, ymm, ymm // , VMASKMOVPS_XMM_XMM_M128 // VMASKMOVPS xmm, xmm, m128 // , VMASKMOVPS_YMM_YMM_M256 // VMASKMOVPS ymm, ymm, m256 // , VMAXPD_XMM_XMM_M128 // VMAXPD xmm, xmm, m128 // , VMAXPD_XMM_XMM_XMM // VMAXPD xmm, xmm, xmm // , VMAXPD_YMM_YMM_M256 // VMAXPD ymm, ymm, m256 , VMAXPD_YMM_YMM_YMM // VMAXPD ymm, ymm, ymm // , VMAXPS_XMM_XMM_M128 // VMAXPS xmm, xmm, m128 // , VMAXPS_XMM_XMM_XMM // VMAXPS xmm, xmm, xmm // , VMAXPS_YMM_YMM_M256 // VMAXPS ymm, ymm, m256 , VMAXPS_YMM_YMM_YMM // VMAXPS ymm, ymm, ymm // , VMAXSD_XMM_XMM_M64 // VMAXSD xmm, xmm, m64 // , VMAXSD_XMM_XMM_XMM // VMAXSD xmm, xmm, xmm // , VMAXSS_XMM_XMM_M32 // VMAXSS xmm, xmm, m32 // , VMAXSS_XMM_XMM_XMM // VMAXSS xmm, xmm, xmm // , VMINPD_XMM_XMM_M128 // VMINPD xmm, xmm, m128 // , VMINPD_XMM_XMM_XMM // VMINPD xmm, xmm, xmm // , VMINPD_YMM_YMM_M256 // VMINPD ymm, ymm, m256 , VMINPD_YMM_YMM_YMM // VMINPD ymm, ymm, ymm // , VMINPS_XMM_XMM_M128 // VMINPS xmm, xmm, m128 // , VMINPS_XMM_XMM_XMM // VMINPS xmm, xmm, xmm // , VMINPS_YMM_YMM_M256 // VMINPS ymm, ymm, m256 , VMINPS_YMM_YMM_YMM // VMINPS ymm, ymm, ymm // , VMINSD_XMM_XMM_M64 // VMINSD xmm, xmm, m64 // , VMINSD_XMM_XMM_XMM // VMINSD xmm, xmm, xmm // , VMINSS_XMM_XMM_M32 // VMINSS xmm, xmm, m32 // , VMINSS_XMM_XMM_XMM // VMINSS xmm, xmm, xmm // , VMOVAPD_M128_XMM // VMOVAPD m128, xmm // , VMOVAPD_M256_YMM // VMOVAPD m256, ymm // , VMOVAPD_XMM_M128 // VMOVAPD xmm, m128 // , VMOVAPD_XMM_XMM // VMOVAPD xmm, xmm // , VMOVAPD_YMM_M256 // VMOVAPD ymm, m256 // , VMOVAPD_YMM_YMM // VMOVAPD ymm, ymm // , VMOVAPS_M128_XMM // VMOVAPS m128, xmm // , VMOVAPS_M256_YMM // VMOVAPS m256, ymm // , VMOVAPS_XMM_M128 // VMOVAPS xmm, m128 // , VMOVAPS_XMM_XMM // VMOVAPS xmm, xmm // , VMOVAPS_YMM_M256 // VMOVAPS ymm, m256 // , VMOVAPS_YMM_YMM // VMOVAPS ymm, ymm // , VMOVD_M32_XMM // VMOVD m32, xmm // , VMOVD_R32_XMM // VMOVD r32, xmm // , VMOVD_XMM_M32 // VMOVD xmm, m32 // , VMOVD_XMM_R32 // VMOVD xmm, r32 // , VMOVDDUP_XMM_M64 // VMOVDDUP xmm, m64 // , VMOVDDUP_XMM_XMM // VMOVDDUP xmm, xmm // , VMOVDDUP_YMM_M256 // VMOVDDUP ymm, m256 // , VMOVDDUP_YMM_YMM // VMOVDDUP ymm, ymm // , VMOVDQA_M128_XMM // VMOVDQA m128, xmm // , VMOVDQA_M256_YMM // VMOVDQA m256, ymm // , VMOVDQA_XMM_M128 // VMOVDQA xmm, m128 // , VMOVDQA_XMM_XMM // VMOVDQA xmm, xmm // , VMOVDQA_YMM_M256 // VMOVDQA ymm, m256 // , VMOVDQA_YMM_YMM // VMOVDQA ymm, ymm // , VMOVDQU_M128_XMM // VMOVDQU m128, xmm // , VMOVDQU_M256_YMM // VMOVDQU m256, ymm // , VMOVDQU_XMM_M128 // VMOVDQU xmm, m128 // , VMOVDQU_XMM_XMM // VMOVDQU xmm, xmm // , VMOVDQU_YMM_M256 // VMOVDQU ymm, m256 // , VMOVDQU_YMM_YMM // VMOVDQU ymm, ymm // , VMOVHLPS_XMM_XMM_XMM // VMOVHLPS xmm, xmm, xmm // , VMOVHPD_M64_XMM // VMOVHPD m64, xmm // , VMOVHPD_XMM_XMM_M64 // VMOVHPD xmm, xmm, m64 // , VMOVHPS_M64_XMM // VMOVHPS m64, xmm // , VMOVHPS_XMM_XMM_M64 // VMOVHPS xmm, xmm, m64 // , VMOVLHPS_XMM_XMM_XMM // VMOVLHPS xmm, xmm, xmm // , VMOVLPD_M64_XMM // VMOVLPD m64, xmm // , VMOVLPD_XMM_XMM_M64 // VMOVLPD xmm, xmm, m64 // , VMOVLPS_M64_XMM // VMOVLPS m64, xmm // , VMOVLPS_XMM_XMM_M64 // VMOVLPS xmm, xmm, m64 // , VMOVMSKPD_R32_XMM // VMOVMSKPD r32, xmm // , VMOVMSKPD_R32_YMM // VMOVMSKPD r32, ymm // , VMOVMSKPD_R64_XMM // VMOVMSKPD r64, xmm // , VMOVMSKPD_R64_YMM // VMOVMSKPD r64, ymm // , VMOVMSKPS_R32_XMM // VMOVMSKPS r32, xmm // , VMOVMSKPS_R32_YMM // VMOVMSKPS r32, ymm // , VMOVMSKPS_R64_XMM // VMOVMSKPS r64, xmm // , VMOVMSKPS_R64_YMM // VMOVMSKPS r64, ymm // , VMOVNTDQ_M128_XMM // VMOVNTDQ m128, xmm // , VMOVNTDQA_XMM_M128 // VMOVNTDQA xmm, m128 // , VMOVNTDQA_YMM_M256 // VMOVNTDQA ymm, m256 // , VMOVNTPD_M128_XMM // VMOVNTPD m128, xmm // , VMOVNTPD_M256_YMM // VMOVNTPD m256, ymm // , VMOVNTPS_M128_XMM // VMOVNTPS m128, xmm // , VMOVNTPS_M256_YMM // VMOVNTPS m256, ymm // , VMOVQ_M64_XMM // VMOVQ m64, xmm // , VMOVQ_R64_XMM // VMOVQ r64, xmm // , VMOVQ_XMM_M64 // VMOVQ xmm, m64 // , VMOVQ_XMM_R64 // VMOVQ xmm, r64 // , VMOVQ_XMM_XMM // VMOVQ xmm, xmm // , VMOVSD_M64_XMM // VMOVSD m64, xmm // , VMOVSD_XMM_M64 // VMOVSD xmm, m64 // , VMOVSD_XMM_XMM_XMM // VMOVSD xmm, xmm, xmm // , VMOVSHDUP_XMM_M128 // VMOVSHDUP xmm, m128 // , VMOVSHDUP_XMM_XMM // VMOVSHDUP xmm, xmm // , VMOVSHDUP_YMM_M256 // VMOVSHDUP ymm, m256 // , VMOVSHDUP_YMM_YMM // VMOVSHDUP ymm, ymm // , VMOVSLDUP_XMM_M128 // VMOVSLDUP xmm, m128 // , VMOVSLDUP_XMM_XMM // VMOVSLDUP xmm, xmm // , VMOVSLDUP_YMM_M256 // VMOVSLDUP ymm, m256 // , VMOVSLDUP_YMM_YMM // VMOVSLDUP ymm, ymm // , VMOVSS_M32_XMM // VMOVSS m32, xmm // , VMOVSS_XMM_M32 // VMOVSS xmm, m32 // , VMOVSS_XMM_XMM_XMM // VMOVSS xmm, xmm, xmm // , VMOVUPD_M128_XMM // VMOVUPD m128, xmm // , VMOVUPD_M256_YMM // VMOVUPD m256, ymm // , VMOVUPD_XMM_M128 // VMOVUPD xmm, m128 // , VMOVUPD_XMM_XMM // VMOVUPD xmm, xmm // , VMOVUPD_YMM_M256 // VMOVUPD ymm, m256 // , VMOVUPD_YMM_YMM // VMOVUPD ymm, ymm // , VMOVUPS_M128_XMM // VMOVUPS m128, xmm // , VMOVUPS_M256_YMM // VMOVUPS m256, ymm // , VMOVUPS_XMM_M128 // VMOVUPS xmm, m128 // , VMOVUPS_XMM_XMM // VMOVUPS xmm, xmm // , VMOVUPS_YMM_M256 // VMOVUPS ymm, m256 // , VMOVUPS_YMM_YMM // VMOVUPS ymm, ymm // , VMPSADBW_XMM_XMM_M128_IMM8 // VMPSADBW xmm, xmm, m128, imm8 // , VMPSADBW_XMM_XMM_XMM_IMM8 // VMPSADBW xmm, xmm, xmm, imm8 // , VMPSADBW_YMM_YMM_M256_IMM8 // VMPSADBW ymm, ymm, m256, imm8 // , VMPSADBW_YMM_YMM_YMM_IMM8 // VMPSADBW ymm, ymm, ymm, imm8 // , VMULPD_XMM_XMM_M128 // VMULPD xmm, xmm, m128 // , VMULPD_XMM_XMM_XMM // VMULPD xmm, xmm, xmm // , VMULPD_YMM_YMM_M256 // VMULPD ymm, ymm, m256 , VMULPD_YMM_YMM_YMM // VMULPD ymm, ymm, ymm // , VMULPS_XMM_XMM_M128 // VMULPS xmm, xmm, m128 // , VMULPS_XMM_XMM_XMM // VMULPS xmm, xmm, xmm // , VMULPS_YMM_YMM_M256 // VMULPS ymm, ymm, m256 , VMULPS_YMM_YMM_YMM // VMULPS ymm, ymm, ymm // , VMULSD_XMM_XMM_M64 // VMULSD xmm, xmm, m64 // , VMULSD_XMM_XMM_XMM // VMULSD xmm, xmm, xmm // , VMULSS_XMM_XMM_M32 // VMULSS xmm, xmm, m32 // , VMULSS_XMM_XMM_XMM // VMULSS xmm, xmm, xmm // , VORPD_XMM_XMM_M128 // VORPD xmm, xmm, m128 // , VORPD_XMM_XMM_XMM // VORPD xmm, xmm, xmm // , VORPD_YMM_YMM_M256 // VORPD ymm, ymm, m256 // , VORPD_YMM_YMM_YMM // VORPD ymm, ymm, ymm // , VORPS_XMM_XMM_M128 // VORPS xmm, xmm, m128 // , VORPS_XMM_XMM_XMM // VORPS xmm, xmm, xmm // , VORPS_YMM_YMM_M256 // VORPS ymm, ymm, m256 // , VORPS_YMM_YMM_YMM // VORPS ymm, ymm, ymm // , VPABSB_XMM_M128 // VPABSB xmm, m128 // , VPABSB_XMM_XMM // VPABSB xmm, xmm // , VPABSB_YMM_M256 // VPABSB ymm, m256 // , VPABSB_YMM_YMM // VPABSB ymm, ymm // , VPABSD_XMM_M128 // VPABSD xmm, m128 // , VPABSD_XMM_XMM // VPABSD xmm, xmm // , VPABSD_YMM_M256 // VPABSD ymm, m256 // , VPABSD_YMM_YMM // VPABSD ymm, ymm // , VPABSW_XMM_M128 // VPABSW xmm, m128 // , VPABSW_XMM_XMM // VPABSW xmm, xmm // , VPABSW_YMM_M256 // VPABSW ymm, m256 // , VPABSW_YMM_YMM // VPABSW ymm, ymm // , VPACKSSDW_XMM_XMM_M128 // VPACKSSDW xmm, xmm, m128 // , VPACKSSDW_XMM_XMM_XMM // VPACKSSDW xmm, xmm, xmm // , VPACKSSDW_YMM_YMM_M256 // VPACKSSDW ymm, ymm, m256 // , VPACKSSDW_YMM_YMM_YMM // VPACKSSDW ymm, ymm, ymm // , VPACKSSWB_XMM_XMM_M128 // VPACKSSWB xmm, xmm, m128 // , VPACKSSWB_XMM_XMM_XMM // VPACKSSWB xmm, xmm, xmm // , VPACKSSWB_YMM_YMM_M256 // VPACKSSWB ymm, ymm, m256 // , VPACKSSWB_YMM_YMM_YMM // VPACKSSWB ymm, ymm, ymm // , VPACKUSDW_XMM_XMM_M128 // VPACKUSDW xmm, xmm, m128 // , VPACKUSDW_XMM_XMM_XMM // VPACKUSDW xmm, xmm, xmm // , VPACKUSDW_YMM_YMM_M256 // VPACKUSDW ymm, ymm, m256 // , VPACKUSDW_YMM_YMM_YMM // VPACKUSDW ymm, ymm, ymm // , VPACKUSWB_XMM_XMM_M128 // VPACKUSWB xmm, xmm, m128 // , VPACKUSWB_XMM_XMM_XMM // VPACKUSWB xmm, xmm, xmm // , VPACKUSWB_YMM_YMM_M256 // VPACKUSWB ymm, ymm, m256 // , VPACKUSWB_YMM_YMM_YMM // VPACKUSWB ymm, ymm, ymm // , VPADDB_XMM_XMM_M128 // VPADDB xmm, xmm, m128 // , VPADDB_XMM_XMM_XMM // VPADDB xmm, xmm, xmm // , VPADDB_YMM_YMM_M256 // VPADDB ymm, ymm, m256 // , VPADDB_YMM_YMM_YMM // VPADDB ymm, ymm, ymm // , VPADDD_XMM_XMM_M128 // VPADDD xmm, xmm, m128 // , VPADDD_XMM_XMM_XMM // VPADDD xmm, xmm, xmm // , VPADDD_YMM_YMM_M256 // VPADDD ymm, ymm, m256 // , VPADDD_YMM_YMM_YMM // VPADDD ymm, ymm, ymm // , VPADDQ_XMM_XMM_M128 // VPADDQ xmm, xmm, m128 // , VPADDQ_XMM_XMM_XMM // VPADDQ xmm, xmm, xmm // , VPADDQ_YMM_YMM_M256 // VPADDQ ymm, ymm, m256 // , VPADDQ_YMM_YMM_YMM // VPADDQ ymm, ymm, ymm // , VPADDSB_XMM_XMM_M128 // VPADDSB xmm, xmm, m128 // , VPADDSB_XMM_XMM_XMM // VPADDSB xmm, xmm, xmm // , VPADDSB_YMM_YMM_M256 // VPADDSB ymm, ymm, m256 // , VPADDSB_YMM_YMM_YMM // VPADDSB ymm, ymm, ymm // , VPADDSW_XMM_XMM_M128 // VPADDSW xmm, xmm, m128 // , VPADDSW_XMM_XMM_XMM // VPADDSW xmm, xmm, xmm // , VPADDSW_YMM_YMM_M256 // VPADDSW ymm, ymm, m256 // , VPADDSW_YMM_YMM_YMM // VPADDSW ymm, ymm, ymm // , VPADDUSB_XMM_XMM_M128 // VPADDUSB xmm, xmm, m128 // , VPADDUSB_XMM_XMM_XMM // VPADDUSB xmm, xmm, xmm // , VPADDUSB_YMM_YMM_M256 // VPADDUSB ymm, ymm, m256 // , VPADDUSB_YMM_YMM_YMM // VPADDUSB ymm, ymm, ymm // , VPADDUSW_XMM_XMM_M128 // VPADDUSW xmm, xmm, m128 // , VPADDUSW_XMM_XMM_XMM // VPADDUSW xmm, xmm, xmm // , VPADDUSW_YMM_YMM_M256 // VPADDUSW ymm, ymm, m256 // , VPADDUSW_YMM_YMM_YMM // VPADDUSW ymm, ymm, ymm // , VPADDW_XMM_XMM_M128 // VPADDW xmm, xmm, m128 // , VPADDW_XMM_XMM_XMM // VPADDW xmm, xmm, xmm // , VPADDW_YMM_YMM_M256 // VPADDW ymm, ymm, m256 // , VPADDW_YMM_YMM_YMM // VPADDW ymm, ymm, ymm // , VPALIGNR_XMM_XMM_M128_IMM8 // VPALIGNR xmm, xmm, m128, imm8 // , VPALIGNR_XMM_XMM_XMM_IMM8 // VPALIGNR xmm, xmm, xmm, imm8 // , VPALIGNR_YMM_YMM_M256_IMM8 // VPALIGNR ymm, ymm, m256, imm8 // , VPALIGNR_YMM_YMM_YMM_IMM8 // VPALIGNR ymm, ymm, ymm, imm8 // , VPAND_XMM_XMM_M128 // VPAND xmm, xmm, m128 // , VPAND_XMM_XMM_XMM // VPAND xmm, xmm, xmm // , VPAND_YMM_YMM_M256 // VPAND ymm, ymm, m256 // , VPAND_YMM_YMM_YMM // VPAND ymm, ymm, ymm // , VPANDN_XMM_XMM_M128 // VPANDN xmm, xmm, m128 // , VPANDN_XMM_XMM_XMM // VPANDN xmm, xmm, xmm // , VPANDN_YMM_YMM_M256 // VPANDN ymm, ymm, m256 // , VPANDN_YMM_YMM_YMM // VPANDN ymm, ymm, ymm // , VPAVGB_XMM_XMM_M128 // VPAVGB xmm, xmm, m128 // , VPAVGB_XMM_XMM_XMM // VPAVGB xmm, xmm, xmm // , VPAVGB_YMM_YMM_M256 // VPAVGB ymm, ymm, m256 // , VPAVGB_YMM_YMM_YMM // VPAVGB ymm, ymm, ymm // , VPAVGW_XMM_XMM_M128 // VPAVGW xmm, xmm, m128 // , VPAVGW_XMM_XMM_XMM // VPAVGW xmm, xmm, xmm // , VPAVGW_YMM_YMM_M256 // VPAVGW ymm, ymm, m256 // , VPAVGW_YMM_YMM_YMM // VPAVGW ymm, ymm, ymm // , VPBLENDD_XMM_XMM_M128_IMM8 // VPBLENDD xmm, xmm, m128, imm8 // , VPBLENDD_XMM_XMM_XMM_IMM8 // VPBLENDD xmm, xmm, xmm, imm8 // , VPBLENDD_YMM_YMM_M256_IMM8 // VPBLENDD ymm, ymm, m256, imm8 // , VPBLENDD_YMM_YMM_YMM_IMM8 // VPBLENDD ymm, ymm, ymm, imm8 // , VPBLENDVB_XMM_XMM_M128_XMM // VPBLENDVB xmm, xmm, m128, xmm // , VPBLENDVB_XMM_XMM_XMM_XMM // VPBLENDVB xmm, xmm, xmm, xmm // , VPBLENDVB_YMM_YMM_M256_YMM // VPBLENDVB ymm, ymm, m256, ymm // , VPBLENDVB_YMM_YMM_YMM_YMM // VPBLENDVB ymm, ymm, ymm, ymm // , VPBLENDW_XMM_XMM_M128_IMM8 // VPBLENDW xmm, xmm, m128, imm8 // , VPBLENDW_XMM_XMM_XMM_IMM8 // VPBLENDW xmm, xmm, xmm, imm8 // , VPBLENDW_YMM_YMM_M256_IMM8 // VPBLENDW ymm, ymm, m256, imm8 // , VPBLENDW_YMM_YMM_YMM_IMM8 // VPBLENDW ymm, ymm, ymm, imm8 // , VPBROADCASTB_XMM_M8 // VPBROADCASTB xmm, m8 // , VPBROADCASTB_XMM_XMM // VPBROADCASTB xmm, xmm // , VPBROADCASTB_YMM_M8 // VPBROADCASTB ymm, m8 // , VPBROADCASTB_YMM_XMM // VPBROADCASTB ymm, xmm // , VPBROADCASTD_XMM_M32 // VPBROADCASTD xmm, m32 // , VPBROADCASTD_XMM_XMM // VPBROADCASTD xmm, xmm // , VPBROADCASTD_YMM_M32 // VPBROADCASTD ymm, m32 // , VPBROADCASTD_YMM_XMM // VPBROADCASTD ymm, xmm // , VPBROADCASTQ_XMM_M64 // VPBROADCASTQ xmm, m64 // , VPBROADCASTQ_XMM_XMM // VPBROADCASTQ xmm, xmm // , VPBROADCASTQ_YMM_M64 // VPBROADCASTQ ymm, m64 // , VPBROADCASTQ_YMM_XMM // VPBROADCASTQ ymm, xmm // , VPBROADCASTW_XMM_M16 // VPBROADCASTW xmm, m16 // , VPBROADCASTW_XMM_XMM // VPBROADCASTW xmm, xmm // , VPBROADCASTW_YMM_M16 // VPBROADCASTW ymm, m16 // , VPBROADCASTW_YMM_XMM // VPBROADCASTW ymm, xmm // , VPCLMULQDQ_XMM_XMM_M128_IMM8 // VPCLMULQDQ xmm, xmm, m128, imm8 // , VPCLMULQDQ_XMM_XMM_XMM_IMM8 // VPCLMULQDQ xmm, xmm, xmm, imm8 // , VPCMPEQB_XMM_XMM_M128 // VPCMPEQB xmm, xmm, m128 // , VPCMPEQB_XMM_XMM_XMM // VPCMPEQB xmm, xmm, xmm // , VPCMPEQB_YMM_YMM_M256 // VPCMPEQB ymm, ymm, m256 // , VPCMPEQB_YMM_YMM_YMM // VPCMPEQB ymm, ymm, ymm // , VPCMPEQD_XMM_XMM_M128 // VPCMPEQD xmm, xmm, m128 // , VPCMPEQD_XMM_XMM_XMM // VPCMPEQD xmm, xmm, xmm // , VPCMPEQD_YMM_YMM_M256 // VPCMPEQD ymm, ymm, m256 // , VPCMPEQD_YMM_YMM_YMM // VPCMPEQD ymm, ymm, ymm // , VPCMPEQQ_XMM_XMM_M128 // VPCMPEQQ xmm, xmm, m128 // , VPCMPEQQ_XMM_XMM_XMM // VPCMPEQQ xmm, xmm, xmm // , VPCMPEQQ_YMM_YMM_M256 // VPCMPEQQ ymm, ymm, m256 // , VPCMPEQQ_YMM_YMM_YMM // VPCMPEQQ ymm, ymm, ymm // , VPCMPEQW_XMM_XMM_M128 // VPCMPEQW xmm, xmm, m128 // , VPCMPEQW_XMM_XMM_XMM // VPCMPEQW xmm, xmm, xmm // , VPCMPEQW_YMM_YMM_M256 // VPCMPEQW ymm, ymm, m256 // , VPCMPEQW_YMM_YMM_YMM // VPCMPEQW ymm, ymm, ymm // , VPCMPESTRI_XMM_M128_IMM8 // VPCMPESTRI xmm, m128, imm8 // , VPCMPESTRI_XMM_XMM_IMM8 // VPCMPESTRI xmm, xmm, imm8 // , VPCMPESTRM_XMM_M128_IMM8 // VPCMPESTRM xmm, m128, imm8 // , VPCMPESTRM_XMM_XMM_IMM8 // VPCMPESTRM xmm, xmm, imm8 // , VPCMPGTB_XMM_XMM_M128 // VPCMPGTB xmm, xmm, m128 // , VPCMPGTB_XMM_XMM_XMM // VPCMPGTB xmm, xmm, xmm // , VPCMPGTB_YMM_YMM_M256 // VPCMPGTB ymm, ymm, m256 // , VPCMPGTB_YMM_YMM_YMM // VPCMPGTB ymm, ymm, ymm // , VPCMPGTD_XMM_XMM_M128 // VPCMPGTD xmm, xmm, m128 // , VPCMPGTD_XMM_XMM_XMM // VPCMPGTD xmm, xmm, xmm // , VPCMPGTD_YMM_YMM_M256 // VPCMPGTD ymm, ymm, m256 // , VPCMPGTD_YMM_YMM_YMM // VPCMPGTD ymm, ymm, ymm // , VPCMPGTQ_XMM_XMM_M128 // VPCMPGTQ xmm, xmm, m128 // , VPCMPGTQ_XMM_XMM_XMM // VPCMPGTQ xmm, xmm, xmm // , VPCMPGTQ_YMM_YMM_M256 // VPCMPGTQ ymm, ymm, m256 // , VPCMPGTQ_YMM_YMM_YMM // VPCMPGTQ ymm, ymm, ymm // , VPCMPGTW_XMM_XMM_M128 // VPCMPGTW xmm, xmm, m128 // , VPCMPGTW_XMM_XMM_XMM // VPCMPGTW xmm, xmm, xmm // , VPCMPGTW_YMM_YMM_M256 // VPCMPGTW ymm, ymm, m256 // , VPCMPGTW_YMM_YMM_YMM // VPCMPGTW ymm, ymm, ymm // , VPCMPISTRI_XMM_M128_IMM8 // VPCMPISTRI xmm, m128, imm8 // , VPCMPISTRI_XMM_XMM_IMM8 // VPCMPISTRI xmm, xmm, imm8 // , VPCMPISTRM_XMM_M128_IMM8 // VPCMPISTRM xmm, m128, imm8 // , VPCMPISTRM_XMM_XMM_IMM8 // VPCMPISTRM xmm, xmm, imm8 // , VPERM2F128_YMM_YMM_M256_IMM8 // VPERM2F128 ymm, ymm, m256, imm8 // , VPERM2F128_YMM_YMM_YMM_IMM8 // VPERM2F128 ymm, ymm, ymm, imm8 // , VPERM2I128_YMM_YMM_M256_IMM8 // VPERM2I128 ymm, ymm, m256, imm8 // , VPERM2I128_YMM_YMM_YMM_IMM8 // VPERM2I128 ymm, ymm, ymm, imm8 // , VPERMD_YMM_YMM_M256 // VPERMD ymm, ymm, m256 // , VPERMD_YMM_YMM_YMM // VPERMD ymm, ymm, ymm // , VPERMILPD_XMM_M128_IMM8 // VPERMILPD xmm, m128, imm8 // , VPERMILPD_XMM_XMM_IMM8 // VPERMILPD xmm, xmm, imm8 // , VPERMILPD_XMM_XMM_M128 // VPERMILPD xmm, xmm, m128 // , VPERMILPD_XMM_XMM_XMM // VPERMILPD xmm, xmm, xmm // , VPERMILPD_YMM_M256_IMM8 // VPERMILPD ymm, m256, imm8 // , VPERMILPD_YMM_YMM_IMM8 // VPERMILPD ymm, ymm, imm8 // , VPERMILPD_YMM_YMM_M256 // VPERMILPD ymm, ymm, m256 // , VPERMILPD_YMM_YMM_YMM // VPERMILPD ymm, ymm, ymm // , VPERMILPS_XMM_M128_IMM8 // VPERMILPS xmm, m128, imm8 // , VPERMILPS_XMM_XMM_IMM8 // VPERMILPS xmm, xmm, imm8 // , VPERMILPS_XMM_XMM_M128 // VPERMILPS xmm, xmm, m128 // , VPERMILPS_XMM_XMM_XMM // VPERMILPS xmm, xmm, xmm // , VPERMILPS_YMM_M256_IMM8 // VPERMILPS ymm, m256, imm8 // , VPERMILPS_YMM_YMM_IMM8 // VPERMILPS ymm, ymm, imm8 // , VPERMILPS_YMM_YMM_M256 // VPERMILPS ymm, ymm, m256 // , VPERMILPS_YMM_YMM_YMM // VPERMILPS ymm, ymm, ymm // , VPERMPD_YMM_M256_IMM8 // VPERMPD ymm, m256, imm8 // , VPERMPD_YMM_YMM_IMM8 // VPERMPD ymm, ymm, imm8 // , VPERMPS_YMM_YMM_M256 // VPERMPS ymm, ymm, m256 // , VPERMPS_YMM_YMM_YMM // VPERMPS ymm, ymm, ymm // , VPERMQ_YMM_M256_IMM8 // VPERMQ ymm, m256, imm8 // , VPERMQ_YMM_YMM_IMM8 // VPERMQ ymm, ymm, imm8 // , VPEXTRB_M8_XMM_IMM8 // VPEXTRB m8, xmm, imm8 // , VPEXTRB_R32_XMM_IMM8 // VPEXTRB r32, xmm, imm8 // , VPEXTRB_R64_XMM_IMM8 // VPEXTRB r64, xmm, imm8 // , VPEXTRD_M32_XMM_IMM8 // VPEXTRD m32, xmm, imm8 // , VPEXTRD_R32_XMM_IMM8 // VPEXTRD r32, xmm, imm8 // , VPEXTRQ_M64_XMM_IMM8 // VPEXTRQ m64, xmm, imm8 // , VPEXTRQ_R64_XMM_IMM8 // VPEXTRQ r64, xmm, imm8 // , VPEXTRW_M16_XMM_IMM8 // VPEXTRW m16, xmm, imm8 // , VPEXTRW_R32_XMM_IMM8 // VPEXTRW r32, xmm, imm8 // , VPEXTRW_R64_XMM_IMM8 // VPEXTRW r64, xmm, imm8 // , VPGATHERDD_XMM_M32_XMM // VPGATHERDD xmm, m32, xmm // , VPGATHERDD_YMM_M32_YMM // VPGATHERDD ymm, m32, ymm // , VPGATHERDQ_XMM_M32_XMM // VPGATHERDQ xmm, m32, xmm // , VPGATHERDQ_YMM_M32_YMM // VPGATHERDQ ymm, m32, ymm // , VPGATHERQD_XMM_M64_XMM // VPGATHERQD xmm, m64, xmm // , VPGATHERQQ_XMM_M64_XMM // VPGATHERQQ xmm, m64, xmm // , VPGATHERQQ_YMM_M64_YMM // VPGATHERQQ ymm, m64, ymm // , VPHADDD_XMM_XMM_M128 // VPHADDD xmm, xmm, m128 // , VPHADDD_XMM_XMM_XMM // VPHADDD xmm, xmm, xmm // , VPHADDD_YMM_YMM_M256 // VPHADDD ymm, ymm, m256 // , VPHADDD_YMM_YMM_YMM // VPHADDD ymm, ymm, ymm // , VPHADDSW_XMM_XMM_M128 // VPHADDSW xmm, xmm, m128 // , VPHADDSW_XMM_XMM_XMM // VPHADDSW xmm, xmm, xmm // , VPHADDSW_YMM_YMM_M256 // VPHADDSW ymm, ymm, m256 // , VPHADDSW_YMM_YMM_YMM // VPHADDSW ymm, ymm, ymm // , VPHADDW_XMM_XMM_M128 // VPHADDW xmm, xmm, m128 // , VPHADDW_XMM_XMM_XMM // VPHADDW xmm, xmm, xmm // , VPHADDW_YMM_YMM_M256 // VPHADDW ymm, ymm, m256 // , VPHADDW_YMM_YMM_YMM // VPHADDW ymm, ymm, ymm // , VPHMINPOSUW_XMM_M128 // VPHMINPOSUW xmm, m128 // , VPHMINPOSUW_XMM_XMM // VPHMINPOSUW xmm, xmm // , VPHSUBD_XMM_XMM_M128 // VPHSUBD xmm, xmm, m128 // , VPHSUBD_XMM_XMM_XMM // VPHSUBD xmm, xmm, xmm // , VPHSUBD_YMM_YMM_M256 // VPHSUBD ymm, ymm, m256 // , VPHSUBD_YMM_YMM_YMM // VPHSUBD ymm, ymm, ymm // , VPHSUBSW_XMM_XMM_M128 // VPHSUBSW xmm, xmm, m128 // , VPHSUBSW_XMM_XMM_XMM // VPHSUBSW xmm, xmm, xmm // , VPHSUBSW_YMM_YMM_M256 // VPHSUBSW ymm, ymm, m256 // , VPHSUBSW_YMM_YMM_YMM // VPHSUBSW ymm, ymm, ymm // , VPHSUBW_XMM_XMM_M128 // VPHSUBW xmm, xmm, m128 // , VPHSUBW_XMM_XMM_XMM // VPHSUBW xmm, xmm, xmm // , VPHSUBW_YMM_YMM_M256 // VPHSUBW ymm, ymm, m256 // , VPHSUBW_YMM_YMM_YMM // VPHSUBW ymm, ymm, ymm // , VPINSRB_XMM_XMM_M8_IMM8 // VPINSRB xmm, xmm, m8, imm8 // , VPINSRB_XMM_XMM_R32_IMM8 // VPINSRB xmm, xmm, r32, imm8 // , VPINSRD_XMM_XMM_M32_IMM8 // VPINSRD xmm, xmm, m32, imm8 // , VPINSRD_XMM_XMM_R32_IMM8 // VPINSRD xmm, xmm, r32, imm8 // , VPINSRQ_XMM_XMM_M64_IMM8 // VPINSRQ xmm, xmm, m64, imm8 // , VPINSRQ_XMM_XMM_R64_IMM8 // VPINSRQ xmm, xmm, r64, imm8 // , VPINSRW_XMM_XMM_M16_IMM8 // VPINSRW xmm, xmm, m16, imm8 // , VPINSRW_XMM_XMM_R32_IMM8 // VPINSRW xmm, xmm, r32, imm8 // , VPMADDUBSW_XMM_XMM_M128 // VPMADDUBSW xmm, xmm, m128 // , VPMADDUBSW_XMM_XMM_XMM // VPMADDUBSW xmm, xmm, xmm // , VPMADDUBSW_YMM_YMM_M256 // VPMADDUBSW ymm, ymm, m256 // , VPMADDUBSW_YMM_YMM_YMM // VPMADDUBSW ymm, ymm, ymm // , VPMADDWD_XMM_XMM_M128 // VPMADDWD xmm, xmm, m128 // , VPMADDWD_XMM_XMM_XMM // VPMADDWD xmm, xmm, xmm // , VPMADDWD_YMM_YMM_M256 // VPMADDWD ymm, ymm, m256 // , VPMADDWD_YMM_YMM_YMM // VPMADDWD ymm, ymm, ymm // , VPMASKMOVD_M128_XMM_XMM // VPMASKMOVD m128, xmm, xmm // , VPMASKMOVD_M256_YMM_YMM // VPMASKMOVD m256, ymm, ymm // , VPMASKMOVD_XMM_XMM_M128 // VPMASKMOVD xmm, xmm, m128 // , VPMASKMOVD_YMM_YMM_M256 // VPMASKMOVD ymm, ymm, m256 // , VPMASKMOVQ_M128_XMM_XMM // VPMASKMOVQ m128, xmm, xmm // , VPMASKMOVQ_M256_YMM_YMM // VPMASKMOVQ m256, ymm, ymm // , VPMASKMOVQ_XMM_XMM_M128 // VPMASKMOVQ xmm, xmm, m128 // , VPMASKMOVQ_YMM_YMM_M256 // VPMASKMOVQ ymm, ymm, m256 // , VPMAXSB_XMM_XMM_M128 // VPMAXSB xmm, xmm, m128 // , VPMAXSB_XMM_XMM_XMM // VPMAXSB xmm, xmm, xmm // , VPMAXSB_YMM_YMM_M256 // VPMAXSB ymm, ymm, m256 // , VPMAXSB_YMM_YMM_YMM // VPMAXSB ymm, ymm, ymm // , VPMAXSD_XMM_XMM_M128 // VPMAXSD xmm, xmm, m128 // , VPMAXSD_XMM_XMM_XMM // VPMAXSD xmm, xmm, xmm // , VPMAXSD_YMM_YMM_M256 // VPMAXSD ymm, ymm, m256 // , VPMAXSD_YMM_YMM_YMM // VPMAXSD ymm, ymm, ymm // , VPMAXSW_XMM_XMM_M128 // VPMAXSW xmm, xmm, m128 // , VPMAXSW_XMM_XMM_XMM // VPMAXSW xmm, xmm, xmm // , VPMAXSW_YMM_YMM_M256 // VPMAXSW ymm, ymm, m256 // , VPMAXSW_YMM_YMM_YMM // VPMAXSW ymm, ymm, ymm // , VPMAXUB_XMM_XMM_M128 // VPMAXUB xmm, xmm, m128 // , VPMAXUB_XMM_XMM_XMM // VPMAXUB xmm, xmm, xmm // , VPMAXUB_YMM_YMM_M256 // VPMAXUB ymm, ymm, m256 // , VPMAXUB_YMM_YMM_YMM // VPMAXUB ymm, ymm, ymm // , VPMAXUD_XMM_XMM_M128 // VPMAXUD xmm, xmm, m128 // , VPMAXUD_XMM_XMM_XMM // VPMAXUD xmm, xmm, xmm // , VPMAXUD_YMM_YMM_M256 // VPMAXUD ymm, ymm, m256 // , VPMAXUD_YMM_YMM_YMM // VPMAXUD ymm, ymm, ymm // , VPMAXUW_XMM_XMM_M128 // VPMAXUW xmm, xmm, m128 // , VPMAXUW_XMM_XMM_XMM // VPMAXUW xmm, xmm, xmm // , VPMAXUW_YMM_YMM_M256 // VPMAXUW ymm, ymm, m256 // , VPMAXUW_YMM_YMM_YMM // VPMAXUW ymm, ymm, ymm // , VPMINSB_XMM_XMM_M128 // VPMINSB xmm, xmm, m128 // , VPMINSB_XMM_XMM_XMM // VPMINSB xmm, xmm, xmm // , VPMINSB_YMM_YMM_M256 // VPMINSB ymm, ymm, m256 // , VPMINSB_YMM_YMM_YMM // VPMINSB ymm, ymm, ymm // , VPMINSD_XMM_XMM_M128 // VPMINSD xmm, xmm, m128 // , VPMINSD_XMM_XMM_XMM // VPMINSD xmm, xmm, xmm // , VPMINSD_YMM_YMM_M256 // VPMINSD ymm, ymm, m256 // , VPMINSD_YMM_YMM_YMM // VPMINSD ymm, ymm, ymm // , VPMINSW_XMM_XMM_M128 // VPMINSW xmm, xmm, m128 // , VPMINSW_XMM_XMM_XMM // VPMINSW xmm, xmm, xmm // , VPMINUB_XMM_XMM_M128 // VPMINUB xmm, xmm, m128 // , VPMINUB_XMM_XMM_XMM // VPMINUB xmm, xmm, xmm // , VPMINUB_YMM_YMM_M256 // VPMINUB ymm, ymm, m256 // , VPMINUB_YMM_YMM_YMM // VPMINUB ymm, ymm, ymm // , VPMINUD_XMM_XMM_M128 // VPMINUD xmm, xmm, m128 // , VPMINUD_XMM_XMM_XMM // VPMINUD xmm, xmm, xmm // , VPMINUD_YMM_YMM_M256 // VPMINUD ymm, ymm, m256 // , VPMINUD_YMM_YMM_YMM // VPMINUD ymm, ymm, ymm // , VPMINUW_XMM_XMM_M128 // VPMINUW xmm, xmm, m128 // , VPMINUW_XMM_XMM_XMM // VPMINUW xmm, xmm, xmm // , VPMINUW_YMM_YMM_M256 // VPMINUW ymm, ymm, m256 // , VPMINUW_YMM_YMM_YMM // VPMINUW ymm, ymm, ymm // , VPMOVMSKB_R32_XMM // VPMOVMSKB r32, xmm // , VPMOVMSKB_R32_YMM // VPMOVMSKB r32, ymm // , VPMOVMSKB_R64_XMM // VPMOVMSKB r64, xmm // , VPMOVMSKB_R64_YMM // VPMOVMSKB r64, ymm // , VPMOVSXBD_XMM_M32 // VPMOVSXBD xmm, m32 // , VPMOVSXBD_XMM_XMM // VPMOVSXBD xmm, xmm // , VPMOVSXBD_YMM_M64 // VPMOVSXBD ymm, m64 // , VPMOVSXBD_YMM_XMM // VPMOVSXBD ymm, xmm // , VPMOVSXBQ_XMM_M16 // VPMOVSXBQ xmm, m16 // , VPMOVSXBQ_XMM_XMM // VPMOVSXBQ xmm, xmm // , VPMOVSXBQ_YMM_M32 // VPMOVSXBQ ymm, m32 // , VPMOVSXBQ_YMM_XMM // VPMOVSXBQ ymm, xmm // , VPMOVSXBW_XMM_M64 // VPMOVSXBW xmm, m64 // , VPMOVSXBW_XMM_XMM // VPMOVSXBW xmm, xmm // , VPMOVSXBW_YMM_M128 // VPMOVSXBW ymm, m128 // , VPMOVSXBW_YMM_XMM // VPMOVSXBW ymm, xmm // , VPMOVSXDQ_XMM_M64 // VPMOVSXDQ xmm, m64 // , VPMOVSXDQ_XMM_XMM // VPMOVSXDQ xmm, xmm // , VPMOVSXDQ_YMM_M128 // VPMOVSXDQ ymm, m128 // , VPMOVSXDQ_YMM_XMM // VPMOVSXDQ ymm, xmm // , VPMOVSXWD_XMM_M64 // VPMOVSXWD xmm, m64 // , VPMOVSXWD_XMM_XMM // VPMOVSXWD xmm, xmm // , VPMOVSXWD_YMM_M128 // VPMOVSXWD ymm, m128 // , VPMOVSXWD_YMM_XMM // VPMOVSXWD ymm, xmm // , VPMOVSXWQ_XMM_M32 // VPMOVSXWQ xmm, m32 // , VPMOVSXWQ_XMM_XMM // VPMOVSXWQ xmm, xmm // , VPMOVSXWQ_YMM_M64 // VPMOVSXWQ ymm, m64 // , VPMOVSXWQ_YMM_XMM // VPMOVSXWQ ymm, xmm // , VPMOVZXBD_XMM_M32 // VPMOVZXBD xmm, m32 // , VPMOVZXBD_XMM_XMM // VPMOVZXBD xmm, xmm // , VPMOVZXBD_YMM_M64 // VPMOVZXBD ymm, m64 // , VPMOVZXBD_YMM_XMM // VPMOVZXBD ymm, xmm // , VPMOVZXBQ_XMM_M16 // VPMOVZXBQ xmm, m16 // , VPMOVZXBQ_XMM_XMM // VPMOVZXBQ xmm, xmm // , VPMOVZXBQ_YMM_M32 // VPMOVZXBQ ymm, m32 // , VPMOVZXBQ_YMM_XMM // VPMOVZXBQ ymm, xmm // , VPMOVZXBW_XMM_M64 // VPMOVZXBW xmm, m64 // , VPMOVZXBW_XMM_XMM // VPMOVZXBW xmm, xmm // , VPMOVZXBW_YMM_M128 // VPMOVZXBW ymm, m128 // , VPMOVZXBW_YMM_XMM // VPMOVZXBW ymm, xmm // , VPMOVZXDQ_XMM_M64 // VPMOVZXDQ xmm, m64 // , VPMOVZXDQ_XMM_XMM // VPMOVZXDQ xmm, xmm // , VPMOVZXDQ_YMM_M128 // VPMOVZXDQ ymm, m128 // , VPMOVZXDQ_YMM_XMM // VPMOVZXDQ ymm, xmm // , VPMOVZXWD_XMM_M64 // VPMOVZXWD xmm, m64 // , VPMOVZXWD_XMM_XMM // VPMOVZXWD xmm, xmm // , VPMOVZXWD_YMM_M128 // VPMOVZXWD ymm, m128 // , VPMOVZXWD_YMM_XMM // VPMOVZXWD ymm, xmm // , VPMOVZXWQ_XMM_M32 // VPMOVZXWQ xmm, m32 // , VPMOVZXWQ_XMM_XMM // VPMOVZXWQ xmm, xmm // , VPMOVZXWQ_YMM_M64 // VPMOVZXWQ ymm, m64 // , VPMOVZXWQ_YMM_XMM // VPMOVZXWQ ymm, xmm // , VPMULDQ_XMM_XMM_M128 // VPMULDQ xmm, xmm, m128 // , VPMULDQ_XMM_XMM_XMM // VPMULDQ xmm, xmm, xmm // , VPMULDQ_YMM_YMM_M256 // VPMULDQ ymm, ymm, m256 // , VPMULDQ_YMM_YMM_YMM // VPMULDQ ymm, ymm, ymm // , VPMULHRSW_XMM_XMM_M128 // VPMULHRSW xmm, xmm, m128 // , VPMULHRSW_XMM_XMM_XMM // VPMULHRSW xmm, xmm, xmm // , VPMULHRSW_YMM_YMM_M256 // VPMULHRSW ymm, ymm, m256 // , VPMULHRSW_YMM_YMM_YMM // VPMULHRSW ymm, ymm, ymm // , VPMULHUW_XMM_XMM_M128 // VPMULHUW xmm, xmm, m128 // , VPMULHUW_XMM_XMM_XMM // VPMULHUW xmm, xmm, xmm // , VPMULHUW_YMM_YMM_M256 // VPMULHUW ymm, ymm, m256 // , VPMULHUW_YMM_YMM_YMM // VPMULHUW ymm, ymm, ymm // , VPMULHW_XMM_XMM_M128 // VPMULHW xmm, xmm, m128 // , VPMULHW_XMM_XMM_XMM // VPMULHW xmm, xmm, xmm // , VPMULHW_YMM_YMM_M256 // VPMULHW ymm, ymm, m256 // , VPMULHW_YMM_YMM_YMM // VPMULHW ymm, ymm, ymm // , VPMULLD_XMM_XMM_M128 // VPMULLD xmm, xmm, m128 // , VPMULLD_XMM_XMM_XMM // VPMULLD xmm, xmm, xmm // , VPMULLD_YMM_YMM_M256 // VPMULLD ymm, ymm, m256 // , VPMULLD_YMM_YMM_YMM // VPMULLD ymm, ymm, ymm // , VPMULLW_XMM_XMM_M128 // VPMULLW xmm, xmm, m128 // , VPMULLW_XMM_XMM_XMM // VPMULLW xmm, xmm, xmm // , VPMULLW_YMM_YMM_M256 // VPMULLW ymm, ymm, m256 // , VPMULLW_YMM_YMM_YMM // VPMULLW ymm, ymm, ymm // , VPMULUDQ_XMM_XMM_M128 // VPMULUDQ xmm, xmm, m128 // , VPMULUDQ_XMM_XMM_XMM // VPMULUDQ xmm, xmm, xmm // , VPMULUDQ_YMM_YMM_M256 // VPMULUDQ ymm, ymm, m256 // , VPMULUDQ_YMM_YMM_YMM // VPMULUDQ ymm, ymm, ymm // , VPOR_XMM_XMM_M128 // VPOR xmm, xmm, m128 // , VPOR_XMM_XMM_XMM // VPOR xmm, xmm, xmm // , VPOR_YMM_YMM_M256 // VPOR ymm, ymm, m256 // , VPOR_YMM_YMM_YMM // VPOR ymm, ymm, ymm // , VPSADBW_XMM_XMM_M128 // VPSADBW xmm, xmm, m128 // , VPSADBW_XMM_XMM_XMM // VPSADBW xmm, xmm, xmm // , VPSADBW_YMM_YMM_M256 // VPSADBW ymm, ymm, m256 // , VPSADBW_YMM_YMM_YMM // VPSADBW ymm, ymm, ymm // , VPSHUFB_XMM_XMM_M128 // VPSHUFB xmm, xmm, m128 // , VPSHUFB_XMM_XMM_XMM // VPSHUFB xmm, xmm, xmm // , VPSHUFB_YMM_YMM_M256 // VPSHUFB ymm, ymm, m256 // , VPSHUFB_YMM_YMM_YMM // VPSHUFB ymm, ymm, ymm // , VPSHUFD_XMM_M128_IMM8 // VPSHUFD xmm, m128, imm8 // , VPSHUFD_XMM_XMM_IMM8 // VPSHUFD xmm, xmm, imm8 // , VPSHUFD_YMM_M256_IMM8 // VPSHUFD ymm, m256, imm8 // , VPSHUFD_YMM_YMM_IMM8 // VPSHUFD ymm, ymm, imm8 // , VPSHUFHW_XMM_M128_IMM8 // VPSHUFHW xmm, m128, imm8 // , VPSHUFHW_XMM_XMM_IMM8 // VPSHUFHW xmm, xmm, imm8 // , VPSHUFHW_YMM_M256_IMM8 // VPSHUFHW ymm, m256, imm8 // , VPSHUFHW_YMM_YMM_IMM8 // VPSHUFHW ymm, ymm, imm8 // , VPSHUFLW_XMM_M128_IMM8 // VPSHUFLW xmm, m128, imm8 // , VPSHUFLW_XMM_XMM_IMM8 // VPSHUFLW xmm, xmm, imm8 // , VPSHUFLW_YMM_M256_IMM8 // VPSHUFLW ymm, m256, imm8 // , VPSHUFLW_YMM_YMM_IMM8 // VPSHUFLW ymm, ymm, imm8 // , VPSIGNB_XMM_XMM_M128 // VPSIGNB xmm, xmm, m128 // , VPSIGNB_XMM_XMM_XMM // VPSIGNB xmm, xmm, xmm // , VPSIGND_XMM_XMM_M128 // VPSIGND xmm, xmm, m128 // , VPSIGND_XMM_XMM_XMM // VPSIGND xmm, xmm, xmm // , VPSIGNW_XMM_XMM_M128 // VPSIGNW xmm, xmm, m128 // , VPSIGNW_XMM_XMM_XMM // VPSIGNW xmm, xmm, xmm // , VPSLLD_XMM_XMM_IMM8 // VPSLLD xmm, xmm, imm8 // , VPSLLD_XMM_XMM_M128 // VPSLLD xmm, xmm, m128 // , VPSLLD_XMM_XMM_XMM // VPSLLD xmm, xmm, xmm // , VPSLLD_YMM_YMM_IMM8 // VPSLLD ymm, ymm, imm8 // , VPSLLD_YMM_YMM_M128 // VPSLLD ymm, ymm, m128 // , VPSLLD_YMM_YMM_XMM // VPSLLD ymm, ymm, xmm // , VPSLLDQ_XMM_XMM_IMM8 // VPSLLDQ xmm, xmm, imm8 // , VPSLLDQ_YMM_YMM_IMM8 // VPSLLDQ ymm, ymm, imm8 // , VPSLLQ_XMM_XMM_IMM8 // VPSLLQ xmm, xmm, imm8 // , VPSLLQ_XMM_XMM_M128 // VPSLLQ xmm, xmm, m128 // , VPSLLQ_XMM_XMM_XMM // VPSLLQ xmm, xmm, xmm // , VPSLLQ_YMM_YMM_IMM8 // VPSLLQ ymm, ymm, imm8 // , VPSLLQ_YMM_YMM_M128 // VPSLLQ ymm, ymm, m128 // , VPSLLQ_YMM_YMM_XMM // VPSLLQ ymm, ymm, xmm // , VPSLLVD_XMM_XMM_M128 // VPSLLVD xmm, xmm, m128 // , VPSLLVD_XMM_XMM_XMM // VPSLLVD xmm, xmm, xmm // , VPSLLVD_YMM_YMM_M256 // VPSLLVD ymm, ymm, m256 // , VPSLLVD_YMM_YMM_YMM // VPSLLVD ymm, ymm, ymm // , VPSLLVQ_XMM_XMM_M128 // VPSLLVQ xmm, xmm, m128 // , VPSLLVQ_XMM_XMM_XMM // VPSLLVQ xmm, xmm, xmm // , VPSLLVQ_YMM_YMM_M256 // VPSLLVQ ymm, ymm, m256 // , VPSLLVQ_YMM_YMM_YMM // VPSLLVQ ymm, ymm, ymm // , VPSLLW_XMM_XMM_IMM8 // VPSLLW xmm, xmm, imm8 // , VPSLLW_XMM_XMM_M128 // VPSLLW xmm, xmm, m128 // , VPSLLW_XMM_XMM_XMM // VPSLLW xmm, xmm, xmm // , VPSLLW_YMM_YMM_IMM8 // VPSLLW ymm, ymm, imm8 // , VPSLLW_YMM_YMM_M128 // VPSLLW ymm, ymm, m128 // , VPSLLW_YMM_YMM_XMM // VPSLLW ymm, ymm, xmm // , VPSRAD_XMM_XMM_IMM8 // VPSRAD xmm, xmm, imm8 // , VPSRAD_XMM_XMM_M128 // VPSRAD xmm, xmm, m128 // , VPSRAD_XMM_XMM_XMM // VPSRAD xmm, xmm, xmm // , VPSRAD_YMM_YMM_IMM8 // VPSRAD ymm, ymm, imm8 // , VPSRAD_YMM_YMM_M128 // VPSRAD ymm, ymm, m128 // , VPSRAD_YMM_YMM_XMM // VPSRAD ymm, ymm, xmm // , VPSRAVD_XMM_XMM_M128 // VPSRAVD xmm, xmm, m128 // , VPSRAVD_XMM_XMM_XMM // VPSRAVD xmm, xmm, xmm // , VPSRAVD_YMM_YMM_M256 // VPSRAVD ymm, ymm, m256 // , VPSRAVD_YMM_YMM_YMM // VPSRAVD ymm, ymm, ymm // , VPSRAW_XMM_XMM_IMM8 // VPSRAW xmm, xmm, imm8 // , VPSRAW_XMM_XMM_M128 // VPSRAW xmm, xmm, m128 // , VPSRAW_XMM_XMM_XMM // VPSRAW xmm, xmm, xmm // , VPSRAW_YMM_YMM_IMM8 // VPSRAW ymm, ymm, imm8 // , VPSRAW_YMM_YMM_M128 // VPSRAW ymm, ymm, m128 // , VPSRAW_YMM_YMM_XMM // VPSRAW ymm, ymm, xmm // , VPSRLD_XMM_XMM_IMM8 // VPSRLD xmm, xmm, imm8 // , VPSRLD_XMM_XMM_M128 // VPSRLD xmm, xmm, m128 // , VPSRLD_XMM_XMM_XMM // VPSRLD xmm, xmm, xmm // , VPSRLD_YMM_YMM_IMM8 // VPSRLD ymm, ymm, imm8 // , VPSRLD_YMM_YMM_M128 // VPSRLD ymm, ymm, m128 // , VPSRLD_YMM_YMM_XMM // VPSRLD ymm, ymm, xmm // , VPSRLDQ_XMM_XMM_IMM8 // VPSRLDQ xmm, xmm, imm8 // , VPSRLDQ_YMM_YMM_IMM8 // VPSRLDQ ymm, ymm, imm8 // , VPSRLQ_XMM_XMM_IMM8 // VPSRLQ xmm, xmm, imm8 // , VPSRLQ_XMM_XMM_M128 // VPSRLQ xmm, xmm, m128 // , VPSRLQ_XMM_XMM_XMM // VPSRLQ xmm, xmm, xmm // , VPSRLQ_YMM_YMM_IMM8 // VPSRLQ ymm, ymm, imm8 // , VPSRLQ_YMM_YMM_M128 // VPSRLQ ymm, ymm, m128 // , VPSRLQ_YMM_YMM_XMM // VPSRLQ ymm, ymm, xmm // , VPSRLVD_XMM_XMM_M128 // VPSRLVD xmm, xmm, m128 // , VPSRLVD_XMM_XMM_XMM // VPSRLVD xmm, xmm, xmm // , VPSRLVD_YMM_YMM_M256 // VPSRLVD ymm, ymm, m256 // , VPSRLVD_YMM_YMM_YMM // VPSRLVD ymm, ymm, ymm // , VPSRLVQ_XMM_XMM_M128 // VPSRLVQ xmm, xmm, m128 // , VPSRLVQ_XMM_XMM_XMM // VPSRLVQ xmm, xmm, xmm // , VPSRLVQ_YMM_YMM_M256 // VPSRLVQ ymm, ymm, m256 // , VPSRLVQ_YMM_YMM_YMM // VPSRLVQ ymm, ymm, ymm // , VPSRLW_XMM_XMM_IMM8 // VPSRLW xmm, xmm, imm8 // , VPSRLW_XMM_XMM_M128 // VPSRLW xmm, xmm, m128 // , VPSRLW_XMM_XMM_XMM // VPSRLW xmm, xmm, xmm // , VPSRLW_YMM_YMM_IMM8 // VPSRLW ymm, ymm, imm8 // , VPSRLW_YMM_YMM_M128 // VPSRLW ymm, ymm, m128 // , VPSRLW_YMM_YMM_XMM // VPSRLW ymm, ymm, xmm // , VPSUBB_XMM_XMM_M128 // VPSUBB xmm, xmm, m128 // , VPSUBB_XMM_XMM_XMM // VPSUBB xmm, xmm, xmm // , VPSUBB_YMM_YMM_M256 // VPSUBB ymm, ymm, m256 // , VPSUBB_YMM_YMM_YMM // VPSUBB ymm, ymm, ymm // , VPSUBD_XMM_XMM_M128 // VPSUBD xmm, xmm, m128 // , VPSUBD_XMM_XMM_XMM // VPSUBD xmm, xmm, xmm // , VPSUBD_YMM_YMM_M256 // VPSUBD ymm, ymm, m256 // , VPSUBD_YMM_YMM_YMM // VPSUBD ymm, ymm, ymm // , VPSUBQ_XMM_XMM_M128 // VPSUBQ xmm, xmm, m128 // , VPSUBQ_XMM_XMM_XMM // VPSUBQ xmm, xmm, xmm // , VPSUBQ_YMM_YMM_M256 // VPSUBQ ymm, ymm, m256 // , VPSUBQ_YMM_YMM_YMM // VPSUBQ ymm, ymm, ymm // , VPSUBSB_XMM_XMM_M128 // VPSUBSB xmm, xmm, m128 // , VPSUBSB_XMM_XMM_XMM // VPSUBSB xmm, xmm, xmm // , VPSUBSB_YMM_YMM_M256 // VPSUBSB ymm, ymm, m256 // , VPSUBSB_YMM_YMM_YMM // VPSUBSB ymm, ymm, ymm // , VPSUBSW_XMM_XMM_M128 // VPSUBSW xmm, xmm, m128 // , VPSUBSW_XMM_XMM_XMM // VPSUBSW xmm, xmm, xmm // , VPSUBSW_YMM_YMM_M256 // VPSUBSW ymm, ymm, m256 // , VPSUBSW_YMM_YMM_YMM // VPSUBSW ymm, ymm, ymm // , VPSUBUSB_XMM_XMM_M128 // VPSUBUSB xmm, xmm, m128 // , VPSUBUSB_XMM_XMM_XMM // VPSUBUSB xmm, xmm, xmm // , VPSUBUSB_YMM_YMM_M256 // VPSUBUSB ymm, ymm, m256 // , VPSUBUSB_YMM_YMM_YMM // VPSUBUSB ymm, ymm, ymm // , VPSUBUSW_XMM_XMM_M128 // VPSUBUSW xmm, xmm, m128 // , VPSUBUSW_XMM_XMM_XMM // VPSUBUSW xmm, xmm, xmm // , VPSUBUSW_YMM_YMM_M256 // VPSUBUSW ymm, ymm, m256 // , VPSUBUSW_YMM_YMM_YMM // VPSUBUSW ymm, ymm, ymm // , VPSUBW_XMM_XMM_M128 // VPSUBW xmm, xmm, m128 // , VPSUBW_XMM_XMM_XMM // VPSUBW xmm, xmm, xmm // , VPSUBW_YMM_YMM_M256 // VPSUBW ymm, ymm, m256 // , VPSUBW_YMM_YMM_YMM // VPSUBW ymm, ymm, ymm // , VPTEST_XMM_M128 // VPTEST xmm, m128 // , VPTEST_XMM_XMM // VPTEST xmm, xmm // , VPTEST_YMM_M256 // VPTEST ymm, m256 // , VPTEST_YMM_YMM // VPTEST ymm, ymm // , VPUNPCKHBW_XMM_XMM_M128 // VPUNPCKHBW xmm, xmm, m128 // , VPUNPCKHBW_XMM_XMM_XMM // VPUNPCKHBW xmm, xmm, xmm // , VPUNPCKHBW_YMM_YMM_M256 // VPUNPCKHBW ymm, ymm, m256 // , VPUNPCKHBW_YMM_YMM_YMM // VPUNPCKHBW ymm, ymm, ymm // , VPUNPCKHDQ_XMM_XMM_M128 // VPUNPCKHDQ xmm, xmm, m128 // , VPUNPCKHDQ_XMM_XMM_XMM // VPUNPCKHDQ xmm, xmm, xmm // , VPUNPCKHDQ_YMM_YMM_M256 // VPUNPCKHDQ ymm, ymm, m256 // , VPUNPCKHDQ_YMM_YMM_YMM // VPUNPCKHDQ ymm, ymm, ymm // , VPUNPCKHQDQ_XMM_XMM_M128 // VPUNPCKHQDQ xmm, xmm, m128 // , VPUNPCKHQDQ_XMM_XMM_XMM // VPUNPCKHQDQ xmm, xmm, xmm // , VPUNPCKHQDQ_YMM_YMM_M256 // VPUNPCKHQDQ ymm, ymm, m256 // , VPUNPCKHQDQ_YMM_YMM_YMM // VPUNPCKHQDQ ymm, ymm, ymm // , VPUNPCKHWD_XMM_XMM_M128 // VPUNPCKHWD xmm, xmm, m128 // , VPUNPCKHWD_XMM_XMM_XMM // VPUNPCKHWD xmm, xmm, xmm // , VPUNPCKHWD_YMM_YMM_M256 // VPUNPCKHWD ymm, ymm, m256 // , VPUNPCKHWD_YMM_YMM_YMM // VPUNPCKHWD ymm, ymm, ymm // , VPUNPCKLBW_XMM_XMM_M128 // VPUNPCKLBW xmm, xmm, m128 // , VPUNPCKLBW_XMM_XMM_XMM // VPUNPCKLBW xmm, xmm, xmm // , VPUNPCKLBW_YMM_YMM_M256 // VPUNPCKLBW ymm, ymm, m256 // , VPUNPCKLBW_YMM_YMM_YMM // VPUNPCKLBW ymm, ymm, ymm // , VPUNPCKLDQ_XMM_XMM_M128 // VPUNPCKLDQ xmm, xmm, m128 // , VPUNPCKLDQ_XMM_XMM_XMM // VPUNPCKLDQ xmm, xmm, xmm // , VPUNPCKLDQ_YMM_YMM_M256 // VPUNPCKLDQ ymm, ymm, m256 // , VPUNPCKLDQ_YMM_YMM_YMM // VPUNPCKLDQ ymm, ymm, ymm // , VPUNPCKLQDQ_XMM_XMM_M128 // VPUNPCKLQDQ xmm, xmm, m128 // , VPUNPCKLQDQ_XMM_XMM_XMM // VPUNPCKLQDQ xmm, xmm, xmm // , VPUNPCKLQDQ_YMM_YMM_M256 // VPUNPCKLQDQ ymm, ymm, m256 // , VPUNPCKLQDQ_YMM_YMM_YMM // VPUNPCKLQDQ ymm, ymm, ymm // , VPUNPCKLWD_XMM_XMM_M128 // VPUNPCKLWD xmm, xmm, m128 // , VPUNPCKLWD_XMM_XMM_XMM // VPUNPCKLWD xmm, xmm, xmm // , VPUNPCKLWD_YMM_YMM_M256 // VPUNPCKLWD ymm, ymm, m256 // , VPUNPCKLWD_YMM_YMM_YMM // VPUNPCKLWD ymm, ymm, ymm // , VPXOR_XMM_XMM_M128 // VPXOR xmm, xmm, m128 // , VPXOR_XMM_XMM_XMM // VPXOR xmm, xmm, xmm // , VPXOR_YMM_YMM_M256 // VPXOR ymm, ymm, m256 // , VPXOR_YMM_YMM_YMM // VPXOR ymm, ymm, ymm // , VRCPPS_XMM_M128 // VRCPPS xmm, m128 // , VRCPPS_XMM_XMM // VRCPPS xmm, xmm // , VRCPPS_YMM_M256 // VRCPPS ymm, m256 , VRCPPS_YMM_YMM // VRCPPS ymm, ymm // , VRCPSS_XMM_XMM_M32 // VRCPSS xmm, xmm, m32 // , VRCPSS_XMM_XMM_XMM // VRCPSS xmm, xmm, xmm // , VROUNDPD_XMM_M128_IMM8 // VROUNDPD xmm, m128, imm8 // , VROUNDPD_XMM_XMM_IMM8 // VROUNDPD xmm, xmm, imm8 // , VROUNDPD_YMM_M256_IMM8 // VROUNDPD ymm, m256, imm8 // , VROUNDPD_YMM_YMM_IMM8 // VROUNDPD ymm, ymm, imm8 // , VROUNDPS_XMM_M128_IMM8 // VROUNDPS xmm, m128, imm8 // , VROUNDPS_XMM_XMM_IMM8 // VROUNDPS xmm, xmm, imm8 // , VROUNDPS_YMM_M256_IMM8 // VROUNDPS ymm, m256, imm8 // , VROUNDPS_YMM_YMM_IMM8 // VROUNDPS ymm, ymm, imm8 // , VROUNDSD_XMM_XMM_M64_IMM8 // VROUNDSD xmm, xmm, m64, imm8 // , VROUNDSD_XMM_XMM_XMM_IMM8 // VROUNDSD xmm, xmm, xmm, imm8 // , VROUNDSS_XMM_XMM_M32_IMM8 // VROUNDSS xmm, xmm, m32, imm8 // , VROUNDSS_XMM_XMM_XMM_IMM8 // VROUNDSS xmm, xmm, xmm, imm8 // , VRSQRTPS_XMM_M128 // VRSQRTPS xmm, m128 // , VRSQRTPS_XMM_XMM // VRSQRTPS xmm, xmm // , VRSQRTPS_YMM_M256 // VRSQRTPS ymm, m256 , VRSQRTPS_YMM_YMM // VRSQRTPS ymm, ymm // , VRSQRTSS_XMM_XMM_M32 // VRSQRTSS xmm, xmm, m32 // , VRSQRTSS_XMM_XMM_XMM // VRSQRTSS xmm, xmm, xmm // , VSHUFPD_XMM_XMM_M128_IMM8 // VSHUFPD xmm, xmm, m128, imm8 // , VSHUFPD_XMM_XMM_XMM_IMM8 // VSHUFPD xmm, xmm, xmm, imm8 // , VSHUFPD_YMM_YMM_M256_IMM8 // VSHUFPD ymm, ymm, m256, imm8 // , VSHUFPD_YMM_YMM_YMM_IMM8 // VSHUFPD ymm, ymm, ymm, imm8 // , VSHUFPS_XMM_XMM_M128_IMM8 // VSHUFPS xmm, xmm, m128, imm8 // , VSHUFPS_XMM_XMM_XMM_IMM8 // VSHUFPS xmm, xmm, xmm, imm8 // , VSHUFPS_YMM_YMM_M256_IMM8 // VSHUFPS ymm, ymm, m256, imm8 // , VSHUFPS_YMM_YMM_YMM_IMM8 // VSHUFPS ymm, ymm, ymm, imm8 // , VSQRTPD_XMM_M128 // VSQRTPD xmm, m128 // , VSQRTPD_XMM_XMM // VSQRTPD xmm, xmm // , VSQRTPD_YMM_M256 // VSQRTPD ymm, m256 , VSQRTPD_YMM_YMM // VSQRTPD ymm, ymm // , VSQRTPS_XMM_M128 // VSQRTPS xmm, m128 // , VSQRTPS_XMM_XMM // VSQRTPS xmm, xmm // , VSQRTPS_YMM_M256 // VSQRTPS ymm, m256 , VSQRTPS_YMM_YMM // VSQRTPS ymm, ymm // , VSQRTSD_XMM_XMM_M64 // VSQRTSD xmm, xmm, m64 // , VSQRTSD_XMM_XMM_XMM // VSQRTSD xmm, xmm, xmm // , VSQRTSS_XMM_XMM_M32 // VSQRTSS xmm, xmm, m32 // , VSQRTSS_XMM_XMM_XMM // VSQRTSS xmm, xmm, xmm // , VSTMXCSR_M32 // VSTMXCSR m32 // , VSUBPD_XMM_XMM_M128 // VSUBPD xmm, xmm, m128 // , VSUBPD_XMM_XMM_XMM // VSUBPD xmm, xmm, xmm // , VSUBPD_YMM_YMM_M256 // VSUBPD ymm, ymm, m256 , VSUBPD_YMM_YMM_YMM // VSUBPD ymm, ymm, ymm // , VSUBPS_XMM_XMM_M128 // VSUBPS xmm, xmm, m128 // , VSUBPS_XMM_XMM_XMM // VSUBPS xmm, xmm, xmm // , VSUBPS_YMM_YMM_M256 // VSUBPS ymm, ymm, m256 , VSUBPS_YMM_YMM_YMM // VSUBPS ymm, ymm, ymm // , VSUBSD_XMM_XMM_M64 // VSUBSD xmm, xmm, m64 // , VSUBSD_XMM_XMM_XMM // VSUBSD xmm, xmm, xmm // , VSUBSS_XMM_XMM_M32 // VSUBSS xmm, xmm, m32 // , VSUBSS_XMM_XMM_XMM // VSUBSS xmm, xmm, xmm // , VTESTPD_XMM_M128 // VTESTPD xmm, m128 // , VTESTPD_XMM_XMM // VTESTPD xmm, xmm // , VTESTPD_YMM_M256 // VTESTPD ymm, m256 // , VTESTPD_YMM_YMM // VTESTPD ymm, ymm // , VTESTPS_XMM_M128 // VTESTPS xmm, m128 // , VTESTPS_XMM_XMM // VTESTPS xmm, xmm // , VTESTPS_YMM_M256 // VTESTPS ymm, m256 // , VTESTPS_YMM_YMM // VTESTPS ymm, ymm // , VUCOMISD_XMM_M64 // VUCOMISD xmm, m64 // , VUCOMISD_XMM_XMM // VUCOMISD xmm, xmm // , VUCOMISS_XMM_M32 // VUCOMISS xmm, m32 // , VUCOMISS_XMM_XMM // VUCOMISS xmm, xmm // , VUNPCKHPD_XMM_XMM_M128 // VUNPCKHPD xmm, xmm, m128 // , VUNPCKHPD_XMM_XMM_XMM // VUNPCKHPD xmm, xmm, xmm // , VUNPCKHPD_YMM_YMM_M256 // VUNPCKHPD ymm, ymm, m256 // , VUNPCKHPD_YMM_YMM_YMM // VUNPCKHPD ymm, ymm, ymm // , VUNPCKHPS_XMM_XMM_M128 // VUNPCKHPS xmm, xmm, m128 // , VUNPCKHPS_XMM_XMM_XMM // VUNPCKHPS xmm, xmm, xmm // , VUNPCKHPS_YMM_YMM_M256 // VUNPCKHPS ymm, ymm, m256 // , VUNPCKHPS_YMM_YMM_YMM // VUNPCKHPS ymm, ymm, ymm // , VUNPCKLPD_XMM_XMM_M128 // VUNPCKLPD xmm, xmm, m128 // , VUNPCKLPD_XMM_XMM_XMM // VUNPCKLPD xmm, xmm, xmm // , VUNPCKLPD_YMM_YMM_M256 // VUNPCKLPD ymm, ymm, m256 // , VUNPCKLPD_YMM_YMM_YMM // VUNPCKLPD ymm, ymm, ymm // , VUNPCKLPS_XMM_XMM_M128 // VUNPCKLPS xmm, xmm, m128 // , VUNPCKLPS_XMM_XMM_XMM // VUNPCKLPS xmm, xmm, xmm // , VUNPCKLPS_YMM_YMM_M256 // VUNPCKLPS ymm, ymm, m256 // , VUNPCKLPS_YMM_YMM_YMM // VUNPCKLPS ymm, ymm, ymm // , VXORPD_XMM_XMM_M128 // VXORPD xmm, xmm, m128 // , VXORPD_XMM_XMM_XMM // VXORPD xmm, xmm, xmm // , VXORPD_YMM_YMM_M256 // VXORPD ymm, ymm, m256 // , VXORPD_YMM_YMM_YMM // VXORPD ymm, ymm, ymm // , VXORPS_XMM_XMM_M128 // VXORPS xmm, xmm, m128 // , VXORPS_XMM_XMM_XMM // VXORPS xmm, xmm, xmm // , VXORPS_YMM_YMM_M256 // VXORPS ymm, ymm, m256 // , VXORPS_YMM_YMM_YMM // VXORPS ymm, ymm, ymm , VZEROALL // VZEROALL // , VZEROUPPER // VZEROUPPER // , WAIT // WAIT // , WRFSBASE_R32 // WRFSBASE r32 // , WRFSBASE_R64 // WRFSBASE r64 // , WRGSBASE_R32 // WRGSBASE r32 // , WRGSBASE_R64 // WRGSBASE r64 // , XABORT_IMM8 // XABORT imm8 // , XACQUIRE // XACQUIRE // , XADD_M16_R16 // XADD m16, r16 // , XADD_M32_R32 // XADD m32, r32 // , XADD_M64_R64 // XADD m64, r64 // , XADD_M8_R8 // XADD m8, r8 // , XADD_M8_RH // XADD m8, rh // , XADD_R16_R16 // XADD r16, r16 // , XADD_R32_R32 // XADD r32, r32 // , XADD_R64_R64 // XADD r64, r64 // , XADD_R8_R8 // XADD r8, r8 // , XADD_R8_RH // XADD r8, rh // , XADD_RH_R8 // XADD rh, r8 // , XADD_RH_RH // XADD rh, rh // , XBEGIN_REL32 // XBEGIN rel32 // , XBEGIN_LABEL // XBEGIN label // , XCHG_AX_R16 // XCHG AX, r16 // , XCHG_EAX_R32 // XCHG EAX, r32 // , XCHG_M16_R16 // XCHG m16, r16 // , XCHG_M32_R32 // XCHG m32, r32 // , XCHG_M64_R64 // XCHG m64, r64 // , XCHG_M8_R8 // XCHG m8, r8 // , XCHG_M8_RH // XCHG m8, rh // , XCHG_R16_AX // XCHG r16, AX // , XCHG_R16_M16 // XCHG r16, m16 // , XCHG_R16_R16 // XCHG r16, r16 // , XCHG_R32_EAX // XCHG r32, EAX // , XCHG_R32_M32 // XCHG r32, m32 // , XCHG_R32_R32 // XCHG r32, r32 // , XCHG_R64_M64 // XCHG r64, m64 // , XCHG_R64_R64 // XCHG r64, r64 // , XCHG_R64_RAX // XCHG r64, RAX // , XCHG_R8_M8 // XCHG r8, m8 // , XCHG_R8_R8 // XCHG r8, r8 // , XCHG_R8_RH // XCHG r8, rh // , XCHG_RAX_R64 // XCHG RAX, r64 // , XCHG_RH_M8 // XCHG rh, m8 // , XCHG_RH_R8 // XCHG rh, r8 // , XCHG_RH_RH // XCHG rh, rh // , XEND // XEND // , XGETBV // XGETBV // , XLAT_M8 // XLAT m8 // , XLATB // XLATB // , XOR_AL_IMM8 // XOR AL, imm8 // , XOR_AX_IMM16 // XOR AX, imm16 // , XOR_EAX_IMM32 // XOR EAX, imm32 // , XOR_M16_IMM16 // XOR m16, imm16 // , XOR_M16_IMM8 // XOR m16, imm8 // , XOR_M16_R16 // XOR m16, r16 // , XOR_M32_IMM32 // XOR m32, imm32 // , XOR_M32_IMM8 // XOR m32, imm8 // , XOR_M32_R32 // XOR m32, r32 // , XOR_M64_IMM32 // XOR m64, imm32 // , XOR_M64_IMM8 // XOR m64, imm8 // , XOR_M64_R64 // XOR m64, r64 // , XOR_M8_IMM8 // XOR m8, imm8 // , XOR_M8_R8 // XOR m8, r8 // , XOR_M8_RH // XOR m8, rh // , XOR_R16_IMM16 // XOR r16, imm16 // , XOR_R16_IMM8 // XOR r16, imm8 // , XOR_R16_M16 // XOR r16, m16 // , XOR_R16_R16 // XOR r16, r16 // , XOR_R32_IMM32 // XOR r32, imm32 // , XOR_R32_IMM8 // XOR r32, imm8 // , XOR_R32_M32 // XOR r32, m32 // , XOR_R32_R32 // XOR r32, r32 // , XOR_R64_IMM32 // XOR r64, imm32 // , XOR_R64_IMM8 // XOR r64, imm8 // , XOR_R64_M64 // XOR r64, m64 , XOR_R64_R64 // XOR r64, r64 // , XOR_R8_IMM8 // XOR r8, imm8 // , XOR_R8_M8 // XOR r8, m8 // , XOR_R8_R8 // XOR r8, r8 // , XOR_R8_RH // XOR r8, rh // , XOR_RAX_IMM32 // XOR RAX, imm32 // , XOR_RH_IMM8 // XOR rh, imm8 // , XOR_RH_M8 // XOR rh, m8 // , XOR_RH_R8 // XOR rh, r8 // , XOR_RH_RH // XOR rh, rh // , XORPD_XMM_M128 // XORPD xmm, m128 // , XORPD_XMM_XMM // XORPD xmm, xmm // , XORPS_XMM_M128 // XORPS xmm, m128 // , XORPS_XMM_XMM // XORPS xmm, xmm // , XRELEASE // XRELEASE // , XRSTOR_M16 // XRSTOR m16 // , XRSTOR_M32 // XRSTOR m32 // , XRSTOR_M64 // XRSTOR m64 // , XRSTOR64_M16 // XRSTOR64 m16 // , XRSTOR64_M32 // XRSTOR64 m32 // , XRSTOR64_M64 // XRSTOR64 m64 // , XSAVE_M16 // XSAVE m16 // , XSAVE_M32 // XSAVE m32 // , XSAVE_M64 // XSAVE m64 // , XSAVE64_M16 // XSAVE64 m16 // , XSAVE64_M32 // XSAVE64 m32 // , XSAVE64_M64 // XSAVE64 m64 // , XSAVEOPT_M16 // XSAVEOPT m16 // , XSAVEOPT_M32 // XSAVEOPT m32 // , XSAVEOPT_M64 // XSAVEOPT m64 // , XSAVEOPT64_M16 // XSAVEOPT64 m16 // , XSAVEOPT64_M32 // XSAVEOPT64 m32 // , XSAVEOPT64_M64 // XSAVEOPT64 m64 // , XTEST // XTEST }; set<Opcode> unsupported_ {{ #include "src/sandbox/tables/unsupported.h" } }; bool strata_is_sandbox_unsupported(const x64asm::Opcode& op) { return unsupported_.find(op) != unsupported_.end(); } bool strata_is_base(const x64asm::Opcode& op) { auto& set = instr_cat_base_; return find(set.begin(), set.end(), op) != set.end(); } bool strata_is_crypto(const x64asm::Opcode& op) { auto& set = instr_cat_crypto_; return find(set.begin(), set.end(), op) != set.end(); } bool strata_is_jump(const x64asm::Opcode& op) { auto& set = instr_cat_jump_; return find(set.begin(), set.end(), op) != set.end(); } bool strata_is_imm8(const x64asm::Opcode& op) { auto& set = instr_cat_imm8_; return find(set.begin(), set.end(), op) != set.end(); } bool strata_is_system(const x64asm::Opcode& op) { auto& set = instr_cat_system_; if (find(set.begin(), set.end(), op) != set.end()) { return true; } // also make moffs system Instruction instr(op); for (size_t i = 0; i < instr.arity(); i++) { switch (instr.type(i)) { case Type::MOFFS_8: case Type::MOFFS_16: case Type::MOFFS_32: case Type::MOFFS_64: return true; default: break; } } return false; } bool strata_is_float(const x64asm::Opcode& op) { auto& set = instr_cat_float_; return find(set.begin(), set.end(), op) != set.end(); } bool strata_is_duplicate(const x64asm::Opcode& op) { auto& set = instr_cat_duplicates_; return find(set.begin(), set.end(), op) != set.end(); } bool strata_is_mm(const x64asm::Opcode& opcode) { Instruction instr(opcode); for (size_t i = 0; i < instr.arity(); i++) { switch (instr.type(i)) { case Type::MM: return true; default: break; } } return false; } bool strata_uses_memory(const x64asm::Opcode& opcode) { Instruction instr(opcode); for (size_t i = 0; i < instr.arity(); i++) { switch (instr.type(i)) { case Type::M_8: case Type::M_16: case Type::M_32: case Type::M_64: case Type::M_128: case Type::M_256: case Type::M_16_INT: case Type::M_32_INT: case Type::M_64_INT: case Type::M_32_FP: case Type::M_64_FP: case Type::M_80_FP: case Type::M_80_BCD: case Type::M_2_BYTE: case Type::M_28_BYTE: case Type::M_108_BYTE: case Type::M_512_BYTE: case Type::FAR_PTR_16_16: case Type::FAR_PTR_16_32: case Type::FAR_PTR_16_64: return true; default: break; } } return false; } bool strata_uses_imm(const x64asm::Opcode& opcode) { Instruction instr(opcode); for (size_t i = 0; i < instr.arity(); i++) { switch (instr.type(i)) { case Type::IMM_8: case Type::IMM_16: case Type::IMM_32: case Type::IMM_64: return true; default: break; } } return false; } StrataSupportedReason strata_is_supported_type_reason(x64asm::Type t) { switch (t) { case x64asm::Type::NONE: std::cout << "NONE should not occur!" << std::endl; exit(1); case x64asm::Type::M_8: case x64asm::Type::M_16: case x64asm::Type::M_32: case x64asm::Type::M_64: case x64asm::Type::M_128: case x64asm::Type::M_256: case x64asm::Type::M_16_INT: case x64asm::Type::M_32_INT: case x64asm::Type::M_64_INT: case x64asm::Type::M_32_FP: case x64asm::Type::M_64_FP: case x64asm::Type::M_80_FP: case x64asm::Type::M_80_BCD: case x64asm::Type::M_2_BYTE: case x64asm::Type::M_28_BYTE: case x64asm::Type::M_108_BYTE: case x64asm::Type::M_512_BYTE: return StrataSupportedReason::MEMORY; case x64asm::Type::IMM_8: case x64asm::Type::IMM_16: case x64asm::Type::IMM_32: case x64asm::Type::IMM_64: return StrataSupportedReason::IMMEDIATE; case x64asm::Type::LABEL: return StrataSupportedReason::LABEL; case x64asm::Type::RH: case x64asm::Type::R_8: case x64asm::Type::R_16: case x64asm::Type::R_32: case x64asm::Type::R_64: case x64asm::Type::XMM: case x64asm::Type::YMM: return StrataSupportedReason::SUPPORTED; case x64asm::Type::MM: return StrataSupportedReason::MM; case x64asm::Type::ZERO: case x64asm::Type::ONE: case x64asm::Type::THREE: return StrataSupportedReason::SUPPORTED; case x64asm::Type::AL: case x64asm::Type::CL: case x64asm::Type::AX: case x64asm::Type::DX: case x64asm::Type::EAX: case x64asm::Type::RAX: case x64asm::Type::XMM_0: return StrataSupportedReason::SUPPORTED; case x64asm::Type::HINT: case x64asm::Type::FAR_PTR_16_16: case x64asm::Type::FAR_PTR_16_32: case x64asm::Type::FAR_PTR_16_64: case x64asm::Type::PREF_66: case x64asm::Type::PREF_REX_W: case x64asm::Type::FAR: case x64asm::Type::MOFFS_8: case x64asm::Type::MOFFS_16: case x64asm::Type::MOFFS_32: case x64asm::Type::MOFFS_64: case x64asm::Type::REL_8: case x64asm::Type::REL_32: case x64asm::Type::SREG: case x64asm::Type::FS: case x64asm::Type::GS: case x64asm::Type::ST: case x64asm::Type::ST_0: return StrataSupportedReason::OTHER; default: assert(false); return StrataSupportedReason::OTHER; } } /** Can strata currently handle this x64asm::Type? */ bool strata_is_supported_type(x64asm::Type t) { return strata_is_supported_type_reason(t) == StrataSupportedReason::SUPPORTED; } std::map<x64asm::Type, std::vector<x64asm::Operand>> operands_ = { {x64asm::Type::RH, {x64asm::Constants::ah(), x64asm::Constants::bh(), x64asm::Constants::ch(), x64asm::Constants::dh()}}, {x64asm::Type::R_8, {x64asm::Constants::bl(), x64asm::Constants::cl(), x64asm::Constants::dl()}}, {x64asm::Type::R_16, {x64asm::Constants::bx(), x64asm::Constants::cx(), x64asm::Constants::dx()}}, {x64asm::Type::R_32, {x64asm::Constants::ebx(), x64asm::Constants::ecx(), x64asm::Constants::edx()}}, {x64asm::Type::R_64, {x64asm::Constants::rbx(), x64asm::Constants::rcx(), x64asm::Constants::rdx()}}, {x64asm::Type::M_8, {x64asm::M8(x64asm::Constants::rbx()), x64asm::M8(x64asm::Constants::rcx()), x64asm::M8(x64asm::Constants::rdx())}}, {x64asm::Type::M_16, {x64asm::M16(x64asm::Constants::rbx()), x64asm::M16(x64asm::Constants::rcx()), x64asm::M16(x64asm::Constants::rdx())}}, {x64asm::Type::M_32, {x64asm::M32(x64asm::Constants::rbx()), x64asm::M32(x64asm::Constants::rcx()), x64asm::M32(x64asm::Constants::rdx())}}, {x64asm::Type::M_64, {x64asm::M64(x64asm::Constants::rbx()), x64asm::M64(x64asm::Constants::rcx()), x64asm::M64(x64asm::Constants::rdx())}}, {x64asm::Type::M_128, {x64asm::M128(x64asm::Constants::rbx()), x64asm::M128(x64asm::Constants::rcx()), x64asm::M128(x64asm::Constants::rdx())}}, {x64asm::Type::M_256, {x64asm::M256(x64asm::Constants::rbx()), x64asm::M256(x64asm::Constants::rcx()), x64asm::M256(x64asm::Constants::rdx())}}, {x64asm::Type::XMM, {x64asm::Constants::xmm1(), x64asm::Constants::xmm2(), x64asm::Constants::xmm3(), x64asm::Constants::xmm4()}}, {x64asm::Type::YMM, {x64asm::Constants::ymm1(), x64asm::Constants::ymm2(), x64asm::Constants::ymm3(), x64asm::Constants::ymm4()}}, {x64asm::Type::MM, {x64asm::Constants::mm0(), x64asm::Constants::mm1(), x64asm::Constants::mm2(), x64asm::Constants::mm3()}} }; std::map<x64asm::Type, int> operands_idx_ = { }; x64asm::Operand get_next_operand(x64asm::Type t, uint8_t imm8_val, bool samereg) { if (t == x64asm::Type::IMM_8) { return x64asm::Imm8(imm8_val); } if (t == x64asm::Type::IMM_16) { return x64asm::Imm16(0); } if (t == x64asm::Type::IMM_32) { return x64asm::Imm32(0); } if (t == x64asm::Type::IMM_64) { return x64asm::Imm64(0); } if (t == x64asm::Type::AL) { return x64asm::Constants::al(); } if (t == x64asm::Type::CL) { return x64asm::Constants::cl(); } if (t == x64asm::Type::AX) { return x64asm::Constants::ax(); } if (t == x64asm::Type::DX) { return x64asm::Constants::dx(); } if (t == x64asm::Type::EAX) { return x64asm::Constants::eax(); } if (t == x64asm::Type::RAX) { return x64asm::Constants::rax(); } if (t == x64asm::Type::XMM_0) { return x64asm::Constants::xmm0(); } if (t == x64asm::Type::ZERO) { return x64asm::Constants::zero(); } if (t == x64asm::Type::ONE) { return x64asm::Constants::one(); } if (t == x64asm::Type::THREE) { return x64asm::Constants::three(); } if (operands_.find(t) == operands_.end()) { std::cout << "ERROR: unsupported operand: " << t << std::endl; exit(1); } if (samereg) { if (t == x64asm::Type::R_8) { return x64asm::Constants::al(); } if (t == x64asm::Type::RH) { return x64asm::Constants::ah(); } if (t == x64asm::Type::R_16) { return x64asm::Constants::ax(); } if (t == x64asm::Type::R_32) { return x64asm::Constants::eax(); } if (t == x64asm::Type::R_64) { return x64asm::Constants::rax(); } } if (operands_idx_.find(t) == operands_idx_.end()) { operands_idx_[t] = 0; } std::vector<x64asm::Operand> candidates = operands_[t]; assert((int)operands_[t].size() > operands_idx_[t]); operands_idx_[t] += 1; // increment other counters, too, so that we don't reuse the same register id multiple times auto incr_mem_counters = [&operands_idx_]() -> void { if (operands_idx_.find(x64asm::Type::M_8) == operands_idx_.end()) operands_idx_[x64asm::Type::M_8] = 0; operands_idx_[x64asm::Type::M_8] += 1; if (operands_idx_.find(x64asm::Type::M_16) == operands_idx_.end()) operands_idx_[x64asm::Type::M_16] = 0; operands_idx_[x64asm::Type::M_16] += 1; if (operands_idx_.find(x64asm::Type::M_32) == operands_idx_.end()) operands_idx_[x64asm::Type::M_32] = 0; operands_idx_[x64asm::Type::M_32] += 1; if (operands_idx_.find(x64asm::Type::M_64) == operands_idx_.end()) operands_idx_[x64asm::Type::M_64] = 0; operands_idx_[x64asm::Type::M_64] += 1; if (operands_idx_.find(x64asm::Type::M_128) == operands_idx_.end()) operands_idx_[x64asm::Type::M_128] = 0; operands_idx_[x64asm::Type::M_128] += 1; if (operands_idx_.find(x64asm::Type::M_256) == operands_idx_.end()) operands_idx_[x64asm::Type::M_256] = 0; operands_idx_[x64asm::Type::M_256] += 1; }; if (t == x64asm::Type::R_8 || t == x64asm::Type::R_16 || t == x64asm::Type::R_32 || t == x64asm::Type::R_64) { incr_mem_counters(); } if (t == x64asm::Type::M_8 || t == x64asm::Type::M_16 || t == x64asm::Type::M_32 || t == x64asm::Type::M_64 || t == x64asm::Type::M_128 || t == x64asm::Type::M_256 ) { if (operands_idx_.find(x64asm::Type::R_8) == operands_idx_.end()) operands_idx_[x64asm::Type::R_8] = 0; operands_idx_[x64asm::Type::R_8] += 1; if (operands_idx_.find(x64asm::Type::R_16) == operands_idx_.end()) operands_idx_[x64asm::Type::R_16] = 0; operands_idx_[x64asm::Type::R_16] += 1; if (operands_idx_.find(x64asm::Type::R_32) == operands_idx_.end()) operands_idx_[x64asm::Type::R_32] = 0; operands_idx_[x64asm::Type::R_32] += 1; if (operands_idx_.find(x64asm::Type::R_64) == operands_idx_.end()) operands_idx_[x64asm::Type::R_64] = 0; operands_idx_[x64asm::Type::R_64] += 1; } if (t == x64asm::Type::R_64) { if (operands_idx_.find(x64asm::Type::R_8) == operands_idx_.end()) operands_idx_[x64asm::Type::R_8] = 0; operands_idx_[x64asm::Type::R_8] += 1; if (operands_idx_.find(x64asm::Type::R_16) == operands_idx_.end()) operands_idx_[x64asm::Type::R_16] = 0; operands_idx_[x64asm::Type::R_16] += 1; if (operands_idx_.find(x64asm::Type::R_32) == operands_idx_.end()) operands_idx_[x64asm::Type::R_32] = 0; operands_idx_[x64asm::Type::R_32] += 1; } if (t == x64asm::Type::R_32) { if (operands_idx_.find(x64asm::Type::R_8) == operands_idx_.end()) operands_idx_[x64asm::Type::R_8] = 0; operands_idx_[x64asm::Type::R_8] += 1; if (operands_idx_.find(x64asm::Type::R_16) == operands_idx_.end()) operands_idx_[x64asm::Type::R_16] = 0; operands_idx_[x64asm::Type::R_16] += 1; } if (t == x64asm::Type::R_16) { if (operands_idx_.find(x64asm::Type::R_8) == operands_idx_.end()) operands_idx_[x64asm::Type::R_8] = 0; operands_idx_[x64asm::Type::R_8] += 1; } if (t == x64asm::Type::YMM) { if (operands_idx_.find(x64asm::Type::XMM) == operands_idx_.end()) operands_idx_[x64asm::Type::XMM] = 0; operands_idx_[x64asm::Type::XMM] += 1; } return operands_[t][operands_idx_[t] - 1]; } x64asm::Instruction strata_get_instruction(x64asm::Opcode opc, uint8_t imm8_val, bool samereg) { operands_idx_ = {}; x64asm::Instruction instr(opc); // special case for shld/shrd (versions with cl register) if (opc == SHLD_R16_R16_CL) { instr.set_operand(0, Constants::bx()); instr.set_operand(1, Constants::dx()); instr.set_operand(2, Constants::cl()); } else if (opc == SHLD_R32_R32_CL) { instr.set_operand(0, Constants::ebx()); instr.set_operand(1, Constants::edx()); instr.set_operand(2, Constants::cl()); } else if (opc == SHLD_R64_R64_CL) { instr.set_operand(0, Constants::rbx()); instr.set_operand(1, Constants::rdx()); instr.set_operand(2, Constants::cl()); } else if (opc == SHRD_R16_R16_CL) { instr.set_operand(0, Constants::bx()); instr.set_operand(1, Constants::dx()); instr.set_operand(2, Constants::cl()); } else if (opc == SHRD_R32_R32_CL) { instr.set_operand(0, Constants::ebx()); instr.set_operand(1, Constants::edx()); instr.set_operand(2, Constants::cl()); } else if (opc == SHRD_R64_R64_CL) { instr.set_operand(0, Constants::rbx()); instr.set_operand(1, Constants::rdx()); instr.set_operand(2, Constants::cl()); } // special case for mulb/divb/idivb/imulb else if (opc == IMUL_RH) { instr.set_operand(0, Constants::bh()); } else if (opc == MUL_RH) { instr.set_operand(0, Constants::bh()); } else if (opc == IDIV_RH) { instr.set_operand(0, Constants::bh()); } else if (opc == DIV_RH) { instr.set_operand(0, Constants::bh()); } // special case for cmpxchg with an RH register else if (opc == CMPXCHG_R8_RH) { if (samereg) { instr.set_operand(0, Constants::al()); instr.set_operand(1, Constants::ah()); } else { instr.set_operand(0, Constants::cl()); instr.set_operand(1, Constants::bh()); } } else if (opc == CMPXCHG_RH_RH) { if (samereg) { instr.set_operand(0, Constants::ah()); instr.set_operand(1, Constants::ah()); } else { instr.set_operand(0, Constants::bh()); instr.set_operand(1, Constants::ch()); } } else if (opc == CMPXCHG_RH_R8) { if (samereg) { instr.set_operand(0, Constants::ah()); instr.set_operand(1, Constants::al()); } else { instr.set_operand(0, Constants::bh()); instr.set_operand(1, Constants::cl()); } } // special case for mulx else if (opc == MULX_R32_R32_R32) { instr.set_operand(0, Constants::eax()); instr.set_operand(1, Constants::ebx()); instr.set_operand(2, Constants::ecx()); } else if (opc == MULX_R64_R64_R64) { instr.set_operand(0, Constants::rax()); instr.set_operand(1, Constants::rbx()); instr.set_operand(2, Constants::rcx()); } // normal case else { for (size_t i = 0; i < instr.arity(); i++) { auto t = instr.type(i); if (strata_is_supported_type(t) || strata_is_supported_type_reason(t) == StrataSupportedReason::MM || strata_is_supported_type_reason(t) == StrataSupportedReason::IMMEDIATE || strata_is_supported_type_reason(t) == StrataSupportedReason::MEMORY) { instr.set_operand(i, get_next_operand(t, imm8_val, samereg)); } else { std::cout << "unsupported type: " << t << std::endl; std::cout << (int) opc << std::endl; std::cout << opc << std::endl; std::cout << instr << std::endl; exit(1); } } } if (!instr.check()) { std::cout << "instruction not valid:" << instr << std::endl; exit(1); } return instr; } x64asm::Instruction strata_get_instruction_from_string(std::string xopcode, bool samereg) { // parse opcode // we use opc_8 to indicate that we want to use 8 as the imm8 argument smatch result; regex reg("(.*?)(_([0-9]+))?"); string opc_str; uint8_t num; if (regex_match(xopcode, result, reg)) { if (result[2] == "") { num = 0; } else { string t = result[3]; num = stoi(t); } opc_str = result[1]; } else { exit(3); } Opcode opc; stringstream ss(opc_str); ss >> opc; if (opc == LABEL_DEFN) { cerr << "ERROR: could not parse the extended opcoce: " << xopcode << endl; exit(1); } return strata_get_instruction(opc, num, samereg); } } // namespace stoke
38.414002
147
0.670079
[ "vector" ]
339ea1150f6015a03fa29ae465a943c98c376295
9,591
cpp
C++
dbbrain/src/v20210527/model/HealthReportTask.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
dbbrain/src/v20210527/model/HealthReportTask.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
dbbrain/src/v20210527/model/HealthReportTask.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/dbbrain/v20210527/model/HealthReportTask.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Dbbrain::V20210527::Model; using namespace std; HealthReportTask::HealthReportTask() : m_asyncRequestIdHasBeenSet(false), m_sourceHasBeenSet(false), m_progressHasBeenSet(false), m_createTimeHasBeenSet(false), m_startTimeHasBeenSet(false), m_endTimeHasBeenSet(false), m_instanceInfoHasBeenSet(false), m_healthStatusHasBeenSet(false) { } CoreInternalOutcome HealthReportTask::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("AsyncRequestId") && !value["AsyncRequestId"].IsNull()) { if (!value["AsyncRequestId"].IsInt64()) { return CoreInternalOutcome(Error("response `HealthReportTask.AsyncRequestId` IsInt64=false incorrectly").SetRequestId(requestId)); } m_asyncRequestId = value["AsyncRequestId"].GetInt64(); m_asyncRequestIdHasBeenSet = true; } if (value.HasMember("Source") && !value["Source"].IsNull()) { if (!value["Source"].IsString()) { return CoreInternalOutcome(Error("response `HealthReportTask.Source` IsString=false incorrectly").SetRequestId(requestId)); } m_source = string(value["Source"].GetString()); m_sourceHasBeenSet = true; } if (value.HasMember("Progress") && !value["Progress"].IsNull()) { if (!value["Progress"].IsInt64()) { return CoreInternalOutcome(Error("response `HealthReportTask.Progress` IsInt64=false incorrectly").SetRequestId(requestId)); } m_progress = value["Progress"].GetInt64(); m_progressHasBeenSet = true; } if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull()) { if (!value["CreateTime"].IsString()) { return CoreInternalOutcome(Error("response `HealthReportTask.CreateTime` IsString=false incorrectly").SetRequestId(requestId)); } m_createTime = string(value["CreateTime"].GetString()); m_createTimeHasBeenSet = true; } if (value.HasMember("StartTime") && !value["StartTime"].IsNull()) { if (!value["StartTime"].IsString()) { return CoreInternalOutcome(Error("response `HealthReportTask.StartTime` IsString=false incorrectly").SetRequestId(requestId)); } m_startTime = string(value["StartTime"].GetString()); m_startTimeHasBeenSet = true; } if (value.HasMember("EndTime") && !value["EndTime"].IsNull()) { if (!value["EndTime"].IsString()) { return CoreInternalOutcome(Error("response `HealthReportTask.EndTime` IsString=false incorrectly").SetRequestId(requestId)); } m_endTime = string(value["EndTime"].GetString()); m_endTimeHasBeenSet = true; } if (value.HasMember("InstanceInfo") && !value["InstanceInfo"].IsNull()) { if (!value["InstanceInfo"].IsObject()) { return CoreInternalOutcome(Error("response `HealthReportTask.InstanceInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_instanceInfo.Deserialize(value["InstanceInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_instanceInfoHasBeenSet = true; } if (value.HasMember("HealthStatus") && !value["HealthStatus"].IsNull()) { if (!value["HealthStatus"].IsObject()) { return CoreInternalOutcome(Error("response `HealthReportTask.HealthStatus` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_healthStatus.Deserialize(value["HealthStatus"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_healthStatusHasBeenSet = true; } return CoreInternalOutcome(true); } void HealthReportTask::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_asyncRequestIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AsyncRequestId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_asyncRequestId, allocator); } if (m_sourceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Source"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_source.c_str(), allocator).Move(), allocator); } if (m_progressHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Progress"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_progress, allocator); } if (m_createTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CreateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_createTime.c_str(), allocator).Move(), allocator); } if (m_startTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "StartTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_startTime.c_str(), allocator).Move(), allocator); } if (m_endTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EndTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_endTime.c_str(), allocator).Move(), allocator); } if (m_instanceInfoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_instanceInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_healthStatusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HealthStatus"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_healthStatus.ToJsonObject(value[key.c_str()], allocator); } } int64_t HealthReportTask::GetAsyncRequestId() const { return m_asyncRequestId; } void HealthReportTask::SetAsyncRequestId(const int64_t& _asyncRequestId) { m_asyncRequestId = _asyncRequestId; m_asyncRequestIdHasBeenSet = true; } bool HealthReportTask::AsyncRequestIdHasBeenSet() const { return m_asyncRequestIdHasBeenSet; } string HealthReportTask::GetSource() const { return m_source; } void HealthReportTask::SetSource(const string& _source) { m_source = _source; m_sourceHasBeenSet = true; } bool HealthReportTask::SourceHasBeenSet() const { return m_sourceHasBeenSet; } int64_t HealthReportTask::GetProgress() const { return m_progress; } void HealthReportTask::SetProgress(const int64_t& _progress) { m_progress = _progress; m_progressHasBeenSet = true; } bool HealthReportTask::ProgressHasBeenSet() const { return m_progressHasBeenSet; } string HealthReportTask::GetCreateTime() const { return m_createTime; } void HealthReportTask::SetCreateTime(const string& _createTime) { m_createTime = _createTime; m_createTimeHasBeenSet = true; } bool HealthReportTask::CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; } string HealthReportTask::GetStartTime() const { return m_startTime; } void HealthReportTask::SetStartTime(const string& _startTime) { m_startTime = _startTime; m_startTimeHasBeenSet = true; } bool HealthReportTask::StartTimeHasBeenSet() const { return m_startTimeHasBeenSet; } string HealthReportTask::GetEndTime() const { return m_endTime; } void HealthReportTask::SetEndTime(const string& _endTime) { m_endTime = _endTime; m_endTimeHasBeenSet = true; } bool HealthReportTask::EndTimeHasBeenSet() const { return m_endTimeHasBeenSet; } InstanceBasicInfo HealthReportTask::GetInstanceInfo() const { return m_instanceInfo; } void HealthReportTask::SetInstanceInfo(const InstanceBasicInfo& _instanceInfo) { m_instanceInfo = _instanceInfo; m_instanceInfoHasBeenSet = true; } bool HealthReportTask::InstanceInfoHasBeenSet() const { return m_instanceInfoHasBeenSet; } HealthStatus HealthReportTask::GetHealthStatus() const { return m_healthStatus; } void HealthReportTask::SetHealthStatus(const HealthStatus& _healthStatus) { m_healthStatus = _healthStatus; m_healthStatusHasBeenSet = true; } bool HealthReportTask::HealthStatusHasBeenSet() const { return m_healthStatusHasBeenSet; }
28.37574
142
0.685747
[ "object", "model" ]
33a2021888e77dc17757ced6f2c6b722433b4625
3,430
hh
C++
src/cost.hh
laurentnoe/iedera
07a1a6b236fe69e684de614693b722981da4c189
[ "BSD-2-Clause", "CECILL-B" ]
1
2021-04-15T09:33:18.000Z
2021-04-15T09:33:18.000Z
src/cost.hh
LaurentNoe/iedera
91b8d745da91b124186f7eae31e3df194b202473
[ "BSD-2-Clause", "CECILL-B" ]
1
2018-03-31T22:05:07.000Z
2018-03-31T22:05:07.000Z
src/cost.hh
LaurentNoe/iedera
91b8d745da91b124186f7eae31e3df194b202473
[ "BSD-2-Clause", "CECILL-B" ]
1
2017-01-15T08:45:39.000Z
2017-01-15T08:45:39.000Z
#ifndef __COST_HH__ #define __COST_HH__ /** @defgroup cost cost class template * @brief costs defined over the templated C elements (int, long int, long long int, or other ...), * and in the @f$ (\oplus = min, \otimes = plus) @f$ tropical semi-ring * * * @see matrix, automaton */ // @{ //STL #include <functional> #include <algorithm> #include <vector> //STD #include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <string> //STR using namespace std; /** * @class cost * @brief costs defined in the @f$ (\oplus = min, \otimes = plus) @f$ * tropical semi-ring * * This class defines common operations in the @f$ (\oplus = min, \otimes = plus) @f$ tropical semi-ring to get * compatibility issues with the classical @f$ (\oplus = +, \otimes = \times) @f$ semi-ring used for probabilistic * computations. As such, any algorithm programmed with @f$ (\oplus, \otimes) @f$ * (C++ operators @f$+@f$ and @f$\times@f$) can be used in both cases : either on costs, otherwise on more * traditional floating point values... * * @see matrix, automaton */ template<typename C> class cost { public: /// Build a cost cost(const C c): _c(c) {}; /// Erase a cost ~cost() {}; // @{ /// Operator + (min) for two costs template<typename U> friend cost<U> operator+ (const cost<U> l,const cost<U> r); /// Operator @f$ \times @f$ (add) for two costs template<typename U> friend cost<U> operator* (const cost<U> l,const cost<U> r); /// Operator @f$ != @f$ for two costs template<typename U> friend bool operator!= (const cost<U> l,const cost<U> r); /// Operator @f$ == @f$ for two costs template<typename U> friend bool operator== (const cost<U> l,const cost<U> r); /// Operator @f$ < @f$ for two costs template<typename U> friend bool operator< (const cost<U> l,const cost<U> r); /// Operator @f$ > @f$ for two costs template<typename U> friend bool operator> (const cost<U> l,const cost<U> r); // @} // @{ /// Print a cost template<typename U> friend ostream& operator<< (ostream& os, const cost<U>& c); /// Load a cost template<typename U> friend istream& operator>> (istream& is, cost<U>& c); // @} protected: /// memorized cost C _c; }; /// Operator + (min) for two costs template<typename C> inline cost<C> operator+ (const cost<C> l, const cost<C> r) { cost<C> x(MIN(l._c,r._c)); return x; } /// Operator @f$ \times @f$ (add) for two costs template<typename C> inline cost<C> operator* (const cost<C> l, const cost<C> r) { cost<C> x(l._c + r._c); return x; } /// Operator @f$ == @f$ for two costs template<typename C> inline bool operator== (const cost<C> l, const cost<C> r) { return l._c == r._c; } /// Operator @f$ != @f$ for two costs template<typename C> inline bool operator!= (const cost<C> l, const cost<C> r) { return l._c != r._c; } /// Operator @f$ < @f$ for two costs template<typename C> inline bool operator< (const cost<C> l, const cost<C> r) { return l._c < r._c; } /// Operator @f$ > @f$ for two costs template<typename C> inline bool operator> (const cost<C> l, const cost<C> r) { return l._c > r._c; } /// Print a cost template<typename C> ostream& operator<< (ostream& os, const cost<C>& c) { os << c._c; return os; } /// Load a cost template<typename C> istream& operator>> (istream& is, cost<C>& c) { is >> c._c; return is; } // @} #endif
26.796875
116
0.628571
[ "vector" ]
33a4afb6374c4459d8866c1a62a3c1b960e82f18
13,750
cpp
C++
clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
MochalovaAn/llvm
528aa5ca4aa9df447dc3497ef19da3b124e88d7d
[ "Apache-2.0" ]
1
2021-02-17T04:40:38.000Z
2021-02-17T04:40:38.000Z
clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
MochalovaAn/llvm
528aa5ca4aa9df447dc3497ef19da3b124e88d7d
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
MochalovaAn/llvm
528aa5ca4aa9df447dc3497ef19da3b124e88d7d
[ "Apache-2.0" ]
null
null
null
//===-- CompileCommandsTests.cpp ------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "CompileCommands.h" #include "Config.h" #include "TestFS.h" #include "support/Context.h" #include "llvm/ADT/ScopeExit.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Process.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace clang { namespace clangd { namespace { using ::testing::_; using ::testing::Contains; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::Not; // Sadly, CommandMangler::detect(), which contains much of the logic, is // a bunch of untested integration glue. We test the string manipulation here // assuming its results are correct. // Make use of all features and assert the exact command we get out. // Other tests just verify presence/absence of certain args. TEST(CommandMangler, Everything) { auto Mangler = CommandMangler::forTests(); Mangler.ClangPath = testPath("fake/clang"); Mangler.ResourceDir = testPath("fake/resources"); Mangler.Sysroot = testPath("fake/sysroot"); std::vector<std::string> Cmd = {"clang++", "-Xclang", "-load", "-Xclang", "plugin", "-MF", "dep", "foo.cc"}; Mangler.adjust(Cmd); EXPECT_THAT(Cmd, ElementsAre(testPath("fake/clang++"), "foo.cc", "-fsyntax-only", "-resource-dir=" + testPath("fake/resources"), "-isysroot", testPath("fake/sysroot"))); } TEST(CommandMangler, ResourceDir) { auto Mangler = CommandMangler::forTests(); Mangler.ResourceDir = testPath("fake/resources"); std::vector<std::string> Cmd = {"clang++", "foo.cc"}; Mangler.adjust(Cmd); EXPECT_THAT(Cmd, Contains("-resource-dir=" + testPath("fake/resources"))); } TEST(CommandMangler, Sysroot) { auto Mangler = CommandMangler::forTests(); Mangler.Sysroot = testPath("fake/sysroot"); std::vector<std::string> Cmd = {"clang++", "foo.cc"}; Mangler.adjust(Cmd); EXPECT_THAT(llvm::join(Cmd, " "), HasSubstr("-isysroot " + testPath("fake/sysroot"))); } TEST(CommandMangler, StripPlugins) { auto Mangler = CommandMangler::forTests(); std::vector<std::string> Cmd = {"clang++", "-Xclang", "-load", "-Xclang", "plugin", "foo.cc"}; Mangler.adjust(Cmd); for (const char* Stripped : {"-Xclang", "-load", "plugin"}) EXPECT_THAT(Cmd, Not(Contains(Stripped))); } TEST(CommandMangler, StripOutput) { auto Mangler = CommandMangler::forTests(); std::vector<std::string> Cmd = {"clang++", "-MF", "dependency", "-c", "foo.cc"}; Mangler.adjust(Cmd); for (const char* Stripped : {"-MF", "dependency"}) EXPECT_THAT(Cmd, Not(Contains(Stripped))); } TEST(CommandMangler, StripShowIncludes) { auto Mangler = CommandMangler::forTests(); std::vector<std::string> Cmd = {"clang-cl", "/showIncludes", "foo.cc"}; Mangler.adjust(Cmd); EXPECT_THAT(Cmd, Not(Contains("/showIncludes"))); } TEST(CommandMangler, StripShowIncludesUser) { auto Mangler = CommandMangler::forTests(); std::vector<std::string> Cmd = {"clang-cl", "/showIncludes:user", "foo.cc"}; Mangler.adjust(Cmd); EXPECT_THAT(Cmd, Not(Contains("/showIncludes:user"))); } TEST(CommandMangler, ClangPath) { auto Mangler = CommandMangler::forTests(); Mangler.ClangPath = testPath("fake/clang"); std::vector<std::string> Cmd = {"clang++", "foo.cc"}; Mangler.adjust(Cmd); EXPECT_EQ(testPath("fake/clang++"), Cmd.front()); Cmd = {"unknown-binary", "foo.cc"}; Mangler.adjust(Cmd); EXPECT_EQ(testPath("fake/unknown-binary"), Cmd.front()); Cmd = {testPath("path/clang++"), "foo.cc"}; Mangler.adjust(Cmd); EXPECT_EQ(testPath("path/clang++"), Cmd.front()); Cmd = {"foo/unknown-binary", "foo.cc"}; Mangler.adjust(Cmd); EXPECT_EQ("foo/unknown-binary", Cmd.front()); } // Only run the PATH/symlink resolving test on unix, we need to fiddle // with permissions and environment variables... #ifdef LLVM_ON_UNIX MATCHER(Ok, "") { if (arg) { *result_listener << arg.message(); return false; } return true; } TEST(CommandMangler, ClangPathResolve) { // Set up filesystem: // /temp/ // bin/ // foo -> temp/lib/bar // lib/ // bar llvm::SmallString<256> TempDir; ASSERT_THAT(llvm::sys::fs::createUniqueDirectory("ClangPathResolve", TempDir), Ok()); // /var/tmp is a symlink on Mac. Resolve it so we're asserting the right path. ASSERT_THAT(llvm::sys::fs::real_path(TempDir.str(), TempDir), Ok()); auto CleanDir = llvm::make_scope_exit( [&] { llvm::sys::fs::remove_directories(TempDir); }); ASSERT_THAT(llvm::sys::fs::create_directory(TempDir + "/bin"), Ok()); ASSERT_THAT(llvm::sys::fs::create_directory(TempDir + "/lib"), Ok()); int FD; ASSERT_THAT(llvm::sys::fs::openFileForWrite(TempDir + "/lib/bar", FD), Ok()); ASSERT_THAT(llvm::sys::Process::SafelyCloseFileDescriptor(FD), Ok()); ::chmod((TempDir + "/lib/bar").str().c_str(), 0755); // executable ASSERT_THAT( llvm::sys::fs::create_link(TempDir + "/lib/bar", TempDir + "/bin/foo"), Ok()); // Test the case where the driver is an absolute path to a symlink. auto Mangler = CommandMangler::forTests(); Mangler.ClangPath = testPath("fake/clang"); std::vector<std::string> Cmd = {(TempDir + "/bin/foo").str(), "foo.cc"}; Mangler.adjust(Cmd); // Directory based on resolved symlink, basename preserved. EXPECT_EQ((TempDir + "/lib/foo").str(), Cmd.front()); // Set PATH to point to temp/bin so we can find 'foo' on it. ASSERT_TRUE(::getenv("PATH")); auto RestorePath = llvm::make_scope_exit([OldPath = std::string(::getenv("PATH"))] { ::setenv("PATH", OldPath.c_str(), 1); }); ::setenv("PATH", (TempDir + "/bin").str().c_str(), /*overwrite=*/1); // Test the case where the driver is a $PATH-relative path to a symlink. Mangler = CommandMangler::forTests(); Mangler.ClangPath = testPath("fake/clang"); // Driver found on PATH. Cmd = {"foo", "foo.cc"}; Mangler.adjust(Cmd); // Found the symlink and resolved the path as above. EXPECT_EQ((TempDir + "/lib/foo").str(), Cmd.front()); // Symlink not resolved with -no-canonical-prefixes. Cmd = {"foo", "-no-canonical-prefixes", "foo.cc"}; Mangler.adjust(Cmd); EXPECT_EQ((TempDir + "/bin/foo").str(), Cmd.front()); } #endif TEST(CommandMangler, ConfigEdits) { auto Mangler = CommandMangler::forTests(); std::vector<std::string> Cmd = {"clang++", "foo.cc"}; { Config Cfg; Cfg.CompileFlags.Edits.push_back([](std::vector<std::string> &Argv) { for (auto &Arg : Argv) for (char &C : Arg) C = llvm::toUpper(C); }); Cfg.CompileFlags.Edits.push_back( [](std::vector<std::string> &Argv) { Argv.push_back("--hello"); }); WithContextValue WithConfig(Config::Key, std::move(Cfg)); Mangler.adjust(Cmd); } // Edits are applied in given order and before other mangling. EXPECT_THAT(Cmd, ElementsAre(_, "FOO.CC", "--hello", "-fsyntax-only")); } static std::string strip(llvm::StringRef Arg, llvm::StringRef Argv) { llvm::SmallVector<llvm::StringRef> Parts; llvm::SplitString(Argv, Parts); std::vector<std::string> Args = {Parts.begin(), Parts.end()}; ArgStripper S; S.strip(Arg); S.process(Args); return printArgv(Args); } TEST(ArgStripperTest, Spellings) { // May use alternate prefixes. EXPECT_EQ(strip("-pedantic", "clang -pedantic foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("-pedantic", "clang --pedantic foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("--pedantic", "clang -pedantic foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("--pedantic", "clang --pedantic foo.cc"), "clang foo.cc"); // May use alternate names. EXPECT_EQ(strip("-x", "clang -x c++ foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("-x", "clang --language=c++ foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("--language=", "clang -x c++ foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("--language=", "clang --language=c++ foo.cc"), "clang foo.cc"); } TEST(ArgStripperTest, UnknownFlag) { EXPECT_EQ(strip("-xyzzy", "clang -xyzzy foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("-xyz*", "clang -xyzzy foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("-xyzzy", "clang -Xclang -xyzzy foo.cc"), "clang foo.cc"); } TEST(ArgStripperTest, Xclang) { // Flags may be -Xclang escaped. EXPECT_EQ(strip("-ast-dump", "clang -Xclang -ast-dump foo.cc"), "clang foo.cc"); // Args may be -Xclang escaped. EXPECT_EQ(strip("-add-plugin", "clang -Xclang -add-plugin -Xclang z foo.cc"), "clang foo.cc"); } TEST(ArgStripperTest, ClangCL) { // /I is a synonym for -I in clang-cl mode only. // Not stripped by default. EXPECT_EQ(strip("-I", "clang -I /usr/inc /Interesting/file.cc"), "clang /Interesting/file.cc"); // Stripped when invoked as clang-cl. EXPECT_EQ(strip("-I", "clang-cl -I /usr/inc /Interesting/file.cc"), "clang-cl"); // Stripped when invoked as CL.EXE EXPECT_EQ(strip("-I", "CL.EXE -I /usr/inc /Interesting/file.cc"), "CL.EXE"); // Stripped when passed --driver-mode=cl. EXPECT_EQ(strip("-I", "cc -I /usr/inc /Interesting/file.cc --driver-mode=cl"), "cc --driver-mode=cl"); } TEST(ArgStripperTest, ArgStyles) { // Flag EXPECT_EQ(strip("-Qn", "clang -Qn foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("-Qn", "clang -QnZ foo.cc"), "clang -QnZ foo.cc"); // Joined EXPECT_EQ(strip("-std=", "clang -std= foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("-std=", "clang -std=c++11 foo.cc"), "clang foo.cc"); // Separate EXPECT_EQ(strip("-mllvm", "clang -mllvm X foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("-mllvm", "clang -mllvmX foo.cc"), "clang -mllvmX foo.cc"); // RemainingArgsJoined EXPECT_EQ(strip("/link", "clang-cl /link b c d foo.cc"), "clang-cl"); EXPECT_EQ(strip("/link", "clang-cl /linka b c d foo.cc"), "clang-cl"); // CommaJoined EXPECT_EQ(strip("-Wl,", "clang -Wl,x,y foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("-Wl,", "clang -Wl, foo.cc"), "clang foo.cc"); // MultiArg EXPECT_EQ(strip("-segaddr", "clang -segaddr a b foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("-segaddr", "clang -segaddra b foo.cc"), "clang -segaddra b foo.cc"); // JoinedOrSeparate EXPECT_EQ(strip("-G", "clang -GX foo.cc"), "clang foo.cc"); EXPECT_EQ(strip("-G", "clang -G X foo.cc"), "clang foo.cc"); // JoinedAndSeparate EXPECT_EQ(strip("-plugin-arg-", "clang -cc1 -plugin-arg-X Y foo.cc"), "clang -cc1 foo.cc"); EXPECT_EQ(strip("-plugin-arg-", "clang -cc1 -plugin-arg- Y foo.cc"), "clang -cc1 foo.cc"); } TEST(ArgStripperTest, EndOfList) { // When we hit the end-of-args prematurely, we don't crash. // We consume the incomplete args if we've matched the target option. EXPECT_EQ(strip("-I", "clang -Xclang"), "clang -Xclang"); EXPECT_EQ(strip("-I", "clang -Xclang -I"), "clang"); EXPECT_EQ(strip("-I", "clang -I -Xclang"), "clang"); EXPECT_EQ(strip("-I", "clang -I"), "clang"); } TEST(ArgStripperTest, Multiple) { ArgStripper S; S.strip("-o"); S.strip("-c"); std::vector<std::string> Args = {"clang", "-o", "foo.o", "foo.cc", "-c"}; S.process(Args); EXPECT_THAT(Args, ElementsAre("clang", "foo.cc")); } TEST(ArgStripperTest, Warning) { { // -W is a flag name ArgStripper S; S.strip("-W"); std::vector<std::string> Args = {"clang", "-Wfoo", "-Wno-bar", "-Werror", "foo.cc"}; S.process(Args); EXPECT_THAT(Args, ElementsAre("clang", "foo.cc")); } { // -Wfoo is not a flag name, matched literally. ArgStripper S; S.strip("-Wunused"); std::vector<std::string> Args = {"clang", "-Wunused", "-Wno-unused", "foo.cc"}; S.process(Args); EXPECT_THAT(Args, ElementsAre("clang", "-Wno-unused", "foo.cc")); } } TEST(ArgStripperTest, Define) { { // -D is a flag name ArgStripper S; S.strip("-D"); std::vector<std::string> Args = {"clang", "-Dfoo", "-Dbar=baz", "foo.cc"}; S.process(Args); EXPECT_THAT(Args, ElementsAre("clang", "foo.cc")); } { // -Dbar is not: matched literally ArgStripper S; S.strip("-Dbar"); std::vector<std::string> Args = {"clang", "-Dfoo", "-Dbar=baz", "foo.cc"}; S.process(Args); EXPECT_THAT(Args, ElementsAre("clang", "-Dfoo", "-Dbar=baz", "foo.cc")); S.strip("-Dfoo"); S.process(Args); EXPECT_THAT(Args, ElementsAre("clang", "-Dbar=baz", "foo.cc")); S.strip("-Dbar=*"); S.process(Args); EXPECT_THAT(Args, ElementsAre("clang", "foo.cc")); } } TEST(ArgStripperTest, OrderDependent) { ArgStripper S; // If -include is stripped first, we see -pch as its arg and foo.pch remains. // To get this case right, we must process -include-pch first. S.strip("-include"); S.strip("-include-pch"); std::vector<std::string> Args = {"clang", "-include-pch", "foo.pch", "foo.cc"}; S.process(Args); EXPECT_THAT(Args, ElementsAre("clang", "foo.cc")); } TEST(PrintArgvTest, All) { std::vector<llvm::StringRef> Args = { "one", "two", "thr ee", "f\"o\"ur", "fi\\ve", "$" }; const char *Expected = R"(one two "thr ee" "f\"o\"ur" "fi\\ve" $)"; EXPECT_EQ(Expected, printArgv(Args)); } } // namespace } // namespace clangd } // namespace clang
35.994764
80
0.619491
[ "vector" ]
33a76e176a57e094e0fb6a1bca844937e1e67ce3
1,657
hpp
C++
src/ui/ns_font.hpp
FreeAllegiance/AllegianceDX7
3955756dffea8e7e31d3a55fcf6184232b792195
[ "MIT" ]
76
2015-08-18T19:18:40.000Z
2022-01-08T12:47:22.000Z
src/ui/ns_font.hpp
StudentAlleg/Allegiance
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
[ "MIT" ]
37
2015-08-14T22:44:12.000Z
2020-01-21T01:03:06.000Z
src/ui/ns_font.hpp
StudentAlleg/Allegiance
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
[ "MIT" ]
42
2015-08-13T23:31:35.000Z
2022-03-17T02:20:26.000Z
#pragma once #include "ui.h" #include "items.hpp" using namespace std::literals; class FontNamespace { public: static void AddNamespace(sol::state* m_pLua) { sol::table table = m_pLua->create_table(); table["Create"] = [](std::string name, TRef<Number> size, sol::optional<sol::table> object) { std::map<std::string, TRef<Boolean>> props = { { "Bold", new Boolean(false) }, { "Italic", new Boolean(false) }, { "Underline", new Boolean(false) } }; if (object) { object.value().for_each([&props](sol::object key, sol::object value) { std::string strKey = key.as<std::string>(); if (props.find(strKey) == props.end()) { throw std::runtime_error("Unknown key. Use 'Bold', 'Italic', 'Underline'"); } props[strKey] = value.as<TRef<Boolean>>(); }); } return (TRef<FontValue>)(FontValue*)new TransformedValue4<TRef<IEngineFont>, float, bool, bool, bool>([name](float size, bool bold, bool italic, bool underline) { return CreateEngineFont(name, std::min(100, (int)size), 0, bold, italic, underline); }, size, props["Bold"], props["Italic"], props["Underline"]); }; table["Height"] = [](const TRef<FontValue>& font) { return (TRef<Number>)new TransformedValue<float, TRef<IEngineFont>>([](IEngineFont* font) { return (float)font->GetHeight(); }, font); }; m_pLua->set("Font", table); } };
36.822222
174
0.528666
[ "object" ]
33a92f5ed0909be33d62cbcff3ace5daa93f1920
6,520
cpp
C++
code/w32.mt/Thread.cpp
AndreLouisCaron/w32
75b26a149e268138cbcf43e6f4669756ac4ac850
[ "BSD-2-Clause" ]
9
2015-12-30T15:21:20.000Z
2021-03-21T04:23:14.000Z
code/w32.mt/Thread.cpp
AndreLouisCaron/w32
75b26a149e268138cbcf43e6f4669756ac4ac850
[ "BSD-2-Clause" ]
1
2022-01-02T11:12:57.000Z
2022-01-02T11:12:57.000Z
code/w32.mt/Thread.cpp
AndreLouisCaron/w32
75b26a149e268138cbcf43e6f4669756ac4ac850
[ "BSD-2-Clause" ]
5
2018-04-09T04:44:58.000Z
2020-04-10T12:51:51.000Z
// Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <w32.mt/Thread.hpp> #include <w32/Error.hpp> namespace { ::HANDLE find ( ::DWORD id ) { const ::HANDLE result = ::OpenThread( THREAD_ALL_ACCESS, FALSE, id ); if ( result == NULL ) { const ::DWORD error = ::GetLastError(); UNCHECKED_WIN32C_ERROR(OpenThread, error); } return (result); } } namespace w32 { namespace mt { ::HANDLE Thread::allocate ( ::LPTHREAD_START_ROUTINE function, ::LPVOID context ) { ::DWORD identifier = 0; const ::HANDLE result = ::CreateThread( 0, 0, function, context, 0, &identifier ); if ( result == INVALID_HANDLE_VALUE ) { const ::DWORD error = ::GetLastError(); UNCHECKED_WIN32C_ERROR(CreateThread, error); } return (result); } Thread Thread::current () { const Handle handle(proxy(::GetCurrentThread())); return (Thread(handle)); } Thread Thread::open ( Identifier identifier ) { const Handle handle(claim(::find(identifier))); return (Thread(handle)); } Thread::Thread ( const Handle& handle ) : Object(handle) { } Thread::Thread ( Function function, Parameter parameter ) : Object(Object::claim(allocate(function, parameter))) { } #if _WIN32_WINNT >= _WIN32_WINNT_VISTA Thread::Identifier Thread::identifier () const { const ::DWORD identifier = ::GetThreadId(handle()); if ( identifier == 0 ) { const ::DWORD error = ::GetLastError(); UNCHECKED_WIN32C_ERROR(GetThreadId, error); } return (identifier); } #endif void Thread::priority ( const Priority& priority ) { const ::BOOL result = ::SetThreadPriority( handle(), priority.value() ); if ( result == 0 ) { const ::DWORD error = ::GetLastError(); UNCHECKED_WIN32C_ERROR(SetThreadPriority, error); } } void Thread::terminate ( dword status ) { const ::BOOL result = ::TerminateThread(handle(),status); if ( result == 0 ) { const ::DWORD error = ::GetLastError(); UNCHECKED_WIN32C_ERROR(TerminateThread, error); } } dword Thread::status () const { ::DWORD value = 0; const ::BOOL result = ::GetExitCodeThread(handle(),&value); if ( result == 0 ) { const ::DWORD error = ::GetLastError(); UNCHECKED_WIN32C_ERROR(GetExitCodeThread, error); } return (value); } bool Thread::alive () const { return (status() == STILL_ACTIVE); } dword Thread::suspend () { const ::DWORD count = ::SuspendThread(handle()); if ( count == static_cast<::DWORD>(-1) ) { const ::DWORD error = ::GetLastError(); UNCHECKED_WIN32C_ERROR(SuspendThread, error); } return (count); } dword Thread::resume () { const ::DWORD count = ::ResumeThread(handle()); if ( count == static_cast<::DWORD>(-1) ) { const ::DWORD error = ::GetLastError(); UNCHECKED_WIN32C_ERROR(ResumeThread, error); } return (count); } void Thread::join () const { Waitable(*this).wait(); } bool Thread::join ( const Timespan& timeout ) const { return (Waitable(*this).wait(timeout)); } Thread::operator Waitable () const { return Waitable(handle()); } void sleep ( const Timespan& timespan ) { ::Sleep(timespan.ticks()); } bool alertable ( const Timespan& timespan ) { return (::SleepEx(timespan.ticks(),TRUE) == WAIT_IO_COMPLETION); } const Thread::Priority Thread::Priority::idle () { return (THREAD_PRIORITY_IDLE); } const Thread::Priority Thread::Priority::lowest () { return (THREAD_PRIORITY_LOWEST); } const Thread::Priority Thread::Priority::lower () { return (THREAD_PRIORITY_BELOW_NORMAL); } const Thread::Priority Thread::Priority::normal () { return (THREAD_PRIORITY_NORMAL); } const Thread::Priority Thread::Priority::higher () { return (THREAD_PRIORITY_ABOVE_NORMAL); } const Thread::Priority Thread::Priority::highest () { return (THREAD_PRIORITY_HIGHEST); } const Thread::Priority Thread::Priority::critical () { return (THREAD_PRIORITY_TIME_CRITICAL); } Thread::Priority::Priority ( Value value ) : myValue(value) { } Thread::Priority::Value Thread::Priority::value () const { return (myValue); } Thread::Priority::operator Thread::Priority::Value () const { return (value()); } void yield () { // If there are no other threads, this does nothing. ::SwitchToThread(); } void exit ( dword code ) { ::ExitThread(code); } } }
26.831276
74
0.597393
[ "object" ]
33aa969b4f091934f776c8e81e4808cf3865cb4d
38,860
cpp
C++
source/d3d11/d3d11_device_context.cpp
eliemichel/reshade
797d6b22b27df3fca34e7a0a8e7168df5be329c8
[ "BSD-3-Clause" ]
6
2020-03-22T15:41:29.000Z
2021-11-25T02:52:30.000Z
source/d3d11/d3d11_device_context.cpp
eliemichel/reshade
797d6b22b27df3fca34e7a0a8e7168df5be329c8
[ "BSD-3-Clause" ]
null
null
null
source/d3d11/d3d11_device_context.cpp
eliemichel/reshade
797d6b22b27df3fca34e7a0a8e7168df5be329c8
[ "BSD-3-Clause" ]
1
2021-11-24T23:17:26.000Z
2021-11-24T23:17:26.000Z
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "log.hpp" #include "d3d11_device.hpp" #include "d3d11_device_context.hpp" #include "d3d11_command_list.hpp" D3D11DeviceContext::D3D11DeviceContext(D3D11Device *device, ID3D11DeviceContext *original) : _orig(original), _interface_version(0), _device(device) { assert(original != nullptr); } D3D11DeviceContext::D3D11DeviceContext(D3D11Device *device, ID3D11DeviceContext1 *original) : _orig(original), _interface_version(1), _device(device) { assert(original != nullptr); } D3D11DeviceContext::D3D11DeviceContext(D3D11Device *device, ID3D11DeviceContext2 *original) : _orig(original), _interface_version(2), _device(device) { assert(original != nullptr); } D3D11DeviceContext::D3D11DeviceContext(D3D11Device *device, ID3D11DeviceContext3 *original) : _orig(original), _interface_version(3), _device(device) { assert(original != nullptr); } bool D3D11DeviceContext::check_and_upgrade_interface(REFIID riid) { if (riid == __uuidof(this) || riid == __uuidof(IUnknown) || riid == __uuidof(ID3D11DeviceChild)) return true; static const IID iid_lookup[] = { __uuidof(ID3D11DeviceContext), __uuidof(ID3D11DeviceContext1), __uuidof(ID3D11DeviceContext2), __uuidof(ID3D11DeviceContext3), __uuidof(ID3D11DeviceContext4), }; for (unsigned int version = 0; version < ARRAYSIZE(iid_lookup); ++version) { if (riid != iid_lookup[version]) continue; if (version > _interface_version) { IUnknown *new_interface = nullptr; if (FAILED(_orig->QueryInterface(riid, reinterpret_cast<void **>(&new_interface)))) return false; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "Upgraded ID3D11DeviceContext" << _interface_version << " object " << this << " to ID3D11DeviceContext" << version << '.'; #endif _orig->Release(); _orig = static_cast<ID3D11DeviceContext *>(new_interface); _interface_version = version; } return true; } return false; } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::QueryInterface(REFIID riid, void **ppvObj) { if (ppvObj == nullptr) return E_POINTER; if (check_and_upgrade_interface(riid)) { AddRef(); *ppvObj = this; return S_OK; } return _orig->QueryInterface(riid, ppvObj); } ULONG STDMETHODCALLTYPE D3D11DeviceContext::AddRef() { _orig->AddRef(); return InterlockedIncrement(&_ref); } ULONG STDMETHODCALLTYPE D3D11DeviceContext::Release() { const ULONG ref = InterlockedDecrement(&_ref); const ULONG ref_orig = _orig->Release(); if (ref != 0) return ref; if (ref_orig != 0) LOG(WARN) << "Reference count for ID3D11DeviceContext" << _interface_version << " object " << this << " is inconsistent."; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "Destroyed ID3D11DeviceContext" << _interface_version << " object " << this << '.'; #endif delete this; return 0; } void STDMETHODCALLTYPE D3D11DeviceContext::GetDevice(ID3D11Device **ppDevice) { if (ppDevice == nullptr) return; _device->AddRef(); *ppDevice = _device; } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::GetPrivateData(REFGUID guid, UINT *pDataSize, void *pData) { return _orig->GetPrivateData(guid, pDataSize, pData); } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::SetPrivateData(REFGUID guid, UINT DataSize, const void *pData) { return _orig->SetPrivateData(guid, DataSize, pData); } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::SetPrivateDataInterface(REFGUID guid, const IUnknown *pData) { return _orig->SetPrivateDataInterface(guid, pData); } void STDMETHODCALLTYPE D3D11DeviceContext::VSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) { _orig->VSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::PSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) { _orig->PSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::PSSetShader(ID3D11PixelShader *pPixelShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) { _orig->PSSetShader(pPixelShader, ppClassInstances, NumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::PSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) { _orig->PSSetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::VSSetShader(ID3D11VertexShader *pVertexShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) { _orig->VSSetShader(pVertexShader, ppClassInstances, NumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::DrawIndexed(UINT IndexCount, UINT StartIndexLocation, INT BaseVertexLocation) { _orig->DrawIndexed(IndexCount, StartIndexLocation, BaseVertexLocation); _draw_call_tracker.on_draw(this, IndexCount); } void STDMETHODCALLTYPE D3D11DeviceContext::Draw(UINT VertexCount, UINT StartVertexLocation) { _orig->Draw(VertexCount, StartVertexLocation); _draw_call_tracker.on_draw(this, VertexCount); } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::Map(ID3D11Resource *pResource, UINT Subresource, D3D11_MAP MapType, UINT MapFlags, D3D11_MAPPED_SUBRESOURCE *pMappedResource) { #if RESHADE_DX11_CAPTURE_CONSTANT_BUFFERS _draw_call_tracker.on_map(pResource); #endif return _orig->Map(pResource, Subresource, MapType, MapFlags, pMappedResource); } void STDMETHODCALLTYPE D3D11DeviceContext::Unmap(ID3D11Resource *pResource, UINT Subresource) { _orig->Unmap(pResource, Subresource); } void STDMETHODCALLTYPE D3D11DeviceContext::PSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) { _orig->PSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::IASetInputLayout(ID3D11InputLayout *pInputLayout) { _orig->IASetInputLayout(pInputLayout); } void STDMETHODCALLTYPE D3D11DeviceContext::IASetVertexBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppVertexBuffers, const UINT *pStrides, const UINT *pOffsets) { _orig->IASetVertexBuffers(StartSlot, NumBuffers, ppVertexBuffers, pStrides, pOffsets); } void STDMETHODCALLTYPE D3D11DeviceContext::IASetIndexBuffer(ID3D11Buffer *pIndexBuffer, DXGI_FORMAT Format, UINT Offset) { _orig->IASetIndexBuffer(pIndexBuffer, Format, Offset); } void STDMETHODCALLTYPE D3D11DeviceContext::DrawIndexedInstanced(UINT IndexCountPerInstance, UINT InstanceCount, UINT StartIndexLocation, INT BaseVertexLocation, UINT StartInstanceLocation) { _orig->DrawIndexedInstanced(IndexCountPerInstance, InstanceCount, StartIndexLocation, BaseVertexLocation, StartInstanceLocation); _draw_call_tracker.on_draw(this, IndexCountPerInstance * InstanceCount); } void STDMETHODCALLTYPE D3D11DeviceContext::DrawInstanced(UINT VertexCountPerInstance, UINT InstanceCount, UINT StartVertexLocation, UINT StartInstanceLocation) { _orig->DrawInstanced(VertexCountPerInstance, InstanceCount, StartVertexLocation, StartInstanceLocation); _draw_call_tracker.on_draw(this, VertexCountPerInstance * InstanceCount); } void STDMETHODCALLTYPE D3D11DeviceContext::GSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) { _orig->GSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::GSSetShader(ID3D11GeometryShader *pShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) { _orig->GSSetShader(pShader, ppClassInstances, NumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY Topology) { _orig->IASetPrimitiveTopology(Topology); } void STDMETHODCALLTYPE D3D11DeviceContext::VSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) { _orig->VSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::VSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) { _orig->VSSetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::Begin(ID3D11Asynchronous *pAsync) { _orig->Begin(pAsync); } void STDMETHODCALLTYPE D3D11DeviceContext::End(ID3D11Asynchronous *pAsync) { _orig->End(pAsync); } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::GetData(ID3D11Asynchronous *pAsync, void *pData, UINT DataSize, UINT GetDataFlags) { return _orig->GetData(pAsync, pData, DataSize, GetDataFlags); } void STDMETHODCALLTYPE D3D11DeviceContext::SetPredication(ID3D11Predicate *pPredicate, BOOL PredicateValue) { _orig->SetPredication(pPredicate, PredicateValue); } void STDMETHODCALLTYPE D3D11DeviceContext::GSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) { _orig->GSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::GSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) { _orig->GSSetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::OMSetRenderTargets(UINT NumViews, ID3D11RenderTargetView *const *ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView) { #if RESHADE_DX11_CAPTURE_DEPTH_BUFFERS _draw_call_tracker.track_render_targets(NumViews, ppRenderTargetViews, pDepthStencilView); #endif _orig->OMSetRenderTargets(NumViews, ppRenderTargetViews, pDepthStencilView); } void STDMETHODCALLTYPE D3D11DeviceContext::OMSetRenderTargetsAndUnorderedAccessViews(UINT NumRTVs, ID3D11RenderTargetView *const *ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView, UINT UAVStartSlot, UINT NumUAVs, ID3D11UnorderedAccessView *const *ppUnorderedAccessViews, const UINT *pUAVInitialCounts) { #if RESHADE_DX11_CAPTURE_DEPTH_BUFFERS _draw_call_tracker.track_render_targets(NumRTVs, ppRenderTargetViews, pDepthStencilView); #endif _orig->OMSetRenderTargetsAndUnorderedAccessViews(NumRTVs, ppRenderTargetViews, pDepthStencilView, UAVStartSlot, NumUAVs, ppUnorderedAccessViews, pUAVInitialCounts); } void STDMETHODCALLTYPE D3D11DeviceContext::OMSetBlendState(ID3D11BlendState *pBlendState, const FLOAT BlendFactor[4], UINT SampleMask) { _orig->OMSetBlendState(pBlendState, BlendFactor, SampleMask); } void STDMETHODCALLTYPE D3D11DeviceContext::OMSetDepthStencilState(ID3D11DepthStencilState *pDepthStencilState, UINT StencilRef) { _orig->OMSetDepthStencilState(pDepthStencilState, StencilRef); } void STDMETHODCALLTYPE D3D11DeviceContext::SOSetTargets(UINT NumBuffers, ID3D11Buffer *const *ppSOTargets, const UINT *pOffsets) { _orig->SOSetTargets(NumBuffers, ppSOTargets, pOffsets); } void STDMETHODCALLTYPE D3D11DeviceContext::DrawAuto() { _orig->DrawAuto(); _draw_call_tracker.on_draw(this, 0); } void STDMETHODCALLTYPE D3D11DeviceContext::DrawIndexedInstancedIndirect(ID3D11Buffer *pBufferForArgs, UINT AlignedByteOffsetForArgs) { _orig->DrawIndexedInstancedIndirect(pBufferForArgs, AlignedByteOffsetForArgs); _draw_call_tracker.on_draw(this, 0); } void STDMETHODCALLTYPE D3D11DeviceContext::DrawInstancedIndirect(ID3D11Buffer *pBufferForArgs, UINT AlignedByteOffsetForArgs) { _orig->DrawInstancedIndirect(pBufferForArgs, AlignedByteOffsetForArgs); _draw_call_tracker.on_draw(this, 0); } void STDMETHODCALLTYPE D3D11DeviceContext::Dispatch(UINT ThreadGroupCountX, UINT ThreadGroupCountY, UINT ThreadGroupCountZ) { _orig->Dispatch(ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ); } void STDMETHODCALLTYPE D3D11DeviceContext::DispatchIndirect(ID3D11Buffer *pBufferForArgs, UINT AlignedByteOffsetForArgs) { _orig->DispatchIndirect(pBufferForArgs, AlignedByteOffsetForArgs); } void STDMETHODCALLTYPE D3D11DeviceContext::RSSetState(ID3D11RasterizerState *pRasterizerState) { _orig->RSSetState(pRasterizerState); } void STDMETHODCALLTYPE D3D11DeviceContext::RSSetViewports(UINT NumViewports, const D3D11_VIEWPORT *pViewports) { _orig->RSSetViewports(NumViewports, pViewports); } void STDMETHODCALLTYPE D3D11DeviceContext::RSSetScissorRects(UINT NumRects, const D3D11_RECT *pRects) { _orig->RSSetScissorRects(NumRects, pRects); } void STDMETHODCALLTYPE D3D11DeviceContext::CopySubresourceRegion(ID3D11Resource *pDstResource, UINT DstSubresource, UINT DstX, UINT DstY, UINT DstZ, ID3D11Resource *pSrcResource, UINT SrcSubresource, const D3D11_BOX *pSrcBox) { _orig->CopySubresourceRegion(pDstResource, DstSubresource, DstX, DstY, DstZ, pSrcResource, SrcSubresource, pSrcBox); } void STDMETHODCALLTYPE D3D11DeviceContext::CopyResource(ID3D11Resource *pDstResource, ID3D11Resource *pSrcResource) { _orig->CopyResource(pDstResource, pSrcResource); } void STDMETHODCALLTYPE D3D11DeviceContext::UpdateSubresource(ID3D11Resource *pDstResource, UINT DstSubresource, const D3D11_BOX *pDstBox, const void *pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch) { _orig->UpdateSubresource(pDstResource, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch); } void STDMETHODCALLTYPE D3D11DeviceContext::CopyStructureCount(ID3D11Buffer *pDstBuffer, UINT DstAlignedByteOffset, ID3D11UnorderedAccessView *pSrcView) { _orig->CopyStructureCount(pDstBuffer, DstAlignedByteOffset, pSrcView); } void STDMETHODCALLTYPE D3D11DeviceContext::ClearRenderTargetView(ID3D11RenderTargetView *pRenderTargetView, const FLOAT ColorRGBA[4]) { _orig->ClearRenderTargetView(pRenderTargetView, ColorRGBA); } void STDMETHODCALLTYPE D3D11DeviceContext::ClearUnorderedAccessViewUint(ID3D11UnorderedAccessView *pUnorderedAccessView, const UINT Values[4]) { _orig->ClearUnorderedAccessViewUint(pUnorderedAccessView, Values); } void STDMETHODCALLTYPE D3D11DeviceContext::ClearUnorderedAccessViewFloat(ID3D11UnorderedAccessView *pUnorderedAccessView, const FLOAT Values[4]) { _orig->ClearUnorderedAccessViewFloat(pUnorderedAccessView, Values); } void STDMETHODCALLTYPE D3D11DeviceContext::ClearDepthStencilView(ID3D11DepthStencilView *pDepthStencilView, UINT ClearFlags, FLOAT Depth, UINT8 Stencil) { #if RESHADE_DX11_CAPTURE_DEPTH_BUFFERS if (!_device->_runtimes.empty()) _draw_call_tracker.track_cleared_depthstencil(this, ClearFlags, pDepthStencilView, _device->_current_dsv_clear_index++, _device->_runtimes.front().get()); #endif _orig->ClearDepthStencilView(pDepthStencilView, ClearFlags, Depth, Stencil); } void STDMETHODCALLTYPE D3D11DeviceContext::GenerateMips(ID3D11ShaderResourceView *pShaderResourceView) { _orig->GenerateMips(pShaderResourceView); } void STDMETHODCALLTYPE D3D11DeviceContext::SetResourceMinLOD(ID3D11Resource *pResource, FLOAT MinLOD) { _orig->SetResourceMinLOD(pResource, MinLOD); } FLOAT STDMETHODCALLTYPE D3D11DeviceContext::GetResourceMinLOD(ID3D11Resource *pResource) { return _orig->GetResourceMinLOD(pResource); } void STDMETHODCALLTYPE D3D11DeviceContext::ResolveSubresource(ID3D11Resource *pDstResource, UINT DstSubresource, ID3D11Resource *pSrcResource, UINT SrcSubresource, DXGI_FORMAT Format) { _orig->ResolveSubresource(pDstResource, DstSubresource, pSrcResource, SrcSubresource, Format); } void STDMETHODCALLTYPE D3D11DeviceContext::ExecuteCommandList(ID3D11CommandList *pCommandList, BOOL RestoreContextState) { assert(pCommandList != nullptr); // The only way to create a command list is through 'FinishCommandList', so can always assume a proxy object here D3D11CommandList *const command_list_proxy = static_cast<D3D11CommandList *>(pCommandList); // Merge command list trackers into device one _draw_call_tracker.merge(command_list_proxy->_draw_call_tracker); // Get original command list pointer from proxy object and execute with it _orig->ExecuteCommandList(command_list_proxy->_orig, RestoreContextState); } void STDMETHODCALLTYPE D3D11DeviceContext::HSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) { _orig->HSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::HSSetShader(ID3D11HullShader *pHullShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) { _orig->HSSetShader(pHullShader, ppClassInstances, NumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::HSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) { _orig->HSSetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::HSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) { _orig->HSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::DSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) { _orig->DSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::DSSetShader(ID3D11DomainShader *pDomainShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) { _orig->DSSetShader(pDomainShader, ppClassInstances, NumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::DSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) { _orig->DSSetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::DSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) { _orig->DSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::CSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) { _orig->CSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::CSSetUnorderedAccessViews(UINT StartSlot, UINT NumUAVs, ID3D11UnorderedAccessView *const *ppUnorderedAccessViews, const UINT *pUAVInitialCounts) { _orig->CSSetUnorderedAccessViews(StartSlot, NumUAVs, ppUnorderedAccessViews, pUAVInitialCounts); } void STDMETHODCALLTYPE D3D11DeviceContext::CSSetShader(ID3D11ComputeShader *pComputeShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) { _orig->CSSetShader(pComputeShader, ppClassInstances, NumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::CSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) { _orig->CSSetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::CSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) { _orig->CSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::VSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) { _orig->VSGetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::PSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) { _orig->PSGetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::PSGetShader(ID3D11PixelShader **ppPixelShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) { _orig->PSGetShader(ppPixelShader, ppClassInstances, pNumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::PSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) { _orig->PSGetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::VSGetShader(ID3D11VertexShader **ppVertexShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) { _orig->VSGetShader(ppVertexShader, ppClassInstances, pNumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::PSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) { _orig->PSGetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::IAGetInputLayout(ID3D11InputLayout **ppInputLayout) { _orig->IAGetInputLayout(ppInputLayout); } void STDMETHODCALLTYPE D3D11DeviceContext::IAGetVertexBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppVertexBuffers, UINT *pStrides, UINT *pOffsets) { _orig->IAGetVertexBuffers(StartSlot, NumBuffers, ppVertexBuffers, pStrides, pOffsets); } void STDMETHODCALLTYPE D3D11DeviceContext::IAGetIndexBuffer(ID3D11Buffer **pIndexBuffer, DXGI_FORMAT *Format, UINT *Offset) { _orig->IAGetIndexBuffer(pIndexBuffer, Format, Offset); } void STDMETHODCALLTYPE D3D11DeviceContext::GSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) { _orig->GSGetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::GSGetShader(ID3D11GeometryShader **ppGeometryShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) { _orig->GSGetShader(ppGeometryShader, ppClassInstances, pNumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::IAGetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY *pTopology) { _orig->IAGetPrimitiveTopology(pTopology); } void STDMETHODCALLTYPE D3D11DeviceContext::VSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) { _orig->VSGetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::VSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) { _orig->VSGetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::GetPredication(ID3D11Predicate **ppPredicate, BOOL *pPredicateValue) { _orig->GetPredication(ppPredicate, pPredicateValue); } void STDMETHODCALLTYPE D3D11DeviceContext::GSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) { _orig->GSGetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::GSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) { _orig->GSGetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::OMGetRenderTargets(UINT NumViews, ID3D11RenderTargetView **ppRenderTargetViews, ID3D11DepthStencilView **ppDepthStencilView) { _orig->OMGetRenderTargets(NumViews, ppRenderTargetViews, ppDepthStencilView); } void STDMETHODCALLTYPE D3D11DeviceContext::OMGetRenderTargetsAndUnorderedAccessViews(UINT NumRTVs, ID3D11RenderTargetView **ppRenderTargetViews, ID3D11DepthStencilView **ppDepthStencilView, UINT UAVStartSlot, UINT NumUAVs, ID3D11UnorderedAccessView **ppUnorderedAccessViews) { _orig->OMGetRenderTargetsAndUnorderedAccessViews(NumRTVs, ppRenderTargetViews, ppDepthStencilView, UAVStartSlot, NumUAVs, ppUnorderedAccessViews); } void STDMETHODCALLTYPE D3D11DeviceContext::OMGetBlendState(ID3D11BlendState **ppBlendState, FLOAT BlendFactor[4], UINT *pSampleMask) { _orig->OMGetBlendState(ppBlendState, BlendFactor, pSampleMask); } void STDMETHODCALLTYPE D3D11DeviceContext::OMGetDepthStencilState(ID3D11DepthStencilState **ppDepthStencilState, UINT *pStencilRef) { _orig->OMGetDepthStencilState(ppDepthStencilState, pStencilRef); } void STDMETHODCALLTYPE D3D11DeviceContext::SOGetTargets(UINT NumBuffers, ID3D11Buffer **ppSOTargets) { _orig->SOGetTargets(NumBuffers, ppSOTargets); } void STDMETHODCALLTYPE D3D11DeviceContext::RSGetState(ID3D11RasterizerState **ppRasterizerState) { _orig->RSGetState(ppRasterizerState); } void STDMETHODCALLTYPE D3D11DeviceContext::RSGetViewports(UINT *pNumViewports, D3D11_VIEWPORT *pViewports) { _orig->RSGetViewports(pNumViewports, pViewports); } void STDMETHODCALLTYPE D3D11DeviceContext::RSGetScissorRects(UINT *pNumRects, D3D11_RECT *pRects) { _orig->RSGetScissorRects(pNumRects, pRects); } void STDMETHODCALLTYPE D3D11DeviceContext::HSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) { _orig->HSGetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::HSGetShader(ID3D11HullShader **ppHullShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) { _orig->HSGetShader(ppHullShader, ppClassInstances, pNumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::HSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) { _orig->HSGetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::HSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) { _orig->HSGetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::DSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) { _orig->DSGetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::DSGetShader(ID3D11DomainShader **ppDomainShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) { _orig->DSGetShader(ppDomainShader, ppClassInstances, pNumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::DSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) { _orig->DSGetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::DSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) { _orig->DSGetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::CSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) { _orig->CSGetShaderResources(StartSlot, NumViews, ppShaderResourceViews); } void STDMETHODCALLTYPE D3D11DeviceContext::CSGetUnorderedAccessViews(UINT StartSlot, UINT NumUAVs, ID3D11UnorderedAccessView **ppUnorderedAccessViews) { _orig->CSGetUnorderedAccessViews(StartSlot, NumUAVs, ppUnorderedAccessViews); } void STDMETHODCALLTYPE D3D11DeviceContext::CSGetShader(ID3D11ComputeShader **ppComputeShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) { _orig->CSGetShader(ppComputeShader, ppClassInstances, pNumClassInstances); } void STDMETHODCALLTYPE D3D11DeviceContext::CSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) { _orig->CSGetSamplers(StartSlot, NumSamplers, ppSamplers); } void STDMETHODCALLTYPE D3D11DeviceContext::CSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) { _orig->CSGetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers); } void STDMETHODCALLTYPE D3D11DeviceContext::ClearState() { _orig->ClearState(); } void STDMETHODCALLTYPE D3D11DeviceContext::Flush() { _orig->Flush(); } UINT STDMETHODCALLTYPE D3D11DeviceContext::GetContextFlags() { return _orig->GetContextFlags(); } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::FinishCommandList(BOOL RestoreDeferredContextState, ID3D11CommandList **ppCommandList) { const HRESULT hr = _orig->FinishCommandList(RestoreDeferredContextState, ppCommandList); if (SUCCEEDED(hr)) { assert(ppCommandList != nullptr); const auto command_list_proxy = new D3D11CommandList(_device, *ppCommandList); command_list_proxy->_draw_call_tracker = _draw_call_tracker; *ppCommandList = command_list_proxy; } // All statistics are now stored in the command list tracker, so reset current tracker here _draw_call_tracker.reset(); return hr; } D3D11_DEVICE_CONTEXT_TYPE STDMETHODCALLTYPE D3D11DeviceContext::GetType() { return _orig->GetType(); } void STDMETHODCALLTYPE D3D11DeviceContext::CopySubresourceRegion1(ID3D11Resource *pDstResource, UINT DstSubresource, UINT DstX, UINT DstY, UINT DstZ, ID3D11Resource *pSrcResource, UINT SrcSubresource, const D3D11_BOX *pSrcBox, UINT CopyFlags) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->CopySubresourceRegion1(pDstResource, DstSubresource, DstX, DstY, DstZ, pSrcResource, SrcSubresource, pSrcBox, CopyFlags); } void STDMETHODCALLTYPE D3D11DeviceContext::UpdateSubresource1(ID3D11Resource *pDstResource, UINT DstSubresource, const D3D11_BOX *pDstBox, const void *pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch, UINT CopyFlags) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->UpdateSubresource1(pDstResource, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch, CopyFlags); } void STDMETHODCALLTYPE D3D11DeviceContext::DiscardResource(ID3D11Resource *pResource) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->DiscardResource(pResource); } void STDMETHODCALLTYPE D3D11DeviceContext::DiscardView(ID3D11View *pResourceView) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->DiscardView(pResourceView); } void STDMETHODCALLTYPE D3D11DeviceContext::VSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->VSSetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::HSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->HSSetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::DSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->DSSetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::GSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->GSSetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::PSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->PSSetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::CSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->CSSetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::VSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->VSGetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::HSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->HSGetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::DSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->DSGetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::GSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->GSGetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::PSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->PSGetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::CSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->CSGetConstantBuffers1(StartSlot, NumBuffers, ppConstantBuffers, pFirstConstant, pNumConstants); } void STDMETHODCALLTYPE D3D11DeviceContext::SwapDeviceContextState(ID3DDeviceContextState *pState, ID3DDeviceContextState **ppPreviousState) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->SwapDeviceContextState(pState, ppPreviousState); } void STDMETHODCALLTYPE D3D11DeviceContext::ClearView(ID3D11View *pView, const FLOAT Color[4], const D3D11_RECT *pRect, UINT NumRects) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->ClearView(pView, Color, pRect, NumRects); } void STDMETHODCALLTYPE D3D11DeviceContext::DiscardView1(ID3D11View *pResourceView, const D3D11_RECT *pRects, UINT NumRects) { assert(_interface_version >= 1); static_cast<ID3D11DeviceContext1 *>(_orig)->DiscardView1(pResourceView, pRects, NumRects); } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::UpdateTileMappings(ID3D11Resource *pTiledResource, UINT NumTiledResourceRegions, const D3D11_TILED_RESOURCE_COORDINATE *pTiledResourceRegionStartCoordinates, const D3D11_TILE_REGION_SIZE *pTiledResourceRegionSizes, ID3D11Buffer *pTilePool, UINT NumRanges, const UINT *pRangeFlags, const UINT *pTilePoolStartOffsets, const UINT *pRangeTileCounts, UINT Flags) { assert(_interface_version >= 2); return static_cast<ID3D11DeviceContext2 *>(_orig)->UpdateTileMappings(pTiledResource, NumTiledResourceRegions, pTiledResourceRegionStartCoordinates, pTiledResourceRegionSizes, pTilePool, NumRanges, pRangeFlags, pTilePoolStartOffsets, pRangeTileCounts, Flags); } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::CopyTileMappings(ID3D11Resource *pDestTiledResource, const D3D11_TILED_RESOURCE_COORDINATE *pDestRegionStartCoordinate, ID3D11Resource *pSourceTiledResource, const D3D11_TILED_RESOURCE_COORDINATE *pSourceRegionStartCoordinate, const D3D11_TILE_REGION_SIZE *pTileRegionSize, UINT Flags) { assert(_interface_version >= 2); return static_cast<ID3D11DeviceContext2 *>(_orig)->CopyTileMappings(pDestTiledResource, pDestRegionStartCoordinate, pSourceTiledResource, pSourceRegionStartCoordinate, pTileRegionSize, Flags); } void STDMETHODCALLTYPE D3D11DeviceContext::CopyTiles(ID3D11Resource *pTiledResource, const D3D11_TILED_RESOURCE_COORDINATE *pTileRegionStartCoordinate, const D3D11_TILE_REGION_SIZE *pTileRegionSize, ID3D11Buffer *pBuffer, UINT64 BufferStartOffsetInBytes, UINT Flags) { assert(_interface_version >= 2); static_cast<ID3D11DeviceContext2 *>(_orig)->CopyTiles(pTiledResource, pTileRegionStartCoordinate, pTileRegionSize, pBuffer, BufferStartOffsetInBytes, Flags); } void STDMETHODCALLTYPE D3D11DeviceContext::UpdateTiles(ID3D11Resource *pDestTiledResource, const D3D11_TILED_RESOURCE_COORDINATE *pDestTileRegionStartCoordinate, const D3D11_TILE_REGION_SIZE *pDestTileRegionSize, const void *pSourceTileData, UINT Flags) { assert(_interface_version >= 2); static_cast<ID3D11DeviceContext2 *>(_orig)->UpdateTiles(pDestTiledResource, pDestTileRegionStartCoordinate, pDestTileRegionSize, pSourceTileData, Flags); } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::ResizeTilePool(ID3D11Buffer *pTilePool, UINT64 NewSizeInBytes) { assert(_interface_version >= 2); return static_cast<ID3D11DeviceContext2 *>(_orig)->ResizeTilePool(pTilePool, NewSizeInBytes); } void STDMETHODCALLTYPE D3D11DeviceContext::TiledResourceBarrier(ID3D11DeviceChild *pTiledResourceOrViewAccessBeforeBarrier, ID3D11DeviceChild *pTiledResourceOrViewAccessAfterBarrier) { assert(_interface_version >= 2); static_cast<ID3D11DeviceContext2 *>(_orig)->TiledResourceBarrier(pTiledResourceOrViewAccessBeforeBarrier, pTiledResourceOrViewAccessAfterBarrier); } BOOL STDMETHODCALLTYPE D3D11DeviceContext::IsAnnotationEnabled() { assert(_interface_version >= 2); return static_cast<ID3D11DeviceContext2 *>(_orig)->IsAnnotationEnabled(); } void STDMETHODCALLTYPE D3D11DeviceContext::SetMarkerInt(LPCWSTR pLabel, INT Data) { assert(_interface_version >= 2); static_cast<ID3D11DeviceContext2 *>(_orig)->SetMarkerInt(pLabel, Data); } void STDMETHODCALLTYPE D3D11DeviceContext::BeginEventInt(LPCWSTR pLabel, INT Data) { assert(_interface_version >= 2); static_cast<ID3D11DeviceContext2 *>(_orig)->BeginEventInt(pLabel, Data); } void STDMETHODCALLTYPE D3D11DeviceContext::EndEvent() { assert(_interface_version >= 2); static_cast<ID3D11DeviceContext2 *>(_orig)->EndEvent(); } void STDMETHODCALLTYPE D3D11DeviceContext::Flush1(D3D11_CONTEXT_TYPE ContextType, HANDLE hEvent) { assert(_interface_version >= 3); static_cast<ID3D11DeviceContext3 *>(_orig)->Flush1(ContextType, hEvent); } void STDMETHODCALLTYPE D3D11DeviceContext::SetHardwareProtectionState(BOOL HwProtectionEnable) { assert(_interface_version >= 3); static_cast<ID3D11DeviceContext3 *>(_orig)->SetHardwareProtectionState(HwProtectionEnable); } void STDMETHODCALLTYPE D3D11DeviceContext::GetHardwareProtectionState(BOOL *pHwProtectionEnable) { assert(_interface_version >= 3); static_cast<ID3D11DeviceContext3 *>(_orig)->GetHardwareProtectionState(pHwProtectionEnable); } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::Signal(ID3D11Fence *pFence, UINT64 Value) { assert(_interface_version >= 4); return static_cast<ID3D11DeviceContext4 *>(_orig)->Signal(pFence, Value); } HRESULT STDMETHODCALLTYPE D3D11DeviceContext::Wait(ID3D11Fence *pFence, UINT64 Value) { assert(_interface_version >= 4); return static_cast<ID3D11DeviceContext4 *>(_orig)->Wait(pFence, Value); }
49.693095
403
0.827149
[ "object" ]
33ad6980fac1b3ecd34044060a8e4bc27de16c64
1,661
cpp
C++
src/Engine/Renderer/Apis/OpenGL/Mesh/OpenGLStaticVoxelMeshData.cpp
Sausty/GameProject-1
0c0c13dea2b446213cea9074a02bcf588fb46559
[ "MIT" ]
null
null
null
src/Engine/Renderer/Apis/OpenGL/Mesh/OpenGLStaticVoxelMeshData.cpp
Sausty/GameProject-1
0c0c13dea2b446213cea9074a02bcf588fb46559
[ "MIT" ]
null
null
null
src/Engine/Renderer/Apis/OpenGL/Mesh/OpenGLStaticVoxelMeshData.cpp
Sausty/GameProject-1
0c0c13dea2b446213cea9074a02bcf588fb46559
[ "MIT" ]
null
null
null
// // Created by MarcasRealAccount on 31. Oct. 2020 // #include "Engine/Renderer/Apis/OpenGL/Mesh/OpenGLStaticVoxelMeshData.h" namespace gp1 { OpenGLStaticVoxelMeshData::OpenGLStaticVoxelMeshData(Mesh* mesh) : OpenGLMeshData(mesh) {} bool OpenGLStaticVoxelMeshData::HasVertices() { return GetMesh<StaticVoxelMesh>()->m_Vertices.size() > 0; } uint32_t OpenGLStaticVoxelMeshData::GetCustomDataSize() { return static_cast<uint32_t>(GetMesh<StaticVoxelMesh>()->m_Vertices.size()); } void OpenGLStaticVoxelMeshData::InitCustomGLData() { CreateVBOs(this->m_NumVBOs + 1); BindNextVBO(GL_ARRAY_BUFFER); glBufferData(GL_ARRAY_BUFFER, GetMesh<StaticVoxelMesh>()->m_Vertices.size() * sizeof(StaticVoxelMeshVertex), GetMesh<StaticVoxelMesh>()->m_Vertices.data(), GL_STATIC_DRAW); CreateVertexAttribArrays(4); SetVertexAttribPointer(static_cast<uint32_t>(VertexAttribIndex::POSITION), 3, GL_FLOAT, false, sizeof(StaticVoxelMeshVertex), offsetof(StaticVoxelMeshVertex, position)); SetVertexAttribPointer(static_cast<uint32_t>(VertexAttribIndex::NORMAL), 3, GL_FLOAT, false, sizeof(StaticVoxelMeshVertex), offsetof(StaticVoxelMeshVertex, normal)); SetVertexAttribPointer(static_cast<uint32_t>(VertexAttribIndex::UV), 2, GL_FLOAT, false, sizeof(StaticVoxelMeshVertex), offsetof(StaticVoxelMeshVertex, uv)); SetVertexAttribIPointer(static_cast<uint32_t>(VertexAttribIndex::SSBO_INDEX), 1, GL_UNSIGNED_INT, sizeof(StaticVoxelMeshVertex), offsetof(StaticVoxelMeshVertex, SSBOIndex)); UnbindVBO(GL_ARRAY_BUFFER); } void OpenGLStaticVoxelMeshData::ClearCustomData() { GetMesh<StaticVoxelMesh>()->m_Vertices.clear(); } } // namespace gp1
44.891892
175
0.796508
[ "mesh" ]
33ae3c7c2b28a2e3acc3406ef914449c8f446009
18,298
cpp
C++
clang/lib/CodeGen/CGObjCRuntime.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
605
2019-10-18T01:15:54.000Z
2022-03-31T14:31:04.000Z
clang/lib/CodeGen/CGObjCRuntime.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,180
2019-10-18T01:21:21.000Z
2022-03-31T23:25:41.000Z
clang/lib/CodeGen/CGObjCRuntime.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
275
2019-10-18T05:27:22.000Z
2022-03-30T09:04:21.000Z
//==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This abstract class defines the interface for Objective-C runtime-specific // code generation. It provides some concrete helper methods for functionality // shared between all (or most) of the Objective-C runtimes supported by clang. // //===----------------------------------------------------------------------===// #include "CGObjCRuntime.h" #include "CGCXXABI.h" #include "CGCleanup.h" #include "CGRecordLayout.h" #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/StmtObjC.h" #include "clang/CodeGen/CGFunctionInfo.h" #include "clang/CodeGen/CodeGenABITypes.h" #include "llvm/Support/SaveAndRestore.h" using namespace clang; using namespace CodeGen; uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) { return CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar) / CGM.getContext().getCharWidth(); } uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, const ObjCImplementationDecl *OID, const ObjCIvarDecl *Ivar) { return CGM.getContext().lookupFieldBitOffset(OID->getClassInterface(), OID, Ivar) / CGM.getContext().getCharWidth(); } unsigned CGObjCRuntime::ComputeBitfieldBitOffset( CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar) { return CGM.getContext().lookupFieldBitOffset(ID, ID->getImplementation(), Ivar); } LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF, const ObjCInterfaceDecl *OID, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers, llvm::Value *Offset) { // Compute (type*) ( (char *) BaseValue + Offset) QualType InterfaceTy{OID->getTypeForDecl(), 0}; QualType ObjectPtrTy = CGF.CGM.getContext().getObjCObjectPointerType(InterfaceTy); QualType IvarTy = Ivar->getUsageType(ObjectPtrTy).withCVRQualifiers(CVRQualifiers); llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy); llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy); V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, V, Offset, "add.ptr"); if (!Ivar->isBitField()) { V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy)); LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy); return LV; } // We need to compute an access strategy for this bit-field. We are given the // offset to the first byte in the bit-field, the sub-byte offset is taken // from the original layout. We reuse the normal bit-field access strategy by // treating this as an access to a struct where the bit-field is in byte 0, // and adjust the containing type size as appropriate. // // FIXME: Note that currently we make a very conservative estimate of the // alignment of the bit-field, because (a) it is not clear what guarantees the // runtime makes us, and (b) we don't have a way to specify that the struct is // at an alignment plus offset. // // Note, there is a subtle invariant here: we can only call this routine on // non-synthesized ivars but we may be called for synthesized ivars. However, // a synthesized ivar can never be a bit-field, so this is safe. uint64_t FieldBitOffset = CGF.CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar); uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth(); uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign(); uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext()); CharUnits StorageSize = CGF.CGM.getContext().toCharUnitsFromBits( llvm::alignTo(BitOffset + BitFieldSize, AlignmentBits)); CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits); // Allocate a new CGBitFieldInfo object to describe this access. // // FIXME: This is incredibly wasteful, these should be uniqued or part of some // layout object. However, this is blocked on other cleanups to the // Objective-C code, so for now we just live with allocating a bunch of these // objects. CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo( CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize, CGF.CGM.getContext().toBits(StorageSize), CharUnits::fromQuantity(0))); Address Addr(V, Alignment); Addr = CGF.Builder.CreateElementBitCast(Addr, llvm::Type::getIntNTy(CGF.getLLVMContext(), Info->StorageSize)); return LValue::MakeBitfield(Addr, *Info, IvarTy, LValueBaseInfo(AlignmentSource::Decl), TBAAAccessInfo()); } namespace { struct CatchHandler { const VarDecl *Variable; const Stmt *Body; llvm::BasicBlock *Block; llvm::Constant *TypeInfo; /// Flags used to differentiate cleanups and catchalls in Windows SEH unsigned Flags; }; struct CallObjCEndCatch final : EHScopeStack::Cleanup { CallObjCEndCatch(bool MightThrow, llvm::FunctionCallee Fn) : MightThrow(MightThrow), Fn(Fn) {} bool MightThrow; llvm::FunctionCallee Fn; void Emit(CodeGenFunction &CGF, Flags flags) override { if (MightThrow) CGF.EmitRuntimeCallOrInvoke(Fn); else CGF.EmitNounwindRuntimeCall(Fn); } }; } void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S, llvm::FunctionCallee beginCatchFn, llvm::FunctionCallee endCatchFn, llvm::FunctionCallee exceptionRethrowFn) { // Jump destination for falling out of catch bodies. CodeGenFunction::JumpDest Cont; if (S.getNumCatchStmts()) Cont = CGF.getJumpDestInCurrentScope("eh.cont"); bool useFunclets = EHPersonality::get(CGF).usesFuncletPads(); CodeGenFunction::FinallyInfo FinallyInfo; if (!useFunclets) if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) FinallyInfo.enter(CGF, Finally->getFinallyBody(), beginCatchFn, endCatchFn, exceptionRethrowFn); SmallVector<CatchHandler, 8> Handlers; // Enter the catch, if there is one. if (S.getNumCatchStmts()) { for (const ObjCAtCatchStmt *CatchStmt : S.catch_stmts()) { const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); Handlers.push_back(CatchHandler()); CatchHandler &Handler = Handlers.back(); Handler.Variable = CatchDecl; Handler.Body = CatchStmt->getCatchBody(); Handler.Block = CGF.createBasicBlock("catch"); Handler.Flags = 0; // @catch(...) always matches. if (!CatchDecl) { auto catchAll = getCatchAllTypeInfo(); Handler.TypeInfo = catchAll.RTTI; Handler.Flags = catchAll.Flags; // Don't consider any other catches. break; } Handler.TypeInfo = GetEHType(CatchDecl->getType()); } EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size()); for (unsigned I = 0, E = Handlers.size(); I != E; ++I) Catch->setHandler(I, { Handlers[I].TypeInfo, Handlers[I].Flags }, Handlers[I].Block); } if (useFunclets) if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) { CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true); if (!CGF.CurSEHParent) CGF.CurSEHParent = cast<NamedDecl>(CGF.CurFuncDecl); // Outline the finally block. const Stmt *FinallyBlock = Finally->getFinallyBody(); HelperCGF.startOutlinedSEHHelper(CGF, /*isFilter*/false, FinallyBlock); // Emit the original filter expression, convert to i32, and return. HelperCGF.EmitStmt(FinallyBlock); HelperCGF.FinishFunction(FinallyBlock->getEndLoc()); llvm::Function *FinallyFunc = HelperCGF.CurFn; // Push a cleanup for __finally blocks. CGF.pushSEHCleanup(NormalAndEHCleanup, FinallyFunc); } // Emit the try body. CGF.EmitStmt(S.getTryBody()); // Leave the try. if (S.getNumCatchStmts()) CGF.popCatchScope(); // Remember where we were. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); // Emit the handlers. for (unsigned I = 0, E = Handlers.size(); I != E; ++I) { CatchHandler &Handler = Handlers[I]; CGF.EmitBlock(Handler.Block); llvm::CatchPadInst *CPI = nullptr; SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(CGF.CurrentFuncletPad); if (useFunclets) if ((CPI = dyn_cast_or_null<llvm::CatchPadInst>(Handler.Block->getFirstNonPHI()))) { CGF.CurrentFuncletPad = CPI; CPI->setOperand(2, CGF.getExceptionSlot().getPointer()); } llvm::Value *RawExn = CGF.getExceptionFromSlot(); // Enter the catch. llvm::Value *Exn = RawExn; if (beginCatchFn) Exn = CGF.EmitNounwindRuntimeCall(beginCatchFn, RawExn, "exn.adjusted"); CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange()); if (endCatchFn) { // Add a cleanup to leave the catch. bool EndCatchMightThrow = (Handler.Variable == nullptr); CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup, EndCatchMightThrow, endCatchFn); } // Bind the catch parameter if it exists. if (const VarDecl *CatchParam = Handler.Variable) { llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType()); llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType); CGF.EmitAutoVarDecl(*CatchParam); EmitInitOfCatchParam(CGF, CastExn, CatchParam); } if (CPI) CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI); CGF.ObjCEHValueStack.push_back(Exn); CGF.EmitStmt(Handler.Body); CGF.ObjCEHValueStack.pop_back(); // Leave any cleanups associated with the catch. cleanups.ForceCleanup(); CGF.EmitBranchThroughCleanup(Cont); } // Go back to the try-statement fallthrough. CGF.Builder.restoreIP(SavedIP); // Pop out of the finally. if (!useFunclets && S.getFinallyStmt()) FinallyInfo.exit(CGF); if (Cont.isValid()) CGF.EmitBlock(Cont.getBlock()); } void CGObjCRuntime::EmitInitOfCatchParam(CodeGenFunction &CGF, llvm::Value *exn, const VarDecl *paramDecl) { Address paramAddr = CGF.GetAddrOfLocalVar(paramDecl); switch (paramDecl->getType().getQualifiers().getObjCLifetime()) { case Qualifiers::OCL_Strong: exn = CGF.EmitARCRetainNonBlock(exn); LLVM_FALLTHROUGH; case Qualifiers::OCL_None: case Qualifiers::OCL_ExplicitNone: case Qualifiers::OCL_Autoreleasing: CGF.Builder.CreateStore(exn, paramAddr); return; case Qualifiers::OCL_Weak: CGF.EmitARCInitWeak(paramAddr, exn); return; } llvm_unreachable("invalid ownership qualifier"); } namespace { struct CallSyncExit final : EHScopeStack::Cleanup { llvm::FunctionCallee SyncExitFn; llvm::Value *SyncArg; CallSyncExit(llvm::FunctionCallee SyncExitFn, llvm::Value *SyncArg) : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {} void Emit(CodeGenFunction &CGF, Flags flags) override { CGF.EmitNounwindRuntimeCall(SyncExitFn, SyncArg); } }; } void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF, const ObjCAtSynchronizedStmt &S, llvm::FunctionCallee syncEnterFn, llvm::FunctionCallee syncExitFn) { CodeGenFunction::RunCleanupsScope cleanups(CGF); // Evaluate the lock operand. This is guaranteed to dominate the // ARC release and lock-release cleanups. const Expr *lockExpr = S.getSynchExpr(); llvm::Value *lock; if (CGF.getLangOpts().ObjCAutoRefCount) { lock = CGF.EmitARCRetainScalarExpr(lockExpr); lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock); } else { lock = CGF.EmitScalarExpr(lockExpr); } lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy); // Acquire the lock. CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow(); // Register an all-paths cleanup to release the lock. CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock); // Emit the body of the statement. CGF.EmitStmt(S.getSynchBody()); } /// Compute the pointer-to-function type to which a message send /// should be casted in order to correctly call the given method /// with the given arguments. /// /// \param method - may be null /// \param resultType - the result type to use if there's no method /// \param callArgs - the actual arguments, including implicit ones CGObjCRuntime::MessageSendInfo CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method, QualType resultType, CallArgList &callArgs) { // If there's a method, use information from that. if (method) { const CGFunctionInfo &signature = CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty); llvm::PointerType *signatureType = CGM.getTypes().GetFunctionType(signature)->getPointerTo(); const CGFunctionInfo &signatureForCall = CGM.getTypes().arrangeCall(signature, callArgs); return MessageSendInfo(signatureForCall, signatureType); } // There's no method; just use a default CC. const CGFunctionInfo &argsInfo = CGM.getTypes().arrangeUnprototypedObjCMessageSend(resultType, callArgs); // Derive the signature to call from that. llvm::PointerType *signatureType = CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo(); return MessageSendInfo(argsInfo, signatureType); } bool CGObjCRuntime::canMessageReceiverBeNull(CodeGenFunction &CGF, const ObjCMethodDecl *method, bool isSuper, const ObjCInterfaceDecl *classReceiver, llvm::Value *receiver) { // Super dispatch assumes that self is non-null; even the messenger // doesn't have a null check internally. if (isSuper) return false; // If this is a direct dispatch of a class method, check whether the class, // or anything in its hierarchy, was weak-linked. if (classReceiver && method && method->isClassMethod()) return isWeakLinkedClass(classReceiver); // If we're emitting a method, and self is const (meaning just ARC, for now), // and the receiver is a load of self, then self is a valid object. if (auto curMethod = dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) { auto self = curMethod->getSelfDecl(); if (self->getType().isConstQualified()) { if (auto LI = dyn_cast<llvm::LoadInst>(receiver->stripPointerCasts())) { llvm::Value *selfAddr = CGF.GetAddrOfLocalVar(self).getPointer(); if (selfAddr == LI->getPointerOperand()) { return false; } } } } // Otherwise, assume it can be null. return true; } bool CGObjCRuntime::isWeakLinkedClass(const ObjCInterfaceDecl *ID) { do { if (ID->isWeakImported()) return true; } while ((ID = ID->getSuperClass())); return false; } void CGObjCRuntime::destroyCalleeDestroyedArguments(CodeGenFunction &CGF, const ObjCMethodDecl *method, const CallArgList &callArgs) { CallArgList::const_iterator I = callArgs.begin(); for (auto i = method->param_begin(), e = method->param_end(); i != e; ++i, ++I) { const ParmVarDecl *param = (*i); if (param->hasAttr<NSConsumedAttr>()) { RValue RV = I->getRValue(CGF); assert(RV.isScalar() && "NullReturnState::complete - arg not on object"); CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime); } else { QualType QT = param->getType(); auto *RT = QT->getAs<RecordType>(); if (RT && RT->getDecl()->isParamDestroyedInCallee()) { RValue RV = I->getRValue(CGF); QualType::DestructionKind DtorKind = QT.isDestructedType(); switch (DtorKind) { case QualType::DK_cxx_destructor: CGF.destroyCXXObject(CGF, RV.getAggregateAddress(), QT); break; case QualType::DK_nontrivial_c_struct: CGF.destroyNonTrivialCStruct(CGF, RV.getAggregateAddress(), QT); break; default: llvm_unreachable("unexpected dtor kind"); break; } } } } } llvm::Constant * clang::CodeGen::emitObjCProtocolObject(CodeGenModule &CGM, const ObjCProtocolDecl *protocol) { return CGM.getObjCRuntime().GetOrEmitProtocol(protocol); } std::string CGObjCRuntime::getSymbolNameForMethod(const ObjCMethodDecl *OMD, bool includeCategoryName) { std::string buffer; llvm::raw_string_ostream out(buffer); CGM.getCXXABI().getMangleContext().mangleObjCMethodName(OMD, out, /*includePrefixByte=*/true, includeCategoryName); return buffer; }
38.200418
91
0.638922
[ "object" ]
33af890f8038dd84ea98ead28dc8cf437d3d7a8f
5,638
cpp
C++
hamming/hamming.cpp
j-bresson/gecodeMCP
5b104ac86a4d2f48ebcf130220707a5b79397308
[ "MIT" ]
null
null
null
hamming/hamming.cpp
j-bresson/gecodeMCP
5b104ac86a4d2f48ebcf130220707a5b79397308
[ "MIT" ]
null
null
null
hamming/hamming.cpp
j-bresson/gecodeMCP
5b104ac86a4d2f48ebcf130220707a5b79397308
[ "MIT" ]
null
null
null
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <tack@gecode.org> * * Copyright: * Guido Tack, 2004 * * Last modified: * $Date: 2009-05-14 02:59:23 +0200 (Do, 14 Mai 2009) $ by $Author: tack $ * $Revision: 9099 $ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include <gecode/driver.hh> #include <gecode/int.hh> #include <gecode/minimodel.hh> #include <gecode/set.hh> using namespace Gecode; /** * \brief %Options for %Hamming problems * */ #define MAXSTRINGLENGTH 200000 static char result[MAXSTRINGLENGTH]; class HammingOptions : public Options { private: /// Number of bits Driver::UnsignedIntOption _bits; /// Minimum distance Driver::UnsignedIntOption _distance; /// Number of symbols Driver::UnsignedIntOption _size; public: /// Initialize options for example with name \a s HammingOptions(const char* s, unsigned int bits0, unsigned int distance0, unsigned int size0) : Options(s) , _bits("-bits","word size in bits",bits0) , _distance("-distance","minimum distance",distance0) , _size("-size","number of symbols",size0) { add(_bits); add(_distance); add(_size); } /// Return number of bits unsigned int bits(void) const { return _bits.value(); } /// Return minimum distance unsigned int distance(void) const { return _distance.value(); } /// Return number of symbols unsigned int size(void) const { return _size.value(); } }; /** * \brief %Example: Generating %Hamming codes * * Generate a Hamming code that fits in b-bit words to code n symbols where * the Hamming distance between every two symbol codes is at least d. * The Hamming distance between two words is the number of bit positions * where they differ. * * \ingroup ExProblem * */ class Hamming : public Script { private: /// The hamming code SetVarArray xs; public: /// Actual model Hamming(const HammingOptions& opt) : Script(opt), xs(*this,opt.size(),IntSet::empty,1,opt.bits()) { SetVarArray cxs(*this,xs.size()); for (int i=0; i<xs.size(); i++) rel(*this, xs[i], SRT_CMPL, cxs[i]); for (int i=0; i<xs.size(); i++) { SetVar y = xs[i]; SetVar cy = cxs[i]; for (int j=i+1; j<xs.size(); j++) { SetVar x = xs[j]; SetVar cx = cxs[j]; SetVar xIntCy(*this); SetVar yIntCx(*this); rel(*this, x, SOT_INTER, cy, SRT_EQ, xIntCy); rel(*this, y, SOT_INTER, cx, SRT_EQ, yIntCx); IntVar xIntCyCard(*this,0,x.cardMax()); IntVar yIntCxCard(*this,0,y.cardMax()); cardinality(*this, xIntCy, xIntCyCard); cardinality(*this, yIntCx, yIntCxCard); rel(*this, xIntCyCard+yIntCxCard >= opt.distance()); } } branch(*this, xs, SET_VAR_NONE(), SET_VAL_MIN_INC()); // branch(*this, xs, SET_VAR_RND, SET_VAL_MAX_INC); } /// Print solution virtual void print(std::ostream& os) const { for (int i=0; i<xs.size(); i++) { os << "(" ; for (int j=0;j<=xs[i].glbMax();j++) if (xs[i].contains(j)) os << j << " " ; os << ")" ; os << "\t[" << i << "] = " << xs[i] << std::endl; } print_to_string(); } virtual void print_to_string() const { std::ostringstream outputstring; outputstring << "(" ; for (int i=0; i<xs.size(); i++) { outputstring << "(" ; for (int j=0;j<=xs[i].glbMax();j++) if (xs[i].contains(j)) outputstring << j << " " ; outputstring << ")" ; } outputstring << ")" ; strcpy(result,outputstring.str().c_str()); } /// Constructor for copying \a s Hamming(Hamming& s) : Script(s) { xs.update(*this, s.xs); } /// Copy during cloning virtual Space* copy(void) { return new Hamming(*this); } }; /** \brief Main-function * \relates Hamming */ int main(int argc, char* argv[]) { HammingOptions opt("Hamming",20,3,32); opt.parse(argc,argv); Script::run<Hamming,DFS,HammingOptions>(opt); return 0; } /* function to be called in the framework version */ extern "C" { char *hammingG(int bits,int distance,int size,int solutions,int timelimit,char *resultat) { HammingOptions opt("Hamming",bits,distance,size); opt.iterations(5); opt.solutions(solutions); opt.time(timelimit); strcpy(result,"nilnil"); Script::run<Hamming,DFS,HammingOptions>(opt); sprintf(resultat, "%s", result); return result; } };
26.101852
90
0.638524
[ "model" ]
33b1d121a23125e5bf6ae213834ac61c30ede0e7
13,084
hpp
C++
include/memory/hadesmem/injector.hpp
Bia10/hadesmem
b91bce37611d0e939a55d9490c49780f9f0f3bff
[ "MIT" ]
1
2021-04-30T05:20:02.000Z
2021-04-30T05:20:02.000Z
include/memory/hadesmem/injector.hpp
Bia10/hadesmem
b91bce37611d0e939a55d9490c49780f9f0f3bff
[ "MIT" ]
null
null
null
include/memory/hadesmem/injector.hpp
Bia10/hadesmem
b91bce37611d0e939a55d9490c49780f9f0f3bff
[ "MIT" ]
null
null
null
// Copyright (C) 2010-2015 Joshua Boyce // See the file COPYING for copying permission. #pragma once #include <algorithm> #include <array> #include <cstdint> #include <iterator> #include <string> #include <utility> #include <vector> #include <windows.h> #include <hadesmem/alloc.hpp> #include <hadesmem/call.hpp> #include <hadesmem/config.hpp> #include <hadesmem/detail/argv_quote.hpp> #include <hadesmem/detail/assert.hpp> #include <hadesmem/detail/environment_variable.hpp> #include <hadesmem/detail/filesystem.hpp> #include <hadesmem/detail/force_initialize.hpp> #include <hadesmem/detail/self_path.hpp> #include <hadesmem/detail/static_assert.hpp> #include <hadesmem/detail/smart_handle.hpp> #include <hadesmem/detail/trace.hpp> #include <hadesmem/error.hpp> #include <hadesmem/find_procedure.hpp> #include <hadesmem/module.hpp> #include <hadesmem/process.hpp> #include <hadesmem/write.hpp> // TODO: IAT based injection. Required to allow injection before DllMain etc. of // other moudles are executed. Include support for .NET target processes. // Important because some obfuscated games have anti-debug etc. tricks hidden in // the DllMain of a static import. // TODO: .NET injection (without DLL dependency if possible). // TODO: Add manual mapping support again. // TODO: IME injection. https://github.com/dwendt/UniversalInject // TODO: SetWindowsHookEx based injction. Useful for bypassing // ObRegistercallbacks based protections? namespace hadesmem { namespace detail { class SteamEnvironmentVariable { public: explicit SteamEnvironmentVariable(std::wstring const& name, std::uint32_t app_id) : name_(name), app_id_{app_id} { if (!app_id_) { return; } old_value_ = ReadEnvironmentVariable(name); auto const app_id_str = detail::NumToStr<wchar_t>(app_id_); WriteEnvironmentVariable(name_, app_id_str.c_str()); } ~SteamEnvironmentVariable() { if (!app_id_) { return; } try { WriteEnvironmentVariable( name_, old_value_.first ? old_value_.second.data() : nullptr); } catch (...) { HADESMEM_DETAIL_TRACE_A( boost::current_exception_diagnostic_information().c_str()); HADESMEM_DETAIL_ASSERT(false); } } private: SteamEnvironmentVariable(SteamEnvironmentVariable const&) = delete; SteamEnvironmentVariable& operator=(SteamEnvironmentVariable const&) = delete; std::wstring name_{}; std::uint32_t app_id_{}; std::pair<bool, std::vector<wchar_t>> old_value_{}; }; } // TODO: Type safety. struct InjectFlags { enum : std::uint32_t { kNone = 0, kPathResolution = 1 << 0, kAddToSearchOrder = 1 << 1, kKeepSuspended = 1 << 2, kInvalidFlagMaxValue = 1 << 3 }; }; inline HMODULE InjectDll(Process const& process, std::wstring const& path, std::uint32_t flags) { HADESMEM_DETAIL_ASSERT(!(flags & ~(InjectFlags::kInvalidFlagMaxValue - 1UL))); bool const path_resolution = !!(flags & InjectFlags::kPathResolution); std::wstring const path_real = [&]() -> std::wstring { if (path_resolution && detail::IsPathRelative(path)) { return detail::CombinePath(detail::GetSelfDirPath(), path); } return path; }(); bool const add_path = !!(flags & InjectFlags::kAddToSearchOrder); if (add_path && detail::IsPathRelative(path_real)) { HADESMEM_DETAIL_THROW_EXCEPTION( Error() << ErrorString("Cannot modify search order unless an absolute " "path or path resolution is used.")); } // Only performing this check when path resolution is enabled // because otherwise we would need to perform the check in the // context of the remote process, which is not possible to do without // introducing race conditions and other potential problems. So we // just let LoadLibraryExW do the check for us. if (path_resolution && !detail::DoesFileExist(path_real)) { HADESMEM_DETAIL_THROW_EXCEPTION( Error() << ErrorString("Could not find module file.")); } HADESMEM_DETAIL_TRACE_A("Calling ForceLdrInitializeThunk."); detail::ForceLdrInitializeThunk(process.GetId()); HADESMEM_DETAIL_TRACE_FORMAT_W(L"Module path is \"%s\".", path_real.c_str()); std::size_t const path_buf_size = (path_real.size() + 1) * sizeof(wchar_t); HADESMEM_DETAIL_TRACE_A("Allocating memory for module path."); Allocator const lib_file_remote{process, path_buf_size}; HADESMEM_DETAIL_TRACE_A("Writing memory for module path."); WriteString(process, lib_file_remote.GetBase(), path_real); HADESMEM_DETAIL_TRACE_A("Finding LoadLibraryExW."); Module const kernel32_mod{process, L"kernel32.dll"}; auto const load_library = FindProcedure(process, kernel32_mod, "LoadLibraryExW"); HADESMEM_DETAIL_TRACE_A("Calling LoadLibraryExW."); auto const load_library_ret = Call(process, reinterpret_cast<decltype(&LoadLibraryExW)>(load_library), CallConv::kStdCall, static_cast<LPCWSTR>(lib_file_remote.GetBase()), nullptr, add_path ? LOAD_WITH_ALTERED_SEARCH_PATH : 0UL); if (!load_library_ret.GetReturnValue()) { HADESMEM_DETAIL_THROW_EXCEPTION( Error{} << ErrorString{"LoadLibraryExW failed."} << ErrorCodeWinLast{load_library_ret.GetLastError()}); } return load_library_ret.GetReturnValue(); } inline void FreeDll(Process const& process, HMODULE module) { Module const kernel32_mod{process, L"kernel32.dll"}; auto const free_library = FindProcedure(process, kernel32_mod, "FreeLibrary"); auto const free_library_ret = Call(process, reinterpret_cast<decltype(&FreeLibrary)>(free_library), CallConv::kStdCall, module); if (!free_library_ret.GetReturnValue()) { HADESMEM_DETAIL_THROW_EXCEPTION( Error{} << ErrorString{"FreeLibrary failed."} << ErrorCodeWinLast{free_library_ret.GetLastError()}); } } // TODO: Support passing an arg to the export (e.g. a string). inline CallResult<DWORD_PTR> CallExport(Process const& process, HMODULE module, std::string const& export_name) { Module const module_remote{process, module}; auto const export_ptr = FindProcedure(process, module_remote, export_name); return Call( process, reinterpret_cast<DWORD_PTR (*)()>(export_ptr), CallConv::kDefault); } class CreateAndInjectData { public: explicit CreateAndInjectData(Process const& process, HMODULE module, DWORD_PTR export_ret, DWORD export_last_error, detail::SmartHandle&& thread_handle) : process_{process}, module_{module}, export_ret_{export_ret}, export_last_error_{export_last_error}, thread_handle_{std::move(thread_handle)} { } explicit CreateAndInjectData(Process const&& process, HMODULE module, DWORD_PTR export_ret, DWORD export_last_error, detail::SmartHandle&& thread_handle) = delete; Process GetProcess() const { return process_; } HMODULE GetModule() const noexcept { return module_; } DWORD_PTR GetExportRet() const noexcept { return export_ret_; } DWORD GetExportLastError() const noexcept { return export_last_error_; } HANDLE GetThreadHandle() const noexcept { return thread_handle_.GetHandle(); } void ResumeThread() const { if (::ResumeThread(thread_handle_.GetHandle()) == static_cast<DWORD>(-1)) { DWORD const last_error = ::GetLastError(); HADESMEM_DETAIL_THROW_EXCEPTION(Error{} << ErrorString{"ResumeThread failed."} << ErrorCodeWinLast{last_error}); } } private: Process process_; HMODULE module_; DWORD_PTR export_ret_; DWORD export_last_error_; detail::SmartHandle thread_handle_; }; // TODO: Improve argument passing suppport for programs with complex command // lines. E.g. Aion (from NCWest) requires a command line with embedded // quotation marks which we don't correctly handle. template <typename ArgsIter> inline CreateAndInjectData CreateAndInject(std::wstring const& path, std::wstring const& work_dir, ArgsIter args_beg, ArgsIter args_end, std::wstring const& module, std::string const& export_name, std::uint32_t flags, std::uint32_t steam_app_id = 0) { using ArgsIterValueType = typename std::iterator_traits<ArgsIter>::value_type; HADESMEM_DETAIL_STATIC_ASSERT( std::is_base_of<std::wstring, ArgsIterValueType>::value); std::wstring const command_line = [&]() { std::wstring command_line_temp; detail::ArgvQuote(&command_line_temp, path, false); auto const parse_arg = [&](std::wstring const& arg) { command_line_temp += L' '; detail::ArgvQuote(&command_line_temp, arg, false); }; std::for_each(args_beg, args_end, parse_arg); return command_line_temp; }(); std::vector<wchar_t> proc_args(std::begin(command_line), std::end(command_line)); proc_args.push_back(L'\0'); std::wstring const work_dir_real = [&]() -> std::wstring { if (work_dir.empty() && !path.empty() && !detail::IsPathRelative(path)) { std::size_t const separator = path.find_last_of(L"\\/"); if (separator != std::wstring::npos && separator != path.size() - 1) { return path.substr(0, separator + 1); } } return work_dir; }(); // TODO: Make this thread-safe. If multiple injections occur simultaneously // from different threads the environment variables may trample each other // etc. detail::SteamEnvironmentVariable app_id(L"SteamAppId", steam_app_id); detail::SteamEnvironmentVariable game_id(L"SteamGameId", steam_app_id); STARTUPINFO start_info{}; start_info.cb = static_cast<DWORD>(sizeof(start_info)); PROCESS_INFORMATION proc_info{}; if (!::CreateProcessW(path.c_str(), proc_args.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT, nullptr, work_dir_real.empty() ? nullptr : work_dir_real.c_str(), &start_info, &proc_info)) { DWORD const last_error = ::GetLastError(); HADESMEM_DETAIL_THROW_EXCEPTION(Error{} << ErrorString{"CreateProcess failed."} << ErrorCodeWinLast{last_error}); } detail::SmartHandle const proc_handle{proc_info.hProcess}; detail::SmartHandle thread_handle{proc_info.hThread}; try { Process const process{proc_info.dwProcessId}; HMODULE const remote_module = InjectDll(process, module, flags); CallResult<DWORD_PTR> const export_ret = [&]() { if (!export_name.empty()) { return CallExport(process, remote_module, export_name); } return CallResult<DWORD_PTR>(0, 0); }(); if (!(flags & InjectFlags::kKeepSuspended)) { if (::ResumeThread(thread_handle.GetHandle()) == static_cast<DWORD>(-1)) { DWORD const last_error = ::GetLastError(); HADESMEM_DETAIL_THROW_EXCEPTION( Error{} << ErrorString{"ResumeThread failed."} << ErrorCodeWinLast{last_error} << ErrorCodeWinRet{export_ret.GetReturnValue()} << ErrorCodeWinOther{export_ret.GetLastError()}); } } return CreateAndInjectData{process, remote_module, export_ret.GetReturnValue(), export_ret.GetLastError(), std::move(thread_handle)}; } catch (std::exception const& /*e*/) { // Terminate process if injection failed, otherwise the 'zombie' process // would be leaked. BOOL const terminated = ::TerminateProcess(proc_handle.GetHandle(), 0); (void)terminated; HADESMEM_DETAIL_ASSERT(terminated != FALSE); throw; } } }
31.83455
81
0.620147
[ "vector" ]
33b2e3781b54a1e4fed238b4e1fde97682f39584
1,868
cpp
C++
code/LeetCode_752.cpp
Aden-Q/LeetCode
4bbf772c886f42ce3d72d01fd737929b99df3eb3
[ "MIT" ]
1
2019-09-22T03:08:14.000Z
2019-09-22T03:08:14.000Z
code/LeetCode_752.cpp
Aden-Q/leetcode
ebd4804edd4f172b9981b22c18d9ff654cf20762
[ "Apache-2.0" ]
null
null
null
code/LeetCode_752.cpp
Aden-Q/leetcode
ebd4804edd4f172b9981b22c18d9ff654cf20762
[ "Apache-2.0" ]
null
null
null
// Open the lock // 广搜3.8%,不想说什么 #include <iostream> #include <vector> #include <set> #include <queue> using namespace std; class Solution { public: int openLock(vector<string>& deadends, string target) { string init = "0000"; set<string> used; // BFS的排除空间 queue<string> q; // 搜索队列 int qsize; used.insert(init); q.push(init); int step = 0; int i,j,k; string cur, next, tmp; // 每次从队列中取出要处理的那个元素 if(count(deadends.begin(),deadends.end(),init)>0) return -1; while(!q.empty()){ step++; qsize = q.size(); for(i=0;i<qsize;i++){ cur = q.front(); q.pop(); for(j=0;j<4;j++){ // 否则把相邻字符串入队 for(k=-1;k<=1;k++){ tmp = cur; char& c = tmp[j]; c = (c+k+10-'0') % 10 + '0'; if(tmp == target) return step; else if(used.count(tmp) == 0 && count(deadends.begin(), deadends.end(), tmp) == 0){ q.push(tmp); used.insert(tmp); } } } } } return -1; } }; int main(){ //string ss[] = {"0000"}; string ss[] = {"0201","0101","0102","1212","2002"}; //string ss[] = {"8887","8889","8878","8898","8788","8988","7888","9888"}; //string ss[] = {"8888"}; vector<string> vec(ss,ss+5); int k; //k = count(vec.begin(), vec.end(),"0201"); //cout << k << endl; //string s = "8888"; //string s = "0009"; string s = "0202"; int res; Solution test; res = test.openLock(vec, s); cout << res << endl; return 0; }
25.944444
107
0.409529
[ "vector" ]
33b57484a1a7212cb98f24068d76b44b27f56b2d
2,114
cpp
C++
lib/gwp_asan/tests/thread_contention.cpp
1995hnagamin/compiler-rt
52ad1a728a9295f34debe1541d82ae391df87b8b
[ "Apache-2.0" ]
289
2015-01-16T09:21:17.000Z
2022-03-21T07:55:44.000Z
lib/gwp_asan/tests/thread_contention.cpp
1995hnagamin/compiler-rt
52ad1a728a9295f34debe1541d82ae391df87b8b
[ "Apache-2.0" ]
47
2019-12-11T02:34:13.000Z
2020-06-08T19:26:59.000Z
lib/gwp_asan/tests/thread_contention.cpp
1995hnagamin/compiler-rt
52ad1a728a9295f34debe1541d82ae391df87b8b
[ "Apache-2.0" ]
330
2015-01-17T16:41:29.000Z
2022-03-31T06:00:53.000Z
//===-- thread_contention.cpp -----------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "gwp_asan/tests/harness.h" // Note: Compilation of <atomic> and <thread> are extremely expensive for // non-opt builds of clang. #include <atomic> #include <cstdlib> #include <thread> #include <vector> void asyncTask(gwp_asan::GuardedPoolAllocator *GPA, std::atomic<bool> *StartingGun, unsigned NumIterations) { while (!*StartingGun) { // Wait for starting gun. } // Get ourselves a new allocation. for (unsigned i = 0; i < NumIterations; ++i) { volatile char *Ptr = reinterpret_cast<volatile char *>( GPA->allocate(GPA->maximumAllocationSize())); // Do any other threads have access to this page? EXPECT_EQ(*Ptr, 0); // Mark the page as from malloc. Wait to see if another thread also takes // this page. *Ptr = 'A'; std::this_thread::sleep_for(std::chrono::nanoseconds(10000)); // Check we still own the page. EXPECT_EQ(*Ptr, 'A'); // And now release it. *Ptr = 0; GPA->deallocate(const_cast<char *>(Ptr)); } } void runThreadContentionTest(unsigned NumThreads, unsigned NumIterations, gwp_asan::GuardedPoolAllocator *GPA) { std::atomic<bool> StartingGun{false}; std::vector<std::thread> Threads; if (std::thread::hardware_concurrency() < NumThreads) { NumThreads = std::thread::hardware_concurrency(); } for (unsigned i = 0; i < NumThreads; ++i) { Threads.emplace_back(asyncTask, GPA, &StartingGun, NumIterations); } StartingGun = true; for (auto &T : Threads) T.join(); } TEST_F(CustomGuardedPoolAllocator, ThreadContention) { unsigned NumThreads = 4; unsigned NumIterations = 10000; InitNumSlots(NumThreads); runThreadContentionTest(NumThreads, NumIterations, &GPA); }
30.2
80
0.636708
[ "vector" ]
33b670f45481f9b7d49a191bac9fea78a5f5f54a
3,797
cpp
C++
src/scenepic/graph.cpp
microsoft/scenepic
e3fd2c6312fa670a92b7888962b6812c262c6759
[ "MIT" ]
28
2021-10-05T08:51:26.000Z
2022-03-18T11:19:23.000Z
src/scenepic/graph.cpp
microsoft/scenepic
e3fd2c6312fa670a92b7888962b6812c262c6759
[ "MIT" ]
17
2021-10-05T11:36:17.000Z
2022-02-10T13:33:43.000Z
src/scenepic/graph.cpp
microsoft/scenepic
e3fd2c6312fa670a92b7888962b6812c262c6759
[ "MIT" ]
2
2021-12-12T16:42:51.000Z
2022-02-23T11:50:14.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "graph.h" #include "util.h" namespace scenepic { Graph::Margin::Margin() : Margin(10) {} Graph::Margin::Margin(double size) : Margin(size, size, size, size) {} Graph::Margin::Margin(double top, double right, double bottom, double left) : top(top), right(right), bottom(bottom), left(left) {} std::string Graph::Margin::to_string() const { return this->to_json().to_string(); } JsonValue Graph::Margin::to_json() const { JsonValue obj; obj["Top"] = this->top; obj["Right"] = this->right; obj["Bottom"] = this->bottom; obj["Left"] = this->left; return obj; } Graph::Sparkline::Sparkline( const std::string& name, const ValueBuffer& values, const Color& color, float line_width) : m_name(name), m_values(values), m_color(color), m_line_width(line_width) {} JsonValue Graph::Sparkline::to_json() const { JsonValue command; command["CommandType"] = "AddSparkline"; command["ValueBuffer"] = matrix_to_json(m_values); command["Name"] = m_name; command["StrokeStyle"] = m_color.to_html_hex(); command["LineWidth"] = m_line_width; return command; } const std::string& Graph::canvas_id() const { return m_canvas_id; } void Graph::add_sparkline( const std::string& name, const std::vector<float>& values, const scenepic::Color& color, float line_width) { ValueBuffer value_buffer(values.size(), 1); std::copy(values.begin(), values.end(), value_buffer.data()); m_sparklines.emplace_back(name, value_buffer, color, line_width); } Graph::Graph(const std::string& canvas_id) : m_canvas_id(canvas_id) {} std::string Graph::to_string() const { return this->to_json().to_string(); } JsonValue Graph::to_json() const { JsonValue obj; JsonValue canvas_commands; JsonValue margin; margin["CommandType"] = "SetMargin"; margin["Value"] = m_margin.to_json(); canvas_commands.append(margin); JsonValue background; background["CommandType"] = "SetBackgroundStyle"; background["Value"] = m_background_color.to_html_hex(); canvas_commands.append(background); JsonValue text; text["CommandType"] = "SetTextStyle"; text["FontFamily"] = m_font_family; text["SizeInPixels"] = m_text_size; canvas_commands.append(text); for (const auto& sparkline : m_sparklines) { canvas_commands.append(sparkline.to_json()); } if (!m_media_id.empty()) { JsonValue media; media["CommandType"] = "SetMedia"; media["MediaId"] = m_media_id; canvas_commands.append(media); } obj["CommandType"] = "CanvasCommands"; obj["CanvasId"] = m_canvas_id; obj["Commands"] = canvas_commands; return obj; } const Color& Graph::background_color() const { return m_background_color; } Graph& Graph::background_color(const Color& color) { m_background_color = color; return *this; } const Graph::Margin& Graph::margin() const { return m_margin; } Graph& Graph::margin(const Graph::Margin& margin) { m_margin = margin; return *this; } const std::string& Graph::font_family() const { return m_font_family; } Graph& Graph::font_family(const std::string& font_family) { m_font_family = font_family; return *this; } float Graph::text_size() const { return m_text_size; } Graph& Graph::text_size(float text_size) { m_text_size = text_size; return *this; } const std::string& Graph::media_id() const { return m_media_id; } Graph& Graph::media_id(const std::string& media_id) { m_media_id = media_id; return *this; } } // namespace scenepic
22.335294
77
0.653411
[ "vector" ]
33ba297457241f66b020bcf48987a39f8f6a6c19
729
cpp
C++
CPP/ch13/usedma.cpp
jerryhanjj/cpp
3efc23951f8a97d18516e8dbd911b3d2547899bd
[ "BSD-3-Clause" ]
null
null
null
CPP/ch13/usedma.cpp
jerryhanjj/cpp
3efc23951f8a97d18516e8dbd911b3d2547899bd
[ "BSD-3-Clause" ]
null
null
null
CPP/ch13/usedma.cpp
jerryhanjj/cpp
3efc23951f8a97d18516e8dbd911b3d2547899bd
[ "BSD-3-Clause" ]
null
null
null
// usedma.cpp -- inheritance, friends, and DMA // comiple with dma.cpp #include <iostream> #include "dma.h" int main() { using std::cout; using std::endl; baseDMA shirt("Portablelly", 8); lacksDMA balloon("red", "Blimpo", 4); hasDMA map("Mercator", "Buffalo Keys", 5); cout << "Displaying baseDMA object:\n"; cout << shirt << endl; cout << "Displaying lacksDMA object:\n"; cout << balloon << endl; cout << "Displaying hasDMA object:\n"; cout << map << endl; lacksDMA balloon2(balloon); cout << "Result of lacksDMA copy:\n"; cout << balloon2 << endl; hasDMA map2; map2 = map; cout << "Result of hasDMA assignment:\n"; cout << map2 << endl; return 0; }
25.137931
46
0.599451
[ "object" ]
33baec4d04ed132cc87c9dd3fdecd7d9015fd20a
6,846
cpp
C++
pixy firmware/src/host/pixymon/videowidget.cpp
beeedy/candleBot
f3693997dae6862b11407003c11535dcbee56132
[ "MIT" ]
1
2019-05-30T00:52:06.000Z
2019-05-30T00:52:06.000Z
pixy firmware/src/host/pixymon/videowidget.cpp
beeedy/candleBot
f3693997dae6862b11407003c11535dcbee56132
[ "MIT" ]
1
2015-05-11T19:51:54.000Z
2015-05-11T19:51:54.000Z
pixy firmware/src/host/pixymon/videowidget.cpp
beeedy/candleBot
f3693997dae6862b11407003c11535dcbee56132
[ "MIT" ]
null
null
null
// // begin license header // // This file is part of Pixy CMUcam5 or "Pixy" for short // // All Pixy source code is provided under the terms of the // GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html). // Those wishing to use Pixy source code, software and/or // technologies under different licensing terms should contact us at // cmucam@cs.cmu.edu. Such licensing terms are available for // all portions of the Pixy codebase presented here. // // end license header // #include <QTimer> #include <QPainter> #include <QDebug> #include <QMouseEvent> #include <QMetaType> #include "mainwindow.h" #include "videowidget.h" #include "console.h" // experimental //#include "interpreter.h" #include "renderer.h" VideoWidget::VideoWidget(MainWindow *main) : QWidget((QWidget *)main) { qRegisterMetaType<VideoWidget::InputMode>("VideoWidget::InputMode"); m_main = main; m_xOffset=0; m_yOffset=0; m_scale = 1.0; m_drag = false; m_inputMode = NONE; m_selection = false; // set size policy--- preferred aspect ratio QSizePolicy policy = sizePolicy(); policy.setHeightForWidth(true); setSizePolicy(policy); setMouseTracking(true); } VideoWidget::~VideoWidget() { } //0: don’t render, just put on image list, first //RENDER_FLAG_BLEND: tack on to end of image list //RENDER_FLAG_FLUSH put on image list first, and render //RENDER_FLAG_BLEND | RENDER_FLAG_FLUSH: tack on end of image list and render void VideoWidget::handleImage(QImage image, uchar renderFlags) { if (!(renderFlags&RENDER_FLAG_BLEND)) m_images.clear(); m_images.push_back(image); if (renderFlags&RENDER_FLAG_FLUSH) { m_renderedImages.clear(); m_renderedImages = m_images; m_images.clear(); repaint(); } } void VideoWidget::clear() { m_images.clear(); QImage img(m_width, m_height, QImage::Format_RGB32); img.fill(0xff000000); handleImage(img, RENDER_FLAG_FLUSH); } int VideoWidget::activeWidth() { return m_width; } int VideoWidget::activeHeight() { return m_height; } void VideoWidget::paintEvent(QPaintEvent *event) { unsigned int i; m_width = this->width(); m_height = this->height(); float war; float pmar; QPainter p(this); // we could render to a QImage instead of to a widget. This might take longer, but // it would allow us to save off the blended image, e.g. to a file. QPixmap bgPixmap; if (m_renderedImages.size()==0) return; // background pixmap bgPixmap = QPixmap::fromImage(m_renderedImages[0]); // calc aspect ratios war = (float)m_width/(float)m_height; // widget aspect ratio pmar = (float)bgPixmap.width()/(float)bgPixmap.height(); // set blending mode p.setCompositionMode(QPainter::CompositionMode_SourceOver); // figure out if we need to offset our rendering rectangle if (war>pmar) { // width is greater than video m_width = this->height()*pmar; m_xOffset = (this->width()-m_width)/2; m_yOffset = 0; } else { // height is greater than video m_height = this->width()/pmar; m_yOffset = (this->height()-m_height)/2; m_xOffset = 0; } // figure out scale between background resolution and active width of widget m_scale = (float)m_width/bgPixmap.width(); // draw background p.drawPixmap(QRect(m_xOffset, m_yOffset, m_width, m_height), bgPixmap); // draw/blend foreground images for (i=1; i<m_renderedImages.size(); i++) p.drawPixmap(QRect(m_xOffset, m_yOffset, m_width, m_height), QPixmap::fromImage(m_renderedImages[i])); // draw selection rectangle if (m_selection) { p.setBrush(QBrush(QColor(0xff, 0xff, 0xff, 0x20))); p.setPen(QPen(QColor(0xff, 0xff, 0xff, 0xff))); p.drawRect(m_x0, m_y0, m_sbWidth, m_sbHeight); } QWidget::paintEvent(event); } int VideoWidget::heightForWidth(int w) const { return w/VW_ASPECT_RATIO; } void VideoWidget::mouseMoveEvent(QMouseEvent *event) { Qt::MouseButtons b = event->buttons(); int x = event->x(); int y = event->y(); if (m_drag==false && b&Qt::LeftButton) { m_drag = true; m_x0 = x; m_y0 = y; } else if (m_drag==true && b==Qt::NoButton) { m_drag = false; } if (m_drag && m_inputMode==REGION) { m_sbWidth = x-m_x0; m_sbHeight = y-m_y0; // check if we have clicked outside of active region if (m_x0-m_xOffset>0 && m_y0-m_yOffset>0 && m_x0<m_xOffset+m_width && m_y0<m_yOffset+m_height) { m_selection = true; // limit drag to within active region if (m_x0-m_xOffset+m_sbWidth>m_width) m_sbWidth = m_width-m_x0+m_xOffset; if (m_y0-m_yOffset+m_sbHeight>m_height) m_sbHeight = m_height-m_y0+m_yOffset; if (m_x0-m_xOffset+m_sbWidth<0) m_sbWidth = -m_x0+m_xOffset; if (m_y0-m_yOffset+m_sbHeight<0) m_sbHeight = -m_y0+m_yOffset; repaint(); } } QWidget::mouseMoveEvent(event); } void VideoWidget::mousePressEvent(QMouseEvent *event) { m_selection = false; repaint(); QWidget::mousePressEvent(event); } void VideoWidget::mouseReleaseEvent(QMouseEvent *event) { int x, y, width, height; if (m_selection) { x = (m_x0-m_xOffset)/m_scale+.5; y = (m_y0-m_yOffset)/m_scale+.5; width = m_sbWidth/m_scale+.5; height = m_sbHeight/m_scale+.5; // deal with box inversion if (width<0) { x += width; width = -width; } if (height<0) { y += height; height = -height; } emit selection(x, y, width, height); acceptInput(NONE); //DBG("%d %d %d %d", x, y, width, height); m_selection = false; } else if (m_inputMode==POINT) { x = (event->x()-m_xOffset)/m_scale+.5; y = (event->y()-m_yOffset)/m_scale+.5; emit selection(x, y, 0, 0); acceptInput(NONE); } QWidget::mouseReleaseEvent(event); } void VideoWidget::resizeEvent(QResizeEvent *event) { m_selection = false; QWidget::resizeEvent(event); } void VideoWidget::acceptInput(VideoWidget::InputMode mode) { m_inputMode = mode; if (mode==REGION || mode==POINT) setCursor(Qt::CrossCursor); else { m_selection = false; setCursor(Qt::ArrowCursor); } }
26.229885
111
0.60298
[ "render" ]
33bb6021ec0014a472490aaa0d51660f43133ef0
4,876
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/MimeText_Binding_Match_8/CPP/mimetext_binding_match_8.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Remoting/MimeText_Binding_Match_8/CPP/mimetext_binding_match_8.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Remoting/MimeText_Binding_Match_8/CPP/mimetext_binding_match_8.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// System.Web.Services.Description.MimeTextBinding // System.Web.Services.Description.MimeTextBinding() // System.Web.Services.Description.MimeTextMatch() // System.Web.Services.Description.MimeTextMatch.Name // System.Web.Services.Description.MimeTextMatch.Type // System.Web.Services.Description.MimeTextMatch.Pattern // System.Web.Services.Description.MimeTextMatch.IgnoreCase // System.Web.Services.Description.MimeTextBinding.Matches /* This program demostrates constructor and 'Matches' property of 'MimeTextBinding' class and 'Name', 'Type', 'Pattern', 'IgnoreCase' properties of 'MimeTextMatch' class. It takes 'MimeText_Binding_Match_8_Input_CPP.wsdl' as an input file which does not contain 'Binding' object that supports 'HttpPost'. A text pattern ''TITLE&gt;(.*?)&lt;' with text name as 'Title' and with type name set, is added to the wsdl file. Finally the ' modified ServiceDescription is written to 'MimeText_Binding_Match_8_Output_CPP.wsdl'. */ // <Snippet1> #using <System.Xml.dll> #using <System.Web.Services.dll> #using <System.dll> using namespace System; using namespace System::Web::Services::Description; using namespace System::Collections; using namespace System::Xml; int main() { try { ServiceDescription^ myServiceDescription = ServiceDescription::Read( "MimeText_Binding_Match_8_Input_CPP.wsdl" ); // Create a Binding. Binding^ myBinding = gcnew Binding; // Initialize the Name property of the Binding. myBinding->Name = "MimeText_Binding_MatchServiceHttpPost"; XmlQualifiedName^ myXmlQualifiedName = gcnew XmlQualifiedName( "s0:MimeText_Binding_MatchServiceHttpPost" ); myBinding->Type = myXmlQualifiedName; // Create an HttpBinding. HttpBinding^ myHttpBinding = gcnew HttpBinding; myHttpBinding->Verb = "POST"; // Add the HttpBinding to the Binding. myBinding->Extensions->Add( myHttpBinding ); // Create an OperationBinding. OperationBinding^ myOperationBinding = gcnew OperationBinding; myOperationBinding->Name = "AddNumbers"; HttpOperationBinding^ myHttpOperationBinding = gcnew HttpOperationBinding; myHttpOperationBinding->Location = "/AddNumbers"; // Add the HttpOperationBinding to the OperationBinding. myOperationBinding->Extensions->Add( myHttpOperationBinding ); // Create an InputBinding. InputBinding^ myInputBinding = gcnew InputBinding; MimeContentBinding^ postMimeContentbinding = gcnew MimeContentBinding; postMimeContentbinding->Type = "application/x-www-form-urlencoded"; myInputBinding->Extensions->Add( postMimeContentbinding ); // Add the InputBinding to the OperationBinding. myOperationBinding->Input = myInputBinding; // <Snippet8> // <Snippet7> // <Snippet6> // <Snippet5> // <Snippet4> // <Snippet3> // <Snippet2> // Create an OutputBinding. OutputBinding^ myOutputBinding = gcnew OutputBinding; // Create a MimeTextBinding. MimeTextBinding^ myMimeTextBinding = gcnew MimeTextBinding; // Create a MimeTextMatch. MimeTextMatch^ myMimeTextMatch = gcnew MimeTextMatch; MimeTextMatchCollection^ myMimeTextMatchCollection; // Initialize properties of the MimeTextMatch. myMimeTextMatch->Name = "Title"; myMimeTextMatch->Type = "*/*"; myMimeTextMatch->Pattern = "'TITLE&gt;(.*?)&lt;"; myMimeTextMatch->IgnoreCase = true; // Initialize a MimeTextMatchCollection. myMimeTextMatchCollection = myMimeTextBinding->Matches; // Add the MimeTextMatch to the MimeTextMatchCollection. myMimeTextMatchCollection->Add( myMimeTextMatch ); myOutputBinding->Extensions->Add( myMimeTextBinding ); // Add the OutputBinding to the OperationBinding. myOperationBinding->Output = myOutputBinding; // </Snippet2> // </Snippet3> // </Snippet4> // </Snippet5> // </Snippet6> // </Snippet7> // </Snippet8> // Add the OutputBinding to the OperationBinding. myOperationBinding->Output = myOutputBinding; // Add the OperationBinding to the Binding. myBinding->Operations->Add( myOperationBinding ); // Add the Binding to the BindingCollection of the ServiceDescription. myServiceDescription->Bindings->Add( myBinding ); // Write the ServiceDescription as a WSDL file. myServiceDescription->Write( "MimeText_Binding_Match_8_Output_CPP.wsdl" ); Console::WriteLine( "WSDL file named 'MimeText_Binding_Match_8_Output_CPP.wsdl' was" " created successfully." ); } catch ( Exception^ e ) { Console::WriteLine( "Exception: {0}", e->Message ); } } // </Snippet1>
37.79845
120
0.694217
[ "object" ]
33be9de2addb7ceb1c63875fa72b9c90d7f770cf
26,890
cpp
C++
libraries/script-engine/src/AssetScriptingInterface.cpp
GeorgeDeac/project-athena
0fb1f374506ac0ecf51b00d1bfba2b4f224823f0
[ "Apache-2.0" ]
2
2017-05-29T17:59:48.000Z
2017-05-29T19:01:40.000Z
libraries/script-engine/src/AssetScriptingInterface.cpp
GeorgeDeac/project-athena
0fb1f374506ac0ecf51b00d1bfba2b4f224823f0
[ "Apache-2.0" ]
2
2018-11-01T02:16:43.000Z
2018-11-16T00:45:44.000Z
libraries/script-engine/src/AssetScriptingInterface.cpp
GeorgeDeac/project-athena
0fb1f374506ac0ecf51b00d1bfba2b4f224823f0
[ "Apache-2.0" ]
1
2017-08-05T00:17:36.000Z
2017-08-05T00:17:36.000Z
// // AssetScriptingInterface.cpp // libraries/script-engine/src // // Created by Stephen Birarda on 2016-03-08. // Copyright 2016 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "AssetScriptingInterface.h" #include <QMimeDatabase> #include <QThread> #include <QtScript/QScriptEngine> #include <AssetRequest.h> #include <AssetUpload.h> #include <AssetUtils.h> #include <BaseScriptEngine.h> #include <MappingRequest.h> #include <NodeList.h> #include <RegisteredMetaTypes.h> #include "ScriptEngine.h" #include "ScriptEngineLogging.h" #include <shared/QtHelpers.h> #include <Gzip.h> #include <future> using Promise = MiniPromise::Promise; AssetScriptingInterface::AssetScriptingInterface(QObject* parent) : BaseAssetScriptingInterface(parent) { qCDebug(scriptengine) << "AssetScriptingInterface::AssetScriptingInterface" << parent; MiniPromise::registerMetaTypes(parent); } #define JS_VERIFY(cond, error) { if (!this->jsVerify(cond, error)) { return; } } bool AssetScriptingInterface::initializeCache() { if (!Parent::initializeCache()) { if (assetClient()) { std::promise<bool> cacheStatusResult; Promise assetClientPromise(makePromise(__func__)); assetClientPromise->moveToThread(qApp->thread()); // To ensure the finally() is processed. assetClient()->cacheInfoRequestAsync(assetClientPromise); assetClientPromise->finally([&](QString, QVariantMap result) { cacheStatusResult.set_value(!result.isEmpty()); }); return cacheStatusResult.get_future().get(); } else { return false; } } else { return true; } } void AssetScriptingInterface::uploadData(QString data, QScriptValue callback) { auto handler = jsBindCallback(thisObject(), callback); QByteArray dataByteArray = data.toUtf8(); auto upload = DependencyManager::get<AssetClient>()->createUpload(dataByteArray); Promise deferred = makePromise(__FUNCTION__); deferred->ready([=](QString error, QVariantMap result) { auto url = result.value("url").toString(); auto hash = result.value("hash").toString(); jsCallback(handler, url, hash); }); connect(upload, &AssetUpload::finished, upload, [deferred](AssetUpload* upload, const QString& hash) { // we are now on the "Resource Manager" thread (and "hash" being a *reference* makes it unsafe to use directly) Q_ASSERT(QThread::currentThread() == upload->thread()); deferred->resolve({ { "url", "atp:" + hash }, { "hash", hash }, }); upload->deleteLater(); }); upload->start(); } void AssetScriptingInterface::setMapping(QString path, QString hash, QScriptValue callback) { auto handler = jsBindCallback(thisObject(), callback); auto setMappingRequest = assetClient()->createSetMappingRequest(path, hash); Promise deferred = makePromise(__FUNCTION__); deferred->ready([=](QString error, QVariantMap result) { jsCallback(handler, error, result); }); connect(setMappingRequest, &SetMappingRequest::finished, setMappingRequest, [deferred](SetMappingRequest* request) { Q_ASSERT(QThread::currentThread() == request->thread()); // we are now on the "Resource Manager" thread QString error = request->getErrorString(); // forward a thread-safe values back to our thread deferred->handle(error, { { "error", request->getError() } }); request->deleteLater(); }); setMappingRequest->start(); } /**jsdoc * The success or failure of an {@link Assets.downloadData} call. * @typedef {object} Assets.DownloadDataError * @property {string} errorMessage - <code>""</code> if the download was successful, otherwise a description of the error. */ void AssetScriptingInterface::downloadData(QString urlString, QScriptValue callback) { // FIXME: historically this API method failed silently when given a non-atp prefixed // urlString (or if the AssetRequest failed). // .. is that by design or could we update without breaking things to provide better feedback to scripts? if (!urlString.startsWith(ATP_SCHEME)) { // ... for now at least log a message so user can check logs qCDebug(scriptengine) << "AssetScriptingInterface::downloadData url must be of form atp:<hash-value>"; return; } QString hash = AssetUtils::extractAssetHash(urlString); auto handler = jsBindCallback(thisObject(), callback); auto assetClient = DependencyManager::get<AssetClient>(); auto assetRequest = assetClient->createRequest(hash); Promise deferred = makePromise(__FUNCTION__); deferred->ready([=](QString error, QVariantMap result) { // FIXME: to remain backwards-compatible the signature here is "callback(data, n/a)" jsCallback(handler, result.value("data").toString(), { { "errorMessage", error } }); }); connect(assetRequest, &AssetRequest::finished, assetRequest, [deferred](AssetRequest* request) { Q_ASSERT(QThread::currentThread() == request->thread()); // we are now on the "Resource Manager" thread Q_ASSERT(request->getState() == AssetRequest::Finished); if (request->getError() == AssetRequest::Error::NoError) { QString data = QString::fromUtf8(request->getData()); // forward a thread-safe values back to our thread deferred->resolve({ { "data", data } }); } else { // FIXME: propagate error to scripts? (requires changing signature or inverting param order above..) //deferred->resolve(request->getErrorString(), { { "error", requet->getError() } }); qCDebug(scriptengine) << "AssetScriptingInterface::downloadData ERROR: " << request->getErrorString(); } request->deleteLater(); }); assetRequest->start(); } void AssetScriptingInterface::setBakingEnabled(QString path, bool enabled, QScriptValue callback) { auto setBakingEnabledRequest = DependencyManager::get<AssetClient>()->createSetBakingEnabledRequest({ path }, enabled); Promise deferred = jsPromiseReady(makePromise(__FUNCTION__), thisObject(), callback); if (!deferred) { return; } connect(setBakingEnabledRequest, &SetBakingEnabledRequest::finished, setBakingEnabledRequest, [deferred](SetBakingEnabledRequest* request) { Q_ASSERT(QThread::currentThread() == request->thread()); // we are now on the "Resource Manager" thread QString error = request->getErrorString(); // forward thread-safe values back to our thread deferred->handle(error, {}); request->deleteLater(); }); setBakingEnabledRequest->start(); } #if (PR_BUILD || DEV_BUILD) void AssetScriptingInterface::sendFakedHandshake() { auto nodeList = DependencyManager::get<NodeList>(); SharedNodePointer assetServer = nodeList->soloNodeOfType(NodeType::AssetServer); nodeList->sendFakedHandshakeRequestToNode(assetServer); } #endif void AssetScriptingInterface::getMapping(QString asset, QScriptValue callback) { auto path = AssetUtils::getATPUrl(asset).path(); auto handler = jsBindCallback(thisObject(), callback); JS_VERIFY(AssetUtils::isValidFilePath(path), "invalid ATP file path: " + asset + "(path:"+path+")"); JS_VERIFY(callback.isFunction(), "expected second parameter to be a callback function"); Promise promise = getAssetInfo(path); promise->ready([=](QString error, QVariantMap result) { jsCallback(handler, error, result.value("hash").toString()); }); } bool AssetScriptingInterface::jsVerify(bool condition, const QString& error) { if (condition) { return true; } if (context()) { context()->throwError(error); } else { qCDebug(scriptengine) << "WARNING -- jsVerify failed outside of a valid JS context: " + error; } return false; } QScriptValue AssetScriptingInterface::jsBindCallback(QScriptValue scope, QScriptValue callback) { QScriptValue handler = ::makeScopedHandlerObject(scope, callback); QScriptValue value = handler.property("callback"); if (!jsVerify(handler.isObject() && value.isFunction(), QString("jsBindCallback -- .callback is not a function (%1)").arg(value.toVariant().typeName()))) { return QScriptValue(); } return handler; } Promise AssetScriptingInterface::jsPromiseReady(Promise promise, QScriptValue scope, QScriptValue callback) { auto handler = jsBindCallback(scope, callback); if (!jsVerify(handler.isValid(), "jsPromiseReady -- invalid callback handler")) { return nullptr; } return promise->ready([this, handler](QString error, QVariantMap result) { jsCallback(handler, error, result); }); } void AssetScriptingInterface::jsCallback(const QScriptValue& handler, const QScriptValue& error, const QScriptValue& result) { Q_ASSERT(thread() == QThread::currentThread()); auto errorValue = !error.toBool() ? QScriptValue::NullValue : error; JS_VERIFY(handler.isObject() && handler.property("callback").isFunction(), QString("jsCallback -- .callback is not a function (%1)") .arg(handler.property("callback").toVariant().typeName())); ::callScopedHandlerObject(handler, errorValue, result); } void AssetScriptingInterface::jsCallback(const QScriptValue& handler, const QScriptValue& error, const QVariantMap& result) { Q_ASSERT(thread() == QThread::currentThread()); Q_ASSERT(handler.engine()); auto engine = handler.engine(); jsCallback(handler, error, engine->toScriptValue(result)); } void AssetScriptingInterface::deleteAsset(QScriptValue options, QScriptValue scope, QScriptValue callback) { jsVerify(false, "TODO: deleteAsset API"); } /**jsdoc * Source and download options for {@link Assets.getAsset}. * @typedef {object} Assets.GetOptions * @property {boolean} [decompress=false] - <code>true</code> to gunzip decompress the downloaded data. Synonym: * <code>compressed</code>. * @property {Assets.ResponseType} [responseType="text"] - The desired result type. * @property {string} url - The mapped path or hash to download. May have a leading <code>"atp:"</code>. */ /**jsdoc * Result value returned by {@link Assets.getAsset}. * @typedef {object} Assets.GetResult * @property {number} [byteLength] - The number of bytes in the downloaded content in <code>response</code>. * @property {boolean} cached - <code>true</code> if the item was retrieved from the cache, <code>false</code> if it was * downloaded. * @property {string} [contentType] - The automatically detected MIME type of the content. * @property {boolean} [decompressed] - <code>true</code> if the content was decompressed, <code>false</code> if it wasn't. * @property {string} [hash] - The hash for the downloaded asset. * @property {string} [hashURL] - The ATP URL of the hash file. * @property {string} [path] - The path for the asset, if a path was requested. Otherwise, <code>undefined</code>. * @property {string|object|ArrayBuffer} [response] - The downloaded content. * @property {Assets.ResponseType} [responseType] - The type of the downloaded content in <code>response</code>. * @property {string} [url] - The URL of the asset requested: the path with leading <code>"atp:"</code> if a path was * requested, otherwise the requested URL. * @property {boolean} [wasRedirected] - <code>true</code> if the downloaded data is the baked version of the asset, * <code>false</code> if it isn't baked. */ void AssetScriptingInterface::getAsset(QScriptValue options, QScriptValue scope, QScriptValue callback) { JS_VERIFY(options.isObject() || options.isString(), "expected request options Object or URL as first parameter"); auto decompress = options.property("decompress").toBool() || options.property("compressed").toBool(); auto responseType = options.property("responseType").toString().toLower(); auto url = options.property("url").toString(); if (options.isString()) { url = options.toString(); } if (responseType.isEmpty()) { responseType = "text"; } auto asset = AssetUtils::getATPUrl(url).path(); JS_VERIFY(AssetUtils::isValidHash(asset) || AssetUtils::isValidFilePath(asset), QString("Invalid ATP url '%1'").arg(url)); JS_VERIFY(RESPONSE_TYPES.contains(responseType), QString("Invalid responseType: '%1' (expected: %2)").arg(responseType).arg(RESPONSE_TYPES.join(" | "))); Promise fetched = jsPromiseReady(makePromise("fetched"), scope, callback); if (!fetched) { return; } Promise mapped = makePromise("mapped"); mapped->fail(fetched); mapped->then([=](QVariantMap result) { QString hash = result.value("hash").toString(); QString url = result.value("url").toString(); if (!AssetUtils::isValidHash(hash)) { fetched->reject("internal hash error: " + hash, result); } else { Promise promise = loadAsset(hash, decompress, responseType); promise->mixin(result); promise->ready([=](QString error, QVariantMap loadResult) { loadResult["url"] = url; // maintain mapped .url in results (vs. atp:hash returned by loadAsset) fetched->handle(error, loadResult); }); } }); if (AssetUtils::isValidHash(asset)) { mapped->resolve({ { "hash", asset }, { "url", url }, }); } else { getAssetInfo(asset)->ready(mapped); } } /**jsdoc * Source options for {@link Assets.resolveAsset}. * @typedef {object} Assets.ResolveOptions * @property {string} url - The hash or path to resolve. May have a leading <code>"atp:"</code>. */ /**jsdoc * Result value returned by {@link Assets.resolveAsset}. * <p>Note: If resolving a hash, a file of that hash need not be present on the asset server for the hash to resolve.</p> * @typedef {object} Assets.ResolveResult * @property {string} [hash] - The hash of the asset. * @property {string} [hashURL] - The url of the asset's hash file, with leading <code>atp:</code>. * @property {string} [path] - The path to the asset. * @property {string} [url] - The URL of the asset. * @property {boolean} [wasRedirected] - <code>true</code> if the resolved data is for the baked version of the asset, * <code>false</code> if it isn't. */ void AssetScriptingInterface::resolveAsset(QScriptValue options, QScriptValue scope, QScriptValue callback) { const QString& URL{ "url" }; auto url = (options.isString() ? options : options.property(URL)).toString(); auto asset = AssetUtils::getATPUrl(url).path(); JS_VERIFY(AssetUtils::isValidFilePath(asset) || AssetUtils::isValidHash(asset), "expected options to be an asset URL or request options containing .url property"); jsPromiseReady(getAssetInfo(asset), scope, callback); } /**jsdoc * Content and decompression options for {@link Assets.decompressData}. * @typedef {object} Assets.DecompressOptions * @property {ArrayBuffer} data - The data to decompress. * @property {Assets.ResponseType} [responseType=text] - The type of decompressed data to return. */ /**jsdoc * Result value returned by {@link Assets.decompressData}. * @typedef {object} Assets.DecompressResult * @property {number} [byteLength] - The number of bytes in the decompressed data. * @property {string} [contentType] - The MIME type of the decompressed data. * @property {boolean} [decompressed] - <code>true</code> if the data is decompressed. * @property {string|object|ArrayBuffer} [response] - The decompressed data. * @property {Assets.ResponseType} [responseType] - The type of the decompressed data in <code>response</code>. */ void AssetScriptingInterface::decompressData(QScriptValue options, QScriptValue scope, QScriptValue callback) { auto data = options.property("data"); QByteArray dataByteArray = qscriptvalue_cast<QByteArray>(data); auto responseType = options.property("responseType").toString().toLower(); if (responseType.isEmpty()) { responseType = "text"; } Promise completed = jsPromiseReady(makePromise(__FUNCTION__), scope, callback); Promise decompressed = decompressBytes(dataByteArray); if (responseType == "arraybuffer") { decompressed->ready(completed); } else { decompressed->ready([=](QString error, QVariantMap result) { Promise converted = convertBytes(result.value("data").toByteArray(), responseType); converted->mixin(result); converted->ready(completed); }); } } namespace { const int32_t DEFAULT_GZIP_COMPRESSION_LEVEL = -1; const int32_t MAX_GZIP_COMPRESSION_LEVEL = 9; } /**jsdoc * Content and compression options for {@link Assets.compressData}. * @typedef {object} Assets.CompressOptions * @property {string|ArrayBuffer} data - The data to compress. * @property {number} level - The compression level, range <code>-1</code> &ndash; <code>9</code>. <code>-1</code> means * use the default gzip compression level, <code>0</code> means no compression, and <code>9</code> means maximum * compression. */ /**jsdoc * Result value returned by {@link Assets.compressData}. * @typedef {object} Assets.CompressResult * @property {number} [byteLength] - The number of bytes in the compressed data. * @property {boolean} [compressed] - <code>true</code> if the data is compressed. * @property {string} [contentType] - The MIME type of the compressed data, i.e., <code>"application/gzip"</code>. * @property {ArrayBuffer} [data] - The compressed data. */ void AssetScriptingInterface::compressData(QScriptValue options, QScriptValue scope, QScriptValue callback) { auto data = options.property("data").isValid() ? options.property("data") : options; QByteArray dataByteArray = data.isString() ? data.toString().toUtf8() : qscriptvalue_cast<QByteArray>(data); int level = options.property("level").isNumber() ? options.property("level").toInt32() : DEFAULT_GZIP_COMPRESSION_LEVEL; JS_VERIFY(level >= DEFAULT_GZIP_COMPRESSION_LEVEL || level <= MAX_GZIP_COMPRESSION_LEVEL, QString("invalid .level %1").arg(level)); jsPromiseReady(compressBytes(dataByteArray, level), scope, callback); } /**jsdoc * Content and upload options for {@link Assets.putAsset}. * @typedef {object} Assets.PutOptions * @property {boolean} [compress=false] - <code>true</code> to gzip compress the content for upload and storage, * <code>false</code> to upload and store the data without gzip compression. Synonym: <code>compressed</code>. * @property {string|ArrayBuffer} data - The content to upload. * @property {string} [path] - A user-friendly path for the file in the asset server. May have a leading * <code>"atp:"</code>. IF not specified, no path-to-hash mapping is set. * <p>Note: The asset server destroys any unmapped SHA256-named file at server restart. Either set the mapping path * with this property or use {@link Assets.setMapping} to set a path-to-hash mapping for the uploaded file.</p> */ /**jsdoc * Result value returned by {@link Assets.putAsset}. * @typedef {object} Assets.PutResult * @property {number} [byteLength] - The number of bytes in the hash file stored on the asset server. * @property {boolean} [compressed] - <code>true</code> if the content stored is gzip compressed. * @property {string} [contentType] - <code>"application/gzip"</code> if the content stored is gzip compressed. * @property {string} [hash] - The SHA256 hash of the content. * @property {string} [url] - The <code>atp:</code> URL of the content: using the path if specified, otherwise the hash. * @property {string} [path] - The uploaded content's mapped path, if specified. */ void AssetScriptingInterface::putAsset(QScriptValue options, QScriptValue scope, QScriptValue callback) { auto compress = options.property("compress").toBool() || options.property("compressed").toBool(); auto data = options.isObject() ? options.property("data") : options; auto rawPath = options.property("path").toString(); auto path = AssetUtils::getATPUrl(rawPath).path(); QByteArray dataByteArray = data.isString() ? data.toString().toUtf8() : qscriptvalue_cast<QByteArray>(data); JS_VERIFY(path.isEmpty() || AssetUtils::isValidFilePath(path), QString("expected valid ATP file path '%1' ('%2')").arg(rawPath).arg(path)); JS_VERIFY(dataByteArray.size() > 0, QString("expected non-zero .data (got %1 / #%2 bytes)").arg(data.toVariant().typeName()).arg(dataByteArray.size())); // [compressed] => uploaded to server => [mapped to path] Promise prepared = makePromise("putAsset::prepared"); Promise uploaded = makePromise("putAsset::uploaded"); Promise completed = makePromise("putAsset::completed"); jsPromiseReady(completed, scope, callback); if (compress) { Promise compress = compressBytes(dataByteArray, DEFAULT_GZIP_COMPRESSION_LEVEL); compress->ready(prepared); } else { prepared->resolve({{ "data", dataByteArray }}); } prepared->fail(completed); prepared->then([=](QVariantMap result) { Promise upload = uploadBytes(result.value("data").toByteArray()); upload->mixin(result); upload->ready(uploaded); }); uploaded->fail(completed); if (path.isEmpty()) { uploaded->then(completed); } else { uploaded->then([=](QVariantMap result) { QString hash = result.value("hash").toString(); if (!AssetUtils::isValidHash(hash)) { completed->reject("path mapping requested, but did not receive valid hash", result); } else { Promise link = symlinkAsset(hash, path); link->mixin(result); link->ready(completed); } }); } } /**jsdoc * Source for {@link Assets.queryCacheMeta}. * @typedef {object} Assets.QueryCacheMetaOptions * @property {string} url - The URL of the cached asset to get information on. Must start with <code>"atp:"</code> or * <code>"cache:"</code>. */ void AssetScriptingInterface::queryCacheMeta(QScriptValue options, QScriptValue scope, QScriptValue callback) { QString url = options.isString() ? options.toString() : options.property("url").toString(); JS_VERIFY(QUrl(url).isValid(), QString("Invalid URL '%1'").arg(url)); jsPromiseReady(Parent::queryCacheMeta(url), scope, callback); } /**jsdoc * Source and retrieval options for {@link Assets.loadFromCache}. * @typedef {object} Assets.LoadFromCacheOptions * @property {boolean} [decompress=false] - <code>true</code> to gunzip decompress the cached data. Synonym: * <code>compressed</code>. * @property {Assets.ResponseType} [responseType=text] - The desired result type. * @property {string} url - The URL of the asset to load from cache. Must start with <code>"atp:"</code> or * <code>"cache:"</code>. */ void AssetScriptingInterface::loadFromCache(QScriptValue options, QScriptValue scope, QScriptValue callback) { QString url, responseType; bool decompress = false; if (options.isString()) { url = options.toString(); responseType = "text"; } else { url = options.property("url").toString(); responseType = options.property("responseType").isValid() ? options.property("responseType").toString() : "text"; decompress = options.property("decompress").toBool() || options.property("compressed").toBool(); } JS_VERIFY(QUrl(url).isValid(), QString("Invalid URL '%1'").arg(url)); JS_VERIFY(RESPONSE_TYPES.contains(responseType), QString("Invalid responseType: '%1' (expected: %2)").arg(responseType).arg(RESPONSE_TYPES.join(" | "))); jsPromiseReady(Parent::loadFromCache(url, decompress, responseType), scope, callback); } bool AssetScriptingInterface::canWriteCacheValue(const QUrl& url) { auto scriptEngine = qobject_cast<ScriptEngine*>(engine()); if (!scriptEngine) { return false; } // allow cache writes only from Client, EntityServer and Agent scripts bool isAllowedContext = ( scriptEngine->isClientScript() || scriptEngine->isAgentScript() ); if (!isAllowedContext) { return false; } return true; } /**jsdoc * The data to save to the cache and cache options for {@link Assets.saveToCache}. * @typedef {object} Assets.SaveToCacheOptions * @property {string|ArrayBuffer} data - The data to save to the cache. * @property {Assets.SaveToCacheHeaders} [headers] - The last-modified and expiry times for the cache item. * @property {string} [url] - The URL to associate with the cache item. Must start with <code>"atp:"</code> or * <code>"cache:"</code>. If not specified, the URL is <code>"atp:"</code> followed by the SHA256 hash of the content. */ void AssetScriptingInterface::saveToCache(QScriptValue options, QScriptValue scope, QScriptValue callback) { JS_VERIFY(options.isObject(), QString("expected options object as first parameter not: %1").arg(options.toVariant().typeName())); QString url = options.property("url").toString(); QByteArray data = qscriptvalue_cast<QByteArray>(options.property("data")); QVariantMap headers = qscriptvalue_cast<QVariantMap>(options.property("headers")); saveToCache(url, data, headers, scope, callback); } void AssetScriptingInterface::saveToCache(const QUrl& rawURL, const QByteArray& data, const QVariantMap& metadata, QScriptValue scope, QScriptValue callback) { QUrl url = rawURL; if (url.path().isEmpty() && !data.isEmpty()) { // generate a valid ATP URL from the data -- appending any existing fragment or querystring values auto atpURL = AssetUtils::getATPUrl(hashDataHex(data)); atpURL.setQuery(url.query()); atpURL.setFragment(url.fragment()); url = atpURL; } auto hash = AssetUtils::extractAssetHash(url.toDisplayString()); JS_VERIFY(url.isValid(), QString("Invalid URL '%1'").arg(url.toString())); JS_VERIFY(canWriteCacheValue(url), "Invalid cache write URL: " + url.toString()); JS_VERIFY(url.scheme() == "atp" || url.scheme() == "cache", "only 'atp' and 'cache' URL schemes supported"); JS_VERIFY(hash.isEmpty() || hash == hashDataHex(data), QString("invalid checksum hash for atp:HASH style URL (%1 != %2)").arg(hash, hashDataHex(data))); jsPromiseReady(Parent::saveToCache(url, data, metadata), scope, callback); }
46.522491
159
0.684455
[ "object" ]
33bfdb4507b5de0b2f9624d97984adc4b340793f
4,716
hpp
C++
indexed_bzip2/Prefetcher.hpp
mxmlnkn/indexed_bzip2
a09580c7f7ab07f216106a90941c2f05f401643f
[ "MIT" ]
15
2020-04-24T01:53:28.000Z
2022-03-11T08:47:26.000Z
indexed_bzip2/Prefetcher.hpp
mxmlnkn/indexed_bzip2
a09580c7f7ab07f216106a90941c2f05f401643f
[ "MIT" ]
12
2019-12-08T18:57:45.000Z
2022-01-19T21:12:45.000Z
indexed_bzip2/Prefetcher.hpp
mxmlnkn/indexed_bzip2
a09580c7f7ab07f216106a90941c2f05f401643f
[ "MIT" ]
3
2020-10-03T20:40:42.000Z
2022-02-19T22:49:25.000Z
#pragma once #include <algorithm> #include <cassert> #include <cmath> #include <cstddef> #include <deque> #include <iterator> #include <numeric> #include <optional> #include <vector> namespace FetchingStrategy { class FetchingStrategy { public: virtual ~FetchingStrategy() = default; virtual void fetch( size_t index ) = 0; [[nodiscard]] virtual std::vector<size_t> prefetch( size_t maxAmountToPrefetch ) const = 0; }; /** * Simply prefetches the next n indexes after the last access. */ class FetchNext : public FetchingStrategy { public: void fetch( size_t index ) override { m_lastFetched = index; } [[nodiscard]] std::vector<size_t> prefetch( size_t maxAmountToPrefetch ) const override { if ( !m_lastFetched ) { return {}; } std::vector<size_t> toPrefetch( maxAmountToPrefetch ); std::iota( toPrefetch.begin(), toPrefetch.end(), *m_lastFetched + 1 ); return toPrefetch; } private: static constexpr size_t MEMORY_SIZE = 3; std::optional<size_t> m_lastFetched; }; /** * Similar to @ref FetchNext but the amount of returned subsequent indexes is relative to the amount of * consecutive accesses in the memory. * If all are consecutive, returns the specified amount to prefetch. * Else, if there are only random access in memory, then it will return nothing to prefetch to avoid wasted computation. * Inbetween, interpolate exponentially, i.e., for a memory size of 3 and 4 requested prefetch indexes: * 1 consecutive pair -> 1 * 2 consecutive pair -> 2 * 3 consecutive pair -> 4 */ class FetchNextSmart : public FetchingStrategy { public: void fetch( size_t index ) override { /* Ignore duplicate accesses, which in the case of bzip2 blocks most likely means * that the caller reads only small parts from the block per call. */ if ( !m_previousIndexes.empty() && ( m_previousIndexes.front() == index ) ) { return; } m_previousIndexes.push_front( index ); while ( m_previousIndexes.size() > MEMORY_SIZE ) { m_previousIndexes.pop_back(); } } [[nodiscard]] std::vector<size_t> prefetch( size_t maxAmountToPrefetch ) const override { if ( m_previousIndexes.empty() || ( maxAmountToPrefetch == 0 ) ) { return {}; } /** This avoids division by 0 further down below! */ if ( m_previousIndexes.size() == 1 ) { std::vector<size_t> toPrefetch( maxAmountToPrefetch ); std::iota( toPrefetch.begin(), toPrefetch.end(), m_previousIndexes.front() + 1 ); return toPrefetch; } size_t consecutiveCount = 0; /**< can be at most m_previousIndexes.size() - 1 */ for ( auto it = m_previousIndexes.begin(), nit = std::next( it ); nit != m_previousIndexes.end(); ++it, ++nit ) { if ( *it == *nit + 1 ) { ++consecutiveCount; } } /* Handle special case of only random accesses. */ if ( consecutiveCount == 0 ) { return {}; } size_t lastConsecutiveCount = 0; for ( auto it = m_previousIndexes.begin(), nit = std::next( it ); nit != m_previousIndexes.end(); ++it, ++nit ) { if ( *it == *nit + 1 ) { ++lastConsecutiveCount; } else { break; } } /** 0 <= consecutiveRatio <= 1 */ const auto consecutiveRatio = static_cast<double>( lastConsecutiveCount ) / ( m_previousIndexes.size() - 1 ); /** 1 <= maxAmountToPrefetch +- floating point errors */ const auto amountToPrefetch = std::round( std::exp2( consecutiveRatio * std::log2( maxAmountToPrefetch ) ) ); assert( amountToPrefetch >= 0 ); assert( static_cast<size_t>( amountToPrefetch ) <= maxAmountToPrefetch ); std::vector<size_t> toPrefetch( static_cast<size_t>( amountToPrefetch ) ); std::iota( toPrefetch.begin(), toPrefetch.end(), m_previousIndexes.front() + 1 ); return toPrefetch; } private: static constexpr size_t MEMORY_SIZE = 3; std::deque<size_t> m_previousIndexes; }; /** @todo A prefetcher that can detect multiple interleaved consecutive patterns by sorting all last indexes and * then search for consecutive (|diff neighbors| == 1) and return predictions for all of them at the same * time relative to their length. Well, for bzip2, it sounds like the possibility of this happening is low. * Even consecutive backward seeking should be a low frequency use case. */ }
31.026316
120
0.619805
[ "vector" ]
33c045cce71ebe7c91dfce1b16e89ba1ea33287f
21,528
cc
C++
GeneratorInterface/HydjetInterface/src/HydjetHadronizer.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
13
2015-11-30T15:49:45.000Z
2022-02-08T16:11:30.000Z
GeneratorInterface/HydjetInterface/src/HydjetHadronizer.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
640
2015-02-11T18:55:47.000Z
2022-03-31T14:12:23.000Z
GeneratorInterface/HydjetInterface/src/HydjetHadronizer.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
51
2015-08-11T21:01:40.000Z
2022-03-30T07:31:34.000Z
/** \brief Interface to the HYDJET generator (since core v. 1.9.1), produces HepMC events \version 2.0 \authors Camelia Mironov, Andrey Belyaev */ #include <iostream> #include <cmath> #include "boost/lexical_cast.hpp" #include "FWCore/Concurrency/interface/SharedResourceNames.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/Run.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/EDMException.h" #include "GeneratorInterface/Core/interface/FortranInstance.h" #include "GeneratorInterface/HydjetInterface/interface/HydjetHadronizer.h" #include "GeneratorInterface/HydjetInterface/interface/HydjetWrapper.h" #include "GeneratorInterface/Pythia6Interface/interface/Pythia6Declarations.h" #include "GeneratorInterface/Pythia6Interface/interface/Pythia6Service.h" #include "HepMC/IO_HEPEVT.h" #include "HepMC/PythiaWrapper6_4.h" #include "HepMC/GenEvent.h" #include "HepMC/HeavyIon.h" #include "HepMC/SimpleVector.h" #include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h" #include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h" #include "SimDataFormats/GeneratorProducts/interface/GenRunInfoProduct.h" #include "SimDataFormats/HiGenData/interface/GenHIEvent.h" using namespace edm; using namespace std; using namespace gen; namespace { int convertStatus(int st) { if (st <= 0) return 0; if (st <= 10) return 1; if (st <= 20) return 2; if (st <= 30) return 3; else return st; } } // namespace const std::vector<std::string> HydjetHadronizer::theSharedResources = {edm::SharedResourceNames::kPythia6, gen::FortranInstance::kFortranInstance}; //_____________________________________________________________________ HydjetHadronizer::HydjetHadronizer(const ParameterSet& pset, edm::ConsumesCollector&& iC) : BaseHadronizer(pset), evt(nullptr), pset_(pset), abeamtarget_(pset.getParameter<double>("aBeamTarget")), angularspecselector_(pset.getParameter<int>("angularSpectrumSelector")), bfixed_(pset.getParameter<double>("bFixed")), bmax_(pset.getParameter<double>("bMax")), bmin_(pset.getParameter<double>("bMin")), cflag_(pset.getParameter<int>("cFlag")), embedding_(pset.getParameter<bool>("embeddingMode")), comenergy(pset.getParameter<double>("comEnergy")), doradiativeenloss_(pset.getParameter<bool>("doRadiativeEnLoss")), docollisionalenloss_(pset.getParameter<bool>("doCollisionalEnLoss")), fracsoftmult_(pset.getParameter<double>("fracSoftMultiplicity")), hadfreeztemp_(pset.getParameter<double>("hadronFreezoutTemperature")), hymode_(pset.getParameter<string>("hydjetMode")), maxEventsToPrint_(pset.getUntrackedParameter<int>("maxEventsToPrint", 1)), maxlongy_(pset.getParameter<double>("maxLongitudinalRapidity")), maxtrany_(pset.getParameter<double>("maxTransverseRapidity")), nsub_(0), nhard_(0), nmultiplicity_(pset.getParameter<int>("nMultiplicity")), nsoft_(0), nquarkflavor_(pset.getParameter<int>("qgpNumQuarkFlavor")), pythiaPylistVerbosity_(pset.getUntrackedParameter<int>("pythiaPylistVerbosity", 0)), qgpt0_(pset.getParameter<double>("qgpInitialTemperature")), qgptau0_(pset.getParameter<double>("qgpProperTimeFormation")), phi0_(0.), sinphi0_(0.), cosphi0_(1.), rotate_(pset.getParameter<bool>("rotateEventPlane")), shadowingswitch_(pset.getParameter<int>("shadowingSwitch")), signn_(pset.getParameter<double>("sigmaInelNN")), fVertex_(nullptr), pythia6Service_(new Pythia6Service(pset)) { // Default constructor if (pset.exists("signalVtx")) signalVtx_ = pset.getUntrackedParameter<std::vector<double> >("signalVtx"); if (signalVtx_.size() == 4) { if (!fVertex_) fVertex_ = new HepMC::FourVector(); LogDebug("EventSignalVertex") << "Setting event signal vertex " << " x = " << signalVtx_.at(0) << " y = " << signalVtx_.at(1) << " z= " << signalVtx_.at(2) << " t = " << signalVtx_.at(3) << endl; fVertex_->set(signalVtx_.at(0), signalVtx_.at(1), signalVtx_.at(2), signalVtx_.at(3)); } // PYLIST Verbosity Level // Valid PYLIST arguments are: 1, 2, 3, 5, 7, 11, 12, 13 pythiaPylistVerbosity_ = pset.getUntrackedParameter<int>("pythiaPylistVerbosity", 0); LogDebug("PYLISTverbosity") << "Pythia PYLIST verbosity level = " << pythiaPylistVerbosity_; //Max number of events printed on verbosity level maxEventsToPrint_ = pset.getUntrackedParameter<int>("maxEventsToPrint", 0); LogDebug("Events2Print") << "Number of events to be printed = " << maxEventsToPrint_; if (embedding_) { cflag_ = 0; src_ = iC.consumes<CrossingFrame<edm::HepMCProduct> >( pset.getUntrackedParameter<edm::InputTag>("backgroundLabel", edm::InputTag("mix", "generatorSmeared"))); } int cm = 1, va, vb, vc; HYJVER(cm, va, vb, vc); HepMC::HEPEVT_Wrapper::set_max_number_entries(4000); } //_____________________________________________________________________ HydjetHadronizer::~HydjetHadronizer() { // destructor call_pystat(1); delete pythia6Service_; } //_____________________________________________________________________ void HydjetHadronizer::doSetRandomEngine(CLHEP::HepRandomEngine* v) { pythia6Service_->setRandomEngine(v); } //_____________________________________________________________________ void HydjetHadronizer::add_heavy_ion_rec(HepMC::GenEvent* evt) { // heavy ion record in the final CMSSW Event double npart = hyfpar.npart; int nproj = static_cast<int>(npart / 2); int ntarg = static_cast<int>(npart - nproj); HepMC::HeavyIon* hi = new HepMC::HeavyIon(nsub_, // Ncoll_hard/N of SubEvents nproj, // Npart_proj ntarg, // Npart_targ static_cast<int>(hyfpar.nbcol), // Ncoll 0, // spectator_neutrons 0, // spectator_protons 0, // N_Nwounded_collisions 0, // Nwounded_N_collisions 0, // Nwounded_Nwounded_collisions hyfpar.bgen * nuclear_radius(), // impact_parameter in [fm] phi0_, // event_plane_angle 0, //hypsi3.psi3, // eccentricity hyjpar.sigin // sigma_inel_NN ); evt->set_heavy_ion(*hi); delete hi; } //___________________________________________________________________ HepMC::GenParticle* HydjetHadronizer::build_hyjet(int index, int barcode) { // Build particle object corresponding to index in hyjets (soft+hard) double x0 = hyjets.phj[0][index]; double y0 = hyjets.phj[1][index]; double x = x0 * cosphi0_ - y0 * sinphi0_; double y = y0 * cosphi0_ + x0 * sinphi0_; HepMC::GenParticle* p = new HepMC::GenParticle(HepMC::FourVector(x, // px y, // py hyjets.phj[2][index], // pz hyjets.phj[3][index]), // E hyjets.khj[1][index], // id convertStatus(hyjets.khj[0][index] // status )); p->suggest_barcode(barcode); return p; } //___________________________________________________________________ HepMC::GenVertex* HydjetHadronizer::build_hyjet_vertex(int i, int id) { // build verteces for the hyjets stored events double x0 = hyjets.vhj[0][i]; double y0 = hyjets.vhj[1][i]; double x = x0 * cosphi0_ - y0 * sinphi0_; double y = y0 * cosphi0_ + x0 * sinphi0_; double z = hyjets.vhj[2][i]; double t = hyjets.vhj[4][i]; HepMC::GenVertex* vertex = new HepMC::GenVertex(HepMC::FourVector(x, y, z, t), id); return vertex; } //___________________________________________________________________ bool HydjetHadronizer::generatePartonsAndHadronize() { Pythia6Service::InstanceWrapper guard(pythia6Service_); // generate single event if (embedding_) { const edm::Event& e = getEDMEvent(); HepMC::GenVertex* genvtx = nullptr; const HepMC::GenEvent* inev = nullptr; Handle<CrossingFrame<HepMCProduct> > cf; e.getByToken(src_, cf); MixCollection<HepMCProduct> mix(cf.product()); if (mix.size() < 1) { throw cms::Exception("MatchVtx") << "Mixing has " << mix.size() << " sub-events, should have been at least 1" << endl; } const HepMCProduct& bkg = mix.getObject(0); if (!(bkg.isVtxGenApplied())) { throw cms::Exception("MatchVtx") << "Input background does not have smeared vertex!" << endl; } else { inev = bkg.GetEvent(); } genvtx = inev->signal_process_vertex(); if (!genvtx) throw cms::Exception("MatchVtx") << "Input background does not have signal process vertex!" << endl; double aX, aY, aZ, aT; aX = genvtx->position().x(); aY = genvtx->position().y(); aZ = genvtx->position().z(); aT = genvtx->position().t(); if (!fVertex_) { fVertex_ = new HepMC::FourVector(); } LogInfo("MatchVtx") << " setting vertex " << " aX " << aX << " aY " << aY << " aZ " << aZ << " aT " << aT << endl; fVertex_->set(aX, aY, aZ, aT); const HepMC::HeavyIon* hi = inev->heavy_ion(); if (hi) { bfixed_ = (hi->impact_parameter()) / nuclear_radius(); phi0_ = hi->event_plane_angle(); sinphi0_ = sin(phi0_); cosphi0_ = cos(phi0_); } else { LogWarning("EventEmbedding") << "Background event does not have heavy ion record!"; } } else if (rotate_) rotateEvtPlane(); nsoft_ = 0; nhard_ = 0; edm::LogInfo("HYDJETmode") << "##### HYDJET nhsel = " << hyjpar.nhsel; edm::LogInfo("HYDJETfpart") << "##### HYDJET fpart = " << hyflow.fpart; edm::LogInfo("HYDJETtf") << "##### HYDJET hadron freez-out temp, Tf = " << hyflow.Tf; edm::LogInfo("HYDJETinTemp") << "##### HYDJET: QGP init temperature, T0 =" << pyqpar.T0u; edm::LogInfo("HYDJETinTau") << "##### HYDJET: QGP formation time,tau0 =" << pyqpar.tau0u; int ntry = 0; while (nsoft_ == 0 && nhard_ == 0) { if (ntry > 100) { edm::LogError("HydjetEmptyEvent") << "##### HYDJET: No Particles generated, Number of tries =" << ntry; // Throw an exception. Use the EventCorruption exception since it maps onto SkipEvent // which is what we want to do here. std::ostringstream sstr; sstr << "HydjetHadronizerProducer: No particles generated after " << ntry << " tries.\n"; edm::Exception except(edm::errors::EventCorruption, sstr.str()); throw except; } else { HYEVNT(bfixed_); nsoft_ = hyfpar.nhyd; nsub_ = hyjpar.njet; nhard_ = hyfpar.npyt; ++ntry; } } if (hyjpar.nhsel < 3) nsub_++; // event information HepMC::GenEvent* evt = new HepMC::GenEvent(); if (nhard_ > 0 || nsoft_ > 0) get_particles(evt); evt->set_signal_process_id(pypars.msti[0]); // type of the process evt->set_event_scale(pypars.pari[16]); // Q^2 add_heavy_ion_rec(evt); if (fVertex_) { // generate new vertex & apply the shift // Copy the HepMC::GenEvent std::unique_ptr<edm::HepMCProduct> HepMCEvt(new edm::HepMCProduct(evt)); HepMCEvt->applyVtxGen(fVertex_); evt = new HepMC::GenEvent((*HepMCEvt->GetEvent())); } HepMC::HEPEVT_Wrapper::check_hepevt_consistency(); LogDebug("HEPEVT_info") << "Ev numb: " << HepMC::HEPEVT_Wrapper::event_number() << " Entries number: " << HepMC::HEPEVT_Wrapper::number_entries() << " Max. entries " << HepMC::HEPEVT_Wrapper::max_number_entries() << std::endl; event().reset(evt); return true; } //_____________________________________________________________________ bool HydjetHadronizer::get_particles(HepMC::GenEvent* evt) { // Hard particles. The first nhard_ lines from hyjets array. // Pythia/Pyquen sub-events (sub-collisions) for a given event // Return T/F if success/failure // Create particles from lujet entries, assign them into vertices and // put the vertices in the GenEvent, for each SubEvent // The SubEvent information is kept by storing indeces of main vertices // of subevents as a vector in GenHIEvent. LogDebug("SubEvent") << " Number of sub events " << nsub_; LogDebug("Hydjet") << " Number of hard events " << hyjpar.njet; LogDebug("Hydjet") << " Number of hard particles " << nhard_; LogDebug("Hydjet") << " Number of soft particles " << nsoft_; LogDebug("Hydjet") << " nhard_ + nsoft_ = " << nhard_ + nsoft_ << " hyjets.nhj = " << hyjets.nhj << endl; int ihy = 0; int isub = -1; int isub_l = -1; int stab = 0; vector<HepMC::GenParticle*> primary_particle(hyjets.nhj); vector<HepMC::GenParticle*> particle(hyjets.nhj); HepMC::GenVertex* sub_vertices = new HepMC::GenVertex(HepMC::FourVector(0, 0, 0, 0), 0); // just initialization // contain the last index in for each subevent vector<int> index(nsub_); while (ihy < hyjets.nhj) { isub = std::floor((hyjets.khj[2][ihy] / 50000)); int hjoffset = isub * 50000; if (isub != isub_l) { sub_vertices = new HepMC::GenVertex(HepMC::FourVector(0, 0, 0, 0), isub); evt->add_vertex(sub_vertices); if (!evt->signal_process_vertex()) evt->set_signal_process_vertex(sub_vertices); index[isub] = ihy - 1; isub_l = isub; } if (convertStatus(hyjets.khj[0][ihy]) == 1) stab++; LogDebug("Hydjet_array") << ihy << " MULTin ev.:" << hyjets.nhj << " SubEv.#" << isub << " Part #" << ihy + 1 << ", PDG: " << hyjets.khj[1][ihy] << " (st. " << convertStatus(hyjets.khj[0][ihy]) << ") mother=" << hyjets.khj[2][ihy] - (isub * 50000) + index[isub] + 1 << " (" << hyjets.khj[2][ihy] << "), childs (" << hyjets.khj[3][ihy] - (isub * 50000) + index[isub] + 1 << "-" << hyjets.khj[4][ihy] - (isub * 50000) + index[isub] + 1 << "), vtx (" << hyjets.vhj[0][ihy] << "," << hyjets.vhj[1][ihy] << "," << hyjets.vhj[2][ihy] << ") " << std::endl; if (hyjets.khj[2][ihy] == 0) { primary_particle[ihy] = build_hyjet(ihy, ihy + 1); sub_vertices->add_particle_out(primary_particle[ihy]); LogDebug("Hydjet_array") << " ---> " << ihy + 1 << std::endl; } else { particle[ihy] = build_hyjet(ihy, ihy + 1); int mid = hyjets.khj[2][ihy] - hjoffset + index[isub]; int mid_t = mid; while ((mid < ihy) && (hyjets.khj[1][mid] < 100) && (hyjets.khj[3][mid + 1] - hjoffset + index[isub] == ihy)) mid++; if (hyjets.khj[1][mid] < 100) mid = mid_t; HepMC::GenParticle* mother = primary_particle.at(mid); HepMC::GenVertex* prods = build_hyjet_vertex(ihy, isub); if (!mother) { mother = particle[mid]; primary_particle[mid] = mother; } HepMC::GenVertex* prod_vertex = mother->end_vertex(); if (!prod_vertex) { prod_vertex = prods; prod_vertex->add_particle_in(mother); LogDebug("Hydjet_array") << " <--- " << mid + 1 << std::endl; evt->add_vertex(prod_vertex); prods = nullptr; } prod_vertex->add_particle_out(particle[ihy]); LogDebug("Hydjet_array") << " ---" << mid + 1 << "---> " << ihy + 1 << std::endl; if (prods) delete prods; } ihy++; } LogDebug("Hydjet_array") << " MULTin ev.:" << hyjets.nhj << ", last index: " << ihy - 1 << ", Sub events: " << isub + 1 << ", stable particles: " << stab << std::endl; return true; } //______________________________________________________________ bool HydjetHadronizer::call_hyinit(double energy, double a, int ifb, double bmin, double bmax, double bfix, int nh) { // initialize hydjet pydatr.mrpy[2] = 1; HYINIT(energy, a, ifb, bmin, bmax, bfix, nh); return true; } //______________________________________________________________ bool HydjetHadronizer::hydjet_init(const ParameterSet& pset) { // set hydjet options // hydjet running mode mode // kHydroOnly --- nhsel=0 jet production off (pure HYDRO event), nhsel=0 // kHydroJets --- nhsle=1 jet production on, jet quenching off (HYDRO+njet*PYTHIA events) // kHydroQJet --- nhsel=2 jet production & jet quenching on (HYDRO+njet*PYQUEN events) // kJetsOnly --- nhsel=3 jet production on, jet quenching off, HYDRO off (njet*PYTHIA events) // kQJetsOnly --- nhsel=4 jet production & jet quenching on, HYDRO off (njet*PYQUEN events) if (hymode_ == "kHydroOnly") hyjpar.nhsel = 0; else if (hymode_ == "kHydroJets") hyjpar.nhsel = 1; else if (hymode_ == "kHydroQJets") hyjpar.nhsel = 2; else if (hymode_ == "kJetsOnly") hyjpar.nhsel = 3; else if (hymode_ == "kQJetsOnly") hyjpar.nhsel = 4; else hyjpar.nhsel = 2; // fraction of soft hydro induced multiplicity hyflow.fpart = fracsoftmult_; // hadron freez-out temperature hyflow.Tf = hadfreeztemp_; // maximum longitudinal collective rapidity hyflow.ylfl = maxlongy_; // maximum transverse collective rapidity hyflow.ytfl = maxtrany_; // shadowing on=1, off=0 hyjpar.ishad = shadowingswitch_; // set inelastic nucleon-nucleon cross section hyjpar.sigin = signn_; // angular emitted gluon spectrum selection pyqpar.ianglu = angularspecselector_; // number of active quark flavors in qgp pyqpar.nfu = nquarkflavor_; // initial temperature of QGP pyqpar.T0u = qgpt0_; // proper time of QGP formation pyqpar.tau0u = qgptau0_; // type of medium induced partonic energy loss if (doradiativeenloss_ && docollisionalenloss_) { edm::LogInfo("HydjetEnLoss") << "##### Radiative AND Collisional partonic energy loss ON ####"; pyqpar.ienglu = 0; } else if (doradiativeenloss_) { edm::LogInfo("HydjetenLoss") << "##### Only RADIATIVE partonic energy loss ON ####"; pyqpar.ienglu = 1; } else if (docollisionalenloss_) { edm::LogInfo("HydjetEnLoss") << "##### Only COLLISIONAL partonic energy loss ON ####"; pyqpar.ienglu = 2; } else { edm::LogInfo("HydjetEnLoss") << "##### Radiative AND Collisional partonic energy loss ON ####"; pyqpar.ienglu = 0; } return true; } //_____________________________________________________________________ bool HydjetHadronizer::readSettings(int) { Pythia6Service::InstanceWrapper guard(pythia6Service_); pythia6Service_->setGeneralParams(); return true; } //_____________________________________________________________________ bool HydjetHadronizer::initializeForInternalPartons() { Pythia6Service::InstanceWrapper guard(pythia6Service_); // pythia6Service_->setGeneralParams(); // the input impact parameter (bxx_) is in [fm]; transform in [fm/RA] for hydjet usage const float ra = nuclear_radius(); LogInfo("RAScaling") << "Nuclear radius(RA) = " << ra; bmin_ /= ra; bmax_ /= ra; bfixed_ /= ra; // hydjet running options hydjet_init(pset_); // initialize hydjet LogInfo("HYDJETinAction") << "##### Calling HYINIT(" << comenergy << "," << abeamtarget_ << "," << cflag_ << "," << bmin_ << "," << bmax_ << "," << bfixed_ << "," << nmultiplicity_ << ") ####"; call_hyinit(comenergy, abeamtarget_, cflag_, bmin_, bmax_, bfixed_, nmultiplicity_); return true; } bool HydjetHadronizer::declareStableParticles(const std::vector<int>& _pdg) { std::vector<int> pdg = _pdg; for (size_t i = 0; i < pdg.size(); i++) { int pyCode = pycomp_(pdg[i]); std::ostringstream pyCard; pyCard << "MDCY(" << pyCode << ",1)=0"; std::cout << pyCard.str() << std::endl; call_pygive(pyCard.str()); } return true; } //________________________________________________________________ void HydjetHadronizer::rotateEvtPlane() { const double pi = 3.14159265358979; phi0_ = 2. * pi * gen::pyr_(nullptr) - pi; sinphi0_ = sin(phi0_); cosphi0_ = cos(phi0_); } //________________________________________________________________ bool HydjetHadronizer::hadronize() { return false; } bool HydjetHadronizer::decay() { return true; } bool HydjetHadronizer::residualDecay() { return true; } void HydjetHadronizer::finalizeEvent() {} void HydjetHadronizer::statistics() {} const char* HydjetHadronizer::classname() const { return "gen::HydjetHadronizer"; }
38.511628
117
0.620912
[ "object", "vector", "transform" ]
33c0b5a76fb30f9970e156ffa8a8dd5307f3cbd7
801
cc
C++
part-4/039.cc
angrylearners/NPU-2019-CPP-course
0c526b1788f1922dd6af43e7534b3a4882ed397a
[ "MIT" ]
null
null
null
part-4/039.cc
angrylearners/NPU-2019-CPP-course
0c526b1788f1922dd6af43e7534b3a4882ed397a
[ "MIT" ]
null
null
null
part-4/039.cc
angrylearners/NPU-2019-CPP-course
0c526b1788f1922dd6af43e7534b3a4882ed397a
[ "MIT" ]
null
null
null
// // Created by 31838 on 9/23/2019. // #include <queue> #include <iostream> #include "common.h" auto main() -> int { auto num = Input<uint64_t>(std::cin); auto shift = Input<int64_t>(std::cin); std::vector<char> digits{}; while (num > 0) { auto ch = (char) ((num % 10) + '0'); digits.push_back(ch); num /= 10; } if (shift < 0) for (uint64_t i = 0; i < -1 * shift; i++) { auto front = digits.front(); digits.erase(digits.begin()); digits.push_back(front); } else if (shift > 0) for (uint64_t i = 0; i < shift; i++) { auto back = digits.back(); digits.erase(digits.end() - 1); digits.insert(digits.begin(), back); } for (auto v:digits) std::cout << v; std::cout << std::endl; return EXIT_SUCCESS; }
20.025
47
0.545568
[ "vector" ]
33c3b4a9ba38bef4cd9766cc3437b32373612529
2,196
hpp
C++
include/protozero/buffer_vector.hpp
mapbox/protozero
49acea746bff44b4e627e85676c49fca94a7a20a
[ "BSD-2-Clause", "Apache-2.0" ]
204
2015-07-11T13:07:05.000Z
2022-03-27T19:49:26.000Z
include/protozero/buffer_vector.hpp
mapbox/protozero
49acea746bff44b4e627e85676c49fca94a7a20a
[ "BSD-2-Clause", "Apache-2.0" ]
83
2015-07-10T22:27:33.000Z
2022-01-24T08:51:30.000Z
include/protozero/buffer_vector.hpp
mapbox/protozero
49acea746bff44b4e627e85676c49fca94a7a20a
[ "BSD-2-Clause", "Apache-2.0" ]
60
2015-08-24T10:04:13.000Z
2022-02-16T03:01:35.000Z
#ifndef PROTOZERO_BUFFER_VECTOR_HPP #define PROTOZERO_BUFFER_VECTOR_HPP /***************************************************************************** protozero - Minimalistic protocol buffer decoder and encoder in C++. This file is from https://github.com/mapbox/protozero where you can find more documentation. *****************************************************************************/ /** * @file buffer_vector.hpp * * @brief Contains the customization points for buffer implementation based * on std::vector<char> */ #include "buffer_tmpl.hpp" #include "config.hpp" #include <cstddef> #include <iterator> #include <vector> namespace protozero { // Implementation of buffer customizations points for std::vector<char> /// @cond INTERNAL template <> struct buffer_customization<std::vector<char>> { static std::size_t size(const std::vector<char>* buffer) noexcept { return buffer->size(); } static void append(std::vector<char>* buffer, const char* data, std::size_t count) { buffer->insert(buffer->end(), data, data + count); } static void append_zeros(std::vector<char>* buffer, std::size_t count) { buffer->insert(buffer->end(), count, '\0'); } static void resize(std::vector<char>* buffer, std::size_t size) { protozero_assert(size < buffer->size()); buffer->resize(size); } static void reserve_additional(std::vector<char>* buffer, std::size_t size) { buffer->reserve(buffer->size() + size); } static void erase_range(std::vector<char>* buffer, std::size_t from, std::size_t to) { protozero_assert(from <= buffer->size()); protozero_assert(to <= buffer->size()); protozero_assert(from <= to); buffer->erase(std::next(buffer->begin(), from), std::next(buffer->begin(), to)); } static char* at_pos(std::vector<char>* buffer, std::size_t pos) { protozero_assert(pos <= buffer->size()); return (&*buffer->begin()) + pos; } static void push_back(std::vector<char>* buffer, char ch) { buffer->push_back(ch); } }; /// @endcond } // namespace protozero #endif // PROTOZERO_BUFFER_VECTOR_HPP
28.153846
90
0.612477
[ "vector" ]
33c46393c0db144f2d1277c193122ed7fd617ca1
5,828
hpp
C++
libctrpf/include/CTRPluginFramework/Menu/MenuFolder.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
libctrpf/include/CTRPluginFramework/Menu/MenuFolder.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
libctrpf/include/CTRPluginFramework/Menu/MenuFolder.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
#ifndef CTRPLUGINFRAMEWORK_MENUFOLDER_HPP #define CTRPLUGINFRAMEWORK_MENUFOLDER_HPP #include "types.h" #include "CTRPluginFramework/Graphics/Color.hpp" #include <string> #include <memory> namespace CTRPluginFramework { #ifndef SEPARATOR_TYPE #define SEPARATOR_TYPE enum class Separator { None, Filled, Stippled }; #endif enum class ActionType { Opening, Closing }; class MenuFolderImpl; class MenuFolder { public: MenuFolder(const std::string &name, const std::string &note = ""); MenuFolder(const std::string &name, const std::vector<MenuEntry *> &entries); MenuFolder(const std::string &name, const std::string &note, const std::vector<MenuEntry *> &entries); /** * \brief Destroy a MenuFolder.\n * Upon destruction all MenuEntry and MenuFolder objects contained by this folder\n * will be destroyed too (so all pointers will be invalidated). */ ~MenuFolder(); /** * \brief Hide the folder from the menu.\n * Will disable every MenuEntry objects contained in this folder and subfolders */ void Hide(void) const; /** * \brief Display the folder previously hidden in the menu */ void Show(void) const; /** * \brief Check if the current folder is visible in the menu * \return true if the folder is visible, false otherwise */ bool IsVisible(void) const; /** * \brief Set if this entry must display a separator on top of the entry * \param type Type of separator to display */ void UseTopSeparator(Separator type = Separator::Filled) const; /** * \brief Set if this entry must display a separator at the bottom of the entry * \param type Type of separator to display */ void UseBottomSeparator(Separator type = Separator::Filled) const; /** * \brief Append a MenuEntry object to this folder * \param item The entry to append */ void Append(MenuEntry *item) const; /** * \brief Append a MenuFolder object to this folder * \param item The folder to append */ void Append(MenuFolder *item) const; /** * \brief Get all entries present in this folder (doesn't contain subfolder's) * \return A std::vector with pointers to all MenuEntry objects */ std::vector<MenuEntry *> GetEntryList(void) const; /** * \brief Get all folders present in this folder (doesn't contain subfolder's) * \return A std::vector with pointers to all MenuEntry objects */ std::vector<MenuFolder *> GetFolderList(void) const; /** * \brief Get a reference of the string that hold the name of this folder * \return A reference of the std::string */ std::string &Name(void) const; /** * \brief Get a reference of the string that hold the note of this folder * \return A reference of the std::string */ std::string &Note(void) const; /** * @brief Get the entry's name color * @return A reference to current name color */ Color &NameColor(void) const; /** * \brief Get the number of items that his folder contains (not counting subfolders's content) * \return The count of items */ u32 ItemsCount(void) const; /** * \brief Remove and destroy all items contained by this folder.\n * This invalidate all pointers to any contained object. */ void Clear(void) const; /** * \brief Remove all objects in the range specified * \param startIndex The index where the range begin * \param count The number of elements to remove * \param destroy If the elements must be destroyed (invalidate pointers and release ressources) */ void Remove(u32 startIndex, u32 count, bool destroy) const; /** * \brief Add an entry to this folder * \param entry The MenuEntry object that must be added * \return A pointer to this MenuFolder */ MenuFolder *operator += (const MenuEntry *entry); /** * \brief Remove an entry from this folder * \param entry The MenuEntry object that must be removed * \return A pointer to this MenuFolder */ MenuFolder *operator -= (const MenuEntry *entry); /** * \brief Add a (sub)folder to this folder * \param folder The MenuFolder object that must added * \return A pointer to this MenuFolder */ MenuFolder *operator += (const MenuFolder *folder); /** * \brief Remove a (sub)folder to this folder * \param folder The MenuFolder object that must be removed * \return A pointer to this MenuFolder */ MenuFolder *operator -= (const MenuFolder *folder); /** * \brief Callback type, receive the object that called the callback \n * along with the action which triggered the callback * \return Whether the folder can be opened (on ActionType::Opening only, ignored for ActionType::Closing) */ using MenuFolder_OnActionFunc = bool(*)(MenuFolder &, ActionType); /** * \brief This callback is called when the folder is about to be opened or closed */ MenuFolder_OnActionFunc OnAction; private: friend class PluginMenu; std::unique_ptr<MenuFolderImpl> _item; }; } #endif
32.377778
113
0.59523
[ "object", "vector" ]
33c47337bef208307cd3b4743095caf1ca81a4ea
4,408
cpp
C++
applications/RANSApplication/custom_processes/rans_epsilon_turbulent_mixing_length_inlet_process.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
applications/RANSApplication/custom_processes/rans_epsilon_turbulent_mixing_length_inlet_process.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
applications/RANSApplication/custom_processes/rans_epsilon_turbulent_mixing_length_inlet_process.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Suneth Warnakulasuriya // // System includes #include <cmath> #include <limits> // External includes // Project includes #include "includes/define.h" #include "utilities/parallel_utilities.h" #include "utilities/variable_utils.h" // Application includes #include "rans_application_variables.h" // Include base h #include "rans_epsilon_turbulent_mixing_length_inlet_process.h" namespace Kratos { RansEpsilonTurbulentMixingLengthInletProcess::RansEpsilonTurbulentMixingLengthInletProcess( Model& rModel, Parameters rParameters) : mrModel(rModel) { KRATOS_TRY rParameters.ValidateAndAssignDefaults(GetDefaultParameters()); mTurbulentMixingLength = rParameters["turbulent_mixing_length"].GetDouble(); mIsConstrained = rParameters["is_fixed"].GetBool(); mEchoLevel = rParameters["echo_level"].GetInt(); mModelPartName = rParameters["model_part_name"].GetString(); mMinValue = rParameters["min_value"].GetDouble(); KRATOS_ERROR_IF(mTurbulentMixingLength < std::numeric_limits<double>::epsilon()) << "turbulent_mixing_length should be greater than zero.\n"; KRATOS_ERROR_IF(mMinValue < 0.0) << "Minimum turbulent energy dissipation " "rate needs to be positive in the " "modelpart " << mModelPartName << "\n."; KRATOS_CATCH(""); } void RansEpsilonTurbulentMixingLengthInletProcess::ExecuteInitialize() { if (mIsConstrained) { auto& r_model_part = mrModel.GetModelPart(mModelPartName); VariableUtils().ApplyFixity(TURBULENT_ENERGY_DISSIPATION_RATE, true, r_model_part.Nodes()); KRATOS_INFO_IF(this->Info(), mEchoLevel > 0) << "Fixed TURBULENT_ENERGY_DISSIPATION_RATE dofs in " << mModelPartName << ".\n"; } } void RansEpsilonTurbulentMixingLengthInletProcess::ExecuteInitializeSolutionStep() { KRATOS_TRY auto& r_model_part = mrModel.GetModelPart(mModelPartName); const double c_mu_75 = std::pow(r_model_part.GetProcessInfo()[TURBULENCE_RANS_C_MU], 0.75); auto& r_nodes = r_model_part.Nodes(); block_for_each(r_nodes, [&](ModelPart::NodeType& rNode) { const double tke = rNode.FastGetSolutionStepValue(TURBULENT_KINETIC_ENERGY); rNode.FastGetSolutionStepValue(TURBULENT_ENERGY_DISSIPATION_RATE) = std::max( c_mu_75 * std::pow(std::max(tke, 0.0), 1.5) / mTurbulentMixingLength, mMinValue); }); KRATOS_INFO_IF(this->Info(), mEchoLevel > 0) << "Applied epsilon values to " << mModelPartName << ".\n"; KRATOS_CATCH(""); } int RansEpsilonTurbulentMixingLengthInletProcess::Check() { const auto& r_model_part = mrModel.GetModelPart(mModelPartName); KRATOS_ERROR_IF(!r_model_part.HasNodalSolutionStepVariable(TURBULENT_KINETIC_ENERGY)) << "TURBULENT_KINETIC_ENERGY is not found in nodal solution step variables list of " << mModelPartName << "."; KRATOS_ERROR_IF(!r_model_part.HasNodalSolutionStepVariable(TURBULENT_ENERGY_DISSIPATION_RATE)) << "TURBULENT_ENERGY_DISSIPATION_RATE is not found in nodal solution step variables list of " << mModelPartName << "."; return 0; } std::string RansEpsilonTurbulentMixingLengthInletProcess::Info() const { return std::string("RansEpsilonTurbulentMixingLengthInletProcess"); } void RansEpsilonTurbulentMixingLengthInletProcess::PrintInfo(std::ostream& rOStream) const { rOStream << this->Info(); } void RansEpsilonTurbulentMixingLengthInletProcess::PrintData(std::ostream& rOStream) const { } const Parameters RansEpsilonTurbulentMixingLengthInletProcess::GetDefaultParameters() const { const auto default_parameters = Parameters(R"( { "model_part_name" : "PLEASE_SPECIFY_MODEL_PART_NAME", "turbulent_mixing_length" : 0.005, "echo_level" : 0, "is_fixed" : true, "min_value" : 1e-14 })"); return default_parameters; } } // namespace Kratos.
32.175182
101
0.670145
[ "model" ]
33c475e97d2addf5ed87e89e4655da92d552d941
1,263
cpp
C++
src/CGnuPlotEveryData.cpp
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
null
null
null
src/CGnuPlotEveryData.cpp
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
null
null
null
src/CGnuPlotEveryData.cpp
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
1
2019-04-01T13:08:45.000Z
2019-04-01T13:08:45.000Z
#include <CGnuPlotEveryData.h> #include <CExpr.h> #include <CStrUtil.h> namespace { bool evaluateExpression(CExpr *expr, const std::string &exprStr, CExprValuePtr &value) { bool oldQuiet = expr->getQuiet(); expr->setQuiet(true); if (! expr->evaluateExpression(exprStr, value)) value = CExprValuePtr(); expr->setQuiet(oldQuiet); return true; } } //--- CGnuPlotEveryData:: CGnuPlotEveryData(CExpr *expr, const std::string &str) { if (str != "") (void) parse(expr, str); } bool CGnuPlotEveryData:: parse(CExpr *expr, const std::string &str) { assert(expr); std::vector<std::string> inds; CStrUtil::addFields(str, inds, ":"); //--- auto parseInd = [&](int i, int &var, int def) { var = def; if (int(inds.size()) > i) { CExprValuePtr value; var = def; if (inds[i] != "" && evaluateExpression(expr, inds[i], value)) { long l; if (value.isValid() && value->getIntegerValue(l)) var = l; } } }; parseInd(0, pointStep_ , 1); parseInd(1, blockStep_ , 1); parseInd(2, pointStart_, 0); parseInd(3, blockStart_, 0); parseInd(4, pointEnd_ , std::numeric_limits<int>::max()); parseInd(5, blockEnd_ , std::numeric_limits<int>::max()); return true; }
18.304348
88
0.613618
[ "vector" ]
33c7742078a531691b7b523b9dc1f5404c9d8d64
1,842
cpp
C++
lib/src/Music/SoundSystem.cpp
F4r3n/FarenMediaLibrary
3f71054df7178ca79781b101ca2d58cd95a20a43
[ "Apache-2.0" ]
7
2016-09-09T16:43:15.000Z
2021-06-16T22:32:33.000Z
lib/src/Music/SoundSystem.cpp
F4r3n/FarenMediaLibrary
3f71054df7178ca79781b101ca2d58cd95a20a43
[ "Apache-2.0" ]
null
null
null
lib/src/Music/SoundSystem.cpp
F4r3n/FarenMediaLibrary
3f71054df7178ca79781b101ca2d58cd95a20a43
[ "Apache-2.0" ]
1
2020-01-05T19:22:32.000Z
2020-01-05T19:22:32.000Z
#include "Music/SoundSystem.h" #include "Music/Speaker.h" #include "Music/Listener.h" #include <memory> #include "Components/CTransform.h" #include "Core/Transform.h" #include "Components/CSource.h" #include <AL/al.h> #include <AL/alc.h> //TODO WTF REMAKE ALL using namespace fms; SoundSystem::SoundSystem() { _speaker = nullptr; _listener = nullptr; } SoundSystem::~SoundSystem() { } void SoundSystem::pre_update(EntityManager& em) { } void SoundSystem::update(float , EntityManager& em, EventManager& ) { int error = 0; for(auto &&e : em.iterate<fmc::CTransform, fmc::CSource>()) { if((error = alGetError()) != 0) { //std::cerr << "Error openal" << std::endl; return; } fmc::CSource* sound = e->get<fmc::CSource>(); fmc::CTransform* transform = e->get<fmc::CTransform>(); if(sound->toUpdate) { _SetSettings(transform->GetTransform(), sound); } } } void SoundSystem::_SetSettings(const fm::Transform &inTransform, fmc::CSource* sound) { alSourcef(sound->source, AL_PITCH, sound->pitch); alSourcef(sound->source, AL_GAIN, sound->volume); alSource3f(sound->source, AL_POSITION, inTransform.position.x, inTransform.position.y, 0); alSource3f(sound->source, AL_VELOCITY, 0, 0, 0); alSourcei(sound->source, AL_LOOPING, sound->isLooping); } void SoundSystem::init(EntityManager& em, EventManager& event) { _speaker = std::unique_ptr<fm::Speaker>(new fm::Speaker()); _listener = std::unique_ptr<fm::Listener>(new fm::Listener()); for(auto &&e : em.iterate<fmc::CTransform, fmc::CSource>()) { fmc::CSource* sound = e->get<fmc::CSource>(); fmc::CTransform* transform = e->get<fmc::CTransform>(); _SetSettings(transform->GetTransform(), sound); } } void SoundSystem::over() { }
29.238095
94
0.649837
[ "transform" ]
33ce9956cbc2cb14ec7001edb7de5e8d1d0d7bf9
35,379
cc
C++
tensorflow/core/kernels/data/experimental/snapshot_util.cc
so5462/tensorflow
0f9acc15ba56ecf01a79889d29295310559c681a
[ "Apache-2.0" ]
74
2020-07-06T17:11:39.000Z
2022-01-28T06:31:28.000Z
tensorflow/core/kernels/data/experimental/snapshot_util.cc
sseung0703/tensorflow
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
[ "Apache-2.0" ]
88
2020-11-24T08:18:10.000Z
2022-03-25T20:28:30.000Z
tensorflow/core/kernels/data/experimental/snapshot_util.cc
sseung0703/tensorflow
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
[ "Apache-2.0" ]
12
2020-07-08T07:27:17.000Z
2021-12-27T08:54:27.000Z
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/data/experimental/snapshot_util.h" #include <queue> #include "absl/memory/memory.h" #include "tensorflow/core/common_runtime/dma_helper.h" #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/framework/tensor.pb.h" #include "tensorflow/core/kernels/data/name_utils.h" #include "tensorflow/core/lib/io/buffered_inputstream.h" #include "tensorflow/core/lib/io/random_inputstream.h" #include "tensorflow/core/lib/io/record_writer.h" #include "tensorflow/core/lib/io/snappy/snappy_inputbuffer.h" #include "tensorflow/core/lib/io/snappy/snappy_outputbuffer.h" #include "tensorflow/core/lib/io/zlib_compression_options.h" #include "tensorflow/core/lib/io/zlib_inputstream.h" #include "tensorflow/core/lib/io/zlib_outputbuffer.h" #include "tensorflow/core/platform/coding.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/file_system.h" #include "tensorflow/core/platform/path.h" #include "tensorflow/core/platform/random.h" #include "tensorflow/core/platform/stringprintf.h" #include "tensorflow/core/profiler/lib/traceme.h" #include "tensorflow/core/protobuf/data/experimental/snapshot.pb.h" namespace tensorflow { namespace data { namespace snapshot_util { /* static */ constexpr const int64 CustomReader::kSnappyReaderInputBufferSizeBytes; /* static */ constexpr const int64 CustomReader::kSnappyReaderOutputBufferSizeBytes; std::string HashDirectory(const std::string& path, uint64 hash) { return io::JoinPath( path, strings::Printf("%llu", static_cast<unsigned long long>(hash))); } std::string RunDirectory(const std::string& hash_directory, uint64 run_id) { return RunDirectory( hash_directory, strings::Printf("%llu", static_cast<unsigned long long>(run_id))); } std::string RunDirectory(const std::string& hash_directory, const std::string& run_id) { return io::JoinPath(hash_directory, run_id); } std::string ShardDirectory(const std::string& run_directory, int64 shard_id) { return io::JoinPath( run_directory, strings::Printf("%08llu%s", static_cast<unsigned long long>(shard_id), kShardDirectorySuffix)); } std::string GetCheckpointFileName(const std::string& shard_directory, uint64 checkpoint_id) { return io::JoinPath( shard_directory, strings::Printf("%08llu.snapshot", static_cast<unsigned long long>(checkpoint_id))); } Status Writer::Create(Env* env, const std::string& filename, const std::string& compression_type, int version, const DataTypeVector& dtypes, std::unique_ptr<Writer>* out_writer) { switch (version) { case 1: *out_writer = absl::make_unique<CustomWriter>(filename, compression_type, dtypes); break; case 2: *out_writer = absl::make_unique<TFRecordWriter>(filename, compression_type); break; default: return errors::InvalidArgument("Snapshot writer version: ", version, " is not supported."); } return (*out_writer)->Initialize(env); } TFRecordWriter::TFRecordWriter(const std::string& filename, const std::string& compression_type) : filename_(filename), compression_type_(compression_type) {} Status TFRecordWriter::Initialize(tensorflow::Env* env) { TF_RETURN_IF_ERROR(env->NewAppendableFile(filename_, &dest_)); record_writer_ = absl::make_unique<io::RecordWriter>( dest_.get(), io::RecordWriterOptions::CreateRecordWriterOptions( /*compression_type=*/compression_type_)); return Status::OK(); } Status TFRecordWriter::WriteTensors(const std::vector<Tensor>& tensors) { for (const auto& tensor : tensors) { TensorProto proto; tensor.AsProtoTensorContent(&proto); #if defined(PLATFORM_GOOGLE) TF_RETURN_IF_ERROR(record_writer_->WriteRecord(proto.SerializeAsCord())); #else // PLATFORM_GOOGLE TF_RETURN_IF_ERROR(record_writer_->WriteRecord(proto.SerializeAsString())); #endif // PLATFORM_GOOGLE } return Status::OK(); } Status TFRecordWriter::Sync() { TF_RETURN_IF_ERROR(record_writer_->Flush()); return dest_->Flush(); } Status TFRecordWriter::Close() { if (record_writer_ != nullptr) { TF_RETURN_IF_ERROR(Sync()); TF_RETURN_IF_ERROR(record_writer_->Close()); TF_RETURN_IF_ERROR(dest_->Close()); record_writer_ = nullptr; dest_ = nullptr; } return Status::OK(); } TFRecordWriter::~TFRecordWriter() { Status s = Close(); if (!s.ok()) { LOG(ERROR) << "Failed to close snapshot file " << filename_ << ": " << s; } } CustomWriter::CustomWriter(const std::string& filename, const std::string& compression_type, const DataTypeVector& dtypes) : filename_(filename), compression_type_(compression_type), dtypes_(dtypes) {} Status CustomWriter::Initialize(tensorflow::Env* env) { TF_RETURN_IF_ERROR(env->NewAppendableFile(filename_, &dest_)); #if defined(IS_SLIM_BUILD) if (compression_type_ != io::compression::kNone) { LOG(ERROR) << "Compression is unsupported on mobile platforms. Turning " << "off compression."; } #else // IS_SLIM_BUILD if (compression_type_ == io::compression::kGzip) { zlib_underlying_dest_.swap(dest_); io::ZlibCompressionOptions zlib_options; zlib_options = io::ZlibCompressionOptions::GZIP(); io::ZlibOutputBuffer* zlib_output_buffer = new io::ZlibOutputBuffer( zlib_underlying_dest_.get(), zlib_options.input_buffer_size, zlib_options.output_buffer_size, zlib_options); TF_CHECK_OK(zlib_output_buffer->Init()); dest_.reset(zlib_output_buffer); } #endif // IS_SLIM_BUILD simple_tensor_mask_.reserve(dtypes_.size()); for (const auto& dtype : dtypes_) { if (DataTypeCanUseMemcpy(dtype)) { simple_tensor_mask_.push_back(true); num_simple_++; } else { simple_tensor_mask_.push_back(false); num_complex_++; } } return Status::OK(); } Status CustomWriter::WriteTensors(const std::vector<Tensor>& tensors) { if (compression_type_ != io::compression::kSnappy) { experimental::SnapshotRecord record; for (const auto& tensor : tensors) { TensorProto* t = record.add_tensor(); tensor.AsProtoTensorContent(t); } #if defined(PLATFORM_GOOGLE) return WriteRecord(record.SerializeAsCord()); #else // PLATFORM_GOOGLE return WriteRecord(record.SerializeAsString()); #endif // PLATFORM_GOOGLE } if (compression_type_ != io::compression::kSnappy) { return errors::InvalidArgument("Compression ", compression_type_, " is not supported."); } std::vector<const TensorBuffer*> tensor_buffers; tensor_buffers.reserve(num_simple_); std::vector<TensorProto> tensor_protos; tensor_protos.reserve(num_complex_); experimental::SnapshotTensorMetadata metadata; int64 total_size = 0; for (int i = 0, end = tensors.size(); i < end; ++i) { const Tensor& tensor = tensors[i]; experimental::TensorMetadata* tensor_metadata = metadata.add_tensor_metadata(); tensor.shape().AsProto(tensor_metadata->mutable_tensor_shape()); int64 size = 0; if (simple_tensor_mask_[i]) { auto tensor_buffer = DMAHelper::buffer(&tensor); tensor_buffers.push_back(tensor_buffer); size = tensor_buffer->size(); } else { TensorProto proto; tensor.AsProtoTensorContent(&proto); size = proto.ByteSizeLong(); tensor_protos.push_back(std::move(proto)); } tensor_metadata->set_tensor_size_bytes(size); total_size += size; } std::vector<char> uncompressed(total_size); char* position = uncompressed.data(); int buffer_index = 0; int proto_index = 0; for (int i = 0, end = tensors.size(); i < end; ++i) { const auto& tensor_metadata = metadata.tensor_metadata(i); if (simple_tensor_mask_[i]) { memcpy(position, tensor_buffers[buffer_index]->data(), tensor_metadata.tensor_size_bytes()); buffer_index++; } else { tensor_protos[proto_index].SerializeToArray( position, tensor_metadata.tensor_size_bytes()); proto_index++; } position += tensor_metadata.tensor_size_bytes(); } DCHECK_EQ(position, uncompressed.data() + total_size); string output; if (!port::Snappy_Compress(uncompressed.data(), total_size, &output)) { return errors::Internal("Failed to compress using snappy."); } #if defined(PLATFORM_GOOGLE) absl::Cord metadata_serialized = metadata.SerializeAsCord(); #else // PLATFORM_GOOGLE std::string metadata_serialized = metadata.SerializeAsString(); #endif // PLATFORM_GOOGLE TF_RETURN_IF_ERROR(WriteRecord(metadata_serialized)); TF_RETURN_IF_ERROR(WriteRecord(output)); return Status::OK(); } Status CustomWriter::Sync() { return dest_->Sync(); } Status CustomWriter::Close() { if (dest_ != nullptr) { TF_RETURN_IF_ERROR(dest_->Close()); dest_ = nullptr; } if (zlib_underlying_dest_ != nullptr) { TF_RETURN_IF_ERROR(zlib_underlying_dest_->Close()); zlib_underlying_dest_ = nullptr; } return Status::OK(); } CustomWriter::~CustomWriter() { Status s = Close(); if (!s.ok()) { LOG(ERROR) << "Could not finish writing file: " << s; } } Status CustomWriter::WriteRecord(const StringPiece& data) { char header[kHeaderSize]; core::EncodeFixed64(header, data.size()); TF_RETURN_IF_ERROR(dest_->Append(StringPiece(header, sizeof(header)))); return dest_->Append(data); } #if defined(PLATFORM_GOOGLE) Status CustomWriter::WriteRecord(const absl::Cord& data) { char header[kHeaderSize]; core::EncodeFixed64(header, data.size()); TF_RETURN_IF_ERROR(dest_->Append(StringPiece(header, sizeof(header)))); return dest_->Append(data); } #endif // PLATFORM_GOOGLE Status Reader::Create(Env* env, const std::string& filename, const string& compression_type, int version, const DataTypeVector& dtypes, std::unique_ptr<Reader>* out_reader) { switch (version) { // CustomReader is able to read a legacy snapshot file format (v0) though // custom writer doesn't have the ability to write it any more since it is // strictly worse than V1. case 0: case 1: *out_reader = absl::make_unique<CustomReader>(filename, compression_type, version, dtypes); break; case 2: *out_reader = absl::make_unique<TFRecordReader>(filename, compression_type, dtypes); break; default: return errors::InvalidArgument("Snapshot reader version: ", version, " is not supported."); } return (*out_reader)->Initialize(env); } Status Reader::SkipRecords(int64 num_records) { // TODO(frankchn): Optimize to not parse the entire Tensor and actually skip. for (int i = 0; i < num_records; ++i) { std::vector<Tensor> unused_tensors; TF_RETURN_IF_ERROR(ReadTensors(&unused_tensors)); } return Status::OK(); } class Reader::Dataset : public DatasetBase { public: explicit Dataset(const std::string& shard_dir, const std::string& compression, const int64 version, const DataTypeVector& dtypes, const std::vector<PartialTensorShape>& shapes, const int64 start_index, DatasetContext::Params params) : DatasetBase(DatasetContext(std::move(params))), shard_dir_(shard_dir), compression_(compression), version_(version), dtypes_(dtypes), shapes_(shapes), start_index_(start_index) {} const DataTypeVector& output_dtypes() const override { return dtypes_; } const std::vector<PartialTensorShape>& output_shapes() const override { return shapes_; } std::string DebugString() const override { return "snapshot_util::Reader::Dataset"; } Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override { return Status::OK(); } Status CheckExternalState() const override { return Status::OK(); } protected: Status AsGraphDefInternal(SerializationContext* ctx, DatasetGraphDefBuilder* b, Node** node) const override { // Not necessary perform any serialization as this dataset is only // constructed at runtime in C++ and will be reconstructed every time. return Status::OK(); } std::unique_ptr<IteratorBase> MakeIteratorInternal( const string& prefix) const override { return absl::make_unique<Iterator>(Iterator::Params{ this, name_utils::IteratorPrefix(node_name(), prefix)}); } private: class Iterator : public DatasetIterator<Dataset> { public: explicit Iterator(const Params& params) : DatasetIterator<Dataset>(params), current_checkpoint_id_(0) {} Status Initialize(IteratorContext* ctx) override { TF_RETURN_IF_ERROR(Reader::Create( ctx->env(), GetCurrentFilename(), dataset()->compression_, dataset()->version_, dataset()->dtypes_, &reader_)); bool end_of_sequence; for (int64 i = 0; i < dataset()->start_index_; ++i) { // TODO(frankchn): Optimize this to not parse every single element. std::vector<Tensor> unused; TF_RETURN_IF_ERROR(GetNextInternal(ctx, &unused, &end_of_sequence)); } return Status::OK(); } protected: Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { *end_of_sequence = false; Status s = reader_->ReadTensors(out_tensors); if (!errors::IsOutOfRange(s)) { return s; } Status status = AdvanceToNextFile(ctx->env()); if (errors::IsNotFound(status)) { *end_of_sequence = true; return Status::OK(); } else { return status; } } Status SaveInternal(SerializationContext* ctx, IteratorStateWriter* writer) override { // Not necessary to save any state as this iterator will be reconstructed // from scratch when the parent snapshot dataset is restored from // checkpoint. return Status::OK(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { // Not necessary to restore any state as this iterator will be // reconstructed from scratch when the parent snapshot dataset is restored // from checkpoint. return Status::OK(); } private: std::string GetCurrentFilename() { return GetCheckpointFileName(dataset()->shard_dir_, current_checkpoint_id_); } Status AdvanceToNextFile(Env* env) { current_checkpoint_id_++; TF_RETURN_IF_ERROR(env->FileExists(GetCurrentFilename())); return Reader::Create(env, GetCurrentFilename(), dataset()->compression_, dataset()->version_, dataset()->dtypes_, &reader_); } std::unique_ptr<Reader> reader_; // Stores the id current checkpoint file that we are in the process of // reading (e.g. if the file is currently 00000001.snapshot, then this will // be 1). uint64 current_checkpoint_id_; }; const std::string shard_dir_; const std::string compression_; const int64 version_; const DataTypeVector dtypes_; const std::vector<PartialTensorShape> shapes_; const int64 start_index_; }; class Reader::NestedDataset : public DatasetBase { public: explicit NestedDataset(std::vector<DatasetBase*> datasets, DatasetContext::Params params) : DatasetBase(DatasetContext(std::move(params))), datasets_(datasets) { dtypes_.push_back(DT_VARIANT); gtl::InlinedVector<int64, 1> element_dim_sizes; element_dim_sizes.push_back(1); partial_shapes_.emplace_back(element_dim_sizes); } const DataTypeVector& output_dtypes() const override { return dtypes_; } const std::vector<PartialTensorShape>& output_shapes() const override { return partial_shapes_; } std::string DebugString() const override { return "snapshot_util::Reader::NestedDataset"; } Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override { inputs->clear(); return Status::OK(); } Status CheckExternalState() const override { return Status::OK(); } protected: Status AsGraphDefInternal(SerializationContext* ctx, DatasetGraphDefBuilder* b, Node** node) const override { // Not necessary perform any serialization as this dataset is only // constructed at runtime in C++ and will be reconstructed every time. return Status::OK(); } std::unique_ptr<IteratorBase> MakeIteratorInternal( const string& prefix) const override { return absl::make_unique<Iterator>(Iterator::Params{ this, name_utils::IteratorPrefix(node_name(), prefix)}); } private: std::vector<DatasetBase*> datasets_; DataTypeVector dtypes_; std::vector<PartialTensorShape> partial_shapes_; class Iterator : public DatasetIterator<NestedDataset> { public: explicit Iterator(const Params& params) : DatasetIterator<NestedDataset>(params), index_(0) {} protected: Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { const int64 num_datasets = dataset()->datasets_.size(); *end_of_sequence = num_datasets == index_; if (!*end_of_sequence) { Tensor tensor(DT_VARIANT, TensorShape({})); TF_RETURN_IF_ERROR( StoreDatasetInVariantTensor(dataset()->datasets_[index_], &tensor)); out_tensors->clear(); out_tensors->push_back(std::move(tensor)); index_++; } return Status::OK(); } Status SaveInternal(SerializationContext* ctx, IteratorStateWriter* writer) override { // Not necessary to save any state as this iterator will be reconstructed // from scratch when the parent snapshot dataset is restored from // checkpoint. return Status::OK(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { // Not necessary to restore any state as this iterator will be // reconstructed from scratch when the parent snapshot dataset is restored // from checkpoint. return Status::OK(); } private: int64 index_; }; }; Status Reader::MakeNestedDataset(Env* env, const std::vector<std::string>& shard_dirs, const string& compression_type, int version, const DataTypeVector& dtypes, const std::vector<PartialTensorShape>& shapes, const int64 start_index, DatasetBase** output) { std::vector<DatasetBase*> datasets; datasets.reserve(shard_dirs.size()); for (const auto& shard_dir : shard_dirs) { // TODO(frankchn): The reading pattern could be controlled in a non-round // robin fashion, so we cannot assume a round-robin manner when restoring. int64 dataset_start_index = start_index / shard_dirs.size(); if (start_index % shard_dirs.size() > datasets.size()) { dataset_start_index++; } datasets.push_back( new Dataset(shard_dir, compression_type, version, dtypes, shapes, dataset_start_index, DatasetContext::Params({"snapshot_util::Reader::Dataset", "snapshot_util_reader_Dataset"}))); } // Rotate the vector such that the first dataset contains the next element // to be produced. std::rotate(datasets.begin(), datasets.begin() + (start_index % shard_dirs.size()), datasets.end()); *output = new NestedDataset( datasets, DatasetContext::Params({"snapshot_util::Reader::NestedDataset", "snapshot_util_reader_NestedDataset"})); return Status::OK(); } TFRecordReader::TFRecordReader(const std::string& filename, const string& compression_type, const DataTypeVector& dtypes) : filename_(filename), offset_(0), compression_type_(compression_type), dtypes_(dtypes) {} Status TFRecordReader::Initialize(Env* env) { TF_RETURN_IF_ERROR(env->NewRandomAccessFile(filename_, &file_)); record_reader_ = absl::make_unique<io::RecordReader>( file_.get(), io::RecordReaderOptions::CreateRecordReaderOptions( /*compression_type=*/compression_type_)); return Status::OK(); } Status TFRecordReader::ReadTensors(std::vector<Tensor>* read_tensors) { read_tensors->reserve(dtypes_.size()); for (int i = 0; i < dtypes_.size(); ++i) { tstring record; TF_RETURN_IF_ERROR(record_reader_->ReadRecord(&offset_, &record)); TensorProto proto; proto.ParseFromArray(record.data(), record.size()); Tensor tensor; if (!tensor.FromProto(proto)) { return errors::DataLoss("Unable to parse tensor from stored proto."); } read_tensors->push_back(std::move(tensor)); } return Status::OK(); } CustomReader::CustomReader(const std::string& filename, const string& compression_type, const int version, const DataTypeVector& dtypes) : filename_(filename), compression_type_(compression_type), version_(version), dtypes_(dtypes) {} Status CustomReader::Initialize(Env* env) { TF_RETURN_IF_ERROR(env->NewRandomAccessFile(filename_, &file_)); input_stream_ = std::make_unique<io::RandomAccessInputStream>(file_.get()); #if defined(IS_SLIM_BUILD) if (compression_type_ != io::compression::kNone) { LOG(ERROR) << "Compression is unsupported on mobile platforms. Turning " << "off compression."; } #else // IS_SLIM_BUILD if (compression_type_ == io::compression::kGzip) { io::ZlibCompressionOptions zlib_options; zlib_options = io::ZlibCompressionOptions::GZIP(); input_stream_ = absl::make_unique<io::ZlibInputStream>( input_stream_.release(), zlib_options.input_buffer_size, zlib_options.output_buffer_size, zlib_options, true); } else if (compression_type_ == io::compression::kSnappy) { if (version_ == 0) { input_stream_ = absl::make_unique<io::SnappyInputBuffer>( file_.get(), /*input_buffer_bytes=*/kSnappyReaderInputBufferSizeBytes, /*output_buffer_bytes=*/kSnappyReaderOutputBufferSizeBytes); } else { input_stream_ = absl::make_unique<io::BufferedInputStream>(file_.get(), 64 << 20); } } #endif // IS_SLIM_BUILD simple_tensor_mask_.reserve(dtypes_.size()); for (const auto& dtype : dtypes_) { if (DataTypeCanUseMemcpy(dtype)) { simple_tensor_mask_.push_back(true); num_simple_++; } else { simple_tensor_mask_.push_back(false); num_complex_++; } } return Status::OK(); } Status CustomReader::ReadTensors(std::vector<Tensor>* read_tensors) { profiler::TraceMe activity( [&]() { return absl::StrCat(kClassName, kSeparator, "ReadTensors"); }, profiler::TraceMeLevel::kInfo); if (version_ == 0 || compression_type_ != io::compression::kSnappy) { return ReadTensorsV0(read_tensors); } if (version_ != 1) { return errors::InvalidArgument("Version: ", version_, " is not supported."); } if (compression_type_ != io::compression::kSnappy) { return errors::InvalidArgument("Compression ", compression_type_, " is not supported."); } experimental::SnapshotTensorMetadata metadata; tstring metadata_str; TF_RETURN_IF_ERROR(ReadRecord(&metadata_str)); if (!metadata.ParseFromArray(metadata_str.data(), metadata_str.size())) { return errors::DataLoss("Could not parse SnapshotTensorMetadata"); } read_tensors->reserve(metadata.tensor_metadata_size()); std::vector<Tensor> simple_tensors; simple_tensors.reserve(num_simple_); std::vector<std::pair<std::unique_ptr<char[]>, size_t>> tensor_proto_strs; tensor_proto_strs.reserve(num_complex_); TF_RETURN_IF_ERROR( SnappyUncompress(&metadata, &simple_tensors, &tensor_proto_strs)); int simple_index = 0; int complex_index = 0; for (int i = 0, end = simple_tensor_mask_.size(); i < end; ++i) { if (simple_tensor_mask_[i]) { read_tensors->push_back(std::move(simple_tensors[simple_index])); simple_index++; } else { auto tensor_proto_str = std::move(tensor_proto_strs[complex_index].first); size_t tensor_proto_size = tensor_proto_strs[complex_index].second; TensorProto tp; #if defined(PLATFORM_GOOGLE) absl::string_view tensor_proto_view(tensor_proto_str.get(), tensor_proto_size); absl::Cord c = absl::MakeCordFromExternal( tensor_proto_view, [s = std::move(tensor_proto_str)] {}); if (!tp.ParseFromCord(c)) { return errors::Internal("Could not parse TensorProto"); } #else // PLATFORM_GOOGLE if (!tp.ParseFromArray(tensor_proto_str.get(), tensor_proto_size)) { return errors::Internal("Could not parse TensorProto"); } #endif // PLATFORM_GOOGLE Tensor t; if (!t.FromProto(tp)) { return errors::Internal("Could not parse Tensor"); } read_tensors->push_back(std::move(t)); complex_index++; } } return Status::OK(); } Status CustomReader::ReadTensorsV0(std::vector<Tensor>* read_tensors) { experimental::SnapshotRecord record; #if defined(PLATFORM_GOOGLE) absl::Cord c; TF_RETURN_IF_ERROR(ReadRecord(&c)); record.ParseFromCord(c); #else // PLATFORM_GOOGLE tstring record_bytes; TF_RETURN_IF_ERROR(ReadRecord(&record_bytes)); record.ParseFromArray(record_bytes.data(), record_bytes.size()); #endif // PLATFORM_GOOGLE read_tensors->reserve(record.tensor_size()); for (int i = 0; i < record.tensor_size(); ++i) { read_tensors->emplace_back(); if (!read_tensors->back().FromProto(record.tensor(i))) { return errors::DataLoss("Unable to parse tensor from proto."); } } return Status::OK(); } Status CustomReader::SnappyUncompress( const experimental::SnapshotTensorMetadata* metadata, std::vector<Tensor>* simple_tensors, std::vector<std::pair<std::unique_ptr<char[]>, size_t>>* tensor_proto_strs) { tstring compressed; TF_RETURN_IF_ERROR(ReadRecord(&compressed)); size_t size; if (!port::Snappy_GetUncompressedLength(compressed.data(), compressed.size(), &size)) { return errors::Internal("Could not get snappy uncompressed length"); } int num_tensors = metadata->tensor_metadata_size(); std::vector<struct iovec> iov(num_tensors); int index = 0; int64 total_size = 0; for (int i = 0, end = simple_tensor_mask_.size(); i < end; ++i) { const auto& tensor_metadata = metadata->tensor_metadata(i); if (simple_tensor_mask_[i]) { TensorShape shape(tensor_metadata.tensor_shape()); Tensor simple_tensor(dtypes_[i], shape); TensorBuffer* buffer = DMAHelper::buffer(&simple_tensor); iov[index].iov_base = buffer->data(); iov[index].iov_len = buffer->size(); simple_tensors->push_back(std::move(simple_tensor)); } else { auto tensor_proto_str = absl::make_unique<char[]>(tensor_metadata.tensor_size_bytes()); iov[index].iov_base = tensor_proto_str.get(); iov[index].iov_len = tensor_metadata.tensor_size_bytes(); tensor_proto_strs->push_back(std::make_pair( std::move(tensor_proto_str), tensor_metadata.tensor_size_bytes())); } total_size += iov[index].iov_len; index++; } const int64 size_int = size; if (size_int != total_size) { return errors::Internal("Uncompressed size mismatch. Snappy expects ", size, " whereas the tensor metadata suggests ", total_size); } if (!port::Snappy_UncompressToIOVec(compressed.data(), compressed.size(), iov.data(), num_tensors)) { return errors::Internal("Failed to perform snappy decompression."); } return Status::OK(); } Status CustomReader::ReadRecord(tstring* record) { tstring header; TF_RETURN_IF_ERROR(input_stream_->ReadNBytes(kHeaderSize, &header)); uint64 length = core::DecodeFixed64(header.data()); return input_stream_->ReadNBytes(length, record); } #if defined(PLATFORM_GOOGLE) Status CustomReader::ReadRecord(absl::Cord* record) { tstring header; TF_RETURN_IF_ERROR(input_stream_->ReadNBytes(kHeaderSize, &header)); uint64 length = core::DecodeFixed64(header.data()); if (compression_type_ == io::compression::kNone) { return input_stream_->ReadNBytes(length, record); } else { auto tmp_str = absl::make_unique<tstring>(); TF_RETURN_IF_ERROR(input_stream_->ReadNBytes(length, tmp_str.get())); absl::string_view tmp_str_view(*tmp_str); record->Append( absl::MakeCordFromExternal(tmp_str_view, [s = std::move(tmp_str)] {})); return Status::OK(); } } #endif Status WriteMetadataFile(Env* env, const string& dir, const experimental::SnapshotMetadataRecord* metadata) { string metadata_filename = io::JoinPath(dir, kMetadataFilename); TF_RETURN_IF_ERROR(env->RecursivelyCreateDir(dir)); std::string tmp_filename = absl::StrCat(metadata_filename, "-tmp-", random::New64()); TF_RETURN_IF_ERROR(WriteBinaryProto(env, tmp_filename, *metadata)); return env->RenameFile(tmp_filename, metadata_filename); } Status ReadMetadataFile(Env* env, const string& dir, experimental::SnapshotMetadataRecord* metadata, bool* file_exists) { string metadata_filename = io::JoinPath(dir, kMetadataFilename); Status s = env->FileExists(metadata_filename); *file_exists = s.ok(); if (*file_exists) { return ReadBinaryProto(env, metadata_filename, metadata); } else { return Status::OK(); } } Status DumpDatasetGraph(Env* env, const std::string& path, uint64 hash, const GraphDef* graph) { std::string hash_hex = strings::StrCat(strings::Hex(hash, strings::kZeroPad16)); std::string graph_file = io::JoinPath(path, absl::StrCat(hash_hex, "-graph.pbtxt")); LOG(INFO) << "Graph hash is " << hash_hex << ", writing to " << graph_file; TF_RETURN_IF_ERROR(env->RecursivelyCreateDir(path)); return WriteTextProto(env, graph_file, *graph); } Status DetermineOpState(const std::string& mode_string, bool file_exists, const experimental::SnapshotMetadataRecord* metadata, const uint64 pending_snapshot_expiry_seconds, Mode* mode) { if (mode_string == kModeRead) { // In read mode, we should expect a metadata file is written. if (!file_exists) { return errors::NotFound("Metadata file does not exist."); } LOG(INFO) << "Overriding mode to reader."; *mode = READER; return Status::OK(); } if (mode_string == kModeWrite) { LOG(INFO) << "Overriding mode to writer."; *mode = WRITER; return Status::OK(); } if (mode_string == kModePassthrough) { LOG(INFO) << "Overriding mode to passthrough."; *mode = PASSTHROUGH; return Status::OK(); } if (!file_exists) { *mode = WRITER; return Status::OK(); } if (metadata->finalized()) { // File found, snapshot has been finalized. *mode = READER; return Status::OK(); } int64 expiration_timer = static_cast<int64>(EnvTime::NowMicros()) - pending_snapshot_expiry_seconds * 1000000; if (metadata->creation_timestamp() >= expiration_timer) { // Someone else is already writing and time has not expired. *mode = PASSTHROUGH; return Status::OK(); } else { // Time has expired, we write regardless. *mode = WRITER; return Status::OK(); } } AsyncWriter::AsyncWriter(Env* env, int64 file_index, const std::string& shard_directory, uint64 checkpoint_id, const std::string& compression, int64 version, const DataTypeVector& output_types, std::function<void(Status)> done) { thread_ = absl::WrapUnique(env->StartThread( ThreadOptions(), absl::StrCat("writer_thread_", file_index), [this, env, shard_directory, checkpoint_id, compression, version, &output_types, done = std::move(done)] { done(WriterThread(env, shard_directory, checkpoint_id, compression, version, output_types)); })); } void AsyncWriter::Write(const std::vector<Tensor>& tensors) { mutex_lock l(mu_); ElementOrEOF element; element.value = tensors; deque_.push_back(std::move(element)); } void AsyncWriter::SignalEOF() { mutex_lock l(mu_); ElementOrEOF be; be.end_of_sequence = true; deque_.push_back(std::move(be)); } void AsyncWriter::Consume(ElementOrEOF* be) { mutex_lock l(mu_); mu_.Await(tensorflow::Condition(this, &AsyncWriter::ElementAvailable)); *be = deque_.front(); deque_.pop_front(); } bool AsyncWriter::ElementAvailable() { return !deque_.empty(); } Status AsyncWriter::WriterThread(Env* env, const std::string& shard_directory, uint64 checkpoint_id, const std::string& compression, int64 version, DataTypeVector output_types) { std::unique_ptr<snapshot_util::Writer> writer; TF_RETURN_IF_ERROR(env->RecursivelyCreateDir(shard_directory)); TF_RETURN_IF_ERROR(snapshot_util::Writer::Create( env, GetCheckpointFileName(shard_directory, checkpoint_id), compression, version, std::move(output_types), &writer)); while (true) { ElementOrEOF be; Consume(&be); if (be.end_of_sequence) { TF_RETURN_IF_ERROR(writer->Close()); break; } TF_RETURN_IF_ERROR(writer->WriteTensors(be.value)); } return Status::OK(); } } // namespace snapshot_util } // namespace data } // namespace tensorflow
35.485456
80
0.666271
[ "shape", "vector" ]
33cfa98e943ace21bfd0b46af5f4aafa979f8a25
9,081
cpp
C++
WickedEngine/wiTransform.cpp
Svengali/WickedEngine
6f56672476993ea95039db003b6dcf39231855db
[ "Zlib", "MIT" ]
1
2022-03-23T04:00:42.000Z
2022-03-23T04:00:42.000Z
WickedEngine/wiTransform.cpp
Svengali/WickedEngine
6f56672476993ea95039db003b6dcf39231855db
[ "Zlib", "MIT" ]
null
null
null
WickedEngine/wiTransform.cpp
Svengali/WickedEngine
6f56672476993ea95039db003b6dcf39231855db
[ "Zlib", "MIT" ]
null
null
null
#include "wiTransform.h" #include "wiArchive.h" #include "wiMath.h" #include <vector> namespace wiSceneComponents { std::atomic<uint64_t> Node::__Unique_ID_Counter = 0; Node::Node() { name = ""; ID = __Unique_ID_Counter.fetch_add(1); } void Node::Serialize(wiArchive& archive) { if (archive.IsReadMode()) { archive >> name; } else { archive << name; } } Transform::Transform() :Node() { parent = nullptr; parentName = ""; boneParent = ""; ClearTransform(); } Transform::~Transform() { detach(); detachChild(); } XMMATRIX Transform::getMatrix(int getTranslation, int getRotation, int getScale) { return XMLoadFloat4x4(&world); } //attach to parent void Transform::attachTo(Transform* newParent, int copyTranslation, int copyRotation, int copyScale) { if (newParent != nullptr) { if (parent != nullptr) { detach(); } parent = newParent; parentName = newParent->name; copyParentT = copyTranslation; copyParentR = copyRotation; copyParentS = copyScale; XMStoreFloat4x4(&parent_inv_rest, XMMatrixInverse(nullptr, parent->getMatrix(copyParentT, copyParentR, copyParentS))); parent->children.insert(this); } } Transform* Transform::find(const std::string& findname) { if (!name.compare(findname)) { return this; } for (Transform* x : children) { if (x != nullptr) { Transform* found = x->find(findname); if (found != nullptr) { return found; } } } return nullptr; } Transform* Transform::find(uint64_t id) { if (GetID()==id) { return this; } for (Transform* x : children) { if (x != nullptr) { Transform* found = x->find(id); if (found != nullptr) { return found; } } } return nullptr; } //detach child - detach all if no parameters void Transform::detachChild(Transform* child) { if (child == nullptr) { if (children.empty()) { return; } std::vector<Transform*> delChildren(children.begin(), children.end()); for (Transform* c : delChildren) { if (c != nullptr) { c->detach(); } } children.clear(); } else { if (children.find(child) != children.end()) { child->detach(); } } } //detach from parent void Transform::detach() { if (parent != nullptr) { if (parent->children.find(this) != parent->children.end()) { parent->children.erase(this); } applyTransform(copyParentT, copyParentR, copyParentS); } parent = nullptr; } void Transform::applyTransform(int t, int r, int s) { if (t) translation_rest = translation; if (r) rotation_rest = rotation; if (s) scale_rest = scale; } void Transform::transform(const XMFLOAT3& t, const XMFLOAT4& r, const XMFLOAT3& s) { hasChanged = true; translation_rest.x += t.x; translation_rest.y += t.y; translation_rest.z += t.z; XMStoreFloat4(&rotation_rest, XMQuaternionNormalize(XMQuaternionMultiply(XMLoadFloat4(&rotation_rest), XMLoadFloat4(&r)))); scale_rest.x *= s.x; scale_rest.y *= s.y; scale_rest.z *= s.z; UpdateTransform(); } void Transform::transform(const XMMATRIX& m) { XMVECTOR v[3]; if (XMMatrixDecompose(&v[0], &v[1], &v[2], m)) { XMFLOAT3 t, s; XMFLOAT4 r; XMStoreFloat3(&s, v[0]); XMStoreFloat4(&r, v[1]); XMStoreFloat3(&t, v[2]); transform(t, r, s); } } void Transform::UpdateTransform() { worldPrev = world; translationPrev = translation; scalePrev = scale; rotationPrev = rotation; XMVECTOR s = XMLoadFloat3(&scale_rest); XMVECTOR r = XMLoadFloat4(&rotation_rest); XMVECTOR t = XMLoadFloat3(&translation_rest); XMMATRIX w = XMMatrixScalingFromVector(s)* XMMatrixRotationQuaternion(r)* XMMatrixTranslationFromVector(t) ; XMStoreFloat4x4(&world_rest, w); if (parent != nullptr) { w = w * XMLoadFloat4x4(&parent_inv_rest) * parent->getMatrix(); XMVECTOR v[3]; XMMatrixDecompose(&v[0], &v[1], &v[2], w); XMStoreFloat3(&scale, v[0]); XMStoreFloat4(&rotation, v[1]); XMStoreFloat3(&translation, v[2]); XMStoreFloat4x4(&world, w); hasChanged = hasChanged || parent->hasChanged; } else { world = world_rest; translation = translation_rest; rotation = rotation_rest; scale = scale_rest; } for (Transform* child : children) { child->UpdateTransform(); } } void Transform::Translate(const XMFLOAT3& value) { transform(value); } void Transform::RotateRollPitchYaw(const XMFLOAT3& value) { hasChanged = true; // This needs to be handled a bit differently XMVECTOR quat = XMLoadFloat4(&rotation_rest); XMVECTOR x = XMQuaternionRotationRollPitchYaw(value.x, 0, 0); XMVECTOR y = XMQuaternionRotationRollPitchYaw(0, value.y, 0); XMVECTOR z = XMQuaternionRotationRollPitchYaw(0, 0, value.z); quat = XMQuaternionMultiply(x, quat); quat = XMQuaternionMultiply(quat, y); quat = XMQuaternionMultiply(z, quat); quat = XMQuaternionNormalize(quat); XMStoreFloat4(&rotation_rest, quat); UpdateTransform(); } void Transform::Rotate(const XMFLOAT4& quaternion) { transform(XMFLOAT3(0, 0, 0), quaternion); } void Transform::Scale(const XMFLOAT3& value) { transform(XMFLOAT3(0, 0, 0), XMFLOAT4(0, 0, 0, 1), value); } void Transform::Lerp(const Transform* a, const Transform* b, float t) { hasChanged = true; translation_rest = wiMath::Lerp(a->translation, b->translation, t); rotation_rest = wiMath::Slerp(a->rotation, b->rotation, t); scale_rest = wiMath::Lerp(a->scale, b->scale, t); UpdateTransform(); } void Transform::CatmullRom(const Transform* a, const Transform* b, const Transform* c, const Transform* d, float t) { hasChanged = true; XMVECTOR T = XMVectorCatmullRom( XMLoadFloat3(&a->translation), XMLoadFloat3(&b->translation), XMLoadFloat3(&c->translation), XMLoadFloat3(&d->translation), t ); //XMVECTOR qA = XMQuaternionNormalize(XMLoadFloat4(&a->rotation)); //XMVECTOR qB = XMQuaternionNormalize(XMLoadFloat4(&b->rotation)); //XMVECTOR qC = XMQuaternionNormalize(XMLoadFloat4(&c->rotation)); //XMVECTOR qD = XMQuaternionNormalize(XMLoadFloat4(&d->rotation)); //XMQuaternionSquadSetup(&qB, &qC, &qD, qA, qB, qC, qD); //XMVECTOR diff_ab = XMQuaternionMultiply(XMQuaternionInverse(qA), qB); // rot from a to b //diff_ab = XMQuaternionNormalize(XMVectorMultiply(diff_ab, XMVectorSet(1, 1, 1, 0.33333f))); // div angle by 3 and normalize //XMVECTOR modified_a = XMQuaternionNormalize(XMQuaternionMultiply(qB, diff_ab)); // rot b by diff_ab and normalize //XMVECTOR diff_dc = XMQuaternionMultiply(XMQuaternionInverse(qD), qC); // rot from d to c //diff_dc = XMQuaternionNormalize(XMVectorMultiply(diff_dc, XMVectorSet(1, 1, 1, 0.33333f))); // div angle by 3 and normalize //XMVECTOR modified_d = XMQuaternionNormalize(XMQuaternionMultiply(qC, diff_dc)); // rot c by diff_dc and normalize //XMVECTOR R = XMQuaternionSquad(qB, modified_a, modified_d, qC, t); //XMVECTOR Q1, Q2, Q3; //XMQuaternionSquadSetup( // &Q1, &Q2, &Q3, // XMLoadFloat4(&a->rotation), // XMLoadFloat4(&b->rotation), // XMLoadFloat4(&c->rotation), // XMLoadFloat4(&d->rotation) //); //float squadT = t * 0.3333f + 0.3333f; //XMVECTOR R = XMQuaternionSquad( // XMQuaternionNormalize(XMLoadFloat4(&a->rotation)), // XMQuaternionNormalize(Q1), // XMQuaternionNormalize(Q2), // XMQuaternionNormalize(Q3), // squadT //); //XMVECTOR R = XMQuaternionSquad( // XMQuaternionNormalize(XMLoadFloat4(&b->rotation)), // XMQuaternionNormalize(XMLoadFloat4(&a->rotation)), // XMQuaternionNormalize(XMLoadFloat4(&d->rotation)), // XMQuaternionNormalize(XMLoadFloat4(&c->rotation)), // t //); // Catmull-rom has issues with full rotation for quaternions: XMVECTOR R = XMVectorCatmullRom( XMLoadFloat4(&a->rotation), XMLoadFloat4(&b->rotation), XMLoadFloat4(&c->rotation), XMLoadFloat4(&d->rotation), t ); //// Simple blend that is not smooth on control point change: //XMVECTOR R = XMQuaternionSlerp( // XMLoadFloat4(&b->rotation), // XMLoadFloat4(&c->rotation), // t //); R = XMQuaternionNormalize(R); XMVECTOR S = XMVectorCatmullRom( XMLoadFloat3(&a->scale), XMLoadFloat3(&b->scale), XMLoadFloat3(&c->scale), XMLoadFloat3(&d->scale), t ); XMStoreFloat3(&translation_rest, T); XMStoreFloat4(&rotation_rest, R); XMStoreFloat3(&scale_rest, S); UpdateTransform(); } Transform* Transform::GetRoot() { if (parent != nullptr) { return parent->GetRoot(); } return this; } uint32_t Transform::GetLayerMask() const { if (parent != nullptr) { return parent->GetLayerMask() & Node::GetLayerMask(); } return Node::GetLayerMask(); } void Transform::Serialize(wiArchive& archive) { Node::Serialize(archive); if (archive.IsReadMode()) { archive >> parentName; archive >> translation_rest; archive >> rotation_rest; archive >> scale_rest; archive >> world_rest; archive >> boneParent; archive >> parent_inv_rest; archive >> copyParentT; archive >> copyParentR; archive >> copyParentS; UpdateTransform(); } else { archive << parentName; archive << translation_rest; archive << rotation_rest; archive << scale_rest; archive << world_rest; archive << boneParent; archive << parent_inv_rest; archive << copyParentT; archive << copyParentR; archive << copyParentS; } } }
23.344473
126
0.694527
[ "vector", "transform" ]
33d66c7c416fd9170607a46d0ffbcc1b55fcbb3b
16,723
cpp
C++
src/hash.cpp
fujita-y/digamma
6cb8fe1e01c662db346f61b5ea61ada72454fa3e
[ "BSD-2-Clause" ]
31
2020-01-03T23:02:49.000Z
2022-01-31T00:58:15.000Z
src/hash.cpp
fujita-y/digamma
6cb8fe1e01c662db346f61b5ea61ada72454fa3e
[ "BSD-2-Clause" ]
null
null
null
src/hash.cpp
fujita-y/digamma
6cb8fe1e01c662db346f61b5ea61ada72454fa3e
[ "BSD-2-Clause" ]
3
2020-01-03T23:02:57.000Z
2020-09-07T00:22:29.000Z
// Copyright (c) 2004-2022 Yoshikatsu Fujita / LittleWing Company Limited. // See LICENSE file for terms and conditions of use. #include "core.h" #include "hash.h" #include "utf8.h" #include "arith.h" #include "equiv.h" #define EQUAL_HASH_DEPTH_LIMIT 100 uint32_t address_hash1(void *adrs, uint32_t bound) { return (((uintptr_t)adrs >> 3) * 2654435761U + ((uintptr_t)adrs & 7)) % bound; } uint32_t address_hash2(void *adrs, uint32_t bound) { uint32_t hash = (((uintptr_t)adrs >> 3) * 13845163U) % bound; return hash + (hash == 0); } uint32_t string_hash1(const char *str, uint32_t bound) { int hash = 107; while (*str) hash = hash * 32 - hash + (*str++); return hash % bound; } uint32_t string_hash2(const char *str, uint32_t bound) { int hash = 131; while (*str) hash = hash * 4 + hash + (*str++); hash = hash % bound; return hash + (hash == 0); } static uint32_t eqv_hash1(scm_obj_t obj, uint32_t bound) { if (CELLP(obj)) { if (FLONUMP(obj)) { scm_flonum_t flonum = (scm_flonum_t)obj; assert(sizeof(flonum->value) == 8); uint32_t* datum = (uint32_t*)(&flonum->value); return (datum[0] + datum[1] * 5) % bound; } if (BIGNUMP(obj)) { scm_bignum_t bignum = (scm_bignum_t)obj; int count = bn_get_count(bignum); uint32_t hash = bn_get_sign(bignum) + count * 5; if (sizeof(digit_t) == sizeof(uint32_t)) { for (int i = 0; i < count; i++) hash = hash * 5 + bignum->elts[i]; } else { for (int i = 0; i < count; i++) { hash = hash * 5 + (bignum->elts[i] & 0xffffffff) + ((uint64_t)bignum->elts[i] >> 32); } } return hash % bound; } if (RATIONALP(obj)) { scm_rational_t rational = (scm_rational_t)obj; uint32_t hash; hash = eqv_hash(rational->nume, INT32_MAX) * 5 - eqv_hash(rational->deno, INT32_MAX); return hash % bound; } if (COMPLEXP(obj)) { scm_complex_t complex = (scm_complex_t)obj; uint32_t hash; hash = eqv_hash(complex->real, INT32_MAX) * 5 + eqv_hash(complex->imag, INT32_MAX); return hash % bound; } } return address_hash1(obj, bound); } static uint32_t eqv_hash2(scm_obj_t obj, uint32_t bound) { if (CELLP(obj)) { if (FLONUMP(obj)) { scm_flonum_t flonum = (scm_flonum_t)obj; assert(sizeof(flonum->value) == 8); uint32_t* datum = (uint32_t*)(&flonum->value); uint32_t hash = (datum[0] + datum[1] * 3) % bound; return hash + (hash == 0); } if (BIGNUMP(obj)) { scm_bignum_t bignum = (scm_bignum_t)obj; int count = bn_get_count(bignum); uint32_t hash = bn_get_sign(bignum) + count * 3; if (sizeof(digit_t) == sizeof(uint32_t)) { for (int i = 0; i < count; i++) hash = hash * 3 + bignum->elts[i]; } else { for (int i = 0; i < count; i++) { hash = hash * 3 + (bignum->elts[i] & 0xffffffff) + ((uint64_t)bignum->elts[i] >> 32); } } hash = hash % bound; return hash + (hash == 0); } if (RATIONALP(obj)) { scm_rational_t rational = (scm_rational_t)obj; uint32_t hash = eqv_hash2(rational->nume, INT32_MAX) * 3 - eqv_hash2(rational->deno, INT32_MAX); hash = hash % bound; return hash + (hash == 0); } if (COMPLEXP(obj)) { scm_complex_t complex = (scm_complex_t)obj; uint32_t hash = eqv_hash2(complex->real, INT32_MAX) * 3 + eqv_hash2(complex->imag, INT32_MAX); hash = hash % bound; return hash + (hash == 0); } } return address_hash2(obj, bound); } static uint32_t obj_hash(scm_obj_t obj, int depth) { if (depth > EQUAL_HASH_DEPTH_LIMIT) return 1; if (CELLP(obj)) { if (PAIRP(obj)) { uint32_t hash1 = obj_hash(CAR(obj), depth + 1); uint32_t hash2 = obj_hash(CDR(obj), depth + 1); return (hash1 + hash2 * 64 - hash2); } if (VECTORP(obj)) { scm_vector_t vector = (scm_vector_t)obj; int n = vector->count; scm_obj_t* elts = vector->elts; uint32_t hash = 1; for (int i = 0; i < n; i++) { hash = hash * 32 - hash + obj_hash(elts[i], depth + 1); } return hash; } if (SYMBOLP(obj)) return symbol_hash((scm_symbol_t)obj, INT32_MAX); if (STRINGP(obj)) return string_hash((scm_string_t)obj, INT32_MAX); if (number_pred(obj)) return eqv_hash(obj, INT32_MAX); return HDR_TC(HDR(obj)); } return address_hash1(obj, INT32_MAX); } uint32_t eqv_hash(scm_obj_t obj, uint32_t bound) { return eqv_hash1(obj, bound); } uint32_t equal_hash(scm_obj_t obj, uint32_t bound) { return obj_hash(obj, 0) % bound; } uint32_t string_hash(scm_obj_t obj, uint32_t bound) { assert(STRINGP(obj)); scm_string_t string = (scm_string_t)obj; return string_hash1(string->name, bound); } uint32_t symbol_hash(scm_obj_t obj, uint32_t bound) { assert(SYMBOLP(obj)); scm_symbol_t symbol = (scm_symbol_t)obj; return string_hash2(symbol->name, bound); } bool eqv_hash_equiv(scm_obj_t obj1, scm_obj_t obj2) { return eqv_pred(obj1, obj2); } bool equal_hash_equiv(scm_obj_t obj1, scm_obj_t obj2) { return r5rs_equal_pred(obj1, obj2); } bool string_hash_equiv(scm_obj_t obj1, scm_obj_t obj2) { return string_eq_pred(obj1, obj2); } int lookup_mutable_hashtable_size(int n) { static const int primes[] = { 7, 13, 29, 59, 113, 223, 431, 821, 1567, 2999, 5701, 10837, 20593, 39133, 74353, 141277, 268439, 510047, 969097, 1841291, 3498457, 5247701, 7871573, 11807381, 17711087, 26566649, 39849977, 59774983, 89662483, 134493731, 201740597, 302610937, 453916423, 680874641, 1021311983, 1531968019, 2147483647 }; for (int i = 0; i < array_sizeof(primes); i++) { if (primes[i] > n) return primes[i]; } fatal("%s:%u internal error: hashtable too big",__FILE__ , __LINE__); } int lookup_immutable_hashtable_size(int n) { static const int primes[] = { 7, 11, 13, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 157, 191, 229, 277, 337, 409, 491, 593, 719, 863, 1039, 1249, 1499, 1801, 2161, 2593, 3119, 3761, 4513, 5417, 6521, 7829, 9397, 11279, 13537, 16249, 19501, 23417, 28109, 33739, 40487, 48589, 58309, 69991, 84011, 100823, 120997, 145207, 174257, 209123, 250949, 301141, 361373, 433651, 520381, 624467, 749383, 899263, 1079123, 1294957, 1553971, 1864769, 2237743, 2685301, 3222379, 3866857, 4640231, 5568287, 6681947, 8018347, 9622021, 11546449, 13855747, 16626941, 19952329, 23942797, 28731359, 34477637, 41373173, 49647809, 59577379, 71492873, 85791451, 102949741, 123539747, 148247713, 177897311, 213476789, 256172149, 307406587, 368887919, 442665511, 531198691, 637438433, 764926171, 917911471, 1101493807, 1321792573, 1586151131, 1903381357, 2147483647 }; for (int i = 0; i < array_sizeof(primes); i++) { if (primes[i] > n) return primes[i]; } fatal("%s:%u internal error: hashtable too big",__FILE__ , __LINE__); } static int put_eq_hashtable(scm_hashtable_t ht, scm_obj_t key, scm_obj_t value) { ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == scm_hash_free) { ht_datum->live++; ht_datum->used++; goto found; } if (tag == scm_hash_deleted) { ht_datum->live++; goto found; } if (tag == key) goto found; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); found: ht_datum->elts[index] = key; ht_datum->elts[index + nsize] = value; if (ht_datum->used < HASH_BUSY_THRESHOLD(nsize)) return 0; if (ht_datum->live < HASH_DENSE_THRESHOLD(nsize)) return nsize; return lookup_mutable_hashtable_size(nsize); } static scm_obj_t get_eq_hashtable(scm_hashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key) return ht_datum->elts[index + nsize]; if (tag == scm_hash_free) return scm_undef; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } static int remove_eq_hashtable(scm_hashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->elts[index + nsize] = scm_unspecified; ht_datum->live--; return ht_datum->live < HASH_SPARSE_THRESHOLD(nsize) ? lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)) : 0; // set size 175% of live } if (tag == scm_hash_free) return 0; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } scm_obj_t lookup_weakhashtable(scm_weakhashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); weakhashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t entry = ht_datum->elts[index]; if (entry == scm_hash_free) return scm_undef; if (entry != scm_hash_deleted) { assert(WEAKMAPPINGP(entry)); scm_weakmapping_t wmap = (scm_weakmapping_t)entry; if (wmap->key == scm_false) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->live--; } else { if (wmap->key == key) return wmap; } } index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } int remove_weakhashtable(scm_weakhashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); weakhashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t entry = ht_datum->elts[index]; if (entry == scm_hash_free) return 0; if (entry != scm_hash_deleted) { assert(WEAKMAPPINGP(entry)); scm_weakmapping_t wmap = (scm_weakmapping_t)entry; if (wmap->key == scm_false) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->live--; } else if (wmap->key == key) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->live--; return ht_datum->live < HASH_SPARSE_THRESHOLD(nsize) ? lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)) : 0; // set size 175% of live } } index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } int put_weakhashtable(scm_weakhashtable_t ht, scm_weakmapping_t wmap) { ht->lock.verify_locked(); scm_obj_t key = wmap->key; weakhashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t entry = ht_datum->elts[index]; if (entry == scm_hash_free) { ht_datum->live++; ht_datum->used++; goto found; } if (entry == scm_hash_deleted) { ht_datum->live++; goto found; } assert(WEAKMAPPINGP(entry)); assert(((scm_weakmapping_t)entry)->key != key); // use lookup_weakhashtable() before put_weakhashtable() index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); found: ht_datum->elts[index] = wmap; if (ht_datum->used < HASH_BUSY_THRESHOLD(nsize)) return 0; if (ht_datum->live < HASH_SPARSE_THRESHOLD(nsize)) return lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)); if (ht_datum->live < HASH_DENSE_THRESHOLD(nsize)) return nsize; return lookup_mutable_hashtable_size(nsize); } static uint32_t simple_hash2(uint32_t hash, int nsize) { int dist = nsize >> 6; dist = (dist < 8) ? ((nsize > 8) ? 8 : 1) : dist; int hash2 = dist - (hash % dist); assert(hash2 && hash2 < nsize); return hash2; } int put_hashtable(scm_hashtable_t ht, scm_obj_t key, scm_obj_t value) { if (ht->type == SCM_HASHTABLE_TYPE_EQ) return put_eq_hashtable(ht, key, value); ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = (*ht->hash)(key, nsize); int hash2 = simple_hash2(hash1, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == scm_hash_free) { ht_datum->live++; ht_datum->used++; goto found; } if (tag == scm_hash_deleted) { ht_datum->live++; goto found; } if (tag == key || (*ht->equiv)(tag, key)) goto found; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); found: ht_datum->elts[index] = key; ht_datum->elts[index + nsize] = value; if (ht_datum->used < HASH_BUSY_THRESHOLD(nsize)) return 0; if (ht_datum->live < HASH_DENSE_THRESHOLD(nsize)) return nsize; return lookup_mutable_hashtable_size(nsize); } scm_obj_t get_hashtable(scm_hashtable_t ht, scm_obj_t key) { if (ht->type == SCM_HASHTABLE_TYPE_EQ) return get_eq_hashtable(ht, key); ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = (*ht->hash)(key, nsize); int hash2 = simple_hash2(hash1, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key || (*ht->equiv)(tag, key)) return ht_datum->elts[index + nsize]; if (tag == scm_hash_free) return scm_undef; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } int remove_hashtable(scm_hashtable_t ht, scm_obj_t key) { if (ht->type == SCM_HASHTABLE_TYPE_EQ) return remove_eq_hashtable(ht, key); ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = (*ht->hash)(key, nsize); int hash2 = simple_hash2(hash1, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key || (*ht->equiv)(tag, key)) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->elts[index + nsize] = scm_unspecified; ht_datum->live--; return ht_datum->live < HASH_SPARSE_THRESHOLD(nsize) ? lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)) : 0; } if (tag == scm_hash_free) return 0; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); }
33.580321
127
0.593255
[ "vector" ]
33d75e27365c31111ad5c806417ae01b9ee8fb0b
10,463
cpp
C++
src/caffe/layer_factory.cpp
Sinnaj94/caffe
5e64d35994c750f45ba9086d43e859c4bb543fa2
[ "Intel", "BSD-2-Clause" ]
null
null
null
src/caffe/layer_factory.cpp
Sinnaj94/caffe
5e64d35994c750f45ba9086d43e859c4bb543fa2
[ "Intel", "BSD-2-Clause" ]
null
null
null
src/caffe/layer_factory.cpp
Sinnaj94/caffe
5e64d35994c750f45ba9086d43e859c4bb543fa2
[ "Intel", "BSD-2-Clause" ]
null
null
null
// Make sure we include Python.h before any system header // to avoid _POSIX_C_SOURCE redefinition #ifdef WITH_PYTHON_LAYER #include <boost/python.hpp> #endif #include <string> #include "caffe/layer.hpp" #include "caffe/layer_factory.hpp" //#include "caffe/layers/clip_layer.hpp" #include "caffe/layers/conv_layer.hpp" #include "caffe/layers/deconv_layer.hpp" #include "caffe/layers/lrn_layer.hpp" #include "caffe/layers/pooling_layer.hpp" #include "caffe/layers/relu_layer.hpp" #include "caffe/layers/sigmoid_layer.hpp" #include "caffe/layers/softmax_layer.hpp" #include "caffe/layers/tanh_layer.hpp" #include "caffe/proto/caffe.pb.h" #ifdef USE_CUDNN #include "caffe/layers/cudnn_conv_layer.hpp" #include "caffe/layers/cudnn_deconv_layer.hpp" #include "caffe/layers/cudnn_lcn_layer.hpp" #include "caffe/layers/cudnn_lrn_layer.hpp" #include "caffe/layers/cudnn_pooling_layer.hpp" #include "caffe/layers/cudnn_relu_layer.hpp" #include "caffe/layers/cudnn_sigmoid_layer.hpp" #include "caffe/layers/cudnn_softmax_layer.hpp" #include "caffe/layers/cudnn_tanh_layer.hpp" #endif #ifdef WITH_PYTHON_LAYER #include "caffe/layers/python_layer.hpp" #endif namespace caffe { // Get convolution layer according to engine. template <typename Dtype> shared_ptr<Layer<Dtype> > GetConvolutionLayer( const LayerParameter& param) { ConvolutionParameter conv_param = param.convolution_param(); ConvolutionParameter_Engine engine = conv_param.engine(); #ifdef USE_CUDNN bool use_dilation = false; for (int i = 0; i < conv_param.dilation_size(); ++i) { if (conv_param.dilation(i) > 1) { use_dilation = true; } } #endif if (engine == ConvolutionParameter_Engine_DEFAULT) { engine = ConvolutionParameter_Engine_CAFFE; #ifdef USE_CUDNN if (!use_dilation) { engine = ConvolutionParameter_Engine_CUDNN; } #endif } if (engine == ConvolutionParameter_Engine_CAFFE) { return shared_ptr<Layer<Dtype> >(new ConvolutionLayer<Dtype>(param)); #ifdef USE_CUDNN } else if (engine == ConvolutionParameter_Engine_CUDNN) { if (use_dilation) { LOG(FATAL) << "CuDNN doesn't support the dilated convolution at Layer " << param.name(); } return shared_ptr<Layer<Dtype> >(new CuDNNConvolutionLayer<Dtype>(param)); #endif } else { LOG(FATAL) << "Layer " << param.name() << " has unknown engine."; throw; // Avoids missing return warning } } REGISTER_LAYER_CREATOR(Convolution, GetConvolutionLayer); // Get deconvolution layer according to engine. template <typename Dtype> shared_ptr<Layer<Dtype> > GetDeconvolutionLayer(const LayerParameter& param) { ConvolutionParameter conv_param = param.convolution_param(); ConvolutionParameter_Engine engine = conv_param.engine(); #ifdef USE_CUDNN bool use_dilation = false; for (int i = 0; i < conv_param.dilation_size(); ++i) { if (conv_param.dilation(i) > 1) { use_dilation = true; } } #endif if (engine == ConvolutionParameter_Engine_DEFAULT) { engine = ConvolutionParameter_Engine_CAFFE; #ifdef USE_CUDNN if (!use_dilation) { engine = ConvolutionParameter_Engine_CUDNN; } #endif } if (engine == ConvolutionParameter_Engine_CAFFE) { return shared_ptr<Layer<Dtype> >(new DeconvolutionLayer<Dtype>(param)); #ifdef USE_CUDNN } else if (engine == ConvolutionParameter_Engine_CUDNN) { if (use_dilation) { LOG(FATAL) << "CuDNN doesn't support the dilated deconvolution at Layer " << param.name(); } return shared_ptr<Layer<Dtype> >(new CuDNNDeconvolutionLayer<Dtype>(param)); #endif } else { LOG(FATAL) << "Layer " << param.name() << " has unknown engine."; throw; // Avoids missing return warning } } REGISTER_LAYER_CREATOR(Deconvolution, GetDeconvolutionLayer); // Get pooling layer according to engine. template <typename Dtype> shared_ptr<Layer<Dtype> > GetPoolingLayer(const LayerParameter& param) { PoolingParameter_Engine engine = param.pooling_param().engine(); if (engine == PoolingParameter_Engine_DEFAULT) { engine = PoolingParameter_Engine_CAFFE; #ifdef USE_CUDNN engine = PoolingParameter_Engine_CUDNN; #endif } if (engine == PoolingParameter_Engine_CAFFE) { return shared_ptr<Layer<Dtype> >(new PoolingLayer<Dtype>(param)); #ifdef USE_CUDNN } else if (engine == PoolingParameter_Engine_CUDNN) { if (param.top_size() > 1) { LOG(INFO) << "cuDNN does not support multiple tops. " << "Using Caffe's own pooling layer."; return shared_ptr<Layer<Dtype> >(new PoolingLayer<Dtype>(param)); } // CuDNN assumes layers are not being modified in place, thus // breaking our index tracking for updates in some cases in Caffe. // Until there is a workaround in Caffe (index management) or // cuDNN, use Caffe layer to max pooling, or don't use in place // layers after max pooling layers if (param.pooling_param().pool() == PoolingParameter_PoolMethod_MAX) { return shared_ptr<Layer<Dtype> >(new PoolingLayer<Dtype>(param)); } else { return shared_ptr<Layer<Dtype> >(new CuDNNPoolingLayer<Dtype>(param)); } #endif } else { LOG(FATAL) << "Layer " << param.name() << " has unknown engine."; throw; // Avoids missing return warning } } REGISTER_LAYER_CREATOR(Pooling, GetPoolingLayer); // Get LRN layer according to engine template <typename Dtype> shared_ptr<Layer<Dtype> > GetLRNLayer(const LayerParameter& param) { LRNParameter_Engine engine = param.lrn_param().engine(); if (engine == LRNParameter_Engine_DEFAULT) { #ifdef USE_CUDNN engine = LRNParameter_Engine_CUDNN; #else engine = LRNParameter_Engine_CAFFE; #endif } if (engine == LRNParameter_Engine_CAFFE) { return shared_ptr<Layer<Dtype> >(new LRNLayer<Dtype>(param)); #ifdef USE_CUDNN } else if (engine == LRNParameter_Engine_CUDNN) { LRNParameter lrn_param = param.lrn_param(); if (lrn_param.norm_region() ==LRNParameter_NormRegion_WITHIN_CHANNEL) { return shared_ptr<Layer<Dtype> >(new CuDNNLCNLayer<Dtype>(param)); } else { // local size is too big to be handled through cuDNN if (param.lrn_param().local_size() > CUDNN_LRN_MAX_N) { return shared_ptr<Layer<Dtype> >(new LRNLayer<Dtype>(param)); } else { return shared_ptr<Layer<Dtype> >(new CuDNNLRNLayer<Dtype>(param)); } } #endif } else { LOG(FATAL) << "Layer " << param.name() << " has unknown engine."; throw; // Avoids missing return warning } } REGISTER_LAYER_CREATOR(LRN, GetLRNLayer); // Get relu layer according to engine. template <typename Dtype> shared_ptr<Layer<Dtype> > GetReLULayer(const LayerParameter& param) { ReLUParameter_Engine engine = param.relu_param().engine(); if (engine == ReLUParameter_Engine_DEFAULT) { engine = ReLUParameter_Engine_CAFFE; #ifdef USE_CUDNN engine = ReLUParameter_Engine_CUDNN; #endif } if (engine == ReLUParameter_Engine_CAFFE) { return shared_ptr<Layer<Dtype> >(new ReLULayer<Dtype>(param)); #ifdef USE_CUDNN } else if (engine == ReLUParameter_Engine_CUDNN) { return shared_ptr<Layer<Dtype> >(new CuDNNReLULayer<Dtype>(param)); #endif } else { LOG(FATAL) << "Layer " << param.name() << " has unknown engine."; throw; // Avoids missing return warning } } REGISTER_LAYER_CREATOR(ReLU, GetReLULayer); // Get sigmoid layer according to engine. template <typename Dtype> shared_ptr<Layer<Dtype> > GetSigmoidLayer(const LayerParameter& param) { SigmoidParameter_Engine engine = param.sigmoid_param().engine(); if (engine == SigmoidParameter_Engine_DEFAULT) { engine = SigmoidParameter_Engine_CAFFE; #ifdef USE_CUDNN engine = SigmoidParameter_Engine_CUDNN; #endif } if (engine == SigmoidParameter_Engine_CAFFE) { return shared_ptr<Layer<Dtype> >(new SigmoidLayer<Dtype>(param)); #ifdef USE_CUDNN } else if (engine == SigmoidParameter_Engine_CUDNN) { return shared_ptr<Layer<Dtype> >(new CuDNNSigmoidLayer<Dtype>(param)); #endif } else { LOG(FATAL) << "Layer " << param.name() << " has unknown engine."; throw; // Avoids missing return warning } } REGISTER_LAYER_CREATOR(Sigmoid, GetSigmoidLayer); // Get softmax layer according to engine. template <typename Dtype> shared_ptr<Layer<Dtype> > GetSoftmaxLayer(const LayerParameter& param) { SoftmaxParameter_Engine engine = param.softmax_param().engine(); if (engine == SoftmaxParameter_Engine_DEFAULT) { engine = SoftmaxParameter_Engine_CAFFE; #ifdef USE_CUDNN engine = SoftmaxParameter_Engine_CUDNN; #endif } if (engine == SoftmaxParameter_Engine_CAFFE) { return shared_ptr<Layer<Dtype> >(new SoftmaxLayer<Dtype>(param)); #ifdef USE_CUDNN } else if (engine == SoftmaxParameter_Engine_CUDNN) { return shared_ptr<Layer<Dtype> >(new CuDNNSoftmaxLayer<Dtype>(param)); #endif } else { LOG(FATAL) << "Layer " << param.name() << " has unknown engine."; throw; // Avoids missing return warning } } REGISTER_LAYER_CREATOR(Softmax, GetSoftmaxLayer); // Get tanh layer according to engine. template <typename Dtype> shared_ptr<Layer<Dtype> > GetTanHLayer(const LayerParameter& param) { TanHParameter_Engine engine = param.tanh_param().engine(); if (engine == TanHParameter_Engine_DEFAULT) { engine = TanHParameter_Engine_CAFFE; #ifdef USE_CUDNN engine = TanHParameter_Engine_CUDNN; #endif } if (engine == TanHParameter_Engine_CAFFE) { return shared_ptr<Layer<Dtype> >(new TanHLayer<Dtype>(param)); #ifdef USE_CUDNN } else if (engine == TanHParameter_Engine_CUDNN) { return shared_ptr<Layer<Dtype> >(new CuDNNTanHLayer<Dtype>(param)); #endif } else { LOG(FATAL) << "Layer " << param.name() << " has unknown engine."; throw; // Avoids missing return warning } } REGISTER_LAYER_CREATOR(TanH, GetTanHLayer); #ifdef WITH_PYTHON_LAYER template <typename Dtype> shared_ptr<Layer<Dtype> > GetPythonLayer(const LayerParameter& param) { Py_Initialize(); try { bp::object module = bp::import(param.python_param().module().c_str()); bp::object layer = module.attr(param.python_param().layer().c_str())(param); return bp::extract<shared_ptr<PythonLayer<Dtype> > >(layer)(); } catch (bp::error_already_set) { PyErr_Print(); throw; } } REGISTER_LAYER_CREATOR(Python, GetPythonLayer); #endif // Layers that use their constructor as their default creator should be // registered in their corresponding cpp files. Do not register them here. } // namespace caffe
33.751613
80
0.722068
[ "object" ]
33da6690e50565fd9908aafa336259a5cb41814e
14,906
cc
C++
src/base/flat_hash_map_benchmark.cc
ztlevi/perfetto
a0de991bf39c5744ab4eef00eae823c378eb99a9
[ "Apache-2.0" ]
3
2022-01-27T23:05:58.000Z
2022-01-28T07:53:34.000Z
src/base/flat_hash_map_benchmark.cc
ztlevi/perfetto
a0de991bf39c5744ab4eef00eae823c378eb99a9
[ "Apache-2.0" ]
null
null
null
src/base/flat_hash_map_benchmark.cc
ztlevi/perfetto
a0de991bf39c5744ab4eef00eae823c378eb99a9
[ "Apache-2.0" ]
2
2022-03-29T02:58:16.000Z
2022-03-29T13:19:34.000Z
// Copyright (C) 2019 The Android Open Source Project // // 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 <functional> #include <random> #include <unordered_map> #include <benchmark/benchmark.h> #include <stdio.h> #include <sys/mman.h> #include <unistd.h> #include "perfetto/base/logging.h" #include "perfetto/ext/base/file_utils.h" #include "perfetto/ext/base/flat_hash_map.h" #include "perfetto/ext/base/hash.h" #include "perfetto/ext/base/scoped_file.h" #include "perfetto/ext/base/string_view.h" // This benchmark allows to compare our FlatHashMap implementation against // reference implementations from Absl (Google), Folly F14 (FB), and Tssil's // reference RobinHood hashmap. // Those libraries are not checked in into the repo. If you want to reproduce // the benchmark you need to: // - Manually install the three libraries using following the instructions in // their readme (they all use cmake). // - When running cmake, remember to pass // -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS='-DNDEBUG -O3 -msse4.2 -mavx'. // That sets cflags for a more fair comparison. // - Set is_debug=false in the GN args. // - Set the GN var perfetto_benchmark_3p_libs_prefix="/usr/local" (or whatever // other directory you set as DESTDIR when running make install). // The presence of the perfetto_benchmark_3p_libs_prefix GN variable will // automatically define PERFETTO_HASH_MAP_COMPARE_THIRD_PARTY_LIBS. #if defined(PERFETTO_HASH_MAP_COMPARE_THIRD_PARTY_LIBS) // Last tested: https://github.com/abseil/abseil-cpp @ f2dbd918d. #include <absl/container/flat_hash_map.h> // Last tested: https://github.com/facebook/folly @ 028a9abae3. #include <folly/container/F14Map.h> // Last tested: https://github.com/Tessil/robin-map @ a603419b9. #include <tsl/robin_map.h> #endif namespace { using namespace perfetto; using benchmark::Counter; using perfetto::base::AlreadyHashed; using perfetto::base::LinearProbe; using perfetto::base::QuadraticHalfProbe; using perfetto::base::QuadraticProbe; // Our FlatHashMap doesn't have a STL-like interface, mainly because we use // columnar-oriented storage, not array-of-tuples, so we can't easily map into // that interface. This wrapper makes our FlatHashMap compatible with STL (just // for what it takes to build this translation unit), at the cost of some small // performance penalty (around 1-2%). template <typename Key, typename Value, typename Hasher, typename Probe> class Ours : public base::FlatHashMap<Key, Value, Hasher, Probe> { public: struct Iterator { using value_type = std::pair<const Key&, Value&>; Iterator(const Key& k, Value& v) : pair_{k, v} {} value_type* operator->() { return &pair_; } value_type& operator*() { return pair_; } bool operator==(const Iterator& other) const { return &pair_.first == &other.pair_.first; } bool operator!=(const Iterator& other) const { return !operator==(other); } value_type pair_; }; void insert(std::pair<Key, Value>&& pair) { this->Insert(std::move(pair.first), std::move(pair.second)); } Iterator find(const Key& key) { const size_t idx = this->FindInternal(key); return Iterator(this->keys_[idx], this->values_[idx]); } Iterator end() { return Iterator(this->keys_[this->kNotFound], this->values_[this->kNotFound]); } }; std::vector<uint64_t> LoadTraceStrings(benchmark::State& state) { std::vector<uint64_t> str_hashes; // This requires that the user has downloaded the file // go/perfetto-benchmark-trace-strings into /tmp/trace_strings. The file is // too big (2.3 GB after uncompression) and it's not worth adding it to the // //test/data. Also it contains data from a team member's phone and cannot // be public. base::ScopedFstream f(fopen("/tmp/trace_strings", "re")); if (!f) { state.SkipWithError( "Test strings missing. Googlers: download " "go/perfetto-benchmark-trace-strings and save into /tmp/trace_strings"); return str_hashes; } char line[4096]; while (fgets(line, sizeof(line), *f)) { base::Hash hasher; hasher.Update(line, strlen(line)); str_hashes.emplace_back(hasher.digest()); } return str_hashes; } bool IsBenchmarkFunctionalOnly() { return getenv("BENCHMARK_FUNCTIONAL_TEST_ONLY") != nullptr; } size_t num_samples() { return IsBenchmarkFunctionalOnly() ? size_t(100) : size_t(10 * 1000 * 1000); } // Uses directly the base::FlatHashMap with no STL wrapper. Configures the map // in append-only mode. void BM_HashMap_InsertTraceStrings_AppendOnly(benchmark::State& state) { std::vector<uint64_t> hashes = LoadTraceStrings(state); for (auto _ : state) { base::FlatHashMap<uint64_t, uint64_t, AlreadyHashed<uint64_t>, LinearProbe, /*AppendOnly=*/true> mapz; for (uint64_t hash : hashes) mapz.Insert(hash, 42); benchmark::ClobberMemory(); state.counters["uniq"] = Counter(static_cast<double>(mapz.size())); } state.counters["tot"] = Counter(static_cast<double>(hashes.size()), Counter::kIsIterationInvariant); state.counters["rate"] = Counter(static_cast<double>(hashes.size()), Counter::kIsIterationInvariantRate); } template <typename MapType> void BM_HashMap_InsertTraceStrings(benchmark::State& state) { std::vector<uint64_t> hashes = LoadTraceStrings(state); for (auto _ : state) { MapType mapz; for (uint64_t hash : hashes) mapz.insert({hash, 42}); benchmark::ClobberMemory(); state.counters["uniq"] = Counter(static_cast<double>(mapz.size())); } state.counters["tot"] = Counter(static_cast<double>(hashes.size()), Counter::kIsIterationInvariant); state.counters["rate"] = Counter(static_cast<double>(hashes.size()), Counter::kIsIterationInvariantRate); } template <typename MapType> void BM_HashMap_TraceTids(benchmark::State& state) { std::vector<std::pair<char, int>> ops_and_tids; { base::ScopedFstream f(fopen("/tmp/tids", "re")); if (!f) { // This test requires a large (800MB) test file. It's not checked into the // repository's //test/data because it would slow down all developers for // a marginal benefit. state.SkipWithError( "Please run `curl -Lo /tmp/tids " "https://storage.googleapis.com/perfetto/test_datalong_trace_tids.txt" "` and try again."); return; } char op; int tid; while (fscanf(*f, "%c %d\n", &op, &tid) == 2) ops_and_tids.emplace_back(op, tid); } for (auto _ : state) { MapType mapz; for (const auto& ops_and_tid : ops_and_tids) { if (ops_and_tid.first == '[') { mapz[ops_and_tid.second]++; } else { mapz.insert({ops_and_tid.second, 0}); } } benchmark::ClobberMemory(); state.counters["uniq"] = Counter(static_cast<double>(mapz.size())); } state.counters["rate"] = Counter(static_cast<double>(ops_and_tids.size()), Counter::kIsIterationInvariantRate); } template <typename MapType> void BM_HashMap_InsertRandInts(benchmark::State& state) { std::minstd_rand0 rng(0); std::vector<size_t> keys(static_cast<size_t>(num_samples())); std::shuffle(keys.begin(), keys.end(), rng); for (auto _ : state) { MapType mapz; for (const auto key : keys) mapz.insert({key, key}); benchmark::DoNotOptimize(mapz); benchmark::ClobberMemory(); } state.counters["insertions"] = Counter(static_cast<double>(keys.size()), Counter::kIsIterationInvariantRate); } // This test is performs insertions on integers that are designed to create // lot of clustering on the same small set of buckets. // This covers the unlucky case of using a map with a poor hashing function. template <typename MapType> void BM_HashMap_InsertCollidingInts(benchmark::State& state) { std::vector<size_t> keys; const size_t kNumSamples = num_samples(); // Generates numbers that are all distinct from each other, but that are // designed to collide on the same buckets. constexpr size_t kShift = 8; // Collide on the same 2^8 = 256 buckets. for (size_t i = 0; i < kNumSamples; i++) { size_t bucket = i & ((1 << kShift) - 1); // [0, 256]. size_t multiplier = i >> kShift; // 0,0,0... 1,1,1..., 2,2,2... size_t key = 8192 * multiplier + bucket; keys.push_back(key); } for (auto _ : state) { MapType mapz; for (const size_t key : keys) mapz.insert({key, key}); benchmark::DoNotOptimize(mapz); benchmark::ClobberMemory(); } state.counters["insertions"] = Counter(static_cast<double>(keys.size()), Counter::kIsIterationInvariantRate); } // Unlike the previous benchmark, here integers don't just collide on the same // buckets, they have a large number of duplicates with the same values. // Most of those insertions are no-ops. This tests the ability of the hashmap // to deal with cases where the hash function is good but the insertions contain // lot of dupes (e.g. dealing with pids). template <typename MapType> void BM_HashMap_InsertDupeInts(benchmark::State& state) { std::vector<size_t> keys; const size_t kNumSamples = num_samples(); for (size_t i = 0; i < kNumSamples; i++) keys.push_back(i % 16384); for (auto _ : state) { MapType mapz; for (const size_t key : keys) mapz.insert({key, key}); benchmark::DoNotOptimize(mapz); benchmark::ClobberMemory(); } state.counters["insertions"] = Counter(static_cast<double>(keys.size()), Counter::kIsIterationInvariantRate); } template <typename MapType> void BM_HashMap_LookupRandInts(benchmark::State& state) { std::minstd_rand0 rng(0); std::vector<size_t> keys(static_cast<size_t>(num_samples())); std::shuffle(keys.begin(), keys.end(), rng); MapType mapz; for (const size_t key : keys) mapz.insert({key, key}); for (auto _ : state) { int64_t total = 0; for (const size_t key : keys) { auto it = mapz.find(static_cast<uint64_t>(key)); PERFETTO_CHECK(it != mapz.end()); total += it->second; } benchmark::DoNotOptimize(total); benchmark::ClobberMemory(); state.counters["sum"] = Counter(static_cast<double>(total)); } state.counters["lookups"] = Counter(static_cast<double>(keys.size()), Counter::kIsIterationInvariantRate); } } // namespace using Ours_LinearProbing = Ours<uint64_t, uint64_t, AlreadyHashed<uint64_t>, LinearProbe>; using Ours_QuadProbing = Ours<uint64_t, uint64_t, AlreadyHashed<uint64_t>, QuadraticProbe>; using Ours_QuadCompProbing = Ours<uint64_t, uint64_t, AlreadyHashed<uint64_t>, QuadraticHalfProbe>; using StdUnorderedMap = std::unordered_map<uint64_t, uint64_t, AlreadyHashed<uint64_t>>; #if defined(PERFETTO_HASH_MAP_COMPARE_THIRD_PARTY_LIBS) using RobinMap = tsl::robin_map<uint64_t, uint64_t, AlreadyHashed<uint64_t>>; using AbslFlatHashMap = absl::flat_hash_map<uint64_t, uint64_t, AlreadyHashed<uint64_t>>; using FollyF14FastMap = folly::F14FastMap<uint64_t, uint64_t, AlreadyHashed<uint64_t>>; #endif BENCHMARK(BM_HashMap_InsertTraceStrings_AppendOnly); BENCHMARK_TEMPLATE(BM_HashMap_InsertTraceStrings, Ours_LinearProbing); BENCHMARK_TEMPLATE(BM_HashMap_InsertTraceStrings, Ours_QuadProbing); BENCHMARK_TEMPLATE(BM_HashMap_InsertTraceStrings, StdUnorderedMap); #if defined(PERFETTO_HASH_MAP_COMPARE_THIRD_PARTY_LIBS) BENCHMARK_TEMPLATE(BM_HashMap_InsertTraceStrings, RobinMap); BENCHMARK_TEMPLATE(BM_HashMap_InsertTraceStrings, AbslFlatHashMap); BENCHMARK_TEMPLATE(BM_HashMap_InsertTraceStrings, FollyF14FastMap); #endif #define TID_ARGS int, uint64_t, std::hash<int> BENCHMARK_TEMPLATE(BM_HashMap_TraceTids, Ours<TID_ARGS, LinearProbe>); BENCHMARK_TEMPLATE(BM_HashMap_TraceTids, Ours<TID_ARGS, QuadraticProbe>); BENCHMARK_TEMPLATE(BM_HashMap_TraceTids, Ours<TID_ARGS, QuadraticHalfProbe>); BENCHMARK_TEMPLATE(BM_HashMap_TraceTids, std::unordered_map<TID_ARGS>); #if defined(PERFETTO_HASH_MAP_COMPARE_THIRD_PARTY_LIBS) BENCHMARK_TEMPLATE(BM_HashMap_TraceTids, tsl::robin_map<TID_ARGS>); BENCHMARK_TEMPLATE(BM_HashMap_TraceTids, absl::flat_hash_map<TID_ARGS>); BENCHMARK_TEMPLATE(BM_HashMap_TraceTids, folly::F14FastMap<TID_ARGS>); #endif BENCHMARK_TEMPLATE(BM_HashMap_InsertRandInts, Ours_LinearProbing); BENCHMARK_TEMPLATE(BM_HashMap_InsertRandInts, Ours_QuadProbing); BENCHMARK_TEMPLATE(BM_HashMap_InsertRandInts, StdUnorderedMap); #if defined(PERFETTO_HASH_MAP_COMPARE_THIRD_PARTY_LIBS) BENCHMARK_TEMPLATE(BM_HashMap_InsertRandInts, RobinMap); BENCHMARK_TEMPLATE(BM_HashMap_InsertRandInts, AbslFlatHashMap); BENCHMARK_TEMPLATE(BM_HashMap_InsertRandInts, FollyF14FastMap); #endif BENCHMARK_TEMPLATE(BM_HashMap_InsertCollidingInts, Ours_LinearProbing); BENCHMARK_TEMPLATE(BM_HashMap_InsertCollidingInts, Ours_QuadProbing); BENCHMARK_TEMPLATE(BM_HashMap_InsertCollidingInts, Ours_QuadCompProbing); BENCHMARK_TEMPLATE(BM_HashMap_InsertCollidingInts, StdUnorderedMap); #if defined(PERFETTO_HASH_MAP_COMPARE_THIRD_PARTY_LIBS) BENCHMARK_TEMPLATE(BM_HashMap_InsertCollidingInts, RobinMap); BENCHMARK_TEMPLATE(BM_HashMap_InsertCollidingInts, AbslFlatHashMap); BENCHMARK_TEMPLATE(BM_HashMap_InsertCollidingInts, FollyF14FastMap); #endif BENCHMARK_TEMPLATE(BM_HashMap_InsertDupeInts, Ours_LinearProbing); BENCHMARK_TEMPLATE(BM_HashMap_InsertDupeInts, Ours_QuadProbing); BENCHMARK_TEMPLATE(BM_HashMap_InsertDupeInts, Ours_QuadCompProbing); BENCHMARK_TEMPLATE(BM_HashMap_InsertDupeInts, StdUnorderedMap); #if defined(PERFETTO_HASH_MAP_COMPARE_THIRD_PARTY_LIBS) BENCHMARK_TEMPLATE(BM_HashMap_InsertDupeInts, RobinMap); BENCHMARK_TEMPLATE(BM_HashMap_InsertDupeInts, AbslFlatHashMap); BENCHMARK_TEMPLATE(BM_HashMap_InsertDupeInts, FollyF14FastMap); #endif BENCHMARK_TEMPLATE(BM_HashMap_LookupRandInts, Ours_LinearProbing); BENCHMARK_TEMPLATE(BM_HashMap_LookupRandInts, Ours_QuadProbing); BENCHMARK_TEMPLATE(BM_HashMap_LookupRandInts, StdUnorderedMap); #if defined(PERFETTO_HASH_MAP_COMPARE_THIRD_PARTY_LIBS) BENCHMARK_TEMPLATE(BM_HashMap_LookupRandInts, RobinMap); BENCHMARK_TEMPLATE(BM_HashMap_LookupRandInts, AbslFlatHashMap); BENCHMARK_TEMPLATE(BM_HashMap_LookupRandInts, FollyF14FastMap); #endif
39.329815
80
0.728767
[ "vector" ]
33df9b6af203ae68dfbe08e7af1d925b227eab57
652
cpp
C++
test/src/box/test_frma.cpp
steinwurf/petro
d06485f0c1748c425d5f30444638883e62aedf62
[ "BSD-3-Clause" ]
3
2017-08-24T14:14:53.000Z
2018-05-14T02:48:16.000Z
test/src/box/test_frma.cpp
steinwurf/petro
d06485f0c1748c425d5f30444638883e62aedf62
[ "BSD-3-Clause" ]
10
2016-06-17T07:10:25.000Z
2021-12-14T13:37:29.000Z
test/src/box/test_frma.cpp
steinwurf/petro
d06485f0c1748c425d5f30444638883e62aedf62
[ "BSD-3-Clause" ]
3
2017-06-12T19:22:27.000Z
2019-01-03T19:18:24.000Z
// Copyright (c) Steinwurf ApS 2016. // All Rights Reserved // // Distributed under the "BSD License". See the accompanying LICENSE.rst file. #include <petro/box/data_box.hpp> #include <petro/box/frma.hpp> #include <gtest/gtest.h> #include <cstdint> #include <memory> #include <system_error> #include <vector> TEST(box_test_frma, construct) { std::vector<uint8_t> buffer = {0x00, 0x00, 0x00, 0x00, 'f', 'r', 'm', 'a'}; auto frma_box = std::make_shared<petro::box::frma>(buffer.data(), buffer.size()); std::error_code error; frma_box->parse(error); ASSERT_FALSE(bool(error)); EXPECT_EQ("frma", frma_box->type()); }
23.285714
79
0.670245
[ "vector" ]
33e15537429f7e66f2ef8c3ef934c4d163c5cb9e
16,817
hpp
C++
include/rmi/rmi.hpp
alhuan/analysis-rmi
be787ee9a02e04210d41af51c8a053f6dea575e9
[ "Apache-2.0" ]
null
null
null
include/rmi/rmi.hpp
alhuan/analysis-rmi
be787ee9a02e04210d41af51c8a053f6dea575e9
[ "Apache-2.0" ]
null
null
null
include/rmi/rmi.hpp
alhuan/analysis-rmi
be787ee9a02e04210d41af51c8a053f6dea575e9
[ "Apache-2.0" ]
null
null
null
#pragma once #include <algorithm> #include <vector> namespace rmi { /** * Struct to hold the approximated position and error bounds returned by the index. */ struct Approx { std::size_t pos; ///< The estimated position of the key. std::size_t lo; ///< The lower bound of the search range. std::size_t hi; ///< The upper bound of the search range. }; /** * This is a reimplementation of a two-layer recursive model index (RMI) supporting a variety of (monotonic) models. * RMIs were invented by Kraska et al. (https://dl.acm.org/doi/epdf/10.1145/3183713.3196909). * * Note that this is the base class which does not provide error bounds. * * @tparam Key the type of the keys to be indexed * @tparam Layer1 the type of the model used in layer1 * @tparam Layer2 the type of the models used in layer2 */ template<typename Key, typename Layer1, typename Layer2> class Rmi { using key_type = Key; using layer1_type = Layer1; using layer2_type = Layer2; protected: std::size_t n_keys_; ///< The number of keys the index was built on. std::size_t layer2_size_; ///< The number of models in layer2. layer1_type l1_; ///< The layer1 model. layer2_type *l2_; ///< The array of layer2 models. public: /** * Default constructor. */ Rmi() = default; /** * Builds the index with @p layer2_size models in layer2 on the sorted @p keys. * @param keys vector of sorted keys to be indexed * @param layer2_size the number of models in layer2 */ Rmi(const std::vector<key_type> &keys, const std::size_t layer2_size) : Rmi(keys.begin(), keys.end(), layer2_size) { } /** * Builds the index with @p layer2_size models in layer2 on the sorted keys in the range [first, last). * @param first, last iterators that define the range of sorted keys to be indexed * @param layer2_size the number of models in layer2 */ template<typename RandomIt> Rmi(RandomIt first, RandomIt last, const std::size_t layer2_size) : n_keys_(std::distance(first, last)) , layer2_size_(layer2_size) { // Train layer1. l1_ = layer1_type(first, last, 0, static_cast<double>(layer2_size) / n_keys_); // train with compression // Train layer2. l2_ = new layer2_type[layer2_size]; std::size_t segment_start = 0; std::size_t segment_id = 0; // Assign each key to its segment. for (std::size_t i = 0; i != n_keys_; ++i) { auto pos = first + i; std::size_t pred_segment_id = get_segment_id(*pos); // If a key is assigned to a new segment, all models must be trained up to the new segment. if (pred_segment_id > segment_id) { new (&l2_[segment_id]) layer2_type(first + segment_start, pos, segment_start); for (std::size_t j = segment_id + 1; j < pred_segment_id; ++j) { new (&l2_[j]) layer2_type(pos - 1, pos, i - 1); // train other models on last key in previous segment } segment_id = pred_segment_id; segment_start = i; } } // Train remaining models. new (&l2_[segment_id]) layer2_type(first + segment_start, last, segment_start); for (std::size_t j = segment_id + 1; j < layer2_size; ++j) { new (&l2_[j]) layer2_type(last - 1, last, n_keys_ - 1); // train remaining models on last key } } /** * Destructor. */ ~Rmi() { delete[] l2_; } /** * Returns the id of the segment @p key belongs to. * @param key to get segment id for * @return segment id of the given key */ std::size_t get_segment_id(const key_type key) const { return std::clamp<double>(l1_.predict(key), 0, layer2_size_ - 1); } /** * Returns a position estimate and search bounds for a given key. * @param key to search for * @return position estimate and search bounds */ Approx search(const key_type key) const { auto segment_id = get_segment_id(key); std::size_t pred = std::clamp<double>(l2_[segment_id].predict(key), 0, n_keys_ - 1); return {pred, 0, n_keys_}; } /** * Returns the number of keys the index was built on. * @return the number of keys the index was built on */ std::size_t n_keys() const { return n_keys_; } /** * Returns the number of models in layer2. * @return the number of models in layer2 */ std::size_t layer2_size() const { return layer2_size_; } /** * Returns the size of the index in bytes. * @return index size in bytes */ std::size_t size_in_bytes() { return l1_.size_in_bytes() + layer2_size_ * l2_[0].size_in_bytes() + sizeof(n_keys_) + sizeof(layer2_size_); } /** * Returns the maximum error of a layer-2 model */ std::size_t max_error() { return n_keys_; } }; /** * Recursive model index with global absolute bounds. */ template<typename Key, typename Layer1, typename Layer2> class RmiGAbs : public Rmi<Key, Layer1, Layer2> { using base_type = Rmi<Key, Layer1, Layer2>; using key_type = Key; using layer1_type = Layer1; using layer2_type = Layer2; protected: std::size_t error_; ///< The error bound of the layer2 models. public: /** * Default constructor. */ RmiGAbs() = default; /** * Builds the index with @p layer2_size models in layer2 on the sorted @p keys. * @param keys vector of sorted keys to be indexed * @param layer2_size the number of models in layer2 */ RmiGAbs(const std::vector<key_type> &keys, const std::size_t layer2_size) : RmiGAbs(keys.begin(), keys.end(), layer2_size) { } /** * Builds the index with @p layer2_size models in layer2 on the sorted keys in the range [first, last). * @param first, last iterators that define the range of sorted keys to be indexed * @param layer2_size the number of models in layer2 */ template<typename RandomIt> RmiGAbs(RandomIt first, RandomIt last, const std::size_t layer2_size) : base_type(first, last, layer2_size) { // Compute global absolute errror bounds. error_ = 0; for (std::size_t i = 0; i != base_type::n_keys_; ++i) { key_type key = *(first + i); std::size_t segment_id = base_type::get_segment_id(key); std::size_t pred = std::clamp<double>(base_type::l2_[segment_id].predict(key), 0, base_type::n_keys_ - 1); if (pred > i) { // overestimation error_ = std::max(error_, pred - i); } else { // underestimation error_ = std::max(error_, i - pred); } } } /** * Returns a position estimate and search bounds for a given key. * @param key to search for * @return position estimate and search bounds */ Approx search(const key_type key) const { auto segment_id = base_type::get_segment_id(key); std::size_t pred = std::clamp<double>(base_type::l2_[segment_id].predict(key), 0, base_type::n_keys_ - 1); std::size_t lo = pred > error_ ? pred - error_ : 0; std::size_t hi = std::min(pred + error_ + 1, base_type::n_keys_); return {pred, lo, hi}; } /** * Returns the size of the index in bytes. * @return index size in bytes */ std::size_t size_in_bytes() { return base_type::size_in_bytes() + sizeof(error_); } /** * Returns the maximum error of a layer-2 model */ std::size_t max_error() { return error_; } }; /** * Recursive model index with global individual bounds. */ template<typename Key, typename Layer1, typename Layer2> class RmiGInd : public Rmi<Key, Layer1, Layer2> { using base_type = Rmi<Key, Layer1, Layer2>; using key_type = Key; using layer1_type = Layer1; using layer2_type = Layer2; protected: std::size_t error_lo_; ///< The lower error bound of the layer2 models. std::size_t error_hi_; ///< The upper error bound of the layer2 models. public: /** * Default constructor. */ RmiGInd() = default; /** * Builds the index with @p layer2_size models in layer2 on the sorted @p keys. * @param keys vector of sorted keys to be indexed * @param layer2_size the number of models in layer2 */ RmiGInd(const std::vector<key_type> &keys, const std::size_t layer2_size) : RmiGInd(keys.begin(), keys.end(), layer2_size) { } /** * Builds the index with @p layer2_size models in layer2 on the sorted keys in the range [first, last). * @param first, last iterators that define the range of sorted keys to be indexed * @param layer2_size the number of models in layer2 */ template<typename RandomIt> RmiGInd(RandomIt first, RandomIt last, const std::size_t layer2_size) : base_type(first, last, layer2_size) { // Compute global absolute errror bounds. error_lo_ = 0; error_hi_ = 0; for (std::size_t i = 0; i != base_type::n_keys_; ++i) { key_type key = *(first + i); std::size_t segment_id = base_type::get_segment_id(key); std::size_t pred = std::clamp<double>(base_type::l2_[segment_id].predict(key), 0, base_type::n_keys_ - 1); if (pred > i) { // overestimation error_lo_ = std::max(error_lo_, pred - i); } else { // underestimation error_hi_ = std::max(error_hi_, i - pred); } } } /** * Returns a position estimate and search bounds for a given key. * @param key to search for * @return position estimate and search bounds */ Approx search(const key_type key) const { auto segment_id = base_type::get_segment_id(key); std::size_t pred = std::clamp<double>(base_type::l2_[segment_id].predict(key), 0, base_type::n_keys_ - 1); std::size_t lo = pred > error_lo_ ? pred - error_lo_ : 0; std::size_t hi = std::min(pred + error_hi_ + 1, base_type::n_keys_); return {pred, lo, hi}; } /** * Returns the size of the index in bytes. * @return index size in bytes */ std::size_t size_in_bytes() { return base_type::size_in_bytes() + sizeof(error_lo_) + sizeof(error_hi_); } /** * Returns the maximum error of a layer-2 model */ std::size_t max_error() { return std::max(error_lo_, error_hi_); } }; /** * Recursive model index with local absolute bounds. */ template<typename Key, typename Layer1, typename Layer2> class RmiLAbs : public Rmi<Key, Layer1, Layer2> { using base_type = Rmi<Key, Layer1, Layer2>; using key_type = Key; using layer1_type = Layer1; using layer2_type = Layer2; protected: std::vector<std::size_t> errors_; ///< The error bounds of the layer2 models. public: /** * Default constructor. */ RmiLAbs() = default; /** * Builds the index with @p layer2_size models in layer2 on the sorted @p keys. * @param keys vector of sorted keys to be indexed * @param layer2_size the number of models in layer2 */ RmiLAbs(const std::vector<key_type> &keys, const std::size_t layer2_size) : RmiLAbs(keys.begin(), keys.end(), layer2_size) { } /** * Builds the index with @p layer2_size models in layer2 on the sorted keys in the range [first, last). * @param first, last iterators that define the range of sorted keys to be indexed * @param layer2_size the number of models in layer2 */ template<typename RandomIt> RmiLAbs(RandomIt first, RandomIt last, const std::size_t layer2_size) : base_type(first, last, layer2_size) { // Compute local absolute errror bounds. errors_ = std::vector<std::size_t>(layer2_size); for (std::size_t i = 0; i != base_type::n_keys_; ++i) { key_type key = *(first + i); std::size_t segment_id = base_type::get_segment_id(key); std::size_t pred = std::clamp<double>(base_type::l2_[segment_id].predict(key), 0, base_type::n_keys_ - 1); if (pred > i) { // overestimation errors_[segment_id] = std::max(errors_[segment_id], pred - i); } else { // underestimation errors_[segment_id] = std::max(errors_[segment_id], i - pred); } } } /** * Returns a position estimate and search bounds for a given key. * @param key to search for * @return position estimate and search bounds */ Approx search(const key_type key) const { auto segment_id = base_type::get_segment_id(key); std::size_t pred = std::clamp<double>(base_type::l2_[segment_id].predict(key), 0, base_type::n_keys_ - 1); std::size_t err = errors_[segment_id]; std::size_t lo = pred > err ? pred - err : 0; std::size_t hi = std::min(pred + err + 1, base_type::n_keys_); return {pred, lo, hi}; } /** * Returns the size of the index in bytes. * @return index size in bytes */ std::size_t size_in_bytes() { return base_type::size_in_bytes() + errors_.size() * sizeof(errors_.front()); } /** * Returns the maximum error of a layer-2 model */ std::size_t max_error() { return errors_.back(); } }; /** * Recursive model index with local individual bounds. */ template<typename Key, typename Layer1, typename Layer2> class RmiLInd : public Rmi<Key, Layer1, Layer2> { using base_type = Rmi<Key, Layer1, Layer2>; using key_type = Key; using layer1_type = Layer1; using layer2_type = Layer2; protected: /** * Struct to store a lower and an upper error bound. */ struct bounds { std::size_t lo; ///< The lower error bound. std::size_t hi; ///< The upper error bound. /** * Default constructor. */ bounds() : lo(0), hi(0) { } }; std::vector<bounds> errors_; ///< The error bounds of the layer2 models. std::size_t max_error_; public: /** * Default constructor. */ RmiLInd() = default; /** * Builds the index with @p layer2_size models in layer2 on the sorted @p keys. * @param keys vector of sorted keys to be indexed * @param layer2_size the number of models in layer2 */ RmiLInd(const std::vector<key_type> &keys, const std::size_t layer2_size) : RmiLInd(keys.begin(), keys.end(), layer2_size) { } /** * Builds the index with @p layer2_size models in layer2 on the sorted keys in the range [first, last). * @param first, last iterators that define the range of sorted keys to be indexed * @param layer2_size the number of models in layer2 */ template<typename RandomIt> RmiLInd(RandomIt first, RandomIt last, const std::size_t layer2_size) : base_type(first, last, layer2_size) { max_error_ = 0; // Compute local individual errror bounds. errors_ = std::vector<bounds>(layer2_size); for (std::size_t i = 0; i != base_type::n_keys_; ++i) { key_type key = *(first + i); std::size_t segment_id = base_type::get_segment_id(key); std::size_t pred = std::clamp<double>(base_type::l2_[segment_id].predict(key), 0, base_type::n_keys_ - 1); if (pred > i) { // overestimation std::size_t &lo = errors_[segment_id].lo; lo = std::max(lo, pred - i); max_error_ = std::max(lo, max_error_); } else { // underestimation std::size_t &hi = errors_[segment_id].hi; hi = std::max(hi, i - pred); max_error_ = std::max(hi, max_error_); } } } /** * Returns a position estimate and search bounds for a given key. * @param key to search for * @return position estimate and search bounds */ Approx search(const key_type key) const { auto segment_id = base_type::get_segment_id(key); std::size_t pred = std::clamp<double>(base_type::l2_[segment_id].predict(key), 0, base_type::n_keys_ - 1); bounds err = errors_[segment_id]; std::size_t lo = pred > err.lo ? pred - err.lo : 0; std::size_t hi = std::min(pred + err.hi + 1, base_type::n_keys_); return {pred, lo, hi}; } /** * Returns the size of the index in bytes. * @return index size in bytes */ std::size_t size_in_bytes() { return base_type::size_in_bytes() + errors_.size() * sizeof(errors_.front()); } /** * Returns the maximum error of a layer-2 model */ std::size_t max_error() { return max_error_; } }; } // namespace rmi
35.933761
121
0.615032
[ "vector", "model" ]
33e1c6c28512a8e66496c3bd2600a5f8a0d939d7
149,640
cpp
C++
third_party/mlir/lib/Parser/Parser.cpp
ai2ys/tensorflow
0d604056e58d102832c732fbb1d4b9b997c72b8c
[ "Apache-2.0" ]
2
2019-12-07T16:18:05.000Z
2020-02-16T10:39:37.000Z
third_party/mlir/lib/Parser/Parser.cpp
ai2ys/tensorflow
0d604056e58d102832c732fbb1d4b9b997c72b8c
[ "Apache-2.0" ]
null
null
null
third_party/mlir/lib/Parser/Parser.cpp
ai2ys/tensorflow
0d604056e58d102832c732fbb1d4b9b997c72b8c
[ "Apache-2.0" ]
null
null
null
//===- Parser.cpp - MLIR Parser Implementation ----------------------------===// // // Copyright 2019 The MLIR Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= // // This file implements the parser for the MLIR textual form. // //===----------------------------------------------------------------------===// #include "mlir/Parser.h" #include "Lexer.h" #include "mlir/Analysis/Verifier.h" #include "mlir/IR/AffineExpr.h" #include "mlir/IR/AffineMap.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Dialect.h" #include "mlir/IR/IntegerSet.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Module.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Support/STLExtras.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/ADT/bit.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SMLoc.h" #include "llvm/Support/SourceMgr.h" #include <algorithm> using namespace mlir; using llvm::MemoryBuffer; using llvm::SMLoc; using llvm::SourceMgr; namespace { class Parser; //===----------------------------------------------------------------------===// // ParserState //===----------------------------------------------------------------------===// /// This class refers to all of the state maintained globally by the parser, /// such as the current lexer position etc. The Parser base class provides /// methods to access this. class ParserState { public: ParserState(const llvm::SourceMgr &sourceMgr, MLIRContext *ctx) : context(ctx), lex(sourceMgr, ctx), curToken(lex.lexToken()) {} // A map from attribute alias identifier to Attribute. llvm::StringMap<Attribute> attributeAliasDefinitions; // A map from type alias identifier to Type. llvm::StringMap<Type> typeAliasDefinitions; private: ParserState(const ParserState &) = delete; void operator=(const ParserState &) = delete; friend class Parser; // The context we're parsing into. MLIRContext *const context; // The lexer for the source file we're parsing. Lexer lex; // This is the next token that hasn't been consumed yet. Token curToken; }; //===----------------------------------------------------------------------===// // Parser //===----------------------------------------------------------------------===// /// This class implement support for parsing global entities like types and /// shared entities like SSA names. It is intended to be subclassed by /// specialized subparsers that include state, e.g. when a local symbol table. class Parser { public: Builder builder; Parser(ParserState &state) : builder(state.context), state(state) {} // Helper methods to get stuff from the parser-global state. ParserState &getState() const { return state; } MLIRContext *getContext() const { return state.context; } const llvm::SourceMgr &getSourceMgr() { return state.lex.getSourceMgr(); } /// Parse a comma-separated list of elements up until the specified end token. ParseResult parseCommaSeparatedListUntil(Token::Kind rightToken, const std::function<ParseResult()> &parseElement, bool allowEmptyList = true); /// Parse a comma separated list of elements that must have at least one entry /// in it. ParseResult parseCommaSeparatedList(const std::function<ParseResult()> &parseElement); ParseResult parsePrettyDialectSymbolName(StringRef &prettyName); // We have two forms of parsing methods - those that return a non-null // pointer on success, and those that return a ParseResult to indicate whether // they returned a failure. The second class fills in by-reference arguments // as the results of their action. //===--------------------------------------------------------------------===// // Error Handling //===--------------------------------------------------------------------===// /// Emit an error and return failure. InFlightDiagnostic emitError(const Twine &message = {}) { return emitError(state.curToken.getLoc(), message); } InFlightDiagnostic emitError(SMLoc loc, const Twine &message = {}); /// Encode the specified source location information into an attribute for /// attachment to the IR. Location getEncodedSourceLocation(llvm::SMLoc loc) { return state.lex.getEncodedSourceLocation(loc); } //===--------------------------------------------------------------------===// // Token Parsing //===--------------------------------------------------------------------===// /// Return the current token the parser is inspecting. const Token &getToken() const { return state.curToken; } StringRef getTokenSpelling() const { return state.curToken.getSpelling(); } /// If the current token has the specified kind, consume it and return true. /// If not, return false. bool consumeIf(Token::Kind kind) { if (state.curToken.isNot(kind)) return false; consumeToken(kind); return true; } /// Advance the current lexer onto the next token. void consumeToken() { assert(state.curToken.isNot(Token::eof, Token::error) && "shouldn't advance past EOF or errors"); state.curToken = state.lex.lexToken(); } /// Advance the current lexer onto the next token, asserting what the expected /// current token is. This is preferred to the above method because it leads /// to more self-documenting code with better checking. void consumeToken(Token::Kind kind) { assert(state.curToken.is(kind) && "consumed an unexpected token"); consumeToken(); } /// Consume the specified token if present and return success. On failure, /// output a diagnostic and return failure. ParseResult parseToken(Token::Kind expectedToken, const Twine &message); //===--------------------------------------------------------------------===// // Type Parsing //===--------------------------------------------------------------------===// ParseResult parseFunctionResultTypes(SmallVectorImpl<Type> &elements); ParseResult parseTypeListNoParens(SmallVectorImpl<Type> &elements); ParseResult parseTypeListParens(SmallVectorImpl<Type> &elements); /// Parse an arbitrary type. Type parseType(); /// Parse a complex type. Type parseComplexType(); /// Parse an extended type. Type parseExtendedType(); /// Parse a function type. Type parseFunctionType(); /// Parse a memref type. Type parseMemRefType(); /// Parse a non function type. Type parseNonFunctionType(); /// Parse a tensor type. Type parseTensorType(); /// Parse a tuple type. Type parseTupleType(); /// Parse a vector type. VectorType parseVectorType(); ParseResult parseDimensionListRanked(SmallVectorImpl<int64_t> &dimensions, bool allowDynamic = true); ParseResult parseXInDimensionList(); //===--------------------------------------------------------------------===// // Attribute Parsing //===--------------------------------------------------------------------===// /// Parse an arbitrary attribute with an optional type. Attribute parseAttribute(Type type = {}); /// Parse an attribute dictionary. ParseResult parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes); /// Parse an extended attribute. Attribute parseExtendedAttr(Type type); /// Parse a float attribute. Attribute parseFloatAttr(Type type, bool isNegative); /// Parse a decimal or a hexadecimal literal, which can be either an integer /// or a float attribute. Attribute parseDecOrHexAttr(Type type, bool isNegative); /// Parse an opaque elements attribute. Attribute parseOpaqueElementsAttr(); /// Parse a dense elements attribute. Attribute parseDenseElementsAttr(); ShapedType parseElementsLiteralType(); /// Parse a sparse elements attribute. Attribute parseSparseElementsAttr(); //===--------------------------------------------------------------------===// // Location Parsing //===--------------------------------------------------------------------===// /// Parse an inline location. ParseResult parseLocation(LocationAttr &loc); /// Parse a raw location instance. ParseResult parseLocationInstance(LocationAttr &loc); /// Parse a callsite location instance. ParseResult parseCallSiteLocation(LocationAttr &loc); /// Parse a fused location instance. ParseResult parseFusedLocation(LocationAttr &loc); /// Parse a name or FileLineCol location instance. ParseResult parseNameOrFileLineColLocation(LocationAttr &loc); /// Parse an optional trailing location. /// /// trailing-location ::= location? /// template <typename Owner> ParseResult parseOptionalTrailingLocation(Owner *owner) { // If there is a 'loc' we parse a trailing location. if (!getToken().is(Token::kw_loc)) return success(); // Parse the location. LocationAttr directLoc; if (parseLocation(directLoc)) return failure(); owner->setLoc(directLoc); return success(); } //===--------------------------------------------------------------------===// // Affine Parsing //===--------------------------------------------------------------------===// ParseResult parseAffineMapOrIntegerSetReference(AffineMap &map, IntegerSet &set); /// Parse an AffineMap where the dim and symbol identifiers are SSA ids. ParseResult parseAffineMapOfSSAIds(AffineMap &map, llvm::function_ref<ParseResult(bool)> parseElement); private: /// The Parser is subclassed and reinstantiated. Do not add additional /// non-trivial state here, add it to the ParserState class. ParserState &state; }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Helper methods. //===----------------------------------------------------------------------===// /// Parse a comma separated list of elements that must have at least one entry /// in it. ParseResult Parser::parseCommaSeparatedList( const std::function<ParseResult()> &parseElement) { // Non-empty case starts with an element. if (parseElement()) return failure(); // Otherwise we have a list of comma separated elements. while (consumeIf(Token::comma)) { if (parseElement()) return failure(); } return success(); } /// Parse a comma-separated list of elements, terminated with an arbitrary /// token. This allows empty lists if allowEmptyList is true. /// /// abstract-list ::= rightToken // if allowEmptyList == true /// abstract-list ::= element (',' element)* rightToken /// ParseResult Parser::parseCommaSeparatedListUntil( Token::Kind rightToken, const std::function<ParseResult()> &parseElement, bool allowEmptyList) { // Handle the empty case. if (getToken().is(rightToken)) { if (!allowEmptyList) return emitError("expected list element"); consumeToken(rightToken); return success(); } if (parseCommaSeparatedList(parseElement) || parseToken(rightToken, "expected ',' or '" + Token::getTokenSpelling(rightToken) + "'")) return failure(); return success(); } /// Parse the body of a pretty dialect symbol, which starts and ends with <>'s, /// and may be recursive. Return with the 'prettyName' StringRef encompasing /// the entire pretty name. /// /// pretty-dialect-sym-body ::= '<' pretty-dialect-sym-contents+ '>' /// pretty-dialect-sym-contents ::= pretty-dialect-sym-body /// | '(' pretty-dialect-sym-contents+ ')' /// | '[' pretty-dialect-sym-contents+ ']' /// | '{' pretty-dialect-sym-contents+ '}' /// | '[^[<({>\])}\0]+' /// ParseResult Parser::parsePrettyDialectSymbolName(StringRef &prettyName) { // Pretty symbol names are a relatively unstructured format that contains a // series of properly nested punctuation, with anything else in the middle. // Scan ahead to find it and consume it if successful, otherwise emit an // error. auto *curPtr = getTokenSpelling().data(); SmallVector<char, 8> nestedPunctuation; // Scan over the nested punctuation, bailing out on error and consuming until // we find the end. We know that we're currently looking at the '<', so we // can go until we find the matching '>' character. assert(*curPtr == '<'); do { char c = *curPtr++; switch (c) { case '\0': // This also handles the EOF case. return emitError("unexpected nul or EOF in pretty dialect name"); case '<': case '[': case '(': case '{': nestedPunctuation.push_back(c); continue; case '-': // The sequence `->` is treated as special token. if (*curPtr == '>') ++curPtr; continue; case '>': if (nestedPunctuation.pop_back_val() != '<') return emitError("unbalanced '>' character in pretty dialect name"); break; case ']': if (nestedPunctuation.pop_back_val() != '[') return emitError("unbalanced ']' character in pretty dialect name"); break; case ')': if (nestedPunctuation.pop_back_val() != '(') return emitError("unbalanced ')' character in pretty dialect name"); break; case '}': if (nestedPunctuation.pop_back_val() != '{') return emitError("unbalanced '}' character in pretty dialect name"); break; default: continue; } } while (!nestedPunctuation.empty()); // Ok, we succeeded, remember where we stopped, reset the lexer to know it is // consuming all this stuff, and return. state.lex.resetPointer(curPtr); unsigned length = curPtr - prettyName.begin(); prettyName = StringRef(prettyName.begin(), length); consumeToken(); return success(); } /// Parse an extended dialect symbol. template <typename Symbol, typename SymbolAliasMap, typename CreateFn> static Symbol parseExtendedSymbol(Parser &p, Token::Kind identifierTok, SymbolAliasMap &aliases, CreateFn &&createSymbol) { // Parse the dialect namespace. StringRef identifier = p.getTokenSpelling().drop_front(); auto loc = p.getToken().getLoc(); p.consumeToken(identifierTok); // If there is no '<' token following this, and if the typename contains no // dot, then we are parsing a symbol alias. if (p.getToken().isNot(Token::less) && !identifier.contains('.')) { // Check for an alias for this type. auto aliasIt = aliases.find(identifier); if (aliasIt == aliases.end()) return (p.emitError("undefined symbol alias id '" + identifier + "'"), nullptr); return aliasIt->second; } // Otherwise, we are parsing a dialect-specific symbol. If the name contains // a dot, then this is the "pretty" form. If not, it is the verbose form that // looks like <"...">. std::string symbolData; auto dialectName = identifier; // Handle the verbose form, where "identifier" is a simple dialect name. if (!identifier.contains('.')) { // Consume the '<'. if (p.parseToken(Token::less, "expected '<' in dialect type")) return nullptr; // Parse the symbol specific data. if (p.getToken().isNot(Token::string)) return (p.emitError("expected string literal data in dialect symbol"), nullptr); symbolData = p.getToken().getStringValue(); loc = p.getToken().getLoc(); p.consumeToken(Token::string); // Consume the '>'. if (p.parseToken(Token::greater, "expected '>' in dialect symbol")) return nullptr; } else { // Ok, the dialect name is the part of the identifier before the dot, the // part after the dot is the dialect's symbol, or the start thereof. auto dotHalves = identifier.split('.'); dialectName = dotHalves.first; auto prettyName = dotHalves.second; // If the dialect's symbol is followed immediately by a <, then lex the body // of it into prettyName. if (p.getToken().is(Token::less) && prettyName.bytes_end() == p.getTokenSpelling().bytes_begin()) { if (p.parsePrettyDialectSymbolName(prettyName)) return nullptr; } symbolData = prettyName.str(); } // Call into the provided symbol construction function. auto encodedLoc = p.getEncodedSourceLocation(loc); return createSymbol(dialectName, symbolData, encodedLoc); } //===----------------------------------------------------------------------===// // Error Handling //===----------------------------------------------------------------------===// InFlightDiagnostic Parser::emitError(SMLoc loc, const Twine &message) { auto diag = mlir::emitError(getEncodedSourceLocation(loc), message); // If we hit a parse error in response to a lexer error, then the lexer // already reported the error. if (getToken().is(Token::error)) diag.abandon(); return diag; } //===----------------------------------------------------------------------===// // Token Parsing //===----------------------------------------------------------------------===// /// Consume the specified token if present and return success. On failure, /// output a diagnostic and return failure. ParseResult Parser::parseToken(Token::Kind expectedToken, const Twine &message) { if (consumeIf(expectedToken)) return success(); return emitError(message); } //===----------------------------------------------------------------------===// // Type Parsing //===----------------------------------------------------------------------===// /// Parse an arbitrary type. /// /// type ::= function-type /// | non-function-type /// Type Parser::parseType() { if (getToken().is(Token::l_paren)) return parseFunctionType(); return parseNonFunctionType(); } /// Parse a function result type. /// /// function-result-type ::= type-list-parens /// | non-function-type /// ParseResult Parser::parseFunctionResultTypes(SmallVectorImpl<Type> &elements) { if (getToken().is(Token::l_paren)) return parseTypeListParens(elements); Type t = parseNonFunctionType(); if (!t) return failure(); elements.push_back(t); return success(); } /// Parse a list of types without an enclosing parenthesis. The list must have /// at least one member. /// /// type-list-no-parens ::= type (`,` type)* /// ParseResult Parser::parseTypeListNoParens(SmallVectorImpl<Type> &elements) { auto parseElt = [&]() -> ParseResult { auto elt = parseType(); elements.push_back(elt); return elt ? success() : failure(); }; return parseCommaSeparatedList(parseElt); } /// Parse a parenthesized list of types. /// /// type-list-parens ::= `(` `)` /// | `(` type-list-no-parens `)` /// ParseResult Parser::parseTypeListParens(SmallVectorImpl<Type> &elements) { if (parseToken(Token::l_paren, "expected '('")) return failure(); // Handle empty lists. if (getToken().is(Token::r_paren)) return consumeToken(), success(); if (parseTypeListNoParens(elements) || parseToken(Token::r_paren, "expected ')'")) return failure(); return success(); } /// Parse a complex type. /// /// complex-type ::= `complex` `<` type `>` /// Type Parser::parseComplexType() { consumeToken(Token::kw_complex); // Parse the '<'. if (parseToken(Token::less, "expected '<' in complex type")) return nullptr; auto typeLocation = getEncodedSourceLocation(getToken().getLoc()); auto elementType = parseType(); if (!elementType || parseToken(Token::greater, "expected '>' in complex type")) return nullptr; return ComplexType::getChecked(elementType, typeLocation); } /// Parse an extended type. /// /// extended-type ::= (dialect-type | type-alias) /// dialect-type ::= `!` dialect-namespace `<` `"` type-data `"` `>` /// dialect-type ::= `!` alias-name pretty-dialect-attribute-body? /// type-alias ::= `!` alias-name /// Type Parser::parseExtendedType() { return parseExtendedSymbol<Type>( *this, Token::exclamation_identifier, state.typeAliasDefinitions, [&](StringRef dialectName, StringRef symbolData, Location loc) -> Type { // If we found a registered dialect, then ask it to parse the type. if (auto *dialect = state.context->getRegisteredDialect(dialectName)) return dialect->parseType(symbolData, loc); // Otherwise, form a new opaque type. return OpaqueType::getChecked( Identifier::get(dialectName, state.context), symbolData, state.context, loc); }); } /// Parse a function type. /// /// function-type ::= type-list-parens `->` function-result-type /// Type Parser::parseFunctionType() { assert(getToken().is(Token::l_paren)); SmallVector<Type, 4> arguments, results; if (parseTypeListParens(arguments) || parseToken(Token::arrow, "expected '->' in function type") || parseFunctionResultTypes(results)) return nullptr; return builder.getFunctionType(arguments, results); } /// Parse a memref type. /// /// memref-type ::= `memref` `<` dimension-list-ranked type /// (`,` semi-affine-map-composition)? (`,` memory-space)? `>` /// /// semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map /// memory-space ::= integer-literal /* | TODO: address-space-id */ /// Type Parser::parseMemRefType() { consumeToken(Token::kw_memref); if (parseToken(Token::less, "expected '<' in memref type")) return nullptr; SmallVector<int64_t, 4> dimensions; if (parseDimensionListRanked(dimensions)) return nullptr; // Parse the element type. auto typeLoc = getToken().getLoc(); auto elementType = parseType(); if (!elementType) return nullptr; // Parse semi-affine-map-composition. SmallVector<AffineMap, 2> affineMapComposition; unsigned memorySpace = 0; bool parsedMemorySpace = false; auto parseElt = [&]() -> ParseResult { if (getToken().is(Token::integer)) { // Parse memory space. if (parsedMemorySpace) return emitError("multiple memory spaces specified in memref type"); auto v = getToken().getUnsignedIntegerValue(); if (!v.hasValue()) return emitError("invalid memory space in memref type"); memorySpace = v.getValue(); consumeToken(Token::integer); parsedMemorySpace = true; } else { // Parse affine map. if (parsedMemorySpace) return emitError("affine map after memory space in memref type"); auto affineMap = parseAttribute(); if (!affineMap) return failure(); // Verify that the parsed attribute is an affine map. if (auto affineMapAttr = affineMap.dyn_cast<AffineMapAttr>()) affineMapComposition.push_back(affineMapAttr.getValue()); else return emitError("expected affine map in memref type"); } return success(); }; // Parse a list of mappings and address space if present. if (consumeIf(Token::comma)) { // Parse comma separated list of affine maps, followed by memory space. if (parseCommaSeparatedListUntil(Token::greater, parseElt, /*allowEmptyList=*/false)) { return nullptr; } } else { if (parseToken(Token::greater, "expected ',' or '>' in memref type")) return nullptr; } return MemRefType::getChecked(dimensions, elementType, affineMapComposition, memorySpace, getEncodedSourceLocation(typeLoc)); } /// Parse any type except the function type. /// /// non-function-type ::= integer-type /// | index-type /// | float-type /// | extended-type /// | vector-type /// | tensor-type /// | memref-type /// | complex-type /// | tuple-type /// | none-type /// /// index-type ::= `index` /// float-type ::= `f16` | `bf16` | `f32` | `f64` /// none-type ::= `none` /// Type Parser::parseNonFunctionType() { switch (getToken().getKind()) { default: return (emitError("expected non-function type"), nullptr); case Token::kw_memref: return parseMemRefType(); case Token::kw_tensor: return parseTensorType(); case Token::kw_complex: return parseComplexType(); case Token::kw_tuple: return parseTupleType(); case Token::kw_vector: return parseVectorType(); // integer-type case Token::inttype: { auto width = getToken().getIntTypeBitwidth(); if (!width.hasValue()) return (emitError("invalid integer width"), nullptr); auto loc = getEncodedSourceLocation(getToken().getLoc()); consumeToken(Token::inttype); return IntegerType::getChecked(width.getValue(), builder.getContext(), loc); } // float-type case Token::kw_bf16: consumeToken(Token::kw_bf16); return builder.getBF16Type(); case Token::kw_f16: consumeToken(Token::kw_f16); return builder.getF16Type(); case Token::kw_f32: consumeToken(Token::kw_f32); return builder.getF32Type(); case Token::kw_f64: consumeToken(Token::kw_f64); return builder.getF64Type(); // index-type case Token::kw_index: consumeToken(Token::kw_index); return builder.getIndexType(); // none-type case Token::kw_none: consumeToken(Token::kw_none); return builder.getNoneType(); // extended type case Token::exclamation_identifier: return parseExtendedType(); } } /// Parse a tensor type. /// /// tensor-type ::= `tensor` `<` dimension-list type `>` /// dimension-list ::= dimension-list-ranked | `*x` /// Type Parser::parseTensorType() { consumeToken(Token::kw_tensor); if (parseToken(Token::less, "expected '<' in tensor type")) return nullptr; bool isUnranked; SmallVector<int64_t, 4> dimensions; if (consumeIf(Token::star)) { // This is an unranked tensor type. isUnranked = true; if (parseXInDimensionList()) return nullptr; } else { isUnranked = false; if (parseDimensionListRanked(dimensions)) return nullptr; } // Parse the element type. auto typeLocation = getEncodedSourceLocation(getToken().getLoc()); auto elementType = parseType(); if (!elementType || parseToken(Token::greater, "expected '>' in tensor type")) return nullptr; if (isUnranked) return UnrankedTensorType::getChecked(elementType, typeLocation); return RankedTensorType::getChecked(dimensions, elementType, typeLocation); } /// Parse a tuple type. /// /// tuple-type ::= `tuple` `<` (type (`,` type)*)? `>` /// Type Parser::parseTupleType() { consumeToken(Token::kw_tuple); // Parse the '<'. if (parseToken(Token::less, "expected '<' in tuple type")) return nullptr; // Check for an empty tuple by directly parsing '>'. if (consumeIf(Token::greater)) return TupleType::get(getContext()); // Parse the element types and the '>'. SmallVector<Type, 4> types; if (parseTypeListNoParens(types) || parseToken(Token::greater, "expected '>' in tuple type")) return nullptr; return TupleType::get(types, getContext()); } /// Parse a vector type. /// /// vector-type ::= `vector` `<` non-empty-static-dimension-list type `>` /// non-empty-static-dimension-list ::= decimal-literal `x` /// static-dimension-list /// static-dimension-list ::= (decimal-literal `x`)* /// VectorType Parser::parseVectorType() { consumeToken(Token::kw_vector); if (parseToken(Token::less, "expected '<' in vector type")) return nullptr; SmallVector<int64_t, 4> dimensions; if (parseDimensionListRanked(dimensions, /*allowDynamic=*/false)) return nullptr; if (dimensions.empty()) return (emitError("expected dimension size in vector type"), nullptr); // Parse the element type. auto typeLoc = getToken().getLoc(); auto elementType = parseType(); if (!elementType || parseToken(Token::greater, "expected '>' in vector type")) return nullptr; return VectorType::getChecked(dimensions, elementType, getEncodedSourceLocation(typeLoc)); } /// Parse a dimension list of a tensor or memref type. This populates the /// dimension list, using -1 for the `?` dimensions if `allowDynamic` is set and /// errors out on `?` otherwise. /// /// dimension-list-ranked ::= (dimension `x`)* /// dimension ::= `?` | decimal-literal /// /// When `allowDynamic` is not set, this is used to parse: /// /// static-dimension-list ::= (decimal-literal `x`)* ParseResult Parser::parseDimensionListRanked(SmallVectorImpl<int64_t> &dimensions, bool allowDynamic) { while (getToken().isAny(Token::integer, Token::question)) { if (consumeIf(Token::question)) { if (!allowDynamic) return emitError("expected static shape"); dimensions.push_back(-1); } else { // Hexadecimal integer literals (starting with `0x`) are not allowed in // aggregate type declarations. Therefore, `0xf32` should be processed as // a sequence of separate elements `0`, `x`, `f32`. if (getTokenSpelling().size() > 1 && getTokenSpelling()[1] == 'x') { // We can get here only if the token is an integer literal. Hexadecimal // integer literals can only start with `0x` (`1x` wouldn't lex as a // literal, just `1` would, at which point we don't get into this // branch). assert(getTokenSpelling()[0] == '0' && "invalid integer literal"); dimensions.push_back(0); state.lex.resetPointer(getTokenSpelling().data() + 1); consumeToken(); } else { // Make sure this integer value is in bound and valid. auto dimension = getToken().getUnsignedIntegerValue(); if (!dimension.hasValue()) return emitError("invalid dimension"); dimensions.push_back((int64_t)dimension.getValue()); consumeToken(Token::integer); } } // Make sure we have an 'x' or something like 'xbf32'. if (parseXInDimensionList()) return failure(); } return success(); } /// Parse an 'x' token in a dimension list, handling the case where the x is /// juxtaposed with an element type, as in "xf32", leaving the "f32" as the next /// token. ParseResult Parser::parseXInDimensionList() { if (getToken().isNot(Token::bare_identifier) || getTokenSpelling()[0] != 'x') return emitError("expected 'x' in dimension list"); // If we had a prefix of 'x', lex the next token immediately after the 'x'. if (getTokenSpelling().size() != 1) state.lex.resetPointer(getTokenSpelling().data() + 1); // Consume the 'x'. consumeToken(Token::bare_identifier); return success(); } //===----------------------------------------------------------------------===// // Attribute parsing. //===----------------------------------------------------------------------===// /// Parse an arbitrary attribute. /// /// attribute-value ::= `unit` /// | bool-literal /// | integer-literal (`:` (index-type | integer-type))? /// | float-literal (`:` float-type)? /// | string-literal (`:` type)? /// | type /// | `[` (attribute-value (`,` attribute-value)*)? `]` /// | `{` (attribute-entry (`,` attribute-entry)*)? `}` /// | symbol-ref-id /// | `dense` `<` attribute-value `>` `:` /// (tensor-type | vector-type) /// | `sparse` `<` attribute-value `,` attribute-value `>` /// `:` (tensor-type | vector-type) /// | `opaque` `<` dialect-namespace `,` hex-string-literal /// `>` `:` (tensor-type | vector-type) /// | extended-attribute /// Attribute Parser::parseAttribute(Type type) { switch (getToken().getKind()) { // Parse an AffineMap or IntegerSet attribute. case Token::l_paren: { // Try to parse an affine map or an integer set reference. AffineMap map; IntegerSet set; if (parseAffineMapOrIntegerSetReference(map, set)) return nullptr; if (map) return builder.getAffineMapAttr(map); assert(set); return builder.getIntegerSetAttr(set); } // Parse an array attribute. case Token::l_square: { consumeToken(Token::l_square); SmallVector<Attribute, 4> elements; auto parseElt = [&]() -> ParseResult { elements.push_back(parseAttribute()); return elements.back() ? success() : failure(); }; if (parseCommaSeparatedListUntil(Token::r_square, parseElt)) return nullptr; return builder.getArrayAttr(elements); } // Parse a boolean attribute. case Token::kw_false: consumeToken(Token::kw_false); return builder.getBoolAttr(false); case Token::kw_true: consumeToken(Token::kw_true); return builder.getBoolAttr(true); // Parse a dense elements attribute. case Token::kw_dense: return parseDenseElementsAttr(); // Parse a dictionary attribute. case Token::l_brace: { SmallVector<NamedAttribute, 4> elements; if (parseAttributeDict(elements)) return nullptr; return builder.getDictionaryAttr(elements); } // Parse an extended attribute, i.e. alias or dialect attribute. case Token::hash_identifier: return parseExtendedAttr(type); // Parse floating point and integer attributes. case Token::floatliteral: return parseFloatAttr(type, /*isNegative=*/false); case Token::integer: return parseDecOrHexAttr(type, /*isNegative=*/false); case Token::minus: { consumeToken(Token::minus); if (getToken().is(Token::integer)) return parseDecOrHexAttr(type, /*isNegative=*/true); if (getToken().is(Token::floatliteral)) return parseFloatAttr(type, /*isNegative=*/true); return (emitError("expected constant integer or floating point value"), nullptr); } // Parse a location attribute. case Token::kw_loc: { LocationAttr attr; return failed(parseLocation(attr)) ? Attribute() : attr; } // Parse an opaque elements attribute. case Token::kw_opaque: return parseOpaqueElementsAttr(); // Parse a sparse elements attribute. case Token::kw_sparse: return parseSparseElementsAttr(); // Parse a string attribute. case Token::string: { auto val = getToken().getStringValue(); consumeToken(Token::string); // Parse the optional trailing colon type if one wasn't explicitly provided. if (!type && consumeIf(Token::colon) && !(type = parseType())) return Attribute(); return type ? StringAttr::get(val, type) : StringAttr::get(val, getContext()); } // Parse a symbol reference attribute. case Token::at_identifier: { auto nameStr = getTokenSpelling(); consumeToken(Token::at_identifier); return builder.getSymbolRefAttr(nameStr.drop_front()); } // Parse a 'unit' attribute. case Token::kw_unit: consumeToken(Token::kw_unit); return builder.getUnitAttr(); default: // Parse a type attribute. if (Type type = parseType()) return builder.getTypeAttr(type); return nullptr; } } /// Attribute dictionary. /// /// attribute-dict ::= `{` `}` /// | `{` attribute-entry (`,` attribute-entry)* `}` /// attribute-entry ::= bare-id `=` attribute-value /// ParseResult Parser::parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes) { if (!consumeIf(Token::l_brace)) return failure(); auto parseElt = [&]() -> ParseResult { // We allow keywords as attribute names. if (getToken().isNot(Token::bare_identifier, Token::inttype) && !getToken().isKeyword()) return emitError("expected attribute name"); Identifier nameId = builder.getIdentifier(getTokenSpelling()); consumeToken(); // Try to parse the '=' for the attribute value. if (!consumeIf(Token::equal)) { // If there is no '=', we treat this as a unit attribute. attributes.push_back({nameId, builder.getUnitAttr()}); return success(); } auto attr = parseAttribute(); if (!attr) return failure(); attributes.push_back({nameId, attr}); return success(); }; if (parseCommaSeparatedListUntil(Token::r_brace, parseElt)) return failure(); return success(); } /// Parse an extended attribute. /// /// extended-attribute ::= (dialect-attribute | attribute-alias) /// dialect-attribute ::= `#` dialect-namespace `<` `"` attr-data `"` `>` /// dialect-attribute ::= `#` alias-name pretty-dialect-sym-body? /// attribute-alias ::= `#` alias-name /// Attribute Parser::parseExtendedAttr(Type type) { Attribute attr = parseExtendedSymbol<Attribute>( *this, Token::hash_identifier, state.attributeAliasDefinitions, [&](StringRef dialectName, StringRef symbolData, Location loc) -> Attribute { // Parse an optional trailing colon type. Type attrType = type; if (consumeIf(Token::colon) && !(attrType = parseType())) return Attribute(); // If we found a registered dialect, then ask it to parse the attribute. if (auto *dialect = state.context->getRegisteredDialect(dialectName)) return dialect->parseAttribute(symbolData, attrType, loc); // Otherwise, form a new opaque attribute. return OpaqueAttr::getChecked( Identifier::get(dialectName, state.context), symbolData, attrType ? attrType : NoneType::get(state.context), loc); }); // Ensure that the attribute has the same type as requested. if (attr && type && attr.getType() != type) { emitError("attribute type different than expected: expected ") << type << ", but got " << attr.getType(); return nullptr; } return attr; } /// Parse a float attribute. Attribute Parser::parseFloatAttr(Type type, bool isNegative) { auto val = getToken().getFloatingPointValue(); if (!val.hasValue()) return (emitError("floating point value too large for attribute"), nullptr); consumeToken(Token::floatliteral); if (!type) { // Default to F64 when no type is specified. if (!consumeIf(Token::colon)) type = builder.getF64Type(); else if (!(type = parseType())) return nullptr; } if (!type.isa<FloatType>()) return (emitError("floating point value not valid for specified type"), nullptr); return FloatAttr::get(type, isNegative ? -val.getValue() : val.getValue()); } /// Construct a float attribute bitwise equivalent to the integer literal. static FloatAttr buildHexadecimalFloatLiteral(Parser *p, FloatType type, uint64_t value) { int width = type.getIntOrFloatBitWidth(); APInt apInt(width, value); if (apInt != value) { p->emitError("hexadecimal float constant out of range for type"); return nullptr; } APFloat apFloat(type.getFloatSemantics(), apInt); return p->builder.getFloatAttr(type, apFloat); } /// Parse a decimal or a hexadecimal literal, which can be either an integer /// or a float attribute. Attribute Parser::parseDecOrHexAttr(Type type, bool isNegative) { auto val = getToken().getUInt64IntegerValue(); if (!val.hasValue()) return (emitError("integer constant out of range for attribute"), nullptr); // Remember if the literal is hexadecimal. StringRef spelling = getToken().getSpelling(); auto loc = state.curToken.getLoc(); bool isHex = spelling.size() > 1 && spelling[1] == 'x'; consumeToken(Token::integer); if (!type) { // Default to i64 if not type is specified. if (!consumeIf(Token::colon)) type = builder.getIntegerType(64); else if (!(type = parseType())) return nullptr; } if (auto floatType = type.dyn_cast<FloatType>()) { // TODO(zinenko): Update once hex format for bfloat16 is supported. if (type.isBF16()) return emitError(loc, "hexadecimal float literal not supported for bfloat16"), nullptr; if (isNegative) return emitError( loc, "hexadecimal float literal should not have a leading minus"), nullptr; if (!isHex) { emitError(loc, "unexpected decimal integer literal for a float attribute") .attachNote() << "add a trailing dot to make the literal a float"; return nullptr; } // Construct a float attribute bitwise equivalent to the integer literal. return buildHexadecimalFloatLiteral(this, floatType, *val); } if (!type.isIntOrIndex()) return emitError(loc, "integer literal not valid for specified type"), nullptr; // Parse the integer literal. int width = type.isIndex() ? 64 : type.getIntOrFloatBitWidth(); APInt apInt(width, *val, isNegative); if (apInt != *val) return emitError(loc, "integer constant out of range for attribute"), nullptr; // Otherwise construct an integer attribute. if (isNegative ? (int64_t)-val.getValue() >= 0 : (int64_t)val.getValue() < 0) return emitError(loc, "integer constant out of range for attribute"), nullptr; return builder.getIntegerAttr(type, isNegative ? -apInt : apInt); } /// Parse an opaque elements attribute. Attribute Parser::parseOpaqueElementsAttr() { consumeToken(Token::kw_opaque); if (parseToken(Token::less, "expected '<' after 'opaque'")) return nullptr; if (getToken().isNot(Token::string)) return (emitError("expected dialect namespace"), nullptr); auto name = getToken().getStringValue(); auto *dialect = builder.getContext()->getRegisteredDialect(name); // TODO(shpeisman): Allow for having an unknown dialect on an opaque // attribute. Otherwise, it can't be roundtripped without having the dialect // registered. if (!dialect) return (emitError("no registered dialect with namespace '" + name + "'"), nullptr); consumeToken(Token::string); if (parseToken(Token::comma, "expected ','")) return nullptr; if (getToken().getKind() != Token::string) return (emitError("opaque string should start with '0x'"), nullptr); auto val = getToken().getStringValue(); if (val.size() < 2 || val[0] != '0' || val[1] != 'x') return (emitError("opaque string should start with '0x'"), nullptr); val = val.substr(2); if (!llvm::all_of(val, llvm::isHexDigit)) return (emitError("opaque string only contains hex digits"), nullptr); consumeToken(Token::string); if (parseToken(Token::greater, "expected '>'") || parseToken(Token::colon, "expected ':'")) return nullptr; auto type = parseElementsLiteralType(); if (!type) return nullptr; return builder.getOpaqueElementsAttr(dialect, type, llvm::fromHex(val)); } namespace { class TensorLiteralParser { public: TensorLiteralParser(Parser &p) : p(p) {} ParseResult parse() { if (p.getToken().is(Token::l_square)) return parseList(shape); return parseElement(); } /// Build a dense attribute instance with the parsed elements and the given /// shaped type. DenseElementsAttr getAttr(llvm::SMLoc loc, ShapedType type); ArrayRef<int64_t> getShape() const { return shape; } private: enum class ElementKind { Boolean, Integer, Float }; /// Return a string to represent the given element kind. const char *getElementKindStr(ElementKind kind) { switch (kind) { case ElementKind::Boolean: return "'boolean'"; case ElementKind::Integer: return "'integer'"; case ElementKind::Float: return "'float'"; } llvm_unreachable("unknown element kind"); } /// Build a Dense Integer attribute for the given type. DenseElementsAttr getIntAttr(llvm::SMLoc loc, ShapedType type, IntegerType eltTy); /// Build a Dense Float attribute for the given type. DenseElementsAttr getFloatAttr(llvm::SMLoc loc, ShapedType type, FloatType eltTy); /// Parse a single element, returning failure if it isn't a valid element /// literal. For example: /// parseElement(1) -> Success, 1 /// parseElement([1]) -> Failure ParseResult parseElement(); /// Parse a list of either lists or elements, returning the dimensions of the /// parsed sub-tensors in dims. For example: /// parseList([1, 2, 3]) -> Success, [3] /// parseList([[1, 2], [3, 4]]) -> Success, [2, 2] /// parseList([[1, 2], 3]) -> Failure /// parseList([[1, [2, 3]], [4, [5]]]) -> Failure ParseResult parseList(llvm::SmallVectorImpl<int64_t> &dims); Parser &p; /// The shape inferred from the parsed elements. SmallVector<int64_t, 4> shape; /// Storage used when parsing elements, this is a pair of <is_negated, token>. std::vector<std::pair<bool, Token>> storage; /// A flag that indicates the type of elements that have been parsed. llvm::Optional<ElementKind> knownEltKind; }; } // namespace /// Build a dense attribute instance with the parsed elements and the given /// shaped type. DenseElementsAttr TensorLiteralParser::getAttr(llvm::SMLoc loc, ShapedType type) { // Check that the parsed storage size has the same number of elements to the // type, or is a known splat. if (!shape.empty() && getShape() != type.getShape()) { p.emitError(loc) << "inferred shape of elements literal ([" << getShape() << "]) does not match type ([" << type.getShape() << "])"; return nullptr; } // If the type is an integer, build a set of APInt values from the storage // with the correct bitwidth. if (auto intTy = type.getElementType().dyn_cast<IntegerType>()) return getIntAttr(loc, type, intTy); // Otherwise, this must be a floating point type. auto floatTy = type.getElementType().dyn_cast<FloatType>(); if (!floatTy) { p.emitError(loc) << "expected floating-point or integer element type, got " << type.getElementType(); return nullptr; } return getFloatAttr(loc, type, floatTy); } /// Build a Dense Integer attribute for the given type. DenseElementsAttr TensorLiteralParser::getIntAttr(llvm::SMLoc loc, ShapedType type, IntegerType eltTy) { std::vector<APInt> intElements; intElements.reserve(storage.size()); for (const auto &signAndToken : storage) { bool isNegative = signAndToken.first; const Token &token = signAndToken.second; // Check to see if floating point values were parsed. if (token.is(Token::floatliteral)) { p.emitError() << "expected integer elements, but parsed floating-point"; return nullptr; } assert(token.isAny(Token::integer, Token::kw_true, Token::kw_false) && "unexpected token type"); if (token.isAny(Token::kw_true, Token::kw_false)) { if (!eltTy.isInteger(1)) p.emitError() << "expected i1 type for 'true' or 'false' values"; APInt apInt(eltTy.getWidth(), token.is(Token::kw_true), /*isSigned=*/false); intElements.push_back(apInt); continue; } // Create APInt values for each element with the correct bitwidth. auto val = token.getUInt64IntegerValue(); if (!val.hasValue() || (isNegative ? (int64_t)-val.getValue() >= 0 : (int64_t)val.getValue() < 0)) { p.emitError(token.getLoc(), "integer constant out of range for attribute"); return nullptr; } APInt apInt(eltTy.getWidth(), val.getValue(), isNegative); if (apInt != val.getValue()) return (p.emitError("integer constant out of range for type"), nullptr); intElements.push_back(isNegative ? -apInt : apInt); } return DenseElementsAttr::get(type, intElements); } /// Build a Dense Float attribute for the given type. DenseElementsAttr TensorLiteralParser::getFloatAttr(llvm::SMLoc loc, ShapedType type, FloatType eltTy) { std::vector<Attribute> floatValues; floatValues.reserve(storage.size()); for (const auto &signAndToken : storage) { bool isNegative = signAndToken.first; const Token &token = signAndToken.second; // Handle hexadecimal float literals. if (token.is(Token::integer) && token.getSpelling().startswith("0x")) { if (isNegative) { p.emitError(token.getLoc()) << "hexadecimal float literal should not have a leading minus"; return nullptr; } auto val = token.getUInt64IntegerValue(); if (!val.hasValue()) { p.emitError("hexadecimal float constant out of range for attribute"); return nullptr; } FloatAttr attr = buildHexadecimalFloatLiteral(&p, eltTy, *val); if (!attr) return nullptr; floatValues.push_back(attr); continue; } // Check to see if any decimal integers or booleans were parsed. if (!token.is(Token::floatliteral)) { p.emitError() << "expected floating-point elements, but parsed integer"; return nullptr; } // Build the float values from tokens. auto val = token.getFloatingPointValue(); if (!val.hasValue()) { p.emitError("floating point value too large for attribute"); return nullptr; } floatValues.push_back(FloatAttr::get(eltTy, isNegative ? -*val : *val)); } return DenseElementsAttr::get(type, floatValues); } ParseResult TensorLiteralParser::parseElement() { switch (p.getToken().getKind()) { // Parse a boolean element. case Token::kw_true: case Token::kw_false: case Token::floatliteral: case Token::integer: storage.emplace_back(/*isNegative=*/false, p.getToken()); p.consumeToken(); break; // Parse a signed integer or a negative floating-point element. case Token::minus: p.consumeToken(Token::minus); if (!p.getToken().isAny(Token::floatliteral, Token::integer)) return p.emitError("expected integer or floating point literal"); storage.emplace_back(/*isNegative=*/true, p.getToken()); p.consumeToken(); break; default: return p.emitError("expected element literal of primitive type"); } return success(); } /// Parse a list of either lists or elements, returning the dimensions of the /// parsed sub-tensors in dims. For example: /// parseList([1, 2, 3]) -> Success, [3] /// parseList([[1, 2], [3, 4]]) -> Success, [2, 2] /// parseList([[1, 2], 3]) -> Failure /// parseList([[1, [2, 3]], [4, [5]]]) -> Failure ParseResult TensorLiteralParser::parseList(llvm::SmallVectorImpl<int64_t> &dims) { p.consumeToken(Token::l_square); auto checkDims = [&](const llvm::SmallVectorImpl<int64_t> &prevDims, const llvm::SmallVectorImpl<int64_t> &newDims) -> ParseResult { if (prevDims == newDims) return success(); return p.emitError("tensor literal is invalid; ranks are not consistent " "between elements"); }; bool first = true; llvm::SmallVector<int64_t, 4> newDims; unsigned size = 0; auto parseCommaSeparatedList = [&]() -> ParseResult { llvm::SmallVector<int64_t, 4> thisDims; if (p.getToken().getKind() == Token::l_square) { if (parseList(thisDims)) return failure(); } else if (parseElement()) { return failure(); } ++size; if (!first) return checkDims(newDims, thisDims); newDims = thisDims; first = false; return success(); }; if (p.parseCommaSeparatedListUntil(Token::r_square, parseCommaSeparatedList)) return failure(); // Return the sublists' dimensions with 'size' prepended. dims.clear(); dims.push_back(size); dims.append(newDims.begin(), newDims.end()); return success(); } /// Parse a dense elements attribute. Attribute Parser::parseDenseElementsAttr() { consumeToken(Token::kw_dense); if (parseToken(Token::less, "expected '<' after 'dense'")) return nullptr; // Parse the literal data. TensorLiteralParser literalParser(*this); if (literalParser.parse()) return nullptr; if (parseToken(Token::greater, "expected '>'") || parseToken(Token::colon, "expected ':'")) return nullptr; auto typeLoc = getToken().getLoc(); auto type = parseElementsLiteralType(); if (!type) return nullptr; return literalParser.getAttr(typeLoc, type); } /// Shaped type for elements attribute. /// /// elements-literal-type ::= vector-type | ranked-tensor-type /// /// This method also checks the type has static shape. ShapedType Parser::parseElementsLiteralType() { auto type = parseType(); if (!type) return nullptr; if (!type.isa<RankedTensorType>() && !type.isa<VectorType>()) { emitError("elements literal must be a ranked tensor or vector type"); return nullptr; } auto sType = type.cast<ShapedType>(); if (!sType.hasStaticShape()) return (emitError("elements literal type must have static shape"), nullptr); return sType; } /// Parse a sparse elements attribute. Attribute Parser::parseSparseElementsAttr() { consumeToken(Token::kw_sparse); if (parseToken(Token::less, "Expected '<' after 'sparse'")) return nullptr; /// Parse indices auto indicesLoc = getToken().getLoc(); TensorLiteralParser indiceParser(*this); if (indiceParser.parse()) return nullptr; if (parseToken(Token::comma, "expected ','")) return nullptr; /// Parse values. auto valuesLoc = getToken().getLoc(); TensorLiteralParser valuesParser(*this); if (valuesParser.parse()) return nullptr; if (parseToken(Token::greater, "expected '>'") || parseToken(Token::colon, "expected ':'")) return nullptr; auto type = parseElementsLiteralType(); if (!type) return nullptr; // If the indices are a splat, i.e. the literal parser parsed an element and // not a list, we set the shape explicitly. The indices are represented by a // 2-dimensional shape where the second dimension is the rank of the type. // Given that the parsed indices is a splat, we know that we only have one // indice and thus one for the first dimension. auto indiceEltType = builder.getIntegerType(64); ShapedType indicesType; if (indiceParser.getShape().empty()) { indicesType = RankedTensorType::get({1, type.getRank()}, indiceEltType); } else { // Otherwise, set the shape to the one parsed by the literal parser. indicesType = RankedTensorType::get(indiceParser.getShape(), indiceEltType); } auto indices = indiceParser.getAttr(indicesLoc, indicesType); // If the values are a splat, set the shape explicitly based on the number of // indices. The number of indices is encoded in the first dimension of the // indice shape type. auto valuesEltType = type.getElementType(); ShapedType valuesType = valuesParser.getShape().empty() ? RankedTensorType::get({indicesType.getDimSize(0)}, valuesEltType) : RankedTensorType::get(valuesParser.getShape(), valuesEltType); auto values = valuesParser.getAttr(valuesLoc, valuesType); /// Sanity check. if (valuesType.getRank() != 1) return (emitError("expected 1-d tensor for values"), nullptr); auto sameShape = (indicesType.getRank() == 1) || (type.getRank() == indicesType.getDimSize(1)); auto sameElementNum = indicesType.getDimSize(0) == valuesType.getDimSize(0); if (!sameShape || !sameElementNum) { emitError() << "expected shape ([" << type.getShape() << "]); inferred shape of indices literal ([" << indicesType.getShape() << "]); inferred shape of values literal ([" << valuesType.getShape() << "])"; return nullptr; } // Build the sparse elements attribute by the indices and values. return SparseElementsAttr::get(type, indices, values); } //===----------------------------------------------------------------------===// // Location parsing. //===----------------------------------------------------------------------===// /// Parse a location. /// /// location ::= `loc` inline-location /// inline-location ::= '(' location-inst ')' /// ParseResult Parser::parseLocation(LocationAttr &loc) { // Check for 'loc' identifier. if (parseToken(Token::kw_loc, "expected 'loc' keyword")) return emitError(); // Parse the inline-location. if (parseToken(Token::l_paren, "expected '(' in inline location") || parseLocationInstance(loc) || parseToken(Token::r_paren, "expected ')' in inline location")) return failure(); return success(); } /// Specific location instances. /// /// location-inst ::= filelinecol-location | /// name-location | /// callsite-location | /// fused-location | /// unknown-location /// filelinecol-location ::= string-literal ':' integer-literal /// ':' integer-literal /// name-location ::= string-literal /// callsite-location ::= 'callsite' '(' location-inst 'at' location-inst ')' /// fused-location ::= fused ('<' attribute-value '>')? /// '[' location-inst (location-inst ',')* ']' /// unknown-location ::= 'unknown' /// ParseResult Parser::parseCallSiteLocation(LocationAttr &loc) { consumeToken(Token::bare_identifier); // Parse the '('. if (parseToken(Token::l_paren, "expected '(' in callsite location")) return failure(); // Parse the callee location. LocationAttr calleeLoc; if (parseLocationInstance(calleeLoc)) return failure(); // Parse the 'at'. if (getToken().isNot(Token::bare_identifier) || getToken().getSpelling() != "at") return emitError("expected 'at' in callsite location"); consumeToken(Token::bare_identifier); // Parse the caller location. LocationAttr callerLoc; if (parseLocationInstance(callerLoc)) return failure(); // Parse the ')'. if (parseToken(Token::r_paren, "expected ')' in callsite location")) return failure(); // Return the callsite location. loc = CallSiteLoc::get(calleeLoc, callerLoc); return success(); } ParseResult Parser::parseFusedLocation(LocationAttr &loc) { consumeToken(Token::bare_identifier); // Try to parse the optional metadata. Attribute metadata; if (consumeIf(Token::less)) { metadata = parseAttribute(); if (!metadata) return emitError("expected valid attribute metadata"); // Parse the '>' token. if (parseToken(Token::greater, "expected '>' after fused location metadata")) return failure(); } llvm::SmallVector<Location, 4> locations; auto parseElt = [&] { LocationAttr newLoc; if (parseLocationInstance(newLoc)) return failure(); locations.push_back(newLoc); return success(); }; if (parseToken(Token::l_square, "expected '[' in fused location") || parseCommaSeparatedList(parseElt) || parseToken(Token::r_square, "expected ']' in fused location")) return failure(); // Return the fused location. loc = FusedLoc::get(locations, metadata, getContext()); return success(); } ParseResult Parser::parseNameOrFileLineColLocation(LocationAttr &loc) { auto *ctx = getContext(); auto str = getToken().getStringValue(); consumeToken(Token::string); // If the next token is ':' this is a filelinecol location. if (consumeIf(Token::colon)) { // Parse the line number. if (getToken().isNot(Token::integer)) return emitError("expected integer line number in FileLineColLoc"); auto line = getToken().getUnsignedIntegerValue(); if (!line.hasValue()) return emitError("expected integer line number in FileLineColLoc"); consumeToken(Token::integer); // Parse the ':'. if (parseToken(Token::colon, "expected ':' in FileLineColLoc")) return failure(); // Parse the column number. if (getToken().isNot(Token::integer)) return emitError("expected integer column number in FileLineColLoc"); auto column = getToken().getUnsignedIntegerValue(); if (!column.hasValue()) return emitError("expected integer column number in FileLineColLoc"); consumeToken(Token::integer); loc = FileLineColLoc::get(str, line.getValue(), column.getValue(), ctx); return success(); } // Otherwise, this is a NameLoc. // Check for a child location. if (consumeIf(Token::l_paren)) { auto childSourceLoc = getToken().getLoc(); // Parse the child location. LocationAttr childLoc; if (parseLocationInstance(childLoc)) return failure(); // The child must not be another NameLoc. if (childLoc.isa<NameLoc>()) return emitError(childSourceLoc, "child of NameLoc cannot be another NameLoc"); loc = NameLoc::get(Identifier::get(str, ctx), childLoc); // Parse the closing ')'. if (parseToken(Token::r_paren, "expected ')' after child location of NameLoc")) return failure(); } else { loc = NameLoc::get(Identifier::get(str, ctx), ctx); } return success(); } ParseResult Parser::parseLocationInstance(LocationAttr &loc) { // Handle either name or filelinecol locations. if (getToken().is(Token::string)) return parseNameOrFileLineColLocation(loc); // Bare tokens required for other cases. if (!getToken().is(Token::bare_identifier)) return emitError("expected location instance"); // Check for the 'callsite' signifying a callsite location. if (getToken().getSpelling() == "callsite") return parseCallSiteLocation(loc); // If the token is 'fused', then this is a fused location. if (getToken().getSpelling() == "fused") return parseFusedLocation(loc); // Check for a 'unknown' for an unknown location. if (getToken().getSpelling() == "unknown") { consumeToken(Token::bare_identifier); loc = UnknownLoc::get(getContext()); return success(); } return emitError("expected location instance"); } //===----------------------------------------------------------------------===// // Affine parsing. //===----------------------------------------------------------------------===// /// Lower precedence ops (all at the same precedence level). LNoOp is false in /// the boolean sense. enum AffineLowPrecOp { /// Null value. LNoOp, Add, Sub }; /// Higher precedence ops - all at the same precedence level. HNoOp is false /// in the boolean sense. enum AffineHighPrecOp { /// Null value. HNoOp, Mul, FloorDiv, CeilDiv, Mod }; namespace { /// This is a specialized parser for affine structures (affine maps, affine /// expressions, and integer sets), maintaining the state transient to their /// bodies. class AffineParser : public Parser { public: AffineParser(ParserState &state, bool allowParsingSSAIds = false, llvm::function_ref<ParseResult(bool)> parseElement = nullptr) : Parser(state), allowParsingSSAIds(allowParsingSSAIds), parseElement(parseElement), numDimOperands(0), numSymbolOperands(0) {} AffineMap parseAffineMapRange(unsigned numDims, unsigned numSymbols); ParseResult parseAffineMapOrIntegerSetInline(AffineMap &map, IntegerSet &set); IntegerSet parseIntegerSetConstraints(unsigned numDims, unsigned numSymbols); ParseResult parseAffineMapOfSSAIds(AffineMap &map); void getDimsAndSymbolSSAIds(SmallVectorImpl<StringRef> &dimAndSymbolSSAIds, unsigned &numDims); private: // Binary affine op parsing. AffineLowPrecOp consumeIfLowPrecOp(); AffineHighPrecOp consumeIfHighPrecOp(); // Identifier lists for polyhedral structures. ParseResult parseDimIdList(unsigned &numDims); ParseResult parseSymbolIdList(unsigned &numSymbols); ParseResult parseDimAndOptionalSymbolIdList(unsigned &numDims, unsigned &numSymbols); ParseResult parseIdentifierDefinition(AffineExpr idExpr); AffineExpr parseAffineExpr(); AffineExpr parseParentheticalExpr(); AffineExpr parseNegateExpression(AffineExpr lhs); AffineExpr parseIntegerExpr(); AffineExpr parseBareIdExpr(); AffineExpr parseSSAIdExpr(bool isSymbol); AffineExpr parseSymbolSSAIdExpr(); AffineExpr getAffineBinaryOpExpr(AffineHighPrecOp op, AffineExpr lhs, AffineExpr rhs, SMLoc opLoc); AffineExpr getAffineBinaryOpExpr(AffineLowPrecOp op, AffineExpr lhs, AffineExpr rhs); AffineExpr parseAffineOperandExpr(AffineExpr lhs); AffineExpr parseAffineLowPrecOpExpr(AffineExpr llhs, AffineLowPrecOp llhsOp); AffineExpr parseAffineHighPrecOpExpr(AffineExpr llhs, AffineHighPrecOp llhsOp, SMLoc llhsOpLoc); AffineExpr parseAffineConstraint(bool *isEq); private: bool allowParsingSSAIds; llvm::function_ref<ParseResult(bool)> parseElement; unsigned numDimOperands; unsigned numSymbolOperands; SmallVector<std::pair<StringRef, AffineExpr>, 4> dimsAndSymbols; }; } // end anonymous namespace /// Create an affine binary high precedence op expression (mul's, div's, mod). /// opLoc is the location of the op token to be used to report errors /// for non-conforming expressions. AffineExpr AffineParser::getAffineBinaryOpExpr(AffineHighPrecOp op, AffineExpr lhs, AffineExpr rhs, SMLoc opLoc) { // TODO: make the error location info accurate. switch (op) { case Mul: if (!lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant()) { emitError(opLoc, "non-affine expression: at least one of the multiply " "operands has to be either a constant or symbolic"); return nullptr; } return lhs * rhs; case FloorDiv: if (!rhs.isSymbolicOrConstant()) { emitError(opLoc, "non-affine expression: right operand of floordiv " "has to be either a constant or symbolic"); return nullptr; } return lhs.floorDiv(rhs); case CeilDiv: if (!rhs.isSymbolicOrConstant()) { emitError(opLoc, "non-affine expression: right operand of ceildiv " "has to be either a constant or symbolic"); return nullptr; } return lhs.ceilDiv(rhs); case Mod: if (!rhs.isSymbolicOrConstant()) { emitError(opLoc, "non-affine expression: right operand of mod " "has to be either a constant or symbolic"); return nullptr; } return lhs % rhs; case HNoOp: llvm_unreachable("can't create affine expression for null high prec op"); return nullptr; } llvm_unreachable("Unknown AffineHighPrecOp"); } /// Create an affine binary low precedence op expression (add, sub). AffineExpr AffineParser::getAffineBinaryOpExpr(AffineLowPrecOp op, AffineExpr lhs, AffineExpr rhs) { switch (op) { case AffineLowPrecOp::Add: return lhs + rhs; case AffineLowPrecOp::Sub: return lhs - rhs; case AffineLowPrecOp::LNoOp: llvm_unreachable("can't create affine expression for null low prec op"); return nullptr; } llvm_unreachable("Unknown AffineLowPrecOp"); } /// Consume this token if it is a lower precedence affine op (there are only /// two precedence levels). AffineLowPrecOp AffineParser::consumeIfLowPrecOp() { switch (getToken().getKind()) { case Token::plus: consumeToken(Token::plus); return AffineLowPrecOp::Add; case Token::minus: consumeToken(Token::minus); return AffineLowPrecOp::Sub; default: return AffineLowPrecOp::LNoOp; } } /// Consume this token if it is a higher precedence affine op (there are only /// two precedence levels) AffineHighPrecOp AffineParser::consumeIfHighPrecOp() { switch (getToken().getKind()) { case Token::star: consumeToken(Token::star); return Mul; case Token::kw_floordiv: consumeToken(Token::kw_floordiv); return FloorDiv; case Token::kw_ceildiv: consumeToken(Token::kw_ceildiv); return CeilDiv; case Token::kw_mod: consumeToken(Token::kw_mod); return Mod; default: return HNoOp; } } /// Parse a high precedence op expression list: mul, div, and mod are high /// precedence binary ops, i.e., parse a /// expr_1 op_1 expr_2 op_2 ... expr_n /// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod). /// All affine binary ops are left associative. /// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is /// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is /// null. llhsOpLoc is the location of the llhsOp token that will be used to /// report an error for non-conforming expressions. AffineExpr AffineParser::parseAffineHighPrecOpExpr(AffineExpr llhs, AffineHighPrecOp llhsOp, SMLoc llhsOpLoc) { AffineExpr lhs = parseAffineOperandExpr(llhs); if (!lhs) return nullptr; // Found an LHS. Parse the remaining expression. auto opLoc = getToken().getLoc(); if (AffineHighPrecOp op = consumeIfHighPrecOp()) { if (llhs) { AffineExpr expr = getAffineBinaryOpExpr(llhsOp, llhs, lhs, opLoc); if (!expr) return nullptr; return parseAffineHighPrecOpExpr(expr, op, opLoc); } // No LLHS, get RHS return parseAffineHighPrecOpExpr(lhs, op, opLoc); } // This is the last operand in this expression. if (llhs) return getAffineBinaryOpExpr(llhsOp, llhs, lhs, llhsOpLoc); // No llhs, 'lhs' itself is the expression. return lhs; } /// Parse an affine expression inside parentheses. /// /// affine-expr ::= `(` affine-expr `)` AffineExpr AffineParser::parseParentheticalExpr() { if (parseToken(Token::l_paren, "expected '('")) return nullptr; if (getToken().is(Token::r_paren)) return (emitError("no expression inside parentheses"), nullptr); auto expr = parseAffineExpr(); if (!expr) return nullptr; if (parseToken(Token::r_paren, "expected ')'")) return nullptr; return expr; } /// Parse the negation expression. /// /// affine-expr ::= `-` affine-expr AffineExpr AffineParser::parseNegateExpression(AffineExpr lhs) { if (parseToken(Token::minus, "expected '-'")) return nullptr; AffineExpr operand = parseAffineOperandExpr(lhs); // Since negation has the highest precedence of all ops (including high // precedence ops) but lower than parentheses, we are only going to use // parseAffineOperandExpr instead of parseAffineExpr here. if (!operand) // Extra error message although parseAffineOperandExpr would have // complained. Leads to a better diagnostic. return (emitError("missing operand of negation"), nullptr); return (-1) * operand; } /// Parse a bare id that may appear in an affine expression. /// /// affine-expr ::= bare-id AffineExpr AffineParser::parseBareIdExpr() { if (getToken().isNot(Token::bare_identifier)) return (emitError("expected bare identifier"), nullptr); StringRef sRef = getTokenSpelling(); for (auto entry : dimsAndSymbols) { if (entry.first == sRef) { consumeToken(Token::bare_identifier); return entry.second; } } return (emitError("use of undeclared identifier"), nullptr); } /// Parse an SSA id which may appear in an affine expression. AffineExpr AffineParser::parseSSAIdExpr(bool isSymbol) { if (!allowParsingSSAIds) return (emitError("unexpected ssa identifier"), nullptr); if (getToken().isNot(Token::percent_identifier)) return (emitError("expected ssa identifier"), nullptr); auto name = getTokenSpelling(); // Check if we already parsed this SSA id. for (auto entry : dimsAndSymbols) { if (entry.first == name) { consumeToken(Token::percent_identifier); return entry.second; } } // Parse the SSA id and add an AffineDim/SymbolExpr to represent it. if (parseElement(isSymbol)) return (emitError("failed to parse ssa identifier"), nullptr); auto idExpr = isSymbol ? getAffineSymbolExpr(numSymbolOperands++, getContext()) : getAffineDimExpr(numDimOperands++, getContext()); dimsAndSymbols.push_back({name, idExpr}); return idExpr; } AffineExpr AffineParser::parseSymbolSSAIdExpr() { if (parseToken(Token::kw_symbol, "expected symbol keyword") || parseToken(Token::l_paren, "expected '(' at start of SSA symbol")) return nullptr; AffineExpr symbolExpr = parseSSAIdExpr(/*isSymbol=*/true); if (!symbolExpr) return nullptr; if (parseToken(Token::r_paren, "expected ')' at end of SSA symbol")) return nullptr; return symbolExpr; } /// Parse a positive integral constant appearing in an affine expression. /// /// affine-expr ::= integer-literal AffineExpr AffineParser::parseIntegerExpr() { auto val = getToken().getUInt64IntegerValue(); if (!val.hasValue() || (int64_t)val.getValue() < 0) return (emitError("constant too large for index"), nullptr); consumeToken(Token::integer); return builder.getAffineConstantExpr((int64_t)val.getValue()); } /// Parses an expression that can be a valid operand of an affine expression. /// lhs: if non-null, lhs is an affine expression that is the lhs of a binary /// operator, the rhs of which is being parsed. This is used to determine /// whether an error should be emitted for a missing right operand. // Eg: for an expression without parentheses (like i + j + k + l), each // of the four identifiers is an operand. For i + j*k + l, j*k is not an // operand expression, it's an op expression and will be parsed via // parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and // -l are valid operands that will be parsed by this function. AffineExpr AffineParser::parseAffineOperandExpr(AffineExpr lhs) { switch (getToken().getKind()) { case Token::bare_identifier: return parseBareIdExpr(); case Token::kw_symbol: return parseSymbolSSAIdExpr(); case Token::percent_identifier: return parseSSAIdExpr(/*isSymbol=*/false); case Token::integer: return parseIntegerExpr(); case Token::l_paren: return parseParentheticalExpr(); case Token::minus: return parseNegateExpression(lhs); case Token::kw_ceildiv: case Token::kw_floordiv: case Token::kw_mod: case Token::plus: case Token::star: if (lhs) emitError("missing right operand of binary operator"); else emitError("missing left operand of binary operator"); return nullptr; default: if (lhs) emitError("missing right operand of binary operator"); else emitError("expected affine expression"); return nullptr; } } /// Parse affine expressions that are bare-id's, integer constants, /// parenthetical affine expressions, and affine op expressions that are a /// composition of those. /// /// All binary op's associate from left to right. /// /// {add, sub} have lower precedence than {mul, div, and mod}. /// /// Add, sub'are themselves at the same precedence level. Mul, floordiv, /// ceildiv, and mod are at the same higher precedence level. Negation has /// higher precedence than any binary op. /// /// llhs: the affine expression appearing on the left of the one being parsed. /// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null, /// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned /// if llhs is non-null; otherwise lhs is returned. This is to deal with left /// associativity. /// /// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function /// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where /// (e2*e3) will be parsed using parseAffineHighPrecOpExpr(). AffineExpr AffineParser::parseAffineLowPrecOpExpr(AffineExpr llhs, AffineLowPrecOp llhsOp) { AffineExpr lhs; if (!(lhs = parseAffineOperandExpr(llhs))) return nullptr; // Found an LHS. Deal with the ops. if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) { if (llhs) { AffineExpr sum = getAffineBinaryOpExpr(llhsOp, llhs, lhs); return parseAffineLowPrecOpExpr(sum, lOp); } // No LLHS, get RHS and form the expression. return parseAffineLowPrecOpExpr(lhs, lOp); } auto opLoc = getToken().getLoc(); if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) { // We have a higher precedence op here. Get the rhs operand for the llhs // through parseAffineHighPrecOpExpr. AffineExpr highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc); if (!highRes) return nullptr; // If llhs is null, the product forms the first operand of the yet to be // found expression. If non-null, the op to associate with llhs is llhsOp. AffineExpr expr = llhs ? getAffineBinaryOpExpr(llhsOp, llhs, highRes) : highRes; // Recurse for subsequent low prec op's after the affine high prec op // expression. if (AffineLowPrecOp nextOp = consumeIfLowPrecOp()) return parseAffineLowPrecOpExpr(expr, nextOp); return expr; } // Last operand in the expression list. if (llhs) return getAffineBinaryOpExpr(llhsOp, llhs, lhs); // No llhs, 'lhs' itself is the expression. return lhs; } /// Parse an affine expression. /// affine-expr ::= `(` affine-expr `)` /// | `-` affine-expr /// | affine-expr `+` affine-expr /// | affine-expr `-` affine-expr /// | affine-expr `*` affine-expr /// | affine-expr `floordiv` affine-expr /// | affine-expr `ceildiv` affine-expr /// | affine-expr `mod` affine-expr /// | bare-id /// | integer-literal /// /// Additional conditions are checked depending on the production. For eg., /// one of the operands for `*` has to be either constant/symbolic; the second /// operand for floordiv, ceildiv, and mod has to be a positive integer. AffineExpr AffineParser::parseAffineExpr() { return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp); } /// Parse a dim or symbol from the lists appearing before the actual /// expressions of the affine map. Update our state to store the /// dimensional/symbolic identifier. ParseResult AffineParser::parseIdentifierDefinition(AffineExpr idExpr) { if (getToken().isNot(Token::bare_identifier)) return emitError("expected bare identifier"); auto name = getTokenSpelling(); for (auto entry : dimsAndSymbols) { if (entry.first == name) return emitError("redefinition of identifier '" + name + "'"); } consumeToken(Token::bare_identifier); dimsAndSymbols.push_back({name, idExpr}); return success(); } /// Parse the list of dimensional identifiers to an affine map. ParseResult AffineParser::parseDimIdList(unsigned &numDims) { if (parseToken(Token::l_paren, "expected '(' at start of dimensional identifiers list")) { return failure(); } auto parseElt = [&]() -> ParseResult { auto dimension = getAffineDimExpr(numDims++, getContext()); return parseIdentifierDefinition(dimension); }; return parseCommaSeparatedListUntil(Token::r_paren, parseElt); } /// Parse the list of symbolic identifiers to an affine map. ParseResult AffineParser::parseSymbolIdList(unsigned &numSymbols) { consumeToken(Token::l_square); auto parseElt = [&]() -> ParseResult { auto symbol = getAffineSymbolExpr(numSymbols++, getContext()); return parseIdentifierDefinition(symbol); }; return parseCommaSeparatedListUntil(Token::r_square, parseElt); } /// Parse the list of symbolic identifiers to an affine map. ParseResult AffineParser::parseDimAndOptionalSymbolIdList(unsigned &numDims, unsigned &numSymbols) { if (parseDimIdList(numDims)) { return failure(); } if (!getToken().is(Token::l_square)) { numSymbols = 0; return success(); } return parseSymbolIdList(numSymbols); } /// Parses an ambiguous affine map or integer set definition inline. ParseResult AffineParser::parseAffineMapOrIntegerSetInline(AffineMap &map, IntegerSet &set) { unsigned numDims = 0, numSymbols = 0; // List of dimensional and optional symbol identifiers. if (parseDimAndOptionalSymbolIdList(numDims, numSymbols)) { return failure(); } // This is needed for parsing attributes as we wouldn't know whether we would // be parsing an integer set attribute or an affine map attribute. bool isArrow = getToken().is(Token::arrow); bool isColon = getToken().is(Token::colon); if (!isArrow && !isColon) { return emitError("expected '->' or ':'"); } else if (isArrow) { parseToken(Token::arrow, "expected '->' or '['"); map = parseAffineMapRange(numDims, numSymbols); return map ? success() : failure(); } else if (parseToken(Token::colon, "expected ':' or '['")) { return failure(); } if ((set = parseIntegerSetConstraints(numDims, numSymbols))) return success(); return failure(); } /// Parse an AffineMap where the dim and symbol identifiers are SSA ids. ParseResult AffineParser::parseAffineMapOfSSAIds(AffineMap &map) { if (parseToken(Token::l_square, "expected '['")) return failure(); SmallVector<AffineExpr, 4> exprs; auto parseElt = [&]() -> ParseResult { auto elt = parseAffineExpr(); exprs.push_back(elt); return elt ? success() : failure(); }; // Parse a multi-dimensional affine expression (a comma-separated list of // 1-d affine expressions); the list cannot be empty. Grammar: // multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `) if (parseCommaSeparatedListUntil(Token::r_square, parseElt, /*allowEmptyList=*/true)) return failure(); // Parsed a valid affine map. if (exprs.empty()) map = AffineMap(); else map = builder.getAffineMap(numDimOperands, dimsAndSymbols.size() - numDimOperands, exprs); return success(); } /// Parse the range and sizes affine map definition inline. /// /// affine-map ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr /// /// multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `) AffineMap AffineParser::parseAffineMapRange(unsigned numDims, unsigned numSymbols) { parseToken(Token::l_paren, "expected '(' at start of affine map range"); SmallVector<AffineExpr, 4> exprs; auto parseElt = [&]() -> ParseResult { auto elt = parseAffineExpr(); ParseResult res = elt ? success() : failure(); exprs.push_back(elt); return res; }; // Parse a multi-dimensional affine expression (a comma-separated list of // 1-d affine expressions); the list cannot be empty. Grammar: // multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `) if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, false)) return AffineMap(); // Parsed a valid affine map. return builder.getAffineMap(numDims, numSymbols, exprs); } /// Parse an affine constraint. /// affine-constraint ::= affine-expr `>=` `0` /// | affine-expr `==` `0` /// /// isEq is set to true if the parsed constraint is an equality, false if it /// is an inequality (greater than or equal). /// AffineExpr AffineParser::parseAffineConstraint(bool *isEq) { AffineExpr expr = parseAffineExpr(); if (!expr) return nullptr; if (consumeIf(Token::greater) && consumeIf(Token::equal) && getToken().is(Token::integer)) { auto dim = getToken().getUnsignedIntegerValue(); if (dim.hasValue() && dim.getValue() == 0) { consumeToken(Token::integer); *isEq = false; return expr; } return (emitError("expected '0' after '>='"), nullptr); } if (consumeIf(Token::equal) && consumeIf(Token::equal) && getToken().is(Token::integer)) { auto dim = getToken().getUnsignedIntegerValue(); if (dim.hasValue() && dim.getValue() == 0) { consumeToken(Token::integer); *isEq = true; return expr; } return (emitError("expected '0' after '=='"), nullptr); } return (emitError("expected '== 0' or '>= 0' at end of affine constraint"), nullptr); } /// Parse the constraints that are part of an integer set definition. /// integer-set-inline /// ::= dim-and-symbol-id-lists `:` /// '(' affine-constraint-conjunction? ')' /// affine-constraint-conjunction ::= affine-constraint (`,` /// affine-constraint)* /// IntegerSet AffineParser::parseIntegerSetConstraints(unsigned numDims, unsigned numSymbols) { if (parseToken(Token::l_paren, "expected '(' at start of integer set constraint list")) return IntegerSet(); SmallVector<AffineExpr, 4> constraints; SmallVector<bool, 4> isEqs; auto parseElt = [&]() -> ParseResult { bool isEq; auto elt = parseAffineConstraint(&isEq); ParseResult res = elt ? success() : failure(); if (elt) { constraints.push_back(elt); isEqs.push_back(isEq); } return res; }; // Parse a list of affine constraints (comma-separated). if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true)) return IntegerSet(); // If no constraints were parsed, then treat this as a degenerate 'true' case. if (constraints.empty()) { /* 0 == 0 */ auto zero = getAffineConstantExpr(0, getContext()); return builder.getIntegerSet(numDims, numSymbols, zero, true); } // Parsed a valid integer set. return builder.getIntegerSet(numDims, numSymbols, constraints, isEqs); } /// Parse an ambiguous reference to either and affine map or an integer set. ParseResult Parser::parseAffineMapOrIntegerSetReference(AffineMap &map, IntegerSet &set) { return AffineParser(state).parseAffineMapOrIntegerSetInline(map, set); } /// Parse an AffineMap of SSA ids. The callback 'parseElement' is used to /// parse SSA value uses encountered while parsing affine expressions. ParseResult Parser::parseAffineMapOfSSAIds( AffineMap &map, llvm::function_ref<ParseResult(bool)> parseElement) { return AffineParser(state, /*allowParsingSSAIds=*/true, parseElement) .parseAffineMapOfSSAIds(map); } //===----------------------------------------------------------------------===// // OperationParser //===----------------------------------------------------------------------===// namespace { /// This class provides support for parsing operations and regions of /// operations. class OperationParser : public Parser { public: OperationParser(ParserState &state, ModuleOp moduleOp) : Parser(state), opBuilder(moduleOp.getBodyRegion()), moduleOp(moduleOp) { } ~OperationParser(); /// After parsing is finished, this function must be called to see if there /// are any remaining issues. ParseResult finalize(); //===--------------------------------------------------------------------===// // SSA Value Handling //===--------------------------------------------------------------------===// /// This represents a use of an SSA value in the program. The first two /// entries in the tuple are the name and result number of a reference. The /// third is the location of the reference, which is used in case this ends /// up being a use of an undefined value. struct SSAUseInfo { StringRef name; // Value name, e.g. %42 or %abc unsigned number; // Number, specified with #12 SMLoc loc; // Location of first definition or use. }; /// Push a new SSA name scope to the parser. void pushSSANameScope(bool isIsolated); /// Pop the last SSA name scope from the parser. ParseResult popSSANameScope(); /// Register a definition of a value with the symbol table. ParseResult addDefinition(SSAUseInfo useInfo, Value *value); /// Parse an optional list of SSA uses into 'results'. ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results); /// Parse a single SSA use into 'result'. ParseResult parseSSAUse(SSAUseInfo &result); /// Given a reference to an SSA value and its type, return a reference. This /// returns null on failure. Value *resolveSSAUse(SSAUseInfo useInfo, Type type); ParseResult parseSSADefOrUseAndType( const std::function<ParseResult(SSAUseInfo, Type)> &action); ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value *> &results); /// Return the location of the value identified by its name and number if it /// has been already reference. llvm::Optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) { auto &values = isolatedNameScopes.back().values; if (!values.count(name) || number >= values[name].size()) return {}; if (values[name][number].first) return values[name][number].second; return {}; } //===--------------------------------------------------------------------===// // Operation Parsing //===--------------------------------------------------------------------===// /// Parse an operation instance. ParseResult parseOperation(); /// Parse a single operation successor and its operand list. ParseResult parseSuccessorAndUseList(Block *&dest, SmallVectorImpl<Value *> &operands); /// Parse a comma-separated list of operation successors in brackets. ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations, SmallVectorImpl<SmallVector<Value *, 4>> &operands); /// Parse an operation instance that is in the generic form. Operation *parseGenericOperation(); /// Parse an operation instance that is in the generic form and insert it at /// the provided insertion point. Operation *parseGenericOperation(Block *insertBlock, Block::iterator insertPt); /// Parse an operation instance that is in the op-defined custom form. Operation *parseCustomOperation(); //===--------------------------------------------------------------------===// // Region Parsing //===--------------------------------------------------------------------===// /// Parse a region into 'region' with the provided entry block arguments. /// 'isIsolatedNameScope' indicates if the naming scope of this region is /// isolated from those above. ParseResult parseRegion(Region &region, ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments, bool isIsolatedNameScope = false); /// Parse a region body into 'region'. ParseResult parseRegionBody(Region &region); //===--------------------------------------------------------------------===// // Block Parsing //===--------------------------------------------------------------------===// /// Parse a new block into 'block'. ParseResult parseBlock(Block *&block); /// Parse a list of operations into 'block'. ParseResult parseBlockBody(Block *block); /// Parse a (possibly empty) list of block arguments. ParseResult parseOptionalBlockArgList(SmallVectorImpl<BlockArgument *> &results, Block *owner); /// Get the block with the specified name, creating it if it doesn't /// already exist. The location specified is the point of use, which allows /// us to diagnose references to blocks that are not defined precisely. Block *getBlockNamed(StringRef name, SMLoc loc); /// Define the block with the specified name. Returns the Block* or nullptr in /// the case of redefinition. Block *defineBlockNamed(StringRef name, SMLoc loc, Block *existing); private: /// Returns the info for a block at the current scope for the given name. std::pair<Block *, SMLoc> &getBlockInfoByName(StringRef name) { return blocksByName.back()[name]; } /// Insert a new forward reference to the given block. void insertForwardRef(Block *block, SMLoc loc) { forwardRef.back().try_emplace(block, loc); } /// Erase any forward reference to the given block. bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); } /// Record that a definition was added at the current scope. void recordDefinition(StringRef def); /// Get the value entry for the given SSA name. SmallVectorImpl<std::pair<Value *, SMLoc>> &getSSAValueEntry(StringRef name); /// Create a forward reference placeholder value with the given location and /// result type. Value *createForwardRefPlaceholder(SMLoc loc, Type type); /// Return true if this is a forward reference. bool isForwardRefPlaceholder(Value *value) { return forwardRefPlaceholders.count(value); } /// This struct represents an isolated SSA name scope. This scope may contain /// other nested non-isolated scopes. These scopes are used for operations /// that are known to be isolated to allow for reusing names within their /// regions, even if those names are used above. struct IsolatedSSANameScope { /// Record that a definition was added at the current scope. void recordDefinition(StringRef def) { definitionsPerScope.back().insert(def); } /// Push a nested name scope. void pushSSANameScope() { definitionsPerScope.push_back({}); } /// Pop a nested name scope. void popSSANameScope() { for (auto &def : definitionsPerScope.pop_back_val()) values.erase(def.getKey()); } /// This keeps track of all of the SSA values we are tracking for each name /// scope, indexed by their name. This has one entry per result number. llvm::StringMap<SmallVector<std::pair<Value *, SMLoc>, 1>> values; /// This keeps track of all of the values defined by a specific name scope. SmallVector<llvm::StringSet<>, 2> definitionsPerScope; }; /// A list of isolated name scopes. SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes; /// This keeps track of the block names as well as the location of the first /// reference for each nested name scope. This is used to diagnose invalid /// block references and memoize them. SmallVector<DenseMap<StringRef, std::pair<Block *, SMLoc>>, 2> blocksByName; SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef; /// These are all of the placeholders we've made along with the location of /// their first reference, to allow checking for use of undefined values. DenseMap<Value *, SMLoc> forwardRefPlaceholders; /// The builder used when creating parsed operation instances. OpBuilder opBuilder; /// The top level module operation. ModuleOp moduleOp; }; } // end anonymous namespace OperationParser::~OperationParser() { for (auto &fwd : forwardRefPlaceholders) { // Drop all uses of undefined forward declared reference and destroy // defining operation. fwd.first->dropAllUses(); fwd.first->getDefiningOp()->destroy(); } } /// After parsing is finished, this function must be called to see if there are /// any remaining issues. ParseResult OperationParser::finalize() { // Check for any forward references that are left. If we find any, error // out. if (!forwardRefPlaceholders.empty()) { SmallVector<std::pair<const char *, Value *>, 4> errors; // Iteration over the map isn't deterministic, so sort by source location. for (auto entry : forwardRefPlaceholders) errors.push_back({entry.second.getPointer(), entry.first}); llvm::array_pod_sort(errors.begin(), errors.end()); for (auto entry : errors) { auto loc = SMLoc::getFromPointer(entry.first); emitError(loc, "use of undeclared SSA value name"); } return failure(); } return success(); } //===----------------------------------------------------------------------===// // SSA Value Handling //===----------------------------------------------------------------------===// void OperationParser::pushSSANameScope(bool isIsolated) { blocksByName.push_back(DenseMap<StringRef, std::pair<Block *, SMLoc>>()); forwardRef.push_back(DenseMap<Block *, SMLoc>()); // Push back a new name definition scope. if (isIsolated) isolatedNameScopes.push_back({}); isolatedNameScopes.back().pushSSANameScope(); } ParseResult OperationParser::popSSANameScope() { auto forwardRefInCurrentScope = forwardRef.pop_back_val(); // Verify that all referenced blocks were defined. if (!forwardRefInCurrentScope.empty()) { SmallVector<std::pair<const char *, Block *>, 4> errors; // Iteration over the map isn't deterministic, so sort by source location. for (auto entry : forwardRefInCurrentScope) { errors.push_back({entry.second.getPointer(), entry.first}); // Add this block to the top-level region to allow for automatic cleanup. moduleOp.getOperation()->getRegion(0).push_back(entry.first); } llvm::array_pod_sort(errors.begin(), errors.end()); for (auto entry : errors) { auto loc = SMLoc::getFromPointer(entry.first); emitError(loc, "reference to an undefined block"); } return failure(); } // Pop the next nested namescope. If there is only one internal namescope, // just pop the isolated scope. auto &currentNameScope = isolatedNameScopes.back(); if (currentNameScope.definitionsPerScope.size() == 1) isolatedNameScopes.pop_back(); else currentNameScope.popSSANameScope(); blocksByName.pop_back(); return success(); } /// Register a definition of a value with the symbol table. ParseResult OperationParser::addDefinition(SSAUseInfo useInfo, Value *value) { auto &entries = getSSAValueEntry(useInfo.name); // Make sure there is a slot for this value. if (entries.size() <= useInfo.number) entries.resize(useInfo.number + 1); // If we already have an entry for this, check to see if it was a definition // or a forward reference. if (auto *existing = entries[useInfo.number].first) { if (!isForwardRefPlaceholder(existing)) { return emitError(useInfo.loc) .append("redefinition of SSA value '", useInfo.name, "'") .attachNote(getEncodedSourceLocation(entries[useInfo.number].second)) .append("previously defined here"); } // If it was a forward reference, update everything that used it to use // the actual definition instead, delete the forward ref, and remove it // from our set of forward references we track. existing->replaceAllUsesWith(value); existing->getDefiningOp()->destroy(); forwardRefPlaceholders.erase(existing); } /// Record this definition for the current scope. entries[useInfo.number] = {value, useInfo.loc}; recordDefinition(useInfo.name); return success(); } /// Parse a (possibly empty) list of SSA operands. /// /// ssa-use-list ::= ssa-use (`,` ssa-use)* /// ssa-use-list-opt ::= ssa-use-list? /// ParseResult OperationParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) { if (getToken().isNot(Token::percent_identifier)) return success(); return parseCommaSeparatedList([&]() -> ParseResult { SSAUseInfo result; if (parseSSAUse(result)) return failure(); results.push_back(result); return success(); }); } /// Parse a SSA operand for an operation. /// /// ssa-use ::= ssa-id /// ParseResult OperationParser::parseSSAUse(SSAUseInfo &result) { result.name = getTokenSpelling(); result.number = 0; result.loc = getToken().getLoc(); if (parseToken(Token::percent_identifier, "expected SSA operand")) return failure(); // If we have an attribute ID, it is a result number. if (getToken().is(Token::hash_identifier)) { if (auto value = getToken().getHashIdentifierNumber()) result.number = value.getValue(); else return emitError("invalid SSA value result number"); consumeToken(Token::hash_identifier); } return success(); } /// Given an unbound reference to an SSA value and its type, return the value /// it specifies. This returns null on failure. Value *OperationParser::resolveSSAUse(SSAUseInfo useInfo, Type type) { auto &entries = getSSAValueEntry(useInfo.name); // If we have already seen a value of this name, return it. if (useInfo.number < entries.size() && entries[useInfo.number].first) { auto *result = entries[useInfo.number].first; // Check that the type matches the other uses. if (result->getType() == type) return result; emitError(useInfo.loc, "use of value '") .append(useInfo.name, "' expects different type than prior uses: ", type, " vs ", result->getType()) .attachNote(getEncodedSourceLocation(entries[useInfo.number].second)) .append("prior use here"); return nullptr; } // Make sure we have enough slots for this. if (entries.size() <= useInfo.number) entries.resize(useInfo.number + 1); // If the value has already been defined and this is an overly large result // number, diagnose that. if (entries[0].first && !isForwardRefPlaceholder(entries[0].first)) return (emitError(useInfo.loc, "reference to invalid result number"), nullptr); // Otherwise, this is a forward reference. Create a placeholder and remember // that we did so. auto *result = createForwardRefPlaceholder(useInfo.loc, type); entries[useInfo.number].first = result; entries[useInfo.number].second = useInfo.loc; return result; } /// Parse an SSA use with an associated type. /// /// ssa-use-and-type ::= ssa-use `:` type ParseResult OperationParser::parseSSADefOrUseAndType( const std::function<ParseResult(SSAUseInfo, Type)> &action) { SSAUseInfo useInfo; if (parseSSAUse(useInfo) || parseToken(Token::colon, "expected ':' and type for SSA operand")) return failure(); auto type = parseType(); if (!type) return failure(); return action(useInfo, type); } /// Parse a (possibly empty) list of SSA operands, followed by a colon, then /// followed by a type list. /// /// ssa-use-and-type-list /// ::= ssa-use-list ':' type-list-no-parens /// ParseResult OperationParser::parseOptionalSSAUseAndTypeList( SmallVectorImpl<Value *> &results) { SmallVector<SSAUseInfo, 4> valueIDs; if (parseOptionalSSAUseList(valueIDs)) return failure(); // If there were no operands, then there is no colon or type lists. if (valueIDs.empty()) return success(); SmallVector<Type, 4> types; if (parseToken(Token::colon, "expected ':' in operand list") || parseTypeListNoParens(types)) return failure(); if (valueIDs.size() != types.size()) return emitError("expected ") << valueIDs.size() << " types to match operand list"; results.reserve(valueIDs.size()); for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) { if (auto *value = resolveSSAUse(valueIDs[i], types[i])) results.push_back(value); else return failure(); } return success(); } /// Record that a definition was added at the current scope. void OperationParser::recordDefinition(StringRef def) { isolatedNameScopes.back().recordDefinition(def); } /// Get the value entry for the given SSA name. SmallVectorImpl<std::pair<Value *, SMLoc>> & OperationParser::getSSAValueEntry(StringRef name) { return isolatedNameScopes.back().values[name]; } /// Create and remember a new placeholder for a forward reference. Value *OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) { // Forward references are always created as operations, because we just need // something with a def/use chain. // // We create these placeholders as having an empty name, which we know // cannot be created through normal user input, allowing us to distinguish // them. auto name = OperationName("placeholder", getContext()); auto *op = Operation::create( getEncodedSourceLocation(loc), name, type, /*operands=*/{}, /*attributes=*/llvm::None, /*successors=*/{}, /*numRegions=*/0, /*resizableOperandList=*/false); forwardRefPlaceholders[op->getResult(0)] = loc; return op->getResult(0); } //===----------------------------------------------------------------------===// // Operation Parsing //===----------------------------------------------------------------------===// /// Parse an operation. /// /// operation ::= /// operation-result? string '(' ssa-use-list? ')' attribute-dict? /// `:` function-type trailing-location? /// operation-result ::= ssa-id ((`:` integer-literal) | (`,` ssa-id)*) `=` /// ParseResult OperationParser::parseOperation() { auto loc = getToken().getLoc(); SmallVector<std::pair<StringRef, SMLoc>, 1> resultIDs; size_t numExpectedResults; if (getToken().is(Token::percent_identifier)) { // Parse the first result id. resultIDs.emplace_back(getTokenSpelling(), loc); consumeToken(Token::percent_identifier); // If the next token is a ':', we parse the expected result count. if (consumeIf(Token::colon)) { // Check that the next token is an integer. if (!getToken().is(Token::integer)) return emitError("expected integer number of results"); // Check that number of results is > 0. auto val = getToken().getUInt64IntegerValue(); if (!val.hasValue() || val.getValue() < 1) return emitError("expected named operation to have atleast 1 result"); consumeToken(Token::integer); numExpectedResults = *val; } else { // Otherwise, this is a comma separated list of result ids. if (consumeIf(Token::comma)) { auto parseNextResult = [&]() -> ParseResult { // Parse the next result id. if (!getToken().is(Token::percent_identifier)) return emitError("expected valid ssa identifier"); resultIDs.emplace_back(getTokenSpelling(), getToken().getLoc()); consumeToken(Token::percent_identifier); return success(); }; if (parseCommaSeparatedList(parseNextResult)) return failure(); } numExpectedResults = resultIDs.size(); } if (parseToken(Token::equal, "expected '=' after SSA name")) return failure(); } Operation *op; if (getToken().is(Token::bare_identifier) || getToken().isKeyword()) op = parseCustomOperation(); else if (getToken().is(Token::string)) op = parseGenericOperation(); else return emitError("expected operation name in quotes"); // If parsing of the basic operation failed, then this whole thing fails. if (!op) return failure(); // If the operation had a name, register it. if (!resultIDs.empty()) { if (op->getNumResults() == 0) return emitError(loc, "cannot name an operation with no results"); if (numExpectedResults != op->getNumResults()) return emitError(loc, "operation defines ") << op->getNumResults() << " results but was provided " << numExpectedResults << " to bind"; // If the number of result names matches the number of operation results, we // can directly use the provided names. if (resultIDs.size() == op->getNumResults()) { for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) if (addDefinition({resultIDs[i].first, 0, resultIDs[i].second}, op->getResult(i))) return failure(); } else { // Otherwise, we use the same name for all results. StringRef name = resultIDs.front().first; for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) if (addDefinition({name, i, loc}, op->getResult(i))) return failure(); } } // Try to parse the optional trailing location. if (parseOptionalTrailingLocation(op)) return failure(); return success(); } /// Parse a single operation successor and its operand list. /// /// successor ::= block-id branch-use-list? /// branch-use-list ::= `(` ssa-use-list ':' type-list-no-parens `)` /// ParseResult OperationParser::parseSuccessorAndUseList(Block *&dest, SmallVectorImpl<Value *> &operands) { // Verify branch is identifier and get the matching block. if (!getToken().is(Token::caret_identifier)) return emitError("expected block name"); dest = getBlockNamed(getTokenSpelling(), getToken().getLoc()); consumeToken(); // Handle optional arguments. if (consumeIf(Token::l_paren) && (parseOptionalSSAUseAndTypeList(operands) || parseToken(Token::r_paren, "expected ')' to close argument list"))) { return failure(); } return success(); } /// Parse a comma-separated list of operation successors in brackets. /// /// successor-list ::= `[` successor (`,` successor )* `]` /// ParseResult OperationParser::parseSuccessors( SmallVectorImpl<Block *> &destinations, SmallVectorImpl<SmallVector<Value *, 4>> &operands) { if (parseToken(Token::l_square, "expected '['")) return failure(); auto parseElt = [this, &destinations, &operands]() { Block *dest; SmallVector<Value *, 4> destOperands; auto res = parseSuccessorAndUseList(dest, destOperands); destinations.push_back(dest); operands.push_back(destOperands); return res; }; return parseCommaSeparatedListUntil(Token::r_square, parseElt, /*allowEmptyList=*/false); } namespace { // RAII-style guard for cleaning up the regions in the operation state before // deleting them. Within the parser, regions may get deleted if parsing failed, // and other errors may be present, in praticular undominated uses. This makes // sure such uses are deleted. struct CleanupOpStateRegions { ~CleanupOpStateRegions() { SmallVector<Region *, 4> regionsToClean; regionsToClean.reserve(state.regions.size()); for (auto &region : state.regions) if (region) for (auto &block : *region) block.dropAllDefinedValueUses(); } OperationState &state; }; } // namespace Operation *OperationParser::parseGenericOperation() { // Get location information for the operation. auto srcLocation = getEncodedSourceLocation(getToken().getLoc()); auto name = getToken().getStringValue(); if (name.empty()) return (emitError("empty operation name is invalid"), nullptr); if (name.find('\0') != StringRef::npos) return (emitError("null character not allowed in operation name"), nullptr); consumeToken(Token::string); OperationState result(srcLocation, name); // Generic operations have a resizable operation list. result.setOperandListToResizable(); // Parse the operand list. SmallVector<SSAUseInfo, 8> operandInfos; if (parseToken(Token::l_paren, "expected '(' to start operand list") || parseOptionalSSAUseList(operandInfos) || parseToken(Token::r_paren, "expected ')' to end operand list")) { return nullptr; } // Parse the successor list but don't add successors to the result yet to // avoid messing up with the argument order. SmallVector<Block *, 2> successors; SmallVector<SmallVector<Value *, 4>, 2> successorOperands; if (getToken().is(Token::l_square)) { // Check if the operation is a known terminator. const AbstractOperation *abstractOp = result.name.getAbstractOperation(); if (abstractOp && !abstractOp->hasProperty(OperationProperty::Terminator)) return emitError("successors in non-terminator"), nullptr; if (parseSuccessors(successors, successorOperands)) return nullptr; } // Parse the region list. CleanupOpStateRegions guard{result}; if (consumeIf(Token::l_paren)) { do { // Create temporary regions with the top level region as parent. result.regions.emplace_back(new Region(moduleOp)); if (parseRegion(*result.regions.back(), /*entryArguments=*/{})) return nullptr; } while (consumeIf(Token::comma)); if (parseToken(Token::r_paren, "expected ')' to end region list")) return nullptr; } if (getToken().is(Token::l_brace)) { if (parseAttributeDict(result.attributes)) return nullptr; } if (parseToken(Token::colon, "expected ':' followed by operation type")) return nullptr; auto typeLoc = getToken().getLoc(); auto type = parseType(); if (!type) return nullptr; auto fnType = type.dyn_cast<FunctionType>(); if (!fnType) return (emitError(typeLoc, "expected function type"), nullptr); result.addTypes(fnType.getResults()); // Check that we have the right number of types for the operands. auto operandTypes = fnType.getInputs(); if (operandTypes.size() != operandInfos.size()) { auto plural = "s"[operandInfos.size() == 1]; return (emitError(typeLoc, "expected ") << operandInfos.size() << " operand type" << plural << " but had " << operandTypes.size(), nullptr); } // Resolve all of the operands. for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) { result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i])); if (!result.operands.back()) return nullptr; } // Add the sucessors, and their operands after the proper operands. for (const auto &succ : llvm::zip(successors, successorOperands)) { Block *successor = std::get<0>(succ); const SmallVector<Value *, 4> &operands = std::get<1>(succ); result.addSuccessor(successor, operands); } return opBuilder.createOperation(result); } Operation *OperationParser::parseGenericOperation(Block *insertBlock, Block::iterator insertPt) { OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder); opBuilder.setInsertionPoint(insertBlock, insertPt); return parseGenericOperation(); } namespace { class CustomOpAsmParser : public OpAsmParser { public: CustomOpAsmParser(SMLoc nameLoc, const AbstractOperation *opDefinition, OperationParser &parser) : nameLoc(nameLoc), opDefinition(opDefinition), parser(parser) {} /// Parse an instance of the operation described by 'opDefinition' into the /// provided operation state. ParseResult parseOperation(OperationState &opState) { if (opDefinition->parseAssembly(*this, opState)) return failure(); return success(); } Operation *parseGenericOperation(Block *insertBlock, Block::iterator insertPt) final { return parser.parseGenericOperation(insertBlock, insertPt); } //===--------------------------------------------------------------------===// // Utilities //===--------------------------------------------------------------------===// /// Return if any errors were emitted during parsing. bool didEmitError() const { return emittedError; } /// Emit a diagnostic at the specified location and return failure. InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override { emittedError = true; return parser.emitError(loc, "custom op '" + opDefinition->name + "' " + message); } llvm::SMLoc getCurrentLocation() override { return parser.getToken().getLoc(); } Builder &getBuilder() const override { return parser.builder; } llvm::SMLoc getNameLoc() const override { return nameLoc; } //===--------------------------------------------------------------------===// // Token Parsing //===--------------------------------------------------------------------===// /// Parse a `->` token. ParseResult parseArrow() override { return parser.parseToken(Token::arrow, "expected '->'"); } /// Parses a `->` if present. ParseResult parseOptionalArrow() override { return success(parser.consumeIf(Token::arrow)); } /// Parse a `:` token. ParseResult parseColon() override { return parser.parseToken(Token::colon, "expected ':'"); } /// Parse a `:` token if present. ParseResult parseOptionalColon() override { return success(parser.consumeIf(Token::colon)); } /// Parse a `,` token. ParseResult parseComma() override { return parser.parseToken(Token::comma, "expected ','"); } /// Parse a `,` token if present. ParseResult parseOptionalComma() override { return success(parser.consumeIf(Token::comma)); } /// Parses a `...` if present. ParseResult parseOptionalEllipsis() override { return success(parser.consumeIf(Token::ellipsis)); } /// Parse a `=` token. ParseResult parseEqual() override { return parser.parseToken(Token::equal, "expected '='"); } /// Parse a `(` token. ParseResult parseLParen() override { return parser.parseToken(Token::l_paren, "expected '('"); } /// Parses a '(' if present. ParseResult parseOptionalLParen() override { return success(parser.consumeIf(Token::l_paren)); } /// Parse a `)` token. ParseResult parseRParen() override { return parser.parseToken(Token::r_paren, "expected ')'"); } /// Parses a ')' if present. ParseResult parseOptionalRParen() override { return success(parser.consumeIf(Token::r_paren)); } /// Parse a `[` token. ParseResult parseLSquare() override { return parser.parseToken(Token::l_square, "expected '['"); } /// Parses a '[' if present. ParseResult parseOptionalLSquare() override { return success(parser.consumeIf(Token::l_square)); } /// Parse a `]` token. ParseResult parseRSquare() override { return parser.parseToken(Token::r_square, "expected ']'"); } /// Parses a ']' if present. ParseResult parseOptionalRSquare() override { return success(parser.consumeIf(Token::r_square)); } //===--------------------------------------------------------------------===// // Attribute Parsing //===--------------------------------------------------------------------===// /// Parse an arbitrary attribute of a given type and return it in result. This /// also adds the attribute to the specified attribute list with the specified /// name. ParseResult parseAttribute(Attribute &result, Type type, StringRef attrName, SmallVectorImpl<NamedAttribute> &attrs) override { result = parser.parseAttribute(type); if (!result) return failure(); attrs.push_back(parser.builder.getNamedAttr(attrName, result)); return success(); } /// Parse a named dictionary into 'result' if it is present. ParseResult parseOptionalAttributeDict(SmallVectorImpl<NamedAttribute> &result) override { if (parser.getToken().isNot(Token::l_brace)) return success(); return parser.parseAttributeDict(result); } //===--------------------------------------------------------------------===// // Identifier Parsing //===--------------------------------------------------------------------===// /// Returns if the current token corresponds to a keyword. bool isCurrentTokenAKeyword() const { return parser.getToken().is(Token::bare_identifier) || parser.getToken().isKeyword(); } /// Parse the given keyword if present. ParseResult parseOptionalKeyword(StringRef keyword) override { // Check that the current token has the same spelling. if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword) return failure(); parser.consumeToken(); return success(); } /// Parse a keyword, if present, into 'keyword'. ParseResult parseOptionalKeyword(StringRef *keyword) override { // Check that the current token is a keyword. if (!isCurrentTokenAKeyword()) return failure(); *keyword = parser.getTokenSpelling(); parser.consumeToken(); return success(); } /// Parse an @-identifier and store it (without the '@' symbol) in a string /// attribute named 'attrName'. ParseResult parseSymbolName(StringAttr &result, StringRef attrName, SmallVectorImpl<NamedAttribute> &attrs) override { if (parser.getToken().isNot(Token::at_identifier)) return failure(); result = getBuilder().getStringAttr(parser.getTokenSpelling().drop_front()); attrs.push_back(getBuilder().getNamedAttr(attrName, result)); parser.consumeToken(); return success(); } //===--------------------------------------------------------------------===// // Operand Parsing //===--------------------------------------------------------------------===// /// Parse a single operand. ParseResult parseOperand(OperandType &result) override { OperationParser::SSAUseInfo useInfo; if (parser.parseSSAUse(useInfo)) return failure(); result = {useInfo.loc, useInfo.name, useInfo.number}; return success(); } /// Parse zero or more SSA comma-separated operand references with a specified /// surrounding delimiter, and an optional required operand count. ParseResult parseOperandList(SmallVectorImpl<OperandType> &result, int requiredOperandCount = -1, Delimiter delimiter = Delimiter::None) override { return parseOperandOrRegionArgList(result, /*isOperandList=*/true, requiredOperandCount, delimiter); } /// Parse zero or more SSA comma-separated operand or region arguments with /// optional surrounding delimiter and required operand count. ParseResult parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result, bool isOperandList, int requiredOperandCount = -1, Delimiter delimiter = Delimiter::None) { auto startLoc = parser.getToken().getLoc(); // Handle delimiters. switch (delimiter) { case Delimiter::None: // Don't check for the absence of a delimiter if the number of operands // is unknown (and hence the operand list could be empty). if (requiredOperandCount == -1) break; // Token already matches an identifier and so can't be a delimiter. if (parser.getToken().is(Token::percent_identifier)) break; // Test against known delimiters. if (parser.getToken().is(Token::l_paren) || parser.getToken().is(Token::l_square)) return emitError(startLoc, "unexpected delimiter"); return emitError(startLoc, "invalid operand"); case Delimiter::OptionalParen: if (parser.getToken().isNot(Token::l_paren)) return success(); LLVM_FALLTHROUGH; case Delimiter::Paren: if (parser.parseToken(Token::l_paren, "expected '(' in operand list")) return failure(); break; case Delimiter::OptionalSquare: if (parser.getToken().isNot(Token::l_square)) return success(); LLVM_FALLTHROUGH; case Delimiter::Square: if (parser.parseToken(Token::l_square, "expected '[' in operand list")) return failure(); break; } // Check for zero operands. if (parser.getToken().is(Token::percent_identifier)) { do { OperandType operandOrArg; if (isOperandList ? parseOperand(operandOrArg) : parseRegionArgument(operandOrArg)) return failure(); result.push_back(operandOrArg); } while (parser.consumeIf(Token::comma)); } // Handle delimiters. If we reach here, the optional delimiters were // present, so we need to parse their closing one. switch (delimiter) { case Delimiter::None: break; case Delimiter::OptionalParen: case Delimiter::Paren: if (parser.parseToken(Token::r_paren, "expected ')' in operand list")) return failure(); break; case Delimiter::OptionalSquare: case Delimiter::Square: if (parser.parseToken(Token::r_square, "expected ']' in operand list")) return failure(); break; } if (requiredOperandCount != -1 && result.size() != static_cast<size_t>(requiredOperandCount)) return emitError(startLoc, "expected ") << requiredOperandCount << " operands"; return success(); } /// Parse zero or more trailing SSA comma-separated trailing operand /// references with a specified surrounding delimiter, and an optional /// required operand count. A leading comma is expected before the operands. ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result, int requiredOperandCount, Delimiter delimiter) override { if (parser.getToken().is(Token::comma)) { parseComma(); return parseOperandList(result, requiredOperandCount, delimiter); } if (requiredOperandCount != -1) return emitError(parser.getToken().getLoc(), "expected ") << requiredOperandCount << " operands"; return success(); } /// Resolve an operand to an SSA value, emitting an error on failure. ParseResult resolveOperand(const OperandType &operand, Type type, SmallVectorImpl<Value *> &result) override { OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number, operand.location}; if (auto *value = parser.resolveSSAUse(operandInfo, type)) { result.push_back(value); return success(); } return failure(); } /// Parse an AffineMap of SSA ids. ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands, Attribute &mapAttr, StringRef attrName, SmallVectorImpl<NamedAttribute> &attrs) override { SmallVector<OperandType, 2> dimOperands; SmallVector<OperandType, 1> symOperands; auto parseElement = [&](bool isSymbol) -> ParseResult { OperandType operand; if (parseOperand(operand)) return failure(); if (isSymbol) symOperands.push_back(operand); else dimOperands.push_back(operand); return success(); }; AffineMap map; if (parser.parseAffineMapOfSSAIds(map, parseElement)) return failure(); // Add AffineMap attribute. if (map) { mapAttr = parser.builder.getAffineMapAttr(map); attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr)); } // Add dim operands before symbol operands in 'operands'. operands.assign(dimOperands.begin(), dimOperands.end()); operands.append(symOperands.begin(), symOperands.end()); return success(); } //===--------------------------------------------------------------------===// // Region Parsing //===--------------------------------------------------------------------===// /// Parse a region that takes `arguments` of `argTypes` types. This /// effectively defines the SSA values of `arguments` and assignes their type. ParseResult parseRegion(Region &region, ArrayRef<OperandType> arguments, ArrayRef<Type> argTypes, bool enableNameShadowing) override { assert(arguments.size() == argTypes.size() && "mismatching number of arguments and types"); SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2> regionArguments; for (const auto &pair : llvm::zip(arguments, argTypes)) { const OperandType &operand = std::get<0>(pair); Type type = std::get<1>(pair); OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number, operand.location}; regionArguments.emplace_back(operandInfo, type); } // Try to parse the region. assert((!enableNameShadowing || opDefinition->hasProperty(OperationProperty::IsolatedFromAbove)) && "name shadowing is only allowed on isolated regions"); if (parser.parseRegion(region, regionArguments, enableNameShadowing)) return failure(); return success(); } /// Parses a region if present. ParseResult parseOptionalRegion(Region &region, ArrayRef<OperandType> arguments, ArrayRef<Type> argTypes, bool enableNameShadowing) override { if (parser.getToken().isNot(Token::l_brace)) return success(); return parseRegion(region, arguments, argTypes, enableNameShadowing); } /// Parse a region argument. The type of the argument will be resolved later /// by a call to `parseRegion`. ParseResult parseRegionArgument(OperandType &argument) override { return parseOperand(argument); } /// Parse a region argument if present. ParseResult parseOptionalRegionArgument(OperandType &argument) override { if (parser.getToken().isNot(Token::percent_identifier)) return success(); return parseRegionArgument(argument); } ParseResult parseRegionArgumentList(SmallVectorImpl<OperandType> &result, int requiredOperandCount = -1, Delimiter delimiter = Delimiter::None) override { return parseOperandOrRegionArgList(result, /*isOperandList=*/false, requiredOperandCount, delimiter); } //===--------------------------------------------------------------------===// // Successor Parsing //===--------------------------------------------------------------------===// /// Parse a single operation successor and its operand list. ParseResult parseSuccessorAndUseList(Block *&dest, SmallVectorImpl<Value *> &operands) override { return parser.parseSuccessorAndUseList(dest, operands); } //===--------------------------------------------------------------------===// // Type Parsing //===--------------------------------------------------------------------===// /// Parse a type. ParseResult parseType(Type &result) override { return failure(!(result = parser.parseType())); } /// Parse an optional arrow followed by a type list. ParseResult parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override { if (!parser.consumeIf(Token::arrow)) return success(); return parser.parseFunctionResultTypes(result); } /// Parse a colon followed by a type. ParseResult parseColonType(Type &result) override { return failure(parser.parseToken(Token::colon, "expected ':'") || !(result = parser.parseType())); } /// Parse a colon followed by a type list, which must have at least one type. ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override { if (parser.parseToken(Token::colon, "expected ':'")) return failure(); return parser.parseTypeListNoParens(result); } /// Parse an optional colon followed by a type list, which if present must /// have at least one type. ParseResult parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override { if (!parser.consumeIf(Token::colon)) return success(); return parser.parseTypeListNoParens(result); } private: /// The source location of the operation name. SMLoc nameLoc; /// The abstract information of the operation. const AbstractOperation *opDefinition; /// The main operation parser. OperationParser &parser; /// A flag that indicates if any errors were emitted during parsing. bool emittedError = false; }; } // end anonymous namespace. Operation *OperationParser::parseCustomOperation() { auto opLoc = getToken().getLoc(); auto opName = getTokenSpelling(); auto *opDefinition = AbstractOperation::lookup(opName, getContext()); if (!opDefinition && !opName.contains('.')) { // If the operation name has no namespace prefix we treat it as a standard // operation and prefix it with "std". // TODO: Would it be better to just build a mapping of the registered // operations in the standard dialect? opDefinition = AbstractOperation::lookup(Twine("std." + opName).str(), getContext()); } if (!opDefinition) { emitError(opLoc) << "custom op '" << opName << "' is unknown"; return nullptr; } consumeToken(); // If the custom op parser crashes, produce some indication to help // debugging. std::string opNameStr = opName.str(); llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'", opNameStr.c_str()); // Get location information for the operation. auto srcLocation = getEncodedSourceLocation(opLoc); // Have the op implementation take a crack and parsing this. OperationState opState(srcLocation, opDefinition->name); CleanupOpStateRegions guard{opState}; CustomOpAsmParser opAsmParser(opLoc, opDefinition, *this); if (opAsmParser.parseOperation(opState)) return nullptr; // If it emitted an error, we failed. if (opAsmParser.didEmitError()) return nullptr; // Otherwise, we succeeded. Use the state it parsed as our op information. return opBuilder.createOperation(opState); } //===----------------------------------------------------------------------===// // Region Parsing //===----------------------------------------------------------------------===// /// Region. /// /// region ::= '{' region-body /// ParseResult OperationParser::parseRegion( Region &region, ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments, bool isIsolatedNameScope) { // Parse the '{'. if (parseToken(Token::l_brace, "expected '{' to begin a region")) return failure(); // Check for an empty region. if (entryArguments.empty() && consumeIf(Token::r_brace)) return success(); auto currentPt = opBuilder.saveInsertionPoint(); // Push a new named value scope. pushSSANameScope(isIsolatedNameScope); // Parse the first block directly to allow for it to be unnamed. Block *block = new Block(); // Add arguments to the entry block. if (!entryArguments.empty()) { for (auto &placeholderArgPair : entryArguments) { auto &argInfo = placeholderArgPair.first; // Ensure that the argument was not already defined. if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) { return emitError(argInfo.loc, "region entry argument '" + argInfo.name + "' is already in use") .attachNote(getEncodedSourceLocation(*defLoc)) << "previously referenced here"; } if (addDefinition(placeholderArgPair.first, block->addArgument(placeholderArgPair.second))) { delete block; return failure(); } } // If we had named arguments, then don't allow a block name. if (getToken().is(Token::caret_identifier)) return emitError("invalid block name in region with named arguments"); } if (parseBlock(block)) { delete block; return failure(); } // Verify that no other arguments were parsed. if (!entryArguments.empty() && block->getNumArguments() > entryArguments.size()) { delete block; return emitError("entry block arguments were already defined"); } // Parse the rest of the region. region.push_back(block); if (parseRegionBody(region)) return failure(); // Pop the SSA value scope for this region. if (popSSANameScope()) return failure(); // Reset the original insertion point. opBuilder.restoreInsertionPoint(currentPt); return success(); } /// Region. /// /// region-body ::= block* '}' /// ParseResult OperationParser::parseRegionBody(Region &region) { // Parse the list of blocks. while (!consumeIf(Token::r_brace)) { Block *newBlock = nullptr; if (parseBlock(newBlock)) return failure(); region.push_back(newBlock); } return success(); } //===----------------------------------------------------------------------===// // Block Parsing //===----------------------------------------------------------------------===// /// Block declaration. /// /// block ::= block-label? operation* /// block-label ::= block-id block-arg-list? `:` /// block-id ::= caret-id /// block-arg-list ::= `(` ssa-id-and-type-list? `)` /// ParseResult OperationParser::parseBlock(Block *&block) { // The first block of a region may already exist, if it does the caret // identifier is optional. if (block && getToken().isNot(Token::caret_identifier)) return parseBlockBody(block); SMLoc nameLoc = getToken().getLoc(); auto name = getTokenSpelling(); if (parseToken(Token::caret_identifier, "expected block name")) return failure(); block = defineBlockNamed(name, nameLoc, block); // Fail if the block was already defined. if (!block) return emitError(nameLoc, "redefinition of block '") << name << "'"; // If an argument list is present, parse it. if (consumeIf(Token::l_paren)) { SmallVector<BlockArgument *, 8> bbArgs; if (parseOptionalBlockArgList(bbArgs, block) || parseToken(Token::r_paren, "expected ')' to end argument list")) return failure(); } if (parseToken(Token::colon, "expected ':' after block name")) return failure(); return parseBlockBody(block); } ParseResult OperationParser::parseBlockBody(Block *block) { // Set the insertion point to the end of the block to parse. opBuilder.setInsertionPointToEnd(block); // Parse the list of operations that make up the body of the block. while (getToken().isNot(Token::caret_identifier, Token::r_brace)) if (parseOperation()) return failure(); return success(); } /// Get the block with the specified name, creating it if it doesn't already /// exist. The location specified is the point of use, which allows /// us to diagnose references to blocks that are not defined precisely. Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) { auto &blockAndLoc = getBlockInfoByName(name); if (!blockAndLoc.first) { blockAndLoc = {new Block(), loc}; insertForwardRef(blockAndLoc.first, loc); } return blockAndLoc.first; } /// Define the block with the specified name. Returns the Block* or nullptr in /// the case of redefinition. Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc, Block *existing) { auto &blockAndLoc = getBlockInfoByName(name); if (!blockAndLoc.first) { // If the caller provided a block, use it. Otherwise create a new one. if (!existing) existing = new Block(); blockAndLoc.first = existing; blockAndLoc.second = loc; return blockAndLoc.first; } // Forward declarations are removed once defined, so if we are defining a // existing block and it is not a forward declaration, then it is a // redeclaration. if (!eraseForwardRef(blockAndLoc.first)) return nullptr; return blockAndLoc.first; } /// Parse a (possibly empty) list of SSA operands with types as block arguments. /// /// ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)* /// ParseResult OperationParser::parseOptionalBlockArgList( SmallVectorImpl<BlockArgument *> &results, Block *owner) { if (getToken().is(Token::r_brace)) return success(); // If the block already has arguments, then we're handling the entry block. // Parse and register the names for the arguments, but do not add them. bool definingExistingArgs = owner->getNumArguments() != 0; unsigned nextArgument = 0; return parseCommaSeparatedList([&]() -> ParseResult { return parseSSADefOrUseAndType( [&](SSAUseInfo useInfo, Type type) -> ParseResult { // If this block did not have existing arguments, define a new one. if (!definingExistingArgs) return addDefinition(useInfo, owner->addArgument(type)); // Otherwise, ensure that this argument has already been created. if (nextArgument >= owner->getNumArguments()) return emitError("too many arguments specified in argument list"); // Finally, make sure the existing argument has the correct type. auto *arg = owner->getArgument(nextArgument++); if (arg->getType() != type) return emitError("argument and block argument type mismatch"); return addDefinition(useInfo, arg); }); }); } //===----------------------------------------------------------------------===// // Top-level entity parsing. //===----------------------------------------------------------------------===// namespace { /// This parser handles entities that are only valid at the top level of the /// file. class ModuleParser : public Parser { public: explicit ModuleParser(ParserState &state) : Parser(state) {} ParseResult parseModule(ModuleOp module); private: /// Parse an attribute alias declaration. ParseResult parseAttributeAliasDef(); /// Parse an attribute alias declaration. ParseResult parseTypeAliasDef(); }; } // end anonymous namespace /// Parses an attribute alias declaration. /// /// attribute-alias-def ::= '#' alias-name `=` attribute-value /// ParseResult ModuleParser::parseAttributeAliasDef() { assert(getToken().is(Token::hash_identifier)); StringRef aliasName = getTokenSpelling().drop_front(); // Check for redefinitions. if (getState().attributeAliasDefinitions.count(aliasName) > 0) return emitError("redefinition of attribute alias id '" + aliasName + "'"); // Make sure this isn't invading the dialect attribute namespace. if (aliasName.contains('.')) return emitError("attribute names with a '.' are reserved for " "dialect-defined names"); consumeToken(Token::hash_identifier); // Parse the '='. if (parseToken(Token::equal, "expected '=' in attribute alias definition")) return failure(); // Parse the attribute value. Attribute attr = parseAttribute(); if (!attr) return failure(); getState().attributeAliasDefinitions[aliasName] = attr; return success(); } /// Parse a type alias declaration. /// /// type-alias-def ::= '!' alias-name `=` 'type' type /// ParseResult ModuleParser::parseTypeAliasDef() { assert(getToken().is(Token::exclamation_identifier)); StringRef aliasName = getTokenSpelling().drop_front(); // Check for redefinitions. if (getState().typeAliasDefinitions.count(aliasName) > 0) return emitError("redefinition of type alias id '" + aliasName + "'"); // Make sure this isn't invading the dialect type namespace. if (aliasName.contains('.')) return emitError("type names with a '.' are reserved for " "dialect-defined names"); consumeToken(Token::exclamation_identifier); // Parse the '=' and 'type'. if (parseToken(Token::equal, "expected '=' in type alias definition") || parseToken(Token::kw_type, "expected 'type' in type alias definition")) return failure(); // Parse the type. Type aliasedType = parseType(); if (!aliasedType) return failure(); // Register this alias with the parser state. getState().typeAliasDefinitions.try_emplace(aliasName, aliasedType); return success(); } /// This is the top-level module parser. ParseResult ModuleParser::parseModule(ModuleOp module) { OperationParser opParser(getState(), module); // Module itself is a name scope. opParser.pushSSANameScope(/*isIsolated=*/true); while (true) { switch (getToken().getKind()) { default: // Parse a top-level operation. if (opParser.parseOperation()) return failure(); break; // If we got to the end of the file, then we're done. case Token::eof: { if (opParser.finalize()) return failure(); // Handle the case where the top level module was explicitly defined. auto &bodyBlocks = module.getBodyRegion().getBlocks(); auto &operations = bodyBlocks.front().getOperations(); assert(!operations.empty() && "expected a valid module terminator"); // Check that the first operation is a module, and it is the only // non-terminator operation. ModuleOp nested = dyn_cast<ModuleOp>(operations.front()); if (nested && std::next(operations.begin(), 2) == operations.end()) { // Merge the data of the nested module operation into 'module'. module.setLoc(nested.getLoc()); module.setAttrs(nested.getOperation()->getAttrList()); bodyBlocks.splice(bodyBlocks.end(), nested.getBodyRegion().getBlocks()); // Erase the original module body. bodyBlocks.pop_front(); } return opParser.popSSANameScope(); } // If we got an error token, then the lexer already emitted an error, just // stop. Someday we could introduce error recovery if there was demand // for it. case Token::error: return failure(); // Parse an attribute alias. case Token::hash_identifier: if (parseAttributeAliasDef()) return failure(); break; // Parse a type alias. case Token::exclamation_identifier: if (parseTypeAliasDef()) return failure(); break; } } } //===----------------------------------------------------------------------===// /// This parses the file specified by the indicated SourceMgr and returns an /// MLIR module if it was valid. If not, it emits diagnostics and returns /// null. OwningModuleRef mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr, MLIRContext *context) { auto sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID()); // This is the result module we are parsing into. OwningModuleRef module(ModuleOp::create(FileLineColLoc::get( sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0, context))); ParserState state(sourceMgr, context); if (ModuleParser(state).parseModule(*module)) return nullptr; // Make sure the parse module has no other structural problems detected by // the verifier. if (failed(verify(*module))) return nullptr; return module; } /// This parses the file specified by the indicated filename and returns an /// MLIR module if it was valid. If not, the error message is emitted through /// the error handler registered in the context, and a null pointer is returned. OwningModuleRef mlir::parseSourceFile(StringRef filename, MLIRContext *context) { llvm::SourceMgr sourceMgr; return parseSourceFile(filename, sourceMgr, context); } /// This parses the file specified by the indicated filename using the provided /// SourceMgr and returns an MLIR module if it was valid. If not, the error /// message is emitted through the error handler registered in the context, and /// a null pointer is returned. OwningModuleRef mlir::parseSourceFile(StringRef filename, llvm::SourceMgr &sourceMgr, MLIRContext *context) { if (sourceMgr.getNumBuffers() != 0) { // TODO(b/136086478): Extend to support multiple buffers. emitError(mlir::UnknownLoc::get(context), "only main buffer parsed at the moment"); return nullptr; } auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename); if (std::error_code error = file_or_err.getError()) { emitError(mlir::UnknownLoc::get(context), "could not open input file " + filename); return nullptr; } // Load the MLIR module. sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc()); return parseSourceFile(sourceMgr, context); } /// This parses the program string to a MLIR module if it was valid. If not, /// it emits diagnostics and returns null. OwningModuleRef mlir::parseSourceString(StringRef moduleStr, MLIRContext *context) { auto memBuffer = MemoryBuffer::getMemBuffer(moduleStr); if (!memBuffer) return nullptr; SourceMgr sourceMgr; sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc()); return parseSourceFile(sourceMgr, context); } Type mlir::parseType(llvm::StringRef typeStr, MLIRContext *context, size_t &numRead) { SourceMgr sourceMgr; auto memBuffer = MemoryBuffer::getMemBuffer(typeStr, /*BufferName=*/"<mlir_type_buffer>", /*RequiresNullTerminator=*/false); sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc()); SourceMgrDiagnosticHandler sourceMgrHandler(sourceMgr, context); ParserState state(sourceMgr, context); Parser parser(state); auto start = parser.getToken().getLoc(); auto ty = parser.parseType(); if (!ty) return Type(); auto end = parser.getToken().getLoc(); numRead = static_cast<size_t>(end.getPointer() - start.getPointer()); return ty; } Type mlir::parseType(llvm::StringRef typeStr, MLIRContext *context) { size_t numRead = 0; return parseType(typeStr, context, numRead); }
35.093809
80
0.640998
[ "shape", "vector" ]
33e6c83a06e9c29eb47e8110b2002accb18cef7b
37,670
hh
C++
cpp/roaring64map.hh
amosbird/CRoaring
18063cc5719461e8758972f2b039189d9553d171
[ "Apache-2.0" ]
null
null
null
cpp/roaring64map.hh
amosbird/CRoaring
18063cc5719461e8758972f2b039189d9553d171
[ "Apache-2.0" ]
null
null
null
cpp/roaring64map.hh
amosbird/CRoaring
18063cc5719461e8758972f2b039189d9553d171
[ "Apache-2.0" ]
null
null
null
/* A C++ header for 64-bit Roaring Bitmaps, implemented by way of a map of many 32-bit Roaring Bitmaps. */ #ifndef INCLUDE_ROARING_64_MAP_HH_ #define INCLUDE_ROARING_64_MAP_HH_ #include <algorithm> #include <cstdarg> // for va_list handling in bitmapOf() #include <cstdio> // for std::printf() in the printf() method #include <cstring> // for std::memcpy() #include <limits> #include <map> #include <new> #include <numeric> #include <stdexcept> #include <string> #include <utility> #include "roaring.hh" using roaring::Roaring; namespace roaring { class Roaring64MapSetBitForwardIterator; class Roaring64MapSetBitBiDirectionalIterator; class Roaring64Map { typedef api::roaring_bitmap_t roaring_bitmap_t; public: /** * Create an empty bitmap */ Roaring64Map() = default; /** * Construct a bitmap from a list of 32-bit integer values. */ Roaring64Map(size_t n, const uint32_t *data) { addMany(n, data); } /** * Construct a bitmap from a list of 64-bit integer values. */ Roaring64Map(size_t n, const uint64_t *data) { addMany(n, data); } /** * Construct a 64-bit map from a 32-bit one */ Roaring64Map(const Roaring &r) { emplaceOrInsert(0, r); } /** * Construct a roaring object from the C struct. * * Passing a NULL point is unsafe. */ Roaring64Map(roaring_bitmap_t *s) { emplaceOrInsert(0, s); } Roaring64Map(const Roaring64Map& r) : roarings(r.roarings), copyOnWrite(r.copyOnWrite) { } Roaring64Map(Roaring64Map&& r) : roarings(r.roarings), copyOnWrite(r.copyOnWrite) { } /** * Assignment operator. */ Roaring64Map &operator=(const Roaring64Map &r) { roarings = r.roarings; return *this; } /** * Construct a bitmap from a list of integer values. */ static Roaring64Map bitmapOf(size_t n...) { Roaring64Map ans; va_list vl; va_start(vl, n); for (size_t i = 0; i < n; i++) { ans.add(va_arg(vl, uint64_t)); } va_end(vl); return ans; } /** * Add value x * */ void add(uint32_t x) { roarings[0].add(x); roarings[0].setCopyOnWrite(copyOnWrite); } void add(uint64_t x) { roarings[highBytes(x)].add(lowBytes(x)); roarings[highBytes(x)].setCopyOnWrite(copyOnWrite); } /** * Add value x * Returns true if a new value was added, false if the value was already existing. */ bool addChecked(uint32_t x) { bool result = roarings[0].addChecked(x); roarings[0].setCopyOnWrite(copyOnWrite); return result; } bool addChecked(uint64_t x) { bool result = roarings[highBytes(x)].addChecked(lowBytes(x)); roarings[highBytes(x)].setCopyOnWrite(copyOnWrite); return result; } /** * Add value n_args from pointer vals * */ void addMany(size_t n_args, const uint32_t *vals) { for (size_t lcv = 0; lcv < n_args; lcv++) { roarings[0].add(vals[lcv]); roarings[0].setCopyOnWrite(copyOnWrite); } } void addMany(size_t n_args, const uint64_t *vals) { for (size_t lcv = 0; lcv < n_args; lcv++) { roarings[highBytes(vals[lcv])].add(lowBytes(vals[lcv])); roarings[highBytes(vals[lcv])].setCopyOnWrite(copyOnWrite); } } /** * Remove value x * */ void remove(uint32_t x) { roarings[0].remove(x); } void remove(uint64_t x) { auto roaring_iter = roarings.find(highBytes(x)); if (roaring_iter != roarings.cend()) roaring_iter->second.remove(lowBytes(x)); } /** * Remove value x * Returns true if a new value was removed, false if the value was not existing. */ bool removeChecked(uint32_t x) { return roarings[0].removeChecked(x); } bool removeChecked(uint64_t x) { auto roaring_iter = roarings.find(highBytes(x)); if (roaring_iter != roarings.cend()) return roaring_iter->second.removeChecked(lowBytes(x)); return false; } /** * Clear the bitmap */ void clear() { roarings.clear(); } /** * Return the largest value (if not empty) * */ uint64_t maximum() const { for (auto roaring_iter = roarings.crbegin(); roaring_iter != roarings.crend(); ++roaring_iter) { if (!roaring_iter->second.isEmpty()) { return uniteBytes(roaring_iter->first, roaring_iter->second.maximum()); } } // we put std::numeric_limits<>::max/min in parenthesis // to avoid a clash with the Windows.h header under Windows return (std::numeric_limits<uint64_t>::min)(); } /** * Return the smallest value (if not empty) * */ uint64_t minimum() const { for (auto roaring_iter = roarings.cbegin(); roaring_iter != roarings.cend(); ++roaring_iter) { if (!roaring_iter->second.isEmpty()) { return uniteBytes(roaring_iter->first, roaring_iter->second.minimum()); } } // we put std::numeric_limits<>::max/min in parenthesis // to avoid a clash with the Windows.h header under Windows return (std::numeric_limits<uint64_t>::max)(); } /** * Check if value x is present */ bool contains(uint32_t x) const { return roarings.count(0) == 0 ? false : roarings.at(0).contains(x); } bool contains(uint64_t x) const { return roarings.count(highBytes(x)) == 0 ? false : roarings.at(highBytes(x)).contains(lowBytes(x)); } /** * Compute the intersection between the current bitmap and the provided * bitmap, * writing the result in the current bitmap. The provided bitmap is not * modified. */ Roaring64Map &operator&=(const Roaring64Map &r) { for (auto &map_entry : roarings) { if (r.roarings.count(map_entry.first) == 1) map_entry.second &= r.roarings.at(map_entry.first); else map_entry.second = Roaring(); } return *this; } /** * Compute the difference between the current bitmap and the provided * bitmap, * writing the result in the current bitmap. The provided bitmap is not * modified. */ Roaring64Map &operator-=(const Roaring64Map &r) { for (auto &map_entry : roarings) { if (r.roarings.count(map_entry.first) == 1) map_entry.second -= r.roarings.at(map_entry.first); } return *this; } /** * Compute the union between the current bitmap and the provided bitmap, * writing the result in the current bitmap. The provided bitmap is not * modified. * * See also the fastunion function to aggregate many bitmaps more quickly. */ Roaring64Map &operator|=(const Roaring64Map &r) { for (const auto &map_entry : r.roarings) { if (roarings.count(map_entry.first) == 0) { roarings[map_entry.first] = map_entry.second; roarings[map_entry.first].setCopyOnWrite(copyOnWrite); } else roarings[map_entry.first] |= map_entry.second; } return *this; } /** * Compute the symmetric union between the current bitmap and the provided * bitmap, * writing the result in the current bitmap. The provided bitmap is not * modified. */ Roaring64Map &operator^=(const Roaring64Map &r) { for (const auto &map_entry : r.roarings) { if (roarings.count(map_entry.first) == 0) { roarings[map_entry.first] = map_entry.second; roarings[map_entry.first].setCopyOnWrite(copyOnWrite); } else roarings[map_entry.first] ^= map_entry.second; } return *this; } /** * Exchange the content of this bitmap with another. */ void swap(Roaring64Map &r) { roarings.swap(r.roarings); } /** * Get the cardinality of the bitmap (number of elements). * Throws std::length_error in the special case where the bitmap is full * (cardinality() == 2^64). Check isFull() before calling to avoid * exception. */ uint64_t cardinality() const { if (isFull()) { #if ROARING_EXCEPTIONS throw std::length_error("bitmap is full, cardinality is 2^64, " "unable to represent in a 64-bit integer"); #else ROARING_TERMINATE("bitmap is full, cardinality is 2^64, " "unable to represent in a 64-bit integer"); #endif } return std::accumulate( roarings.cbegin(), roarings.cend(), (uint64_t)0, [](uint64_t previous, const std::pair<uint32_t, Roaring> &map_entry) { return previous + map_entry.second.cardinality(); }); } /** * Returns true if the bitmap is empty (cardinality is zero). */ bool isEmpty() const { return std::all_of(roarings.cbegin(), roarings.cend(), [](const std::pair<uint32_t, Roaring> &map_entry) { return map_entry.second.isEmpty(); }); } /** * Returns true if the bitmap is full (cardinality is max uint64_t + 1). */ bool isFull() const { // only bother to check if map is fully saturated // // we put std::numeric_limits<>::max/min in parenthesis // to avoid a clash with the Windows.h header under Windows return roarings.size() == ((size_t)(std::numeric_limits<uint32_t>::max)()) + 1 ? std::all_of( roarings.cbegin(), roarings.cend(), [](const std::pair<uint32_t, Roaring> &roaring_map_entry) { // roarings within map are saturated if cardinality // is uint32_t max + 1 return roaring_map_entry.second.cardinality() == ((uint64_t) (std::numeric_limits<uint32_t>::max)()) + 1; }) : false; } /** * Returns true if the bitmap is subset of the other. */ bool isSubset(const Roaring64Map &r) const { for (const auto &map_entry : roarings) { auto roaring_iter = r.roarings.find(map_entry.first); if (roaring_iter == r.roarings.cend()) return false; else if (!map_entry.second.isSubset(roaring_iter->second)) return false; } return true; } /** * Returns true if the bitmap is strict subset of the other. * Throws std::length_error in the special case where the bitmap is full * (cardinality() == 2^64). Check isFull() before calling to avoid exception. */ bool isStrictSubset(const Roaring64Map &r) const { return isSubset(r) && cardinality() != r.cardinality(); } /** * Convert the bitmap to an array. Write the output to "ans", * caller is responsible to ensure that there is enough memory * allocated * (e.g., ans = new uint32[mybitmap.cardinality()];) */ void toUint64Array(uint64_t *ans) const { // Annoyingly, VS 2017 marks std::accumulate() as [[nodiscard]] (void)std::accumulate(roarings.cbegin(), roarings.cend(), ans, [](uint64_t *previous, const std::pair<uint32_t, Roaring> &map_entry) { for (uint32_t low_bits : map_entry.second) *previous++ = uniteBytes(map_entry.first, low_bits); return previous; }); } /** * Return true if the two bitmaps contain the same elements. */ bool operator==(const Roaring64Map &r) const { // we cannot use operator == on the map because either side may contain // empty Roaring Bitmaps auto lhs_iter = roarings.cbegin(); auto rhs_iter = r.roarings.cbegin(); do { // if the left map has reached its end, ensure that the right map // contains only empty Bitmaps if (lhs_iter == roarings.cend()) { while (rhs_iter != r.roarings.cend()) { if (rhs_iter->second.isEmpty()) { ++rhs_iter; continue; } return false; } return true; } // if the left map has an empty bitmap, skip it if (lhs_iter->second.isEmpty()) { ++lhs_iter; continue; } do { // if the right map has reached its end, ensure that the right // map contains only empty Bitmaps if (rhs_iter == r.roarings.cend()) { while (lhs_iter != roarings.cend()) { if (lhs_iter->second.isEmpty()) { ++lhs_iter; continue; } return false; } return true; } // if the right map has an empty bitmap, skip it if (rhs_iter->second.isEmpty()) { ++rhs_iter; continue; } } while (false); // if neither map has reached its end ensure elements are equal and // move to the next element in both } while (lhs_iter++->second == rhs_iter++->second); return false; } /** * compute the negation of the roaring bitmap within a specified interval. * areas outside the range are passed through unchanged. */ void flip(uint64_t range_start, uint64_t range_end) { uint32_t start_high = highBytes(range_start); uint32_t start_low = lowBytes(range_start); uint32_t end_high = highBytes(range_end); uint32_t end_low = lowBytes(range_end); if (start_high == end_high) { roarings[start_high].flip(start_low, end_low); return; } // we put std::numeric_limits<>::max/min in parenthesis // to avoid a clash with the Windows.h header under Windows roarings[start_high].flip(start_low, (std::numeric_limits<uint32_t>::max)()); roarings[start_high++].setCopyOnWrite(copyOnWrite); for (; start_high <= highBytes(range_end) - 1; ++start_high) { roarings[start_high].flip((std::numeric_limits<uint32_t>::min)(), (std::numeric_limits<uint32_t>::max)()); roarings[start_high].setCopyOnWrite(copyOnWrite); } roarings[start_high].flip((std::numeric_limits<uint32_t>::min)(), end_low); roarings[start_high].setCopyOnWrite(copyOnWrite); } /** * Remove run-length encoding even when it is more space efficient * return whether a change was applied */ bool removeRunCompression() { return std::accumulate( roarings.begin(), roarings.end(), true, [](bool previous, std::pair<const uint32_t, Roaring> &map_entry) { return map_entry.second.removeRunCompression() && previous; }); } /** convert array and bitmap containers to run containers when it is more * efficient; * also convert from run containers when more space efficient. Returns * true if the result has at least one run container. * Additional savings might be possible by calling shrinkToFit(). */ bool runOptimize() { return std::accumulate( roarings.begin(), roarings.end(), true, [](bool previous, std::pair<const uint32_t, Roaring> &map_entry) { return map_entry.second.runOptimize() && previous; }); } /** * If needed, reallocate memory to shrink the memory usage. Returns * the number of bytes saved. */ size_t shrinkToFit() { size_t savedBytes = 0; auto iter = roarings.begin(); while (iter != roarings.cend()) { if (iter->second.isEmpty()) { // empty Roarings are 84 bytes savedBytes += 88; roarings.erase(iter++); } else { savedBytes += iter->second.shrinkToFit(); iter++; } } return savedBytes; } /** * Iterate over the bitmap elements. The function iterator is called once * for all the values with ptr (can be NULL) as the second parameter of each * call. * * roaring_iterator is simply a pointer to a function that returns bool * (true means that the iteration should continue while false means that it * should stop), and takes (uint32_t,void*) as inputs. */ void iterate(api::roaring_iterator64 iterator, void *ptr) const { std::for_each(roarings.begin(), roarings.cend(), [=](const std::pair<uint32_t, Roaring> &map_entry) { roaring_iterate64(&map_entry.second.roaring, iterator, uint64_t(map_entry.first) << 32, ptr); }); } /** * If the size of the roaring bitmap is strictly greater than rank, then this function returns true and set element to the element of given rank. Otherwise, it returns false. */ bool select(uint64_t rnk, uint64_t *element) const { for (const auto &map_entry : roarings) { uint64_t sub_cardinality = (uint64_t)map_entry.second.cardinality(); if (rnk < sub_cardinality) { *element = ((uint64_t)map_entry.first) << 32; // assuming little endian return map_entry.second.select((uint32_t)rnk, ((uint32_t *)element)); } rnk -= sub_cardinality; } return false; } /** * Returns the number of integers that are smaller or equal to x. */ uint64_t rank(uint64_t x) const { uint64_t result = 0; auto roaring_destination = roarings.find(highBytes(x)); if (roaring_destination != roarings.cend()) { for (auto roaring_iter = roarings.cbegin(); roaring_iter != roaring_destination; ++roaring_iter) { result += roaring_iter->second.cardinality(); } result += roaring_destination->second.rank(lowBytes(x)); return result; } roaring_destination = roarings.lower_bound(highBytes(x)); for (auto roaring_iter = roarings.cbegin(); roaring_iter != roaring_destination; ++roaring_iter) { result += roaring_iter->second.cardinality(); } return result; } /** * write a bitmap to a char buffer. This is meant to be compatible with * the * Java and Go versions. Returns how many bytes were written which should be * getSizeInBytes(). * * Setting the portable flag to false enable a custom format that * can save space compared to the portable format (e.g., for very * sparse bitmaps). */ size_t write(char *buf, bool portable = true) const { const char *orig = buf; // push map size *((uint64_t *)buf) = roarings.size(); buf += sizeof(uint64_t); std::for_each( roarings.cbegin(), roarings.cend(), [&buf, portable](const std::pair<uint32_t, Roaring> &map_entry) { // push map key std::memcpy(buf, &map_entry.first, sizeof(uint32_t)); // ^-- Note: `*((uint32_t*)buf) = map_entry.first;` is undefined buf += sizeof(uint32_t); // push map value Roaring buf += map_entry.second.write(buf, portable); }); return buf - orig; } /** * read a bitmap from a serialized version. This is meant to be compatible * with * the * Java and Go versions. * * Setting the portable flag to false enable a custom format that * can save space compared to the portable format (e.g., for very * sparse bitmaps). * * This function is unsafe in the sense that if you provide bad data, * many bytes could be read, possibly causing a buffer overflow. See also readSafe. */ static Roaring64Map read(const char *buf, bool portable = true) { Roaring64Map result; // get map size uint64_t map_size = *((uint64_t *)buf); buf += sizeof(uint64_t); for (uint64_t lcv = 0; lcv < map_size; lcv++) { // get map key uint32_t key; std::memcpy(&key, buf, sizeof(uint32_t)); // ^-- Note: `uint32_t key = *((uint32_t*)buf);` is undefined buf += sizeof(uint32_t); // read map value Roaring Roaring read = Roaring::read(buf, portable); result.emplaceOrInsert(key, read); // forward buffer past the last Roaring Bitmap buf += read.getSizeInBytes(portable); } return result; } /** * read a bitmap from a serialized version, reading no more than maxbytes bytes. * This is meant to be compatible with the Java and Go versions. * * Setting the portable flag to false enable a custom format that * can save space compared to the portable format (e.g., for very * sparse bitmaps). */ static Roaring64Map readSafe(const char *buf, size_t maxbytes) { Roaring64Map result; // get map size uint64_t map_size = *((uint64_t *)buf); buf += sizeof(uint64_t); for (uint64_t lcv = 0; lcv < map_size; lcv++) { // get map key if(maxbytes < sizeof(uint32_t)) { #if ROARING_EXCEPTIONS throw std::runtime_error("ran out of bytes"); #else std::terminate(); #endif } uint32_t key; std::memcpy(&key, buf, sizeof(uint32_t)); // ^-- Note: `uint32_t key = *((uint32_t*)buf);` is undefined buf += sizeof(uint32_t); maxbytes -= sizeof(uint32_t); // read map value Roaring Roaring read = Roaring::readSafe(buf, maxbytes); result.emplaceOrInsert(key, read); // forward buffer past the last Roaring Bitmap size_t tz = read.getSizeInBytes(true); buf += tz; maxbytes -= tz; } return result; } /** * How many bytes are required to serialize this bitmap (meant to be * compatible * with Java and Go versions) * * Setting the portable flag to false enable a custom format that * can save space compared to the portable format (e.g., for very * sparse bitmaps). */ size_t getSizeInBytes(bool portable = true) const { // start with, respectively, map size and size of keys for each map // entry return std::accumulate( roarings.cbegin(), roarings.cend(), sizeof(uint64_t) + roarings.size() * sizeof(uint32_t), [=](size_t previous, const std::pair<uint32_t, Roaring> &map_entry) { // add in bytes used by each Roaring return previous + map_entry.second.getSizeInBytes(portable); }); } /** * Computes the intersection between two bitmaps and returns new bitmap. * The current bitmap and the provided bitmap are unchanged. */ Roaring64Map operator&(const Roaring64Map &o) const { return Roaring64Map(*this) &= o; } /** * Computes the difference between two bitmaps and returns new bitmap. * The current bitmap and the provided bitmap are unchanged. */ Roaring64Map operator-(const Roaring64Map &o) const { return Roaring64Map(*this) -= o; } /** * Computes the union between two bitmaps and returns new bitmap. * The current bitmap and the provided bitmap are unchanged. */ Roaring64Map operator|(const Roaring64Map &o) const { return Roaring64Map(*this) |= o; } /** * Computes the symmetric union between two bitmaps and returns new bitmap. * The current bitmap and the provided bitmap are unchanged. */ Roaring64Map operator^(const Roaring64Map &o) const { return Roaring64Map(*this) ^= o; } /** * Whether or not we apply copy and write. */ void setCopyOnWrite(bool val) { if (copyOnWrite == val) return; copyOnWrite = val; std::for_each(roarings.begin(), roarings.end(), [=](std::pair<const uint32_t, Roaring> &map_entry) { map_entry.second.setCopyOnWrite(val); }); } /** * Print the content of the bitmap */ void printf() const { if (!isEmpty()) { auto map_iter = roarings.cbegin(); while (map_iter->second.isEmpty()) ++map_iter; struct iter_data { uint32_t high_bits; char first_char = '{'; } outer_iter_data; outer_iter_data.high_bits = roarings.begin()->first; map_iter->second.iterate( [](uint32_t low_bits, void *inner_iter_data) -> bool { std::printf("%c%llu", ((iter_data *)inner_iter_data)->first_char, (long long unsigned)uniteBytes( ((iter_data *)inner_iter_data)->high_bits, low_bits)); ((iter_data *)inner_iter_data)->first_char = ','; return true; }, (void *)&outer_iter_data); std::for_each( ++map_iter, roarings.cend(), [](const std::pair<uint32_t, Roaring> &map_entry) { map_entry.second.iterate( [](uint32_t low_bits, void *high_bits) -> bool { std::printf(",%llu", (long long unsigned)uniteBytes( *(uint32_t *)high_bits, low_bits)); return true; }, (void *)&map_entry.first); }); } else std::printf("{"); std::printf("}\n"); } /** * Print the content of the bitmap into a string */ std::string toString() const { struct iter_data { std::string str; uint32_t high_bits; char first_char = '{'; } outer_iter_data; if (!isEmpty()) { auto map_iter = roarings.cbegin(); while (map_iter->second.isEmpty()) ++map_iter; outer_iter_data.high_bits = roarings.begin()->first; map_iter->second.iterate( [](uint32_t low_bits, void *inner_iter_data) -> bool { ((iter_data *)inner_iter_data)->str += ((iter_data *)inner_iter_data)->first_char; ((iter_data *)inner_iter_data)->str += std::to_string( uniteBytes(((iter_data *)inner_iter_data)->high_bits, low_bits)); ((iter_data *)inner_iter_data)->first_char = ','; return true; }, (void *)&outer_iter_data); std::for_each( ++map_iter, roarings.cend(), [&outer_iter_data]( const std::pair<uint32_t, Roaring> &map_entry) { outer_iter_data.high_bits = map_entry.first; map_entry.second.iterate( [](uint32_t low_bits, void *inner_iter_data) -> bool { ((iter_data *)inner_iter_data)->str += ((iter_data *)inner_iter_data)->first_char; ((iter_data *)inner_iter_data)->str += std::to_string(uniteBytes( ((iter_data *)inner_iter_data)->high_bits, low_bits)); return true; }, (void *)&outer_iter_data); }); } else outer_iter_data.str = '{'; outer_iter_data.str += '}'; return outer_iter_data.str; } /** * Whether or not copy and write is active. */ bool getCopyOnWrite() const { return copyOnWrite; } /** * computes the logical or (union) between "n" bitmaps (referenced by a * pointer). */ static Roaring64Map fastunion(size_t n, const Roaring64Map **inputs) { Roaring64Map ans; // not particularly fast for (size_t lcv = 0; lcv < n; ++lcv) { ans |= *(inputs[lcv]); } return ans; } friend class Roaring64MapSetBitForwardIterator; friend class Roaring64MapSetBitBiDirectionalIterator; typedef Roaring64MapSetBitForwardIterator const_iterator; typedef Roaring64MapSetBitBiDirectionalIterator const_bidirectional_iterator; /** * Returns an iterator that can be used to access the position of the * set bits. The running time complexity of a full scan is proportional to * the * number * of set bits: be aware that if you have long strings of 1s, this can be * very inefficient. * * It can be much faster to use the toArray method if you want to * retrieve the set bits. */ const_iterator begin() const; /** * A bogus iterator that can be used together with begin() * for constructions such as for(auto i = b.begin(); * i!=b.end(); ++i) {} */ const_iterator end() const; private: std::map<uint32_t, Roaring> roarings; bool copyOnWrite = false; static uint32_t highBytes(const uint64_t in) { return uint32_t(in >> 32); } static uint32_t lowBytes(const uint64_t in) { return uint32_t(in); } static uint64_t uniteBytes(const uint32_t highBytes, const uint32_t lowBytes) { return (uint64_t(highBytes) << 32) | uint64_t(lowBytes); } // this is needed to tolerate gcc's C++11 libstdc++ lacking emplace // prior to version 4.8 void emplaceOrInsert(const uint32_t key, const Roaring &value) { #if defined(__GLIBCXX__) && __GLIBCXX__ < 20130322 roarings.insert(std::make_pair(key, value)); #else roarings.emplace(std::make_pair(key, value)); #endif } }; /** * Used to go through the set bits. Not optimally fast, but convenient. */ class Roaring64MapSetBitForwardIterator { public: typedef std::forward_iterator_tag iterator_category; typedef uint64_t *pointer; typedef uint64_t &reference_type; typedef uint64_t value_type; typedef int64_t difference_type; typedef Roaring64MapSetBitForwardIterator type_of_iterator; /** * Provides the location of the set bit. */ value_type operator*() const { return Roaring64Map::uniteBytes(map_iter->first, i.current_value); } bool operator<(const type_of_iterator &o) const { if (map_iter == map_end) return false; if (o.map_iter == o.map_end) return true; return **this < *o; } bool operator<=(const type_of_iterator &o) const { if (o.map_iter == o.map_end) return true; if (map_iter == map_end) return false; return **this <= *o; } bool operator>(const type_of_iterator &o) const { if (o.map_iter == o.map_end) return false; if (map_iter == map_end) return true; return **this > *o; } bool operator>=(const type_of_iterator &o) const { if (map_iter == map_end) return true; if (o.map_iter == o.map_end) return false; return **this >= *o; } type_of_iterator &operator++() { // ++i, must returned inc. value if (i.has_value == true) roaring_advance_uint32_iterator(&i); while (!i.has_value) { map_iter++; if (map_iter == map_end) return *this; roaring_init_iterator(&map_iter->second.roaring, &i); } return *this; } type_of_iterator operator++(int) { // i++, must return orig. value Roaring64MapSetBitForwardIterator orig(*this); roaring_advance_uint32_iterator(&i); while (!i.has_value) { map_iter++; if (map_iter == map_end) return orig; roaring_init_iterator(&map_iter->second.roaring, &i); } return orig; } bool move(const value_type& x) { map_iter = p.lower_bound(Roaring64Map::highBytes(x)); if (map_iter != p.cend()) { roaring_init_iterator(&map_iter->second.roaring, &i); if (map_iter->first == Roaring64Map::highBytes(x)) { if (roaring_move_uint32_iterator_equalorlarger(&i, Roaring64Map::lowBytes(x))) return true; map_iter++; if (map_iter == map_end) return false; roaring_init_iterator(&map_iter->second.roaring, &i); } return true; } return false; } bool operator==(const Roaring64MapSetBitForwardIterator &o) const { if (map_iter == map_end && o.map_iter == o.map_end) return true; if (o.map_iter == o.map_end) return false; return **this == *o; } bool operator!=(const Roaring64MapSetBitForwardIterator &o) const { if (map_iter == map_end && o.map_iter == o.map_end) return false; if (o.map_iter == o.map_end) return true; return **this != *o; } Roaring64MapSetBitForwardIterator &operator=(const Roaring64MapSetBitForwardIterator& r) { map_iter = r.map_iter; map_end = r.map_end; i = r.i; return *this; } Roaring64MapSetBitForwardIterator(const Roaring64MapSetBitForwardIterator& r) : p(r.p), map_iter(r.map_iter), map_end(r.map_end), i(r.i) { } Roaring64MapSetBitForwardIterator(const Roaring64Map &parent, bool exhausted = false) : p(parent.roarings), map_end(parent.roarings.cend()) { if (exhausted || parent.roarings.empty()) { map_iter = parent.roarings.cend(); } else { map_iter = parent.roarings.cbegin(); roaring_init_iterator(&map_iter->second.roaring, &i); while (!i.has_value) { map_iter++; if (map_iter == map_end) return; roaring_init_iterator(&map_iter->second.roaring, &i); } } } protected: const std::map<uint32_t, Roaring>& p; std::map<uint32_t, Roaring>::const_iterator map_iter; std::map<uint32_t, Roaring>::const_iterator map_end; api::roaring_uint32_iterator_t i; }; class Roaring64MapSetBitBiDirectionalIterator final :public Roaring64MapSetBitForwardIterator { public: Roaring64MapSetBitBiDirectionalIterator(const Roaring64Map &parent, bool exhausted = false) : Roaring64MapSetBitForwardIterator(parent, exhausted), map_begin(parent.roarings.cbegin()) {} Roaring64MapSetBitBiDirectionalIterator &operator=(const Roaring64MapSetBitForwardIterator& r) { *(Roaring64MapSetBitForwardIterator*)this = r; return *this; } type_of_iterator& operator--() { // --i, must return dec.value if (map_iter == map_end) { --map_iter; roaring_init_iterator_last(&map_iter->second.roaring, &i); if (i.has_value) return *this; } roaring_previous_uint32_iterator(&i); while (!i.has_value) { if (map_iter == map_begin) return *this; map_iter--; roaring_init_iterator_last(&map_iter->second.roaring, &i); } return *this; } type_of_iterator operator--(int) { // i--, must return orig. value Roaring64MapSetBitBiDirectionalIterator orig(*this); if (map_iter == map_end) { --map_iter; roaring_init_iterator_last(&map_iter->second.roaring, &i); return orig; } roaring_previous_uint32_iterator(&i); while (!i.has_value) { if (map_iter == map_begin) return orig; map_iter--; roaring_init_iterator_last(&map_iter->second.roaring, &i); } return orig; } protected: std::map<uint32_t, Roaring>::const_iterator map_begin; }; inline Roaring64MapSetBitForwardIterator Roaring64Map::begin() const { return Roaring64MapSetBitForwardIterator(*this); } inline Roaring64MapSetBitForwardIterator Roaring64Map::end() const { return Roaring64MapSetBitForwardIterator(*this, true); } } // namespace roaring #endif /* INCLUDE_ROARING_64_MAP_HH_ */
35.04186
102
0.56395
[ "object" ]
33e7b6501fb4e19d77535650b5a67d907ff7f623
1,312
cpp
C++
nrs/list_comb.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
nrs/list_comb.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
nrs/list_comb.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
/* list_comb() returns all the enumeration of the combination Author: Keitaro Naruse Date: 2021-12-26 MIT License */ #include <iostream> #include <vector> namespace nrs { bool list_comb( std::vector< int >& comb, const std::vector< int >& len ) { int n = comb.size(); bool next_exist = true; for( int i = n - 1; i >= 0; i -- ) { comb.at( i ) ++; if( comb.at( i ) < len.at( i ) ) { break; } else { comb.at( i ) = 0; if( i == 0) { next_exist = false; } } } return( next_exist ); } } // Test driver int main() { // Constants const int N = 4; const std::vector< std::vector< int > > A = { { 1 }, { 2, 3 }, { 4, 5, 6 }, { 7, 8, 9, 10 } }; std::vector< int > L( N ); for( int i = 0; i < N; i ++ ) { L.at( i ) = A.at( i ).size(); } // Main std::vector< int > comb( N, 0 ); do { for( int i = 0; i < comb.size(); i ++ ) { std::cout << comb.at( i ) << " "; } std::cout << std::endl; } while( nrs::list_comb( comb, L ) ); return( 0 ); }
21.16129
78
0.384909
[ "vector" ]
33e800b733fd6c276408a608017ce957c7641264
10,082
hpp
C++
BoostSharp/include/boost/accumulators/statistics/p_square_cumul_dist.hpp
Icenium/BoostSharp
1dd31065fcd65ae6304b182c558bac7c7a738ad5
[ "Apache-2.0" ]
3
2017-05-11T05:30:19.000Z
2019-04-24T05:41:33.000Z
src/third_party/boost/boost/accumulators/statistics/p_square_cumul_dist.hpp
wugh7125/installwizard
42f8aeb78026ff81838528968b1503e73f6c2864
[ "Apache-2.0" ]
null
null
null
src/third_party/boost/boost/accumulators/statistics/p_square_cumul_dist.hpp
wugh7125/installwizard
42f8aeb78026ff81838528968b1503e73f6c2864
[ "Apache-2.0" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
/////////////////////////////////////////////////////////////////////////////// // p_square_cumulative_distribution.hpp // // Copyright 2005 Daniel Egloff, Olivier Gygi. 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) #ifndef BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMUL_DIST_HPP_DE_01_01_2006 #define BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMUL_DIST_HPP_DE_01_01_2006 #include <vector> #include <functional> #include <boost/parameter/keyword.hpp> #include <boost/range.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/accumulators/accumulators_fwd.hpp> #include <boost/accumulators/framework/accumulator_base.hpp> #include <boost/accumulators/framework/extractor.hpp> #include <boost/accumulators/numeric/functional.hpp> #include <boost/accumulators/framework/parameters/sample.hpp> #include <boost/accumulators/statistics_fwd.hpp> #include <boost/accumulators/statistics/count.hpp> namespace boost { namespace accumulators { /////////////////////////////////////////////////////////////////////////////// // num_cells named parameter // BOOST_PARAMETER_NESTED_KEYWORD(tag, p_square_cumulative_distribution_num_cells, num_cells) BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_cumulative_distribution_num_cells) namespace impl { /////////////////////////////////////////////////////////////////////////////// // p_square_cumulative_distribution_impl // cumulative_distribution calculation (as histogram) /** @brief Histogram calculation of the cumulative distribution with the \f$P^2\f$ algorithm A histogram of the sample cumulative distribution is computed dynamically without storing samples based on the \f$ P^2 \f$ algorithm. The returned histogram has a specifiable amount (num_cells) equiprobable (and not equal-sized) cells. For further details, see R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and histograms without storing observations, Communications of the ACM, Volume 28 (October), Number 10, 1985, p. 1076-1085. @param p_square_cumulative_distribution_num_cells. */ template<typename Sample> struct p_square_cumulative_distribution_impl : accumulator_base { typedef typename numeric::functional::average<Sample, std::size_t>::result_type float_type; typedef std::vector<float_type> array_type; typedef std::vector<std::pair<float_type, float_type> > histogram_type; // for boost::result_of typedef iterator_range<typename histogram_type::iterator> result_type; template<typename Args> p_square_cumulative_distribution_impl(Args const &args) : num_cells(args[p_square_cumulative_distribution_num_cells]) , heights(num_cells + 1) , actual_positions(num_cells + 1) , desired_positions(num_cells + 1) , positions_increments(num_cells + 1) , histogram(num_cells + 1) , is_dirty(true) { std::size_t b = this->num_cells; for (std::size_t i = 0; i < b + 1; ++i) { this->actual_positions[i] = i + 1.; this->desired_positions[i] = i + 1.; this->positions_increments[i] = numeric::average(i, b); } } template<typename Args> void operator ()(Args const &args) { this->is_dirty = true; std::size_t cnt = count(args); std::size_t sample_cell = 1; // k std::size_t b = this->num_cells; // accumulate num_cells + 1 first samples if (cnt <= b + 1) { this->heights[cnt - 1] = args[sample]; // complete the initialization of heights by sorting if (cnt == b + 1) { std::sort(this->heights.begin(), this->heights.end()); } } else { // find cell k such that heights[k-1] <= args[sample] < heights[k] and adjust extreme values if (args[sample] < this->heights[0]) { this->heights[0] = args[sample]; sample_cell = 1; } else if (this->heights[b] <= args[sample]) { this->heights[b] = args[sample]; sample_cell = b; } else { typename array_type::iterator it; it = std::upper_bound( this->heights.begin() , this->heights.end() , args[sample] ); sample_cell = std::distance(this->heights.begin(), it); } // increment positions of markers above sample_cell for (std::size_t i = sample_cell; i < b + 1; ++i) { ++this->actual_positions[i]; } // update desired position of markers 2 to num_cells + 1 // (desired position of first marker is always 1) for (std::size_t i = 1; i < b + 1; ++i) { this->desired_positions[i] += this->positions_increments[i]; } // adjust heights of markers 2 to num_cells if necessary for (std::size_t i = 1; i < b; ++i) { // offset to desire position float_type d = this->desired_positions[i] - this->actual_positions[i]; // offset to next position float_type dp = this->actual_positions[i + 1] - this->actual_positions[i]; // offset to previous position float_type dm = this->actual_positions[i - 1] - this->actual_positions[i]; // height ds float_type hp = (this->heights[i + 1] - this->heights[i]) / dp; float_type hm = (this->heights[i - 1] - this->heights[i]) / dm; if ( ( d >= 1. && dp > 1. ) || ( d <= -1. && dm < -1. ) ) { short sign_d = static_cast<short>(d / std::abs(d)); // try adjusting heights[i] using p-squared formula float_type h = this->heights[i] + sign_d / (dp - dm) * ( (sign_d - dm) * hp + (dp - sign_d) * hm ); if ( this->heights[i - 1] < h && h < this->heights[i + 1] ) { this->heights[i] = h; } else { // use linear formula if (d>0) { this->heights[i] += hp; } if (d<0) { this->heights[i] -= hm; } } this->actual_positions[i] += sign_d; } } } } template<typename Args> result_type result(Args const &args) const { if (this->is_dirty) { this->is_dirty = false; // creates a vector of std::pair where each pair i holds // the values heights[i] (x-axis of histogram) and // actual_positions[i] / cnt (y-axis of histogram) std::size_t cnt = count(args); for (std::size_t i = 0; i < this->histogram.size(); ++i) { this->histogram[i] = std::make_pair(this->heights[i], numeric::average(this->actual_positions[i], cnt)); } } //return histogram; return make_iterator_range(this->histogram); } private: std::size_t num_cells; // number of cells b array_type heights; // q_i array_type actual_positions; // n_i array_type desired_positions; // n'_i array_type positions_increments; // dn'_i mutable histogram_type histogram; // histogram mutable bool is_dirty; }; } // namespace detail /////////////////////////////////////////////////////////////////////////////// // tag::p_square_cumulative_distribution // namespace tag { struct p_square_cumulative_distribution : depends_on<count> , p_square_cumulative_distribution_num_cells { /// INTERNAL ONLY /// typedef accumulators::impl::p_square_cumulative_distribution_impl<mpl::_1> impl; }; } /////////////////////////////////////////////////////////////////////////////// // extract::p_square_cumulative_distribution // namespace extract { extractor<tag::p_square_cumulative_distribution> const p_square_cumulative_distribution = {}; BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_cumulative_distribution) } using extract::p_square_cumulative_distribution; // So that p_square_cumulative_distribution can be automatically substituted with // weighted_p_square_cumulative_distribution when the weight parameter is non-void template<> struct as_weighted_feature<tag::p_square_cumulative_distribution> { typedef tag::weighted_p_square_cumulative_distribution type; }; template<> struct feature_of<tag::weighted_p_square_cumulative_distribution> : feature_of<tag::p_square_cumulative_distribution> { }; }} // namespace boost::accumulators #endif
38.189394
125
0.519837
[ "vector" ]
33eaee18fa92d93afd6df02d1c73e675b374f401
12,194
cc
C++
test/common/upstream/cds_api_impl_test.cc
guillaumerosinosky/envoy
2cc9b69f28caa34bd0bc0d4371b669f027807ccd
[ "Apache-2.0" ]
1
2022-01-21T01:39:10.000Z
2022-01-21T01:39:10.000Z
test/common/upstream/cds_api_impl_test.cc
guillaumerosinosky/envoy
2cc9b69f28caa34bd0bc0d4371b669f027807ccd
[ "Apache-2.0" ]
248
2021-06-17T21:12:59.000Z
2022-03-31T21:21:15.000Z
test/common/upstream/cds_api_impl_test.cc
guillaumerosinosky/envoy
2cc9b69f28caa34bd0bc0d4371b669f027807ccd
[ "Apache-2.0" ]
1
2021-07-19T21:16:38.000Z
2021-07-19T21:16:38.000Z
#include <chrono> #include <memory> #include <string> #include <vector> #include "envoy/config/cluster/v3/cluster.pb.h" #include "envoy/config/core/v3/config_source.pb.h" #include "envoy/service/discovery/v3/discovery.pb.h" #include "source/common/config/utility.h" #include "source/common/protobuf/utility.h" #include "source/common/upstream/cds_api_impl.h" #include "test/common/upstream/utility.h" #include "test/mocks/protobuf/mocks.h" #include "test/mocks/upstream/cluster_manager.h" #include "test/mocks/upstream/cluster_priority_set.h" #include "test/test_common/printers.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::_; using testing::InSequence; using testing::Return; using testing::StrEq; using testing::Throw; namespace Envoy { namespace Upstream { namespace { MATCHER_P(WithName, expectedName, "") { return arg.name() == expectedName; } class CdsApiImplTest : public testing::Test { protected: void setup() { envoy::config::core::v3::ConfigSource cds_config; cds_ = CdsApiImpl::create(cds_config, nullptr, cm_, store_, validation_visitor_); cds_->setInitializedCb([this]() -> void { initialized_.ready(); }); EXPECT_CALL(*cm_.subscription_factory_.subscription_, start(_)); cds_->initialize(); cds_callbacks_ = cm_.subscription_factory_.callbacks_; } void expectAdd(const std::string& cluster_name, const std::string& version = std::string("")) { EXPECT_CALL(cm_, addOrUpdateCluster(WithName(cluster_name), version)).WillOnce(Return(true)); } void expectAddToThrow(const std::string& cluster_name, const std::string& exception_msg) { EXPECT_CALL(cm_, addOrUpdateCluster(WithName(cluster_name), _)) .WillOnce(Throw(EnvoyException(exception_msg))); } ClusterManager::ClusterInfoMaps makeClusterInfoMaps(const std::vector<std::string>& active_clusters, const std::vector<std::string>& warming_clusters = {}) { ClusterManager::ClusterInfoMaps maps; for (const auto& cluster : active_clusters) { maps.active_clusters_.emplace(cluster, cm_.thread_local_cluster_.cluster_); } for (const auto& cluster : warming_clusters) { maps.warming_clusters_.emplace(cluster, cm_.thread_local_cluster_.cluster_); } return maps; } NiceMock<MockClusterManager> cm_; Upstream::MockClusterMockPrioritySet mock_cluster_; Stats::IsolatedStoreImpl store_; CdsApiPtr cds_; Config::SubscriptionCallbacks* cds_callbacks_{}; ReadyWatcher initialized_; NiceMock<ProtobufMessage::MockValidationVisitor> validation_visitor_; }; // Regression test against only updating versionInfo() if at least one cluster // is are added/updated even if one or more are removed. TEST_F(CdsApiImplTest, UpdateVersionOnClusterRemove) { InSequence s; setup(); const std::string response1_yaml = R"EOF( version_info: '0' resources: - "@type": type.googleapis.com/envoy.config.cluster.v3.Cluster name: cluster1 type: EDS eds_cluster_config: eds_config: resource_api_version: V3 path: eds path )EOF"; auto response1 = TestUtility::parseYaml<envoy::service::discovery::v3::DiscoveryResponse>(response1_yaml); EXPECT_CALL(cm_, clusters()).WillOnce(Return(makeClusterInfoMaps({}))); expectAdd("cluster1", "0"); EXPECT_CALL(initialized_, ready()); EXPECT_EQ("", cds_->versionInfo()); const auto decoded_resources = TestUtility::decodeResources<envoy::config::cluster::v3::Cluster>(response1); cds_callbacks_->onConfigUpdate(decoded_resources.refvec_, response1.version_info()); EXPECT_EQ("0", cds_->versionInfo()); const std::string response2_yaml = R"EOF( version_info: '1' resources: )EOF"; auto response2 = TestUtility::parseYaml<envoy::service::discovery::v3::DiscoveryResponse>(response2_yaml); EXPECT_CALL(cm_, clusters()).WillOnce(Return(makeClusterInfoMaps({"cluster1"}))); EXPECT_CALL(cm_, removeCluster("cluster1")).WillOnce(Return(true)); const auto decoded_resources_2 = TestUtility::decodeResources<envoy::config::cluster::v3::Cluster>(response2); cds_callbacks_->onConfigUpdate(decoded_resources_2.refvec_, response2.version_info()); EXPECT_EQ("1", cds_->versionInfo()); } // Validate onConfigUpdate throws EnvoyException with duplicate clusters. TEST_F(CdsApiImplTest, ValidateDuplicateClusters) { InSequence s; setup(); envoy::config::cluster::v3::Cluster cluster_1; cluster_1.set_name("duplicate_cluster"); const auto decoded_resources = TestUtility::decodeResources({cluster_1, cluster_1}); EXPECT_CALL(cm_, clusters()).WillRepeatedly(Return(makeClusterInfoMaps({}))); EXPECT_CALL(initialized_, ready()); EXPECT_THROW_WITH_MESSAGE(cds_callbacks_->onConfigUpdate(decoded_resources.refvec_, ""), EnvoyException, "Error adding/updating cluster(s) duplicate_cluster: duplicate cluster " "duplicate_cluster found"); } TEST_F(CdsApiImplTest, EmptyConfigUpdate) { InSequence s; setup(); EXPECT_CALL(cm_, clusters()).WillOnce(Return(makeClusterInfoMaps({}))); EXPECT_CALL(initialized_, ready()); cds_callbacks_->onConfigUpdate({}, ""); } TEST_F(CdsApiImplTest, ConfigUpdateWith2ValidClusters) { { InSequence s; setup(); } EXPECT_CALL(cm_, clusters()).WillOnce(Return(makeClusterInfoMaps({}))); EXPECT_CALL(initialized_, ready()); envoy::config::cluster::v3::Cluster cluster_1; cluster_1.set_name("cluster_1"); expectAdd("cluster_1"); envoy::config::cluster::v3::Cluster cluster_2; cluster_2.set_name("cluster_2"); expectAdd("cluster_2"); const auto decoded_resources = TestUtility::decodeResources({cluster_1, cluster_2}); cds_callbacks_->onConfigUpdate(decoded_resources.refvec_, ""); } TEST_F(CdsApiImplTest, DeltaConfigUpdate) { { InSequence s; setup(); } EXPECT_CALL(initialized_, ready()); { Protobuf::RepeatedPtrField<envoy::service::discovery::v3::Resource> resources; { envoy::config::cluster::v3::Cluster cluster; cluster.set_name("cluster_1"); expectAdd("cluster_1", "v1"); auto* resource = resources.Add(); resource->mutable_resource()->PackFrom(cluster); resource->set_name("cluster_1"); resource->set_version("v1"); } { envoy::config::cluster::v3::Cluster cluster; cluster.set_name("cluster_2"); expectAdd("cluster_2", "v1"); auto* resource = resources.Add(); resource->mutable_resource()->PackFrom(cluster); resource->set_name("cluster_2"); resource->set_version("v1"); } const auto decoded_resources = TestUtility::decodeResources<envoy::config::cluster::v3::Cluster>(resources); cds_callbacks_->onConfigUpdate(decoded_resources.refvec_, {}, "v1"); } { Protobuf::RepeatedPtrField<envoy::service::discovery::v3::Resource> resources; { envoy::config::cluster::v3::Cluster cluster; cluster.set_name("cluster_3"); expectAdd("cluster_3", "v2"); auto* resource = resources.Add(); resource->mutable_resource()->PackFrom(cluster); resource->set_name("cluster_3"); resource->set_version("v2"); } Protobuf::RepeatedPtrField<std::string> removed; *removed.Add() = "cluster_1"; EXPECT_CALL(cm_, removeCluster(StrEq("cluster_1"))).WillOnce(Return(true)); const auto decoded_resources = TestUtility::decodeResources<envoy::config::cluster::v3::Cluster>(resources); cds_callbacks_->onConfigUpdate(decoded_resources.refvec_, removed, "v2"); } } TEST_F(CdsApiImplTest, ConfigUpdateAddsSecondClusterEvenIfFirstThrows) { { InSequence s; setup(); } EXPECT_CALL(cm_, clusters()).WillOnce(Return(makeClusterInfoMaps({}))); EXPECT_CALL(initialized_, ready()); envoy::config::cluster::v3::Cluster cluster_1; cluster_1.set_name("cluster_1"); expectAddToThrow("cluster_1", "An exception"); envoy::config::cluster::v3::Cluster cluster_2; cluster_2.set_name("cluster_2"); expectAdd("cluster_2"); envoy::config::cluster::v3::Cluster cluster_3; cluster_3.set_name("cluster_3"); expectAddToThrow("cluster_3", "Another exception"); const auto decoded_resources = TestUtility::decodeResources({cluster_1, cluster_2, cluster_3}); EXPECT_THROW_WITH_MESSAGE( cds_callbacks_->onConfigUpdate(decoded_resources.refvec_, ""), EnvoyException, "Error adding/updating cluster(s) cluster_1: An exception, cluster_3: Another exception"); } TEST_F(CdsApiImplTest, Basic) { InSequence s; setup(); const std::string response1_yaml = R"EOF( version_info: '0' resources: - "@type": type.googleapis.com/envoy.config.cluster.v3.Cluster name: cluster1 type: EDS eds_cluster_config: eds_config: resource_api_version: V3 path: eds path - "@type": type.googleapis.com/envoy.config.cluster.v3.Cluster name: cluster2 type: EDS eds_cluster_config: eds_config: resource_api_version: V3 path: eds path )EOF"; auto response1 = TestUtility::parseYaml<envoy::service::discovery::v3::DiscoveryResponse>(response1_yaml); EXPECT_CALL(cm_, clusters()).WillOnce(Return(makeClusterInfoMaps({}))); expectAdd("cluster1", "0"); expectAdd("cluster2", "0"); EXPECT_CALL(initialized_, ready()); EXPECT_EQ("", cds_->versionInfo()); const auto decoded_resources = TestUtility::decodeResources<envoy::config::cluster::v3::Cluster>(response1); cds_callbacks_->onConfigUpdate(decoded_resources.refvec_, response1.version_info()); EXPECT_EQ("0", cds_->versionInfo()); const std::string response2_yaml = R"EOF( version_info: '1' resources: - "@type": type.googleapis.com/envoy.config.cluster.v3.Cluster name: cluster1 type: EDS eds_cluster_config: eds_config: resource_api_version: V3 path: eds path - "@type": type.googleapis.com/envoy.config.cluster.v3.Cluster name: cluster3 type: EDS eds_cluster_config: eds_config: resource_api_version: V3 path: eds path )EOF"; auto response2 = TestUtility::parseYaml<envoy::service::discovery::v3::DiscoveryResponse>(response2_yaml); EXPECT_CALL(cm_, clusters()).WillOnce(Return(makeClusterInfoMaps({"cluster1", "cluster2"}))); expectAdd("cluster1", "1"); expectAdd("cluster3", "1"); EXPECT_CALL(cm_, removeCluster("cluster2")); const auto decoded_resources_2 = TestUtility::decodeResources<envoy::config::cluster::v3::Cluster>(response2); cds_callbacks_->onConfigUpdate(decoded_resources_2.refvec_, response2.version_info()); EXPECT_EQ("1", cds_->versionInfo()); } // Validate behavior when the config is delivered but it fails PGV validation. TEST_F(CdsApiImplTest, FailureInvalidConfig) { InSequence s; setup(); const std::string response1_yaml = R"EOF( version_info: '0' resources: - "@type": type.googleapis.com/envoy.config.cluster.v3.Cluster name: cluster1 type: EDS eds_cluster_config: eds_config: resource_api_version: V3 path: eds path - "@type": type.googleapis.com/envoy.config.cluster.v3.Cluster name: cluster1 type: EDS eds_cluster_config: eds_config: resource_api_version: V3 path: eds path )EOF"; auto response1 = TestUtility::parseYaml<envoy::service::discovery::v3::DiscoveryResponse>(response1_yaml); EXPECT_CALL(cm_, clusters()).WillRepeatedly(Return(makeClusterInfoMaps({}))); EXPECT_CALL(initialized_, ready()); const auto decoded_resources = TestUtility::decodeResources<envoy::config::cluster::v3::Cluster>(response1); EXPECT_THROW(cds_callbacks_->onConfigUpdate(decoded_resources.refvec_, response1.version_info()), EnvoyException); EXPECT_EQ("", cds_->versionInfo()); } // Validate behavior when the config fails delivery at the subscription level. TEST_F(CdsApiImplTest, FailureSubscription) { InSequence s; setup(); EXPECT_CALL(initialized_, ready()); // onConfigUpdateFailed() should not be called for gRPC stream connection failure cds_callbacks_->onConfigUpdateFailed(Envoy::Config::ConfigUpdateFailureReason::FetchTimedout, {}); EXPECT_EQ("", cds_->versionInfo()); } } // namespace } // namespace Upstream } // namespace Envoy
32.77957
100
0.723553
[ "vector" ]
33eaf574711dcdd689ce12ad0e2c32abd2be743b
2,137
cpp
C++
pyml/maths/src/arrayInitialisers.cpp
gf712/PyML
83849ff6e1c1bbcf9b87826ef673fb34622a0539
[ "MIT" ]
4
2018-11-23T07:45:51.000Z
2020-12-29T19:32:06.000Z
pyml/maths/src/arrayInitialisers.cpp
gf712/PyML
83849ff6e1c1bbcf9b87826ef673fb34622a0539
[ "MIT" ]
18
2017-11-16T08:32:42.000Z
2017-12-27T15:19:58.000Z
pyml/maths/src/arrayInitialisers.cpp
gf712/PyML
83849ff6e1c1bbcf9b87826ef673fb34622a0539
[ "MIT" ]
3
2018-10-31T17:09:22.000Z
2020-03-02T22:40:23.000Z
// // Created by gil on 22/11/17. // #include "pythonconverters.h" #include "arrayInitialisers.h" template <typename T> flatArray<T>* readFromPythonList(PyObject *pyList) { // read in array from Python list // check if it's a matrix or a vector int cols, rows; flatArray<T>* result = nullptr; if (PyFloat_Check(PyList_GET_ITEM(pyList, 0)) || PyLong_Check(PyList_GET_ITEM(pyList, 0))) { cols = static_cast<int>(PyList_GET_SIZE(pyList)); rows = 1; } else { rows = static_cast<int>(PyList_GET_SIZE(pyList)); cols = static_cast<int>(PyList_GET_SIZE(PyList_GET_ITEM(pyList, 0))); } result = convertPy_flatArray <T> (pyList, rows, cols); return result; } template <typename T> flatArray<T>* emptyArray(int rows, int cols) { flatArray<T>* result = nullptr; T* array = nullptr; int size = rows * cols; array = new T [size]; result = new flatArray <T> (array, rows, cols); delete [] array; return result; } template <typename T> inline flatArray<T>* identity(int n) { int row=0; int size = n * n; flatArray<T>* result = nullptr; T* array = nullptr; array = new T [size]; for (int i = 0; i < size; ++i) { if (i == row) { array[i] = 1; row += n + 1; } else { array[i] = 0; } } result = new flatArray <T> (array, n, n); delete [] array; return result; } template <typename T> inline flatArray<T>* constArray(int rows, int cols, double c) { T* array = nullptr; flatArray<T>* result = nullptr; int size = rows * cols; // convert c to type T c = static_cast<T>(c); array = new T [size]; for (int i = 0; i < size; ++i) { array[i] = c; } result = new flatArray <T> (array, rows, cols); delete [] array; return result; } template <typename T> inline flatArray<T>* zeroArray(int rows, int cols) { return constArray <T> (rows, cols, 0); } template <typename T> inline flatArray<T>* oneArray(int rows, int cols) { return constArray <T> (rows, cols, 1); }
19.252252
96
0.58306
[ "vector" ]
33eb6f1addf5f903172c8dd09b11183dc4e9cc0b
10,321
cpp
C++
src/3d/hybrid/matrix_cmd.cpp
wkrzemien/j-pet-mlem
4ed746f3fe79890e4141158cd49d1869938105de
[ "Apache-2.0" ]
null
null
null
src/3d/hybrid/matrix_cmd.cpp
wkrzemien/j-pet-mlem
4ed746f3fe79890e4141158cd49d1869938105de
[ "Apache-2.0" ]
5
2018-08-08T08:26:04.000Z
2020-05-13T13:33:39.000Z
src/3d/hybrid/matrix_cmd.cpp
wkrzemien/j-pet-mlem
4ed746f3fe79890e4141158cd49d1869938105de
[ "Apache-2.0" ]
5
2018-06-04T21:04:29.000Z
2021-07-03T14:19:39.000Z
/// \page cmd_3d_hybrid_matrix 3d_hybrid_matrix /// \brief 3D Hybrid PET system matrix construction tool /// /// Creates system matrix file and accomanying SVG & PNG files for single slice /// along z-axis. /// /// Authors /// ------- /// - Adam Strzelecki <adam.strzelecki@uj.edu.pl> /// - Piotr Bialas <piotr.bialas@uj.edu.pl> /// /// Usage /// ----- /// \verboutput 3d_hybrid_matrix /// /// \sa \ref cmd_3d_hybrid_phantom #include <random> #include "cmdline.h" #include "util/cmdline_types.h" #include "util/cmdline_hooks.h" #include "3d/hybrid/scanner.h" #include "2d/barrel/scanner_builder.h" #include "2d/barrel/generic_scanner.h" #include "2d/barrel/square_detector.h" #include "2d/barrel/sparse_matrix.h" #include "2d/barrel/matrix_pixel_major.h" #include "2d/geometry/pixel.h" #include "2d/barrel/lor.h" #include "common/model.h" #include "monte_carlo.h" #include "util/progress.h" #include "util/png_writer.h" #include "util/svg_ostream.h" #include "util/json.h" #include "util/backtrace.h" #include "options.h" #include "common/types.h" #include "common/mathematica_graphics.h" #if _OPENMP #include <omp.h> #endif #if HAVE_CUDA #include "cuda/matrix.h" #endif using SquareDetector = PET2D::Barrel::SquareDetector<F>; using Scanner2D = PET2D::Barrel::GenericScanner<SquareDetector, S>; using Scanner = PET3D::Hybrid::Scanner<Scanner2D>; using Pixel = PET2D::Pixel<Scanner2D::S>; using LOR = Scanner2D::LOR; using SparseMatrix = PET2D::Barrel::SparseMatrix<Pixel, LOR, Hit>; using ComputeMatrix = PET2D::Barrel::MatrixPixelMajor<Pixel, LOR, Hit>; template <class ScannerClass, class ModelClass, typename... ModelArgs> static void run(cmdline::parser& cl, ModelArgs... args); using MathematicaGraphics = Common::MathematicaGraphics<F>; int main(int argc, char* argv[]) { CMDLINE_TRY cmdline::parser cl; PET3D::Hybrid::add_matrix_options(cl); cl.parse_check(argc, argv); cmdline::load_accompanying_config(cl, false); if (!cl.exist("tof-step")) { cl.dontsave("tof-step"), cl.dontsave("s-dl"); } PET3D::Hybrid::calculate_scanner_options(cl, argc); #if _OPENMP if (cl.exist("n-threads")) { omp_set_num_threads(cl.get<int>("n-threads")); } #endif if (cl.exist("png") && !cl.exist("from")) { throw("need to specify --from lor when output --png option is specified"); } if (!cl.exist("png") && cl.exist("from")) { throw("need to specify output --png option when --from is specified"); } const auto& shape = cl.get<std::string>("shape"); if (shape != "square") { throw("only square is supported, unsupported shape: " + shape); } const auto& model_name = cl.get<std::string>("model"); const auto& length_scale = cl.get<double>("base-length"); if (model_name == "always") { run<Scanner2D, Common::AlwaysAccept<F>>(cl); } else if (model_name == "scintillator") { run<Scanner2D, Common::ScintillatorAccept<F>>(cl, length_scale); } else { throw("unknown model: " + model_name); } CMDLINE_CATCH } /// \function run template <class ScannerClass, class ModelClass, typename... ModelArgs> static void run(cmdline::parser& cl, ModelArgs... args) { auto scanner2D = PET2D::Barrel::ScannerBuilder<Scanner2D>::build_multiple_rings( PET3D_LONGITUDINAL_SCANNER_CL(cl, Scanner::F)); Scanner scanner(scanner2D, F(cl.get<double>("length"))); ModelClass model(args...); auto output_name = cl.get<cmdline::path>("output"); auto output_base_name = output_name.wo_ext(); if (output_base_name.length()) { std::ofstream out_graphics(output_base_name + ".m"); MathematicaGraphics graphics(out_graphics); graphics.add(scanner.barrel); } auto& n_detectors = cl.get<std::vector<int>>("n-detectors"); auto& n_pixels = cl.get<int>("n-pixels"); auto& m_pixel = cl.get<int>("m-pixel"); auto& s_pixel = cl.get<double>("s-pixel"); auto& n_emissions = cl.get<size_t>("n-emissions"); auto verbose = cl.count("verbose"); auto& z_position = cl.get<double>("z-position"); if (verbose) { std::cerr << " n pixels = " << n_pixels << std::endl; std::cerr << "pixel size = " << s_pixel << std::endl; } std::random_device rd; util::random::tausworthe rng(rd()); if (cl.exist("seed")) { rng.seed(cl.get<util::random::tausworthe::seed_type>("seed")); } if (verbose) { std::cerr << "Monte-Carlo:" << std::endl; #if _OPENMP #if HAVE_CUDA if (!cl.exist("gpu")) #endif std::cerr << " OpenMP threads = " << omp_get_max_threads() << std::endl; #endif std::cerr << " pixels in row = " << n_pixels << std::endl; std::cerr << " pixel size = " << s_pixel << std::endl; std::cerr << " fov radius = " << scanner2D.fov_radius() << std::endl; std::cerr << " outer radius = " << scanner2D.outer_radius() << std::endl; std::cerr << " emissions = " << n_emissions << std::endl; } ComputeMatrix::SparseMatrix sparse_matrix(n_pixels, scanner.barrel.size()); for (auto& fn : cl.rest()) { util::ibstream in(fn, std::ios::binary); ENSURE_IS_OPEN(in, "input matrix", fn); try { ComputeMatrix::SparseMatrix in_sparse_matrix(in); if (in_sparse_matrix.n_tof_positions() > 1) throw("hybrid Monte-Carlo does not support TOF positions"); if (verbose) { std::cerr << "read sparse matrix: " << fn << std::endl; std::cerr << " pixels in row = " << in_sparse_matrix.n_pixels_in_row() << std::endl; std::cerr << " pixel size = " << cl.get<double>("s-pixel"); std::cerr << " emissions = " << in_sparse_matrix.n_emissions() << std::endl; std::cerr << std::endl; } if (sparse_matrix.empty()) { sparse_matrix = in_sparse_matrix; // if we don't have stuff set, set it using matrix if (!cl.exist("n-pixels")) n_pixels = sparse_matrix.n_pixels_in_row(); } else { // join with previous matrix sparse_matrix << in_sparse_matrix; } } catch (std::string& ex) { throw(ex + ": " + fn); } catch (const char* ex) { throw(std::string(ex) + ": " + fn); } } ComputeMatrix matrix(n_pixels, scanner.barrel.size()); util::progress progress(verbose, matrix.total_n_pixels_in_triangle, 1); if (n_emissions == 0) { // don't run any simulation computation } #if HAVE_CUDA // GPU computation else if (cl.exist("gpu")) { bool was_empty = sparse_matrix.empty(); PET3D::Hybrid::GPU::Matrix::run<Scanner>( scanner, rng, n_emissions, z_position, n_pixels, s_pixel, cl.get<double>("base-length"), [&](int completed, bool finished) { progress(completed, finished); }, [&](LOR lor, Pixel pixel, Hit hits) { sparse_matrix.emplace_back(lor, 0, pixel, hits); }, cl.get<int>("cuda-device"), cl.get<int>("cuda-blocks"), cl.get<int>("cuda-threads"), [&](const char* device_name, int n_final_emissions) { n_emissions = n_final_emissions; if (verbose) { std::cerr << " CUDA device = " << device_name << std::endl; std::cerr << "final emissions = " << n_final_emissions << std::endl; } }); sparse_matrix.increment_n_emissions(n_emissions); if (!was_empty) { sparse_matrix.sort_by_lor_n_pixel(); sparse_matrix.merge_duplicates(); } } #endif // CPU reference computation else { if (!sparse_matrix.empty()) { matrix << sparse_matrix; sparse_matrix.resize(0); } PET3D::Hybrid::MonteCarlo<Scanner, ComputeMatrix> monte_carlo( scanner, matrix, s_pixel, m_pixel); monte_carlo(z_position, rng, model, n_emissions, progress); sparse_matrix = matrix.to_sparse(); } // generate output if (cl.exist("output")) { auto fn = cl.get<cmdline::path>("output"); auto fn_wo_ext = fn.wo_ext(); auto fn_wo_path = fn_wo_ext.wo_path(); bool full = cl.exist("full"); util::obstream out(fn, std::ios::binary | std::ios::trunc); if (full) { auto full_matrix = sparse_matrix.to_full(scanner.barrel.symmetry_descriptor()); out << full_matrix; } else { out << sparse_matrix; } std::ofstream os(fn_wo_ext + ".cfg", std::ios::trunc); os << cl; try { util::png_writer png(fn_wo_ext + ".png"); sparse_matrix.output_bitmap(png); } catch (const char* ex) { // don't bail out just produce warning std::cerr << "warning: " << ex << std::endl; } util::svg_ostream<F> svg(fn_wo_ext + ".svg", scanner.barrel.outer_radius(), scanner.barrel.outer_radius(), 1024., 1024.); svg.link_image(fn_wo_path + ".png", -(s_pixel * n_pixels) / 2, -(s_pixel * n_pixels) / 2, s_pixel * n_pixels, s_pixel * n_pixels); svg << const_cast<Scanner2D&>(scanner.barrel); } // visual debugging output if (cl.exist("png")) { LOR lor(0, 0); lor.first = cl.get<int>("from"); if (cl.exist("to")) { lor.second = cl.get<int>("to"); } else { lor.second = (lor.first + n_detectors[0] / 2) % n_detectors[0]; } if (lor.first < lor.second) std::swap(lor.first, lor.second); auto fn = cl.get<cmdline::path>("png"); auto fn_wo_ext = fn.wo_ext(); auto fn_wo_path = fn_wo_ext.wo_path(); util::png_writer png(fn); auto position = cl.get<int>("pos"); if (cl.exist("full")) { sparse_matrix.to_full(scanner.barrel.symmetry_descriptor()) .output_bitmap(png, lor, position); } else { sparse_matrix.output_bitmap(png, lor, position); } util::svg_ostream<F> svg(fn_wo_ext + ".svg", scanner.barrel.outer_radius(), scanner.barrel.outer_radius(), 1024., 1024.); svg.link_image(fn_wo_path + ".png", -(s_pixel * n_pixels) / 2, -(s_pixel * n_pixels) / 2, s_pixel * n_pixels, s_pixel * n_pixels); svg << const_cast<Scanner2D&>(scanner.barrel); } }
31.275758
80
0.606918
[ "geometry", "shape", "vector", "model", "3d" ]
33ed4b3e3a6779f444bcc183b9ef71b504693969
20,026
cpp
C++
llvm/3.4.2/llvm-3.4.2.src/lib/Target/Mips/MipsSEFrameLowering.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
36
2015-01-13T19:34:04.000Z
2022-03-07T22:22:15.000Z
llvm/3.4.2/llvm-3.4.2.src/lib/Target/Mips/MipsSEFrameLowering.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
7
2015-10-20T19:05:01.000Z
2021-11-13T14:55:47.000Z
llvm/3.4.2/llvm-3.4.2.src/lib/Target/Mips/MipsSEFrameLowering.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
18
2015-04-23T20:59:52.000Z
2021-11-18T20:06:39.000Z
//===-- MipsSEFrameLowering.cpp - Mips32/64 Frame Information -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the Mips32/64 implementation of TargetFrameLowering class. // //===----------------------------------------------------------------------===// #include "MipsSEFrameLowering.h" #include "MCTargetDesc/MipsBaseInfo.h" #include "MipsAnalyzeImmediate.h" #include "MipsMachineFunction.h" #include "MipsSEInstrInfo.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; namespace { typedef MachineBasicBlock::iterator Iter; static std::pair<unsigned, unsigned> getMFHiLoOpc(unsigned Src) { if (Mips::ACC64RegClass.contains(Src)) return std::make_pair((unsigned)Mips::PseudoMFHI, (unsigned)Mips::PseudoMFLO); if (Mips::ACC64DSPRegClass.contains(Src)) return std::make_pair((unsigned)Mips::MFHI_DSP, (unsigned)Mips::MFLO_DSP); if (Mips::ACC128RegClass.contains(Src)) return std::make_pair((unsigned)Mips::PseudoMFHI64, (unsigned)Mips::PseudoMFLO64); return std::make_pair(0, 0); } /// Helper class to expand pseudos. class ExpandPseudo { public: ExpandPseudo(MachineFunction &MF); bool expand(); private: bool expandInstr(MachineBasicBlock &MBB, Iter I); void expandLoadCCond(MachineBasicBlock &MBB, Iter I); void expandStoreCCond(MachineBasicBlock &MBB, Iter I); void expandLoadACC(MachineBasicBlock &MBB, Iter I, unsigned RegSize); void expandStoreACC(MachineBasicBlock &MBB, Iter I, unsigned MFHiOpc, unsigned MFLoOpc, unsigned RegSize); bool expandCopy(MachineBasicBlock &MBB, Iter I); bool expandCopyACC(MachineBasicBlock &MBB, Iter I, unsigned MFHiOpc, unsigned MFLoOpc); MachineFunction &MF; MachineRegisterInfo &MRI; }; } ExpandPseudo::ExpandPseudo(MachineFunction &MF_) : MF(MF_), MRI(MF.getRegInfo()) {} bool ExpandPseudo::expand() { bool Expanded = false; for (MachineFunction::iterator BB = MF.begin(), BBEnd = MF.end(); BB != BBEnd; ++BB) for (Iter I = BB->begin(), End = BB->end(); I != End;) Expanded |= expandInstr(*BB, I++); return Expanded; } bool ExpandPseudo::expandInstr(MachineBasicBlock &MBB, Iter I) { switch(I->getOpcode()) { case Mips::LOAD_CCOND_DSP: expandLoadCCond(MBB, I); break; case Mips::STORE_CCOND_DSP: expandStoreCCond(MBB, I); break; case Mips::LOAD_ACC64: case Mips::LOAD_ACC64DSP: expandLoadACC(MBB, I, 4); break; case Mips::LOAD_ACC128: expandLoadACC(MBB, I, 8); break; case Mips::STORE_ACC64: expandStoreACC(MBB, I, Mips::PseudoMFHI, Mips::PseudoMFLO, 4); break; case Mips::STORE_ACC64DSP: expandStoreACC(MBB, I, Mips::MFHI_DSP, Mips::MFLO_DSP, 4); break; case Mips::STORE_ACC128: expandStoreACC(MBB, I, Mips::PseudoMFHI64, Mips::PseudoMFLO64, 8); break; case TargetOpcode::COPY: if (!expandCopy(MBB, I)) return false; break; default: return false; } MBB.erase(I); return true; } void ExpandPseudo::expandLoadCCond(MachineBasicBlock &MBB, Iter I) { // load $vr, FI // copy ccond, $vr assert(I->getOperand(0).isReg() && I->getOperand(1).isFI()); const MipsSEInstrInfo &TII = *static_cast<const MipsSEInstrInfo*>(MF.getTarget().getInstrInfo()); const MipsRegisterInfo &RegInfo = *static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); const TargetRegisterClass *RC = RegInfo.intRegClass(4); unsigned VR = MRI.createVirtualRegister(RC); unsigned Dst = I->getOperand(0).getReg(), FI = I->getOperand(1).getIndex(); TII.loadRegFromStack(MBB, I, VR, FI, RC, &RegInfo, 0); BuildMI(MBB, I, I->getDebugLoc(), TII.get(TargetOpcode::COPY), Dst) .addReg(VR, RegState::Kill); } void ExpandPseudo::expandStoreCCond(MachineBasicBlock &MBB, Iter I) { // copy $vr, ccond // store $vr, FI assert(I->getOperand(0).isReg() && I->getOperand(1).isFI()); const MipsSEInstrInfo &TII = *static_cast<const MipsSEInstrInfo*>(MF.getTarget().getInstrInfo()); const MipsRegisterInfo &RegInfo = *static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); const TargetRegisterClass *RC = RegInfo.intRegClass(4); unsigned VR = MRI.createVirtualRegister(RC); unsigned Src = I->getOperand(0).getReg(), FI = I->getOperand(1).getIndex(); BuildMI(MBB, I, I->getDebugLoc(), TII.get(TargetOpcode::COPY), VR) .addReg(Src, getKillRegState(I->getOperand(0).isKill())); TII.storeRegToStack(MBB, I, VR, true, FI, RC, &RegInfo, 0); } void ExpandPseudo::expandLoadACC(MachineBasicBlock &MBB, Iter I, unsigned RegSize) { // load $vr0, FI // copy lo, $vr0 // load $vr1, FI + 4 // copy hi, $vr1 assert(I->getOperand(0).isReg() && I->getOperand(1).isFI()); const MipsSEInstrInfo &TII = *static_cast<const MipsSEInstrInfo*>(MF.getTarget().getInstrInfo()); const MipsRegisterInfo &RegInfo = *static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); const TargetRegisterClass *RC = RegInfo.intRegClass(RegSize); unsigned VR0 = MRI.createVirtualRegister(RC); unsigned VR1 = MRI.createVirtualRegister(RC); unsigned Dst = I->getOperand(0).getReg(), FI = I->getOperand(1).getIndex(); unsigned Lo = RegInfo.getSubReg(Dst, Mips::sub_lo); unsigned Hi = RegInfo.getSubReg(Dst, Mips::sub_hi); DebugLoc DL = I->getDebugLoc(); const MCInstrDesc &Desc = TII.get(TargetOpcode::COPY); TII.loadRegFromStack(MBB, I, VR0, FI, RC, &RegInfo, 0); BuildMI(MBB, I, DL, Desc, Lo).addReg(VR0, RegState::Kill); TII.loadRegFromStack(MBB, I, VR1, FI, RC, &RegInfo, RegSize); BuildMI(MBB, I, DL, Desc, Hi).addReg(VR1, RegState::Kill); } void ExpandPseudo::expandStoreACC(MachineBasicBlock &MBB, Iter I, unsigned MFHiOpc, unsigned MFLoOpc, unsigned RegSize) { // mflo $vr0, src // store $vr0, FI // mfhi $vr1, src // store $vr1, FI + 4 assert(I->getOperand(0).isReg() && I->getOperand(1).isFI()); const MipsSEInstrInfo &TII = *static_cast<const MipsSEInstrInfo*>(MF.getTarget().getInstrInfo()); const MipsRegisterInfo &RegInfo = *static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); const TargetRegisterClass *RC = RegInfo.intRegClass(RegSize); unsigned VR0 = MRI.createVirtualRegister(RC); unsigned VR1 = MRI.createVirtualRegister(RC); unsigned Src = I->getOperand(0).getReg(), FI = I->getOperand(1).getIndex(); unsigned SrcKill = getKillRegState(I->getOperand(0).isKill()); DebugLoc DL = I->getDebugLoc(); BuildMI(MBB, I, DL, TII.get(MFLoOpc), VR0).addReg(Src); TII.storeRegToStack(MBB, I, VR0, true, FI, RC, &RegInfo, 0); BuildMI(MBB, I, DL, TII.get(MFHiOpc), VR1).addReg(Src, SrcKill); TII.storeRegToStack(MBB, I, VR1, true, FI, RC, &RegInfo, RegSize); } bool ExpandPseudo::expandCopy(MachineBasicBlock &MBB, Iter I) { unsigned Src = I->getOperand(1).getReg(); std::pair<unsigned, unsigned> Opcodes = getMFHiLoOpc(Src); if (!Opcodes.first) return false; return expandCopyACC(MBB, I, Opcodes.first, Opcodes.second); } bool ExpandPseudo::expandCopyACC(MachineBasicBlock &MBB, Iter I, unsigned MFHiOpc, unsigned MFLoOpc) { // mflo $vr0, src // copy dst_lo, $vr0 // mfhi $vr1, src // copy dst_hi, $vr1 const MipsSEInstrInfo &TII = *static_cast<const MipsSEInstrInfo*>(MF.getTarget().getInstrInfo()); const MipsRegisterInfo &RegInfo = *static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); unsigned Dst = I->getOperand(0).getReg(), Src = I->getOperand(1).getReg(); unsigned VRegSize = RegInfo.getMinimalPhysRegClass(Dst)->getSize() / 2; const TargetRegisterClass *RC = RegInfo.intRegClass(VRegSize); unsigned VR0 = MRI.createVirtualRegister(RC); unsigned VR1 = MRI.createVirtualRegister(RC); unsigned SrcKill = getKillRegState(I->getOperand(1).isKill()); unsigned DstLo = RegInfo.getSubReg(Dst, Mips::sub_lo); unsigned DstHi = RegInfo.getSubReg(Dst, Mips::sub_hi); DebugLoc DL = I->getDebugLoc(); BuildMI(MBB, I, DL, TII.get(MFLoOpc), VR0).addReg(Src); BuildMI(MBB, I, DL, TII.get(TargetOpcode::COPY), DstLo) .addReg(VR0, RegState::Kill); BuildMI(MBB, I, DL, TII.get(MFHiOpc), VR1).addReg(Src, SrcKill); BuildMI(MBB, I, DL, TII.get(TargetOpcode::COPY), DstHi) .addReg(VR1, RegState::Kill); return true; } unsigned MipsSEFrameLowering::ehDataReg(unsigned I) const { static const unsigned EhDataReg[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 }; static const unsigned EhDataReg64[] = { Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64 }; return STI.isABI_N64() ? EhDataReg64[I] : EhDataReg[I]; } void MipsSEFrameLowering::emitPrologue(MachineFunction &MF) const { MachineBasicBlock &MBB = MF.front(); MachineFrameInfo *MFI = MF.getFrameInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); const MipsSEInstrInfo &TII = *static_cast<const MipsSEInstrInfo*>(MF.getTarget().getInstrInfo()); const MipsRegisterInfo &RegInfo = *static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); MachineBasicBlock::iterator MBBI = MBB.begin(); DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc(); unsigned SP = STI.isABI_N64() ? Mips::SP_64 : Mips::SP; unsigned FP = STI.isABI_N64() ? Mips::FP_64 : Mips::FP; unsigned ZERO = STI.isABI_N64() ? Mips::ZERO_64 : Mips::ZERO; unsigned ADDu = STI.isABI_N64() ? Mips::DADDu : Mips::ADDu; // First, compute final stack size. uint64_t StackSize = MFI->getStackSize(); // No need to allocate space on the stack. if (StackSize == 0 && !MFI->adjustsStack()) return; MachineModuleInfo &MMI = MF.getMMI(); const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo(); MachineLocation DstML, SrcML; // Adjust stack. TII.adjustStackPtr(SP, -StackSize, MBB, MBBI); // emit ".cfi_def_cfa_offset StackSize" MCSymbol *AdjustSPLabel = MMI.getContext().CreateTempSymbol(); BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL)).addSym(AdjustSPLabel); MMI.addFrameInst( MCCFIInstruction::createDefCfaOffset(AdjustSPLabel, -StackSize)); const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); if (CSI.size()) { // Find the instruction past the last instruction that saves a callee-saved // register to the stack. for (unsigned i = 0; i < CSI.size(); ++i) ++MBBI; // Iterate over list of callee-saved registers and emit .cfi_offset // directives. MCSymbol *CSLabel = MMI.getContext().CreateTempSymbol(); BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL)).addSym(CSLabel); for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(), E = CSI.end(); I != E; ++I) { int64_t Offset = MFI->getObjectOffset(I->getFrameIdx()); unsigned Reg = I->getReg(); // If Reg is a double precision register, emit two cfa_offsets, // one for each of the paired single precision registers. if (Mips::AFGR64RegClass.contains(Reg)) { unsigned Reg0 = MRI->getDwarfRegNum(RegInfo.getSubReg(Reg, Mips::sub_lo), true); unsigned Reg1 = MRI->getDwarfRegNum(RegInfo.getSubReg(Reg, Mips::sub_hi), true); if (!STI.isLittle()) std::swap(Reg0, Reg1); MMI.addFrameInst( MCCFIInstruction::createOffset(CSLabel, Reg0, Offset)); MMI.addFrameInst( MCCFIInstruction::createOffset(CSLabel, Reg1, Offset + 4)); } else { // Reg is either in GPR32 or FGR32. MMI.addFrameInst(MCCFIInstruction::createOffset( CSLabel, MRI->getDwarfRegNum(Reg, 1), Offset)); } } } if (MipsFI->callsEhReturn()) { const TargetRegisterClass *RC = STI.isABI_N64() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass; // Insert instructions that spill eh data registers. for (int I = 0; I < 4; ++I) { if (!MBB.isLiveIn(ehDataReg(I))) MBB.addLiveIn(ehDataReg(I)); TII.storeRegToStackSlot(MBB, MBBI, ehDataReg(I), false, MipsFI->getEhDataRegFI(I), RC, &RegInfo); } // Emit .cfi_offset directives for eh data registers. MCSymbol *CSLabel2 = MMI.getContext().CreateTempSymbol(); BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL)).addSym(CSLabel2); for (int I = 0; I < 4; ++I) { int64_t Offset = MFI->getObjectOffset(MipsFI->getEhDataRegFI(I)); unsigned Reg = MRI->getDwarfRegNum(ehDataReg(I), true); MMI.addFrameInst(MCCFIInstruction::createOffset(CSLabel2, Reg, Offset)); } } // if framepointer enabled, set it to point to the stack pointer. if (hasFP(MF)) { // Insert instruction "move $fp, $sp" at this location. BuildMI(MBB, MBBI, dl, TII.get(ADDu), FP).addReg(SP).addReg(ZERO); // emit ".cfi_def_cfa_register $fp" MCSymbol *SetFPLabel = MMI.getContext().CreateTempSymbol(); BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL)).addSym(SetFPLabel); MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister( SetFPLabel, MRI->getDwarfRegNum(FP, true))); } } void MipsSEFrameLowering::emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const { MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); MachineFrameInfo *MFI = MF.getFrameInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); const MipsSEInstrInfo &TII = *static_cast<const MipsSEInstrInfo*>(MF.getTarget().getInstrInfo()); const MipsRegisterInfo &RegInfo = *static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); DebugLoc dl = MBBI->getDebugLoc(); unsigned SP = STI.isABI_N64() ? Mips::SP_64 : Mips::SP; unsigned FP = STI.isABI_N64() ? Mips::FP_64 : Mips::FP; unsigned ZERO = STI.isABI_N64() ? Mips::ZERO_64 : Mips::ZERO; unsigned ADDu = STI.isABI_N64() ? Mips::DADDu : Mips::ADDu; // if framepointer enabled, restore the stack pointer. if (hasFP(MF)) { // Find the first instruction that restores a callee-saved register. MachineBasicBlock::iterator I = MBBI; for (unsigned i = 0; i < MFI->getCalleeSavedInfo().size(); ++i) --I; // Insert instruction "move $sp, $fp" at this location. BuildMI(MBB, I, dl, TII.get(ADDu), SP).addReg(FP).addReg(ZERO); } if (MipsFI->callsEhReturn()) { const TargetRegisterClass *RC = STI.isABI_N64() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass; // Find first instruction that restores a callee-saved register. MachineBasicBlock::iterator I = MBBI; for (unsigned i = 0; i < MFI->getCalleeSavedInfo().size(); ++i) --I; // Insert instructions that restore eh data registers. for (int J = 0; J < 4; ++J) { TII.loadRegFromStackSlot(MBB, I, ehDataReg(J), MipsFI->getEhDataRegFI(J), RC, &RegInfo); } } // Get the number of bytes from FrameInfo uint64_t StackSize = MFI->getStackSize(); if (!StackSize) return; // Adjust stack. TII.adjustStackPtr(SP, StackSize, MBB, MBBI); } bool MipsSEFrameLowering:: spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const std::vector<CalleeSavedInfo> &CSI, const TargetRegisterInfo *TRI) const { MachineFunction *MF = MBB.getParent(); MachineBasicBlock *EntryBlock = MF->begin(); const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo(); for (unsigned i = 0, e = CSI.size(); i != e; ++i) { // Add the callee-saved register as live-in. Do not add if the register is // RA and return address is taken, because it has already been added in // method MipsTargetLowering::LowerRETURNADDR. // It's killed at the spill, unless the register is RA and return address // is taken. unsigned Reg = CSI[i].getReg(); bool IsRAAndRetAddrIsTaken = (Reg == Mips::RA || Reg == Mips::RA_64) && MF->getFrameInfo()->isReturnAddressTaken(); if (!IsRAAndRetAddrIsTaken) EntryBlock->addLiveIn(Reg); // Insert the spill to the stack frame. bool IsKill = !IsRAAndRetAddrIsTaken; const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); TII.storeRegToStackSlot(*EntryBlock, MI, Reg, IsKill, CSI[i].getFrameIdx(), RC, TRI); } return true; } bool MipsSEFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { const MachineFrameInfo *MFI = MF.getFrameInfo(); // Reserve call frame if the size of the maximum call frame fits into 16-bit // immediate field and there are no variable sized objects on the stack. // Make sure the second register scavenger spill slot can be accessed with one // instruction. return isInt<16>(MFI->getMaxCallFrameSize() + getStackAlignment()) && !MFI->hasVarSizedObjects(); } // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions void MipsSEFrameLowering:: eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const { const MipsSEInstrInfo &TII = *static_cast<const MipsSEInstrInfo*>(MF.getTarget().getInstrInfo()); if (!hasReservedCallFrame(MF)) { int64_t Amount = I->getOperand(0).getImm(); if (I->getOpcode() == Mips::ADJCALLSTACKDOWN) Amount = -Amount; unsigned SP = STI.isABI_N64() ? Mips::SP_64 : Mips::SP; TII.adjustStackPtr(SP, Amount, MBB, I); } MBB.erase(I); } void MipsSEFrameLowering:: processFunctionBeforeCalleeSavedScan(MachineFunction &MF, RegScavenger *RS) const { MachineRegisterInfo &MRI = MF.getRegInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); unsigned FP = STI.isABI_N64() ? Mips::FP_64 : Mips::FP; // Mark $fp as used if function has dedicated frame pointer. if (hasFP(MF)) MRI.setPhysRegUsed(FP); // Create spill slots for eh data registers if function calls eh_return. if (MipsFI->callsEhReturn()) MipsFI->createEhDataRegsFI(); // Expand pseudo instructions which load, store or copy accumulators. // Add an emergency spill slot if a pseudo was expanded. if (ExpandPseudo(MF).expand()) { // The spill slot should be half the size of the accumulator. If target is // mips64, it should be 64-bit, otherwise it should be 32-bt. const TargetRegisterClass *RC = STI.hasMips64() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass; int FI = MF.getFrameInfo()->CreateStackObject(RC->getSize(), RC->getAlignment(), false); RS->addScavengingFrameIndex(FI); } // Set scavenging frame index if necessary. uint64_t MaxSPOffset = MF.getInfo<MipsFunctionInfo>()->getIncomingArgSize() + estimateStackSize(MF); if (isInt<16>(MaxSPOffset)) return; const TargetRegisterClass *RC = STI.isABI_N64() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass; int FI = MF.getFrameInfo()->CreateStackObject(RC->getSize(), RC->getAlignment(), false); RS->addScavengingFrameIndex(FI); } const MipsFrameLowering * llvm::createMipsSEFrameLowering(const MipsSubtarget &ST) { return new MipsSEFrameLowering(ST); }
36.410909
80
0.667482
[ "vector" ]
33eeb8325702a3c1156f3ff8513531085e7ef9d4
2,060
cpp
C++
src/IceRay/camera/sphere/horizontal.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
2
2020-09-04T12:27:15.000Z
2022-01-17T14:49:40.000Z
src/IceRay/camera/sphere/horizontal.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
null
null
null
src/IceRay/camera/sphere/horizontal.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
1
2020-09-04T12:27:52.000Z
2020-09-04T12:27:52.000Z
#include "./horizontal.hpp" #include "math/geometry/deg2rad.hpp" using namespace GS_DDMRM::S_IceRay::S_camera; S_sphere::GC_horizontal::GC_horizontal() :GC_horizontal(::math::geometry::deg2rad(90), ::math::geometry::deg2rad(90) ) { } S_sphere::GC_horizontal::GC_horizontal( T_scalar const& P_theta, T_scalar const& P_phi, T_scalar const& P_radius ) : M2_theta( P_theta ) , M2_phi( P_phi ) , M2_radius( P_radius ) { } S_sphere::GC_horizontal::~GC_horizontal() { } S_sphere::GC_horizontal::T_size S_sphere::GC_horizontal::Fv_beam ( T_beam & P_beam ,T_coord2D const& P_uv )const { static T_scalar const Isc_phi = ::math::constants::PHI; T_coord & I_origin = P_beam[0].M_origin; I_origin[0] = 0; I_origin[1] = 0; I_origin[2] = 0; T_coord & I_direction = P_beam[0].M_direction; I_direction[0] = M2_radius * sin( P_uv[0] * M2_theta/2 ); I_direction[1] = M2_radius * sin( Isc_phi/2 - P_uv[1] * M2_phi/2 ) * cos( P_uv[0] * M2_theta/2 ); I_direction[2] = M2_radius * cos( Isc_phi/2 - P_uv[1] * M2_phi/2 ) * cos( P_uv[0] * M2_theta/2 ); return 1; } void S_sphere::GC_horizontal::Fv_system( T_affine &P_affine, T_coord2D const& P_uv )const { static T_scalar const Isc_phi = ::math::constants::PHI; T_coord I_eY; I_eY[0] = sin( P_uv[1] * M2_theta/2 ); I_eY[1] = sin( Isc_phi/2 - P_uv[0] * M2_phi/2 ) * cos( P_uv[1] * M2_theta/2 ); I_eY[2] = cos( Isc_phi/2 - P_uv[0] * M2_phi/2 ) * cos( P_uv[1] * M2_theta/2 ); T_coord I_z; ::math::linear::vector::load( I_z, 0, 0, 1 ); T_coord I_eX; ::math::linear::vector::cross( I_eX, I_eY, I_z ); ::math::linear::vector::length( I_eX, T_scalar(1) ); T_coord I_eZ; ::math::linear::vector::cross( I_eZ, I_eY, I_eX ); ::math::linear::vector::length( I_eZ, T_scalar(1) ); ::math::linear::vector::fill( P_affine.vector(), 0 ); ::math::linear::matrix::system( P_affine.matrix(), I_eX, I_eY, I_eZ ); }
31.692308
120
0.609223
[ "geometry", "vector" ]
33f19490cd06225ebaf3c8cd0d91db4d1bbc2580
7,268
cc
C++
login_manager/chrome_setup_test.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
5
2019-01-19T15:38:48.000Z
2021-10-06T03:59:46.000Z
login_manager/chrome_setup_test.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
null
null
null
login_manager/chrome_setup_test.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
1
2019-02-15T23:05:30.000Z
2019-02-15T23:05:30.000Z
// Copyright 2016 The Chromium OS 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 "login_manager/chrome_setup.h" #include <set> #include <base/bind.h> #include <base/json/json_writer.h> #include <base/strings/string_number_conversions.h> #include <base/strings/string_split.h> #include <base/strings/stringprintf.h> #include <base/values.h> #include <chromeos-config/libcros_config/fake_cros_config.h> #include <chromeos/ui/chromium_command_builder.h> #include <gtest/gtest.h> using chromeos::ui::ChromiumCommandBuilder; namespace login_manager { class ChromeSetupTest : public ::testing::Test { public: ChromeSetupTest() {} protected: // Two sizes are supported for the wallpaper flags. const std::vector<std::string> kSizes{"small", "large"}; const std::string kNotPresent = "<not present>"; const std::string kModel = "reef"; const base::Callback<bool(const base::FilePath&)> kPathInSetCallback = base::Bind(&ChromeSetupTest::PathInSet, base::Unretained(this)); // This returns true if the path is found in the paths_ set. bool PathInSet(const base::FilePath& path) { return paths_.count(path.MaybeAsASCII()) != 0; } // Returns the value of the given flag [name], by looking it up in [args]. // Note that the value can be missing, in which case "" is returned. // If the flag is not present in the list, returns kNotPresent. std::string GetFlag(const std::vector<std::string>& args, const std::string& name) { for (auto arg : args) { std::vector<std::string> tokens = SplitString(arg, "=", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); CHECK_LE(tokens.size(), 2U); if (tokens[0] == name) return tokens.size() == 1 ? "" : tokens[1]; } return kNotPresent; } // Get the name of the wallpaper flag for the given flag type and size. std::string GetFlagName(const std::string& flag_type, const std::string& size) { return base::StringPrintf("--%s-wallpaper-%s", flag_type.c_str(), size.c_str()); } // Get the expected pathname for the given base name and size. std::string GetPath(const std::string& base, const std::string& size) { return base::StringPrintf("/usr/share/chromeos-assets/wallpaper/%s_%s.jpg", base.c_str(), size.c_str()); } ChromiumCommandBuilder builder_; // Set of paths to report as existing. std::set<std::string> paths_{ GetPath("default", "small"), GetPath("default", "large"), GetPath("child", "small"), GetPath("child", "large"), GetPath("guest", "small"), GetPath("guest", "large"), }; brillo::FakeCrosConfig cros_config_; }; TEST_F(ChromeSetupTest, TestOem) { paths_.insert(GetPath("oem", "small")); paths_.insert(GetPath("oem", "large")); login_manager::SetUpWallpaperFlags(&builder_, nullptr, kPathInSetCallback); std::vector<std::string> argv = builder_.arguments(); ASSERT_EQ(7, argv.size()); for (std::string size : kSizes) { EXPECT_EQ(GetPath("oem", size), GetFlag(argv, GetFlagName("default", size))); EXPECT_EQ(GetPath("child", size), GetFlag(argv, GetFlagName("child", size))); EXPECT_EQ(GetPath("guest", size), GetFlag(argv, GetFlagName("guest", size))); } EXPECT_EQ("", GetFlag(argv, "--default-wallpaper-is-oem")); } TEST_F(ChromeSetupTest, TestDefault) { login_manager::SetUpWallpaperFlags(&builder_, nullptr, kPathInSetCallback); std::vector<std::string> argv = builder_.arguments(); ASSERT_EQ(6, argv.size()); for (std::string size : kSizes) { EXPECT_EQ(GetPath("default", size), GetFlag(argv, GetFlagName("default", size))); EXPECT_EQ(GetPath("child", size), GetFlag(argv, GetFlagName("child", size))); EXPECT_EQ(GetPath("guest", size), GetFlag(argv, GetFlagName("guest", size))); } EXPECT_EQ(kNotPresent, GetFlag(argv, "--default-wallpaper-is-oem")); } TEST_F(ChromeSetupTest, TestModelDoesNotExist) { cros_config_.SetString("/", login_manager::kWallpaperProperty, kModel); login_manager::SetUpWallpaperFlags(&builder_, &cros_config_, kPathInSetCallback); std::vector<std::string> argv = builder_.arguments(); ASSERT_EQ(6, argv.size()); for (std::string size : kSizes) { EXPECT_EQ(GetPath("default", size), GetFlag(argv, GetFlagName("default", size))); EXPECT_EQ(GetPath("child", size), GetFlag(argv, GetFlagName("child", size))); EXPECT_EQ(GetPath("guest", size), GetFlag(argv, GetFlagName("guest", size))); } EXPECT_EQ(kNotPresent, GetFlag(argv, "--default-wallpaper-is-oem")); } TEST_F(ChromeSetupTest, TestModelExists) { cros_config_.SetString("/", login_manager::kWallpaperProperty, kModel); paths_.insert(GetPath(kModel, "large")); paths_.insert(GetPath(kModel, "small")); login_manager::SetUpWallpaperFlags(&builder_, &cros_config_, kPathInSetCallback); std::vector<std::string> argv = builder_.arguments(); ASSERT_EQ(6, argv.size()); for (std::string size : kSizes) { EXPECT_EQ(GetPath(kModel, size), GetFlag(argv, GetFlagName("default", size))); EXPECT_EQ(GetPath("child", size), GetFlag(argv, GetFlagName("child", size))); EXPECT_EQ(GetPath("guest", size), GetFlag(argv, GetFlagName("guest", size))); } EXPECT_EQ(kNotPresent, GetFlag(argv, "--default-wallpaper-is-oem")); } TEST_F(ChromeSetupTest, TestPowerButtonPosition) { login_manager::SetUpPowerButtonPositionFlag(&builder_, &cros_config_); std::vector<std::string> argv = builder_.arguments(); ASSERT_EQ(0, argv.size()); const std::string kPowerButtonEdge = "left"; cros_config_.SetString(login_manager::kPowerButtonPositionPath, login_manager::kPowerButtonEdgeField, kPowerButtonEdge); login_manager::SetUpPowerButtonPositionFlag(&builder_, &cros_config_); argv = builder_.arguments(); ASSERT_EQ(0, argv.size()); // Add "--ash-power-button-position" flag only if both kPowerButtonEdgeField // and kPowerButtonPositionField are set correctly. const std::string kPowerButtonPosition = "0.3"; cros_config_.SetString(login_manager::kPowerButtonPositionPath, login_manager::kPowerButtonPositionField, kPowerButtonPosition); login_manager::SetUpPowerButtonPositionFlag(&builder_, &cros_config_); argv = builder_.arguments(); ASSERT_EQ(1, argv.size()); base::DictionaryValue position_info; position_info.SetString(login_manager::kPowerButtonEdgeField, kPowerButtonEdge); double position_as_double = 0; base::StringToDouble(kPowerButtonPosition, &position_as_double); position_info.SetDouble(login_manager::kPowerButtonPositionField, position_as_double); std::string json_position_info; base::JSONWriter::Write(position_info, &json_position_info); EXPECT_EQ(json_position_info, GetFlag(argv, "--ash-power-button-position")); } } // namespace login_manager
39.934066
79
0.672124
[ "vector" ]
33f1bdb7936cf91068a50f5c7098e3f3c8a98e95
10,958
c++
C++
third_party/capnproto/c++/src/kj/test.c++
17zhangw/peloton
484d76df9344cb5c153a2c361c5d5018912d4cf4
[ "Apache-2.0" ]
2,706
2018-04-05T18:28:50.000Z
2022-03-29T16:56:59.000Z
third_party/capnproto/c++/src/kj/test.c++
17zhangw/peloton
484d76df9344cb5c153a2c361c5d5018912d4cf4
[ "Apache-2.0" ]
242
2018-04-05T22:30:42.000Z
2022-03-19T01:55:11.000Z
third_party/capnproto/c++/src/kj/test.c++
17zhangw/peloton
484d76df9344cb5c153a2c361c5d5018912d4cf4
[ "Apache-2.0" ]
464
2018-04-05T19:10:34.000Z
2022-03-28T13:33:32.000Z
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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 "test.h" #include "main.h" #include "io.h" #include "miniposix.h" #include <stdlib.h> #include <signal.h> #include <string.h> #ifndef _WIN32 #include <sys/mman.h> #endif namespace kj { namespace { TestCase* testCasesHead = nullptr; TestCase** testCasesTail = &testCasesHead; } // namespace TestCase::TestCase(const char* file, uint line, const char* description) : file(file), line(line), description(description), next(nullptr), prev(testCasesTail), matchedFilter(false) { *prev = this; testCasesTail = &next; } TestCase::~TestCase() { *prev = next; if (next == nullptr) { testCasesTail = prev; } else { next->prev = prev; } } // ======================================================================================= namespace _ { // private GlobFilter::GlobFilter(const char* pattern): pattern(heapString(pattern)) {} GlobFilter::GlobFilter(ArrayPtr<const char> pattern): pattern(heapString(pattern)) {} bool GlobFilter::matches(StringPtr name) { // Get out your computer science books. We're implementing a non-deterministic finite automaton. // // Our NDFA has one "state" corresponding to each character in the pattern. // // As you may recall, an NDFA can be transformed into a DFA where every state in the DFA // represents some combination of states in the NDFA. Therefore, we actually have to store a // list of states here. (Actually, what we really want is a set of states, but because our // patterns are mostly non-cyclic a list of states should work fine and be a bit more efficient.) // Our state list starts out pointing only at the start of the pattern. states.resize(0); states.add(0); Vector<uint> scratch; // Iterate through each character in the name. for (char c: name) { // Pull the current set of states off to the side, so that we can populate `states` with the // new set of states. Vector<uint> oldStates = kj::mv(states); states = kj::mv(scratch); states.resize(0); // The pattern can omit a leading path. So if we're at a '/' then enter the state machine at // the beginning on the next char. if (c == '/' || c == '\\') { states.add(0); } // Process each state. for (uint state: oldStates) { applyState(c, state); } // Store the previous state vector for reuse. scratch = kj::mv(oldStates); } // If any one state is at the end of the pattern (or at a wildcard just before the end of the // pattern), we have a match. for (uint state: states) { while (state < pattern.size() && pattern[state] == '*') { ++state; } if (state == pattern.size()) { return true; } } return false; } void GlobFilter::applyState(char c, int state) { if (state < pattern.size()) { switch (pattern[state]) { case '*': // At a '*', we both re-add the current state and attempt to match the *next* state. if (c != '/' && c != '\\') { // '*' doesn't match '/'. states.add(state); } applyState(c, state + 1); break; case '?': // A '?' matches one character (never a '/'). if (c != '/' && c != '\\') { states.add(state + 1); } break; default: // Any other character matches only itself. if (c == pattern[state]) { states.add(state + 1); } break; } } } } // namespace _ (private) // ======================================================================================= namespace { class TestExceptionCallback: public ExceptionCallback { public: TestExceptionCallback(ProcessContext& context): context(context) {} bool failed() { return sawError; } void logMessage(LogSeverity severity, const char* file, int line, int contextDepth, String&& text) override { void* traceSpace[32]; auto trace = getStackTrace(traceSpace, 2); if (text.size() == 0) { text = kj::heapString("expectation failed"); } text = kj::str(kj::repeat('_', contextDepth), file, ':', line, ": ", kj::mv(text)); if (severity == LogSeverity::ERROR || severity == LogSeverity::FATAL) { sawError = true; context.error(kj::str(text, "\nstack: ", strArray(trace, " "), stringifyStackTrace(trace))); } else { context.warning(text); } } private: ProcessContext& context; bool sawError = false; }; } // namespace class TestRunner { public: explicit TestRunner(ProcessContext& context) : context(context), useColor(isatty(STDOUT_FILENO)) {} MainFunc getMain() { return MainBuilder(context, "KJ Test Runner (version not applicable)", "Run all tests that have been linked into the binary with this test runner.") .addOptionWithArg({'f', "filter"}, KJ_BIND_METHOD(*this, setFilter), "<file>[:<line>]", "Run only the specified test case(s). You may use a '*' wildcard in <file>. You may " "also omit any prefix of <file>'s path; test from all matching files will run. " "You may specify multiple filters; any test matching at least one filter will run. " "<line> may be a range, e.g. \"100-500\".") .addOption({'l', "list"}, KJ_BIND_METHOD(*this, setList), "List all test cases that would run, but don't run them. If --filter is specified " "then only the match tests will be listed.") .callAfterParsing(KJ_BIND_METHOD(*this, run)) .build(); } MainBuilder::Validity setFilter(StringPtr pattern) { hasFilter = true; ArrayPtr<const char> filePattern = pattern; uint minLine = kj::minValue; uint maxLine = kj::maxValue; KJ_IF_MAYBE(colonPos, pattern.findLast(':')) { char* end; StringPtr lineStr = pattern.slice(*colonPos + 1); bool parsedRange = false; minLine = strtoul(lineStr.cStr(), &end, 0); if (end != lineStr.begin()) { if (*end == '-') { // A range. const char* part2 = end + 1; maxLine = strtoul(part2, &end, 0); if (end > part2 && *end == '\0') { parsedRange = true; } } else if (*end == '\0') { parsedRange = true; maxLine = minLine; } } if (parsedRange) { // We have an exact line number. filePattern = pattern.slice(0, *colonPos); } else { // Can't parse as a number. Maybe the colon is part of a Windows path name or something. // Let's just keep it as part of the file pattern. minLine = kj::minValue; maxLine = kj::maxValue; } } _::GlobFilter filter(filePattern); for (TestCase* testCase = testCasesHead; testCase != nullptr; testCase = testCase->next) { if (!testCase->matchedFilter && filter.matches(testCase->file) && testCase->line >= minLine && testCase->line <= maxLine) { testCase->matchedFilter = true; } } return true; } MainBuilder::Validity setList() { listOnly = true; return true; } MainBuilder::Validity run() { if (testCasesHead == nullptr) { return "no tests were declared"; } // Find the common path prefix of all filenames, so we can strip it off. ArrayPtr<const char> commonPrefix = StringPtr(testCasesHead->file); for (TestCase* testCase = testCasesHead; testCase != nullptr; testCase = testCase->next) { for (size_t i: kj::indices(commonPrefix)) { if (testCase->file[i] != commonPrefix[i]) { commonPrefix = commonPrefix.slice(0, i); break; } } } // Back off the prefix to the last '/'. while (commonPrefix.size() > 0 && commonPrefix.back() != '/' && commonPrefix.back() != '\\') { commonPrefix = commonPrefix.slice(0, commonPrefix.size() - 1); } // Run the testts. uint passCount = 0; uint failCount = 0; for (TestCase* testCase = testCasesHead; testCase != nullptr; testCase = testCase->next) { if (!hasFilter || testCase->matchedFilter) { auto name = kj::str(testCase->file + commonPrefix.size(), ':', testCase->line, ": ", testCase->description); write(BLUE, "[ TEST ]", name); if (!listOnly) { bool currentFailed = true; KJ_IF_MAYBE(exception, runCatchingExceptions([&]() { TestExceptionCallback exceptionCallback(context); testCase->run(); currentFailed = exceptionCallback.failed(); })) { context.error(kj::str(*exception)); } if (currentFailed) { write(RED, "[ FAIL ]", name); ++failCount; } else { write(GREEN, "[ PASS ]", name); ++passCount; } } } } if (passCount > 0) write(GREEN, kj::str(passCount, " test(s) passed"), ""); if (failCount > 0) write(RED, kj::str(failCount, " test(s) failed"), ""); context.exit(); KJ_UNREACHABLE; } private: ProcessContext& context; bool useColor; bool hasFilter = false; bool listOnly = false; enum Color { RED, GREEN, BLUE }; void write(StringPtr text) { FdOutputStream(STDOUT_FILENO).write(text.begin(), text.size()); } void write(Color color, StringPtr prefix, StringPtr message) { StringPtr startColor, endColor; if (useColor) { switch (color) { case RED: startColor = "\033[0;1;31m"; break; case GREEN: startColor = "\033[0;1;32m"; break; case BLUE: startColor = "\033[0;1;34m"; break; } endColor = "\033[0m"; } String text = kj::str(startColor, prefix, endColor, ' ', message, '\n'); write(text); } }; } // namespace kj KJ_MAIN(kj::TestRunner);
31.219373
99
0.603851
[ "vector" ]
33f43331fece5198ab5d2d6297be6c6e53ffe03c
4,446
hxx
C++
Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromIndexShift.hxx
HongdaZ/ITK
f5d004fa3607b8e11edc30f1ba299df35af8aff8
[ "Apache-2.0" ]
1
2021-01-10T14:19:08.000Z
2021-01-10T14:19:08.000Z
Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromIndexShift.hxx
HongdaZ/ITK
f5d004fa3607b8e11edc30f1ba299df35af8aff8
[ "Apache-2.0" ]
1
2017-03-19T12:56:50.000Z
2018-10-24T10:40:21.000Z
Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromIndexShift.hxx
HongdaZ/ITK
f5d004fa3607b8e11edc30f1ba299df35af8aff8
[ "Apache-2.0" ]
1
2020-07-24T22:58:19.000Z
2020-07-24T22:58:19.000Z
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkRegistrationParameterScalesFromIndexShift_hxx #define itkRegistrationParameterScalesFromIndexShift_hxx #include "itkRegistrationParameterScalesFromIndexShift.h" namespace itk { template <typename TMetric> void RegistrationParameterScalesFromIndexShift<TMetric>::ComputeSampleShifts(const ParametersType & deltaParameters, ScalesType & sampleShifts) { if (this->GetTransformForward()) { this->ComputeSampleShiftsInternal<MovingTransformType>(deltaParameters, sampleShifts); } else { this->ComputeSampleShiftsInternal<FixedTransformType>(deltaParameters, sampleShifts); } } template <typename TMetric> template <typename TTransform> void RegistrationParameterScalesFromIndexShift<TMetric>::ComputeSampleShiftsInternal(const ParametersType & deltaParameters, ScalesType & sampleShifts) { using TransformOutputType = itk::ContinuousIndex<FloatType, TTransform::OutputSpaceDimension>; // We save the old parameters and apply the delta parameters to calculate the // voxel shift. After it is done, we will reset to the old parameters. auto * transform = const_cast<TransformBaseTemplate<typename TMetric::MeasureType> *>(this->GetTransform()); const ParametersType oldParameters = transform->GetParameters(); const auto numSamples = static_cast<const SizeValueType>(this->m_SamplePoints.size()); VirtualPointType point; TransformOutputType newMappedVoxel; // Store the old mapped indices to reduce calls to Transform::SetParameters() std::vector<TransformOutputType> oldMappedVoxels(numSamples); sampleShifts.SetSize(numSamples); // Compute the indices mapped by the old transform for (SizeValueType c = 0; c < numSamples; c++) { point = this->m_SamplePoints[c]; this->template TransformPointToContinuousIndex<TransformOutputType>(point, oldMappedVoxels[c]); } // Apply the delta parameters to the transform this->UpdateTransformParameters(deltaParameters); // compute the indices mapped by the new transform for (SizeValueType c = 0; c < numSamples; c++) { point = this->m_SamplePoints[c]; this->template TransformPointToContinuousIndex<TransformOutputType>(point, newMappedVoxel); // find max shift by checking each sample point sampleShifts[c] = newMappedVoxel.EuclideanDistanceTo(oldMappedVoxels[c]); } // restore the parameters in the transform transform->SetParameters(oldParameters); } /** Transform a physical point to its continuous index */ template <typename TMetric> template <typename TContinuousIndexType> void RegistrationParameterScalesFromIndexShift<TMetric>::TransformPointToContinuousIndex(const VirtualPointType & point, TContinuousIndexType & mappedIndex) { if (this->GetTransformForward()) { MovingPointType mappedPoint; mappedPoint = this->m_Metric->GetMovingTransform()->TransformPoint(point); this->m_Metric->GetMovingImage()->TransformPhysicalPointToContinuousIndex(mappedPoint, mappedIndex); } else { FixedPointType mappedPoint; mappedPoint = this->m_Metric->GetFixedTransform()->TransformPoint(point); this->m_Metric->GetFixedImage()->TransformPhysicalPointToContinuousIndex(mappedPoint, mappedIndex); } } /** Print the information about this class */ template <typename TMetric> void RegistrationParameterScalesFromIndexShift<TMetric>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } } // namespace itk #endif
37.361345
119
0.704229
[ "vector", "transform" ]
33f60c54e53a43ed1d6602da66178cbce417985d
17,757
cpp
C++
src/runtime_src/xdp/profile/plugin/ocl/xocl_plugin.cpp
Himanshu-xilinx/XRT
72ed6f33780396550b3b1e8d3c6011faa0bb0827
[ "Apache-2.0" ]
null
null
null
src/runtime_src/xdp/profile/plugin/ocl/xocl_plugin.cpp
Himanshu-xilinx/XRT
72ed6f33780396550b3b1e8d3c6011faa0bb0827
[ "Apache-2.0" ]
null
null
null
src/runtime_src/xdp/profile/plugin/ocl/xocl_plugin.cpp
Himanshu-xilinx/XRT
72ed6f33780396550b3b1e8d3c6011faa0bb0827
[ "Apache-2.0" ]
3
2020-08-12T03:03:13.000Z
2020-08-12T03:39:45.000Z
/** * Copyright (C) 2016-2017 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located 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. */ #define XDP_SOURCE #include "xocl_plugin.h" #include "xdp/profile/writer/base_profile.h" #include "xdp/profile/core/rt_profile.h" #include <cctype> // needed for std::tolower #ifdef _WIN32 #pragma warning (disable : 4244) /* Disable warning for "int" to "char" conversion in <algorithm> header file included in one of the included files */ #endif namespace xdp { // XOCL XDP Plugin constructor XoclPlugin::XoclPlugin(xocl::platform* Platform) { mPlatformHandle = Platform; /* * Gather Static info at init * as it might not be safe at the end */ getXrtIniSettings(); } XoclPlugin::~XoclPlugin() { } // ********** // Trace time // ********** double XoclPlugin::getTraceTime() { // Everything in xocl layer should use this API auto nsec = xocl::time_ns(); return getTimestampMsec(nsec); } // ************************* // Accelerator port metadata // ************************* // Get the name of the memory resource associated with a device, CU, and memory index // NOTE: This is used for comparison purposes to group associated arguments, hence we // use the resource name. The actual reporting (see getArgumentsBank below) may include // the indices as well, as taken from debug_ip_layout. void XoclPlugin::getMemoryNameFromID(const xocl::device* device_id, const std::shared_ptr<xocl::compute_unit> cu, const std::string arg_id, std::string& memoryName) { try { unsigned long index = (unsigned long)std::stoi(arg_id); auto memidx_mask = cu->get_memidx(index); // auto memidx = 0; for (unsigned int memidx=0; memidx<memidx_mask.size(); ++memidx) { if (memidx_mask.test(memidx)) { // Get bank tag string from index memoryName = "DDR"; if (device_id->is_active()) memoryName = device_id->get_xclbin().memidx_to_banktag(memidx); XDP_LOG("getMemoryNameFromID: idx = %d, memory = %s\n", memidx, memoryName.c_str()); break; } } } catch (const std::runtime_error& ) { memoryName = "DDR"; XDP_LOG("getMemoryNameFromID: caught error, using default of %s\n", memoryName.c_str()); } // Catch old bank format and report as DDR if (memoryName.find("bank") != std::string::npos) memoryName = "DDR"; // Only return the resource name (i.e., remove indices) memoryName = memoryName.substr(0, memoryName.find_last_of("[")); } // Find arguments and memory resources for each accel port on given device void XoclPlugin::setArgumentsBank(const std::string& deviceName) { // Iterate over all devices in platform for (auto device_id : mPlatformHandle->get_device_range()) { std::string currDevice = device_id->get_unique_name(); XDP_LOG("setArgumentsBank: current device = %s, # CUs = %d\n", currDevice.c_str(), device_id->get_num_cus()); if (currDevice.find(deviceName) == std::string::npos) continue; // Iterate over all CUs on this device for (auto& cu : xocl::xocl(device_id)->get_cus()) { auto currCU = cu->get_name(); auto currSymbol = cu->get_symbol(); // Compile sets of ports and memories for this CU std::set<std::string> portSet; std::set<std::string> memorySet; for (auto arg : currSymbol->arguments) { if ((arg.address_qualifier == 0) || (arg.atype != xocl::xclbin::symbol::arg::argtype::indexed)) continue; auto portName = arg.port; // Avoid conflict with boost // std::transform(portName.begin(), portName.end(), portName.begin(), ::tolower); std::transform(portName.begin(), portName.end(), portName.begin(), [](char c){return (char) std::tolower(c);}); portSet.insert(portName); std::string memoryName; getMemoryNameFromID(device_id, cu, arg.id, memoryName); memorySet.insert(memoryName); } // Now find all arguments for each port/memory resource pair for (auto portName : portSet) { for (auto memoryName : memorySet) { XDPPluginI::CUPortArgsBankType row; std::get<0>(row) = currCU; std::get<1>(row) = portName; std::get<3>(row) = memoryName; bool foundArg = false; for (auto arg : currSymbol->arguments) { // Catch arguments we don't care about // Address_Qualifier = 1 : AXI MM Port // Address_Qualifier = 4 : AXI Stream Port if (((arg.address_qualifier != 1) && (arg.address_qualifier != 4)) || (arg.atype != xocl::xclbin::symbol::arg::argtype::indexed)) continue; auto currPort = arg.port; // Avoid conflict with boost // std::transform(currPort.begin(), currPort.end(), currPort.begin(), ::tolower); std::transform(currPort.begin(), currPort.end(), currPort.begin(), [](char c){return (char) std::tolower(c);}); std::string currMemory; getMemoryNameFromID(device_id, cu, arg.id, currMemory); if ((currPort == portName) && (currMemory == memoryName)) { std::get<2>(row) += (!foundArg) ? arg.name : ("|" + arg.name); std::get<4>(row) = arg.port_width; foundArg = true; } } // for args if (foundArg) { XDP_LOG("setArgumentsBank: %s/%s, args = %s, memory = %s, width = %d\n", std::get<0>(row).c_str(), std::get<1>(row).c_str(), std::get<2>(row).c_str(), std::get<3>(row).c_str(), std::get<4>(row)); CUPortVector.push_back(row); } } // for memory } // for port portSet.clear(); memorySet.clear(); } // for CU } // for device } // Get the arguments and memory resource for a given device/CU/port void XoclPlugin::getArgumentsBank(const std::string& /*deviceName*/, const std::string& cuName, const std::string& portName, std::string& argNames, std::string& memoryName) { argNames = "All"; memoryName = "DDR"; bool foundMemory = false; std::string portNameCheck = portName; std::string memoryResource = memoryName; // Given a port string (e.g., "cu1/port1-DDR[0]"), separate out the port name // and the memory resource name (e.g., "DDR") size_t index = portName.find_last_of(IP_LAYOUT_SEP); if (index != std::string::npos) { foundMemory = true; portNameCheck = portName.substr(0, index); memoryName = portName.substr(index+1); size_t index2 = memoryName.find("["); memoryResource = memoryName.substr(0, index2); } // Avoid conflict with boost //std::transform(portNameCheck.begin(), portNameCheck.end(), portNameCheck.begin(), ::tolower); std::transform(portNameCheck.begin(), portNameCheck.end(), portNameCheck.begin(), [](char c){return (char) std::tolower(c);}); // Find CU and port, then capture arguments and bank for (auto& row : CUPortVector) { std::string currCU = std::get<0>(row); std::string currPort = std::get<1>(row); if ((currCU == cuName) && (currPort == portNameCheck)) { std::string currMemory = std::get<3>(row); size_t index3 = currMemory.find("["); auto currMemoryResource = currMemory.substr(0, index3); // Make sure it's the right memory resource if (foundMemory && (currMemoryResource != memoryResource)) continue; argNames = std::get<2>(row); memoryName = currMemory; break; } } } // ***************** // Guidance metadata // ***************** // Gather statistics and put into param/value map // NOTE: this needs to be called while the platforms and devices still exist void XoclPlugin::getGuidanceMetadata(RTProfile *profile) { // 1. Device execution times (and unused devices) getDeviceExecutionTimes(profile); // 2. Unused CUs getUnusedComputeUnits(profile); // 3. Kernel counts getKernelCounts(profile); // 4. Devices with PLRAM Size > 0 getPlramSizeDevices(); // 5. Bit widths for memory types for each device getMemBitWidthDevices(); // 6. Memory Bank Info from Mem Topology getMemUsageStats(); } void XoclPlugin::getDeviceExecutionTimes(RTProfile *profile) { // NOTE: all device are assumed to support PLRAMs setPlramDevice(true); setHbmDevice(false); setKdmaDevice(false); setP2PDevice(false); // Total kernel time for entire application = (last end - first start) double totalKernelTimeMsec = profile->getTotalApplicationKernelTimeMsec(); setTotalApplicationKernelTimeMs(totalKernelTimeMsec); // Traverse all devices in platform for (auto device_id : mPlatformHandle->get_device_range()) { std::string deviceName = device_id->get_unique_name(); // Get execution time for this device // NOTE: if unused, then this returns 0.0 double deviceExecTime = profile->getTotalKernelExecutionTime(deviceName); mDeviceExecTimesMap[deviceName] = std::to_string(deviceExecTime); // TODO: checks below are kludgy; are there better ways to check for device support? // Check if device supports HBM if (deviceName.find("u280") != std::string::npos || deviceName.find("u50") != std::string::npos) { setHbmDevice(true); } // Check if device supports KDMA if ((deviceName.find("xilinx_u200_xdma_201830_2") != std::string::npos) || (deviceName.find("xilinx_vcu1525_xdma_201830_2") != std::string::npos)) setKdmaDevice(true); // Check if device supports P2P if ((deviceName.find("xilinx_u200_xdma_201830_2") != std::string::npos) || (deviceName.find("xilinx_u250_xdma_201830_2") != std::string::npos) || (deviceName.find("xilinx_vcu1525_xdma_201830_2") != std::string::npos) || (deviceName.find("samsung") != std::string::npos)) setP2PDevice(true); } } void XoclPlugin::getUnusedComputeUnits(RTProfile *profile) { // Traverse all devices in platform for (auto device_id : mPlatformHandle->get_device_range()) { std::string deviceName = device_id->get_unique_name(); // Traverse all CUs on current device for (auto& cu : xocl::xocl(device_id)->get_cus()) { auto cuName = cu->get_name(); // Get number of calls for current CU int numCalls = profile->getComputeUnitCalls(deviceName, cuName); std::string cuFullName = deviceName + "|" + cuName; mComputeUnitCallsMap[cuFullName] = std::to_string(numCalls); } } } void XoclPlugin::getKernelCounts(RTProfile* /*profile*/) { // Traverse all devices in this platform for (auto device_id : mPlatformHandle->get_device_range()) { std::string deviceName = device_id->get_unique_name(); // Traverse all CUs on current device for (auto& cu : xocl::xocl(device_id)->get_cus()) { auto kernelName = cu->get_kernel_name(); if (mKernelCountsMap.find(kernelName) == mKernelCountsMap.end()) mKernelCountsMap[kernelName] = 1; else mKernelCountsMap[kernelName] += 1; } } } void XoclPlugin::getPlramSizeDevices() { for (auto device : mPlatformHandle->get_device_range()) { if (!device->is_active()) continue; auto name = device->get_unique_name(); auto sz = xdp::xoclp::platform::device::getPlramSizeBytes(device); if (sz) mDevicePlramSizeMap[name] = sz; } } void XoclPlugin::getMemUsageStats() { for (auto device : mPlatformHandle->get_device_range()) { if (!device->is_active()) continue; xdp::xoclp::platform::device::getMemUsageStats(device, mDeviceMemUsageStatsMap); } } void XoclPlugin::getMemBitWidthDevices() { for (auto device : mPlatformHandle->get_device_range()) { if (!device->is_active()) continue; // TODO: Find a better way to distinguish embedded platforms bool soc = false; std::string deviceName = device->get_unique_name(); if (deviceName.rfind("zc", 0) == 0) { soc = true; } // TODO: figure out how to get this from platform auto name = device->get_unique_name(); if (soc) { mDeviceMemTypeBitWidthMap[name + "|DDR"] = 64; } else { mDeviceMemTypeBitWidthMap[name + "|HBM"] = 256; mDeviceMemTypeBitWidthMap[name + "|DDR"] = 512; mDeviceMemTypeBitWidthMap[name + "|PLRAM"] = 512; } } } void XoclPlugin::getXrtIniSettings() { mXrtIniMap["profile"] = std::to_string(xrt::config::get_profile()); mXrtIniMap["timeline_trace"] = std::to_string(xrt::config::get_timeline_trace()); mXrtIniMap["data_transfer_trace"] = xrt::config::get_data_transfer_trace(); mXrtIniMap["power_profile"] = std::to_string(xrt::config::get_power_profile()); mXrtIniMap["stall_trace"] = xrt::config::get_stall_trace(); mXrtIniMap["trace_buffer_size"] = xrt::config::get_trace_buffer_size(); mXrtIniMap["aie_trace_buffer_size"] = xrt::config::get_aie_trace_buffer_size(); mXrtIniMap["verbosity"] = std::to_string(xrt::config::get_verbosity()); mXrtIniMap["continuous_trace"] = std::to_string(xrt::config::get_continuous_trace()); mXrtIniMap["continuous_trace_interval_ms"] = std::to_string(xrt::config::get_continuous_trace_interval_ms()); mXrtIniMap["lop_trace"] = std::to_string(xrt::config::get_lop_trace()); mXrtIniMap["launch_waveform"] = xrt::config::get_launch_waveform(); } // **************************************** // Platform Metadata required by profiler // **************************************** void XoclPlugin::getProfileKernelName(const std::string& deviceName, const std::string& cuName, std::string& kernelName) { xoclp::platform::get_profile_kernel_name(mPlatformHandle, deviceName, cuName, kernelName); } void XoclPlugin::getTraceStringFromComputeUnit(const std::string& deviceName, const std::string& cuName, std::string& traceString) { std::string kernel; getProfileKernelName(deviceName, cuName, kernel); for (const auto &pair : mComputeUnitKernelTraceMap) { if (pair.first == kernel) { auto index = pair.second.find_last_of("|"); traceString = pair.second.substr(0,index + 1) + cuName + pair.second.substr(index); return; } } traceString = std::string(); } void XoclPlugin::setTraceStringForComputeUnit(const std::string& cuName, std::string& traceString) { if (!cuName.empty() && mComputeUnitKernelTraceMap.find(cuName) == mComputeUnitKernelTraceMap.end()) mComputeUnitKernelTraceMap[cuName] = traceString; } size_t XoclPlugin::getDeviceTimestamp(const std::string& deviceName) { return xoclp::platform::get_device_timestamp(mPlatformHandle,deviceName); } double XoclPlugin::getReadMaxBandwidthMBps() { return xoclp::platform::get_device_max_read(mPlatformHandle); } double XoclPlugin::getWriteMaxBandwidthMBps() { return xoclp::platform::get_device_max_write(mPlatformHandle); } unsigned int XoclPlugin::getProfileNumberSlots(xclPerfMonType type, const std::string& deviceName) { unsigned int numSlots = xoclp::platform::get_profile_num_slots(mPlatformHandle, deviceName, type); return numSlots; } void XoclPlugin::getProfileSlotName(xclPerfMonType type, const std::string& deviceName, unsigned int slotnum, std::string& slotName) { xoclp::platform::get_profile_slot_name(mPlatformHandle, deviceName, type, slotnum, slotName); } void XoclPlugin::getTraceSlotName(xclPerfMonType type, const std::string& deviceName, unsigned int slotnum, std::string& slotName) { xoclp::platform::get_trace_slot_name(mPlatformHandle, deviceName, type, slotnum, slotName); } unsigned int XoclPlugin::getProfileSlotProperties(xclPerfMonType type, const std::string& deviceName, unsigned int slotnum) { return xoclp::platform::get_profile_slot_properties(mPlatformHandle, deviceName, type, slotnum); } unsigned int XoclPlugin::getTraceSlotProperties(xclPerfMonType type, const std::string& deviceName, unsigned int slotnum) { return xoclp::platform::get_trace_slot_properties(mPlatformHandle, deviceName, type, slotnum); } bool XoclPlugin::isAPCtrlChain(const std::string& deviceName, const std::string& cu) { return xoclp::platform::is_ap_ctrl_chain(mPlatformHandle, deviceName,cu); } void XoclPlugin::sendMessage(const std::string &msg) { xrt::message::send(xrt::message::severity_level::XRT_WARNING, msg); } } // xdp
36.612371
130
0.632877
[ "transform" ]
33fb0c942fcc7b920c5506ad2f6d8e1dbe725ee7
11,533
cpp
C++
src/surface/detect_symmetry.cpp
softwarecapital/geometry-central
b4743b4662018d8fa483b31ff4a3af5699db3e93
[ "MIT" ]
539
2018-02-19T16:38:26.000Z
2022-03-31T06:56:22.000Z
src/surface/detect_symmetry.cpp
softwarecapital/geometry-central
b4743b4662018d8fa483b31ff4a3af5699db3e93
[ "MIT" ]
88
2018-11-30T13:19:35.000Z
2022-03-23T18:40:33.000Z
src/surface/detect_symmetry.cpp
softwarecapital/geometry-central
b4743b4662018d8fa483b31ff4a3af5699db3e93
[ "MIT" ]
74
2018-05-12T17:57:04.000Z
2022-03-21T15:01:26.000Z
#include "geometrycentral/surface/detect_symmetry.h" #include "nanoflann/KDTreeVectorOfVectorsAdaptor.h" #include "nanoflann/nanoflann.hpp" #include <array> #include <vector> // Interal implementations that hide the NN lookup while allowing it to be // shared using std::cout; using std::endl; namespace geometrycentral { namespace surface { namespace { // Stupid nanoflann wrapper typedef KDTreeVectorOfVectorsAdaptor<std::vector<std::vector<double>>, double> KdTree; KdTree* buildKDTree(Geometry<Euclidean>* geom) { HalfedgeMesh* mesh = geom->getMesh(); // Pack data in a vector of vectors std::vector<std::vector<double>>* pts = new std::vector<std::vector<double>>(mesh->nVertices()); for (size_t i = 0; i < mesh->nVertices(); i++) { Vector3 p = geom->position(mesh->vertex(i)); (*pts)[i] = {p.x, p.y, p.z}; } KdTree* tree = new KdTree(3, *pts); tree->index->buildIndex(); return tree; } bool findPoint(KdTree* tree, Vector3 target, double toleranceRadius, size_t& result) { std::vector<size_t> ret_indexes(1); std::vector<double> out_dists_sqr(1); nanoflann::KNNResultSet<double> resultSet(1); resultSet.init(&ret_indexes[0], &out_dists_sqr[0]); std::vector<double> query = {target.x, target.y, target.z}; bool success = tree->index->findNeighbors(resultSet, &query[0], nanoflann::SearchParams()); // Nothing found if (!success) return false; double dist = std::sqrt(out_dists_sqr[0]); if (dist > toleranceRadius) return false; // too far // Point found result = ret_indexes[0]; return true; } SymmetryResult detectSymmetryMirror(Geometry<Euclidean>* geom, Vector3 planeNormal, Vector3 planePoint, KdTree* tree) { HalfedgeMesh* mesh = geom->getMesh(); planeNormal = unit(planeNormal); double toleranceRadius = geom->lengthScale() * 1e-5; SymmetryResult result; result.symmetryFound = false; result.symmetrySet = VertexData<std::vector<Vertex>>(*mesh, std::vector<Vertex>()); for (Vertex v : mesh->vertices()) { // Compute the symmetric point Vector3 pos = geom->position(v); Vector3 vecToPlane = dot(planeNormal, planePoint - pos) * planeNormal; Vector3 mirrorPos = pos + 2 * vecToPlane; // If this point is on the positive side of the plane, it's canonical bool isCanonical = dot(planeNormal, pos - planePoint) > -toleranceRadius; // small tolerance for points on plane if (isCanonical) { result.canonicalVertices.push_back(v); } // If this point is its own pair, there's no mirror to look for (assumes no // duplicate verts) if (norm(pos - mirrorPos) < toleranceRadius) continue; // Search for the point size_t mirrorInd; bool success = findPoint(tree, mirrorPos, toleranceRadius, mirrorInd); if (!success) { return result; } // If found, add to lists if (isCanonical) { result.symmetrySet[v].push_back(mesh->vertex(mirrorInd)); } } result.symmetryFound = true; return result; } SymmetryResult detectSymmetryRotation(Geometry<Euclidean>* geom, Vector3 rotAxis, Vector3 rotPoint, int nSym, KdTree* tree) { HalfedgeMesh* mesh = geom->getMesh(); rotAxis = unit(rotAxis); double toleranceRadius = geom->lengthScale() * 1e-5; double deltaTheta = 2 * PI / nSym; // Any axis orthogonal to the rotation axis Vector3 castAxis = Vector3{0.12345623, -.883034723, 0.54457119}; // provably random Vector3 orthAxis = unit(cross(rotAxis, castAxis)); SymmetryResult result; result.symmetryFound = false; result.symmetrySet = VertexData<std::vector<Vertex>>(*mesh, std::vector<Vertex>()); for (Vertex v : mesh->vertices()) { // Compute the symmetric point Vector3 pos = geom->position(v); // Test if canonical Vector3 vPlane = (pos - rotPoint) - dot(rotAxis, pos - rotPoint) * rotAxis; double canonicalAngle = angleInPlane(orthAxis, vPlane, rotAxis); bool isCanonical = norm(vPlane) < toleranceRadius || (canonicalAngle >= 0 && canonicalAngle < deltaTheta); if (isCanonical) { result.canonicalVertices.push_back(v); } for (int iRot = 1; iRot < nSym; iRot++) { double theta = iRot * deltaTheta; Vector3 rotPos = (pos - rotPoint).rotate_around(rotAxis, theta) + rotPoint; // If this point is its own pair, there's no mirror to look for (assumes // no duplicate verts) if (norm(pos - rotPos) < toleranceRadius) continue; // Search for the point size_t rotInd; bool success = findPoint(tree, rotPos, toleranceRadius, rotInd); if (!success) { return result; } // If found, add to lists if (isCanonical) { result.symmetrySet[v].push_back(mesh->vertex(rotInd)); } } } result.symmetryFound = true; return result; } SymmetryResult detectSymmetryDoubleMirror(Geometry<Euclidean>* geom, KdTree* tree) { HalfedgeMesh* mesh = geom->getMesh(); double toleranceRadius = geom->lengthScale() * 1e-5; SymmetryResult result; result.symmetryFound = false; result.symmetrySet = VertexData<std::vector<Vertex>>(*mesh, std::vector<Vertex>()); for (Vertex v : mesh->vertices()) { // Compute the symmetric point Vector3 pos = geom->position(v); // Test if canonical bool isCanonical = pos.y >= 0 && pos.z >= 0; if (isCanonical) { result.canonicalVertices.push_back(v); } for (int iS = 1; iS < 4; iS++) { // Compute positions flipped across axes Vector3 mirrorPos = pos; if (iS % 2 == 1) { mirrorPos.y *= -1; } if (iS >= 2) { mirrorPos.z *= -1; } // If this point is its own pair, there's no mirror to look for (assumes // no duplicate verts) if (norm(pos - mirrorPos) < toleranceRadius) continue; // Search for the point size_t symInd; bool success = findPoint(tree, mirrorPos, toleranceRadius, symInd); if (!success) { return result; } // If found, add to lists if (isCanonical) { result.symmetrySet[v].push_back(mesh->vertex(symInd)); } } } result.symmetryFound = true; return result; } } // namespace SymmetryResult detectSymmetryMirror(Geometry<Euclidean>* geom, Vector3 planeNormal, Vector3 planePoint) { KdTree* tree = buildKDTree(geom); SymmetryResult r = detectSymmetryMirror(geom, planeNormal, planePoint, tree); delete tree; return r; } SymmetryResult detectSymmetryRotation(Geometry<Euclidean>* geom, Vector3 rotAxis, Vector3 rotPoint, int nSym) { KdTree* tree = buildKDTree(geom); SymmetryResult r = detectSymmetryRotation(geom, rotAxis, rotPoint, nSym, tree); delete tree; return r; } SymmetryResult detectSymmetryAuto(Geometry<Euclidean>* geom) { std::cout << "Attempting to automatically detect symmetry..." << std::endl; KdTree* tree = buildKDTree(geom); Vector3 center = geom->center(); // == Mirror symmetry across coordinate axes, about center { SymmetryResult res = detectSymmetryMirror(geom, Vector3{1.0, 0.0, 0.0}, center, tree); if (res.symmetryFound) { cout << " ... symmetry found across x-axis!" << endl; delete tree; return res; } } { SymmetryResult res = detectSymmetryMirror(geom, Vector3{0.0, 1.0, 0.0}, center, tree); if (res.symmetryFound) { cout << " ... symmetry found across y-axis!" << endl; delete tree; return res; } } { SymmetryResult res = detectSymmetryMirror(geom, Vector3{0.0, 0.0, 1.0}, center, tree); if (res.symmetryFound) { cout << " ... symmetry found across z-axis!" << endl; delete tree; return res; } } // == Rotational symmetry about coordinate axes at center // (higher order symmetries are cooler) for (int nSym = 8; nSym >= 2; nSym--) { { SymmetryResult res = detectSymmetryRotation(geom, Vector3{1.0, 0.0, 0.0}, center, nSym, tree); if (res.symmetryFound) { cout << " ... rotational symmetry found about x-axis with index " << nSym << "!" << endl; delete tree; return res; } } { SymmetryResult res = detectSymmetryRotation(geom, Vector3{0.0, 1.0, 0.0}, center, nSym, tree); if (res.symmetryFound) { cout << " ... rotational symmetry found about y-axis with index " << nSym << "!" << endl; delete tree; return res; } } { SymmetryResult res = detectSymmetryRotation(geom, Vector3{0.0, 0.0, 1.0}, center, nSym, tree); if (res.symmetryFound) { cout << " ... rotational symmetry found about z-axis with index " << nSym << "!" << endl; delete tree; return res; } } } cout << " ...no symmetry found." << endl; delete tree; SymmetryResult r; r.symmetryFound = false; return r; } SymmetryResult detectSymmetryAutoMirror(Geometry<Euclidean>* geom) { cout << "Attempting to automatically detect mirror symmetry..." << endl; KdTree* tree = buildKDTree(geom); Vector3 center = geom->center(); // == Mirror symmetry across coordinate axes, about center { SymmetryResult res = detectSymmetryMirror(geom, Vector3{1.0, 0.0, 0.0}, center, tree); if (res.symmetryFound) { cout << " ... symmetry found across x-axis!" << endl; delete tree; return res; } } { SymmetryResult res = detectSymmetryMirror(geom, Vector3{0.0, 1.0, 0.0}, center, tree); if (res.symmetryFound) { cout << " ... symmetry found across y-axis!" << endl; delete tree; return res; } } { SymmetryResult res = detectSymmetryMirror(geom, Vector3{0.0, 0.0, 1.0}, center, tree); if (res.symmetryFound) { cout << " ... symmetry found across z-axis!" << endl; delete tree; return res; } } cout << " ...no symmetry found." << endl; delete tree; SymmetryResult r; r.symmetryFound = false; return r; } SymmetryResult detectSymmetryAutoRotation(Geometry<Euclidean>* geom) { cout << "Attempting to automatically detect rotational symmetry..." << endl; KdTree* tree = buildKDTree(geom); Vector3 center = geom->center(); // == Rotational symmetry about coordinate axes at center // (higher order symmetries are cooler) for (int nSym = 8; nSym >= 2; nSym--) { { SymmetryResult res = detectSymmetryRotation(geom, Vector3{1.0, 0.0, 0.0}, center, nSym, tree); if (res.symmetryFound) { cout << " ... rotational symmetry found about x-axis with index " << nSym << "!" << endl; delete tree; return res; } } { SymmetryResult res = detectSymmetryRotation(geom, Vector3{0.0, 1.0, 0.0}, center, nSym, tree); if (res.symmetryFound) { cout << " ... rotational symmetry found about y-axis with index " << nSym << "!" << endl; delete tree; return res; } } { SymmetryResult res = detectSymmetryRotation(geom, Vector3{0.0, 0.0, 1.0}, center, nSym, tree); if (res.symmetryFound) { cout << " ... rotational symmetry found about z-axis with index " << nSym << "!" << endl; delete tree; return res; } } } cout << " ...no symmetry found." << endl; delete tree; SymmetryResult r; r.symmetryFound = false; return r; } SymmetryResult detectSymmetryDoubleMirror(Geometry<Euclidean>* geom) { KdTree* tree = buildKDTree(geom); SymmetryResult r = detectSymmetryDoubleMirror(geom, tree); delete tree; return r; } } // namespace surface } // namespace geometrycentral
29.955844
119
0.642938
[ "mesh", "geometry", "vector" ]