text
stringlengths 5
1.04M
|
|---|
//=========================================================================
// Copyright (C) 2012 The Elastos 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 "CX509CertificateHelper.h"
namespace Elastosx {
namespace Security {
namespace Cert {
CAR_SINGLETON_IMPL(CX509CertificateHelper)
CAR_INTERFACE_IMPL(CX509CertificateHelper, Singleton, IX509CertificateHelper)
ECode CX509CertificateHelper::GetInstance(
/* [in] */ IInputStream *inStream,
/* [out] */ IX509Certificate **cert)
{
return X509Certificate::GetInstance(inStream, cert);
}
ECode CX509CertificateHelper::GetInstance(
/* [in] */ ArrayOf<Byte>* certData,
/* [out] */ IX509Certificate **cert)
{
return X509Certificate::GetInstance(certData, cert);
}
} // namespace Cert
} // namespace Security
} // namespace Elastosx
|
#ifndef SAGA_PACKAGES_CPR_CPRJOB_HPP
#define SAGA_PACKAGES_CPR_CPRJOB_HPP
#if defined(__WAVE__) && defined(SAGA_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 1, output: "preprocessed/cpr_job.hpp")
#endif
// Copyright (c) 2005-2009 Hartmut Kaiser
// Copyright (c) 2007 Ole Weidner (oweidner@cct.lsu.edu)
// Copyright (c) 2008 Andre Merzky (andre@merzky.net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if defined(__WAVE__) && defined(SAGA_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif
#include <string>
#include <vector>
#include <iosfwd>
// include dependent spec sections
#include <saga/saga/util.hpp>
#include <saga/saga/base.hpp>
#include <saga/saga/types.hpp>
#include <saga/saga/session.hpp>
#include <saga/saga/call.hpp>
#include <saga/saga/job.hpp>
#include <saga/saga/packages/cpr/config.hpp>
#include <saga/saga/detail/attribute.hpp>
#include <saga/saga/detail/permissions.hpp>
// suppress warnings about dependent classes not being exported from the dll
#if defined(BOOST_MSVC)
#pragma warning(push)
#pragma warning(disable: 4251 4231 4275 4660)
#endif
#ifdef SAGA_DEBUG
#include <saga/saga/packages/cpr/preprocessed/cpr_job.hpp>
#else
#if defined(__WAVE__) && defined(SAGA_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 1, output: "preprocessed/cpr_job.hpp")
#endif
///////////////////////////////////////////////////////////////////////////////
namespace saga
{
/*! \brief The <I>Checkpoint and Recovery</I> (CPR) API package
*
*
*/
namespace cpr {
/*! \brief Available %attributes defined for the CPR API package
*
*/
namespace attributes
{
// inherited from saga::job::job?
}
/*! \brief Available %metrics defined for the CPR API package.
*
* Most cp::job metrics are inherited from the job::job class, and only
* four are added to simplify application level checkpoiint management:
* checkpoint, checkpointed, recover, and recovered. <br>
* <br><b>Usage example:</b><br><br>
* <code>//TODO</code>
*/
namespace metrics
{
/*! \brief Fires if the job gets a checkpoint request.
*/
char const* const checkpoint = "cpr_job.Checkpoint";
/*! \brief Fires if the job finishes a checkpoint request.
*/
char const* const checkpointed = "cpr_job.Checkpointed";
/*! \brief Fires if the job gets a recover request.
*/
char const* const recover = "cpr_job.Recover";
/*! \brief Fires if the job finishes a recover request.
*/
char const* const recovered = "cpr_job.Recovered";
}
// /*! \brief The state is equivalent to the inherited
// * saga::job::state, but adds the Checkpointing and Recovering state.
// *
// * Checkpointing identifies a job instance which is in
// * the process of checkpointing.
// *
// * Recovering identifies a job instance which is in
// * the process of recovering.
// */
enum state
{
Unknown = saga::job::Unknown, // -1
New = saga::job::New, // 0
Running = saga::job::Running, // 1
Failed = saga::job::Failed, // 2
Done = saga::job::Done, // 3
Canceled = saga::job::Canceled, // 4
Suspended = saga::job::Suspended, // 5
Checkpointing = 6,
Recovering = 7
};
/*! \brief The job is a saga::job with additional checkpoint and
* recovery related methods.
*
*/
class SAGA_CPR_PACKAGE_EXPORT job
: public saga::job::job
{
private:
friend struct saga::detail::attribute<job>; // needs to access get_impl()
friend struct saga::detail::permissions<job>;
/// @cond
// job cpr management
SAGA_CALL_PRIV_1 (checkpoint, saga::url)
SAGA_CALL_PRIV_1 (recover, saga::url)
SAGA_CALL_PRIV_1 (cpr_stage_in, saga::url)
SAGA_CALL_PRIV_1 (cpr_stage_out, saga::url)
SAGA_CALL_PRIV_0 (cpr_last)
SAGA_CALL_PRIV_0 (cpr_list)
/// @endcond
protected:
/// @cond
/** These methods are not within API scope */
typedef saga::detail::attribute<job> attribute_base;
TR1::shared_ptr <saga::impl::cpr_job> get_impl_sp(void) const;
saga::impl::cpr_job* get_impl (void) const;
explicit job (saga::impl::cpr_job *);
/// @endcond
public:
/*! \brief Creates the object.
*
*
*/
job();
/*! \brief Creates the object.
*
*
*/
explicit job (saga::object const& o);
/*! \brief Destroys the object.
*
*
*/
~job();
/*! \brief Brief %description starts here
*
*
*/
job &operator= (saga::object const& o);
/*! \brief checkpoint a job
* \return void
*
*
*/
void checkpoint (saga::url u = saga::url ())
{
checkpointpriv (u, saga::task_base::Sync());
}
/// @cond
SAGA_CALL_PUB_1_DEF_1 (checkpoint, saga::url, saga::url ())
/// @endcond
/*! \brief recover a job
* \return void
*
*
*/
void recover (saga::url u = saga::url ())
{
recoverpriv (u, saga::task_base::Sync());
}
/// @cond
SAGA_CALL_PUB_1_DEF_1 (recover, saga::url, saga::url ())
/// @endcond
/*! \brief stage-in a checkpoint file
* \return void
*
*
*/
void cpr_stage_in (saga::url u = saga::url ())
{
cpr_stage_inpriv (u, saga::task_base::Sync());
}
/// @cond
SAGA_CALL_PUB_1_DEF_1 (cpr_stage_in, saga::url, saga::url ())
/// @endcond
/*! \brief stage-out a checkpoint file
* \return void
*
*
*/
void cpr_stage_out (saga::url u = saga::url ())
{
cpr_stage_outpriv (u, saga::task_base::Sync());
}
/// @cond
SAGA_CALL_PUB_1_DEF_1 (cpr_stage_out, saga::url, saga::url ())
/// @endcond
/*! \brief get list of known checkpoints
* \return list of known checkpoint URLs
*
*
*/
std::vector <saga::url> cpr_list (void)
{
saga::task t = cpr_listpriv(saga::task_base::Sync());
return t.get_result <std::vector <saga::url> > ();
}
/// @cond
SAGA_CALL_PUB_0_DEF_0 (cpr_list)
/// @endcond
/*! \brief get last known checkpoint
* \return last known checkpoint URL
*
*
*/
saga::url cpr_last (void)
{
saga::task t = cpr_lastpriv(saga::task_base::Sync());
return t.get_result <saga::url> ();
}
/// @cond
SAGA_CALL_PUB_0_DEF_0 (cpr_last)
/// @endcond
};
} // namespace job
} // namespace saga
#if defined(__WAVE__) && defined(SAGA_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif
#endif // !defined(SAGA_DEBUG)
// re-enable warnings about dependent classes not being exported from the dll
#if defined(BOOST_MSVC)
#pragma warning(pop)
#endif
#endif // !defined(SAGA_PACKAGES_CPR_CPRJOB_HPP)
|
/*
*
* Copyright (c) 2021 Project CHIP 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 IS GENERATED BY ZAP
#include "callback.h"
#include <app/common/gen/cluster-id.h>
#include <lib/support/Span.h>
using namespace chip;
// Cluster Init Functions
void emberAfClusterInitCallback(EndpointId endpoint, ClusterId clusterId)
{
switch (clusterId)
{
case ZCL_ACCOUNT_LOGIN_CLUSTER_ID:
emberAfAccountLoginClusterInitCallback(endpoint);
break;
case ZCL_APPLICATION_BASIC_CLUSTER_ID:
emberAfApplicationBasicClusterInitCallback(endpoint);
break;
case ZCL_APPLICATION_LAUNCHER_CLUSTER_ID:
emberAfApplicationLauncherClusterInitCallback(endpoint);
break;
case ZCL_AUDIO_OUTPUT_CLUSTER_ID:
emberAfAudioOutputClusterInitCallback(endpoint);
break;
case ZCL_CONTENT_LAUNCH_CLUSTER_ID:
emberAfContentLaunchClusterInitCallback(endpoint);
break;
case ZCL_DESCRIPTOR_CLUSTER_ID:
emberAfDescriptorClusterInitCallback(endpoint);
break;
case ZCL_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_ID:
emberAfEthernetNetworkDiagnosticsClusterInitCallback(endpoint);
break;
case ZCL_GENERAL_DIAGNOSTICS_CLUSTER_ID:
emberAfGeneralDiagnosticsClusterInitCallback(endpoint);
break;
case ZCL_KEYPAD_INPUT_CLUSTER_ID:
emberAfKeypadInputClusterInitCallback(endpoint);
break;
case ZCL_LEVEL_CONTROL_CLUSTER_ID:
emberAfLevelControlClusterInitCallback(endpoint);
break;
case ZCL_LOW_POWER_CLUSTER_ID:
emberAfLowPowerClusterInitCallback(endpoint);
break;
case ZCL_MEDIA_INPUT_CLUSTER_ID:
emberAfMediaInputClusterInitCallback(endpoint);
break;
case ZCL_MEDIA_PLAYBACK_CLUSTER_ID:
emberAfMediaPlaybackClusterInitCallback(endpoint);
break;
case ZCL_ON_OFF_CLUSTER_ID:
emberAfOnOffClusterInitCallback(endpoint);
break;
case ZCL_OPERATIONAL_CREDENTIALS_CLUSTER_ID:
emberAfOperationalCredentialsClusterInitCallback(endpoint);
break;
case ZCL_SOFTWARE_DIAGNOSTICS_CLUSTER_ID:
emberAfSoftwareDiagnosticsClusterInitCallback(endpoint);
break;
case ZCL_TV_CHANNEL_CLUSTER_ID:
emberAfTvChannelClusterInitCallback(endpoint);
break;
case ZCL_TARGET_NAVIGATOR_CLUSTER_ID:
emberAfTargetNavigatorClusterInitCallback(endpoint);
break;
case ZCL_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_ID:
emberAfThreadNetworkDiagnosticsClusterInitCallback(endpoint);
break;
case ZCL_WAKE_ON_LAN_CLUSTER_ID:
emberAfWakeOnLanClusterInitCallback(endpoint);
break;
case ZCL_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_ID:
emberAfWiFiNetworkDiagnosticsClusterInitCallback(endpoint);
break;
default:
// Unrecognized cluster ID
break;
}
}
void __attribute__((weak)) emberAfAccountLoginClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfApplicationBasicClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfApplicationLauncherClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfAudioOutputClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfContentLaunchClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfDescriptorClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfEthernetNetworkDiagnosticsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfGeneralDiagnosticsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfKeypadInputClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfLevelControlClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfLowPowerClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfMediaInputClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfMediaPlaybackClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfOnOffClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfOperationalCredentialsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfSoftwareDiagnosticsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfTvChannelClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfTargetNavigatorClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfThreadNetworkDiagnosticsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfWakeOnLanClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
//
// Non-Cluster Related Callbacks
//
/** @brief Add To Current App Tasks
*
* This function is only useful to sleepy end devices. This function will note
* the passed item as part of a set of tasks the application has outstanding
* (e.g. message sent requiring APS acknwoledgement). This will affect how the
* application behaves with regard to sleeping and polling. Until the
* outstanding task is completed, the device may poll more frequently and sleep
* less often.
*
* @param tasks Ver.: always
*/
void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {}
/** @brief Remove From Current App Tasks
*
* This function is only useful to sleepy end devices. This function will
* remove the passed item from the set of tasks the application has outstanding
* (e.g. message sent requiring APS acknwoledgement). This will affect how the
* application behaves with regard to sleeping and polling. Removing the item
* from the list of outstanding tasks may allow the device to sleep longer and
* poll less frequently. If there are other outstanding tasks the system may
* still have to stay away and poll more often.
*
* @param tasks Ver.: always
*/
void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {}
/** @brief Allow Network Write Attribute
*
* This function is called by the application framework before it writes an
* attribute in response to a write attribute request from an external device.
* The value passed into this callback is the value to which the attribute is to
* be set by the framework.
Example: In mirroring simple metering data
* on an Energy Services Interface (ESI) (formerly called Energy Service Portal
* (ESP) in SE 1.0).), a mirrored simple meter needs to write read-only
* attributes on its mirror. The-meter-mirror sample application, located in
* app/framework/sample-apps, uses this callback to allow the mirrored device to
* write simple metering attributes on the mirror regardless of the fact that
* most simple metering attributes are defined as read-only by the ZigBee
* specification.
Note: The ZCL specification does not (as of this
* writing) specify any permission-level security for writing writeable
* attributes. As far as the ZCL specification is concerned, if an attribute is
* writeable, any device that has a link key for the device should be able to
* write that attribute. Furthermore if an attribute is read only, it should not
* be written over the air. Thus, if you implement permissions for writing
* attributes as a feature, you MAY be operating outside the specification. This
* is unlikely to be a problem for writing read-only attributes, but it may be a
* problem for attributes that are writeable according to the specification but
* restricted by the application implementing this callback.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param attributeId Ver.: always
* @param mask Ver.: always
* @param manufacturerCode Ver.: always
* @param value Ver.: always
* @param type Ver.: always
*/
EmberAfAttributeWritePermission __attribute__((weak))
emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t mask,
uint16_t manufacturerCode, uint8_t * value, uint8_t type)
{
return EMBER_ZCL_ATTRIBUTE_WRITE_PERMISSION_ALLOW_WRITE_NORMAL; // Default
}
/** @brief Attribute Read Access
*
* This function is called whenever the Application Framework needs to check
* access permission for an attribute read.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param manufacturerCode Ver.: always
* @param attributeId Ver.: always
*/
bool __attribute__((weak))
emberAfAttributeReadAccessCallback(EndpointId endpoint, ClusterId clusterId, uint16_t manufacturerCode, AttributeId attributeId)
{
return true;
}
/** @brief Attribute Write Access
*
* This function is called whenever the Application Framework needs to check
* access permission for an attribute write.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param manufacturerCode Ver.: always
* @param attributeId Ver.: always
*/
bool __attribute__((weak))
emberAfAttributeWriteAccessCallback(EndpointId endpoint, ClusterId clusterId, uint16_t manufacturerCode, AttributeId attributeId)
{
return true;
}
/** @brief Default Response
*
* This function is called by the application framework when a Default Response
* command is received from an external device. The application should return
* true if the message was processed or false if it was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param commandId The command identifier to which this is a response. Ver.:
* always
* @param status Specifies either SUCCESS or the nature of the error that was
* detected in the received command. Ver.: always
*/
bool __attribute__((weak)) emberAfDefaultResponseCallback(ClusterId clusterId, CommandId commandId, EmberAfStatus status)
{
return false;
}
/** @brief Configure Reporting Response
*
* This function is called by the application framework when a Configure
* Reporting Response command is received from an external device. The
* application should return true if the message was processed or false if it
* was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param buffer Buffer containing the list of attribute status records. Ver.:
* always
* @param bufLen The length in bytes of the list. Ver.: always
*/
bool __attribute__((weak)) emberAfConfigureReportingResponseCallback(ClusterId clusterId, uint8_t * buffer, uint16_t bufLen)
{
return false;
}
/** @brief Read Reporting Configuration Response
*
* This function is called by the application framework when a Read Reporting
* Configuration Response command is received from an external device. The
* application should return true if the message was processed or false if it
* was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param buffer Buffer containing the list of attribute reporting configuration
* records. Ver.: always
* @param bufLen The length in bytes of the list. Ver.: always
*/
bool __attribute__((weak)) emberAfReadReportingConfigurationResponseCallback(ClusterId clusterId, uint8_t * buffer, uint16_t bufLen)
{
return false;
}
/** @brief Discover Attributes Response
*
* This function is called by the application framework when a Discover
* Attributes Response or Discover Attributes Extended Response command is
* received from an external device. The Discover Attributes Response command
* contains a bool indicating if discovery is complete and a list of zero or
* more attribute identifier/type records. The final argument indicates whether
* the response is in the extended format or not. The application should return
* true if the message was processed or false if it was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param discoveryComplete Indicates whether there are more attributes to be
* discovered. true if there are no more attributes to be discovered. Ver.:
* always
* @param buffer Buffer containing the list of attribute identifier/type
* records. Ver.: always
* @param bufLen The length in bytes of the list. Ver.: always
* @param extended Indicates whether the response is in the extended format or
* not. Ver.: always
*/
bool __attribute__((weak)) emberAfDiscoverAttributesResponseCallback(ClusterId clusterId, bool discoveryComplete, uint8_t * buffer,
uint16_t bufLen, bool extended)
{
return false;
}
/** @brief Discover Commands Generated Response
*
* This function is called by the framework when Discover Commands Generated
* Response is received.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param manufacturerCode Manufacturer code Ver.: always
* @param discoveryComplete Indicates whether there are more commands to be
* discovered. Ver.: always
* @param commandIds Buffer containing the list of command identifiers. Ver.:
* always
* @param commandIdCount The length of bytes of the list, whish is the same as
* the number of identifiers. Ver.: always
*/
bool __attribute__((weak))
emberAfDiscoverCommandsGeneratedResponseCallback(ClusterId clusterId, uint16_t manufacturerCode, bool discoveryComplete,
CommandId * commandIds, uint16_t commandIdCount)
{
return false;
}
/** @brief Discover Commands Received Response
*
* This function is called by the framework when Discover Commands Received
* Response is received.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param manufacturerCode Manufacturer code Ver.: always
* @param discoveryComplete Indicates whether there are more commands to be
* discovered. Ver.: always
* @param commandIds Buffer containing the list of command identifiers. Ver.:
* always
* @param commandIdCount The length of bytes of the list, whish is the same as
* the number of identifiers. Ver.: always
*/
bool __attribute__((weak))
emberAfDiscoverCommandsReceivedResponseCallback(ClusterId clusterId, uint16_t manufacturerCode, bool discoveryComplete,
CommandId * commandIds, uint16_t commandIdCount)
{
return false;
}
/** @brief Pre Command Received
*
* This callback is the second in the Application Framework's message processing
* chain. At this point in the processing of incoming over-the-air messages, the
* application has determined that the incoming message is a ZCL command. It
* parses enough of the message to populate an EmberAfClusterCommand struct. The
* Application Framework defines this struct value in a local scope to the
* command processing but also makes it available through a global pointer
* called emberAfCurrentCommand, in app/framework/util/util.c. When command
* processing is complete, this pointer is cleared.
*
* @param cmd Ver.: always
*/
bool __attribute__((weak)) emberAfPreCommandReceivedCallback(EmberAfClusterCommand * cmd)
{
return false;
}
/** @brief Pre Message Send
*
* This function is called by the framework when it is about to pass a message
* to the stack primitives for sending. This message may or may not be ZCL,
* ZDO, or some other protocol. This is called prior to
any ZigBee
* fragmentation that may be done. If the function returns true it is assumed
* the callback has consumed and processed the message. The callback must also
* set the EmberStatus status code to be passed back to the caller. The
* framework will do no further processing on the message.
If the
* function returns false then it is assumed that the callback has not processed
* the mesasge and the framework will continue to process accordingly.
*
* @param messageStruct The structure containing the parameters of the APS
* message to be sent. Ver.: always
* @param status A pointer to the status code value that will be returned to the
* caller. Ver.: always
*/
bool __attribute__((weak)) emberAfPreMessageSendCallback(EmberAfMessageStruct * messageStruct, EmberStatus * status)
{
return false;
}
/** @brief Message Sent
*
* This function is called by the application framework from the message sent
* handler, when it is informed by the stack regarding the message sent status.
* All of the values passed to the emberMessageSentHandler are passed on to this
* callback. This provides an opportunity for the application to verify that its
* message has been sent successfully and take the appropriate action. This
* callback should return a bool value of true or false. A value of true
* indicates that the message sent notification has been handled and should not
* be handled by the application framework.
*
* @param type Ver.: always
* @param destination Ver.: always
* @param apsFrame Ver.: always
* @param msgLen Ver.: always
* @param message Ver.: always
* @param status Ver.: always
*/
bool __attribute__((weak)) emberAfMessageSentCallback(const MessageSendDestination & destination, EmberApsFrame * apsFrame,
uint16_t msgLen, uint8_t * message, EmberStatus status)
{
return false;
}
/** @brief Pre Attribute Change
*
* This function is called by the application framework before it changes an
* attribute value. The value passed into this callback is the value to which
* the attribute is to be set by the framework. The application should return
* ::EMBER_ZCL_STATUS_SUCCESS to permit the change or any other ::EmberAfStatus
* to reject it.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param attributeId Ver.: always
* @param mask Ver.: always
* @param manufacturerCode Ver.: always
* @param type Ver.: always
* @param size Ver.: always
* @param value Ver.: always
*/
EmberAfStatus __attribute__((weak))
emberAfPreAttributeChangeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t mask,
uint16_t manufacturerCode, uint8_t type, uint16_t size, uint8_t * value)
{
return EMBER_ZCL_STATUS_SUCCESS;
}
/** @brief Post Attribute Change
*
* This function is called by the application framework after it changes an
* attribute value. The value passed into this callback is the value to which
* the attribute was set by the framework.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param attributeId Ver.: always
* @param mask Ver.: always
* @param manufacturerCode Ver.: always
* @param type Ver.: always
* @param size Ver.: always
* @param value Ver.: always
*/
void __attribute__((weak))
emberAfPostAttributeChangeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t mask,
uint16_t manufacturerCode, uint8_t type, uint16_t size, uint8_t * value)
{}
/** @brief Read Attributes Response
*
* This function is called by the application framework when a Read Attributes
* Response command is received from an external device. The application should
* return true if the message was processed or false if it was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param buffer Buffer containing the list of read attribute status records.
* Ver.: always
* @param bufLen The length in bytes of the list. Ver.: always
*/
bool __attribute__((weak)) emberAfReadAttributesResponseCallback(ClusterId clusterId, uint8_t * buffer, uint16_t bufLen)
{
return false;
}
/** @brief External Attribute Read
*
* Like emberAfExternalAttributeWriteCallback above, this function is called
* when the framework needs to read an attribute that is not stored within the
* Application Framework's data structures.
All of the important
* information about the attribute itself is passed as a pointer to an
* EmberAfAttributeMetadata struct, which is stored within the application and
* used to manage the attribute. A complete description of the
* EmberAfAttributeMetadata struct is provided in
* app/framework/include/af-types.h
This function assumes that the
* application is able to read the attribute, write it into the passed buffer,
* and return immediately. Any attributes that require a state machine for
* reading and writing are not really candidates for externalization at the
* present time. The Application Framework does not currently include a state
* machine for reading or writing attributes that must take place across a
* series of application ticks. Attributes that cannot be read in a timely
* manner should be stored within the Application Framework and updated
* occasionally by the application code from within the
* emberAfMainTickCallback.
If the application was successfully able to
* read the attribute and write it into the passed buffer, it should return a
* value of EMBER_ZCL_STATUS_SUCCESS. Ensure that the size of the externally
* managed attribute value is smaller than what the buffer can hold. In the case
* of a buffer overflow throw an appropriate error such as
* EMBER_ZCL_STATUS_INSUFFICIENT_SPACE. Any other return value indicates the
* application was not able to read the attribute.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param attributeMetadata Ver.: always
* @param manufacturerCode Ver.: always
* @param buffer Ver.: always
* @param maxReadLength Ver.: always
* @param index Ver.: always
*/
EmberAfStatus __attribute__((weak))
emberAfExternalAttributeReadCallback(EndpointId endpoint, ClusterId clusterId, EmberAfAttributeMetadata * attributeMetadata,
uint16_t manufacturerCode, uint8_t * buffer, uint16_t maxReadLength, int32_t index)
{
return EMBER_ZCL_STATUS_FAILURE;
}
/** @brief Write Attributes Response
*
* This function is called by the application framework when a Write Attributes
* Response command is received from an external device. The application should
* return true if the message was processed or false if it was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param buffer Buffer containing the list of write attribute status records.
* Ver.: always
* @param bufLen The length in bytes of the list. Ver.: always
*/
bool __attribute__((weak)) emberAfWriteAttributesResponseCallback(ClusterId clusterId, uint8_t * buffer, uint16_t bufLen)
{
return false;
}
/** @brief External Attribute Write
*
* This function is called whenever the Application Framework needs to write an
* attribute which is not stored within the data structures of the Application
* Framework itself. One of the new features in Version 2 is the ability to
* store attributes outside the Framework. This is particularly useful for
* attributes that do not need to be stored because they can be read off the
* hardware when they are needed, or are stored in some central location used by
* many modules within the system. In this case, you can indicate that the
* attribute is stored externally. When the framework needs to write an external
* attribute, it makes a call to this callback.
This callback is very
* useful for host micros which need to store attributes in persistent memory.
* Because each host micro (used with an Ember NCP) has its own type of
* persistent memory storage, the Application Framework does not include the
* ability to mark attributes as stored in flash the way that it does for Ember
* SoCs like the EM35x. On a host micro, any attributes that need to be stored
* in persistent memory should be marked as external and accessed through the
* external read and write callbacks. Any host code associated with the
* persistent storage should be implemented within this callback.
All of
* the important information about the attribute itself is passed as a pointer
* to an EmberAfAttributeMetadata struct, which is stored within the application
* and used to manage the attribute. A complete description of the
* EmberAfAttributeMetadata struct is provided in
* app/framework/include/af-types.h.
This function assumes that the
* application is able to write the attribute and return immediately. Any
* attributes that require a state machine for reading and writing are not
* candidates for externalization at the present time. The Application Framework
* does not currently include a state machine for reading or writing attributes
* that must take place across a series of application ticks. Attributes that
* cannot be written immediately should be stored within the Application
* Framework and updated occasionally by the application code from within the
* emberAfMainTickCallback.
If the application was successfully able to
* write the attribute, it returns a value of EMBER_ZCL_STATUS_SUCCESS. Any
* other return value indicates the application was not able to write the
* attribute.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param attributeMetadata Ver.: always
* @param manufacturerCode Ver.: always
* @param buffer Ver.: always
* @param index Ver.: always
*/
EmberAfStatus __attribute__((weak))
emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, EmberAfAttributeMetadata * attributeMetadata,
uint16_t manufacturerCode, uint8_t * buffer, int32_t index)
{
return EMBER_ZCL_STATUS_FAILURE;
}
/** @brief Report Attributes
*
* This function is called by the application framework when a Report Attributes
* command is received from an external device. The application should return
* true if the message was processed or false if it was not.
*
* @param clusterId The cluster identifier of this command. Ver.: always
* @param buffer Buffer containing the list of attribute report records. Ver.:
* always
* @param bufLen The length in bytes of the list. Ver.: always
*/
bool __attribute__((weak)) emberAfReportAttributesCallback(ClusterId clusterId, uint8_t * buffer, uint16_t bufLen)
{
return false;
}
/** @brief Get Current Time
*
* This callback is called when device attempts to get current time from the
* hardware. If this device has means to retrieve exact time, then this method
* should implement it. If the callback can't provide the exact time it should
* return 0 to indicate failure. Default action is to return 0, which indicates
* that device does not have access to real time.
*
*/
uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback()
{
return 0;
}
/** @brief Get Endpoint Info
*
* This function is a callback to an application implemented endpoint that
* operates outside the normal application framework. When the framework wishes
* to perform operations with that endpoint it uses this callback to retrieve
* the endpoint's information. If the endpoint exists and the application can
* provide data then true shall be returned. Otherwise the callback must return
* false.
*
* @param endpoint The endpoint to retrieve data for. Ver.: always
* @param returnNetworkIndex The index corresponding to the ZigBee network the
* endpoint belongs to. If not using a multi-network device, 0 must be
* returned. Otherwise on a multi-network device the stack will switch to this
* network before sending the message. Ver.: always
* @param returnEndpointInfo A pointer to a data struct that will be written
* with information about the endpoint. Ver.: always
*/
bool __attribute__((weak))
emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo)
{
return false;
}
/** @brief Registration Abort
*
* This callback is called when the device should abort the registration
* process.
*
*/
void __attribute__((weak)) emberAfRegistrationAbortCallback() {}
/** @brief Interpan Send Message
*
* This function will send a raw MAC message with interpan frame format using
* the passed parameters.
*
* @param header Interpan header info Ver.: always
* @param messageLength The length of the message received or to send Ver.:
* always
* @param message The message data received or to send. Ver.: always
*/
EmberStatus __attribute__((weak))
emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message)
{
return EMBER_LIBRARY_NOT_PRESENT;
}
/** @brief Start Move
*
* This function is called to initiate the process for a device to move (rejoin)
* to a new parent.
*
*/
bool __attribute__((weak)) emberAfStartMoveCallback()
{
return false;
}
|
// Copyright (c) 2015-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <vector>
#include <prevector.h>
#include <reverse_iterator.h>
#include <serialize.h>
#include <streams.h>
#include <test/test_titcoin.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup)
template<unsigned int N, typename T>
class prevector_tester {
typedef std::vector<T> realtype;
realtype real_vector;
realtype real_vector_alt;
typedef prevector<N, T> pretype;
pretype pre_vector;
pretype pre_vector_alt;
typedef typename pretype::size_type Size;
bool passed = true;
FastRandomContext rand_cache;
uint256 rand_seed;
template <typename A, typename B>
void local_check_equal(A a, B b)
{
local_check(a == b);
}
void local_check(bool b)
{
passed &= b;
}
void test() {
const pretype& const_pre_vector = pre_vector;
local_check_equal(real_vector.size(), pre_vector.size());
local_check_equal(real_vector.empty(), pre_vector.empty());
for (Size s = 0; s < real_vector.size(); s++) {
local_check(real_vector[s] == pre_vector[s]);
local_check(&(pre_vector[s]) == &(pre_vector.begin()[s]));
local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s));
local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size()));
}
// local_check(realtype(pre_vector) == real_vector);
local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector);
local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector);
size_t pos = 0;
for (const T& v : pre_vector) {
local_check(v == real_vector[pos++]);
}
for (const T& v : reverse_iterate(pre_vector)) {
local_check(v == real_vector[--pos]);
}
for (const T& v : const_pre_vector) {
local_check(v == real_vector[pos++]);
}
for (const T& v : reverse_iterate(const_pre_vector)) {
local_check(v == real_vector[--pos]);
}
CDataStream ss1(SER_DISK, 0);
CDataStream ss2(SER_DISK, 0);
ss1 << real_vector;
ss2 << pre_vector;
local_check_equal(ss1.size(), ss2.size());
for (Size s = 0; s < ss1.size(); s++) {
local_check_equal(ss1[s], ss2[s]);
}
}
public:
void resize(Size s) {
real_vector.resize(s);
local_check_equal(real_vector.size(), s);
pre_vector.resize(s);
local_check_equal(pre_vector.size(), s);
test();
}
void reserve(Size s) {
real_vector.reserve(s);
local_check(real_vector.capacity() >= s);
pre_vector.reserve(s);
local_check(pre_vector.capacity() >= s);
test();
}
void insert(Size position, const T& value) {
real_vector.insert(real_vector.begin() + position, value);
pre_vector.insert(pre_vector.begin() + position, value);
test();
}
void insert(Size position, Size count, const T& value) {
real_vector.insert(real_vector.begin() + position, count, value);
pre_vector.insert(pre_vector.begin() + position, count, value);
test();
}
template<typename I>
void insert_range(Size position, I first, I last) {
real_vector.insert(real_vector.begin() + position, first, last);
pre_vector.insert(pre_vector.begin() + position, first, last);
test();
}
void erase(Size position) {
real_vector.erase(real_vector.begin() + position);
pre_vector.erase(pre_vector.begin() + position);
test();
}
void erase(Size first, Size last) {
real_vector.erase(real_vector.begin() + first, real_vector.begin() + last);
pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last);
test();
}
void update(Size pos, const T& value) {
real_vector[pos] = value;
pre_vector[pos] = value;
test();
}
void push_back(const T& value) {
real_vector.push_back(value);
pre_vector.push_back(value);
test();
}
void pop_back() {
real_vector.pop_back();
pre_vector.pop_back();
test();
}
void clear() {
real_vector.clear();
pre_vector.clear();
}
void assign(Size n, const T& value) {
real_vector.assign(n, value);
pre_vector.assign(n, value);
}
Size size() const {
return real_vector.size();
}
Size capacity() const {
return pre_vector.capacity();
}
void shrink_to_fit() {
pre_vector.shrink_to_fit();
test();
}
void swap() {
real_vector.swap(real_vector_alt);
pre_vector.swap(pre_vector_alt);
test();
}
void move() {
real_vector = std::move(real_vector_alt);
real_vector_alt.clear();
pre_vector = std::move(pre_vector_alt);
pre_vector_alt.clear();
}
void copy() {
real_vector = real_vector_alt;
pre_vector = pre_vector_alt;
}
~prevector_tester() {
BOOST_CHECK_MESSAGE(passed, "insecure_rand: " + rand_seed.ToString());
}
prevector_tester() {
SeedInsecureRand();
rand_seed = insecure_rand_seed;
rand_cache = insecure_rand_ctx;
}
};
BOOST_AUTO_TEST_CASE(PrevectorTestInt)
{
for (int j = 0; j < 64; j++) {
prevector_tester<8, int> test;
for (int i = 0; i < 2048; i++) {
if (InsecureRandBits(2) == 0) {
test.insert(InsecureRandRange(test.size() + 1), InsecureRand32());
}
if (test.size() > 0 && InsecureRandBits(2) == 1) {
test.erase(InsecureRandRange(test.size()));
}
if (InsecureRandBits(3) == 2) {
int new_size = std::max<int>(0, std::min<int>(30, test.size() + (InsecureRandRange(5)) - 2));
test.resize(new_size);
}
if (InsecureRandBits(3) == 3) {
test.insert(InsecureRandRange(test.size() + 1), 1 + InsecureRandBool(), InsecureRand32());
}
if (InsecureRandBits(3) == 4) {
int del = std::min<int>(test.size(), 1 + (InsecureRandBool()));
int beg = InsecureRandRange(test.size() + 1 - del);
test.erase(beg, beg + del);
}
if (InsecureRandBits(4) == 5) {
test.push_back(InsecureRand32());
}
if (test.size() > 0 && InsecureRandBits(4) == 6) {
test.pop_back();
}
if (InsecureRandBits(5) == 7) {
int values[4];
int num = 1 + (InsecureRandBits(2));
for (int k = 0; k < num; k++) {
values[k] = InsecureRand32();
}
test.insert_range(InsecureRandRange(test.size() + 1), values, values + num);
}
if (InsecureRandBits(5) == 8) {
int del = std::min<int>(test.size(), 1 + (InsecureRandBits(2)));
int beg = InsecureRandRange(test.size() + 1 - del);
test.erase(beg, beg + del);
}
if (InsecureRandBits(5) == 9) {
test.reserve(InsecureRandBits(5));
}
if (InsecureRandBits(6) == 10) {
test.shrink_to_fit();
}
if (test.size() > 0) {
test.update(InsecureRandRange(test.size()), InsecureRand32());
}
if (InsecureRandBits(10) == 11) {
test.clear();
}
if (InsecureRandBits(9) == 12) {
test.assign(InsecureRandBits(5), InsecureRand32());
}
if (InsecureRandBits(3) == 3) {
test.swap();
}
if (InsecureRandBits(4) == 8) {
test.copy();
}
if (InsecureRandBits(5) == 18) {
test.move();
}
}
}
}
BOOST_AUTO_TEST_SUITE_END()
|
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/codecs/g711/audio_encoder_pcm.h"
#include <limits>
#include "webrtc/base/checks.h"
#include "webrtc/common_types.h"
#include "webrtc/modules/audio_coding/codecs/g711/g711_interface.h"
namespace webrtc {
namespace {
template <typename T>
typename T::Config CreateConfig(const CodecInst& codec_inst) {
typename T::Config config;
config.frame_size_ms = codec_inst.pacsize / 8;
config.num_channels = codec_inst.channels;
config.payload_type = codec_inst.pltype;
return config;
}
} // namespace
bool AudioEncoderPcm::Config::IsOk() const {
return (frame_size_ms % 10 == 0) && (num_channels >= 1);
}
AudioEncoderPcm::AudioEncoderPcm(const Config& config, int sample_rate_hz)
: sample_rate_hz_(sample_rate_hz),
num_channels_(config.num_channels),
payload_type_(config.payload_type),
num_10ms_frames_per_packet_(
static_cast<size_t>(config.frame_size_ms / 10)),
full_frame_samples_(
config.num_channels * config.frame_size_ms * sample_rate_hz / 1000),
first_timestamp_in_buffer_(0) {
RTC_CHECK_GT(sample_rate_hz, 0) << "Sample rate must be larger than 0 Hz";
RTC_CHECK_EQ(config.frame_size_ms % 10, 0)
<< "Frame size must be an integer multiple of 10 ms.";
speech_buffer_.reserve(full_frame_samples_);
}
AudioEncoderPcm::~AudioEncoderPcm() = default;
size_t AudioEncoderPcm::MaxEncodedBytes() const {
return full_frame_samples_ * BytesPerSample();
}
int AudioEncoderPcm::SampleRateHz() const {
return sample_rate_hz_;
}
size_t AudioEncoderPcm::NumChannels() const {
return num_channels_;
}
size_t AudioEncoderPcm::Num10MsFramesInNextPacket() const {
return num_10ms_frames_per_packet_;
}
size_t AudioEncoderPcm::Max10MsFramesInAPacket() const {
return num_10ms_frames_per_packet_;
}
int AudioEncoderPcm::GetTargetBitrate() const {
return static_cast<int>(
8 * BytesPerSample() * SampleRateHz() * NumChannels());
}
AudioEncoder::EncodedInfo AudioEncoderPcm::EncodeInternal(
uint32_t rtp_timestamp,
rtc::ArrayView<const int16_t> audio,
size_t max_encoded_bytes,
uint8_t* encoded) {
if (speech_buffer_.empty()) {
first_timestamp_in_buffer_ = rtp_timestamp;
}
speech_buffer_.insert(speech_buffer_.end(), audio.begin(), audio.end());
if (speech_buffer_.size() < full_frame_samples_) {
return EncodedInfo();
}
RTC_CHECK_EQ(speech_buffer_.size(), full_frame_samples_);
RTC_CHECK_GE(max_encoded_bytes, full_frame_samples_);
EncodedInfo info;
info.encoded_timestamp = first_timestamp_in_buffer_;
info.payload_type = payload_type_;
info.encoded_bytes =
EncodeCall(&speech_buffer_[0], full_frame_samples_, encoded);
speech_buffer_.clear();
return info;
}
void AudioEncoderPcm::Reset() {
speech_buffer_.clear();
}
AudioEncoderPcmA::AudioEncoderPcmA(const CodecInst& codec_inst)
: AudioEncoderPcmA(CreateConfig<AudioEncoderPcmA>(codec_inst)) {}
size_t AudioEncoderPcmA::EncodeCall(const int16_t* audio,
size_t input_len,
uint8_t* encoded) {
return WebRtcG711_EncodeA(audio, input_len, encoded);
}
size_t AudioEncoderPcmA::BytesPerSample() const {
return 1;
}
AudioEncoderPcmU::AudioEncoderPcmU(const CodecInst& codec_inst)
: AudioEncoderPcmU(CreateConfig<AudioEncoderPcmU>(codec_inst)) {}
size_t AudioEncoderPcmU::EncodeCall(const int16_t* audio,
size_t input_len,
uint8_t* encoded) {
return WebRtcG711_EncodeU(audio, input_len, encoded);
}
size_t AudioEncoderPcmU::BytesPerSample() const {
return 1;
}
} // namespace webrtc
|
/// @ref core
/// @file glm/ext/matrix_double4x2_precision.hpp
#pragma once
#include "../detail/type_mat4x2.hpp"
namespace glm
{
/// @addtogroup core_matrix_precision
/// @{
/// 4 columns of 2 components matrix of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef mat<4, 2, double, lowp> lowp_dmat4x2;
/// 4 columns of 2 components matrix of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef mat<4, 2, double, mediump> mediump_dmat4x2;
/// 4 columns of 2 components matrix of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef mat<4, 2, double, highp> highp_dmat4x2;
/// @}
}//namespace glm
|
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_GRAPHICS_RENDERSPRITECHAIN_HPP
#define NAZARA_GRAPHICS_RENDERSPRITECHAIN_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Graphics/RenderElement.hpp>
#include <Nazara/Graphics/RenderQueueRegistry.hpp>
#include <Nazara/Graphics/WorldInstance.hpp>
#include <memory>
#include <vector>
namespace Nz
{
class MaterialPass;
class VertexDeclaration;
class ViewerInstance;
class RenderSpriteChain : public RenderElement
{
public:
inline RenderSpriteChain(int renderLayer, std::shared_ptr<MaterialPass> materialPass, std::shared_ptr<RenderPipeline> renderPipeline, const WorldInstance& worldInstance, std::shared_ptr<VertexDeclaration> vertexDeclaration, std::shared_ptr<Texture> textureOverlay, std::size_t spriteCount, const void* spriteData, const Recti& scissorBox);
~RenderSpriteChain() = default;
inline UInt64 ComputeSortingScore(const Frustumf& frustum, const RenderQueueRegistry& registry) const override;
inline const MaterialPass& GetMaterialPass() const;
inline const RenderPipeline& GetRenderPipeline() const;
inline const Recti& GetScissorBox() const;
inline std::size_t GetSpriteCount() const;
inline const void* GetSpriteData() const;
inline const Texture* GetTextureOverlay() const;
inline const VertexDeclaration* GetVertexDeclaration() const;
inline const WorldInstance& GetWorldInstance() const;
inline void Register(RenderQueueRegistry& registry) const override;
private:
std::shared_ptr<MaterialPass> m_materialPass;
std::shared_ptr<RenderPipeline> m_renderPipeline;
std::shared_ptr<VertexDeclaration> m_vertexDeclaration;
std::shared_ptr<Texture> m_textureOverlay;
std::size_t m_spriteCount;
const void* m_spriteData;
const WorldInstance& m_worldInstance;
Recti m_scissorBox;
int m_renderLayer;
};
}
#include <Nazara/Graphics/RenderSpriteChain.inl>
#endif // NAZARA_GRAPHICS_RENDERSPRITECHAIN_HPP
|
// (C) Copyright David Abrahams 2004.
// (C) Copyright Jonathan Turkanis 2005.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
#ifndef BOOST_IOSTREAMS_DETAIL_IS_DEREFERENCEABLE_HPP_INCLUDED
#define BOOST_IOSTREAMS_DETAIL_IS_DEREFERENCEABLE_HPP_INCLUDED
# include <boost/type_traits/detail/bool_trait_def.hpp>
# include <boost/type_traits/detail/template_arity_spec.hpp>
# include <boost/type_traits/remove_cv.hpp>
# include <boost/mpl/aux_/lambda_support.hpp>
# include <boost/mpl/bool.hpp>
# include <boost/detail/workaround.hpp>
namespace boost { namespace iostreams { namespace detail {
// is_dereferenceable<T> metafunction
//
// Requires: Given x of type T&, if the expression *x is well-formed
// it must have complete type; otherwise, it must neither be ambiguous
// nor violate access.
// This namespace ensures that ADL doesn't mess things up.
namespace is_dereferenceable_
{
// a type returned from operator* when no increment is found in the
// type's own namespace
struct tag {};
// any soaks up implicit conversions and makes the following
// operator* less-preferred than any other such operator that
// might be found via ADL.
struct any { template <class T> any(T const&); };
// This is a last-resort operator* for when none other is found
tag operator*(any const&);
# if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3202)) \
|| BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
# define BOOST_comma(a,b) (a)
# else
// In case an operator++ is found that returns void, we'll use ++x,0
tag operator,(tag,int);
# define BOOST_comma(a,b) (a,b)
# endif
// two check overloads help us identify which operator++ was picked
char (& check(tag) )[2];
template <class T>
char check(T const&);
template <class T>
struct impl
{
static typename boost::remove_cv<T>::type& x;
BOOST_STATIC_CONSTANT(
bool
, value = sizeof(is_dereferenceable_::check(BOOST_comma(*x,0))) == 1
);
};
}
# undef BOOST_comma
template<typename T>
struct is_dereferenceable
BOOST_TT_AUX_BOOL_C_BASE(is_dereferenceable_::impl<T>::value)
{
BOOST_TT_AUX_BOOL_TRAIT_VALUE_DECL(is_dereferenceable_::impl<T>::value)
BOOST_MPL_AUX_LAMBDA_SUPPORT(1,is_dereferenceable,(T))
};
} }
BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(1, ::boost::iostreams::detail::is_dereferenceable)
} // End namespaces detail, iostreams, boost.
#endif // BOOST_IOSTREAMS_DETAIL_IS_DEREFERENCEABLE_HPP_INCLUDED
|
// https://leetcode.com/problems/first-missing-positive/
#include <iostream>
using namespace std;
int firstMissingPositive(int arr[], int n)
{
int i = 0;
while (i < n)
{
int correct = arr[i] - 1;
if (arr[i] > 0 && arr[i] <= n && arr[i] != arr[correct])
{
swap(arr[i], arr[correct]);
}
else
{
i++;
}
}
// search for first missing number
for (int index = 0; index < n; index++)
{
if (arr[index] != index + 1)
{
return index + 1;
}
}
// case 2
return n + 1;
}
int main()
{
int arr[4] = {4, 0, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);
cout << firstMissingPositive(arr, n);
return 0;
}
|
/**********************************************************************
Audacity: A Digital Audio Editor
ImportFFmpeg.cpp
Copyright 2008 LRN
Based on ImportFLAC.cpp by Sami Liedes and transcode_sample.c by ANYwebcam Pty Ltd
Licensed under the GNU General Public License v2 or later
*//****************************************************************//**
\class FFmpegImportFileHandle
\brief An ImportFileHandle for FFmpeg data
*//****************************************************************//**
\class FFmpegImportPlugin
\brief An ImportPlugin for FFmpeg data
*//*******************************************************************/
#include "../Audacity.h" // needed before FFmpeg.h
#include "ImportFFmpeg.h"
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>
#include "../FFmpeg.h" // which brings in avcodec.h, avformat.h
#include "../ondemand/ODManager.h"
#ifndef WX_PRECOMP
// Include your minimal set of headers here, or wx.h
#include <wx/window.h>
#endif
#include "../Experimental.h"
#include "../MemoryX.h"
#define DESC _("FFmpeg-compatible files")
//TODO: remove non-audio extensions
#if defined(USE_FFMPEG)
static const wxChar *exts[] =
{
wxT("4xm"),
wxT("MTV"),
wxT("roq"),
wxT("aac"),
wxT("ac3"),
wxT("aif"),
wxT("aiff"),
wxT("afc"),
wxT("aifc"),
wxT("al"),
wxT("amr"),
wxT("apc"),
wxT("ape"),
wxT("apl"),
wxT("mac"),
wxT("asf"),
wxT("wmv"),
wxT("wma"),
wxT("au"),
wxT("avi"),
wxT("avs"),
wxT("bethsoftvid"),
wxT("c93"),
wxT("302"),
wxT("daud"),
wxT("dsicin"),
wxT("dts"),
wxT("dv"),
wxT("dxa"),
wxT("ea"),
wxT("cdata"),
wxT("ffm"),
wxT("film_cpk"),
wxT("flac"),
wxT("flic"),
wxT("flv"),
wxT("gif"),
wxT("gxf"),
wxT("idcin"),
wxT("image2"),
wxT("image2pipe"),
wxT("cgi"),
wxT("ipmovie"),
wxT("nut"),
wxT("lmlm4"),
wxT("m4v"),
wxT("mkv"),
wxT("mm"),
wxT("mmf"),
wxT("mov"),
wxT("mp4"),
wxT("m4a"),
wxT("m4r"),
wxT("3gp"),
wxT("3g2"),
wxT("mj2"),
wxT("mp3"),
wxT("mpc"),
wxT("mpc8"),
wxT("mpg"),
wxT("mpeg"),
wxT("ts"),
wxT("mpegtsraw"),
wxT("mpegvideo"),
wxT("msnwctcp"),
wxT("ul"),
wxT("mxf"),
wxT("nsv"),
wxT("nuv"),
wxT("ogg"),
wxT("psxstr"),
wxT("pva"),
wxT("redir"),
wxT("rl2"),
wxT("rm"),
wxT("ra"),
wxT("rv"),
wxT("rtsp"),
wxT("s16be"),
wxT("sw"),
wxT("s8"),
wxT("sb"),
wxT("sdp"),
wxT("shn"),
wxT("siff"),
wxT("vb"),
wxT("son"),
wxT("smk"),
wxT("sol"),
wxT("swf"),
wxT("thp"),
wxT("tiertexseq"),
wxT("tta"),
wxT("txd"),
wxT("u16be"),
wxT("uw"),
wxT("ub"),
wxT("u8"),
wxT("vfwcap"),
wxT("vmd"),
wxT("voc"),
wxT("wav"),
wxT("wc3movie"),
wxT("wsaud"),
wxT("wsvqa"),
wxT("wv")
};
// all the includes live here by default
#include "Import.h"
#include "../Tags.h"
#include "../Internat.h"
#include "../WaveTrack.h"
#include "ImportPlugin.h"
#ifdef EXPERIMENTAL_OD_FFMPEG
#include "../ondemand/ODDecodeFFmpegTask.h"
#endif
extern FFmpegLibs *FFmpegLibsInst();
class FFmpegImportFileHandle;
/// A representative of FFmpeg loader in
/// the Audacity import plugin list
class FFmpegImportPlugin final : public ImportPlugin
{
public:
FFmpegImportPlugin():
ImportPlugin(wxArrayString(WXSIZEOF(exts),exts))
{
}
~FFmpegImportPlugin() { }
wxString GetPluginStringID() { return wxT("libav"); }
wxString GetPluginFormatDescription();
///! Probes the file and opens it if appropriate
std::unique_ptr<ImportFileHandle> Open(const wxString &Filename) override;
};
///! Does acual import, returned by FFmpegImportPlugin::Open
class FFmpegImportFileHandle final : public ImportFileHandle
{
public:
FFmpegImportFileHandle(const wxString & name);
~FFmpegImportFileHandle();
///! Format initialization
///\return true if successful, false otherwise
bool Init();
///! Codec initialization
///\return true if successful, false otherwise
bool InitCodecs();
wxString GetFileDescription() override;
ByteCount GetFileUncompressedBytes() override;
///! Imports audio
///\return import status (see Import.cpp)
ProgressResult Import(TrackFactory *trackFactory, TrackHolders &outTracks,
Tags *tags) override;
///! Reads next audio frame
///\return pointer to the stream context structure to which the frame belongs to or NULL on error, or 1 if stream is not to be imported.
streamContext* ReadNextFrame();
///! Decodes the frame
///\param sc - stream context (from ReadNextFrame)
///\param flushing - true if flushing (no more frames left), false otherwise
///\return 0 on success, -1 if it can't decode any further
int DecodeFrame(streamContext *sc, bool flushing);
///! Writes decoded data into WaveTracks. Called by DecodeFrame
///\param sc - stream context
ProgressResult WriteData(streamContext *sc);
///! Writes extracted metadata to tags object
///\param avf - file context
///\ tags - Audacity tags object
void WriteMetadata(Tags *tags);
///! Retrieves metadata from FFmpeg and converts to wxString
///\param avf - file context
///\ tags - Audacity tags object
///\ tag - name of tag to set
///\ name - name of metadata item to retrieve
void GetMetadata(Tags *tags, const wxChar *tag, const char *name);
///! Called by Import.cpp
///\return number of readable streams in the file
wxInt32 GetStreamCount() override
{
return mNumStreams;
}
///! Called by Import.cpp
///\return array of strings - descriptions of the streams
const wxArrayString &GetStreamInfo() override
{
return mStreamInfo;
}
///! Called by Import.cpp
///\param StreamID - index of the stream in mStreamInfo and mScs arrays
///\param Use - true if this stream should be imported, false otherwise
void SetStreamUsage(wxInt32 StreamID, bool Use) override
{
if (StreamID < mNumStreams)
mScs->get()[StreamID]->m_use = Use;
}
private:
std::shared_ptr<FFmpegContext> mContext; // An object that does proper IO shutdown in its destructor; may be shared with decoder task.
AVFormatContext *mFormatContext; //!< Format description, also contains metadata and some useful info
int mNumStreams; //!< mNumstreams is less or equal to mFormatContext->nb_streams
ScsPtr mScs; //!< Points to array of pointers to stream contexts, which may be shared with a decoder task.
wxArrayString mStreamInfo; //!< Array of stream descriptions. Length is mNumStreams
wxInt64 mProgressPos; //!< Current timestamp, file position or whatever is used as first argument for Update()
wxInt64 mProgressLen; //!< Duration, total length or whatever is used as second argument for Update()
bool mCancelled; //!< True if importing was canceled by user
bool mStopped; //!< True if importing was stopped by user
wxString mName;
std::list<TrackHolders> mChannels; //!< 2-dimentional array of WaveTrack's. First dimention - streams, second - channels of a stream. Length is mNumStreams
#ifdef EXPERIMENTAL_OD_FFMPEG
bool mUsingOD;
#endif
};
void GetFFmpegImportPlugin(ImportPluginList &importPluginList,
UnusableImportPluginList &WXUNUSED(unusableImportPluginList))
{
importPluginList.push_back( make_movable<FFmpegImportPlugin>() );
}
wxString FFmpegImportPlugin::GetPluginFormatDescription()
{
return DESC;
}
std::unique_ptr<ImportFileHandle> FFmpegImportPlugin::Open(const wxString &filename)
{
auto handle = std::make_unique<FFmpegImportFileHandle>(filename);
//Check if we're loading explicitly supported format
wxString extension = filename.AfterLast(wxT('.'));
if (SupportsExtension(extension))
{
//Audacity is trying to load something that is declared as
//officially supported by this plugin.
//If we don't have FFmpeg configured - tell the user about it.
//Since this will be happening often, use disableable "FFmpeg not found" dialog
//insdead of usual wxMessageBox()
bool newsession = false;
gPrefs->Read(wxT("/NewImportingSession"), &newsession);
if (!FFmpegLibsInst()->ValidLibsLoaded())
{
int dontShowDlg;
gPrefs->Read(wxT("/FFmpeg/NotFoundDontShow"),&dontShowDlg,0);
if (dontShowDlg == 0 && newsession)
{
gPrefs->Write(wxT("/NewImportingSession"), false);
gPrefs->Flush();
FFmpegNotFoundDialog{ nullptr }.ShowModal();
}
}
}
if (!FFmpegLibsInst()->ValidLibsLoaded())
{
return nullptr;
}
// Open the file for import
bool success = handle->Init();
if (!success) {
return nullptr;
}
// This std::move is needed to "upcast" the pointer type
return std::move(handle);
}
FFmpegImportFileHandle::FFmpegImportFileHandle(const wxString & name)
: ImportFileHandle(name)
{
PickFFmpegLibs();
mFormatContext = NULL;
mNumStreams = 0;
mCancelled = false;
mStopped = false;
mName = name;
mProgressPos = 0;
mProgressLen = 1;
}
bool FFmpegImportFileHandle::Init()
{
//FFmpegLibsInst()->LoadLibs(NULL,false); //Loaded at startup or from Prefs now
if (!FFmpegLibsInst()->ValidLibsLoaded())
return false;
av_log_set_callback(av_log_wx_callback);
int err;
std::unique_ptr<FFmpegContext> tempContext;
err = ufile_fopen_input(tempContext, mName);
if (err < 0)
{
wxLogError(wxT("FFmpeg : av_open_input_file() failed for file %s"), mName.c_str());
return false;
}
wxASSERT(tempContext.get());
mFormatContext = tempContext->ic_ptr;
err = avformat_find_stream_info(mFormatContext, NULL);
if (err < 0)
{
wxLogError(wxT("FFmpeg: avformat_find_stream_info() failed for file %s"),mName.c_str());
return false;
}
if (!InitCodecs())
return false;
// Only now do we postpone destroying the FFmpegContext.
// Move from unique to shared pointer
mContext.reset(tempContext.release());
return true;
}
bool FFmpegImportFileHandle::InitCodecs()
{
// Allocate the array of pointers to hold stream contexts pointers
// Some of the allocated space may be unused (corresponds to video, subtitle, or undecodeable audio streams)
mScs = std::make_shared<Scs>(size_t{mFormatContext->nb_streams});
// Fill the stream contexts
for (unsigned int i = 0; i < mFormatContext->nb_streams; i++)
{
if (mFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
{
//Create a context
auto sc = std::make_unique<streamContext>();
sc->m_stream = mFormatContext->streams[i];
sc->m_codecCtx = sc->m_stream->codec;
AVCodec *codec = avcodec_find_decoder(sc->m_codecCtx->codec_id);
if (codec == NULL)
{
wxLogError(wxT("FFmpeg : avcodec_find_decoder() failed. Index[%02d], Codec[%02x - %s]"),i,sc->m_codecCtx->codec_id,sc->m_codecCtx->codec_name);
//FFmpeg can't decode this stream, skip it
continue;
}
if (codec->type != sc->m_codecCtx->codec_type)
{
wxLogError(wxT("FFmpeg : Codec type mismatch, skipping. Index[%02d], Codec[%02x - %s]"),i,sc->m_codecCtx->codec_id,sc->m_codecCtx->codec_name);
//Non-audio codec reported as audio? Nevertheless, we don't need THIS.
continue;
}
if (avcodec_open2(sc->m_codecCtx, codec, NULL) < 0)
{
wxLogError(wxT("FFmpeg : avcodec_open() failed. Index[%02d], Codec[%02x - %s]"),i,sc->m_codecCtx->codec_id,sc->m_codecCtx->codec_name);
//Can't open decoder - skip this stream
continue;
}
// Stream is decodeable and it is audio. Add it and its decription to the arrays
wxString strinfo;
int duration = 0;
if (sc->m_stream->duration > 0)
duration = sc->m_stream->duration * sc->m_stream->time_base.num / sc->m_stream->time_base.den;
else
duration = mFormatContext->duration / AV_TIME_BASE;
wxString bitrate = wxT("");
if (sc->m_codecCtx->bit_rate > 0)
bitrate.Printf(wxT("%d"),sc->m_codecCtx->bit_rate);
else
bitrate.Printf(wxT("?"));
AVDictionaryEntry *tag = av_dict_get(sc->m_stream->metadata, "language", NULL, 0);
wxString lang;
if (tag)
{
lang.FromUTF8(tag->value);
}
strinfo.Printf(_("Index[%02x] Codec[%s], Language[%s], Bitrate[%s], Channels[%d], Duration[%d]"),sc->m_stream->id,codec->name,lang.c_str(),bitrate.c_str(),sc->m_stream->codec->channels, duration);
mStreamInfo.Add(strinfo);
mScs->get()[mNumStreams++] = std::move(sc);
}
//for video and unknown streams do nothing
}
//It doesn't really returns false, but GetStreamCount() will return 0 if file is composed entierly of unreadable streams
return true;
}
wxString FFmpegImportFileHandle::GetFileDescription()
{
return DESC;
}
auto FFmpegImportFileHandle::GetFileUncompressedBytes() -> ByteCount
{
// TODO: Get Uncompressed byte count.
return 0;
}
ProgressResult FFmpegImportFileHandle::Import(TrackFactory *trackFactory,
TrackHolders &outTracks,
Tags *tags)
{
outTracks.clear();
CreateProgress();
// Remove stream contexts which are not marked for importing and adjust mScs and mNumStreams accordingly
const auto scs = mScs->get();
for (int i = 0; i < mNumStreams;)
{
if (!scs[i]->m_use)
{
for (int j = i; j < mNumStreams - 1; j++)
{
scs[j] = std::move(scs[j+1]);
}
mNumStreams--;
}
else i++;
}
mChannels.resize(mNumStreams);
int s = -1;
for (auto &stream : mChannels)
{
++s;
auto sc = scs[s].get();
switch (sc->m_stream->codec->sample_fmt)
{
case AV_SAMPLE_FMT_U8:
case AV_SAMPLE_FMT_S16:
case AV_SAMPLE_FMT_U8P:
case AV_SAMPLE_FMT_S16P:
sc->m_osamplesize = sizeof(int16_t);
sc->m_osamplefmt = int16Sample;
break;
default:
sc->m_osamplesize = sizeof(float);
sc->m_osamplefmt = floatSample;
break;
}
// There is a possibility that number of channels will change over time, but we do not have WaveTracks for NEW channels. Remember the number of channels and stick to it.
sc->m_initialchannels = sc->m_stream->codec->channels;
stream.resize(sc->m_stream->codec->channels);
int c = -1;
for (auto &channel : stream)
{
++c;
channel = trackFactory->NewWaveTrack(sc->m_osamplefmt, sc->m_stream->codec->sample_rate);
if (sc->m_stream->codec->channels == 2)
{
switch (c)
{
case 0:
channel->SetChannel(Track::LeftChannel);
channel->SetLinked(true);
break;
case 1:
channel->SetChannel(Track::RightChannel);
break;
}
}
else
{
channel->SetChannel(Track::MonoChannel);
}
}
}
// Handles the start_time by creating silence. This may or may not be correct.
// There is a possibility that we should ignore first N milliseconds of audio instead. I do not know.
/// TODO: Nag FFmpeg devs about start_time until they finally say WHAT is this and HOW to handle it.
s = -1;
for (auto &stream : mChannels)
{
++s;
int64_t stream_delay = 0;
auto sc = scs[s].get();
if (sc->m_stream->start_time != int64_t(AV_NOPTS_VALUE) && sc->m_stream->start_time > 0)
{
stream_delay = sc->m_stream->start_time;
wxLogDebug(wxT("Stream %d start_time = %lld, that would be %f milliseconds."), s, (long long) sc->m_stream->start_time, double(sc->m_stream->start_time)/AV_TIME_BASE*1000);
}
if (stream_delay != 0)
{
int c = -1;
for (auto &channel : stream)
{
++c;
WaveTrack *t = channel.get();
t->InsertSilence(0,double(stream_delay)/AV_TIME_BASE);
}
}
}
// This is the heart of the importing process
// The result of Import() to be returend. It will be something other than zero if user canceled or some error appears.
auto res = ProgressResult::Success;
#ifdef EXPERIMENTAL_OD_FFMPEG
mUsingOD = false;
gPrefs->Read(wxT("/Library/FFmpegOnDemand"), &mUsingOD);
//at this point we know the file is good and that we have to load the number of channels in mScs[s]->m_stream->codec->channels;
//so for OD loading we create the tracks and releasee the modal lock after starting the ODTask.
if (mUsingOD) {
std::vector<movable_ptr<ODDecodeFFmpegTask>> tasks;
//append blockfiles to each stream and add an individual ODDecodeTask for each one.
s = -1;
for (const auto &stream : mChannels) {
++s;
auto odTask =
make_movable<ODDecodeFFmpegTask>(mScs, ODDecodeFFmpegTask::FromList(mChannels), mContext, s);
odTask->CreateFileDecoder(mFilename);
//each stream has different duration. We need to know it if seeking is to be allowed.
sampleCount sampleDuration = 0;
auto sc = scs[s].get();
if (sc->m_stream->duration > 0)
sampleDuration = ((sampleCount)sc->m_stream->duration * sc->m_stream->time_base.num) * sc->m_stream->codec->sample_rate / sc->m_stream->time_base.den;
else
sampleDuration = ((sampleCount)mFormatContext->duration *sc->m_stream->codec->sample_rate) / AV_TIME_BASE;
// printf(" OD duration samples %qi, sr %d, secs %d\n",sampleDuration, (int)sc->m_stream->codec->sample_rate, (int)sampleDuration/sc->m_stream->codec->sample_rate);
//for each wavetrack within the stream add coded blockfiles
for (int c = 0; c < sc->m_stream->codec->channels; c++) {
WaveTrack *t = stream[c].get();
odTask->AddWaveTrack(t);
auto maxBlockSize = t->GetMaxBlockSize();
//use the maximum blockfile size to divide the sections (about 11secs per blockfile at 44.1khz)
for (decltype(sampleDuration) i = 0; i < sampleDuration; i += maxBlockSize) {
const auto blockLen =
limitSampleBufferSize( maxBlockSize, sampleDuration - i );
t->AppendCoded(mFilename, i, blockLen, c, ODTask::eODFFMPEG);
// This only works well for single streams since we assume
// each stream is of the same duration and channels
res = mProgress->Update(
(i+sampleDuration * c +
sampleDuration*sc->m_stream->codec->channels * s
).as_long_long(),
(sampleDuration *
sc->m_stream->codec->channels * mNumStreams
).as_long_long()
);
if (res != ProgressResult::Success)
break;
}
}
tasks.push_back(std::move(odTask));
}
//Now we add the tasks and let them run, or DELETE them if the user cancelled
if (res == ProgressResult::Success)
for (int i = 0; i < (int)tasks.size(); i++)
ODManager::Instance()->AddNewTask(std::move(tasks[i]));
} else {
#endif
// Read next frame.
for (streamContext *sc; (sc = ReadNextFrame()) != NULL && (res == ProgressResult::Success);)
{
// ReadNextFrame returns 1 if stream is not to be imported
if (sc != (streamContext*)1)
{
// Decode frame until it is not possible to decode any further
while (sc->m_pktRemainingSiz > 0 && (res == ProgressResult::Success || res == ProgressResult::Stopped))
{
if (DecodeFrame(sc,false) < 0)
break;
// If something useable was decoded - write it to mChannels
if (sc->m_frameValid)
res = WriteData(sc);
}
// Cleanup after frame decoding
sc->m_pkt.reset();
}
}
// Flush the decoders.
if ((mNumStreams != 0) && (res == ProgressResult::Success || res == ProgressResult::Stopped))
{
for (int i = 0; i < mNumStreams; i++)
{
auto sc = scs[i].get();
sc->m_pkt.create();
if (DecodeFrame(sc, true) == 0)
{
WriteData(sc);
sc->m_pkt.reset();
}
}
}
#ifdef EXPERIMENTAL_OD_FFMPEG
} // else -- !mUsingOD == true
#endif //EXPERIMENTAL_OD_FFMPEG
// Something bad happened - destroy everything!
if (res == ProgressResult::Cancelled || res == ProgressResult::Failed)
return res;
//else if (res == 2), we just stop the decoding as if the file has ended
// Copy audio from mChannels to newly created tracks (destroying mChannels elements in process)
for (auto &stream : mChannels)
{
for(auto &channel : stream)
{
channel->Flush();
outTracks.push_back(std::move(channel));
}
}
// Save metadata
WriteMetadata(tags);
return res;
}
streamContext *FFmpegImportFileHandle::ReadNextFrame()
{
// Get pointer to array of contiguous unique_ptrs
auto scs = mScs->get();
// This reinterpret_cast to array of plain pointers is innocent
return import_ffmpeg_read_next_frame
(mFormatContext, reinterpret_cast<streamContext**>(scs), mNumStreams);
}
int FFmpegImportFileHandle::DecodeFrame(streamContext *sc, bool flushing)
{
return import_ffmpeg_decode_frame(sc, flushing);
}
ProgressResult FFmpegImportFileHandle::WriteData(streamContext *sc)
{
// Find the stream index in mScs array
int streamid = -1;
auto iter = mChannels.begin();
auto scs = mScs->get();
for (int i = 0; i < mNumStreams; ++iter, ++i)
{
if (scs[i].get() == sc)
{
streamid = i;
break;
}
}
// Stream is not found. This should not really happen
if (streamid == -1)
{
return ProgressResult::Success;
}
// Allocate the buffer to store audio.
auto insamples = sc->m_decodedAudioSamplesValidSiz / sc->m_samplesize;
size_t nChannels = std::min(sc->m_stream->codec->channels, sc->m_initialchannels);
ArraysOf<uint8_t> tmp{ nChannels, sc->m_osamplesize * (insamples / nChannels) };
// Separate the channels and convert input sample format to 16-bit
uint8_t *in = sc->m_decodedAudioSamples.get();
int index = 0;
int pos = 0;
while (pos < insamples)
{
for (int chn = 0; chn < sc->m_stream->codec->channels; chn++)
{
if (chn < nChannels)
{
switch (sc->m_samplefmt)
{
case AV_SAMPLE_FMT_U8:
case AV_SAMPLE_FMT_U8P:
((int16_t *)tmp[chn].get())[index] = (int16_t) (*(uint8_t *)in - 0x80) << 8;
break;
case AV_SAMPLE_FMT_S16:
case AV_SAMPLE_FMT_S16P:
((int16_t *)tmp[chn].get())[index] = (int16_t) *(int16_t *)in;
break;
case AV_SAMPLE_FMT_S32:
case AV_SAMPLE_FMT_S32P:
((float *)tmp[chn].get())[index] = (float) *(int32_t *)in * (1.0 / (1u << 31));
break;
case AV_SAMPLE_FMT_FLT:
case AV_SAMPLE_FMT_FLTP:
((float *)tmp[chn].get())[index] = (float) *(float *)in;
break;
case AV_SAMPLE_FMT_DBL:
case AV_SAMPLE_FMT_DBLP:
((float *)tmp[chn].get())[index] = (float) *(double *)in;
break;
default:
wxLogError(wxT("Stream %d has unrecognized sample format %d."), streamid, sc->m_samplefmt);
return ProgressResult::Success;
break;
}
}
in += sc->m_samplesize;
pos++;
}
index++;
}
// Write audio into WaveTracks
auto iter2 = iter->begin();
for (int chn=0; chn < nChannels; ++iter2, ++chn)
{
iter2->get()->Append((samplePtr)tmp[chn].get(), sc->m_osamplefmt, index);
}
// Try to update the progress indicator (and see if user wants to cancel)
auto updateResult = ProgressResult::Success;
int64_t filesize = avio_size(mFormatContext->pb);
// PTS (presentation time) is the proper way of getting current position
if (sc->m_pkt->pts != int64_t(AV_NOPTS_VALUE) && mFormatContext->duration != int64_t(AV_NOPTS_VALUE))
{
mProgressPos = sc->m_pkt->pts * sc->m_stream->time_base.num / sc->m_stream->time_base.den;
mProgressLen = (mFormatContext->duration > 0 ? mFormatContext->duration / AV_TIME_BASE: 1);
}
// When PTS is not set, use number of frames and number of current frame
else if (sc->m_stream->nb_frames > 0 && sc->m_codecCtx->frame_number > 0 && sc->m_codecCtx->frame_number <= sc->m_stream->nb_frames)
{
mProgressPos = sc->m_codecCtx->frame_number;
mProgressLen = sc->m_stream->nb_frames;
}
// When number of frames is unknown, use position in file
else if (filesize > 0 && sc->m_pkt->pos > 0 && sc->m_pkt->pos <= filesize)
{
mProgressPos = sc->m_pkt->pos;
mProgressLen = filesize;
}
updateResult = mProgress->Update(mProgressPos, mProgressLen != 0 ? mProgressLen : 1);
return updateResult;
}
void FFmpegImportFileHandle::WriteMetadata(Tags *tags)
{
tags->Clear();
GetMetadata(tags, TAG_TITLE, "title");
GetMetadata(tags, TAG_ARTIST, "author");
// GetMetadata(tags, TAG_COPYRIGHT, "copyright");
GetMetadata(tags, TAG_COMMENTS, "comment");
GetMetadata(tags, TAG_ALBUM, "album");
GetMetadata(tags, TAG_YEAR, "year");
GetMetadata(tags, TAG_TRACK, "track");
GetMetadata(tags, TAG_GENRE, "genre");
}
void FFmpegImportFileHandle::GetMetadata(Tags *tags, const wxChar *tag, const char *name)
{
AVDictionaryEntry *meta;
meta = av_dict_get(mFormatContext->metadata, name, NULL, AV_DICT_IGNORE_SUFFIX);
if (meta)
{
tags->SetTag(tag, wxString::FromUTF8(meta->value));
}
}
FFmpegImportFileHandle::~FFmpegImportFileHandle()
{
if (FFmpegLibsInst()->ValidLibsLoaded())
av_log_set_callback(av_log_default_callback);
// Do this before unloading the libraries
mContext.reset();
DropFFmpegLibs();
}
#endif //USE_FFMPEG
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("BTC") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
/* Wallet */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if(model)
{
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Cancel)
return;
disableApplyButton();
/* disable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true;
/* reset all options and save the default values (QSettings) */
model->Reset();
mapper->toFirst();
mapper->submit();
/* re-enable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false;
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Riotoken."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Riotoken."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}
|
// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#pragma once
#ifndef BURGWAR_CORELIB_PLAYERCOMMANDSTORE_HPP
#define BURGWAR_CORELIB_PLAYERCOMMANDSTORE_HPP
#include <CoreLib/CommandStore.hpp>
#include <CoreLib/Export.hpp>
namespace bw
{
class MatchClientSession;
class BURGWAR_CORELIB_API PlayerCommandStore : public CommandStore<MatchClientSession>
{
public:
PlayerCommandStore(const Logger& logger);
~PlayerCommandStore() = default;
};
}
#include <CoreLib/PlayerCommandStore.inl>
#endif
|
/*
* Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#ifndef INCLUDED_LIBRARY_BRIDGE_HPP
#define INCLUDED_LIBRARY_BRIDGE_HPP
#include <cstdint>
#include <boost/assign.hpp>
#include <pkmn/config.hpp>
#include <pkmn/enums.hpp>
#include <pkmn/types/dict.hpp>
#include <pkmn/types/pokemon_text.hpp>
#include <pkmds/pkmds_g5.h>
#include <pkmds/pkmds_g6.h>
namespace pkmn
{
static const pkmn::dict<uint8_t, pokemon_text> ball_dict = boost::assign::map_list_of
(PokeBalls::UNKNOWN, "Poke Ball")
(PokeBalls::POKE_BALL, "Poke Ball")
(PokeBalls::GREAT_BALL, "Great Ball")
(PokeBalls::ULTRA_BALL, "Ultra Ball")
(PokeBalls::MASTER_BALL, "Master Ball")
(PokeBalls::SAFARI_BALL, "Safari Ball")
(PokeBalls::LEVEL_BALL, "Level Ball")
(PokeBalls::LURE_BALL, "Lure Ball")
(PokeBalls::MOON_BALL, "Moon Ball")
(PokeBalls::FRIEND_BALL, "Friend Ball")
(PokeBalls::LOVE_BALL, "Love Ball")
(PokeBalls::HEAVY_BALL, "Heavy Ball")
(PokeBalls::FAST_BALL, "Fast Ball")
(PokeBalls::SPORT_BALL, "Sport Ball")
(PokeBalls::PREMIER_BALL, "Premier Ball")
(PokeBalls::REPEAT_BALL, "Repeat Ball")
(PokeBalls::TIMER_BALL, "Timer Ball")
(PokeBalls::NEST_BALL, "Nest Ball")
(PokeBalls::NET_BALL, "Net Ball")
(PokeBalls::DIVE_BALL, "Dive Ball")
(PokeBalls::LUXURY_BALL, "Luxury Ball")
(PokeBalls::HEAL_BALL, "Heal Ball")
(PokeBalls::QUICK_BALL, "Quick Ball")
(PokeBalls::DUSK_BALL, "Dusk Ball")
(PokeBalls::CHERISH_BALL, "Cherish Ball")
(PokeBalls::PARK_BALL, "Park Ball")
(PokeBalls::DREAM_BALL, "Dream Ball")
;
static const pkmn::dict<pokemon_text, uint8_t> reverse_ball_dict = boost::assign::map_list_of
("None", PokeBalls::POKE_BALL)
("Poke Ball", PokeBalls::POKE_BALL)
("Great Ball", PokeBalls::GREAT_BALL)
("Ultra Ball", PokeBalls::ULTRA_BALL)
("Master Ball", PokeBalls::MASTER_BALL)
("Safari Ball", PokeBalls::SAFARI_BALL)
("Level Ball", PokeBalls::LEVEL_BALL)
("Lure Ball", PokeBalls::LURE_BALL)
("Moon Ball", PokeBalls::MOON_BALL)
("Friend Ball", PokeBalls::FRIEND_BALL)
("Love Ball", PokeBalls::LOVE_BALL)
("Heavy Ball", PokeBalls::HEAVY_BALL)
("Fast Ball", PokeBalls::FAST_BALL)
("Sport Ball", PokeBalls::SPORT_BALL)
("Premier Ball", PokeBalls::PREMIER_BALL)
("Repeat Ball", PokeBalls::REPEAT_BALL)
("Timer Ball", PokeBalls::TIMER_BALL)
("Nest Ball", PokeBalls::NEST_BALL)
("Net Ball", PokeBalls::NET_BALL)
("Dive Ball", PokeBalls::DIVE_BALL)
("Luxury Ball", PokeBalls::LUXURY_BALL)
("Heal Ball", PokeBalls::HEAL_BALL)
("Quick Ball", PokeBalls::QUICK_BALL)
("Dusk Ball", PokeBalls::DUSK_BALL)
("Cherish Ball", PokeBalls::CHERISH_BALL)
("Park Ball", PokeBalls::PARK_BALL)
("Dream Ball", PokeBalls::DREAM_BALL)
;
uint8_t modern_get_IV(uint32_t* IVint, uint8_t IV);
void modern_set_IV(uint32_t* IVint, uint8_t IV, uint8_t val);
bool get_marking(uint8_t* markint, uint8_t mark);
void set_marking(uint8_t* markint, uint8_t mark, bool val);
bool get_ribbon(uint32_t* ribbonint, uint8_t ribbon);
void set_ribbon(uint32_t* ribbonint, uint8_t ribbon, bool val);
uint8_t get_gen3_ball(uint16_t* metlevelint);
void set_gen3_ball(uint16_t* metlevelint, uint8_t ball);
uint8_t get_gen3_met_level(uint16_t* metlevelint);
void set_gen3_met_level(uint16_t* metlevelint, uint8_t level);
uint8_t get_gen_456_met_level(uint8_t* metlevelint);
void set_gen_456_met_level(uint8_t* metlevelint, uint8_t level);
bool get_gen3_otgender(uint16_t* metlevelint);
void set_gen3_otgender(uint16_t* metlevelint, bool is_female);
bool get_gen_456_otgender(uint8_t* metlevelint);
void set_gen_456_otgender(uint8_t* metlevelint, bool is_female);
uint8_t libpkmn_getpkmstat(pokemon_obj* pkm);
void libpkmn_pctoparty(party_pkm* p_pkm, pokemon_obj* pkm);
std::string libpkmn_getpkxformnamesql(pokemonx_obj *pkx);
uint16_t getpkxstat(pokemonx_obj *pkx, unsigned int stat_id);
uint8_t libpkmn_pkxstat(pokemonx_obj* pkx);
void libpkmn_pctopartyx(party_pkx* p_pkx, pokemonx_obj* pkx);
uint8_t libpkmn_game_to_hometown(uint8_t game);
uint8_t hometown_to_libpkmn_game(uint8_t hometown);
uint8_t libpkmn_ball_to_game_ball(uint8_t ball);
uint8_t game_ball_to_libpkmn_ball(uint8_t game_ball);
namespace Hometowns
{
enum hometowns
{
COLOSSEUM_BONUS,
SAPPHIRE,
RUBY,
EMERALD,
FIRERED,
LEAFGREEN,
HEARTGOLD = 7,
SOULSILVER,
DIAMOND = 10,
PEARL,
PLATINUM,
COLOSSEUM_XD = 15,
WHITE = 20,
BLACK,
WHITE_2,
BLACK_2,
X,
Y
};
}
}
#endif /* INCLUDED_LIBRARY_BRIDGE_HPP */
|
//=================================================================================================
/*!
// \file src/mathtest/dmatdmatmin/MDbMHb.cpp
// \brief Source file for the MDbMHb dense matrix/dense matrix minimum math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/HybridMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatmin/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'MDbMHb'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using MDb = blaze::DynamicMatrix<TypeB>;
using MHb = blaze::HybridMatrix<TypeB,128UL,128UL>;
// Creator type definitions
using CMDb = blazetest::Creator<MDb>;
using CMHb = blazetest::Creator<MHb>;
// Running tests with small matrices
for( size_t i=0UL; i<=9UL; ++i ) {
for( size_t j=0UL; j<=9UL; ++j ) {
RUN_DMATDMATMIN_OPERATION_TEST( CMDb( i, j ), CMHb( i, j ) );
}
}
// Running tests with large matrices
RUN_DMATDMATMIN_OPERATION_TEST( CMDb( 67UL, 67UL ), CMHb( 67UL, 67UL ) );
RUN_DMATDMATMIN_OPERATION_TEST( CMDb( 67UL, 127UL ), CMHb( 67UL, 127UL ) );
RUN_DMATDMATMIN_OPERATION_TEST( CMDb( 128UL, 64UL ), CMHb( 128UL, 64UL ) );
RUN_DMATDMATMIN_OPERATION_TEST( CMDb( 128UL, 128UL ), CMHb( 128UL, 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix minimum:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/base/backtrace.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/rds-header.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/ext/asio/ext_async-generator-wait-handle.h"
#include "hphp/runtime/vm/act-rec.h"
#include "hphp/runtime/vm/bytecode.h"
#include "hphp/runtime/vm/func.h"
#include "hphp/runtime/vm/runtime.h"
#include "hphp/runtime/vm/vm-regs.h"
#include "hphp/runtime/vm/jit/tc.h"
#include "hphp/runtime/vm/jit/unique-stubs.h"
#include "hphp/runtime/vm/treadmill.h"
#include "hphp/util/concurrent-scalable-cache.h"
#include "hphp/util/struct-log.h"
#include <folly/small_vector.h>
namespace HPHP {
const StaticString
s_file("file"),
s_line("line"),
s_function("function"),
s_args("args"),
s_class("class"),
s_object("object"),
s_type("type"),
s_include("include"),
s_main("{main}"),
s_metadata("metadata"),
s_86metadata("86metadata"),
s_arrow("->"),
s_double_colon("::");
static c_WaitableWaitHandle* getParentWH(
c_WaitableWaitHandle* wh,
context_idx_t contextIdx,
folly::small_vector<c_WaitableWaitHandle*, 64>& visitedWHs) {
assertx(!wh->isFinished());
auto p = wh->getParentChain().firstInContext(contextIdx);
if (p == nullptr ||
UNLIKELY(std::find(visitedWHs.begin(), visitedWHs.end(), p)
!= visitedWHs.end())) {
// If the parent exists in our backtrace, it means we have detected a
// cycle. We well fall back to savedFP in that case.
return nullptr;
}
visitedWHs.push_back(p);
return p;
}
// walks up the wait handle dependency chain, until it finds activation record
static ActRec* getActRecFromWaitHandle(
c_WaitableWaitHandle* currentWaitHandle,
context_idx_t contextIdx,
Offset* prevPc,
folly::small_vector<c_WaitableWaitHandle*, 64>& visitedWHs) {
while (currentWaitHandle != nullptr) {
assertx(!currentWaitHandle->isFinished());
if (currentWaitHandle->getKind() == c_Awaitable::Kind::AsyncFunction) {
auto resumable = currentWaitHandle->asAsyncFunction()->resumable();
*prevPc = resumable->resumeOffset();
return resumable->actRec();
}
if (currentWaitHandle->getKind() == c_Awaitable::Kind::AsyncGenerator) {
auto resumable = currentWaitHandle->asAsyncGenerator()->resumable();
*prevPc = resumable->resumeOffset();
return resumable->actRec();
}
currentWaitHandle = getParentWH(currentWaitHandle, contextIdx, visitedWHs);
}
*prevPc = 0;
return AsioSession::Get()->getContext(contextIdx)->getSavedFP();
}
static ActRec* getPrevActRec(
const ActRec* fp, Offset* prevPc,
folly::small_vector<c_WaitableWaitHandle*, 64>& visitedWHs) {
c_WaitableWaitHandle* currentWaitHandle = nullptr;
if (fp && fp->func() && fp->resumed()) {
if (fp->func()->isAsyncFunction()) {
currentWaitHandle = frame_afwh(fp);
} else if (fp->func()->isAsyncGenerator()) {
auto const gen = frame_async_generator(fp);
if (gen->isRunning() && !gen->isEagerlyExecuted()) {
currentWaitHandle = gen->getWaitHandle();
}
}
}
if (currentWaitHandle != nullptr) {
if (currentWaitHandle->isFinished()) {
/*
* It's possible in very rare cases (it will return a truncated stack):
* 1) async function which WaitHandle is not referenced by anything
* else finishes
* 2) its return value is an object with destructor
* 3) this destructor gets called as part of destruction of the
* WaitHandleobject, which happens right before FP is adjusted
*/
return nullptr;
}
auto const contextIdx = currentWaitHandle->getContextIdx();
currentWaitHandle = getParentWH(currentWaitHandle, contextIdx, visitedWHs);
return getActRecFromWaitHandle(
currentWaitHandle, contextIdx, prevPc, visitedWHs);
}
return g_context->getPrevVMState(fp, prevPc);
}
// wrapper around getActRecFromWaitHandle, which does some extra validation
static ActRec* getActRecFromWaitHandleWrapper(
c_WaitableWaitHandle* currentWaitHandle, Offset* prevPc,
folly::small_vector<c_WaitableWaitHandle*, 64>& visitedWHs) {
if (currentWaitHandle->isFinished()) {
return nullptr;
}
auto const contextIdx = currentWaitHandle->getContextIdx();
if (contextIdx <= 0) {
return nullptr;
}
return getActRecFromWaitHandle(
currentWaitHandle, contextIdx, prevPc, visitedWHs);
}
Array createBacktrace(const BacktraceArgs& btArgs) {
if (btArgs.isCompact()) {
return createCompactBacktrace()->extract();
}
auto bt = Array::Create();
folly::small_vector<c_WaitableWaitHandle*, 64> visitedWHs;
// If there is a parser frame, put it at the beginning of the backtrace.
if (btArgs.m_parserFrame) {
bt.append(
make_map_array(
s_file, btArgs.m_parserFrame->filename,
s_line, btArgs.m_parserFrame->lineNumber
)
);
}
int depth = 0;
ActRec* fp = nullptr;
Offset pc = 0;
if (btArgs.m_fromWaitHandle) {
fp = getActRecFromWaitHandleWrapper(
btArgs.m_fromWaitHandle, &pc, visitedWHs);
// no frames found, we are done
if (!fp) return bt;
} else {
VMRegAnchor _;
// If there are no VM frames, we're done.
if (!rds::header() || !vmfp()) return bt;
// Get the fp and pc of the top frame (possibly skipping one frame).
if (btArgs.m_skipTop) {
fp = getPrevActRec(vmfp(), &pc, visitedWHs);
// We skipped over the only VM frame, we're done.
if (!fp) return bt;
} else {
fp = vmfp();
auto const unit = fp->func()->unit();
assertx(unit);
pc = unit->offsetOf(vmpc());
}
if (btArgs.m_skipInlined && RuntimeOption::EvalJit) {
while (fp && (jit::TCA)fp->m_savedRip == jit::tc::ustubs().retInlHelper) {
fp = getPrevActRec(fp, &pc, visitedWHs);
}
if (!fp) return bt;
}
}
// Handle the top frame.
if (btArgs.m_withSelf) {
// Builtins don't have a file and line number, so find the first user frame
auto curFp = fp;
auto curPc = pc;
while (curFp && curFp->func()->isBuiltin()) {
curFp = g_context->getPrevVMState(curFp, &curPc);
}
if (curFp) {
auto const unit = curFp->func()->unit();
assertx(unit);
auto const filename = curFp->func()->filename();
ArrayInit frame(btArgs.m_parserFrame ? 4 : 2, ArrayInit::Map{});
frame.set(s_file, Variant{const_cast<StringData*>(filename)});
frame.set(s_line, unit->getLineNumber(curPc));
if (btArgs.m_parserFrame) {
frame.set(s_function, s_include);
frame.set(s_args, Array::Create(btArgs.m_parserFrame->filename));
}
bt.append(frame.toVariant());
depth++;
}
}
// Handle the subsequent VM frames.
Offset prevPc = 0;
for (auto prevFp = getPrevActRec(fp, &prevPc, visitedWHs);
fp != nullptr && (btArgs.m_limit == 0 || depth < btArgs.m_limit);
fp = prevFp, pc = prevPc,
prevFp = getPrevActRec(fp, &prevPc, visitedWHs)) {
// Do not capture frame for HPHP only functions.
if (fp->func()->isNoInjection()) continue;
ArrayInit frame(8, ArrayInit::Map{});
auto const curUnit = fp->func()->unit();
auto const curOp = curUnit->getOp(pc);
auto const isReturning =
curOp == Op::RetC || curOp == Op::RetV || curOp == Op::RetM ||
curOp == Op::CreateCont || curOp == Op::Await ||
fp->localsDecRefd();
// Builtins and generators don't have a file and line number
if (prevFp && !prevFp->func()->isBuiltin()) {
auto const prevUnit = prevFp->func()->unit();
auto prevFile = prevUnit->filepath();
if (prevFp->func()->originalFilename()) {
prevFile = prevFp->func()->originalFilename();
}
assertx(prevFile);
frame.set(s_file, Variant{const_cast<StringData*>(prevFile)});
// In the normal method case, the "saved pc" for line number printing is
// pointing at the cell conversion (Unbox/Pop) instruction, not the call
// itself. For multi-line calls, this instruction is associated with the
// subsequent line which results in an off-by-n. We're subtracting one
// in order to look up the line associated with the FCall/FCallArray
// instruction. Exception handling and the other opcodes (ex. BoxR)
// already do the right thing. The emitter associates object access with
// the subsequent expression and this would be difficult to modify.
auto const opAtPrevPc = prevUnit->getOp(prevPc);
Offset pcAdjust = 0;
if (opAtPrevPc == Op::PopR ||
opAtPrevPc == Op::UnboxR ||
opAtPrevPc == Op::UnboxRNop) {
pcAdjust = 1;
}
frame.set(s_line,
prevFp->func()->unit()->getLineNumber(prevPc - pcAdjust));
}
// Check for include.
String funcname{const_cast<StringData*>(fp->func()->displayName())};
if (fp->func()->isClosureBody()) {
// Strip the file hash from the closure name.
String fullName{const_cast<StringData*>(fp->func()->baseCls()->name())};
funcname = fullName.substr(0, fullName.find(';'));
}
// Check for pseudomain.
if (funcname.empty()) {
if (!prevFp && !btArgs.m_withPseudoMain) continue;
else if (!prevFp) funcname = s_main;
else funcname = s_include;
}
frame.set(s_function, funcname);
if (!funcname.same(s_include)) {
// Closures have an m_this but they aren't in object context.
auto ctx = arGetContextClass(fp);
if (ctx != nullptr && !fp->func()->isClosureBody()) {
frame.set(s_class, Variant{const_cast<StringData*>(ctx->name())});
if (!isReturning && fp->hasThis()) {
if (btArgs.m_withThis) {
frame.set(s_object, Object(fp->getThis()));
}
frame.set(s_type, s_arrow);
} else {
frame.set(s_type, s_double_colon);
}
}
}
bool const mayUseVV = fp->func()->attrs() & AttrMayUseVV;
auto const withNames = btArgs.m_withArgNames;
auto const withValues = btArgs.m_withArgValues;
if ((!btArgs.m_withArgNames && !btArgs.m_withArgValues) ||
!RuntimeOption::EnableArgsInBacktraces) {
// do nothing
} else if (funcname.same(s_include)) {
auto filepath = const_cast<StringData*>(curUnit->filepath());
frame.set(s_args, make_packed_array(filepath));
} else if (isReturning) {
frame.set(s_args, empty_array());
} else {
auto args = Array::Create();
auto const nparams = fp->func()->numNonVariadicParams();
auto const nargs = fp->numArgs();
auto const nformals = std::min<int>(nparams, nargs);
if (UNLIKELY(mayUseVV) &&
UNLIKELY(fp->hasVarEnv() && fp->getVarEnv()->getFP() != fp)) {
// VarEnv is attached to eval or debugger frame, other than the current
// frame. Access locals thru VarEnv.
auto varEnv = fp->getVarEnv();
auto func = fp->func();
for (int i = 0; i < nformals; i++) {
auto const argname = func->localVarName(i);
auto const tv = varEnv->lookup(argname);
auto val = init_null();
if (tv != nullptr) { // the variable hasn't been unset
val = withValues ? tvAsVariant(tv) : "";
}
if (withNames) {
args.set(String(const_cast<StringData*>(argname)), val);
} else {
args.append(val);
}
}
} else {
for (int i = 0; i < nformals; i++) {
Variant val = withValues ? tvAsVariant(frame_local(fp, i)) : "";
if (withNames) {
auto const argname = fp->func()->localVarName(i);
args.set(String(const_cast<StringData*>(argname)), val);
} else {
args.append(val);
}
}
}
// Builtin extra args are not stored in varenv.
if (UNLIKELY(mayUseVV) && nargs > nparams && fp->hasExtraArgs()) {
for (int i = nparams; i < nargs; i++) {
auto arg = fp->getExtraArg(i - nparams);
if (arg->m_type == KindOfUninit) {
args.append(init_null());
} else {
args.append(tvAsVariant(arg));
}
}
}
frame.set(s_args, args);
}
if (btArgs.m_withMetadata && !isReturning) {
if (UNLIKELY(mayUseVV) && UNLIKELY(fp->hasVarEnv())) {
auto tv = fp->getVarEnv()->lookup(s_86metadata.get());
if (tv != nullptr && tv->m_type != KindOfUninit) {
frame.set(s_metadata, tvAsVariant(tv));
}
} else {
auto local = fp->func()->lookupVarId(s_86metadata.get());
if (local != kInvalidId) {
auto tv = frame_local(fp, local);
if (tv->m_type != KindOfUninit) {
frame.set(s_metadata, tvAsVariant(tv));
}
}
}
}
bt.append(frame.toVariant());
depth++;
}
return bt;
}
void addBacktraceToStructLog(const Array& bt, StructuredLogEntry& cols) {
std::set<std::string> strings;
std::vector<folly::StringPiece> files;
std::vector<folly::StringPiece> functions;
std::vector<folly::StringPiece> lines;
auto addString = [&] (std::string&& s) -> folly::StringPiece {
return *strings.insert(std::move(s)).first;
};
auto addVariant = [&] (const Variant& v) -> folly::StringPiece {
if (v.isString()) return v.toCStrRef().slice();
return addString(v.toString().toCppString());
};
for (ArrayIter it(bt.get()); it; ++it) {
Array frame = it.second().toArray();
files.emplace_back(addVariant(frame[s_file]));
if (frame.exists(s_class)) {
functions.emplace_back(
addString(folly::sformat("{}{}{}",
frame[s_class].toString().data(),
frame[s_type].toString().data(),
frame[s_function].toString().data()
)
));
} else {
functions.emplace_back(addVariant(frame[s_function]));
}
lines.emplace_back(addVariant(frame[s_line]));
}
cols.setVec("php_files", files);
cols.setVec("php_functions", functions);
cols.setVec("php_lines", lines);
}
template<class L>
static void walkStack(L func) {
VMRegAnchor _;
folly::small_vector<c_WaitableWaitHandle*, 64> visitedWHs;
ActRec* fp = vmfp();
// If there are no VM frames, we're done.
if (!fp || !rds::header()) return;
// Handle the subsequent VM frames.
Offset prevPc = 0;
for (; fp != nullptr; fp = getPrevActRec(fp, &prevPc, visitedWHs)) {
// Do not capture frame for HPHP only functions.
if (fp->func()->isNoInjection()) continue;
func(fp, prevPc);
}
}
int64_t createBacktraceHash() {
// Settings constants before looping
int64_t hash = 0x9e3779b9;
Unit* prev_unit = nullptr;
walkStack([&] (ActRec* fp, Offset) {
auto const curFunc = fp->func();
auto const curUnit = curFunc->unit();
// Only do a filehash if the file changed. It is very common
// to see sequences of calls within the same file
// File paths are already hashed, and the hash bits are random enough
// That allows us to do a faster combination of hashes using a known
// implementation (boost::hash_combine)
if (prev_unit != curUnit) {
prev_unit = curUnit;
auto filehash = curUnit->filepath()->hash();
hash ^= filehash + 0x9e3779b9 + (hash << 6) + (hash >> 2);
}
// Function names are already hashed, and the hash bits are random enough
// That allows us to do a faster combination of hashes using a known
// implementation (boost::hash_combine)
auto funchash = curFunc->fullName()->hash();
hash ^= funchash + 0x9e3779b9 + (hash << 6) + (hash >> 2);
});
return hash;
}
req::ptr<CompactTrace> createCompactBacktrace() {
auto ret = req::make<CompactTrace>();
walkStack([&] (ActRec* fp, Offset prevPc) { ret->insert(fp, prevPc); });
return ret;
}
namespace {
struct CTKHasher final {
uint64_t hash(const CompactTrace::Key& k) const { return k.m_hash; }
bool equal(const CompactTrace::Key& k1, const CompactTrace::Key& k2) const;
};
struct CacheDeleter final {
void operator()(ArrayData* ad) const {
if (!ad->isUncounted()) return;
Treadmill::enqueue([ad] {
PackedArray::ReleaseUncounted(ad);
});
}
};
using CachedArray = std::shared_ptr<ArrayData>;
using Cache = ConcurrentScalableCache<CompactTrace::Key,CachedArray,CTKHasher>;
Cache s_cache(1024);
bool CTKHasher::equal(
const CompactTrace::Key& k1,
const CompactTrace::Key& k2
) const {
if (k1.m_hash != k2.m_hash || k1.m_frames.size() != k2.m_frames.size()) {
return false;
}
for (int i = 0; i < k1.m_frames.size(); ++i) {
auto& a = k1.m_frames[i];
auto& b = k2.m_frames[i];
if (a.func != b.func || a.prevPcAndHasThis != b.prevPcAndHasThis) {
return false;
}
}
return true;
}
}
IMPLEMENT_RESOURCE_ALLOCATION(CompactTrace)
void CompactTrace::Key::insert(const ActRec* fp, int32_t prevPc) {
auto const funcHash = use_lowptr
? (uintptr_t)fp->func() << 32
: (uintptr_t)fp->func();
m_hash ^= funcHash + 0x9e3779b9 + (m_hash << 6) + (m_hash >> 2);
m_hash ^= prevPc + 0x9e3779b9 + (m_hash << 6) + (m_hash >> 2);
auto const curUnit = fp->func()->unit();
auto const curOp = curUnit->getOp(prevPc);
auto const isReturning =
curOp == Op::RetC || curOp == Op::RetV || curOp == Op::RetM ||
curOp == Op::CreateCont || curOp == Op::Await ||
fp->localsDecRefd();
m_frames.push_back(Frame{
fp->func(),
prevPc,
!isReturning && arGetContextClass(fp) && fp->hasThis()
});
}
Array CompactTrace::Key::extract() const {
PackedArrayInit aInit(m_frames.size(), CheckAllocation{});
for (int idx = 0; idx < m_frames.size(); ++idx) {
auto const prev = idx < m_frames.size() - 1 ? &m_frames[idx + 1] : nullptr;
ArrayInit frame(6, ArrayInit::Map{});
if (prev && !prev->func->isBuiltin()) {
auto const prevUnit = prev->func->unit();
auto prevFile = prevUnit->filepath();
if (prev->func->originalFilename()) {
prevFile = prev->func->originalFilename();
}
auto const prevPc = prev->prevPc;
auto const opAtPrevPc = prevUnit->getOp(prevPc);
Offset pcAdjust = 0;
if (opAtPrevPc == Op::PopR ||
opAtPrevPc == Op::UnboxR ||
opAtPrevPc == Op::UnboxRNop) {
pcAdjust = 1;
}
frame.set(s_file, StrNR(prevFile).asString());
frame.set(s_line, prevUnit->getLineNumber(prevPc - pcAdjust));
}
auto const f = m_frames[idx].func;
// Check for include.
String funcname{const_cast<StringData*>(f->displayName())};
if (f->isClosureBody()) {
// Strip the file hash from the closure name.
String fullName{const_cast<StringData*>(f->baseCls()->name())};
funcname = fullName.substr(0, fullName.find(';'));
}
// Check for pseudomain.
if (funcname.empty()) {
if (!prev) continue;
else funcname = s_include;
}
frame.set(s_function, funcname);
if (!funcname.same(s_include)) {
// Closures have an m_this but they aren't in object context.
auto ctx = m_frames[idx].func->cls();
if (ctx != nullptr && !f->isClosureBody()) {
frame.set(s_class, Variant{const_cast<StringData*>(ctx->name())});
if (m_frames[idx].hasThis) {
frame.set(s_type, s_arrow);
} else {
frame.set(s_type, s_double_colon);
}
}
} else {
auto filepath = const_cast<StringData*>(f->unit()->filepath());
frame.set(s_args, make_packed_array(filepath));
}
aInit.append(frame.toVariant());
}
return aInit.toArray();
}
Array CompactTrace::extract() const {
if (m_key.m_frames.size() == 1) return empty_array();
Cache::ConstAccessor acc;
if (s_cache.find(acc, m_key)) {
return Array(acc.get()->get());
}
auto arr = m_key.extract();
auto ins = CachedArray(
arr.get()->empty()
? staticEmptyArray()
: PackedArray::MakeUncounted(arr.get()),
CacheDeleter()
);
if (!s_cache.insert(m_key, ins)) {
return arr;
}
return Array(ins.get());
}
} // HPHP
|
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
//
// 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 "td/net/HttpConnectionBase.h"
#include "td/net/HttpHeaderCreator.h"
#include "td/utils/common.h"
#include "td/utils/logging.h"
#include "td/utils/misc.h"
#include "td/utils/port/detail/PollableFd.h"
namespace td {
namespace detail {
HttpConnectionBase::HttpConnectionBase(State state, SocketFd fd, SslStream ssl_stream, size_t max_post_size,
size_t max_files, int32 idle_timeout, int32 slow_scheduler_id)
: state_(state)
, fd_(std::move(fd))
, ssl_stream_(std::move(ssl_stream))
, max_post_size_(max_post_size)
, max_files_(max_files)
, idle_timeout_(idle_timeout)
, slow_scheduler_id_(slow_scheduler_id) {
CHECK(state_ != State::Close);
if (ssl_stream_) {
read_source_ >> ssl_stream_.read_byte_flow() >> read_sink_;
write_source_ >> ssl_stream_.write_byte_flow() >> write_sink_;
} else {
read_source_ >> read_sink_;
write_source_ >> write_sink_;
}
peer_address_.init_peer_address(fd_).ignore();
}
void HttpConnectionBase::live_event() {
if (idle_timeout_ != 0) {
set_timeout_in(idle_timeout_);
}
}
void HttpConnectionBase::start_up() {
Scheduler::subscribe(fd_.get_poll_info().extract_pollable_fd(this));
reader_.init(read_sink_.get_output(), max_post_size_, max_files_);
if (state_ == State::Read) {
current_query_ = make_unique<HttpQuery>();
}
live_event();
yield();
}
void HttpConnectionBase::tear_down() {
Scheduler::unsubscribe_before_close(fd_.get_poll_info().get_pollable_fd_ref());
fd_.close();
}
void HttpConnectionBase::write_next_noflush(BufferSlice buffer) {
CHECK(state_ == State::Write);
write_buffer_.append(std::move(buffer));
}
void HttpConnectionBase::write_next(BufferSlice buffer) {
write_next_noflush(std::move(buffer));
loop();
}
void HttpConnectionBase::write_ok() {
CHECK(state_ == State::Write);
current_query_ = make_unique<HttpQuery>();
state_ = State::Read;
live_event();
loop();
}
void HttpConnectionBase::write_error(Status error) {
CHECK(state_ == State::Write);
LOG(WARNING) << "Close HTTP connection: " << error;
state_ = State::Close;
loop();
}
void HttpConnectionBase::timeout_expired() {
LOG(INFO) << "Idle timeout expired";
if (fd_.need_flush_write()) {
on_error(Status::Error("Write timeout expired"));
} else if (state_ == State::Read) {
on_error(Status::Error("Read timeout expired"));
}
stop();
}
void HttpConnectionBase::loop() {
if (ssl_stream_) {
//ssl_stream_.read_byte_flow().set_need_size(0);
ssl_stream_.write_byte_flow().reset_need_size();
}
sync_with_poll(fd_);
if (can_read_local(fd_)) {
LOG(DEBUG) << "Can read from the connection";
auto r = fd_.flush_read();
if (r.is_error()) {
if (!begins_with(r.error().message(), "SSL error {336134278")) { // if error is not yet outputed
LOG(INFO) << "Receive flush_read error: " << r.error();
}
on_error(Status::Error(r.error().public_message()));
return stop();
}
}
read_source_.wakeup();
// TODO: read_next even when state_ == State::Write
bool want_read = false;
bool can_be_slow = slow_scheduler_id_ == -1;
if (state_ == State::Read) {
auto res = reader_.read_next(current_query_.get(), can_be_slow);
if (res.is_error()) {
if (res.error().message() == "SLOW") {
LOG(INFO) << "Slow HTTP connection: migrate to " << slow_scheduler_id_;
CHECK(!can_be_slow);
yield();
migrate(slow_scheduler_id_);
slow_scheduler_id_ = -1;
return;
}
live_event();
state_ = State::Write;
LOG(INFO) << res.error();
HttpHeaderCreator hc;
hc.init_status_line(res.error().code());
hc.set_content_size(0);
write_buffer_.append(hc.finish().ok());
close_after_write_ = true;
on_error(Status::Error(res.error().public_message()));
} else if (res.ok() == 0) {
state_ = State::Write;
LOG(DEBUG) << "Send query to handler";
live_event();
current_query_->peer_address_ = peer_address_;
on_query(std::move(current_query_));
} else {
want_read = true;
}
}
write_source_.wakeup();
if (can_write_local(fd_)) {
LOG(DEBUG) << "Can write to the connection";
auto r = fd_.flush_write();
if (r.is_error()) {
LOG(INFO) << "Receive flush_write error: " << r.error();
on_error(Status::Error(r.error().public_message()));
}
if (close_after_write_ && !fd_.need_flush_write()) {
return stop();
}
}
Status pending_error;
if (fd_.get_poll_info().get_flags_local().has_pending_error()) {
pending_error = fd_.get_pending_error();
}
if (pending_error.is_ok() && write_sink_.status().is_error()) {
pending_error = std::move(write_sink_.status());
}
if (pending_error.is_ok() && read_sink_.status().is_error()) {
pending_error = std::move(read_sink_.status());
}
if (pending_error.is_error()) {
LOG(INFO) << pending_error;
if (!close_after_write_) {
on_error(Status::Error(pending_error.public_message()));
}
state_ = State::Close;
}
if (can_close_local(fd_)) {
LOG(DEBUG) << "Can close the connection";
state_ = State::Close;
}
if (state_ == State::Close) {
LOG_IF(INFO, fd_.need_flush_write()) << "Close nonempty connection";
LOG_IF(INFO, want_read && (!fd_.input_buffer().empty() || current_query_->type_ != HttpQuery::Type::Empty))
<< "Close connection while reading request/response";
return stop();
}
}
void HttpConnectionBase::on_start_migrate(int32 sched_id) {
Scheduler::unsubscribe(fd_.get_poll_info().get_pollable_fd_ref());
}
void HttpConnectionBase::on_finish_migrate() {
Scheduler::subscribe(fd_.get_poll_info().extract_pollable_fd(this));
live_event();
}
} // namespace detail
} // namespace td
|
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/function/cast_rules.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/common/types.hpp"
namespace duckdb {
//! Contains a list of rules for casting
class CastRules {
public:
//! Returns the cost of performing an implicit cost from "from" to "to", or -1 if an implicit cast is not possible
static int64_t ImplicitCast(const LogicalType &from, const LogicalType &to);
};
} // namespace duckdb
|
// Copyright (c) 2007-2015 Hartmut Kaiser
// Copyright (c) 2014 Grant Mercer
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(HPX_PARALLEL_COUNT_JUN_28_2014_0827AM)
#define HPX_PARALLEL_COUNT_JUN_28_2014_0827AM
#include <hpx/parallel/algorithms/count.hpp>
#include <hpx/parallel/segmented_algorithms/count.hpp>
#include <hpx/parallel/container_algorithms/count.hpp>
#endif
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <chain.h>
#include <coins.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <init.h>
#include <keystore.h>
#include <validation.h>
#include <validationinterface.h>
#include <merkleblock.h>
#include <net.h>
#include <policy/policy.h>
#include <policy/rbf.h>
#include <primitives/transaction.h>
#include <rpc/safemode.h>
#include <rpc/server.h>
#include <script/script.h>
#include <script/script_error.h>
#include <script/sign.h>
#include <script/standard.h>
#include <txmempool.h>
#include <uint256.h>
#include <utilstrencodings.h>
#ifdef ENABLE_WALLET
#include <wallet/rpcwallet.h>
#include <wallet/wallet.h>
#endif
#include <future>
#include <stdint.h>
#include <univalue.h>
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
{
// Call into TxToUniv() in bitcoin-common to decode the transaction hex.
//
// Blockchain contextual information (confirmations and blocktime) is not
// available to code in bitcoin-common, so we query them here and push the
// data into the returned UniValue.
TxToUniv(tx, uint256(), entry, true, RPCSerializationFlags());
if (!hashBlock.IsNull()) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
UniValue getrawtransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
throw std::runtime_error(
"getrawtransaction \"txid\" ( verbose \"blockhash\" )\n"
"\nNOTE: By default this function only works for mempool transactions. If the -txindex option is\n"
"enabled, it also works for blockchain transactions. If the block which contains the transaction\n"
"is known, its hash can be provided even for nodes without -txindex. Note that if a blockhash is\n"
"provided, only that block will be searched and if the transaction is in the mempool or other\n"
"blocks, or if this node does not have the given block available, the transaction will not be found.\n"
"DEPRECATED: for now, it also works for transactions with unspent outputs.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
"If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
"3. \"blockhash\" (string, optional) The block in which to look for the transaction\n"
"\nResult (if verbose is not set or set to false):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose is set to true):\n"
"{\n"
" \"in_active_chain\": b, (bool) Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
" \"size\" : n, (numeric) The serialized transaction size\n"
" \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"address\" (string) raccoin address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" true")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" false \"myblockhash\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" true \"myblockhash\"")
);
LOCK(cs_main);
bool in_active_chain = true;
uint256 hash = ParseHashV(request.params[0], "parameter 1");
CBlockIndex* blockindex = nullptr;
if (hash == Params().GenesisBlock().hashMerkleRoot) {
// Special exception for the genesis block coinbase transaction
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved");
}
// Accept either a bool (true) or a num (>=1) to indicate verbose output.
bool fVerbose = false;
if (!request.params[1].isNull()) {
fVerbose = request.params[1].isNum() ? (request.params[1].get_int() != 0) : request.params[1].get_bool();
}
if (!request.params[2].isNull()) {
uint256 blockhash = ParseHashV(request.params[2], "parameter 3");
BlockMap::iterator it = mapBlockIndex.find(blockhash);
if (it == mapBlockIndex.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
}
blockindex = it->second;
in_active_chain = chainActive.Contains(blockindex);
}
CTransactionRef tx;
uint256 hash_block;
if (!GetTransaction(hash, tx, Params().GetConsensus(), hash_block, true, blockindex)) {
std::string errmsg;
if (blockindex) {
if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) {
throw JSONRPCError(RPC_MISC_ERROR, "Block not available");
}
errmsg = "No such transaction found in the provided block";
} else {
errmsg = fTxIndex
? "No such mempool or blockchain transaction"
: "No such mempool transaction. Use -txindex to enable blockchain transaction queries";
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions.");
}
if (!fVerbose) {
return EncodeHexTx(*tx, RPCSerializationFlags());
}
UniValue result(UniValue::VOBJ);
if (blockindex) result.push_back(Pair("in_active_chain", in_active_chain));
TxToJSON(*tx, hash_block, result);
return result;
}
UniValue gettxoutproof(const JSONRPCRequest& request)
{
if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2))
throw std::runtime_error(
"gettxoutproof [\"txid\",...] ( blockhash )\n"
"\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
"\nNOTE: By default this function only works sometimes. This is when there is an\n"
"unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option or\n"
"specify the block in which the transaction is included manually (by blockhash).\n"
"\nArguments:\n"
"1. \"txids\" (string) A json array of txids to filter\n"
" [\n"
" \"txid\" (string) A transaction hash\n"
" ,...\n"
" ]\n"
"2. \"blockhash\" (string, optional) If specified, looks for txid in the block with this hash\n"
"\nResult:\n"
"\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
);
std::set<uint256> setTxids;
uint256 oneTxid;
UniValue txids = request.params[0].get_array();
for (unsigned int idx = 0; idx < txids.size(); idx++) {
const UniValue& txid = txids[idx];
if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid txid ")+txid.get_str());
uint256 hash(uint256S(txid.get_str()));
if (setTxids.count(hash))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ")+txid.get_str());
setTxids.insert(hash);
oneTxid = hash;
}
LOCK(cs_main);
CBlockIndex* pblockindex = nullptr;
uint256 hashBlock;
if (!request.params[1].isNull())
{
hashBlock = uint256S(request.params[1].get_str());
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
pblockindex = mapBlockIndex[hashBlock];
} else {
// Loop through txids and try to find which block they're in. Exit loop once a block is found.
for (const auto& tx : setTxids) {
const Coin& coin = AccessByTxid(*pcoinsTip, tx);
if (!coin.IsSpent()) {
pblockindex = chainActive[coin.nHeight];
break;
}
}
}
if (pblockindex == nullptr)
{
CTransactionRef tx;
if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
pblockindex = mapBlockIndex[hashBlock];
}
CBlock block;
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
unsigned int ntxFound = 0;
for (const auto& tx : block.vtx)
if (setTxids.count(tx->GetHash()))
ntxFound++;
if (ntxFound != setTxids.size())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not all transactions found in specified or retrieved block");
CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
CMerkleBlock mb(block, setTxids);
ssMB << mb;
std::string strHex = HexStr(ssMB.begin(), ssMB.end());
return strHex;
}
UniValue verifytxoutproof(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"verifytxoutproof \"proof\"\n"
"\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
"and throwing an RPC error if the block is not in our best chain\n"
"\nArguments:\n"
"1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
"\nResult:\n"
"[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
);
CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
UniValue res(UniValue::VARR);
std::vector<uint256> vMatch;
std::vector<unsigned int> vIndex;
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
return res;
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
for (const uint256& hash : vMatch)
res.push_back(hash.GetHex());
return res;
}
UniValue createrawtransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 2 || request.params.size() > 4)
throw std::runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime ) ( replaceable )\n"
"\nCreate a transaction spending the given inputs and creating new outputs.\n"
"Outputs can be addresses or data.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"inputs\" (array, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"sequence\":n (numeric, optional) The sequence number\n"
" } \n"
" ,...\n"
" ]\n"
"2. \"outputs\" (object, required) a json object with outputs\n"
" {\n"
" \"address\": x.xxx, (numeric or string, required) The key is the raccoin address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
" \"data\": \"hex\" (string, required) The key is \"data\", the value is hex encoded data\n"
" ,...\n"
" }\n"
"3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
"4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n"
" Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples:\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
);
RPCTypeCheck(request.params, {UniValue::VARR, UniValue::VOBJ, UniValue::VNUM, UniValue::VBOOL}, true);
if (request.params[0].isNull() || request.params[1].isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
UniValue inputs = request.params[0].get_array();
UniValue sendTo = request.params[1].get_obj();
CMutableTransaction rawTx;
if (!request.params[2].isNull()) {
int64_t nLockTime = request.params[2].get_int64();
if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
rawTx.nLockTime = nLockTime;
}
bool rbfOptIn = request.params[3].isTrue();
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
const UniValue& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
uint32_t nSequence;
if (rbfOptIn) {
nSequence = MAX_BIP125_RBF_SEQUENCE;
} else if (rawTx.nLockTime) {
nSequence = std::numeric_limits<uint32_t>::max() - 1;
} else {
nSequence = std::numeric_limits<uint32_t>::max();
}
// set the sequence number if passed in the parameters object
const UniValue& sequenceObj = find_value(o, "sequence");
if (sequenceObj.isNum()) {
int64_t seqNr64 = sequenceObj.get_int64();
if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
} else {
nSequence = (uint32_t)seqNr64;
}
}
CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
rawTx.vin.push_back(in);
}
std::set<CTxDestination> destinations;
std::vector<std::string> addrList = sendTo.getKeys();
for (const std::string& name_ : addrList) {
if (name_ == "data") {
std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
CTxOut out(0, CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
} else {
CTxDestination destination = DecodeDestination(name_);
if (!IsValidDestination(destination)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Raccoin address: ") + name_);
}
if (!destinations.insert(destination).second) {
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);
}
CScript scriptPubKey = GetScriptForDestination(destination);
CAmount nAmount = AmountFromValue(sendTo[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
}
if (!request.params[3].isNull() && rbfOptIn != SignalsOptInRBF(rawTx)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option");
}
return EncodeHexTx(rawTx);
}
UniValue decoderawtransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"decoderawtransaction \"hexstring\" ( iswitness )\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. iswitness (boolean, optional) Whether the transaction hex is a serialized witness transaction\n"
" If iswitness is not present, heuristic tests will be used in decoding\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) raccoin address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decoderawtransaction", "\"hexstring\"")
+ HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
);
LOCK(cs_main);
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});
CMutableTransaction mtx;
bool try_witness = request.params[1].isNull() ? true : request.params[1].get_bool();
bool try_no_witness = request.params[1].isNull() ? true : !request.params[1].get_bool();
if (!DecodeHexTx(mtx, request.params[0].get_str(), try_no_witness, try_witness)) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
UniValue result(UniValue::VOBJ);
TxToUniv(CTransaction(std::move(mtx)), uint256(), result, false);
return result;
}
UniValue decodescript(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"decodescript \"hexstring\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hexstring\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) raccoin address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decodescript", "\"hexstring\"")
+ HelpExampleRpc("decodescript", "\"hexstring\"")
);
RPCTypeCheck(request.params, {UniValue::VSTR});
UniValue r(UniValue::VOBJ);
CScript script;
if (request.params[0].get_str().size() > 0){
std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToUniv(script, r, false);
UniValue type;
type = find_value(r, "type");
if (type.isStr() && type.get_str() != "scripthash") {
// P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
// don't return the address for a P2SH of the P2SH.
r.push_back(Pair("p2sh", EncodeDestination(CScriptID(script))));
}
return r;
}
/** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
UniValue witness(UniValue::VARR);
for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
witness.push_back(HexStr(txin.scriptWitness.stack[i].begin(), txin.scriptWitness.stack[i].end()));
}
entry.push_back(Pair("witness", witness));
entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
entry.push_back(Pair("error", strMessage));
vErrorsRet.push_back(entry);
}
UniValue combinerawtransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"combinerawtransaction [\"hexstring\",...]\n"
"\nCombine multiple partially signed transactions into one transaction.\n"
"The combined transaction may be another partially signed transaction or a \n"
"fully signed transaction."
"\nArguments:\n"
"1. \"txs\" (string) A json array of hex strings of partially signed transactions\n"
" [\n"
" \"hexstring\" (string) A transaction hash\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"\"hex\" (string) The hex-encoded raw transaction with signature(s)\n"
"\nExamples:\n"
+ HelpExampleCli("combinerawtransaction", "[\"myhex1\", \"myhex2\", \"myhex3\"]")
);
UniValue txs = request.params[0].get_array();
std::vector<CMutableTransaction> txVariants(txs.size());
for (unsigned int idx = 0; idx < txs.size(); idx++) {
if (!DecodeHexTx(txVariants[idx], txs[idx].get_str(), true)) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d", idx));
}
}
if (txVariants.empty()) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions");
}
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(cs_main);
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
for (const CTxIn& txin : mergedTx.vin) {
view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
// Use CTransaction for the constant parts of the
// transaction to avoid rehashing.
const CTransaction txConst(mergedTx);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const Coin& coin = view.AccessCoin(txin.prevout);
if (coin.IsSpent()) {
throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent");
}
const CScript& prevPubKey = coin.out.scriptPubKey;
const CAmount& amount = coin.out.nValue;
SignatureData sigdata;
// ... and merge in other signatures:
for (const CMutableTransaction& txv : txVariants) {
if (txv.vin.size() > i) {
sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(txv, i));
}
}
UpdateTransaction(mergedTx, i, sigdata);
}
return EncodeHexTx(mergedTx);
}
UniValue signrawtransaction(const JSONRPCRequest& request)
{
#ifdef ENABLE_WALLET
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
#endif
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw std::runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase(pwallet) + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"
" \"amount\": value (numeric, required) The amount spent\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
" \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
" \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
" {\n"
" \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
" \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
" \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
" \"sequence\" : n, (numeric) Script sequence number\n"
" \"error\" : \"text\" (string) Verification or signing error related to the input\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"")
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
ObserveSafeMode();
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
#else
LOCK(cs_main);
#endif
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true);
CMutableTransaction mtx;
if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
for (const CTxIn& txin : mtx.vin) {
view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (!request.params[2].isNull()) {
fGivenKeys = true;
UniValue keys = request.params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
UniValue k = keys[idx];
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else if (pwallet) {
EnsureWalletIsUnlocked(pwallet);
}
#endif
// Add previous txouts given in the RPC call:
if (!request.params[1].isNull()) {
UniValue prevTxs = request.params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();
RPCTypeCheckObj(prevOut,
{
{"txid", UniValueType(UniValue::VSTR)},
{"vout", UniValueType(UniValue::VNUM)},
{"scriptPubKey", UniValueType(UniValue::VSTR)},
});
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
COutPoint out(txid, nOut);
std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
const Coin& coin = view.AccessCoin(out);
if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
std::string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
Coin newcoin;
newcoin.out.scriptPubKey = scriptPubKey;
newcoin.out.nValue = 0;
if (prevOut.exists("amount")) {
newcoin.out.nValue = AmountFromValue(find_value(prevOut, "amount"));
}
newcoin.nHeight = 1;
view.AddCoin(out, std::move(newcoin), true);
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && (scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash())) {
RPCTypeCheckObj(prevOut,
{
{"txid", UniValueType(UniValue::VSTR)},
{"vout", UniValueType(UniValue::VNUM)},
{"scriptPubKey", UniValueType(UniValue::VSTR)},
{"redeemScript", UniValueType(UniValue::VSTR)},
});
UniValue v = find_value(prevOut, "redeemScript");
if (!v.isNull()) {
std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
// Automatically also add the P2WSH wrapped version of the script (to deal with P2SH-P2WSH).
tempKeystore.AddCScript(GetScriptForWitness(redeemScript));
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwallet) ? tempKeystore : *pwallet);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (!request.params[3].isNull()) {
static std::map<std::string, int> mapSigHashValues = {
{std::string("ALL"), int(SIGHASH_ALL)},
{std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
{std::string("NONE"), int(SIGHASH_NONE)},
{std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
{std::string("SINGLE"), int(SIGHASH_SINGLE)},
{std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
};
std::string strHashType = request.params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Script verification errors
UniValue vErrors(UniValue::VARR);
// Use CTransaction for the constant parts of the
// transaction to avoid rehashing.
const CTransaction txConst(mtx);
// Sign what we can:
for (unsigned int i = 0; i < mtx.vin.size(); i++) {
CTxIn& txin = mtx.vin[i];
const Coin& coin = view.AccessCoin(txin.prevout);
if (coin.IsSpent()) {
TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
continue;
}
const CScript& prevPubKey = coin.out.scriptPubKey;
const CAmount& amount = coin.out.nValue;
SignatureData sigdata;
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mtx.vout.size()))
ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mtx, i, amount, nHashType), prevPubKey, sigdata);
sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(mtx, i));
UpdateTransaction(mtx, i, sigdata);
ScriptError serror = SCRIPT_ERR_OK;
if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {
if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
// Unable to sign input and verification failed (possible attempt to partially sign).
TxInErrorToJSON(txin, vErrors, "Unable to sign input, invalid stack size (possibly missing key)");
} else {
TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
}
}
}
bool fComplete = vErrors.empty();
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(mtx)));
result.push_back(Pair("complete", fComplete));
if (!vErrors.empty()) {
result.push_back(Pair("errors", vErrors));
}
return result;
}
UniValue sendrawtransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n"
+ HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
ObserveSafeMode();
std::promise<void> promise;
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});
// parse hex string from parameter
CMutableTransaction mtx;
if (!DecodeHexTx(mtx, request.params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
const uint256& hashTx = tx->GetHash();
CAmount nMaxRawTxFee = maxTxFee;
if (!request.params[1].isNull() && request.params[1].get_bool())
nMaxRawTxFee = 0;
{ // cs_main scope
LOCK(cs_main);
CCoinsViewCache &view = *pcoinsTip;
bool fHaveChain = false;
for (size_t o = 0; !fHaveChain && o < tx->vout.size(); o++) {
const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
fHaveChain = !existingCoin.IsSpent();
}
bool fHaveMempool = mempool.exists(hashTx);
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
CValidationState state;
bool fMissingInputs;
if (!AcceptToMemoryPool(mempool, state, std::move(tx), &fMissingInputs,
nullptr /* plTxnReplaced */, false /* bypass_limits */, nMaxRawTxFee)) {
if (state.IsInvalid()) {
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
} else {
if (fMissingInputs) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
}
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
} else {
// If wallet is enabled, ensure that the wallet has been made aware
// of the new transaction prior to returning. This prevents a race
// where a user might call sendrawtransaction with a transaction
// to/from their wallet, immediately call some wallet RPC, and get
// a stale result because callbacks have not yet been processed.
CallFunctionInValidationInterfaceQueue([&promise] {
promise.set_value();
});
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
} else {
// Make sure we don't block forever if re-sending
// a transaction already in mempool.
promise.set_value();
}
} // cs_main
promise.get_future().wait();
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
CInv inv(MSG_TX, hashTx);
g_connman->ForEachNode([&inv](CNode* pnode)
{
pnode->PushInventory(inv);
});
return hashTx.GetHex();
}
static const CRPCCommand commands[] =
{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
{ "rawtransactions", "getrawtransaction", &getrawtransaction, {"txid","verbose","blockhash"} },
{ "rawtransactions", "createrawtransaction", &createrawtransaction, {"inputs","outputs","locktime","replaceable"} },
{ "rawtransactions", "decoderawtransaction", &decoderawtransaction, {"hexstring","iswitness"} },
{ "rawtransactions", "decodescript", &decodescript, {"hexstring"} },
{ "rawtransactions", "sendrawtransaction", &sendrawtransaction, {"hexstring","allowhighfees"} },
{ "rawtransactions", "combinerawtransaction", &combinerawtransaction, {"txs"} },
{ "rawtransactions", "signrawtransaction", &signrawtransaction, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
{ "blockchain", "gettxoutproof", &gettxoutproof, {"txids", "blockhash"} },
{ "blockchain", "verifytxoutproof", &verifytxoutproof, {"proof"} },
};
void RegisterRawTransactionRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
|
#pragma once
#ifndef TABLESTORE_CORE_HTTP_RESPONSE_READER_HPP
#define TABLESTORE_CORE_HTTP_RESPONSE_READER_HPP
/*
BSD 3-Clause License
Copyright (c) 2017, Alibaba Cloud
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "types.hpp"
#include "bookmark_input_stream.hpp"
#include "tablestore/core/error.hpp"
#include "tablestore/util/mempiece.hpp"
#include "tablestore/util/optional.hpp"
#include <memory>
#include <deque>
#include <stdint.h>
namespace aliyun {
namespace tablestore {
namespace core {
namespace http {
namespace impl {
class ResponseParserState;
} // namespace impl
class ResponseReader
{
public:
enum RequireMore
{
REQUIRE_MORE,
STOP,
};
explicit ResponseReader(util::Logger&, const Tracker&);
~ResponseReader();
/**
* Feeds and parses another piece of memory.
* If returns true, more pieces are required to complete the response;
* if returns false, the last piece of the response is fed;
* if any error occurs, returns it.
*/
util::Optional<OTSError> feed(RequireMore&, const util::MemPiece&);
std::deque<util::MemPiece>& mutableBody()
{
return mBody;
}
InplaceHeaders& mutableHeaders()
{
return mHeaders;
}
int64_t httpStatus() const
{
return mHttpStatus;
}
int64_t& mutableHttpStatus()
{
return mHttpStatus;
}
private:
util::Optional<OTSError> parse(RequireMore&);
private:
util::Logger& mLogger;
const Tracker& mTracker;
BookmarkInputStream mInputStream;
std::deque<impl::ResponseParserState*> mStates; // own
impl::ResponseParserState* mState; // not own
int64_t mHttpStatus;
InplaceHeaders mHeaders;
std::deque<util::MemPiece> mBody;
};
} // namespace http
} // namespace core
} // namespace tablestore
} // namespace aliyun
#endif
|
//
// Copyright (c) 2017 The Khronos Group 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.
//
#if defined( __APPLE__ )
#include "Sleep.h"
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <IOKit/IOMessage.h>
#include "basic_test_conversions.h"
#define UNUSED __attribute__((unused))
struct
{
io_connect_t connection;
IONotificationPortRef port;
io_object_t iterator;
}sleepInfo;
void sleepCallback( void * refcon,
io_service_t service,
natural_t messageType,
void * messageArgument );
void sleepCallback( void * refcon UNUSED,
io_service_t service UNUSED,
natural_t messageType,
void * messageArgument )
{
IOReturn result;
/*
service -- The IOService whose state has changed.
messageType -- A messageType enum, defined by IOKit/IOMessage.h or by the IOService's family.
messageArgument -- An argument for the message, dependent on the messageType.
*/
switch ( messageType )
{
case kIOMessageSystemWillSleep:
// Handle demand sleep (such as sleep caused by running out of
// batteries, closing the lid of a laptop, or selecting
// sleep from the Apple menu.
IOAllowPowerChange(sleepInfo.connection,(long)messageArgument);
vlog( "Hard sleep occurred.\n" );
break;
case kIOMessageCanSystemSleep:
// In this case, the computer has been idle for several minutes
// and will sleep soon so you must either allow or cancel
// this notification. Important: if you don’t respond, there will
// be a 30-second timeout before the computer sleeps.
// IOCancelPowerChange(root_port,(long)messageArgument);
result = IOCancelPowerChange(sleepInfo.connection,(long)messageArgument);
if( kIOReturnSuccess != result )
vlog( "sleep prevention failed. (%d)\n", result);
break;
case kIOMessageSystemHasPoweredOn:
// Handle wakeup.
break;
}
}
void PreventSleep( void )
{
vlog( "Disabling sleep... " );
sleepInfo.iterator = (io_object_t) 0;
sleepInfo.port = NULL;
sleepInfo.connection = IORegisterForSystemPower
(
&sleepInfo, //void * refcon,
&sleepInfo.port, //IONotificationPortRef * thePortRef,
sleepCallback, //IOServiceInterestCallback callback,
&sleepInfo.iterator //io_object_t * notifier
);
if( (io_connect_t) 0 == sleepInfo.connection )
vlog( "failed.\n" );
else
vlog( "done.\n" );
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(sleepInfo.port),
kCFRunLoopDefaultMode);
}
void ResumeSleep( void )
{
IOReturn result = IODeregisterForSystemPower ( &sleepInfo.iterator );
if( 0 != result )
vlog( "Got error %d restoring sleep \n", result );
else
vlog( "Sleep restored.\n" );
}
#else /* not __APPLE__ */
void PreventSleep( void ) {}
void ResumeSleep( void ) {}
#endif
|
/*****************************************************************************/
/* XDMF */
/* eXtensible Data Model and Format */
/* */
/* Id : XdmfDiff.cpp */
/* */
/* Author: */
/* Kenneth Leiter */
/* kenneth.leiter@arl.army.mil */
/* US Army Research Laboratory */
/* Aberdeen Proving Ground, MD */
/* */
/* Copyright @ 2011 US Army Research Laboratory */
/* All Rights Reserved */
/* See Copyright.txt for details */
/* */
/* This software is distributed WITHOUT ANY WARRANTY; without */
/* even the implied warranty of MERCHANTABILITY or FITNESS */
/* FOR A PARTICULAR PURPOSE. See the above copyright notice */
/* for more information. */
/* */
/*****************************************************************************/
#include <cmath>
#include <iomanip>
#include <iostream>
#include "XdmfArray.hpp"
#include "XdmfArrayType.hpp"
#include "XdmfDiff.hpp"
#include "XdmfError.hpp"
#include "XdmfVisitor.hpp"
//
// local methods
//
namespace {
/**
* @brief Internal class that traverses all items in xdmf hierarchy and
* adds them to mItems.
*/
class XdmfDiffVisitor : public XdmfVisitor {
public:
static shared_ptr<XdmfDiffVisitor>
New()
{
shared_ptr<XdmfDiffVisitor> p(new XdmfDiffVisitor());
return p;
};
~XdmfDiffVisitor()
{
};
void
visit(XdmfItem & item,
const shared_ptr<XdmfBaseVisitor> visitor)
{
mItems.push_back(&item);
item.traverse(visitor);
}
std::vector<XdmfItem *> mItems;
protected:
XdmfDiffVisitor()
{
}
};
template <typename T>
void
diffArrays(XdmfArray * array1,
XdmfArray * array2,
const double absoluteTolerance,
bool & returnValue) {
bool releaseArray1 = false;
if(!array1->isInitialized()) {
array1->read();
releaseArray1 = true;
}
bool releaseArray2 = false;
if(!array2->isInitialized()) {
array2->read();
releaseArray2 = true;
}
const unsigned int size = array1->getSize();
for(unsigned int i=0; i<size; ++i) {
const T array1Value = array1->getValue<T>(i);
const T array2Value = array2->getValue<T>(i);
const T difference =
static_cast<T>(array1Value > array2Value ?
array1Value-array2Value : array2Value-array1Value);
if(difference > absoluteTolerance) {
std::cout << "At Index " << i << " | Expected: "
<< array1Value << " | Got: " << array2Value << std::endl;
returnValue = false;
}
}
if(releaseArray1) {
array1->release();
}
if(releaseArray2) {
array2->release();
}
}
}
shared_ptr<XdmfDiff>
XdmfDiff::New()
{
shared_ptr<XdmfDiff> p(new XdmfDiff());
return p;
}
XdmfDiff::XdmfDiff() :
mAbsoluteTolerance(0.0)
{
}
XdmfDiff::XdmfDiff(const XdmfDiff &diffRef) :
mAbsoluteTolerance(diffRef.mAbsoluteTolerance)
{
}
XdmfDiff::~XdmfDiff()
{
}
bool
XdmfDiff::compare(const shared_ptr<XdmfItem> item1,
const shared_ptr<XdmfItem> item2) const
{
bool returnValue = true;
shared_ptr<XdmfDiffVisitor> diffVisitor1 = XdmfDiffVisitor::New();
shared_ptr<XdmfDiffVisitor> diffVisitor2 = XdmfDiffVisitor::New();
item1->accept(diffVisitor1);
item2->accept(diffVisitor2);
assert(diffVisitor1->mItems.size() == diffVisitor2->mItems.size());
for(std::vector<XdmfItem *>::size_type i=0;
i<diffVisitor1->mItems.size();
++i) {
XdmfItem * item1 = diffVisitor1->mItems[i];
XdmfItem * item2 = diffVisitor2->mItems[i];
// compare item tags
const std::string itemTag1 = item1->getItemTag();
const std::string itemTag2 = item2->getItemTag();
if(itemTag1.compare(itemTag2) != 0) {
std::cout << "Error: Expected " << itemTag1 << " and got " << itemTag2
<< ". The files are not structured the same" << std::endl;
return false;
}
// compare item properties
const std::map<std::string, std::string> itemProperties1 =
item1->getItemProperties();
const std::map<std::string, std::string> itemProperties2 =
item2->getItemProperties();
assert(itemProperties1.size() == itemProperties2.size());
for(std::map<std::string, std::string>::const_iterator iter1 =
itemProperties1.begin();
iter1 != itemProperties1.end();
++iter1) {
const std::string & key = iter1->first;
const std::map<std::string, std::string>::const_iterator iter2 =
itemProperties2.find(key);
if(iter2 == itemProperties2.end()) {
std::cout << "Error: Expected " << key << " and did not find corresponding key "
<< "files are not structured the same" << std::endl;
assert(false);
}
const std::string & value1 = iter1->second;
const std::string & value2 = iter2->second;
if(value1.compare(value2) != 0) {
std::cout << "Error: For: " << itemTag1 << " | Key: " << key
<< "Expected: " << value1 << " | Got: " << value2
<< std::endl;
returnValue = false;
}
}
// compare array values
XdmfArray * array1 = dynamic_cast<XdmfArray *>(item1);
if(array1) {
XdmfArray * array2 = dynamic_cast<XdmfArray *>(item2);
if(array1->getSize() != array2->getSize()) {
std::cout << "Error: For: " << itemTag1
<< " Different number of values stored. Expected: "
<< array1->getSize() << " | Got: " << array2->getSize()
<< std::endl;
returnValue = false;
}
const shared_ptr<const XdmfArrayType> arrayType =
array1->getArrayType();
if(arrayType != array2->getArrayType()) {
std::cout << "Error: For: " << itemTag1
<< " Different type of values stored. Expected: "
<< arrayType->getName() << " | Got: "
<< array2->getArrayType()->getName() << std::endl;
returnValue = false;
}
if(arrayType == XdmfArrayType::Int8()) {
diffArrays<char>(array1,
array2,
mAbsoluteTolerance,
returnValue);
}
else if(arrayType == XdmfArrayType::Int16()) {
diffArrays<short>(array1,
array2,
mAbsoluteTolerance,
returnValue);
}
else if(arrayType == XdmfArrayType::Int32()) {
diffArrays<int>(array1,
array2,
mAbsoluteTolerance,
returnValue);
}
else if(arrayType == XdmfArrayType::Int64()) {
diffArrays<long>(array1,
array2,
mAbsoluteTolerance,
returnValue);
}
else if(arrayType == XdmfArrayType::UInt8()) {
diffArrays<unsigned char>(array1,
array2,
mAbsoluteTolerance,
returnValue);
}
else if(arrayType == XdmfArrayType::UInt16()) {
diffArrays<unsigned short>(array1,
array2,
mAbsoluteTolerance,
returnValue);
}
else if(arrayType == XdmfArrayType::UInt32()) {
diffArrays<unsigned int>(array1,
array2,
mAbsoluteTolerance,
returnValue);
}
else if(arrayType == XdmfArrayType::Float32()) {
diffArrays<float>(array1,
array2,
mAbsoluteTolerance,
returnValue);
}
else if(arrayType == XdmfArrayType::Float64()) {
std::cout << std::setprecision(15);
diffArrays<double>(array1,
array2,
mAbsoluteTolerance,
returnValue);
}
else {
XdmfError::message(XdmfError::FATAL,
"Error: Array Types match, but type is not supported.");
}
}
}
return returnValue;
}
double
XdmfDiff::getAbsoluteTolerance() const
{
return mAbsoluteTolerance;
}
void
XdmfDiff::setAbsoluteTolerance(const double absoluteTolerance)
{
mAbsoluteTolerance = absoluteTolerance;
}
// C Wrappers
XDMFDIFF *
XdmfDiffNew()
{
shared_ptr<XdmfDiff> generatedDiff = XdmfDiff::New();
return (XDMFDIFF *)((void *)(new XdmfDiff(*generatedDiff.get())));
}
int
XdmfDiffCompare(XDMFDIFF * diff, XDMFITEM * item1, XDMFITEM * item2)
{
shared_ptr<XdmfItem> tempItem1 = shared_ptr<XdmfItem>((XdmfItem *)item1, XdmfNullDeleter());
shared_ptr<XdmfItem> tempItem2 = shared_ptr<XdmfItem>((XdmfItem *)item2, XdmfNullDeleter());
return ((XdmfDiff *)diff)->compare(tempItem1, tempItem2);
}
double
XdmfDiffGetAbsoluteTolerance(XDMFDIFF * diff)
{
return ((XdmfDiff *)diff)->getAbsoluteTolerance();
}
void
XdmfDiffSetAbsoluteTolerance(XDMFDIFF * diff, double tolerance)
{
((XdmfDiff *)diff)->setAbsoluteTolerance(tolerance);
}
void
XdmfDiffFree(XDMFDIFF * diff)
{
if (diff != NULL) {
delete ((XdmfDiff *)diff);
diff = NULL;
}
}
|
#include <cstdlib>
#include "Kmer.h"
#include "KmerIntPair.h"
KmerIntPair::KmerIntPair(const Kmer &km, uint32_t val) {
SetKey(km);
SetVal(val);
}
void KmerIntPair::SetVal(const uint32_t val) {
//char val8 = (val > 0xFF) ? 0xFF : (char)val;
//memcpy(&this->v + KmerIntPair::IntOffset, &val8, sizeof(uint8_t));
//this->v[KmerIntPair::IntOffset] = val8;
//this->v[KmerIntPair::IntOffset] = val;
KmerIntPair::cnt = val;
//memcpy(this+KmerIntPair::IntOffset, &val, sizeof(uint32_t));
}
uint32_t KmerIntPair::GetVal() const {
//uint8_t tmp = *reinterpret_cast<const uint8_t*>(this+KmerIntPair::IntOffset);
//2/12/2015, uint8_t to uint32_t
//uint32_t tmp = *reinterpret_cast<const uint32_t*>(this+KmerIntPair::IntOffset);
//return tmp;
//return (uint8_t)this->v[KmerIntPair::IntOffset];
return KmerIntPair::cnt;
}
const Kmer& KmerIntPair::GetKey() const {
return *reinterpret_cast<const Kmer*>(this + KmerIntPair::KmerOffset);
}
void KmerIntPair::SetKey(const Kmer& km) {
memcpy(this, &km, sizeof(Kmer));
}
void SetKmerKey::operator()(KmerIntPair *value, const Kmer& km) {
memcpy(value + KmerIntPair::KmerOffset, &km, sizeof(Kmer));
}
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <list>
// iterator insert(const_iterator position, const value_type& x);
// UNSUPPORTED: libcxx-no-debug-mode
// ADDITIONAL_COMPILE_FLAGS: -D_LIBCPP_DEBUG=1
#include <list>
#include "test_macros.h"
#include "debug_macros.h"
int main(int, char**)
{
std::list<int> v1(3);
std::list<int> v2(3);
int i = 4;
TEST_LIBCPP_ASSERT_FAILURE(v1.insert(v2.begin(), i),
"list::insert(iterator, x) called with an iterator not referring to this list");
return 0;
}
|
#include "HIMultiTrackSelector.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "DataFormats/Common/interface/ValueMap.h"
#include "CondFormats/DataRecord/interface/GBRWrapperRcd.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include <Math/DistFunc.h>
#include <TMath.h>
#include <TFile.h>
namespace {
// not a generic solution (wrong for N negative for instance)
template<int N>
struct PowN {
template<typename T>
static T op(T t) { return PowN<N/2>::op(t)*PowN<(N+1)/2>::op(t);}
};
template<>
struct PowN<0> {
template<typename T>
static T op(T t) { return T(1);}
};
template<>
struct PowN<1> {
template<typename T>
static T op(T t) { return t;}
};
template<>
struct PowN<2> {
template<typename T>
static T op(T t) { return t*t;}
};
template<typename T>
T powN(T t, int n) {
switch(n) {
case 4: return PowN<4>::op(t); // the only one that matters
case 3: return PowN<3>::op(t); // and this
case 8: return PowN<8>::op(t); // used in conversion????
case 2: return PowN<2>::op(t);
case 5: return PowN<5>::op(t);
case 6: return PowN<6>::op(t);
case 7: return PowN<7>::op(t);
case 0: return PowN<0>::op(t);
case 1: return PowN<1>::op(t);
default : return std::pow(t,T(n));
}
}
}
using namespace reco;
HIMultiTrackSelector::HIMultiTrackSelector()
{
useForestFromDB_ = true;
forest_ = nullptr;
}
void HIMultiTrackSelector::ParseForestVars()
{
mvavars_indices.clear();
for (unsigned i=0;i<forestVars_.size();i++)
{
std::string v = forestVars_[i];
int ind = -1;
if (v=="chi2perdofperlayer") ind=chi2perdofperlayer;
if (v=="dxyperdxyerror") ind=dxyperdxyerror;
if (v=="dzperdzerror") ind=dzperdzerror;
if (v=="relpterr") ind=relpterr;
if (v=="lostmidfrac") ind=lostmidfrac;
if (v=="minlost") ind=minlost;
if (v=="nhits") ind=nhits;
if (v=="eta") ind=eta;
if (v=="chi2n_no1dmod") ind=chi2n_no1dmod;
if (v=="chi2n") ind=chi2n ;
if (v=="nlayerslost") ind=nlayerslost ;
if (v=="nlayers3d") ind=nlayers3d ;
if (v=="nlayers") ind=nlayers ;
if (v=="ndof") ind=ndof ;
if (v=="etaerror") ind=etaerror;
if (ind==-1) edm::LogWarning("HIMultiTrackSelector") << "Unknown forest variable "<<v<<". Please make sure it's in the list of supported variables\n";
mvavars_indices.push_back(ind);
}
}
HIMultiTrackSelector::HIMultiTrackSelector( const edm::ParameterSet & cfg ) :
src_( consumes<reco::TrackCollection>( cfg.getParameter<edm::InputTag>( "src" ) ) ),
hSrc_(consumes<TrackingRecHitCollection>( cfg.getParameter<edm::InputTag>( "src" ) ) ),
beamspot_( consumes<reco::BeamSpot>( cfg.getParameter<edm::InputTag>( "beamspot" ) ) ),
useVertices_( cfg.getParameter<bool>( "useVertices" ) ),
useVtxError_( cfg.getParameter<bool>( "useVtxError" ) )
// now get the pset for each selector
{
if (useVertices_) vertices_ = consumes<reco::VertexCollection>(cfg.getParameter<edm::InputTag>( "vertices" ));
applyPixelMergingCuts_ = false;
if(cfg.exists("applyPixelMergingCuts"))
applyPixelMergingCuts_ = cfg.getParameter<bool>("applyPixelMergingCuts");
useAnyMVA_ = false;
forestLabel_ = "MVASelectorIter0";
std::string type = "BDTG";
useForestFromDB_ = true;
dbFileName_ = "";
forest_ = nullptr;
if(cfg.exists("useAnyMVA")) useAnyMVA_ = cfg.getParameter<bool>("useAnyMVA");
if(useAnyMVA_){
if(cfg.exists("mvaType"))type = cfg.getParameter<std::string>("mvaType");
if(cfg.exists("GBRForestLabel"))forestLabel_ = cfg.getParameter<std::string>("GBRForestLabel");
if(cfg.exists("GBRForestVars")) {
forestVars_ = cfg.getParameter<std::vector<std::string> >("GBRForestVars");
ParseForestVars();
}
if(cfg.exists("GBRForestFileName")){
dbFileName_ = cfg.getParameter<std::string>("GBRForestFileName");
useForestFromDB_ = false;
}
mvaType_ = type;
}
std::vector<edm::ParameterSet> trkSelectors( cfg.getParameter<std::vector< edm::ParameterSet> >("trackSelectors") );
qualityToSet_.reserve(trkSelectors.size());
vtxNumber_.reserve(trkSelectors.size());
vertexCut_.reserve(trkSelectors.size());
res_par_.reserve(trkSelectors.size());
chi2n_par_.reserve(trkSelectors.size());
chi2n_no1Dmod_par_.reserve(trkSelectors.size());
d0_par1_.reserve(trkSelectors.size());
dz_par1_.reserve(trkSelectors.size());
d0_par2_.reserve(trkSelectors.size());
dz_par2_.reserve(trkSelectors.size());
applyAdaptedPVCuts_.reserve(trkSelectors.size());
max_d0_.reserve(trkSelectors.size());
max_z0_.reserve(trkSelectors.size());
nSigmaZ_.reserve(trkSelectors.size());
pixel_pTMinCut_.reserve(trkSelectors.size());
pixel_pTMaxCut_.reserve(trkSelectors.size());
min_layers_.reserve(trkSelectors.size());
min_3Dlayers_.reserve(trkSelectors.size());
max_lostLayers_.reserve(trkSelectors.size());
min_hits_bypass_.reserve(trkSelectors.size());
applyAbsCutsIfNoPV_.reserve(trkSelectors.size());
max_d0NoPV_.reserve(trkSelectors.size());
max_z0NoPV_.reserve(trkSelectors.size());
preFilter_.reserve(trkSelectors.size());
max_relpterr_.reserve(trkSelectors.size());
min_nhits_.reserve(trkSelectors.size());
max_minMissHitOutOrIn_.reserve(trkSelectors.size());
max_lostHitFraction_.reserve(trkSelectors.size());
min_eta_.reserve(trkSelectors.size());
max_eta_.reserve(trkSelectors.size());
useMVA_.reserve(trkSelectors.size());
//mvaReaders_.reserve(trkSelectors.size());
min_MVA_.reserve(trkSelectors.size());
//mvaType_.reserve(trkSelectors.size());
produces<edm::ValueMap<float> >("MVAVals");
for ( unsigned int i=0; i<trkSelectors.size(); i++) {
qualityToSet_.push_back( TrackBase::undefQuality );
// parameters for vertex selection
vtxNumber_.push_back( useVertices_ ? trkSelectors[i].getParameter<int32_t>("vtxNumber") : 0 );
vertexCut_.push_back( useVertices_ ? trkSelectors[i].getParameter<std::string>("vertexCut") : nullptr);
// parameters for adapted optimal cuts on chi2 and primary vertex compatibility
res_par_.push_back(trkSelectors[i].getParameter< std::vector<double> >("res_par") );
chi2n_par_.push_back( trkSelectors[i].getParameter<double>("chi2n_par") );
chi2n_no1Dmod_par_.push_back( trkSelectors[i].getParameter<double>("chi2n_no1Dmod_par") );
d0_par1_.push_back(trkSelectors[i].getParameter< std::vector<double> >("d0_par1"));
dz_par1_.push_back(trkSelectors[i].getParameter< std::vector<double> >("dz_par1"));
d0_par2_.push_back(trkSelectors[i].getParameter< std::vector<double> >("d0_par2"));
dz_par2_.push_back(trkSelectors[i].getParameter< std::vector<double> >("dz_par2"));
// Boolean indicating if adapted primary vertex compatibility cuts are to be applied.
applyAdaptedPVCuts_.push_back(trkSelectors[i].getParameter<bool>("applyAdaptedPVCuts"));
// Impact parameter absolute cuts.
max_d0_.push_back(trkSelectors[i].getParameter<double>("max_d0"));
max_z0_.push_back(trkSelectors[i].getParameter<double>("max_z0"));
nSigmaZ_.push_back(trkSelectors[i].getParameter<double>("nSigmaZ"));
// Cuts on numbers of layers with hits/3D hits/lost hits.
min_layers_.push_back(trkSelectors[i].getParameter<uint32_t>("minNumberLayers") );
min_3Dlayers_.push_back(trkSelectors[i].getParameter<uint32_t>("minNumber3DLayers") );
max_lostLayers_.push_back(trkSelectors[i].getParameter<uint32_t>("maxNumberLostLayers"));
min_hits_bypass_.push_back(trkSelectors[i].getParameter<uint32_t>("minHitsToBypassChecks"));
// Flag to apply absolute cuts if no PV passes the selection
applyAbsCutsIfNoPV_.push_back(trkSelectors[i].getParameter<bool>("applyAbsCutsIfNoPV"));
keepAllTracks_.push_back( trkSelectors[i].getParameter<bool>("keepAllTracks"));
max_relpterr_.push_back(trkSelectors[i].getParameter<double>("max_relpterr"));
min_nhits_.push_back(trkSelectors[i].getParameter<uint32_t>("min_nhits"));
max_minMissHitOutOrIn_.push_back(
trkSelectors[i].existsAs<int32_t>("max_minMissHitOutOrIn") ?
trkSelectors[i].getParameter<int32_t>("max_minMissHitOutOrIn") : 99);
max_lostHitFraction_.push_back(
trkSelectors[i].existsAs<double>("max_lostHitFraction") ?
trkSelectors[i].getParameter<double>("max_lostHitFraction") : 1.0);
min_eta_.push_back(trkSelectors[i].existsAs<double>("min_eta") ?
trkSelectors[i].getParameter<double>("min_eta"):-9999);
max_eta_.push_back(trkSelectors[i].existsAs<double>("max_eta") ?
trkSelectors[i].getParameter<double>("max_eta"):9999);
setQualityBit_.push_back( false );
std::string qualityStr = trkSelectors[i].getParameter<std::string>("qualityBit");
if (!qualityStr.empty()) {
setQualityBit_[i] = true;
qualityToSet_[i] = TrackBase::qualityByName(trkSelectors[i].getParameter<std::string>("qualityBit"));
}
if (setQualityBit_[i] && (qualityToSet_[i] == TrackBase::undefQuality)) throw cms::Exception("Configuration") <<
"You can't set the quality bit " << trkSelectors[i].getParameter<std::string>("qualityBit") << " as it is 'undefQuality' or unknown.\n";
if (applyAbsCutsIfNoPV_[i]) {
max_d0NoPV_.push_back(trkSelectors[i].getParameter<double>("max_d0NoPV"));
max_z0NoPV_.push_back(trkSelectors[i].getParameter<double>("max_z0NoPV"));
}
else{//dummy values
max_d0NoPV_.push_back(0.);
max_z0NoPV_.push_back(0.);
}
name_.push_back( trkSelectors[i].getParameter<std::string>("name") );
preFilter_[i]=trkSelectors.size(); // no prefilter
std::string pfName=trkSelectors[i].getParameter<std::string>("preFilterName");
if (!pfName.empty()) {
bool foundPF=false;
for ( unsigned int j=0; j<i; j++)
if (name_[j]==pfName ) {
foundPF=true;
preFilter_[i]=j;
}
if ( !foundPF)
throw cms::Exception("Configuration") << "Invalid prefilter name in HIMultiTrackSelector "
<< trkSelectors[i].getParameter<std::string>("preFilterName");
}
if(applyPixelMergingCuts_)
{
pixel_pTMinCut_.push_back(trkSelectors[i].getParameter< std::vector<double> >("pixel_pTMinCut"));
pixel_pTMaxCut_.push_back(trkSelectors[i].getParameter< std::vector<double> >("pixel_pTMaxCut"));
}
// produces<std::vector<int> >(name_[i]).setBranchAlias( name_[i] + "TrackQuals");
produces<edm::ValueMap<int> >(name_[i]).setBranchAlias( name_[i] + "TrackQuals");
if(useAnyMVA_){
bool thisMVA = false;
if(trkSelectors[i].exists("useMVA"))thisMVA = trkSelectors[i].getParameter<bool>("useMVA");
useMVA_.push_back(thisMVA);
if(thisMVA){
double minVal = -1;
if(trkSelectors[i].exists("minMVA"))minVal = trkSelectors[i].getParameter<double>("minMVA");
min_MVA_.push_back(minVal);
}else{
min_MVA_.push_back(-9999.0);
}
}else{
min_MVA_.push_back(-9999.0);
}
}
}
HIMultiTrackSelector::~HIMultiTrackSelector() {
delete forest_;
}
void HIMultiTrackSelector::beginStream(edm::StreamID) {
if(!useForestFromDB_){
TFile gbrfile(dbFileName_.c_str());
forest_ = (GBRForest*)gbrfile.Get(forestLabel_.c_str());
}
}
void HIMultiTrackSelector::run( edm::Event& evt, const edm::EventSetup& es ) const
{
using namespace std;
using namespace edm;
using namespace reco;
// Get tracks
Handle<TrackCollection> hSrcTrack;
evt.getByToken(src_, hSrcTrack );
const TrackCollection& srcTracks(*hSrcTrack);
// get hits in track..
Handle<TrackingRecHitCollection> hSrcHits;
evt.getByToken(hSrc_, hSrcHits );
const TrackingRecHitCollection & srcHits(*hSrcHits);
// looking for the beam spot
edm::Handle<reco::BeamSpot> hBsp;
evt.getByToken(beamspot_, hBsp);
const reco::BeamSpot& vertexBeamSpot(*hBsp);
// Select good primary vertices for use in subsequent track selection
edm::Handle<reco::VertexCollection> hVtx;
if (useVertices_) evt.getByToken(vertices_, hVtx);
unsigned int trkSize=srcTracks.size();
std::vector<int> selTracksSave( qualityToSet_.size()*trkSize,0);
std::vector<float> mvaVals_(srcTracks.size(),-99.f);
processMVA(evt,es, mvaVals_, *hVtx);
for (unsigned int i=0; i<qualityToSet_.size(); i++) {
std::vector<int> selTracks(trkSize,0);
auto selTracksValueMap = std::make_unique<edm::ValueMap<int>>();
edm::ValueMap<int>::Filler filler(*selTracksValueMap);
std::vector<Point> points;
std::vector<float> vterr, vzerr;
if (useVertices_) selectVertices(i,*hVtx, points, vterr, vzerr);
// Loop over tracks
size_t current = 0;
for (TrackCollection::const_iterator it = srcTracks.begin(), ed = srcTracks.end(); it != ed; ++it, ++current) {
const Track & trk = * it;
// Check if this track passes cuts
LogTrace("TrackSelection") << "ready to check track with pt="<< trk.pt() ;
//already removed
bool ok=true;
float mvaVal = 0;
if (preFilter_[i]<i && selTracksSave[preFilter_[i]*trkSize+current] < 0) {
selTracks[current]=-1;
ok=false;
if ( !keepAllTracks_[i])
continue;
}
else {
if(useAnyMVA_) mvaVal = mvaVals_[current];
ok = select(i,vertexBeamSpot, srcHits, trk, points, vterr, vzerr,mvaVal);
if (!ok) {
LogTrace("TrackSelection") << "track with pt="<< trk.pt() << " NOT selected";
if (!keepAllTracks_[i]) {
selTracks[current]=-1;
continue;
}
}
else
LogTrace("TrackSelection") << "track with pt="<< trk.pt() << " selected";
}
if (preFilter_[i]<i ) {
selTracks[current]=selTracksSave[preFilter_[i]*trkSize+current];
}
else {
selTracks[current]=trk.qualityMask();
}
if ( ok && setQualityBit_[i]) {
selTracks[current]= (selTracks[current] | (1<<qualityToSet_[i]));
if (qualityToSet_[i]==TrackBase::tight) {
selTracks[current]=(selTracks[current] | (1<<TrackBase::loose));
}
else if (qualityToSet_[i]==TrackBase::highPurity) {
selTracks[current]=(selTracks[current] | (1<<TrackBase::loose));
selTracks[current]=(selTracks[current] | (1<<TrackBase::tight));
}
if (!points.empty()) {
if (qualityToSet_[i]==TrackBase::loose) {
selTracks[current]=(selTracks[current] | (1<<TrackBase::looseSetWithPV));
}
else if (qualityToSet_[i]==TrackBase::highPurity) {
selTracks[current]=(selTracks[current] | (1<<TrackBase::looseSetWithPV));
selTracks[current]=(selTracks[current] | (1<<TrackBase::highPuritySetWithPV));
}
}
}
}
for ( unsigned int j=0; j< trkSize; j++ ) selTracksSave[j+i*trkSize]=selTracks[j];
filler.insert(hSrcTrack, selTracks.begin(),selTracks.end());
filler.fill();
// evt.put(std::move(selTracks),name_[i]);
evt.put(std::move(selTracksValueMap),name_[i]);
}
}
bool HIMultiTrackSelector::select(unsigned int tsNum,
const reco::BeamSpot &vertexBeamSpot,
const TrackingRecHitCollection & recHits,
const reco::Track &tk,
const std::vector<Point> &points,
std::vector<float> &vterr,
std::vector<float> &vzerr,
double mvaVal) const {
// Decide if the given track passes selection cuts.
using namespace std;
//cuts on number of valid hits
auto nhits = tk.numberOfValidHits();
if(nhits>=min_hits_bypass_[tsNum]) return true;
if(nhits < min_nhits_[tsNum]) return false;
if ( tk.ndof() < 1E-5 ) return false;
//////////////////////////////////////////////////
//Adding the MVA selection before any other cut//
////////////////////////////////////////////////
if(useAnyMVA_ && useMVA_[tsNum]){
if(mvaVal < min_MVA_[tsNum])return false; else return true;
}
/////////////////////////////////
//End of MVA selection section//
///////////////////////////////
// Cuts on numbers of layers with hits/3D hits/lost hits.
uint32_t nlayers = tk.hitPattern().trackerLayersWithMeasurement();
uint32_t nlayers3D = tk.hitPattern().pixelLayersWithMeasurement() +
tk.hitPattern().numberOfValidStripLayersWithMonoAndStereo();
uint32_t nlayersLost = tk.hitPattern().trackerLayersWithoutMeasurement(reco::HitPattern::TRACK_HITS);
LogDebug("TrackSelection") << "cuts on nlayers: " << nlayers << " " << nlayers3D << " " << nlayersLost << " vs "
<< min_layers_[tsNum] << " " << min_3Dlayers_[tsNum] << " " << max_lostLayers_[tsNum];
if (nlayers < min_layers_[tsNum]) return false;
if (nlayers3D < min_3Dlayers_[tsNum]) return false;
if (nlayersLost > max_lostLayers_[tsNum]) return false;
LogTrace("TrackSelection") << "cuts on nlayers passed";
float chi2n = tk.normalizedChi2();
float chi2n_no1Dmod = chi2n;
int count1dhits = 0;
auto ith = tk.extra()->firstRecHit();
auto edh = ith + tk.recHitsSize();
for (; ith<edh; ++ith) {
const TrackingRecHit & hit = recHits[ith];
if (hit.dimension()==1) ++count1dhits;
}
if (count1dhits > 0) {
float chi2 = tk.chi2();
float ndof = tk.ndof();
chi2n = (chi2+count1dhits)/float(ndof+count1dhits);
}
// For each 1D rechit, the chi^2 and ndof is increased by one. This is a way of retaining approximately
// the same normalized chi^2 distribution as with 2D rechits.
if (chi2n > chi2n_par_[tsNum]*nlayers) return false;
if (chi2n_no1Dmod > chi2n_no1Dmod_par_[tsNum]*nlayers) return false;
// Get track parameters
float pt = std::max(float(tk.pt()),0.000001f);
float eta = tk.eta();
if (eta<min_eta_[tsNum] || eta>max_eta_[tsNum]) return false;
//cuts on relative error on pt
float relpterr = float(tk.ptError())/pt;
if(relpterr > max_relpterr_[tsNum]) return false;
int lostIn = tk.hitPattern().numberOfLostTrackerHits(reco::HitPattern::MISSING_INNER_HITS);
int lostOut = tk.hitPattern().numberOfLostTrackerHits(reco::HitPattern::MISSING_OUTER_HITS);
int minLost = std::min(lostIn,lostOut);
if (minLost > max_minMissHitOutOrIn_[tsNum]) return false;
float lostMidFrac = tk.numberOfLostHits()==0? 0. : tk.numberOfLostHits() / (tk.numberOfValidHits() + tk.numberOfLostHits());
if (lostMidFrac > max_lostHitFraction_[tsNum]) return false;
// Pixel Track Merging pT dependent cuts
if( applyPixelMergingCuts_ )
{
// hard cut at absolute min/max pt
if( pt < pixel_pTMinCut_[tsNum][0] ) return false;
if( pt > pixel_pTMaxCut_[tsNum][0] ) return false;
// tapering cuts with chi2n_no1Dmod
double pTMaxCutPos = ( pixel_pTMaxCut_[tsNum][0] - pt ) /
( pixel_pTMaxCut_[tsNum][0] - pixel_pTMaxCut_[tsNum][1] );
double pTMinCutPos = ( pt - pixel_pTMinCut_[tsNum][0] ) /
( pixel_pTMinCut_[tsNum][1] - pixel_pTMinCut_[tsNum][0] );
if( pt > pixel_pTMaxCut_[tsNum][1] &&
chi2n_no1Dmod > pixel_pTMaxCut_[tsNum][2]*nlayers*pow(pTMaxCutPos,pixel_pTMaxCut_[tsNum][3]) )
return false;
if( pt < pixel_pTMinCut_[tsNum][1] &&
chi2n_no1Dmod > pixel_pTMinCut_[tsNum][2]*nlayers*pow(pTMinCutPos,pixel_pTMinCut_[tsNum][3]) )
return false;
}
//other track parameters
float d0 = -tk.dxy(vertexBeamSpot.position()), d0E = tk.d0Error(),
dz = tk.dz(vertexBeamSpot.position()), dzE = tk.dzError();
// parametrized d0 resolution for the track pt
float nomd0E = sqrt(res_par_[tsNum][0]*res_par_[tsNum][0]+(res_par_[tsNum][1]/pt)*(res_par_[tsNum][1]/pt));
// parametrized z0 resolution for the track pt and eta
float nomdzE = nomd0E*(std::cosh(eta));
float dzCut = std::min( powN(dz_par1_[tsNum][0]*nlayers,int(dz_par1_[tsNum][1]+0.5))*nomdzE,
powN(dz_par2_[tsNum][0]*nlayers,int(dz_par2_[tsNum][1]+0.5))*dzE );
float d0Cut = std::min( powN(d0_par1_[tsNum][0]*nlayers,int(d0_par1_[tsNum][1]+0.5))*nomd0E,
powN(d0_par2_[tsNum][0]*nlayers,int(d0_par2_[tsNum][1]+0.5))*d0E );
// ---- PrimaryVertex compatibility cut
bool primaryVertexZCompatibility(false);
bool primaryVertexD0Compatibility(false);
if (points.empty()) { //If not primaryVertices are reconstructed, check just the compatibility with the BS
//z0 within (n sigma + dzCut) of the beam spot z, if no good vertex is found
if ( abs(dz) < hypot(vertexBeamSpot.sigmaZ()*nSigmaZ_[tsNum],dzCut) ) primaryVertexZCompatibility = true;
// d0 compatibility with beam line
if (abs(d0) < d0Cut) primaryVertexD0Compatibility = true;
}
int iv=0;
for (std::vector<Point>::const_iterator point = points.begin(), end = points.end(); point != end; ++point) {
LogTrace("TrackSelection") << "Test track w.r.t. vertex with z position " << point->z();
if(primaryVertexZCompatibility && primaryVertexD0Compatibility) break;
float dzPV = tk.dz(*point); //re-evaluate the dz with respect to the vertex position
float d0PV = tk.dxy(*point); //re-evaluate the dxy with respect to the vertex position
if(useVtxError_){
float dzErrPV = std::sqrt(dzE*dzE+vzerr[iv]*vzerr[iv]); // include vertex error in z
float d0ErrPV = std::sqrt(d0E*d0E+vterr[iv]*vterr[iv]); // include vertex error in xy
iv++;
if (abs(dzPV) < dz_par1_[tsNum][0]*pow(nlayers,dz_par1_[tsNum][1])*nomdzE &&
abs(dzPV) < dz_par2_[tsNum][0]*pow(nlayers,dz_par2_[tsNum][1])*dzErrPV &&
abs(dzPV) < max_z0_[tsNum]) primaryVertexZCompatibility = true;
if (abs(d0PV) < d0_par1_[tsNum][0]*pow(nlayers,d0_par1_[tsNum][1])*nomd0E &&
abs(d0PV) < d0_par2_[tsNum][0]*pow(nlayers,d0_par2_[tsNum][1])*d0ErrPV &&
abs(d0PV) < max_d0_[tsNum]) primaryVertexD0Compatibility = true;
}else{
if (abs(dzPV) < dzCut) primaryVertexZCompatibility = true;
if (abs(d0PV) < d0Cut) primaryVertexD0Compatibility = true;
}
LogTrace("TrackSelection") << "distances " << dzPV << " " << d0PV << " vs " << dzCut << " " << d0Cut;
}
if (points.empty() && applyAbsCutsIfNoPV_[tsNum]) {
if ( abs(dz) > max_z0NoPV_[tsNum] || abs(d0) > max_d0NoPV_[tsNum]) return false;
} else {
// Absolute cuts on all tracks impact parameters with respect to beam-spot.
// If BS is not compatible, verify if at least the reco-vertex is compatible (useful for incorrect BS settings)
if (abs(d0) > max_d0_[tsNum] && !primaryVertexD0Compatibility) return false;
LogTrace("TrackSelection") << "absolute cuts on d0 passed";
if (abs(dz) > max_z0_[tsNum] && !primaryVertexZCompatibility) return false;
LogTrace("TrackSelection") << "absolute cuts on dz passed";
}
LogTrace("TrackSelection") << "cuts on PV: apply adapted PV cuts? " << applyAdaptedPVCuts_[tsNum]
<< " d0 compatibility? " << primaryVertexD0Compatibility
<< " z compatibility? " << primaryVertexZCompatibility ;
if (applyAdaptedPVCuts_[tsNum]) {
return (primaryVertexD0Compatibility && primaryVertexZCompatibility);
} else {
return true;
}
}
void HIMultiTrackSelector::selectVertices(unsigned int tsNum,
const reco::VertexCollection &vtxs,
std::vector<Point> &points,
std::vector<float> &vterr,
std::vector<float> &vzerr) const {
// Select good primary vertices
using namespace reco;
int32_t toTake = vtxNumber_[tsNum];
for (VertexCollection::const_iterator it = vtxs.begin(), ed = vtxs.end(); it != ed; ++it) {
LogDebug("SelectVertex") << " select vertex with z position " << it->z() << " "
<< it->chi2() << " " << it->ndof() << " " << TMath::Prob(it->chi2(), static_cast<int32_t>(it->ndof()));
Vertex vtx = *it;
bool pass = vertexCut_[tsNum]( vtx );
if( pass ) {
points.push_back(it->position());
vterr.push_back(sqrt(it->yError()*it->xError()));
vzerr.push_back(it->zError());
LogTrace("SelectVertex") << " SELECTED vertex with z position " << it->z();
toTake--; if (toTake == 0) break;
}
}
}
void HIMultiTrackSelector::processMVA(edm::Event& evt, const edm::EventSetup& es, std::vector<float> & mvaVals_,const reco::VertexCollection &vertices ) const
{
using namespace std;
using namespace edm;
using namespace reco;
// Get tracks
Handle<TrackCollection> hSrcTrack;
evt.getByToken( src_, hSrcTrack );
const TrackCollection& srcTracks(*hSrcTrack);
assert(mvaVals_.size()==srcTracks.size());
// get hits in track..
Handle<TrackingRecHitCollection> hSrcHits;
evt.getByToken( hSrc_, hSrcHits );
const TrackingRecHitCollection & srcHits(*hSrcHits);
auto mvaValValueMap = std::make_unique<edm::ValueMap<float>>();
edm::ValueMap<float>::Filler mvaFiller(*mvaValValueMap);
if(!useAnyMVA_){
// mvaVals_ already initalized...
mvaFiller.insert(hSrcTrack,mvaVals_.begin(),mvaVals_.end());
mvaFiller.fill();
evt.put(std::move(mvaValValueMap),"MVAVals");
return;
}
bool checkvertex = std::find(mvavars_indices.begin(), mvavars_indices.end(),dxyperdxyerror)!=mvavars_indices.end()
|| std::find(mvavars_indices.begin(), mvavars_indices.end(),dzperdzerror)!=mvavars_indices.end();
size_t current = 0;
for (TrackCollection::const_iterator it = srcTracks.begin(), ed = srcTracks.end(); it != ed; ++it, ++current) {
const Track & trk = * it;
float mvavalues[15];
mvavalues[ndof] = trk.ndof();
mvavalues[nlayers] = trk.hitPattern().trackerLayersWithMeasurement();
mvavalues[nlayers3d] = trk.hitPattern().pixelLayersWithMeasurement() + trk.hitPattern().numberOfValidStripLayersWithMonoAndStereo();
mvavalues[nlayerslost] = trk.hitPattern().trackerLayersWithoutMeasurement(reco::HitPattern::TRACK_HITS);
mvavalues[chi2n_no1dmod] = trk.normalizedChi2();
mvavalues[chi2perdofperlayer] = mvavalues[chi2n_no1dmod]/mvavalues[nlayers];
float chi2n1d = trk.normalizedChi2();
int count1dhits = 0;
auto ith = trk.extra()->firstRecHit();
auto edh = ith + trk.recHitsSize();
for (; ith<edh; ++ith) {
const TrackingRecHit & hit = srcHits[ith];
if (hit.dimension()==1) ++count1dhits;
}
if (count1dhits > 0) {
float chi2 = trk.chi2();
float ndof = trk.ndof();
chi2n1d = (chi2+count1dhits)/float(ndof+count1dhits);
}
mvavalues[chi2n] = chi2n1d;//chi2 and 1d modes
mvavalues[eta] = trk.eta();
mvavalues[relpterr] = float(trk.ptError())/std::max(float(trk.pt()),0.000001f);
mvavalues[nhits] = trk.numberOfValidHits();
int lostIn = trk.hitPattern().numberOfLostTrackerHits(reco::HitPattern::MISSING_INNER_HITS);
int lostOut = trk.hitPattern().numberOfLostTrackerHits(reco::HitPattern::MISSING_OUTER_HITS);
mvavalues[minlost] = std::min(lostIn,lostOut);
mvavalues[lostmidfrac] = trk.numberOfLostHits() / (trk.numberOfValidHits() + trk.numberOfLostHits());
mvavalues[etaerror] = trk.etaError();
float reldz = 0;
float reldxy = 0;
if (checkvertex) {
int vtxind = 0; // only first vertex is taken into account for the speed purposes
float dxy = trk.dxy(vertices[vtxind].position()), dxyE = sqrt(trk.dxyError()*trk.dxyError()+vertices[vtxind].xError()*vertices[vtxind].yError());
float dz = trk.dz(vertices[vtxind].position()), dzE = sqrt(trk.dzError()*trk.dzError()+vertices[vtxind].zError()*vertices[vtxind].zError());
reldz = dz/dzE;
reldxy = dxy/dxyE;
}
mvavalues[dxyperdxyerror] = reldxy;
mvavalues[dzperdzerror] = reldz;
std::vector<float> gbrValues;
//fill in the gbrValues vector with the necessary variables
for (unsigned i=0;i<mvavars_indices.size();i++) {
gbrValues.push_back(mvavalues[mvavars_indices[i]]);
}
GBRForest const * forest = forest_;
if(useForestFromDB_){
edm::ESHandle<GBRForest> forestHandle;
es.get<GBRWrapperRcd>().get(forestLabel_,forestHandle);
forest = forestHandle.product();
}
auto gbrVal = forest->GetClassifier(&gbrValues[0]);
mvaVals_[current] = gbrVal;
}
mvaFiller.insert(hSrcTrack,mvaVals_.begin(),mvaVals_.end());
mvaFiller.fill();
evt.put(std::move(mvaValValueMap),"MVAVals");
}
#include "FWCore/PluginManager/interface/ModuleDef.h"
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(HIMultiTrackSelector);
|
#include "StatementParser.hpp"
#include <utility>
std::shared_ptr<statements::Statement> parsers::StatementParser::parse(std::string statement)
{
if (this->next_ != nullptr)
{
return this->next_->parse(std::move(statement));
}
return nullptr;
}
void parsers::StatementParser::set_next(std::shared_ptr<StatementParser> statement_parser)
{
this->next_ = std::move(statement_parser);
}
|
//
// Copyright (c) YugaByte, 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 "yb/yql/cql/cqlserver/cql_rpc.h"
#include "yb/yql/cql/cqlserver/cql_message.h"
#include "yb/yql/cql/cqlserver/cql_service.h"
#include "yb/yql/cql/cqlserver/cql_statement.h"
#include "yb/rpc/connection.h"
#include "yb/rpc/messenger.h"
#include "yb/rpc/reactor.h"
#include "yb/rpc/rpc_introspection.pb.h"
#include "yb/util/debug/trace_event.h"
#include "yb/util/size_literals.h"
using yb::cqlserver::CQLMessage;
using namespace std::literals; // NOLINT
using namespace std::placeholders;
using yb::operator"" _KB;
using yb::operator"" _MB;
DECLARE_bool(rpc_dump_all_traces);
DECLARE_int32(rpc_slow_query_threshold_ms);
DEFINE_int32(rpcz_max_cql_query_dump_size, 4_KB,
"The maximum size of the CQL query string in the RPCZ dump.");
DEFINE_int32(rpcz_max_cql_batch_dump_count, 4_KB,
"The maximum number of CQL batch elements in the RPCZ dump.");
DECLARE_int32(rpc_max_message_size);
// Max msg length for CQL.
// Since yb_rpc limit is 255MB, we limit consensensus size to 254MB,
// and hence max cql message length to 253MB
// This length corresponds to 3 strings with size of 64MB along with any additional fields
// and overheads
DEFINE_int32(max_message_length, 254_MB,
"The maximum message length of the cql message.");
namespace yb {
namespace cqlserver {
CQLConnectionContext::CQLConnectionContext(
rpc::GrowableBufferAllocator* allocator,
const MemTrackerPtr& call_tracker)
: ConnectionContextWithCallId(allocator),
ql_session_(new ql::QLSession()),
parser_(CQLMessage::kMessageHeaderLength, CQLMessage::kHeaderPosLength,
FLAGS_max_message_length, rpc::IncludeHeader::kTrue, this),
call_tracker_(call_tracker) {
}
Result<size_t> CQLConnectionContext::ProcessCalls(const rpc::ConnectionPtr& connection,
const IoVecs& data,
rpc::ReadBufferFull read_buffer_full) {
return parser_.Parse(connection, data);
}
size_t CQLConnectionContext::BufferLimit() {
return FLAGS_max_message_length;
}
Status CQLConnectionContext::HandleCall(
const rpc::ConnectionPtr& connection, std::vector<char>* call_data) {
auto reactor = connection->reactor();
DCHECK(reactor->IsCurrentThread());
auto call = rpc::InboundCall::Create<CQLInboundCall>(
connection, call_processed_listener(), ql_session_);
Status s = call->ParseFrom(call_tracker_, call_data);
if (!s.ok()) {
LOG(WARNING) << connection->ToString() << ": received bad data: " << s.ToString();
return STATUS_SUBSTITUTE(NetworkError, "Bad data: $0", s.ToUserMessage());
}
s = Store(call.get());
if (!s.ok()) {
return s;
}
reactor->messenger()->QueueInboundCall(call);
return Status::OK();
}
uint64_t CQLConnectionContext::ExtractCallId(rpc::InboundCall* call) {
return down_cast<CQLInboundCall*>(call)->stream_id();
}
void CQLConnectionContext::DumpPB(const rpc::DumpRunningRpcsRequestPB& req,
rpc::RpcConnectionPB* resp) {
const string keyspace = ql_session_->current_keyspace();
if (!keyspace.empty()) {
resp->mutable_connection_details()->mutable_cql_connection_details()->set_keyspace(keyspace);
}
ConnectionContextWithCallId::DumpPB(req, resp);
}
CQLInboundCall::CQLInboundCall(rpc::ConnectionPtr conn,
CallProcessedListener call_processed_listener,
ql::QLSession::SharedPtr ql_session)
: InboundCall(std::move(conn), std::move(call_processed_listener)),
ql_session_(std::move(ql_session)) {
}
Status CQLInboundCall::ParseFrom(const MemTrackerPtr& call_tracker, std::vector<char>* call_data) {
TRACE_EVENT_FLOW_BEGIN0("rpc", "CQLInboundCall", this);
TRACE_EVENT0("rpc", "CQLInboundCall::ParseFrom");
consumption_ = ScopedTrackedConsumption(call_tracker, call_data->size());
// Parsing of CQL message is deferred to CQLServiceImpl::Handle. Just save the serialized data.
request_data_.swap(*call_data);
serialized_request_ = Slice(request_data_.data(), request_data_.size());
// Fill the service name method name to transfer the call to. The method name is for debug
// tracing only. Inside CQLServiceImpl::Handle, we rely on the opcode to dispatch the execution.
stream_id_ = cqlserver::CQLRequest::ParseStreamId(serialized_request_);
return Status::OK();
}
const std::string& CQLInboundCall::service_name() const {
static std::string result = "yb.cqlserver.CQLServerService"s;
return result;
}
const std::string& CQLInboundCall::method_name() const {
static std::string result = "ExecuteRequest"s;
return result;
}
void CQLInboundCall::Serialize(boost::container::small_vector_base<RefCntBuffer>* output) const {
TRACE_EVENT0("rpc", "CQLInboundCall::Serialize");
CHECK_GT(response_msg_buf_.size(), 0);
output->push_back(response_msg_buf_);
}
void CQLInboundCall::RespondFailure(rpc::ErrorStatusPB::RpcErrorCodePB error_code,
const Status& status) {
const auto& context = static_cast<const CQLConnectionContext&>(connection()->context());
const auto compression_scheme = context.compression_scheme();
faststring msg;
switch (error_code) {
case rpc::ErrorStatusPB::ERROR_SERVER_TOO_BUSY: {
// Return OVERLOADED error to redirect CQL client to the next host.
ErrorResponse(stream_id_, ErrorResponse::Code::OVERLOADED, "CQL service queue full")
.Serialize(compression_scheme, &msg);
break;
}
case rpc::ErrorStatusPB::ERROR_APPLICATION: FALLTHROUGH_INTENDED;
case rpc::ErrorStatusPB::ERROR_NO_SUCH_METHOD: FALLTHROUGH_INTENDED;
case rpc::ErrorStatusPB::ERROR_NO_SUCH_SERVICE: FALLTHROUGH_INTENDED;
case rpc::ErrorStatusPB::ERROR_INVALID_REQUEST: FALLTHROUGH_INTENDED;
case rpc::ErrorStatusPB::FATAL_SERVER_SHUTTING_DOWN: FALLTHROUGH_INTENDED;
case rpc::ErrorStatusPB::FATAL_DESERIALIZING_REQUEST: FALLTHROUGH_INTENDED;
case rpc::ErrorStatusPB::FATAL_VERSION_MISMATCH: FALLTHROUGH_INTENDED;
case rpc::ErrorStatusPB::FATAL_UNAUTHORIZED: FALLTHROUGH_INTENDED;
case rpc::ErrorStatusPB::FATAL_UNKNOWN: {
LOG(ERROR) << "Unexpected error status: "
<< rpc::ErrorStatusPB::RpcErrorCodePB_Name(error_code);
ErrorResponse(stream_id_, ErrorResponse::Code::SERVER_ERROR, "Server error")
.Serialize(compression_scheme, &msg);
break;
}
}
response_msg_buf_ = RefCntBuffer(msg);
QueueResponse(/* is_success */ false);
}
void CQLInboundCall::RespondSuccess(const RefCntBuffer& buffer,
const yb::rpc::RpcMethodMetrics& metrics) {
RecordHandlingCompleted(metrics.handler_latency);
response_msg_buf_ = buffer;
QueueResponse(/* is_success */ true);
}
void CQLInboundCall::GetCallDetails(rpc::RpcCallInProgressPB *call_in_progress_pb) {
std::shared_ptr<const CQLRequest> request =
#ifdef THREAD_SANITIZER
request_;
#else
std::atomic_load_explicit(&request_, std::memory_order_acquire);
#endif
if (request == nullptr) {
return;
}
rpc::CQLCallDetailsPB* call_in_progress = call_in_progress_pb->mutable_cql_details();
rpc::CQLStatementsDetailsPB* details_pb;
std::shared_ptr<const CQLStatement> statement_ptr;
string query_id;
int j = 0;
switch (request->opcode()) {
case CQLMessage::Opcode::PREPARE:
call_in_progress->set_type("PREPARE");
details_pb = call_in_progress->add_call_details();
details_pb->set_sql_string((static_cast<const PrepareRequest&>(*request)).query()
.substr(0, FLAGS_rpcz_max_cql_query_dump_size));
return;
case CQLMessage::Opcode::EXECUTE:
call_in_progress->set_type("EXECUTE");
details_pb = call_in_progress->add_call_details();
query_id = (static_cast<const ExecuteRequest&>(*request)).query_id();
details_pb->set_sql_id(b2a_hex(query_id));
statement_ptr = service_impl_->GetPreparedStatement(query_id);
if (statement_ptr != nullptr) {
details_pb->set_sql_string(statement_ptr->text()
.substr(0, FLAGS_rpcz_max_cql_query_dump_size));
}
return;
case CQLMessage::Opcode::QUERY:
call_in_progress->set_type("QUERY");
details_pb = call_in_progress->add_call_details();
details_pb->set_sql_string((static_cast<const QueryRequest&>(*request)).query()
.substr(0, FLAGS_rpcz_max_cql_query_dump_size));
return;
case CQLMessage::Opcode::BATCH:
call_in_progress->set_type("BATCH");
for (const BatchRequest::Query& batchQuery :
(static_cast<const BatchRequest&>(*request)).queries()) {
details_pb = call_in_progress->add_call_details();
if (batchQuery.is_prepared) {
details_pb->set_sql_id(b2a_hex(batchQuery.query_id));
statement_ptr = service_impl_->GetPreparedStatement(batchQuery.query_id);
if (statement_ptr != nullptr) {
if (statement_ptr->text().size() > FLAGS_rpcz_max_cql_query_dump_size) {
string short_text = statement_ptr->text()
.substr(0, FLAGS_rpcz_max_cql_query_dump_size);
details_pb->set_sql_string(short_text);
} else {
details_pb->set_sql_string(statement_ptr->text());
}
}
} else {
details_pb->set_sql_string(batchQuery.query
.substr(0, FLAGS_rpcz_max_cql_query_dump_size));
}
if (++j >= FLAGS_rpcz_max_cql_batch_dump_count) {
// Showing only rpcz_max_cql_batch_dump_count queries
break;
}
}
return;
default:
return;
}
}
void CQLInboundCall::LogTrace() const {
MonoTime now = MonoTime::Now();
int total_time = now.GetDeltaSince(timing_.time_received).ToMilliseconds();
if (PREDICT_FALSE(FLAGS_rpc_dump_all_traces || total_time > FLAGS_rpc_slow_query_threshold_ms)) {
LOG(INFO) << ToString() << " took " << total_time << "ms. Trace:";
trace_->Dump(&LOG(INFO), true);
}
}
std::string CQLInboundCall::ToString() const {
return Format("CQL Call from $0", connection()->remote());
}
bool CQLInboundCall::DumpPB(const rpc::DumpRunningRpcsRequestPB& req,
rpc::RpcCallInProgressPB* resp) {
if (req.include_traces() && trace_) {
resp->set_trace_buffer(trace_->DumpToString(true));
}
resp->set_micros_elapsed(
MonoTime::Now().GetDeltaSince(timing_.time_received).ToMicroseconds());
GetCallDetails(resp);
return true;
}
MonoTime CQLInboundCall::GetClientDeadline() const {
// TODO(Robert) - fill in CQL timeout
return MonoTime::Max();
}
} // namespace cqlserver
} // namespace yb
|
#include "sdf_data.hpp"
#include "sdf_escape.hpp"
#include <iostream>
#include <cmath>
namespace /*anonymous*/ {
std::string ident(int depth);
std::string ident(int depth) {
return std::string(2*depth, ' ');
}
}
namespace sdfparse {
void DelayFile::print(std::ostream& os, int depth) const {
os << ident(depth) << "(DELAYFILE\n";
header().print(os, depth+1);
for(auto& cell : cells()) {
cell.print(os, depth+1);
}
os << ident(depth) << ")\n";
}
void Header::print(std::ostream& os, int depth) const {
os << ident(depth) << "(SDFVERSION \"" << sdfversion() << "\")\n";
os << ident(depth) << "(DESIGN \"" << design() << "\")\n";
os << ident(depth) << "(VENDOR \"" << vendor() << "\")\n";
os << ident(depth) << "(PROGRAM \"" << program() << "\")\n";
os << ident(depth) << "(VERSION \"" << version() << "\")\n";
os << ident(depth) << "(DIVIDER " << divider() << ")\n";
timescale().print(os, depth);
}
void Timescale::print(std::ostream& os, int depth) const {
os << ident(depth) << "(TIMESCALE " << value() << " " << unit() << ")\n";
}
void Cell::print(std::ostream& os, int depth) const {
os << ident(depth) << "(CELL\n";
os << ident(depth+1) << "(CELLTYPE \"" << escape_sdf_identifier(celltype()) << "\")\n";
os << ident(depth+1) << "(INSTANCE " << escape_sdf_identifier(instance()) << ")\n";
delay().print(os, depth+1);
timing_check().print(os, depth+1);
os << ident(depth) << ")\n";
}
void Delay::print(std::ostream& os, int depth) const {
if(!iopaths_.empty()) {
os << ident(depth) << "(DELAY\n";
os << ident(depth+1) << "(" << type() << "\n";
for(auto& iopath : iopaths()) {
iopath.print(os, depth+2);
}
os << ident(depth+1) << ")\n";
os << ident(depth) << ")\n";
}
}
void Timing::print(std::ostream& os, int depth) const {
os << ident(depth) << type() << port() << " " << clock() << " " << t() << ")\n";
}
void TimingCheck::print(std::ostream& os, int depth) const {
if(!timing().empty()) {
os << ident(depth) << "(TIMINGCHECK\n";
for(auto& timing_check : timing()) {
timing_check.print(os, depth+1);
}
os << ident(depth) << ")\n";
}
}
std::ostream& operator<<(std::ostream& os, const Delay::Type& type) {
if(type == Delay::Type::ABSOLUTE) {
os << "ABSOLUTE";
} else {
assert(false);
}
return os;
}
void Iopath::print(std::ostream& os, int depth) const {
os << ident(depth) << "(IOPATH " << input() << " " << output() << " " << rise() << " " << fall() << ")\n";
}
std::ostream& operator<<(std::ostream& os, const RealTriple& val) {
if(std::isnan(val.min()) && std::isnan(val.typ()) && std::isnan(val.max())) {
os << "()";
} else {
os << "(" << val.min() << ":" << val.typ() << ":" << val.max() << ")";
}
return os;
}
bool operator==(const RealTriple& lhs, const RealTriple& rhs) {
return lhs.min() == rhs.min() && lhs.typ() == rhs.typ() && lhs.max() == rhs.max();
}
std::ostream& operator<<(std::ostream& os, const PortSpec& port_spec) {
if(port_spec.condition() != PortCondition::NONE) {
os << "(" << port_spec.condition() << " ";
}
os << escape_sdf_identifier(port_spec.port(), EscapeStyle::EXCLUDE_LAST_INDEX);
if(port_spec.condition() != PortCondition::NONE) {
os << ")";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const PortCondition& val) {
if(val == PortCondition::POSEDGE) os << "posedge";
else if (val == PortCondition::NEGEDGE) os << "negedge";
else if (val == PortCondition::NONE) os << "none";
else assert(false);
return os;
}
} //sdfparse
|
//=================================================================================================
/*!
// \file src/boost/DMatTrans.cpp
// \brief Source file for the Boost dense matrix transpose kernel
//
// Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <iostream>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <blaze/util/Timing.h>
#include <blazemark/boost/DMatTrans.h>
#include <blazemark/boost/init/Matrix.h>
#include <blazemark/system/Config.h>
namespace blazemark {
namespace boost {
//=================================================================================================
//
// KERNEL FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Boost uBLAS dense matrix transpose kernel.
//
// \param N The number of rows and columns of the matrix.
// \param steps The number of iteration steps to perform.
// \return Minimum runtime of the kernel function.
//
// This kernel function implements the dense matrix transpose by means of the Boost uBLAS
// functionality.
*/
double dmattrans( size_t N, size_t steps )
{
using ::blazemark::element_t;
using ::boost::numeric::ublas::row_major;
::blaze::setSeed( seed );
::boost::numeric::ublas::matrix<element_t,row_major> A( N, N ), B( N, N );
::blaze::timing::WcTimer timer;
init( A );
noalias( B ) = trans( A );
for( size_t rep=0UL; rep<reps; ++rep )
{
timer.start();
for( size_t step=0UL; step<steps; ++step ) {
noalias( B ) = trans( A );
}
timer.end();
if( B.size1() != N )
std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n";
if( timer.last() > maxtime )
break;
}
const double minTime( timer.min() );
const double avgTime( timer.average() );
if( minTime * ( 1.0 + deviation*0.01 ) < avgTime )
std::cerr << " Boost uBLAS kernel 'dmattrans': Time deviation too large!!!\n";
return minTime;
}
//*************************************************************************************************
} // namespace boost
} // namespace blazemark
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/services/libassistant/service_controller.h"
#include <memory>
#include "base/base_paths.h"
#include "base/json/json_reader.h"
#include "base/run_loop.h"
#include "base/test/gtest_util.h"
#include "base/test/scoped_path_override.h"
#include "base/test/task_environment.h"
#include "chromeos/assistant/internal/libassistant/shared_headers.h"
#include "chromeos/assistant/internal/test_support/fake_assistant_manager.h"
#include "chromeos/assistant/internal/test_support/fake_assistant_manager_internal.h"
#include "chromeos/services/libassistant/grpc/assistant_client_observer.h"
#include "chromeos/services/libassistant/public/mojom/service_controller.mojom.h"
#include "chromeos/services/libassistant/public/mojom/settings_controller.mojom.h"
#include "chromeos/services/libassistant/settings_controller.h"
#include "chromeos/services/libassistant/test_support/fake_libassistant_factory.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace libassistant {
namespace {
using mojom::ServiceState;
using ::testing::StrictMock;
#define EXPECT_NO_CALLS(args...) EXPECT_CALL(args).Times(0)
// Tests if the JSON string contains the given path with the given value
#define EXPECT_HAS_PATH_WITH_VALUE(config_string, path, expected_value) \
({ \
absl::optional<base::Value> config = \
base::JSONReader::Read(config_string); \
ASSERT_TRUE(config.has_value()); \
const base::Value* actual = config->FindPath(path); \
base::Value expected = base::Value(expected_value); \
ASSERT_NE(actual, nullptr) \
<< "Path '" << path << "' not found in config: " << config_string; \
EXPECT_EQ(*actual, expected); \
})
std::vector<mojom::AuthenticationTokenPtr> ToVector(
mojom::AuthenticationTokenPtr token) {
std::vector<mojom::AuthenticationTokenPtr> result;
result.push_back(std::move(token));
return result;
}
class StateObserverMock : public mojom::StateObserver {
public:
StateObserverMock() : receiver_(this) {}
MOCK_METHOD(void, OnStateChanged, (ServiceState));
mojo::PendingRemote<mojom::StateObserver> BindAndPassReceiver() {
return receiver_.BindNewPipeAndPassRemote();
}
private:
mojo::Receiver<mojom::StateObserver> receiver_;
};
class AssistantClientObserverMock : public AssistantClientObserver {
public:
AssistantClientObserverMock() = default;
AssistantClientObserverMock(const AssistantClientObserverMock&) = delete;
AssistantClientObserverMock& operator=(const AssistantClientObserverMock&) =
delete;
~AssistantClientObserverMock() override = default;
// AssistantClientObserver implementation:
MOCK_METHOD(void,
OnAssistantClientCreated,
(AssistantClient * assistant_client));
MOCK_METHOD(void,
OnAssistantClientStarted,
(AssistantClient * assistant_client));
MOCK_METHOD(void,
OnAssistantClientRunning,
(AssistantClient * assistant_client));
MOCK_METHOD(void,
OnDestroyingAssistantClient,
(AssistantClient * assistant_client));
MOCK_METHOD(void, OnAssistantClientDestroyed, ());
};
class SettingsControllerMock : public mojom::SettingsController {
public:
SettingsControllerMock() = default;
SettingsControllerMock(const SettingsControllerMock&) = delete;
SettingsControllerMock& operator=(const SettingsControllerMock&) = delete;
~SettingsControllerMock() override = default;
// mojom::SettingsController implementation:
MOCK_METHOD(void,
SetAuthenticationTokens,
(std::vector<mojom::AuthenticationTokenPtr> tokens));
MOCK_METHOD(void, SetListeningEnabled, (bool value));
MOCK_METHOD(void, SetLocale, (const std::string& value));
MOCK_METHOD(void, SetSpokenFeedbackEnabled, (bool value));
MOCK_METHOD(void, SetDarkModeEnabled, (bool value));
MOCK_METHOD(void, SetHotwordEnabled, (bool value));
MOCK_METHOD(void,
GetSettings,
(const std::string& selector,
bool include_header,
GetSettingsCallback callback));
MOCK_METHOD(void,
UpdateSettings,
(const std::string& settings, UpdateSettingsCallback callback));
};
class MediaManagerMock : public assistant_client::MediaManager {
public:
MediaManagerMock() = default;
MediaManagerMock(const MediaManagerMock&) = delete;
MediaManagerMock& operator=(const MediaManagerMock&) = delete;
~MediaManagerMock() override = default;
// assistant_client::MediaManager:
MOCK_METHOD(void, AddListener, (Listener * listener));
MOCK_METHOD(void, Next, ());
MOCK_METHOD(void, Previous, ());
MOCK_METHOD(void, Resume, ());
MOCK_METHOD(void, Pause, ());
MOCK_METHOD(void, PlayPause, ());
MOCK_METHOD(void, StopAndClearPlaylist, ());
MOCK_METHOD(void,
SetExternalPlaybackState,
(const assistant_client::MediaStatus& new_status));
};
class AssistantServiceControllerTest : public testing::Test {
public:
AssistantServiceControllerTest()
: service_controller_(
std::make_unique<ServiceController>(&libassistant_factory_)) {
service_controller_->Bind(client_.BindNewPipeAndPassReceiver(),
&settings_controller_);
}
mojo::Remote<mojom::ServiceController>& client() { return client_; }
ServiceController& service_controller() {
DCHECK(service_controller_);
return *service_controller_;
}
void RunUntilIdle() { base::RunLoop().RunUntilIdle(); }
// Add the state observer. Will expect the call that follows immediately after
// adding the observer.
void AddStateObserver(StateObserverMock* observer) {
EXPECT_CALL(*observer, OnStateChanged);
service_controller().AddAndFireStateObserver(
observer->BindAndPassReceiver());
RunUntilIdle();
}
void AddAndFireAssistantClientObserver(AssistantClientObserver* observer) {
service_controller().AddAndFireAssistantClientObserver(observer);
}
void RemoveAssistantClientObserver(AssistantClientObserver* observer) {
service_controller().RemoveAssistantClientObserver(observer);
}
void AddAndFireStateObserver(StateObserverMock* observer) {
service_controller().AddAndFireStateObserver(
observer->BindAndPassReceiver());
RunUntilIdle();
}
void Initialize(mojom::BootupConfigPtr config = mojom::BootupConfig::New()) {
service_controller().Initialize(std::move(config), BindURLLoaderFactory());
}
void Start() {
service_controller().Start();
libassistant_factory_.assistant_manager().SetMediaManager(&media_manager_);
RunUntilIdle();
}
void SendOnStartFinished() {
auto* device_state_listener =
libassistant_factory_.assistant_manager().device_state_listener();
ASSERT_NE(device_state_listener, nullptr);
device_state_listener->OnStartFinished();
RunUntilIdle();
}
void Stop() {
service_controller().Stop();
RunUntilIdle();
}
void DestroyServiceController() { service_controller_.reset(); }
std::string libassistant_config() {
return libassistant_factory_.libassistant_config();
}
SettingsControllerMock& settings_controller_mock() {
return settings_controller_;
}
private:
mojo::PendingRemote<network::mojom::URLLoaderFactory> BindURLLoaderFactory() {
mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote;
url_loader_factory_.Clone(pending_remote.InitWithNewPipeAndPassReceiver());
return pending_remote;
}
base::test::SingleThreadTaskEnvironment environment_;
base::ScopedPathOverride home_override{base::DIR_HOME};
network::TestURLLoaderFactory url_loader_factory_;
FakeLibassistantFactory libassistant_factory_;
testing::NiceMock<SettingsControllerMock> settings_controller_;
mojo::Remote<mojom::ServiceController> client_;
std::unique_ptr<ServiceController> service_controller_;
MediaManagerMock media_manager_;
};
} // namespace
namespace mojom {
void PrintTo(const ServiceState state, std::ostream* stream) {
switch (state) {
case ServiceState::kRunning:
*stream << "kRunning";
return;
case ServiceState::kStarted:
*stream << "kStarted";
return;
case ServiceState::kStopped:
*stream << "kStopped";
return;
}
*stream << "INVALID ServiceState (" << static_cast<int>(state) << ")";
}
} // namespace mojom
TEST_F(AssistantServiceControllerTest, StateShouldStartAsStopped) {
Initialize();
StateObserverMock observer;
EXPECT_CALL(observer, OnStateChanged(ServiceState::kStopped));
AddAndFireStateObserver(&observer);
}
TEST_F(AssistantServiceControllerTest,
StateShouldChangeToStartedAfterCallingStart) {
Initialize();
StateObserverMock observer;
AddStateObserver(&observer);
EXPECT_CALL(observer, OnStateChanged(ServiceState::kStarted));
Start();
}
TEST_F(AssistantServiceControllerTest,
StateShouldChangeToStoppedAfterCallingStop) {
Initialize();
Start();
StateObserverMock observer;
AddStateObserver(&observer);
EXPECT_CALL(observer, OnStateChanged(ServiceState::kStopped));
Stop();
}
TEST_F(AssistantServiceControllerTest,
StateShouldChangeToRunningAfterLibassistantSignalsItsDone) {
Initialize();
Start();
StateObserverMock observer;
AddStateObserver(&observer);
EXPECT_CALL(observer, OnStateChanged(ServiceState::kRunning));
SendOnStartFinished();
}
TEST_F(AssistantServiceControllerTest,
ShouldSendCurrentStateWhenAddingObserver) {
Initialize();
{
StateObserverMock observer;
EXPECT_CALL(observer, OnStateChanged(ServiceState::kStopped));
AddAndFireStateObserver(&observer);
}
Start();
{
StateObserverMock observer;
EXPECT_CALL(observer, OnStateChanged(ServiceState::kStarted));
AddAndFireStateObserver(&observer);
}
Stop();
{
StateObserverMock observer;
EXPECT_CALL(observer, OnStateChanged(ServiceState::kStopped));
AddAndFireStateObserver(&observer);
}
}
TEST_F(AssistantServiceControllerTest,
ShouldCreateAssistantManagerWhenCallingInitialize) {
EXPECT_EQ(nullptr, service_controller().assistant_client());
Initialize();
EXPECT_NE(nullptr,
service_controller().assistant_client()->assistant_manager());
}
TEST_F(AssistantServiceControllerTest, ShouldBeNoopWhenCallingStartTwice) {
// Note: This is the preferred behavior for services exposed through mojom.
Initialize();
Start();
StateObserverMock observer;
AddStateObserver(&observer);
EXPECT_NO_CALLS(observer, OnStateChanged);
Start();
}
TEST_F(AssistantServiceControllerTest, CallingStopTwiceShouldBeANoop) {
Initialize();
Stop();
StateObserverMock observer;
AddStateObserver(&observer);
EXPECT_NO_CALLS(observer, OnStateChanged);
Stop();
}
TEST_F(AssistantServiceControllerTest, ShouldAllowStartAfterStop) {
Initialize();
Start();
Stop();
// The second Initialize() call should create the AssistantManager.
Initialize();
EXPECT_NE(nullptr,
service_controller().assistant_client()->assistant_manager());
// The second Start() call should send out a state update.
StateObserverMock observer;
AddStateObserver(&observer);
EXPECT_CALL(observer, OnStateChanged(ServiceState::kStarted));
Start();
EXPECT_NE(nullptr,
service_controller().assistant_client()->assistant_manager());
}
TEST_F(AssistantServiceControllerTest,
ShouldDestroyAssistantManagerWhenCallingStop) {
Initialize();
Start();
EXPECT_NE(nullptr,
service_controller().assistant_client()->assistant_manager());
Stop();
EXPECT_EQ(nullptr, service_controller().assistant_client());
}
TEST_F(AssistantServiceControllerTest,
StateShouldChangeToStoppedWhenBeingDestroyed) {
Initialize();
Start();
StateObserverMock observer;
AddStateObserver(&observer);
EXPECT_CALL(observer, OnStateChanged(ServiceState::kStopped));
DestroyServiceController();
RunUntilIdle();
}
TEST_F(AssistantServiceControllerTest,
ShouldCreateButNotPublishAssistantManagerInternalWhenCallingInitialize) {
EXPECT_EQ(nullptr, service_controller().assistant_client());
Initialize();
EXPECT_NE(
nullptr,
service_controller().assistant_client()->assistant_manager_internal());
}
TEST_F(AssistantServiceControllerTest,
ShouldPublishAssistantManagerInternalWhenCallingStart) {
Initialize();
Start();
EXPECT_NE(
nullptr,
service_controller().assistant_client()->assistant_manager_internal());
}
TEST_F(AssistantServiceControllerTest,
ShouldDestroyAssistantManagerInternalWhenCallingStop) {
Initialize();
EXPECT_NE(
nullptr,
service_controller().assistant_client()->assistant_manager_internal());
Start();
Stop();
EXPECT_EQ(nullptr, service_controller().assistant_client());
}
TEST_F(AssistantServiceControllerTest,
ShouldPassS3ServerUriOverrideToMojomService) {
auto bootup_config = mojom::BootupConfig::New();
bootup_config->s3_server_uri_override = "the-s3-server-uri-override";
Initialize(std::move(bootup_config));
EXPECT_HAS_PATH_WITH_VALUE(libassistant_config(),
"testing.s3_grpc_server_uri",
"the-s3-server-uri-override");
}
TEST_F(AssistantServiceControllerTest,
ShouldCallOnAssistantClientCreatedWhenCallingInitialize) {
StrictMock<AssistantClientObserverMock> observer;
AddAndFireAssistantClientObserver(&observer);
EXPECT_CALL(observer, OnAssistantClientCreated)
.WillOnce([&controller =
service_controller()](AssistantClient* assistant_client) {
EXPECT_EQ(assistant_client, controller.assistant_client());
});
Initialize();
RemoveAssistantClientObserver(&observer);
}
TEST_F(AssistantServiceControllerTest,
ShouldCallOnAssistantClientCreatedWhenAddingObserver) {
Initialize();
StrictMock<AssistantClientObserverMock> observer;
EXPECT_CALL(observer, OnAssistantClientCreated)
.WillOnce([&controller =
service_controller()](AssistantClient* assistant_client) {
EXPECT_EQ(assistant_client, controller.assistant_client());
});
AddAndFireAssistantClientObserver(&observer);
RemoveAssistantClientObserver(&observer);
}
TEST_F(AssistantServiceControllerTest,
ShouldCallOnAssistantClientStartedWhenCallingStart) {
StrictMock<AssistantClientObserverMock> observer;
AddAndFireAssistantClientObserver(&observer);
EXPECT_CALL(observer, OnAssistantClientCreated);
Initialize();
EXPECT_CALL(observer, OnAssistantClientStarted)
.WillOnce([&controller =
service_controller()](AssistantClient* assistant_client) {
EXPECT_EQ(assistant_client, controller.assistant_client());
});
Start();
RemoveAssistantClientObserver(&observer);
}
TEST_F(AssistantServiceControllerTest,
ShouldCallOnAssistantManagerInitializedAndCreatedWhenAddingObserver) {
Initialize();
Start();
StrictMock<AssistantClientObserverMock> observer;
EXPECT_CALL(observer, OnAssistantClientCreated)
.WillOnce([&controller =
service_controller()](AssistantClient* assistant_client) {
EXPECT_EQ(assistant_client, controller.assistant_client());
});
EXPECT_CALL(observer, OnAssistantClientStarted)
.WillOnce([&controller =
service_controller()](AssistantClient* assistant_client) {
EXPECT_EQ(assistant_client, controller.assistant_client());
});
AddAndFireAssistantClientObserver(&observer);
RemoveAssistantClientObserver(&observer);
}
TEST_F(AssistantServiceControllerTest,
ShouldCallOnAssistantClientRunningWhenCallingOnStartFinished) {
StrictMock<AssistantClientObserverMock> observer;
AddAndFireAssistantClientObserver(&observer);
EXPECT_CALL(observer, OnAssistantClientCreated);
Initialize();
EXPECT_CALL(observer, OnAssistantClientStarted);
Start();
EXPECT_CALL(observer, OnAssistantClientRunning)
.WillOnce([&controller =
service_controller()](AssistantClient* assistant_client) {
EXPECT_EQ(assistant_client, controller.assistant_client());
});
SendOnStartFinished();
RemoveAssistantClientObserver(&observer);
}
TEST_F(AssistantServiceControllerTest,
ShouldCallOnAssistantClientRunningWhenAddingObserver) {
Initialize();
Start();
SendOnStartFinished();
StrictMock<AssistantClientObserverMock> observer;
EXPECT_CALL(observer, OnAssistantClientCreated)
.WillOnce([&controller =
service_controller()](AssistantClient* assistant_client) {
EXPECT_EQ(assistant_client, controller.assistant_client());
});
EXPECT_CALL(observer, OnAssistantClientStarted)
.WillOnce([&controller =
service_controller()](AssistantClient* assistant_client) {
EXPECT_EQ(assistant_client, controller.assistant_client());
});
EXPECT_CALL(observer, OnAssistantClientRunning)
.WillOnce([&controller =
service_controller()](AssistantClient* assistant_client) {
EXPECT_EQ(assistant_client, controller.assistant_client());
});
AddAndFireAssistantClientObserver(&observer);
RemoveAssistantClientObserver(&observer);
}
TEST_F(AssistantServiceControllerTest,
ShouldCallOnDestroyingAssistantClientWhenCallingStop) {
StrictMock<AssistantClientObserverMock> observer;
AddAndFireAssistantClientObserver(&observer);
EXPECT_CALL(observer, OnAssistantClientCreated);
EXPECT_CALL(observer, OnAssistantClientStarted);
Initialize();
Start();
EXPECT_CALL(observer, OnDestroyingAssistantClient)
.WillOnce([&controller =
service_controller()](AssistantClient* assistant_client) {
EXPECT_EQ(assistant_client, controller.assistant_client());
});
EXPECT_CALL(observer, OnAssistantClientDestroyed);
Stop();
RemoveAssistantClientObserver(&observer);
}
TEST_F(AssistantServiceControllerTest,
ShouldNotCallAssistantClientObserverWhenItHasBeenRemoved) {
StrictMock<AssistantClientObserverMock> observer;
AddAndFireAssistantClientObserver(&observer);
RemoveAssistantClientObserver(&observer);
EXPECT_NO_CALLS(observer, OnAssistantClientCreated);
EXPECT_NO_CALLS(observer, OnAssistantClientStarted);
EXPECT_NO_CALLS(observer, OnDestroyingAssistantClient);
EXPECT_NO_CALLS(observer, OnAssistantClientDestroyed);
Initialize();
Start();
Stop();
RemoveAssistantClientObserver(&observer);
}
TEST_F(AssistantServiceControllerTest,
ShouldCallOnDestroyingAssistantClientWhenBeingDestroyed) {
Initialize();
Start();
StrictMock<AssistantClientObserverMock> observer;
EXPECT_CALL(observer, OnAssistantClientCreated);
EXPECT_CALL(observer, OnAssistantClientStarted);
AddAndFireAssistantClientObserver(&observer);
EXPECT_CALL(observer, OnDestroyingAssistantClient);
EXPECT_CALL(observer, OnAssistantClientDestroyed);
DestroyServiceController();
}
TEST_F(AssistantServiceControllerTest,
ShouldPassBootupConfigToSettingsController) {
const bool hotword_enabled = true;
const bool spoken_feedback_enabled = false;
EXPECT_CALL(settings_controller_mock(), SetLocale("locale"));
EXPECT_CALL(settings_controller_mock(), SetHotwordEnabled(hotword_enabled));
EXPECT_CALL(settings_controller_mock(),
SetSpokenFeedbackEnabled(spoken_feedback_enabled));
EXPECT_CALL(settings_controller_mock(), SetAuthenticationTokens);
auto bootup_config = mojom::BootupConfig::New();
bootup_config->locale = "locale";
bootup_config->hotword_enabled = hotword_enabled;
bootup_config->spoken_feedback_enabled = spoken_feedback_enabled;
bootup_config->authentication_tokens =
ToVector(mojom::AuthenticationToken::New("user", "token"));
Initialize(std::move(bootup_config));
}
} // namespace libassistant
} // namespace chromeos
|
#include "ControlMap.h"
using namespace curtinfrc::controllers;
void ControlMap::InitSmartControllerGroup(SmartControllerGroup &contGroup) {
// Xbox (0) Rebinds
const tAxis lowerElevator = { 1, XboxController::kLeftThrottle }, raiseElevator = { 1, XboxController::kRightThrottle };
tButton lowerElevatorButton = { 1, 28 }, raiseElevatorButton = { 1, 27 };
contGroup.GetController(lowerElevator.cont).Map(lowerElevator, lowerElevatorButton);
contGroup.GetController(raiseElevator.cont).Map(raiseElevator, raiseElevatorButton);
}
// DRIVETRAIN AXIS JOYMAP
const tAxis ControlMap::leftAxis{ 1, XboxController::kLeftYAxis };
const tAxis ControlMap::rightAxis{ 1, XboxController::kRightYAxis };
// DRIVETRAIN JOYMAP
const std::vector<tButton> ControlMap::reverseDrivetrain{ }; // Toggles the direction of the drivetrain
const std::vector<tButton> ControlMap::holdMovement{ }; // Makes the robot 'line up' (0 magnitude but still rotating)
const std::vector<tButton> ControlMap::chargeForward{ };
const double ControlMap::drivetrainMinThrottle = 0.3;
const double ControlMap::drivetrainForwardThrottle = -0.9;
const double ControlMap::drivetrainTurnThrottle = -0.6;
// CargoFlipper JOYMAP
const std::vector<tButton> ControlMap::raiseFlipper{ { 1, XboxController::kY } };
const std::vector<tButton> ControlMap::lowerFlipper{ { 1, XboxController::kA } };
// BEELEVATOR JOYMAP
const std::vector<tButton> ControlMap::raiseLift{ { 2, XboxController::kA }, { 2, 20 } };
const std::vector<tButton> ControlMap::lowerLift{ { 2, XboxController::kB } };
const std::vector<tButton> ControlMap::liftGoalGround{ { 1, 28 } };
const std::vector<tButton> ControlMap::liftGoalLower1{ { 2, 11 } };
const std::vector<tButton> ControlMap::liftGoalLower2{ { 2, 12 } };
const std::vector<tButton> ControlMap::liftGoalMiddle1{ { 2, 9 } };
const std::vector<tButton> ControlMap::liftGoalMiddle2{ { 2, 10 } };
const std::vector<tButton> ControlMap::liftGoalUpper1{ { 2, 7 } };
const std::vector<tButton> ControlMap::liftGoalUpper2{ { 2, 8 } };
const double ControlMap::liftSetpointGround = 0.08; // Exact values need to be tested
const double ControlMap::liftSetpointLower1 = 0.46;
const double ControlMap::liftSetpointLower2 = 0.68;
const double ControlMap::liftSetpointMiddle1 = 1.18;
const double ControlMap::liftSetpointMiddle2 = 1.39;
const double ControlMap::liftSetpointUpper1 = 1.89;
const double ControlMap::liftSetpointUpper2 = 1.7;
// HATCH JOYMAP
const std::vector<tButton> ControlMap::hatchGrab{ { 1, XboxController::kY } };
const std::vector<tButton> ControlMap::hatchRelease{ { 1, XboxController::kA } };
const std::vector<tButton> ControlMap::hatchStow{ { 1, XboxController::kBumperRight } };
const std::vector<tButton> ControlMap::hatchToggleEnabled{ { 1, XboxController::kStart } }; // Changes the currently enabled hatch intake
// BOX INTAKE JOYMAP
const std::vector<tButton> ControlMap::boxIn{ { 1, XboxController::kX } }; // reversed
const std::vector<tButton> ControlMap::boxOut{ { 1, XboxController::kB } }; // reversed
const std::vector<tButton> ControlMap::boxStow{ { 1, XboxController::kBumperLeft } };
const double ControlMap::boxDeployedThrottle = 0.6;
const double ControlMap::boxStowingThrottle = 0.4;
const double ControlMap::boxStowedThrottle = 0.2;
// CONTROLSYSTEM JOYMAP
// const std::vector<tButton> ControlMap::compressorOn{ { 1, XboxController::kBack } };
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/dom/trustedtypes/trusted_url.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
namespace blink {
TrustedURL::TrustedURL(const KURL& url) : url_(url) {}
TrustedURL* TrustedURL::create(ScriptState* script_state, const String& url) {
KURL result(ExecutionContext::From(script_state)->CompleteURL(url));
if (!result.IsValid() || !result.ProtocolIsInHTTPFamily())
result = KURL("about:invalid");
return TrustedURL::Create(result);
}
TrustedURL* TrustedURL::unsafelyCreate(ScriptState* script_state,
const String& url) {
return TrustedURL::Create(
ExecutionContext::From(script_state)->CompleteURL(url));
}
String TrustedURL::toString() const {
return url_.GetString();
}
} // namespace blink
|
/*
* 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/green/model/DeleteImageLibRequest.h>
using AlibabaCloud::Green::Model::DeleteImageLibRequest;
DeleteImageLibRequest::DeleteImageLibRequest() :
RpcServiceRequest("green", "2017-08-23", "DeleteImageLib")
{
setMethod(HttpRequest::Method::Post);
}
DeleteImageLibRequest::~DeleteImageLibRequest()
{}
std::string DeleteImageLibRequest::getSourceIp()const
{
return sourceIp_;
}
void DeleteImageLibRequest::setSourceIp(const std::string& sourceIp)
{
sourceIp_ = sourceIp;
setParameter("SourceIp", sourceIp);
}
int DeleteImageLibRequest::getId()const
{
return id_;
}
void DeleteImageLibRequest::setId(int id)
{
id_ = id;
setParameter("Id", std::to_string(id));
}
|
// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <fs.h>
#include <qt/intro.h>
#include <qt/forms/ui_intro.h>
#include <qt/guiutil.h>
#include <util.h>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <cmath>
static const uint64_t GB_BYTES = 1000000000LL;
/* Minimum free space (in GB) needed for data directory */
static const uint64_t BLOCK_CHAIN_SIZE = 18;
/* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */
static const uint64_t CHAIN_STATE_SIZE = 3;
/* Total required space (in GB) depending on user choice (prune, not prune) */
static uint64_t requiredSpace;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
explicit FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public Q_SLOTS:
void check();
Q_SIGNALS:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include <qt/intro.moc>
FreespaceChecker::FreespaceChecker(Intro *_intro)
{
this->intro = _intro;
}
void FreespaceChecker::check()
{
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch (const fs::filesystem_error&)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME)));
ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME)));
ui->lblExplanation1->setText(ui->lblExplanation1->text()
.arg(tr(PACKAGE_NAME))
.arg(BLOCK_CHAIN_SIZE)
.arg(2009)
.arg(tr("Digitaleuro"))
);
ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME)));
uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0));
requiredSpace = BLOCK_CHAIN_SIZE;
QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time.");
if (pruneTarget) {
uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES);
if (prunedGBs <= requiredSpace) {
requiredSpace = prunedGBs;
storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory.");
}
ui->lblExplanation3->setVisible(true);
} else {
ui->lblExplanation3->setVisible(false);
}
requiredSpace += CHAIN_STATE_SIZE;
ui->sizeWarningLabel->setText(
tr("%1 will download and store a copy of the Digitaleuro block chain.").arg(tr(PACKAGE_NAME)) + " " +
storageRequiresMsg.arg(requiredSpace) + " " +
tr("The wallet will also be stored in this directory.")
);
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
Q_EMIT stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
bool Intro::pickDataDirectory()
{
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!gArgs.GetArg("-datadir", "").empty())
return true;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
return false;
}
dataDir = intro.getDataDirectory();
try {
if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) {
// If a new data directory has been created, make wallets subdirectory too
TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets");
}
break;
} catch (const fs::filesystem_error&) {
QMessageBox::critical(0, tr(PACKAGE_NAME),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
settings.setValue("fReset", false);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory())
gArgs.SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
return true;
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < requiredSpace * GB_BYTES)
{
freeString += " " + tr("(of %n GB needed)", "", requiredSpace);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
Q_EMIT requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
|
/*
Copyright (C) 2016-2018 Draios Inc dba Sysdig.
This file is part of falco.
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 "falco_outputs.h"
#include "config_falco.h"
#include "formats.h"
#include "logger.h"
using namespace std;
const static struct luaL_reg ll_falco_outputs [] =
{
{"handle_http", &falco_outputs::handle_http},
{NULL,NULL}
};
falco_outputs::falco_outputs(falco_engine *engine)
: m_falco_engine(engine),
m_initialized(false),
m_buffered(true),
m_json_output(false),
m_time_format_iso_8601(false)
{
}
falco_outputs::~falco_outputs()
{
// Note: The assert()s in this destructor were previously places where
// exceptions were thrown. C++11 doesn't allow destructors to
// emit exceptions; if they're thrown, they'll trigger a call
// to 'terminate()'. To maintain similar behavior, the exceptions
// were replace with calls to 'assert()'
if(m_initialized)
{
lua_getglobal(m_ls, m_lua_output_cleanup.c_str());
if(!lua_isfunction(m_ls, -1))
{
falco_logger::log(LOG_ERR, std::string("No function ") + m_lua_output_cleanup + " found. ");
assert(nullptr == "Missing lua cleanup function in ~falco_outputs");
}
if(lua_pcall(m_ls, 0, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
falco_logger::log(LOG_ERR, std::string("lua_pcall failed, err: ") + lerr);
assert(nullptr == "lua_pcall failed in ~falco_outputs");
}
}
}
void falco_outputs::init(bool json_output,
bool json_include_output_property,
uint32_t rate, uint32_t max_burst, bool buffered,
bool time_format_iso_8601)
{
// The engine must have been given an inspector by now.
if(! m_inspector)
{
throw falco_exception("No inspector provided");
}
m_json_output = json_output;
falco_common::init(m_lua_main_filename.c_str(), FALCO_SOURCE_LUA_DIR);
// Note that falco_formats is added to both the lua state used
// by the falco engine as well as the separate lua state used
// by falco outputs.
falco_formats::init(m_inspector, m_falco_engine, m_ls, json_output, json_include_output_property);
falco_logger::init(m_ls);
luaL_openlib(m_ls, "c_outputs", ll_falco_outputs, 0);
m_notifications_tb.init(rate, max_burst);
m_buffered = buffered;
m_time_format_iso_8601 = time_format_iso_8601;
m_initialized = true;
}
void falco_outputs::add_output(output_config oc)
{
uint8_t nargs = 3;
lua_getglobal(m_ls, m_lua_add_output.c_str());
if(!lua_isfunction(m_ls, -1))
{
throw falco_exception("No function " + m_lua_add_output + " found. ");
}
lua_pushstring(m_ls, oc.name.c_str());
lua_pushnumber(m_ls, (m_buffered ? 1 : 0));
lua_pushnumber(m_ls, (m_time_format_iso_8601 ? 1 : 0));
// If we have options, build up a lua table containing them
if (oc.options.size())
{
nargs = 4;
lua_createtable(m_ls, 0, oc.options.size());
for (auto it = oc.options.cbegin(); it != oc.options.cend(); ++it)
{
lua_pushstring(m_ls, (*it).second.c_str());
lua_setfield(m_ls, -2, (*it).first.c_str());
}
}
if(lua_pcall(m_ls, nargs, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
throw falco_exception(string(lerr));
}
}
void falco_outputs::handle_event(gen_event *ev, string &rule, string &source,
falco_common::priority_type priority, string &format)
{
if(!m_notifications_tb.claim())
{
falco_logger::log(LOG_DEBUG, "Skipping rate-limited notification for rule " + rule + "\n");
return;
}
lua_getglobal(m_ls, m_lua_output_event.c_str());
if(lua_isfunction(m_ls, -1))
{
lua_pushlightuserdata(m_ls, ev);
lua_pushstring(m_ls, rule.c_str());
lua_pushstring(m_ls, source.c_str());
lua_pushstring(m_ls, falco_common::priority_names[priority].c_str());
lua_pushnumber(m_ls, priority);
lua_pushstring(m_ls, format.c_str());
if(lua_pcall(m_ls, 6, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
string err = "Error invoking function output: " + string(lerr);
throw falco_exception(err);
}
}
else
{
throw falco_exception("No function " + m_lua_output_event + " found in lua compiler module");
}
}
void falco_outputs::handle_msg(uint64_t now,
falco_common::priority_type priority,
std::string &msg,
std::string &rule,
std::map<std::string,std::string> &output_fields)
{
std::string full_msg;
if(m_json_output)
{
nlohmann::json jmsg;
// Convert the time-as-nanoseconds to a more json-friendly ISO8601.
time_t evttime = now/1000000000;
char time_sec[20]; // sizeof "YYYY-MM-DDTHH:MM:SS"
char time_ns[12]; // sizeof ".sssssssssZ"
string iso8601evttime;
strftime(time_sec, sizeof(time_sec), "%FT%T", gmtime(&evttime));
snprintf(time_ns, sizeof(time_ns), ".%09luZ", now % 1000000000);
iso8601evttime = time_sec;
iso8601evttime += time_ns;
jmsg["output"] = msg;
jmsg["priority"] = "Critical";
jmsg["rule"] = rule;
jmsg["time"] = iso8601evttime;
jmsg["output_fields"] = output_fields;
full_msg = jmsg.dump();
}
else
{
std::string timestr;
bool first = true;
sinsp_utils::ts_to_string(now, ×tr, false, true);
full_msg = timestr + ": " + falco_common::priority_names[LOG_CRIT] + " " + msg + "(";
for(auto &pair : output_fields)
{
if(first)
{
first = false;
}
else
{
full_msg += " ";
}
full_msg += pair.first + "=" + pair.second;
}
full_msg += ")";
}
lua_getglobal(m_ls, m_lua_output_msg.c_str());
if(lua_isfunction(m_ls, -1))
{
lua_pushstring(m_ls, full_msg.c_str());
lua_pushstring(m_ls, falco_common::priority_names[priority].c_str());
lua_pushnumber(m_ls, priority);
if(lua_pcall(m_ls, 3, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
string err = "Error invoking function output: " + string(lerr);
throw falco_exception(err);
}
}
else
{
throw falco_exception("No function " + m_lua_output_msg + " found in lua compiler module");
}
}
void falco_outputs::reopen_outputs()
{
lua_getglobal(m_ls, m_lua_output_reopen.c_str());
if(!lua_isfunction(m_ls, -1))
{
throw falco_exception("No function " + m_lua_output_reopen + " found. ");
}
if(lua_pcall(m_ls, 0, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
throw falco_exception(string(lerr));
}
}
int falco_outputs::handle_http(lua_State *ls)
{
CURL *curl = NULL;
CURLcode res = CURLE_FAILED_INIT;
struct curl_slist *slist1;
slist1 = NULL;
if (!lua_isstring(ls, -1) ||
!lua_isstring(ls, -2))
{
lua_pushstring(ls, "Invalid arguments passed to handle_http()");
lua_error(ls);
}
string url = (char *) lua_tostring(ls, 1);
string msg = (char *) lua_tostring(ls, 2);
curl = curl_easy_init();
if(curl)
{
slist1 = curl_slist_append(slist1, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist1);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, msg.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1L);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
falco_logger::log(LOG_ERR,"libcurl error: " + string(curl_easy_strerror(res)));
}
curl_easy_cleanup(curl);
curl = NULL;
curl_slist_free_all(slist1);
slist1 = NULL;
}
return 1;
}
|
#ifndef SPROUT_FUNCTIONAL_TYPE_TRAITS_IS_STRICT_FUNCTION_HPP
#define SPROUT_FUNCTIONAL_TYPE_TRAITS_IS_STRICT_FUNCTION_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/functional/type_traits/has_type.hpp>
namespace sprout {
//
// is_strict_unary_function
//
template<typename Fn>
struct is_strict_unary_function
: public std::integral_constant<
bool,
sprout::has_result_type<Fn>::value
&& sprout::has_argument_type<Fn>::value
>
{};
//
// is_strict_binary_function
//
template<typename Fn>
struct is_strict_binary_function
: public std::integral_constant<
bool,
sprout::has_result_type<Fn>::value
&& sprout::has_first_argument_type<Fn>::value
&& sprout::has_second_argument_type<Fn>::value
>
{};
} // namespace sprout
#endif // #ifndef SPROUT_FUNCTIONAL_TYPE_TRAITS_IS_STRICT_FUNCTION_HPP
|
/*
**==============================================================================
**
** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer
**
** 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 "config.h"
#include "Adapter_Tracer.h"
#include "log.h"
CIMPLE_NAMESPACE_BEGIN
void AdapterTracer::pEntry(
const char* name,
const char* file,
size_t line)
{
if(_log_enabled_state)
{
log(LL_DBG, file, line, "Enter: %s()", name);
}
}
void AdapterTracer::pExit(const char* name,
const char* file,
size_t line)
{
if(_log_enabled_state)
{
log(LL_DBG, file, line, "Exit: %s", name);
}
}
void AdapterTracer::pExit(const char* name,
const char* file,
size_t line,
bool value)
{
if(_log_enabled_state)
{
log(LL_DBG, file, line, "Exit: %s %s", name, value? "true": "false");
}
}
void AdapterTracer::pExit(const char* name,
const char* file,
size_t line,
int value)
{
if(_log_enabled_state)
{
log(LL_DBG, file, line, "Exit: %s %d", name, value);
}
}
void AdapterTracer::pExit(const char* name,
const char* file,
size_t line,
uint32 value)
{
if(_log_enabled_state)
{
log(LL_DBG, file, line, "Exit: %s %u", name, value);
}
}
CIMPLE_NAMESPACE_END
|
/**
* Copyright (C) 2016 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kFTDC
#include "mongo/platform/basic.h"
#include "mongo/util/procparser.h"
#include <boost/filesystem.hpp>
#include <map>
#include "mongo/bson/bsonobj.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/log.h"
namespace mongo {
namespace {
using StringMap = std::map<std::string, uint64_t>;
StringMap toStringMap(BSONObj& obj) {
StringMap map;
for (const auto& e : obj) {
map[e.fieldName()] = e.numberLong();
}
return map;
}
StringMap toNestedStringMap(BSONObj& obj) {
StringMap map;
for (const auto& e : obj) {
if (e.isABSONObj()) {
std::string prefix = std::string(e.fieldName()) + ".";
for (const auto& child : e.Obj()) {
map[prefix + child.fieldName()] = child.numberLong();
}
}
}
return map;
}
#define ASSERT_KEY(_key) ASSERT_TRUE(stringMap.find(_key) != stringMap.end());
#define ASSERT_NO_KEY(_key) ASSERT_TRUE(stringMap.find(_key) == stringMap.end());
#define ASSERT_KEY_AND_VALUE(_key, _value) ASSERT_EQUALS(stringMap.at(_key), _value);
#define ASSERT_PARSE_STAT(_keys, _x) \
BSONObjBuilder builder; \
ASSERT_OK(procparser::parseProcStat(_keys, _x, 1000, &builder)); \
auto obj = builder.obj(); \
auto stringMap = toStringMap(obj);
#define ASSERT_PARSE_MEMINFO(_keys, _x) \
BSONObjBuilder builder; \
ASSERT_OK(procparser::parseProcMemInfo(_keys, _x, &builder)); \
auto obj = builder.obj(); \
auto stringMap = toStringMap(obj);
#define ASSERT_PARSE_NETSTAT(_keys, _x) \
BSONObjBuilder builder; \
ASSERT_OK(procparser::parseProcNetstat(_keys, _x, &builder)); \
auto obj = builder.obj(); \
auto stringMap = toStringMap(obj);
#define ASSERT_PARSE_DISKSTATS(_disks, _x) \
BSONObjBuilder builder; \
ASSERT_OK(procparser::parseProcDiskStats(_disks, _x, &builder)); \
auto obj = builder.obj(); \
auto stringMap = toNestedStringMap(obj);
TEST(FTDCProcStat, TestStat) {
std::vector<StringData> keys{"cpu", "ctxt", "processes"};
// Normal case
{
ASSERT_PARSE_STAT(
keys,
"cpu 41801 9179 32206 831134223 34279 0 947 0 0 0\n"
"cpu0 2977 450 2475 69253074 1959 0 116 0 0 0\n"
"cpu1 6213 4261 9400 69177349 845 0 539 0 0 0\n"
"cpu2 1949 831 3699 69261035 645 0 0 0 0 0\n"
"cpu3 2222 644 3283 69264801 783 0 0 0 0 0\n"
"cpu4 16576 607 4757 69232589 8195 0 291 0 0 0\n"
"cpu5 3742 391 4571 69257332 2322 0 0 0 0 0\n"
"cpu6 2173 376 743 69284308 400 0 0 0 0 0\n"
"cpu7 1232 375 704 69285753 218 0 0 0 0 0\n"
"cpu8 960 127 576 69262851 18107 0 0 0 0 0\n"
"cpu9 1755 227 744 69283938 362 0 0 0 0 0\n"
"cpu10 1380 641 678 69285193 219 0 0 0 0 0\n"
"cpu11 618 244 572 69285995 218 0 0 0 0 0\n"
"intr 54084718 135 2 ....\n"
"ctxt 190305514\n"
"btime 1463584038\n"
"processes 47438\n"
"procs_running 1\n"
"procs_blocked 0\n"
"softirq 102690251 8 26697410 115481 23345078 816026 0 2296 26068778 0 25645174\n");
ASSERT_KEY_AND_VALUE("user_ms", 41801UL);
ASSERT_KEY_AND_VALUE("nice_ms", 9179UL);
ASSERT_KEY_AND_VALUE("system_ms", 32206UL);
ASSERT_KEY_AND_VALUE("idle_ms", 831134223UL);
ASSERT_KEY_AND_VALUE("iowait_ms", 34279UL);
ASSERT_KEY_AND_VALUE("irq_ms", 0UL);
ASSERT_KEY_AND_VALUE("softirq_ms", 947UL);
ASSERT_KEY_AND_VALUE("steal_ms", 0UL);
ASSERT_KEY_AND_VALUE("guest_ms", 0UL);
ASSERT_KEY_AND_VALUE("guest_nice_ms", 0UL);
ASSERT_KEY_AND_VALUE("ctxt", 190305514UL);
ASSERT_KEY_AND_VALUE("processes", 47438UL);
}
// Missing fields in cpu and others
{
ASSERT_PARSE_STAT(keys,
"cpu 41801 9179 32206\n"
"ctxt 190305514\n");
ASSERT_KEY_AND_VALUE("user_ms", 41801UL);
ASSERT_KEY_AND_VALUE("nice_ms", 9179UL);
ASSERT_KEY_AND_VALUE("system_ms", 32206UL);
ASSERT_NO_KEY("idle_ms");
ASSERT_KEY_AND_VALUE("ctxt", 190305514UL);
ASSERT_NO_KEY("processes");
}
// Missing fields in cpu and others
{
ASSERT_PARSE_STAT(keys,
"cpu 41801\n"
"ctxt 190305514\n");
ASSERT_KEY_AND_VALUE("user_ms", 41801UL);
ASSERT_NO_KEY("nice_ms");
ASSERT_KEY_AND_VALUE("ctxt", 190305514UL);
ASSERT_NO_KEY("processes");
}
// Missing fields in cpu
{
ASSERT_PARSE_STAT(keys,
"cpu \n"
"ctxt 190305514\n");
ASSERT_KEY_AND_VALUE("ctxt", 190305514UL);
ASSERT_NO_KEY("processes");
}
// Single string with only cpu and numbers
{
ASSERT_PARSE_STAT(keys, "cpu 41801 9179 32206");
ASSERT_KEY_AND_VALUE("user_ms", 41801UL);
ASSERT_KEY_AND_VALUE("nice_ms", 9179UL);
ASSERT_KEY_AND_VALUE("system_ms", 32206UL);
ASSERT_NO_KEY("idle_ms");
}
// Single string with only cpu
{
BSONObjBuilder builder;
ASSERT_NOT_OK(procparser::parseProcStat(keys, "cpu", 1000, &builder));
}
// Single string with only cpu and a number, and empty ctxt
{
ASSERT_PARSE_STAT(keys,
"cpu 123\n"
"ctxt");
ASSERT_KEY_AND_VALUE("user_ms", 123UL);
}
// Empty String
{
BSONObjBuilder builder;
ASSERT_NOT_OK(procparser::parseProcStat(keys, "", 1000, &builder));
}
}
// Test we can parse the /proc/stat on this machine. Also assert we have the expected fields
// This tests is designed to exercise our parsing code on various Linuxes and fail
// Normally when run in the FTDC loop we return a non-fatal error so we may not notice the failure
// otherwise.
TEST(FTDCProcStat, TestLocalStat) {
std::vector<StringData> keys{
"btime", "cpu", "ctxt", "processes", "procs_blocked", "procs_running",
};
BSONObjBuilder builder;
ASSERT_OK(procparser::parseProcStatFile("/proc/stat", keys, &builder));
BSONObj obj = builder.obj();
auto stringMap = toStringMap(obj);
log() << "OBJ:" << obj;
ASSERT_KEY("user_ms");
ASSERT_KEY("nice_ms");
ASSERT_KEY("idle_ms");
ASSERT_KEY("system_ms");
ASSERT_KEY("iowait_ms");
ASSERT_KEY("irq_ms");
ASSERT_KEY("softirq_ms");
ASSERT_KEY("steal_ms");
// Needs 2.6.24 - ASSERT_KEY("guest_ms");
// Needs 2.6.33 - ASSERT_KEY("guest_nice_ms");
ASSERT_KEY("ctxt");
ASSERT_KEY("btime");
ASSERT_KEY("processes");
ASSERT_KEY("procs_running");
ASSERT_KEY("procs_blocked");
}
TEST(FTDCProcStat, TestLocalNonExistentStat) {
std::vector<StringData> keys{
"btime", "cpu", "ctxt", "processes", "procs_blocked", "procs_running",
};
BSONObjBuilder builder;
ASSERT_NOT_OK(procparser::parseProcStatFile("/proc/does_not_exist", keys, &builder));
}
TEST(FTDCProcMemInfo, TestMemInfo) {
std::vector<StringData> keys{"Key1", "Key2", "Key3"};
// Normal case
{
ASSERT_PARSE_MEMINFO(keys, "Key1: 123 kB\nKey2: 456 kB");
ASSERT_KEY_AND_VALUE("Key1_kb", 123UL);
ASSERT_KEY_AND_VALUE("Key2_kb", 456UL);
}
// Space in key name
{
ASSERT_PARSE_MEMINFO(keys, "Key1: 123 kB\nKey 2: 456 kB");
ASSERT_KEY_AND_VALUE("Key1_kb", 123UL);
ASSERT_NO_KEY("Key2_kb");
}
// No newline
{
ASSERT_PARSE_MEMINFO(keys, "Key1: 123 kB Key2: 456 kB");
ASSERT_KEY_AND_VALUE("Key1_kb", 123UL);
ASSERT_NO_KEY("Key2_kb");
}
// Missing colon on first key
{
ASSERT_PARSE_MEMINFO(keys, "Key1 123 kB\nKey2: 456 kB");
ASSERT_KEY_AND_VALUE("Key1_kb", 123UL);
ASSERT_KEY_AND_VALUE("Key2_kb", 456UL);
}
// One token missing kB, HugePages is not size in kB
{
ASSERT_PARSE_MEMINFO(keys, "Key1: 123 kB\nKey2: 456\nKey3: 789 kB\nKey4: 789 kB");
ASSERT_KEY_AND_VALUE("Key1_kb", 123UL);
ASSERT_KEY_AND_VALUE("Key2", 456UL);
ASSERT_KEY_AND_VALUE("Key3_kb", 789UL);
ASSERT_NO_KEY("Key4_kb");
}
// Empty string
{
BSONObjBuilder builder;
ASSERT_NOT_OK(procparser::parseProcMemInfo(keys, "", &builder));
}
}
// Test we can parse the /proc/meminfo on this machine. Also assert we have the expected fields
// This tests is designed to exercise our parsing code on various Linuxes and fail
// Normally when run in the FTDC loop we return a non-fatal error so we may not notice the failure
// otherwise.
TEST(FTDCProcMemInfo, TestLocalMemInfo) {
std::vector<StringData> keys{
"Active", "Active(anon)",
"Active(file)", "AnonHugePages",
"AnonPages", "Bounce",
"Buffers", "Cached",
"CmaFree", "CmaTotal",
"CommitLimit", "Committed_AS",
"Dirty", "HardwareCorrupted",
"Inactive", "Inactive(anon)",
"Inactive(file)", "KernelStack",
"Mapped", "MemAvailable",
"MemFree", "MemTotal",
"Mlocked", "NFS_Unstable",
"PageTables", "SReclaimable",
"SUnreclaim", "Shmem",
"Slab", "SwapCached",
"SwapFree", "SwapTotal",
"Unevictable", "VmallocChunk",
"VmallocTotal", "VmallocUsed",
"Writeback", "WritebackTmp",
};
BSONObjBuilder builder;
ASSERT_OK(procparser::parseProcMemInfoFile("/proc/meminfo", keys, &builder));
BSONObj obj = builder.obj();
auto stringMap = toStringMap(obj);
log() << "OBJ:" << obj;
ASSERT_KEY("MemTotal_kb");
ASSERT_KEY("MemFree_kb");
// Needs in 3.15+ - ASSERT_KEY("MemAvailable_kb");
ASSERT_KEY("Buffers_kb");
ASSERT_KEY("Cached_kb");
ASSERT_KEY("SwapCached_kb");
ASSERT_KEY("Active_kb");
ASSERT_KEY("Inactive_kb");
// Needs 2.6.28+ - ASSERT_KEY("Active(anon)_kb");
// Needs 2.6.28+ - ASSERT_KEY("Inactive(anon)_kb");
// Needs 2.6.28+ - ASSERT_KEY("Active(file)_kb");
// Needs 2.6.28+ - ASSERT_KEY("Inactive(file)_kb");
// Needs 2.6.28+ - ASSERT_KEY("Unevictable_kb");
// Needs 2.6.28+ - ASSERT_KEY("Mlocked_kb");
ASSERT_KEY("SwapTotal_kb");
ASSERT_KEY("SwapFree_kb");
ASSERT_KEY("Dirty_kb");
ASSERT_KEY("Writeback_kb");
ASSERT_KEY("AnonPages_kb");
ASSERT_KEY("Mapped_kb");
// Needs 2.6.32+ - ASSERT_KEY("Shmem_kb");
ASSERT_KEY("Slab_kb");
// Needs 2.6.19+ - ASSERT_KEY("SReclaimable_kb");
// Needs 2.6.19+ - ASSERT_KEY("SUnreclaim_kb");
// Needs 2.6.32+ - ASSERT_KEY("KernelStack_kb");
ASSERT_KEY("PageTables_kb");
ASSERT_KEY("NFS_Unstable_kb");
ASSERT_KEY("Bounce_kb");
// Needs 2.6.19+ - ASSERT_KEY("WritebackTmp_kb");
ASSERT_KEY("CommitLimit_kb");
ASSERT_KEY("Committed_AS_kb");
ASSERT_KEY("VmallocTotal_kb");
ASSERT_KEY("VmallocUsed_kb");
ASSERT_KEY("VmallocChunk_kb");
// Needs CONFIG_MEMORY_FAILURE & 2.6.32+ ASSERT_KEY("HardwareCorrupted_kb");
// Needs CONFIG_TRANSPARENT_HUGEPAGE - ASSERT_KEY("AnonHugePages_kb");
// Needs CONFIG_CMA & 3.19+ - ASSERT_KEY("CmaTotal_kb");
// Needs CONFIG_CMA & 3.19+ - ASSERT_KEY("CmaFree_kb");
}
TEST(FTDCProcMemInfo, TestLocalNonExistentMemInfo) {
std::vector<StringData> keys{};
BSONObjBuilder builder;
ASSERT_NOT_OK(procparser::parseProcMemInfoFile("/proc/does_not_exist", keys, &builder));
}
TEST(FTDCProcNetstat, TestNetstat) {
// test keys
std::vector<StringData> keys{"pfx1", "pfx2", "pfx3"};
// Normal case
{
ASSERT_PARSE_NETSTAT(keys,
"pfx1 key1 key2 key3\n"
"pfx1 1 2 3\n"
"pfxX key1 key2\n"
"pfxX key1 key2\n"
"pfx2 key4 key5\n"
"pfx2 4 5\n");
ASSERT_KEY_AND_VALUE("pfx1key1", 1UL);
ASSERT_KEY_AND_VALUE("pfx1key2", 2UL);
ASSERT_NO_KEY("pfxXkey1");
ASSERT_NO_KEY("pfxXkey2");
ASSERT_KEY_AND_VALUE("pfx1key3", 3UL)
ASSERT_KEY_AND_VALUE("pfx2key4", 4UL);
ASSERT_KEY_AND_VALUE("pfx2key5", 5UL);
}
// Mismatched keys and values
{
ASSERT_PARSE_NETSTAT(keys,
"pfx1 key1 key2 key3\n"
"pfx1 1 2 3 4\n"
"pfx2 key4 key5\n"
"pfx2 4\n"
"pfx3 key6 key7\n");
ASSERT_KEY_AND_VALUE("pfx1key1", 1UL);
ASSERT_KEY_AND_VALUE("pfx1key2", 2UL);
ASSERT_KEY_AND_VALUE("pfx1key3", 3UL);
ASSERT_NO_KEY("pfx1key4");
ASSERT_KEY_AND_VALUE("pfx2key4", 4UL);
ASSERT_NO_KEY("pfx2key5");
ASSERT_NO_KEY("pfx3key6");
ASSERT_NO_KEY("pfx3key7");
}
// Non-numeric value
{
ASSERT_PARSE_NETSTAT(keys,
"pfx1 key1 key2 key3\n"
"pfx1 1 foo 3\n");
ASSERT_KEY_AND_VALUE("pfx1key1", 1UL);
ASSERT_NO_KEY("pfx1key2");
ASSERT_KEY_AND_VALUE("pfx1key3", 3UL)
}
// No newline
{
ASSERT_PARSE_NETSTAT(keys,
"pfx1 key1 key2 key3\n"
"pfx1 1 2 3\n"
"pfx2 key4 key5\n"
"pfx2 4 5");
ASSERT_KEY_AND_VALUE("pfx1key1", 1UL);
ASSERT_KEY_AND_VALUE("pfx1key2", 2UL);
ASSERT_KEY_AND_VALUE("pfx1key3", 3UL)
ASSERT_KEY_AND_VALUE("pfx2key4", 4UL);
ASSERT_KEY_AND_VALUE("pfx2key5", 5UL);
}
// Single line only
{
BSONObjBuilder builder;
ASSERT_NOT_OK(procparser::parseProcNetstat(keys, "pfx1 key1 key2 key3\n", &builder));
}
// Empty string
{
BSONObjBuilder builder;
ASSERT_NOT_OK(procparser::parseProcNetstat(keys, "", &builder));
}
}
// Test we can parse the /proc/net/netstat on this machine and assert we have some expected fields
// Some keys can vary between distros, so we test only for the existence of a few basic ones
TEST(FTDCProcNetstat, TestLocalNetstat) {
BSONObjBuilder builder;
std::vector<StringData> keys{"TcpExt:"_sd, "IpExt:"_sd};
ASSERT_OK(procparser::parseProcNetstatFile(keys, "/proc/net/netstat", &builder));
BSONObj obj = builder.obj();
auto stringMap = toStringMap(obj);
log() << "OBJ:" << obj;
ASSERT_KEY("TcpExt:TCPTimeouts");
ASSERT_KEY("TcpExt:TCPPureAcks");
ASSERT_KEY("TcpExt:TCPAbortOnTimeout");
ASSERT_KEY("TcpExt:EmbryonicRsts");
ASSERT_KEY("TcpExt:ListenDrops");
ASSERT_KEY("TcpExt:ListenOverflows");
ASSERT_KEY("TcpExt:DelayedACKs");
ASSERT_KEY("IpExt:OutOctets");
ASSERT_KEY("IpExt:InOctets");
}
// Test we can parse the /proc/net/snmp on this machine and assert we have some expected fields
// Some keys can vary between distros, so we test only for the existence of a few basic ones
TEST(FTDCProcNetstat, TestLocalNetSnmp) {
BSONObjBuilder builder;
std::vector<StringData> keys{"Tcp:"_sd, "Ip:"_sd};
ASSERT_OK(procparser::parseProcNetstatFile(keys, "/proc/net/snmp", &builder));
BSONObj obj = builder.obj();
auto stringMap = toStringMap(obj);
log() << "OBJ:" << obj;
ASSERT_KEY("Ip:InReceives");
ASSERT_KEY("Ip:OutRequests");
ASSERT_KEY("Tcp:InSegs");
ASSERT_KEY("Tcp:OutSegs");
}
TEST(FTDCProcNetstat, TestLocalNonExistentNetstat) {
std::vector<StringData> keys{};
BSONObjBuilder builder;
ASSERT_NOT_OK(procparser::parseProcNetstatFile(keys, "/proc/does_not_exist", &builder));
}
TEST(FTDCProcDiskStats, TestDiskStats) {
std::vector<StringData> disks{"dm-1", "sda", "sdb"};
// Normal case including high device major numbers.
{
ASSERT_PARSE_DISKSTATS(
disks,
" 8 0 sda 120611 33630 6297628 96550 349797 167398 11311562 2453603 0 117514 "
"2554160\n"
" 8 1 sda1 138 37 8642 315 3 0 18 14 0 292 329\n"
" 8 2 sda2 120409 33593 6285754 96158 329029 167398 11311544 2450573 0 115611 "
"2550739\n"
" 8 16 sdb 12707 3876 1525418 57507 997 3561 297576 97976 0 37870 155619\n"
" 8 17 sdb1 12601 3876 1521090 57424 992 3561 297576 97912 0 37738 155468\n"
" 11 0 sr0 0 0 0 0 0 0 0 0 0 0 0\n"
"2253 0 dm-0 154910 0 6279522 177681 506513 0 11311544 5674418 0 117752 5852275\n"
"2253 1 dm-1 109 0 4584 226 0 0 0 0 0 172 226");
ASSERT_KEY_AND_VALUE("sda.reads", 120611UL);
ASSERT_KEY_AND_VALUE("sda.writes", 349797UL);
ASSERT_KEY_AND_VALUE("sda.io_queued_ms", 2554160UL);
ASSERT_KEY_AND_VALUE("sdb.reads", 12707UL);
ASSERT_KEY_AND_VALUE("sdb.writes", 997UL);
ASSERT_KEY_AND_VALUE("sdb.io_queued_ms", 155619UL);
ASSERT_KEY_AND_VALUE("dm-1.reads", 109UL);
ASSERT_KEY_AND_VALUE("dm-1.writes", 0UL);
ASSERT_KEY_AND_VALUE("dm-1.io_queued_ms", 226UL);
}
// Exclude a block device without any activity
{
ASSERT_PARSE_DISKSTATS(
disks,
" 8 0 sda 120611 33630 6297628 96550 349797 167398 11311562 2453603 0 117514 "
"2554160\n"
" 8 1 sda1 138 37 8642 315 3 0 18 14 0 292 329\n"
" 8 2 sda2 120409 33593 6285754 96158 329029 167398 11311544 2450573 0 115611 "
"2550739\n"
" 8 16 sdb 0 0 0 0 0 0 0 0 0 0 0\n"
" 8 17 sdb1 12601 3876 1521090 57424 992 3561 297576 97912 0 37738 155468\n"
" 11 0 sr0 0 0 0 0 0 0 0 0 0 0 0\n"
"2253 0 dm-0 154910 0 6279522 177681 506513 0 11311544 5674418 0 117752 5852275\n"
"2253 1 dm-1 109 0 4584 226 0 0 0 0 0 172 226");
ASSERT_KEY_AND_VALUE("sda.reads", 120611UL);
ASSERT_KEY_AND_VALUE("sda.writes", 349797UL);
ASSERT_KEY_AND_VALUE("sda.io_queued_ms", 2554160UL);
ASSERT_NO_KEY("sdb.reads");
ASSERT_NO_KEY("sdb.writes");
ASSERT_NO_KEY("sdb.io_queued_ms");
ASSERT_KEY_AND_VALUE("dm-1.reads", 109UL);
ASSERT_KEY_AND_VALUE("dm-1.writes", 0UL);
ASSERT_KEY_AND_VALUE("dm-1.io_queued_ms", 226UL);
}
// Strings with less numbers
{ ASSERT_PARSE_DISKSTATS(disks, "8 0 sda 120611 33630 6297628 96550 349797 "); }
// Strings with no numbers
{ ASSERT_PARSE_DISKSTATS(disks, "8 0 sda"); }
// Strings that are too short
{
BSONObjBuilder builder;
ASSERT_NOT_OK(procparser::parseProcDiskStats(disks, "8 0", &builder));
ASSERT_NOT_OK(procparser::parseProcDiskStats(disks, "8", &builder));
ASSERT_NOT_OK(procparser::parseProcDiskStats(disks, "", &builder));
}
}
TEST(FTDCProcDiskStats, TestLocalNonExistentStat) {
std::vector<StringData> disks{"dm-1", "sda", "sdb"};
BSONObjBuilder builder;
ASSERT_NOT_OK(procparser::parseProcDiskStatsFile("/proc/does_not_exist", disks, &builder));
}
TEST(FTDCProcDiskStats, TestFindBadPhysicalDiskPaths) {
// Validate nothing goes wrong when we check a non-existent path.
{
auto disks = procparser::findPhysicalDisks("/proc/does_not_exist");
ASSERT_EQUALS(0UL, disks.size());
}
// Validate nothing goes wrong when we check a path we do not have permission.
{
auto disks = procparser::findPhysicalDisks("/sys/kernel/debug");
ASSERT_EQUALS(0UL, disks.size());
}
}
// Test we can parse the /proc/diskstats on this machine. Also assert we have the expected fields
// This tests is designed to exercise our parsing code on various Linuxes and fail
// Normally when run in the FTDC loop we return a non-fatal error so we may not notice the failure
// otherwise.
TEST(FTDCProcDiskStats, TestLocalDiskStats) {
auto disks = procparser::findPhysicalDisks("/sys/block");
std::vector<StringData> disks2;
for (const auto& disk : disks) {
log() << "DISK:" << disk;
disks2.emplace_back(disk);
}
ASSERT_NOT_EQUALS(0UL, disks.size());
BSONObjBuilder builder;
ASSERT_OK(procparser::parseProcDiskStatsFile("/proc/diskstats", disks2, &builder));
BSONObj obj = builder.obj();
auto stringMap = toNestedStringMap(obj);
log() << "OBJ:" << obj;
bool foundDisk = false;
for (const auto& disk : disks) {
std::string prefix(disk);
prefix += ".";
auto reads = prefix + "reads";
auto io_queued_ms = prefix + "io_queued_ms";
// Make sure that if have the first field, then we have the last field.
if (stringMap.find(reads) != stringMap.end()) {
foundDisk = true;
if (stringMap.find(io_queued_ms) == stringMap.end()) {
FAIL(std::string("Inconsistency for ") + disk);
}
}
}
if (!foundDisk) {
FAIL("Did not find any interesting disks on this machine.");
}
}
} // namespace
} // namespace mongo
|
#include "dropper.h"
#include <QtWidgets/QApplication>
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
Dropper w;
w.show();
return a.exec();
}
|
//@group GUI
#include "Utils.h"
#include "GUI.h"
#include "GUI_Internal.h"
#include "GUI_Slider.h"
#include "Renderer.h"
#define SLIDER_MIN_RUN_PIXELS 0.0f
#define SLIDER_MIN_CARET_WIDTH 2.0f
#define SLIDER_HEIGHT m_pContext->
namespace DgE
{
namespace GUI
{
class SliderContext
{
public:
SliderContext()
: value(0)
, length(100.0f)
, isVertical(false)
, position{}
, style{}
, pSlider{}
, pParent{}
, clbk_HoverOn()
, clbk_HoverOff()
{
if (clbk_HoverOn == nullptr)
char t = 0;
}
float value; // normalised between 0 and 1
float length;
bool isVertical;
vec2 position;
Style::Slider style;
SliderBase *pSlider;
Widget *pParent;
std::function<void()> clbk_HoverOn;
std::function<void()> clbk_HoverOff;
float GetLowerLength();
void GetAABBs(UIAABB &lower, UIAABB &upper, UIAABB &caret);
void GetInnerAABBs(UIAABB &lower, UIAABB &upper, UIAABB &caret);
void SetValFromScreenCoord(vec2 const & point);
};
void SliderContext::GetAABBs(UIAABB &a_lower, UIAABB &a_upper, UIAABB &a_caret)
{
vec2 globalPos = pSlider->GetGlobalPosition();
vec2 size = pSlider->GetSize();
if (!isVertical)
{
a_lower.position.x() = globalPos.x();
a_lower.position.y() = globalPos.y() + (size.y() - style.components[Style::Slider::c_LowerBar].height) / 2.0f;
a_lower.size.x() = GetLowerLength();
a_lower.size.y() = style.components[Style::Slider::c_LowerBar].height;
a_upper.position.x() = globalPos.x() + GetLowerLength();
a_upper.position.y() = globalPos.y() + (size.y() - style.components[Style::Slider::c_UpperBar].height) / 2.0f;
a_upper.size.x() = length - GetLowerLength();
a_upper.size.y() = style.components[Style::Slider::c_UpperBar].height;
a_caret.position.x() = globalPos.x() + GetLowerLength() - style.caretWidth / 2.0f;
a_caret.position.y() = globalPos.y() + (size.y() - style.components[Style::Slider::c_Caret].height) / 2.0f;
a_caret.size.x() = style.caretWidth;
a_caret.size.y() = style.components[Style::Slider::c_Caret].height;
}
else
{
a_lower.position.x() = globalPos.x() + (size.x() - style.components[Style::Slider::c_LowerBar].height) / 2.0f;
a_lower.position.y() = globalPos.y() + length - GetLowerLength();
a_lower.size.x() = style.components[Style::Slider::c_LowerBar].height;
a_lower.size.y() = GetLowerLength();
a_upper.position.x() = globalPos.x() + (size.x() - style.components[Style::Slider::c_UpperBar].height) / 2.0f;
a_upper.position.y() = globalPos.y();
a_upper.size.x() = style.components[Style::Slider::c_UpperBar].height;
a_upper.size.y() = length - GetLowerLength();
a_caret.position.x() = globalPos.x() + (size.x() - style.components[Style::Slider::c_Caret].height) / 2.0f;
a_caret.position.y() = globalPos.y() + length - GetLowerLength() - style.caretWidth / 2.0f;
a_caret.size.x() = style.components[Style::Slider::c_Caret].height;
a_caret.size.y() = style.caretWidth;
}
}
void SliderContext::GetInnerAABBs(UIAABB &a_lower, UIAABB &a_upper, UIAABB &a_caret)
{
GetAABBs(a_lower, a_upper, a_caret);
vec2 posOffsetLower(style.components[Style::Slider::c_LowerBar].borderWidth, style.components[Style::Slider::c_LowerBar].borderWidth);
vec2 posOffsetUpper(style.components[Style::Slider::c_UpperBar].borderWidth, style.components[Style::Slider::c_UpperBar].borderWidth);
vec2 posOffsetCaret(style.components[Style::Slider::c_Caret].borderWidth, style.components[Style::Slider::c_Caret].borderWidth);
a_lower.position += posOffsetLower;
a_upper.position += posOffsetUpper;
a_caret.position += posOffsetCaret;
a_lower.size -= 2.0f * posOffsetLower;
a_upper.size -= 2.0f * posOffsetUpper;
a_caret.size -= 2.0f * posOffsetCaret;
}
void SliderContext::SetValFromScreenCoord(vec2 const &point)
{
if (!isVertical)
{
float start = pSlider->GetGlobalPosition().x() + style.caretWidth / 2.0f;
value = (point.x() - start) / (length - style.caretWidth);
}
else
{
float start = pSlider->GetGlobalPosition().y() + length - style.caretWidth / 2.0f;
value = (start - point.y()) / (length - style.caretWidth);
}
if (value < 0.0f)
value = 0.0f;
else if (value > 1.0f)
value = 1.0f;
}
float SliderContext::GetLowerLength()
{
return style.caretWidth / 2.0f + ((length - style.caretWidth) * value);
}
//------------------------------------------------------------------------------------
// State class declarations
//------------------------------------------------------------------------------------
class SliderState
{
public:
SliderState(SliderContext * a_pData);
virtual ~SliderState() {};
virtual WidgetState QueryState() const = 0;
virtual SliderState * HandleMessage(Message *) = 0;
protected:
SliderContext * m_pContext;
};
class SliderStaticState : public SliderState
{
public:
SliderStaticState(SliderContext * a_pData, WidgetState);
~SliderStaticState() {}
WidgetState QueryState() const override;
SliderState * HandleMessage(Message * a_pMsg) override;
SliderState * HandleMessage(Message_GUI_PointerDown * a_pMsg);
SliderState * HandleMessage(Message_GUI_PointerMove * a_pMsg);
private:
WidgetState m_state;
};
class SliderActiveState : public SliderState
{
public:
SliderActiveState(SliderContext * a_pData, float caretOffset);
~SliderActiveState() {}
WidgetState QueryState() const override;
SliderState * HandleMessage(Message * a_pMsg) override;
SliderState * HandleMessage(Message_GUI_PointerMove * a_pMsg);
private:
float m_offset;
};
//------------------------------------------------------------------------------------
// SliderState
//------------------------------------------------------------------------------------
SliderState::SliderState(SliderContext * a_pData)
: m_pContext(a_pData)
{
}
//------------------------------------------------------------------------------------
// SliderStaticState
//------------------------------------------------------------------------------------
SliderStaticState::SliderStaticState(SliderContext * a_pData, WidgetState a_state)
: SliderState(a_pData)
, m_state(a_state)
{
}
WidgetState SliderStaticState::QueryState() const
{
return m_state;
}
SliderState * SliderStaticState::HandleMessage(Message * a_pMsg)
{
if (a_pMsg->GetCategory() != MC_GUI)
return nullptr;
SliderState * pResult = nullptr;
if (a_pMsg->GetID() == Message_GUI_PointerDown::GetStaticID())
pResult = HandleMessage(dynamic_cast<Message_GUI_PointerDown *>(a_pMsg));
else if (a_pMsg->GetID() == Message_GUI_PointerMove::GetStaticID())
pResult = HandleMessage(dynamic_cast<Message_GUI_PointerMove *>(a_pMsg));
return pResult;
}
SliderState * SliderStaticState::HandleMessage(Message_GUI_PointerDown * a_pMsg)
{
UIAABB aabb;
if (!m_pContext->pSlider->GetGlobalViewableArea(aabb))
return nullptr;
vec2 point((float)a_pMsg->x, (float)a_pMsg->y);
if (!PointInBox(point, aabb))
return nullptr;
UIAABB barLower = {};
UIAABB barUpper = {};
UIAABB caret = {};
m_pContext->GetAABBs(barLower, barUpper, caret);
if (PointInBox(point, caret))
{
a_pMsg->SetFlag(Message::Flag::Handled, true);
float caretOffset;
if (!m_pContext->isVertical)
caretOffset = aabb.position.x() + m_pContext->GetLowerLength() - point.x();
else
caretOffset = aabb.position.y() + m_pContext->length - m_pContext->GetLowerLength() - point.y();
return new SliderActiveState(m_pContext, caretOffset);
}
else if (PointInBox(point, barLower) || PointInBox(point, barUpper))
{
a_pMsg->SetFlag(Message::Flag::Handled, true);
m_pContext->SetValFromScreenCoord(point);
m_pContext->pSlider->NewValueClbk(m_pContext->value);
return new SliderActiveState(m_pContext, 0.0f);
}
return nullptr;
}
SliderState * SliderStaticState::HandleMessage(Message_GUI_PointerMove * a_pMsg)
{
vec2 point((float)a_pMsg->x, (float)a_pMsg->y);
UIAABB barLower = {};
UIAABB barUpper = {};
UIAABB caret = {};
m_pContext->GetAABBs(barLower, barUpper, caret);
bool isInside = PointInBox(vec2((float)a_pMsg->x, (float)a_pMsg->y), caret);
if (isInside)
a_pMsg->ConsumeHover();
if (isInside && (m_state == WidgetState::None))
{
m_state = WidgetState::HoverOn;
if (m_pContext->clbk_HoverOn != nullptr)
m_pContext->clbk_HoverOn();
}
if (!isInside && (m_state == WidgetState::HoverOn))
{
m_state = WidgetState::None;
if (m_pContext->clbk_HoverOff != nullptr)
m_pContext->clbk_HoverOff();
}
return nullptr;
}
//------------------------------------------------------------------------------------
// SliderActiveState
//------------------------------------------------------------------------------------
SliderActiveState::SliderActiveState(SliderContext * a_pData, float a_offset)
: SliderState(a_pData)
, m_offset(a_offset)
{
}
WidgetState SliderActiveState::QueryState() const
{
return WidgetState::HasFocus;
}
SliderState * SliderActiveState::HandleMessage(Message * a_pMsg)
{
if (a_pMsg->GetCategory() != MC_GUI)
return nullptr;
if (a_pMsg->GetID() == Message_GUI_PointerUp::GetStaticID())
{
a_pMsg->SetFlag(Message::Flag::Handled, true);
return new SliderStaticState(m_pContext, WidgetState::HoverOn);
}
if (a_pMsg->GetID() == Message_GUI_PointerMove::GetStaticID())
return HandleMessage(dynamic_cast<Message_GUI_PointerMove *>(a_pMsg));
return nullptr;
}
SliderState * SliderActiveState::HandleMessage(Message_GUI_PointerMove * a_pMsg)
{
vec2 point((float)a_pMsg->x, (float)a_pMsg->y);
m_pContext->SetValFromScreenCoord(point + vec2(m_offset, m_offset));
m_pContext->pSlider->NewValueClbk(m_pContext->value);
a_pMsg->SetFlag(Message::Flag::Handled, true);
return nullptr;
}
//------------------------------------------------------------------------------------
// SliderBase
//------------------------------------------------------------------------------------
class SliderBase::PIMPL
{
public:
PIMPL() : pState(nullptr), context() {}
~PIMPL() { delete pState; }
SliderState *pState;
SliderContext context;
};
SliderBase::SliderBase(vec2 const & a_position, float length, float a_value, Style::Slider const &style, bool isVertical, std::initializer_list<WidgetFlag> a_flags)
: Widget({WidgetFlag::NotResponsive,
WidgetFlag::StretchWidth
}, a_flags)
, m_pimpl(new PIMPL())
{
SetStyle(style);
m_pimpl->context.isVertical = isVertical;
if (m_pimpl->context.style.caretWidth < SLIDER_MIN_CARET_WIDTH)
m_pimpl->context.style.caretWidth = SLIDER_MIN_CARET_WIDTH;
m_pimpl->context.length = length;
if (m_pimpl->context.length < (m_pimpl->context.style.caretWidth + SLIDER_MIN_RUN_PIXELS))
m_pimpl->context.length = m_pimpl->context.style.caretWidth + SLIDER_MIN_RUN_PIXELS;
m_pimpl->context.value = a_value;
if (m_pimpl->context.value < 0.0f)
m_pimpl->context.value = 0.0f;
else if (m_pimpl->context.value > 1.0f)
m_pimpl->context.value = 1.0f;
m_pimpl->context.position = a_position;
m_pimpl->context.pSlider = this;
m_pimpl->pState = new SliderStaticState(&m_pimpl->context, WidgetState::None);
}
SliderBase::~SliderBase()
{
delete m_pimpl;
}
Style::Slider const &SliderBase::GetDefaultStyle()
{
return s_style;
}
Style::Slider const &SliderBase::GetStyle() const
{
return m_pimpl->context.style;
}
void SliderBase::SetStyle(Style::Slider const &style)
{
m_pimpl->context.style = style;
}
void SliderBase::_HandleMessage(Message * a_pMsg)
{
SliderState *pNewState = m_pimpl->pState->HandleMessage(a_pMsg);
if (pNewState != nullptr)
{
delete m_pimpl->pState;
m_pimpl->pState = pNewState;
}
}
void SliderBase::Draw()
{
int colourIndex = m_pimpl->pState->QueryState() == WidgetState::None ? (int)Style::Slider::s_Default : (int)Style::Slider::s_Hover;
UIAABB viewableWindow;
if (!GetGlobalViewableArea(viewableWindow))
return;
::DgE::Renderer::SetSissorBox((int)viewableWindow.position.x(), (int)viewableWindow.position.y(), (int)viewableWindow.size.x(), (int)viewableWindow.size.y());
UIAABB lower, upper, caret;
m_pimpl->context.GetInnerAABBs(lower, upper, caret);
Colour lb = m_pimpl->context.style.colours[Style::Slider::c_LowerBar][colourIndex].face;
Colour ub = m_pimpl->context.style.colours[Style::Slider::c_UpperBar][colourIndex].face;
Colour c = m_pimpl->context.style.colours[Style::Slider::c_Caret][colourIndex].face;
if (m_pimpl->context.style.components[Style::Slider::c_LowerBar].borderWidth == 0.0f)
Renderer::DrawBox(lower, m_pimpl->context.style.colours[Style::Slider::c_LowerBar][colourIndex].face);
else
Renderer::DrawBoxWithBorder(lower,
m_pimpl->context.style.components[Style::Slider::c_LowerBar].borderWidth,
m_pimpl->context.style.colours[Style::Slider::c_LowerBar][colourIndex].face,
m_pimpl->context.style.colours[Style::Slider::c_LowerBar][colourIndex].border);
if (m_pimpl->context.style.components[Style::Slider::c_UpperBar].borderWidth == 0.0f)
Renderer::DrawBox(upper, m_pimpl->context.style.colours[Style::Slider::c_UpperBar][colourIndex].face);
else
Renderer::DrawBoxWithBorder(upper,
m_pimpl->context.style.components[Style::Slider::c_UpperBar].borderWidth,
m_pimpl->context.style.colours[Style::Slider::c_UpperBar][colourIndex].face,
m_pimpl->context.style.colours[Style::Slider::c_UpperBar][colourIndex].border);
if (m_pimpl->context.style.components[Style::Slider::c_Caret].borderWidth == 0.0f)
Renderer::DrawBox(caret, m_pimpl->context.style.colours[Style::Slider::c_Caret][colourIndex].face);
else
Renderer::DrawBoxWithBorder(lower,
m_pimpl->context.style.components[Style::Slider::c_Caret].borderWidth,
m_pimpl->context.style.colours[Style::Slider::c_Caret][colourIndex].face,
m_pimpl->context.style.colours[Style::Slider::c_Caret][colourIndex].border);
}
void SliderBase::BindHoverOn(std::function<void()> a_fn)
{
m_pimpl->context.clbk_HoverOn = a_fn;
}
void SliderBase::BindHoverOff(std::function<void()> a_fn)
{
m_pimpl->context.clbk_HoverOff = a_fn;
}
WidgetState SliderBase::QueryState() const
{
return m_pimpl->pState->QueryState();
}
float SliderBase::SetNormalisedValue(float a_val)
{
if (a_val < 0.0f)
a_val = 0.0f;
else if (a_val > 1.0f)
a_val = 1.0f;
m_pimpl->context.value = a_val;
return m_pimpl->context.value;
}
Widget * SliderBase::GetParent() const
{
return m_pimpl->context.pParent;
}
void SliderBase::SetParent(Widget * a_pParent)
{
m_pimpl->context.pParent = a_pParent;
}
void SliderBase::SetLocalPosition(vec2 const & a_pos)
{
m_pimpl->context.position = a_pos;
}
void SliderBase::SetSize(vec2 const & a_size)
{
m_pimpl->context.length = a_size.x();
if (m_pimpl->context.length < (m_pimpl->context.style.caretWidth + SLIDER_MIN_RUN_PIXELS))
m_pimpl->context.length = (m_pimpl->context.style.caretWidth + SLIDER_MIN_RUN_PIXELS);
}
vec2 SliderBase::GetLocalPosition()
{
return m_pimpl->context.position;
}
vec2 SliderBase::GetSize()
{
float c = m_pimpl->context.style.components[Style::Slider::c_Caret].height;
float l = m_pimpl->context.style.components[Style::Slider::c_LowerBar].height;
float u = m_pimpl->context.style.components[Style::Slider::c_UpperBar].height;
float h = c;
if (l > h) h = l;
if (u > h) h = u;
int const i = m_pimpl->context.isVertical ? 1 : 0;
int const j = (i + 1) & 1;
vec2 result;
result[i] = m_pimpl->context.length;
result[j] = h;
return result;
}
}
}
|
// Copyright (c) 2009-2018 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
#include <hoomd/HOOMDMath.h>
#include "../DEMEvaluator.h"
#include "../NoFriction.h"
#include "../WCAPotential.h"
#include "../SWCAPotential.h"
#include "../DEM2DForceCompute.h"
#include "../DEM2DForceComputeGPU.h"
#include "../DEM3DForceCompute.h"
#include "../DEM3DForceComputeGPU.h"
#include <hoomd/extern/pybind/include/pybind11/pybind11.h>
namespace py = pybind11;
void export_NF_WCA_2D(py::module& m)
{
typedef WCAPotential<Scalar, Scalar4, NoFriction<Scalar> > WCA;
typedef DEM2DForceCompute<Scalar, Scalar4, WCA> WCA_DEM_2D;
py::class_<WCA_DEM_2D, std::shared_ptr<WCA_DEM_2D> >(m, "WCADEM2D", py::base<ForceCompute>())
.def(py::init< std::shared_ptr<SystemDefinition>, std::shared_ptr<NeighborList>, Scalar, WCA>())
.def("setParams", &WCA_DEM_2D::setParams)
.def("setRcut", &WCA_DEM_2D::setRcut)
;
#ifdef ENABLE_CUDA
typedef DEM2DForceComputeGPU<Scalar, Scalar2, Scalar4, WCA> WCA_DEM_2D_GPU;
py::class_<WCA_DEM_2D_GPU, std::shared_ptr<WCA_DEM_2D_GPU> >(m, "WCADEM2DGPU", py::base<WCA_DEM_2D>())
.def(py::init< std::shared_ptr<SystemDefinition>, std::shared_ptr<NeighborList>, Scalar, WCA>())
.def("setParams", &WCA_DEM_2D_GPU::setParams)
.def("setRcut", &WCA_DEM_2D_GPU::setRcut)
.def("setAutotunerParams", &WCA_DEM_2D_GPU::setAutotunerParams)
;
#endif
}
|
// This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#include "lgedgeiter.hpp"
#include "lgraph.hpp"
#include "sub_node.hpp"
void LGraph::each_sorted_graph_io(std::function<void(Node_pin &pin, Port_ID pos)> f1, bool hierarchical) {
if (node_internal.size() < Node::Hardcoded_output_nid)
return;
std::vector<std::pair<Node_pin, Port_ID>> pin_pair;
auto hidx = hierarchical? Hierarchy_tree::root_index() : Hierarchy_tree::invalid_index();
auto out = Node(this, hidx, Node::Hardcoded_output_nid);
for (auto &o_pin : out.out_setup_pins()) {
auto pos = get_self_sub_node().get_graph_pos_from_instance_pid(o_pin.get_pid());
pin_pair.emplace_back(std::make_pair(o_pin, pos));
}
auto inp = Node(this, hidx, Node::Hardcoded_input_nid);
for (auto &i_pin : inp.out_setup_pins()) {
auto pos = get_self_sub_node().get_graph_pos_from_instance_pid(i_pin.get_pid());
pin_pair.emplace_back(std::make_pair(i_pin, pos));
}
std::sort(pin_pair.begin(), pin_pair.end(), [](const std::pair<Node_pin, Port_ID> &a, const std::pair<Node_pin, Port_ID> &b) {
if (a.second == Port_invalid && b.second == Port_invalid)
return a.first.get_pid() < b.first.get_pid();
if (a.second == Port_invalid)
return true;
if (b.second == Port_invalid)
return false;
return a.second < b.second;
});
for (auto &pp : pin_pair) {
f1(pp.first, pp.second);
}
}
void LGraph::each_pin(const Node_pin &dpin, std::function<bool(Index_ID idx)> f1) const {
Index_ID first_idx2 = dpin.get_idx();
Index_ID idx2 = first_idx2;
bool should_not_find = false;
while (true) {
I(!should_not_find);
bool cont = f1(idx2);
if (!cont)
return;
do{
if (node_internal[idx2].is_last_state()) {
#ifndef NDEBUG
idx2 = dpin.get_node().get_nid();
should_not_find = true; // loop and try the others (should not have it before root)
#else
idx2 = node_internal[idx2].get_nid();
#endif
}else{
idx2 = node_internal[idx2].get_next();
}
if (idx2==first_idx2)
return;
} while (node_internal[idx2].get_dst_pid() != dpin.get_pid());
}
}
void LGraph::each_graph_input(std::function<void(Node_pin &pin)> f1, bool hierarchical) {
if (node_internal.size() < Node::Hardcoded_output_nid)
return;
auto hidx = hierarchical? Hierarchy_tree::root_index() : Hierarchy_tree::invalid_index();
auto node = Node(this, hidx, Node::Hardcoded_input_nid);
for (auto &pin : node.out_setup_pins()) {
f1(pin);
}
}
void LGraph::each_graph_output(std::function<void(Node_pin &pin)> f1, bool hierarchical) {
if (node_internal.size() < Node::Hardcoded_output_nid)
return;
auto hidx = hierarchical? Hierarchy_tree::root_index() : Hierarchy_tree::invalid_index();
auto node = Node(this, hidx, Node::Hardcoded_output_nid);
for (auto &pin : node.out_setup_pins()) {
f1(pin);
}
}
void LGraph::each_sub_fast_direct(const std::function<bool(Node &, Lg_type_id)> fn) {
const auto &m = get_down_nodes_map();
for (auto it = m.begin(), end = m.end(); it != end; ++it) {
Index_ID cid = it->first.nid;
I(cid);
I(node_internal[cid].is_node_state());
I(node_internal[cid].is_master_root());
auto node = Node(this, it->first);
bool cont = fn(node, it->second);
if (!cont)
return;
}
}
void LGraph::each_sub_unique_fast(const std::function<bool(Node &, Lg_type_id)> fn) {
const auto &m = get_down_nodes_map();
std::set<Lg_type_id> visited;
for (auto it = m.begin(), end = m.end(); it != end; ++it) {
Index_ID cid = it->first.nid;
I(cid);
I(node_internal[cid].is_node_state());
I(node_internal[cid].is_master_root());
auto node = Node(this, it->first);
bool cont = true;
if (visited.find(it->second) == visited.end()) {
cont = fn(node, it->second);
visited.insert(it->second);
}
if (!cont) return;
}
}
|
#include "Conversion/Messages/actionlib_msgs/ActionlibMsgsGoalStatusConverter.h"
UActionlibMsgsGoalStatusConverter::UActionlibMsgsGoalStatusConverter(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
_MessageType = "actionlib_msgs/GoalStatus";
}
bool UActionlibMsgsGoalStatusConverter::ConvertIncomingMessage(const ROSBridgePublishMsg* message, TSharedPtr<FROSBaseMsg> &BaseMsg)
{
auto g = new ROSMessages::actionlib_msgs::GoalStatus();
BaseMsg = TSharedPtr<FROSBaseMsg>(g);
return _bson_extract_child_goal_status(message->full_msg_bson_, "msg", g);
}
bool UActionlibMsgsGoalStatusConverter::ConvertOutgoingMessage(TSharedPtr<FROSBaseMsg> BaseMsg, bson_t** message)
{
auto GoalStatus = StaticCastSharedPtr<ROSMessages::actionlib_msgs::GoalStatus>(BaseMsg);
*message = new bson_t;
bson_init(*message);
_bson_append_goal_status(*message, GoalStatus.Get());
return true;
}
|
#include <allegro_flare/bitmap_object.h>
namespace allegro_flare
{
BitmapObject *BitmapObject::dummy = NULL;
}
|
// This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2003, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
//! rcsid="$Id: PointerManager.cc 7577 2010-02-21 09:46:39Z craftit $"
//! lib=RavlCore
//! file="Ravl/Core/System/PointerManager.cc"
#include "Ravl/PointerManager.hh"
#define DODEBUG 0
#if DODEBUG
#define ONDEBUG(x) x
#else
#define ONDEBUG(x)
#endif
namespace RavlN {
//:----------------------------------------------------
//: Destructor.
StoredPointerC::~StoredPointerC() {
ONDEBUG(cerr << "StoredPointerC::~StoredPointerC(), Called. " << (void *) actions << " " << (void *) obj << "\n");
if(actions != 0 && obj != 0)
actions->Free(obj);
}
//:----------------------------------------------------
//: Default constructor.
PointerManagerBodyC::PointerManagerBodyC(bool forSave)
: idAlloc(0)
{}
//: Destructor.
PointerManagerBodyC::~PointerManagerBodyC()
{ ONDEBUG(cerr << "PointerManagerBodyC::~PointerManagerBodyC(), Called. \n"); }
//:----------------------------------------------------
BinOStreamC &operator<<(BinOStreamC &strm,IOPtrC obj) {
if(!strm.PointerManager().IsValid())
strm.PointerManager() = PointerManagerC(true);
PointerManagerC mgr(strm.PointerManager());
SizeT id;
if(mgr.Lookup(obj,id)) { // Seen this object already ?
ONDEBUG(cerr << "Storing id " << id << " from " << *((void **)obj.Pointer()) << "\n");
strm << id;
} else {
// Not seen before, save id then object.
id = mgr.Insert(obj);
ONDEBUG(cerr << "Storing data with id " << id << " \n");
strm << id;
obj.Save(strm);
}
return strm;
}
//: Load managed pointer from a stream.
BinIStreamC &operator>>(BinIStreamC &strm,IOPtrC obj) {
if(!strm.PointerManager().IsValid())
strm.PointerManager() = PointerManagerC(false);
PointerManagerC mgr(strm.PointerManager());
SizeT id;
strm >> id;
StoredPointerC *ptr = mgr.Lookup(id);
if(ptr != 0) { // Seen this object already ?
ONDEBUG(cerr << "Loading id " << id << " \n");
obj.Assign(*ptr);
} else {
// Not seen before, save id then object.
ONDEBUG(cerr << "Loading data with id " << id << "\n");
obj.Load(strm);
mgr.Insert(id,obj);
}
return strm;
}
}
|
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// @ref gtx_perpendicular
/// @file glm/gtx/perpendicular.hpp
/// @date 2005-12-21 / 2011-06-07
/// @author Christophe Riccio
///
/// @see core (dependence)
/// @see gtx_projection (dependence)
///
/// @defgroup gtx_perpendicular GLM_GTX_perpendicular
/// @ingroup gtx
///
/// @brief Perpendicular of a vector from other one
///
/// <glm/gtx/perpendicular.hpp> need to be included to use these functionalities.
///////////////////////////////////////////////////////////////////////////////////
#ifndef GLM_GTX_perpendicular
#define GLM_GTX_perpendicular
// Dependency:
#include "../glm.hpp"
#include "../gtx/projection.hpp"
#if(defined(GLM_MESSAGES) && !defined(GLM_EXT_INCLUDED))
# pragma message("GLM: GLM_GTX_perpendicular extension included")
#endif
namespace glm
{
/// @addtogroup gtx_perpendicular
/// @{
//! Projects x a perpendicular axis of Normal.
//! From GLM_GTX_perpendicular extension.
template <typename vecType>
GLM_FUNC_DECL vecType perp(
vecType const & x,
vecType const & Normal);
/// @}
}//namespace glm
#include "perpendicular.inl"
#endif//GLM_GTX_perpendicular
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_83_goodB2G.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml
Template File: sources-vasinks-83_goodB2G.tmpl.cpp
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Copy a fixed string into data
* Sinks: vfprintf
* GoodSink: vfwprintf with a format string
* BadSink : vfwprintf without a format string
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITGOOD
#include <stdarg.h>
#include "std_testcase.h"
#include "CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_83.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
namespace CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_83
{
CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_83_goodB2G::CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_83_goodB2G(wchar_t * dataCopy)
{
data = dataCopy;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
static void goodB2GVaSink(wchar_t * data, ...)
{
{
va_list args;
va_start(args, data);
/* FIX: Specify the format disallowing a format string vulnerability */
vfwprintf(stdout, L"%s", args);
va_end(args);
}
}
CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_83_goodB2G::~CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_83_goodB2G()
{
goodB2GVaSink(data, data);
}
}
#endif /* OMITGOOD */
|
// NOTE: this works on Linux Mint 19.3... You may need to modify it to work on a non-Linux OS
#include <iostream>
#include "Color.h"
//gets user input
void getInput(std::string username, std::string message = "", Color::Modifier userColor = (Color::FG_BLUE), Color::Modifier defColor = (Color::FG_DEFAULT)){
std::string temp;
std::cout << userColor << username << " " << defColor << message;
getline(std::cin, temp);
}
// displays messages
void showMessage(std::string username, std::string message, bool endLine = false, Color::Modifier userColor = (Color::FG_BLUE), Color::Modifier defColor = (Color::FG_DEFAULT)){
if (endLine){
std::cout << userColor << username << " " << defColor << message << std::endl;
}else{
std::cout << userColor << username << " " << defColor << message;
}
}
int main(int argc, char const *argv[])
{
system("echo off"); // so it doesn't repeat system commands
system("clear"); // cls in windows
// allow us to change the color of the output
Color::Modifier blue(Color::FG_BLUE);
Color::Modifier def(Color::FG_DEFAULT);
std::string username = "eternm##$:";
std::string connectedUsername = username + "BKUW300PS345672:";
std::cout << "\t\tWelcome to your terminal." << std::endl;
getInput(username);
getInput(username);
showMessage(connectedUsername, " 4 root 0 0 87456 14m 11m S 0.0 3.0 0:00.55 termial", true);
showMessage(connectedUsername, " 1772 root 0 -20 2415 2016 1312 S 0.0 0.5 0:00.17 init", true);
showMessage(connectedUsername, " 1 root 0 0 0 0 0 S 0.0 1.2 0:00.00 cpuset ./01dat", true);
showMessage(connectedUsername, " 29 root 0 0 0 0 0 S 0.0 5.0 0:00.00 evilcorpwdthread", true);
showMessage(connectedUsername, " 4098 root 0 0 0 0 0 S 0.0 0.4 0:00.05 evilcorpwdthread/0:0", true);
showMessage(connectedUsername, " 19 root 0 0 0 0 0 S 0.0 0.9 0:00.90 evilcorpwdthread/u:0", true);
getInput(connectedUsername);
showMessage(username, "Logout...", true);
getInput(username);
getInput(username, "You are about to hack the govenment... Continue? [y/n]: ");
for (int i = 0; i <= 100; i+=20){
std::cout << blue << username << " " << def << "Hacking user... " << i << "%" << std::endl;
system("sleep 1");
}
getInput(username);
return 0;
}
|
#include "malloc-extensions.h"
#include "../snmalloc.h"
using namespace snmalloc;
void get_malloc_info_v1(malloc_info_v1* stats)
{
auto next_memory_usage = default_memory_provider().memory_usage();
stats->current_memory_usage = next_memory_usage.first;
stats->peak_memory_usage = next_memory_usage.second;
}
|
/**
* @file unit_test_fnd_numeric_ranges_iota.cpp
*
* @brief ranges::iota のテスト
*
* @author myoukaku
*/
#include <bksge/fnd/numeric/ranges/iota.hpp>
#include <bksge/fnd/iterator/begin.hpp>
#include <bksge/fnd/iterator/end.hpp>
#include <gtest/gtest.h>
#include "constexpr_test.hpp"
#include "ranges_test.hpp"
namespace bksge_numeric_test
{
namespace ranges_iota_test
{
#define VERIFY(...) if (!(__VA_ARGS__)) { return false; }
// iota(first, last, value)
inline BKSGE_CXX14_CONSTEXPR bool test01()
{
namespace ranges = bksge::ranges;
{
int a[5]{};
auto ret = ranges::iota(bksge::begin(a), bksge::end(a), 0);
VERIFY(ret == bksge::end(a));
VERIFY(a[0] == 0);
VERIFY(a[1] == 1);
VERIFY(a[2] == 2);
VERIFY(a[3] == 3);
VERIFY(a[4] == 4);
}
{
int a[6]{};
auto ret = ranges::iota(bksge::begin(a), bksge::end(a), 10);
VERIFY(ret == bksge::end(a));
VERIFY(a[0] == 10);
VERIFY(a[1] == 11);
VERIFY(a[2] == 12);
VERIFY(a[3] == 13);
VERIFY(a[4] == 14);
VERIFY(a[5] == 15);
}
{
int a[6]{};
auto ret = ranges::iota(bksge::begin(a), bksge::begin(a)+3, 10);
VERIFY(ret == bksge::begin(a)+3);
VERIFY(a[0] == 10);
VERIFY(a[1] == 11);
VERIFY(a[2] == 12);
VERIFY(a[3] == 0);
VERIFY(a[4] == 0);
VERIFY(a[5] == 0);
}
return true;
}
// iota(rng, value)
inline BKSGE_CXX14_CONSTEXPR bool test02()
{
namespace ranges = bksge::ranges;
{
int a[3]{};
auto ret = ranges::iota(a, 0);
VERIFY(ret == bksge::end(a));
VERIFY(a[0] == 0);
VERIFY(a[1] == 1);
VERIFY(a[2] == 2);
}
{
int a[4]{};
test_range<int, output_iterator_wrapper> ra(a);
auto ret = ranges::iota(ra, 42);
VERIFY(ret == bksge::end(ra));
VERIFY(a[0] == 42);
VERIFY(a[1] == 43);
VERIFY(a[2] == 44);
VERIFY(a[3] == 45);
}
return true;
}
#undef VERIFY
GTEST_TEST(NumericTest, RangesIotaTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(test01());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(test02());
}
} // namespace ranges_iota_test
} // namespace bksge_numeric_test
|
// 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 <algorithm>
#include <cstdlib>
#include <limits>
#include <random>
#include <string>
#include <vector>
#include <boost/scoped_ptr.hpp>
#include "common/object-pool.h"
#include "runtime/bufferpool/reservation-tracker.h"
#include "runtime/bufferpool/suballocator.h"
#include "runtime/test-env.h"
#include "service/fe-support.h"
#include "testutil/death-test-util.h"
#include "testutil/gtest-util.h"
#include "testutil/rand-util.h"
#include "util/bit-util.h"
#include "common/names.h"
using std::lognormal_distribution;
using std::mt19937;
using std::shuffle;
using std::uniform_int_distribution;
namespace impala {
class SuballocatorTest : public ::testing::Test {
public:
virtual void SetUp() override {
test_env_.reset(new TestEnv);
test_env_->DisableBufferPool();
ASSERT_OK(test_env_->Init());
RandTestUtil::SeedRng("SUBALLOCATOR_TEST_SEED", &rng_);
profile_ = RuntimeProfile::Create(&obj_pool_, "test profile");
}
virtual void TearDown() override {
for (unique_ptr<BufferPool::ClientHandle>& client : clients_) {
buffer_pool_->DeregisterClient(client.get());
}
clients_.clear();
buffer_pool_.reset();
global_reservation_.Close();
obj_pool_.Clear();
}
/// The minimum buffer size used in most tests. Chosen so that the buffer is split
/// at least several ways.
const static int64_t TEST_BUFFER_LEN = Suballocator::MIN_ALLOCATION_BYTES * 16;
protected:
/// Initialize 'buffer_pool_' and 'global_reservation_' with a limit of 'total_mem'
/// bytes of buffers of minimum length 'min_buffer_len'.
void InitPool(int64_t min_buffer_len, int total_mem) {
global_reservation_.InitRootTracker(nullptr, total_mem);
buffer_pool_.reset(
new BufferPool(test_env_->metrics(), min_buffer_len, total_mem, 0));
}
/// Register a client with 'buffer_pool_'. The client is automatically deregistered
/// and freed at the end of the test.
void RegisterClient(
ReservationTracker* parent_reservation, BufferPool::ClientHandle** client) {
clients_.push_back(make_unique<BufferPool::ClientHandle>());
*client = clients_.back().get();
ASSERT_OK(buffer_pool_->RegisterClient("test client", NULL, parent_reservation, NULL,
numeric_limits<int64_t>::max(), profile_, *client));
}
/// Assert that the memory for all of the suballocations is writable and disjoint by
/// writing a distinct value to each suballocation and reading it back. Only works for
/// suballocations at least 8 bytes in size.
void AssertMemoryValid(const vector<unique_ptr<Suballocation>>& allocs);
/// Free all the suballocations and clear the vector.
static void FreeAllocations(
Suballocator* allocator, vector<unique_ptr<Suballocation>>* allocs) {
for (auto& alloc : *allocs) allocator->Free(move(alloc));
allocs->clear();
}
static void ExpectReservationUnused(BufferPool::ClientHandle* client) {
EXPECT_EQ(client->GetUsedReservation(), 0) << client->DebugString();
}
BufferPool* buffer_pool() { return buffer_pool_.get(); }
/// Pool for objects with per-test lifetime. Cleared after every test.
ObjectPool obj_pool_;
/// The top-level global reservation. Initialized in InitPool() and closed after every
/// test.
ReservationTracker global_reservation_;
/// The buffer pool. Initialized in InitPool() and reset after every test.
scoped_ptr<BufferPool> buffer_pool_;
/// Clients for the buffer pool. Deregistered and freed after every test.
vector<unique_ptr<BufferPool::ClientHandle>> clients_;
boost::scoped_ptr<TestEnv> test_env_;
/// Global profile - recreated for every test.
RuntimeProfile* profile_;
/// Per-test random number generator. Seeded before every test.
mt19937 rng_;
};
const int64_t SuballocatorTest::TEST_BUFFER_LEN;
/// Basic test to make sure that we can make multiple suballocations of the same size
/// while using the expected number of buffers.
TEST_F(SuballocatorTest, SameSizeAllocations) {
const int64_t TOTAL_MEM = TEST_BUFFER_LEN * 100;
InitPool(TEST_BUFFER_LEN, TOTAL_MEM);
BufferPool::ClientHandle* client;
RegisterClient(&global_reservation_, &client);
Suballocator allocator(buffer_pool(), client, TEST_BUFFER_LEN);
vector<unique_ptr<Suballocation>> allocs;
// Make suballocations smaller than the buffer size.
const int64_t ALLOC_SIZE = TEST_BUFFER_LEN / 4;
int64_t allocated_mem = 0;
while (allocated_mem < TOTAL_MEM) {
allocs.emplace_back();
ASSERT_OK(allocator.Allocate(ALLOC_SIZE, &allocs.back()));
ASSERT_TRUE(allocs.back() != nullptr) << ALLOC_SIZE << " " << allocated_mem << " "
<< global_reservation_.DebugString();
allocated_mem += ALLOC_SIZE;
}
// Attempts to allocate more memory should fail gracefully.
const int64_t MAX_ALLOC_SIZE = 1L << 24;
for (int alloc_size = 1; alloc_size <= MAX_ALLOC_SIZE; alloc_size *= 2) {
unique_ptr<Suballocation> failed_alloc;
ASSERT_OK(allocator.Allocate(alloc_size, &failed_alloc));
ASSERT_TRUE(failed_alloc == nullptr) << alloc_size << " " << allocated_mem << " "
<< global_reservation_.DebugString();
}
AssertMemoryValid(allocs);
// Check that reservation usage matches the amount allocated.
EXPECT_EQ(client->GetUsedReservation(), allocated_mem)
<< global_reservation_.DebugString();
FreeAllocations(&allocator, &allocs);
ExpectReservationUnused(client);
}
/// Check behaviour of zero-length allocation.
TEST_F(SuballocatorTest, ZeroLengthAllocation) {
const int64_t TOTAL_MEM = TEST_BUFFER_LEN * 100;
InitPool(TEST_BUFFER_LEN, TOTAL_MEM);
BufferPool::ClientHandle* client;
RegisterClient(&global_reservation_, &client);
Suballocator allocator(buffer_pool(), client, TEST_BUFFER_LEN);
unique_ptr<Suballocation> alloc;
// Zero-length allocations are allowed and rounded up to the minimum size.
ASSERT_OK(allocator.Allocate(0, &alloc));
ASSERT_TRUE(alloc != nullptr) << global_reservation_.DebugString();
EXPECT_EQ(alloc->len(), Suballocator::MIN_ALLOCATION_BYTES);
allocator.Free(move(alloc));
ExpectReservationUnused(client);
}
/// Check behaviour of out-of-range allocation.
TEST_F(SuballocatorTest, OutOfRangeAllocations) {
const int64_t TOTAL_MEM = TEST_BUFFER_LEN * 100;
InitPool(TEST_BUFFER_LEN, TOTAL_MEM);
BufferPool::ClientHandle* client;
RegisterClient(&global_reservation_, &client);
Suballocator allocator(buffer_pool(), client, TEST_BUFFER_LEN);
unique_ptr<Suballocation> alloc;
// Negative allocations are not allowed and cause a DCHECK.
IMPALA_ASSERT_DEBUG_DEATH(allocator.Allocate(-1, &alloc), "");
// Too-large allocations fail gracefully.
ASSERT_FALSE(allocator.Allocate(Suballocator::MAX_ALLOCATION_BYTES + 1, &alloc).ok())
<< global_reservation_.DebugString();
ExpectReservationUnused(client);
}
/// Basic test to make sure that non-power-of-two suballocations are handled as expected
/// by rounding up.
TEST_F(SuballocatorTest, NonPowerOfTwoAllocations) {
const int64_t TOTAL_MEM = TEST_BUFFER_LEN * 128;
InitPool(TEST_BUFFER_LEN, TOTAL_MEM);
BufferPool::ClientHandle* client;
RegisterClient(&global_reservation_, &client);
Suballocator allocator(buffer_pool(), client, TEST_BUFFER_LEN);
vector<int64_t> alloc_sizes;
// Multiply by 7 to get some unusual sizes.
for (int64_t alloc_size = 7; BitUtil::RoundUpToPowerOfTwo(alloc_size) <= TOTAL_MEM;
alloc_size *= 7) {
alloc_sizes.push_back(alloc_size);
}
// Test edge cases around power-of-two-sizes.
for (int64_t power_of_two = 2; power_of_two <= TOTAL_MEM; power_of_two *= 2) {
alloc_sizes.push_back(power_of_two - 1);
if (power_of_two != TOTAL_MEM) alloc_sizes.push_back(power_of_two + 1);
}
for (int64_t alloc_size : alloc_sizes) {
unique_ptr<Suballocation> alloc;
ASSERT_OK(allocator.Allocate(alloc_size, &alloc));
ASSERT_TRUE(alloc != nullptr) << alloc_size << " "
<< global_reservation_.DebugString();
// Check that it was rounded up to a power-of-two.
EXPECT_EQ(alloc->len(), max(Suballocator::MIN_ALLOCATION_BYTES,
BitUtil::RoundUpToPowerOfTwo(alloc_size)));
EXPECT_EQ(max(TEST_BUFFER_LEN, alloc->len()), client->GetUsedReservation())
<< global_reservation_.DebugString();
memset(alloc->data(), 0, alloc->len()); // Check memory is writable.
allocator.Free(move(alloc));
}
ExpectReservationUnused(client);
}
/// Test that simulates hash table's patterns of doubling suballocations and validates
/// that memory does not become fragmented.
TEST_F(SuballocatorTest, DoublingAllocations) {
const int64_t TOTAL_MEM = TEST_BUFFER_LEN * 100;
InitPool(TEST_BUFFER_LEN, TOTAL_MEM);
BufferPool::ClientHandle* client;
RegisterClient(&global_reservation_, &client);
Suballocator allocator(buffer_pool(), client, TEST_BUFFER_LEN);
const int NUM_ALLOCS = 16;
vector<unique_ptr<Suballocation>> allocs(NUM_ALLOCS);
// Start with suballocations smaller than the page.
for (int64_t curr_alloc_size = TEST_BUFFER_LEN / 8;
curr_alloc_size * NUM_ALLOCS < TOTAL_MEM; curr_alloc_size *= 2) {
// Randomise the order of suballocations so that coalescing happens in different ways.
shuffle(allocs.begin(), allocs.end(), rng_);
for (unique_ptr<Suballocation>& alloc : allocs) {
unique_ptr<Suballocation> old_alloc = move(alloc);
ASSERT_OK(allocator.Allocate(curr_alloc_size, &alloc));
if (old_alloc != nullptr) allocator.Free(move(old_alloc));
}
AssertMemoryValid(allocs);
// Test that the memory isn't fragmented more than expected. In the worst case, the
// suballocations should require an extra page.
//
// If curr_alloc_size is at least the buffer size, there is no fragmentation because
// all previous suballocations are coalesced and freed, and all new suballocations
// are backed by a newly-allocated buffer.
//
// If curr_alloc_size is less than the buffer size, we lose at most a buffer to
// fragmentation because previous suballocations are incrementally freed in a way
// such that they can always be coalesced and reused. At least N/2 out of N of the
// Free() calls in an iteration result in the free memory being coalesced. This is
// because either the buddy is freed earlier or later, and the coalescing must happen
// either in the current Free() call or a later Free() call. Therefore at least
// N/2 - 1 out of N Allocate() calls follow a Free() call that coalesced memory
// and can therefore alway recycle a coalesced suballocation instead of allocating
// additional buffers.
//
// In the worst case we end up with two buffers with gaps: one buffer carried over
// from the previous iteration with a single curr_alloc_size gap (if the last Free()
// coalesced two buddies of curr_alloc_size / 2) and one buffer with only
// 'curr_alloc_size' bytes in use (if an Allocate() call couldn't recycle memory and
// had to allocate a new buffer).
EXPECT_LE(client->GetUsedReservation(),
TEST_BUFFER_LEN + max(TEST_BUFFER_LEN, curr_alloc_size * NUM_ALLOCS));
}
// Check that reservation usage behaves as expected.
FreeAllocations(&allocator, &allocs);
ExpectReservationUnused(client);
}
/// Do some randomised testing of the allocator. Simulate some interesting patterns with
/// a mix of long and short runs of suballocations of variable size. Try to ensure that we
/// spend some time with the allocator near its upper limit, where most suballocations
/// will fail, and also in other parts of its range.
TEST_F(SuballocatorTest, RandomAllocations) {
const int64_t TOTAL_MEM = TEST_BUFFER_LEN * 1000;
InitPool(TEST_BUFFER_LEN, TOTAL_MEM);
BufferPool::ClientHandle* client;
RegisterClient(&global_reservation_, &client);
Suballocator allocator(buffer_pool(), client, TEST_BUFFER_LEN);
vector<unique_ptr<Suballocation>> allocs;
int64_t allocated_mem = 0;
for (int iter = 0; iter < 1000; ++iter) {
// We want to make runs of suballocations and frees. Use lognormal distribution so
// that runs are mostly short, but there are some long runs mixed in.
int num_allocs = max(1, static_cast<int>(lognormal_distribution<double>(3, 1)(rng_)));
const bool alloc = uniform_int_distribution<int>(0, 1)(rng_);
if (alloc) {
const int64_t remaining_mem_per_alloc = (TOTAL_MEM - allocated_mem) / num_allocs;
// Fraction is ~0.12 on average but sometimes ranges above 1.0 so that we'll hit the
// max reservation and suballocations will fail.
double fraction_to_alloc = lognormal_distribution<double>(2, 1)(rng_) / 100.;
int64_t alloc_size = max(8L, BitUtil::RoundUpToPowerOfTwo(static_cast<int64_t>(
fraction_to_alloc * remaining_mem_per_alloc)));
for (int i = 0; i < num_allocs; ++i) {
unique_ptr<Suballocation> alloc;
ASSERT_OK(allocator.Allocate(alloc_size, &alloc));
if (alloc != nullptr) {
EXPECT_EQ(alloc->len(), max(alloc_size, Suballocator::MIN_ALLOCATION_BYTES));
allocated_mem += alloc->len();
allocs.push_back(move(alloc));
} else {
LOG(INFO) << "Failed to alloc " << alloc_size << " consumed " << allocated_mem
<< "/" << TOTAL_MEM;
}
}
} else {
// Free a random subset of suballocations.
num_allocs = min<int>(num_allocs, allocs.size());
shuffle(allocs.end() - num_allocs, allocs.end(), rng_);
for (int i = 0; i < num_allocs; ++i) {
allocated_mem -= allocs.back()->len();
allocator.Free(move(allocs.back()));
allocs.pop_back();
}
}
// Occasionally check that the suballocations are valid.
if (iter % 50 == 0) AssertMemoryValid(allocs);
}
// Check that memory is released when suballocations are freed.
FreeAllocations(&allocator, &allocs);
ExpectReservationUnused(client);
}
void SuballocatorTest::AssertMemoryValid(
const vector<unique_ptr<Suballocation>>& allocs) {
for (int64_t i = 0; i < allocs.size(); ++i) {
const unique_ptr<Suballocation>& alloc = allocs[i];
ASSERT_GE(alloc->len(), 8);
// Memory should be 8-byte aligned.
ASSERT_EQ(0, reinterpret_cast<uint64_t>(alloc->data()) % 8) << alloc->data();
for (int64_t offset = 0; offset < alloc->len(); offset += 8) {
*reinterpret_cast<int64_t*>(alloc->data() + offset) = i;
}
}
for (int64_t i = 0; i < allocs.size(); ++i) {
const unique_ptr<Suballocation>& alloc = allocs[i];
for (int64_t offset = 0; offset < alloc->len(); offset += 8) {
ASSERT_EQ(*reinterpret_cast<int64_t*>(alloc->data() + offset), i)
<< i << " " << alloc->data() << " " << offset;
}
}
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
impala::InitCommonRuntime(argc, argv, true, impala::TestInfo::BE_TEST);
impala::InitFeSupport();
return RUN_ALL_TESTS();
}
|
#include <bits/stdc++.h>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define ii pair<int, int>
#define ll long long
#define vi vector<int>
#define vc vector<char>
#define pb push_back
#define rz resize
#define mp make_pair
#define f first
#define s second
#define FOR(n) for (int i = 0; i < n; i++)
#define FOR1(n) for (int i = 1; i <= n; i++)
#define RFOR(n) for (int i = n - 1; i >= 0; i--)
#define DFOR(n, m) FOR(n) for (int j = 0; j < m; j++)
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int ddx[8] = {1, 0, -1, -1, -1, 0, 1, 1};
int ddy[8] = {1, 1, 1, 0, -1, -1, -1, 0};
bool in_bounds(int x, int y, int n, int m) {
if (x >= 0 && x < n && y >= 0 && y < m) return true;
return false;
}
const int N = 2 * 1e5 + 10;
int n, m;
int p[N];
int find (int x) {
if (p[x] == -1) return x;
return p[x] = find(p[x]);
}
void merge(int a, int b) {
a = find(a); b = find(b);
if (a == b) return;
if (a >= n) swap(a, b);
p[b] = a;
}
int main() {
freopen("revegetate.in", "r", stdin);
freopen("revegetate.out", "w", stdout);
scanf("%d%d", &n, &m);
memset(p, -1, sizeof p);
FOR(m) {
int a, b; char c;
cin >> c >> a >> b;
a--, b--;
if (a > b) swap(a, b);
if (c == 'S') {
merge(a, b);
merge(a + n, b + n);
}
else {
merge(a, b + n);
merge(b, a + n);
}
}
int cnt = 0;
FOR(n) {
if (find(i) == find(i + n)) {
printf("0");
return 0;
}
}
FOR(n)
merge(i, i + n);
printf("1");
FOR(n) {
if (i == find(i)) printf("0");
}
cout<<endl;
return 0;
}
|
/*
* Copyright 2022, Oak Ridge National Laboratory.
* MGARD-X: MultiGrid Adaptive Reduction of Data Portable across GPUs and CPUs
* Author: Jieyang Chen (chenj3@ornl.gov)
* Date: March 17, 2022
*/
#ifndef MGARD_X_ARRAY_HPP
#define MGARD_X_ARRAY_HPP
// #include "Common.h"
// #include "CommonInternal.h"
#include <algorithm>
#include <vector>
#include "Array.h"
// #include "../DeviceAdapters/DeviceAdapter.h"
namespace mgard_x {
template <DIM D, typename T, typename DeviceType>
Array<D, T, DeviceType>::Array() {
this->host_allocated = false;
this->device_allocated = false;
}
template <DIM D, typename T, typename DeviceType>
Array<D, T, DeviceType>::Array(std::vector<SIZE> _shape, bool pitched,
bool managed) {
this->host_allocated = false;
this->device_allocated = false;
this->pitched = pitched;
this->managed = managed;
std::reverse(_shape.begin(), _shape.end());
this->_shape = _shape;
int ret = check_shape<D>(_shape);
if (ret == -1) {
std::cerr << log::log_err << "Number of dimensions mismatch (" << D
<< " != " << _shape.size()
<< "). mgard_x::Array not "
"initialized!\n";
return;
}
this->D_padded = D;
if (D < 3) {
this->D_padded = 3;
}
if (D % 2 == 0) {
this->D_padded = D + 1;
}
// padding dimensions
for (int d = this->_shape.size(); d < D_padded; d++) {
this->_shape.push_back(1);
}
this->linearized_depth = 1;
for (int i = 2; i < D_padded; i++) {
this->linearized_depth *= this->_shape[i];
}
if (this->pitched) {
if (!this->managed) {
SIZE ld = 0;
MemoryManager<DeviceType>().MallocND(
this->dv, this->_shape[0], this->_shape[1] * this->linearized_depth,
ld, 0);
this->_ldvs.push_back(ld);
for (int i = 1; i < D_padded; i++) {
this->_ldvs.push_back(this->_shape[i]);
}
} else {
std::cerr << log::log_err
<< "Does not support managed memory in pitched mode.\n";
}
} else {
if (!this->managed) {
MemoryManager<DeviceType>().Malloc1D(
this->dv, this->_shape[0] * this->_shape[1] * this->linearized_depth,
0);
for (int i = 0; i < D_padded; i++) {
this->_ldvs.push_back(this->_shape[i]);
}
} else {
MemoryManager<DeviceType>().MallocManaged1D(
this->dv, this->_shape[0] * this->_shape[1] * this->linearized_depth,
0);
for (int i = 0; i < D_padded; i++) {
this->_ldvs.push_back(this->_shape[i]);
}
}
}
this->device_allocated = true;
}
template <DIM D, typename T, typename DeviceType>
void Array<D, T, DeviceType>::copy(const Array<D, T, DeviceType> &array) {
this->free();
this->_shape = array._shape;
this->pitched = array.pitched;
this->D_padded = array.D_padded;
this->linearized_depth = array.linearized_depth;
this->_ldvs.resize(D_padded);
if (this->pitched) {
SIZE ld = 0;
MemoryManager<DeviceType>().MallocND(
this->dv, this->_shape[0], this->_shape[1] * this->linearized_depth, ld,
0);
this->_ldvs[0] = ld;
for (int i = 1; i < D_padded; i++) {
this->_ldvs[i] = this->_shape[i];
}
} else {
MemoryManager<DeviceType>().Malloc1D(
this->dv, this->_shape[0] * this->_shape[1] * this->linearized_depth,
0);
for (int i = 0; i < D_padded; i++) {
this->_ldvs[i] = this->_shape[i];
}
}
MemoryManager<DeviceType>().CopyND(
this->dv, this->_ldvs[0], array.dv, array._ldvs[0], array._shape[0],
array._shape[1] * this->linearized_depth, 0);
DeviceRuntime<DeviceType>::SyncQueue(0);
this->device_allocated = true;
}
template <DIM D, typename T, typename DeviceType>
void Array<D, T, DeviceType>::move(Array<D, T, DeviceType> &&array) {
this->free();
this->_shape = array._shape;
this->pitched = array.pitched;
this->D_padded = array.D_padded;
this->linearized_depth = array.linearized_depth;
if (array.device_allocated) {
this->dv = array.dv;
this->_ldvs = array._ldvs;
this->device_allocated = true;
array.device_allocated = false;
array.dv = NULL;
}
}
template <DIM D, typename T, typename DeviceType>
void Array<D, T, DeviceType>::memset(int value) {
if (this->pitched) {
MemoryManager<DeviceType>().MemsetND(
this->dv, this->_ldvs[0], this->_shape[0],
this->_shape[1] * this->linearized_depth, value, 0);
} else {
MemoryManager<DeviceType>().Memset1D(
this->dv, this->_shape[0] * this->_shape[1] * this->linearized_depth,
value, 0);
}
DeviceRuntime<DeviceType>::SyncQueue(0);
}
template <DIM D, typename T, typename DeviceType>
void Array<D, T, DeviceType>::free() {
if (device_allocated) {
MemoryManager<DeviceType>().Free(dv);
device_allocated = false;
dv = NULL;
}
if (host_allocated && !keepHostCopy) {
MemoryManager<DeviceType>().FreeHost(hv);
host_allocated = false;
hv = NULL;
}
}
template <DIM D, typename T, typename DeviceType>
Array<D, T, DeviceType>::Array(const Array<D, T, DeviceType> &array) {
this->copy(array);
}
template <DIM D, typename T, typename DeviceType>
Array<D, T, DeviceType> &Array<D, T, DeviceType>::
operator=(const Array<D, T, DeviceType> &array) {
// printf("Array operator =\n");
this->copy(array);
return *this;
}
template <DIM D, typename T, typename DeviceType>
Array<D, T, DeviceType> &Array<D, T, DeviceType>::
operator=(Array<D, T, DeviceType> &&array) {
// printf("Array move = \n");
this->move(std::move(array));
return *this;
}
template <DIM D, typename T, typename DeviceType>
Array<D, T, DeviceType>::Array(Array<D, T, DeviceType> &&array) {
// printf("Array move\n");
this->move(std::move(array));
}
template <DIM D, typename T, typename DeviceType>
Array<D, T, DeviceType>::~Array() {
this->free();
}
template <DIM D, typename T, typename DeviceType>
void Array<D, T, DeviceType>::load(const T *data, SIZE ld) {
if (ld == 0) {
ld = _shape[0];
}
MemoryManager<DeviceType>().CopyND(dv, _ldvs[0], data, ld, _shape[0],
_shape[1] * linearized_depth, 0);
DeviceRuntime<DeviceType>::SyncQueue(0);
}
template <DIM D, typename T, typename DeviceType>
T *Array<D, T, DeviceType>::hostCopy(bool keep) {
if (!device_allocated) {
std::cout << log::log_err << "device buffer not initialized.\n";
exit(-1);
}
if (!host_allocated) {
MemoryManager<DeviceType>().MallocHost(
hv, _shape[0] * _shape[1] * linearized_depth, 0);
host_allocated = true;
}
MemoryManager<DeviceType>().CopyND(hv, _shape[0], dv, _ldvs[0], _shape[0],
_shape[1] * linearized_depth, 0);
DeviceRuntime<DeviceType>::SyncQueue(0);
keepHostCopy = keep;
return hv;
}
template <DIM D, typename T, typename DeviceType>
T *Array<D, T, DeviceType>::data(SIZE &ld) {
ld = _ldvs[0];
return dv;
}
template <DIM D, typename T, typename DeviceType>
std::vector<SIZE> &Array<D, T, DeviceType>::shape() {
return _shape;
}
template <DIM D, typename T, typename DeviceType>
T *Array<D, T, DeviceType>::data() {
return dv;
}
template <DIM D, typename T, typename DeviceType>
std::vector<SIZE> Array<D, T, DeviceType>::ld() {
return _ldvs;
}
template <DIM D, typename T, typename DeviceType>
bool Array<D, T, DeviceType>::is_pitched() {
return pitched;
}
} // namespace mgard_x
#endif
|
// Copyright 2019-20 Genten Studios
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
#pragma once
#include <Client/Graphics/Layer.hpp>
#include <Client/Graphics/ShaderPipeline.hpp>
#include <Client/Graphics/Window.hpp>
namespace phx::client
{
/**
* @brief The loading SplashScreen for the client.
*
* @see Layer
* @see LayerStack
*/
class SplashScreen : public gfx::Layer
{
public:
SplashScreen();
~SplashScreen() override = default;
void onEvent(events::Event& e) override;
void onAttach() override;
void onDetach() override;
void tick(float dt) override;
private:
gfx::ShaderPipeline m_pipeline;
unsigned int m_vao = 0;
unsigned int m_vbo = 0;
unsigned int m_texture = 0;
float m_alpha = -0.5f;
float m_multiplier = 1.f;
};
} // namespace phx::client
|
//===- test_cxx_gen.cc ----------------------------------------------------===//
//
// Copyright (C) 2019-2020 Alibaba Group Holding Limited.
//
// 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.
// =============================================================================
// clang-format off
// RUN: %cxx %s -DCG_TEST -o %t %flags %include %link
// RUN: %t > %t.gen.cc
// RUN: cat %t.gen.cc | FileCheck %s --check-prefix=GEN
// Runtime test (build and for for mkldnn)
// RUN: %cxx %s -DRUNTIME_TEST -I%odla_path/include -c -o %t.main.o
// RUN: %cxx %t.gen.cc -I%odla_path/include -c -o %t.gen.o
// RUN: %cxx %odla_path/platforms/odla_dnnl.cc -I%odla_path/include -I%dnnl_path/include -c -o %t.dnnl.o
// RUN: %cxx %t.dnnl.o %t.gen.o %t.main.o -L%dnnl_path/lib -ldnnl -o %t.mkl_exe -Wl,-rpath=%dnnl_path/lib -I%odla_path/include
// RUN: %t.mkl_exe 2>&1| FileCheck %s --check-prefix=EXECUTE
// GEN: include <ODLA/odla.h>
// GEN: extern const float w0[3];
// GEN: extern const float w1[3];
// GEN: static odla_computation Comp;
// GEN: void func(const float input[3], float out_add1[3]) {
// GEN: func_init();
// GEN: odla_BindToArgumentById((const odla_value_id)"input", input, Ctx);
// GEN: odla_BindToOutputById((const odla_value_id)"add1", out_add1, Ctx);
// GEN: odla_ExecuteComputation(Comp, Ctx, ODLA_COMPUTE_INFERENCE, nullptr);
// GEN: }
// EXECUTE: 6.000000
// EXECUTE: 9.000000
// EXECUTE: 12.000000
// clang-format on
#include "test_cxx_gen.in"
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include "checkpoints.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7 * 24 * 60 * 60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xb3;
pchMessageStart[1] = 0x07;
pchMessageStart[2] = 0x9a;
pchMessageStart[3] = 0x1e;
vAlertPubKey = ParseHex("04eb9fd13c016ed9a2f222989769417ed3a16e6fbf3bd55023679be17f0bab053cd9f161528241bc9a2894ad5ebbbd551be1a4bd2d10cdb679228c91e26e26900e");
nDefaultPort = 11957;
nRPCPort = 11958;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
const char* pszTimestamp = "http://www.bbc.co.uk/news/world-us-canada-42926976"; // Trump Russia: Democrats say firing special counsel could cause crisis
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 4867816 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1517690700, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1517690700;
genesis.nBits = 0x1f00ffff;
genesis.nNonce = 561379;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0xf4bbfc518aa3622dbeb8d2818a606b82c2b8b1ac2f28553ebdb6fc04d7abaccf"));
assert(genesis.hashMerkleRoot == uint256("0x40bdd3d5ae84b91a71190094a82948400eb3356e87c5376b64d79509cf552d84"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,18);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,59);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,93);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x44)(0xD5)(0xBC).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x44)(0xF0)(0xA3).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
nPOSStartBlock = 1;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xf1;
pchMessageStart[1] = 0xe3;
pchMessageStart[2] = 0xdc;
pchMessageStart[3] = 0xc6;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("04eb9fd13c016ed9a2f222989769417ed3a16e6fbf3bd55023679be17f0bab053cd9f161528241bc9a2894ad5ebbbd551be1a4bd2d10cdb679228c91e26e26900e");
nDefaultPort = 21957;
nRPCPort = 21958;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = 51214089;
genesis.nNonce = 93481;
//assert(hashGenesisBlock == uint256(""));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,27);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,95);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,98);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x05)(0x55)(0xCF)(0xB1).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = list_of(0x05)(0x55)(0xD4)(0x7A).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
nPOSStartBlock = 1;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Types/generated/game/ui/MenuGameController.hpp>
namespace RED4ext
{
namespace game::ui {
struct BaseCharacterCreationController : game::ui::MenuGameController
{
static constexpr const char* NAME = "gameuiBaseCharacterCreationController";
static constexpr const char* ALIAS = "BaseCharacterCreationController";
};
RED4EXT_ASSERT_SIZE(BaseCharacterCreationController, 0xD0);
} // namespace game::ui
using BaseCharacterCreationController = game::ui::BaseCharacterCreationController;
} // namespace RED4ext
|
#ifndef __IBUFFER_HPP__
#define __IBUFFER_HPP__
/*==========================================================================;
*
* Copyright (C) 1999-2000 Microsoft Corporation. All Rights Reserved.
*
* File: ibuffer.hpp
* Content: Class header the Index buffer class
*
***************************************************************************/
// Includes
#include "buffer.hpp"
// The base-class implementation of the Index buffer assumes
// that it is resides system-memory. It may be managed.
class CIndexBuffer : public IDirect3DIndexBuffer8, public CBuffer
{
public:
// Creation function for Index Buffers
static HRESULT Create(CBaseDevice *pDevice,
DWORD cbLength,
DWORD dwUsage,
D3DFORMAT Format,
D3DPOOL Pool,
REF_TYPE refType,
IDirect3DIndexBuffer8 **ppIndexBuffer);
static HRESULT CreateSysmemIndexBuffer(CBaseDevice *pDevice,
DWORD cbLength,
DWORD dwUsage,
DWORD dwActualUsage,
D3DFORMAT Format,
D3DPOOL Pool,
D3DPOOL ActualPool,
REF_TYPE refType,
CIndexBuffer **pIB);
static HRESULT CreateDriverIndexBuffer(CBaseDevice *pDevice,
DWORD cbLength,
DWORD dwUsage,
DWORD dwActualUsage,
D3DFORMAT Format,
D3DPOOL Pool,
D3DPOOL ActualPool,
REF_TYPE refType,
CIndexBuffer **pVB);
static HRESULT CreateDriverManagedIndexBuffer(CBaseDevice *pDevice,
DWORD cbLength,
DWORD dwUsage,
DWORD dwActualUsage,
D3DFORMAT Format,
D3DPOOL Pool,
D3DPOOL ActualPool,
REF_TYPE refType,
CIndexBuffer **pVB);
// Methods for Resource Management
// Create duplicate of current object in new pool;
// LOD is ignored for our type
virtual HRESULT Clone(D3DPOOL Pool,
CResource **ppResource) const;
virtual const D3DBUFFER_DESC* GetBufferDesc() const;
HRESULT UpdateDirtyPortion(CResource *pResourceTarget);
// IUnknown methods
STDMETHOD(QueryInterface) (REFIID riid,
LPVOID FAR * ppvObj);
STDMETHOD_(ULONG,AddRef) ();
STDMETHOD_(ULONG,Release) ();
// Some Methods for IDirect3DBuffer
STDMETHOD(SetPrivateData)(REFGUID riid,
CONST VOID* pvData,
DWORD cbData,
DWORD dwFlags);
STDMETHOD(GetPrivateData)(REFGUID riid,
LPVOID pvData,
LPDWORD pcbData);
STDMETHOD(FreePrivateData)(REFGUID riid);
STDMETHOD(GetDevice)(IDirect3DDevice8 **ppDevice);
STDMETHOD_(DWORD, GetPriority)();
STDMETHOD_(DWORD, SetPriority)(DWORD dwPriority);
STDMETHOD_(void, PreLoad)();
STDMETHOD_(D3DRESOURCETYPE, GetType)();
// Methods for IDirect3DIndexBuffer8
STDMETHOD(Lock)(UINT cbOffsetToLock,
UINT cbSizeToLock,
BYTE **ppbData,
DWORD dwFlags);
STDMETHOD(Unlock)();
STDMETHOD(GetDesc)(D3DINDEXBUFFER_DESC *pDesc);
BYTE* Data() const
{
DXGASSERT(m_desc.Usage & D3DUSAGE_SOFTWAREPROCESSING);
DXGASSERT(m_desc.Pool == D3DPOOL_SYSTEMMEM || m_desc.Pool == D3DPOOL_MANAGED);
DXGASSERT(m_LockCount == 0);
return GetPrivateDataPointer();
}
protected:
CIndexBuffer(CBaseDevice *pDevice,
DWORD cbLength,
DWORD dwUsage,
DWORD dwActualUsage,
D3DFORMAT Format,
D3DPOOL Pool,
D3DPOOL ActualPool,
REF_TYPE refType,
HRESULT *phr);
#if DBG
HRESULT ValidateLockParams(UINT cbOffsetToLock,
UINT SizeToLock,
BYTE **ppbData,
DWORD dwFlags) const;
#endif // DBG
// Member data
D3DINDEXBUFFER_DESC m_desc;
DWORD m_usageUser;
}; // class CIndexBuffer
class CIndexBufferMT : public CIndexBuffer
{
public:
STDMETHOD(Lock)(UINT cbOffsetToLock,
UINT cbSizeToLock,
BYTE **ppbData,
DWORD dwFlags)
{
API_ENTER(Device());
return CIndexBuffer::Lock(cbOffsetToLock, cbSizeToLock, ppbData, dwFlags);
}
STDMETHOD(Unlock)()
{
API_ENTER(Device());
return CIndexBuffer::Unlock();
}
friend CIndexBuffer;
protected:
CIndexBufferMT(CBaseDevice *pDevice,
DWORD cbLength,
DWORD Usage,
DWORD ActualUsage,
D3DFORMAT Format,
D3DPOOL Pool,
D3DPOOL ActualPool,
REF_TYPE refType,
HRESULT *phr) :
CIndexBuffer(pDevice,
cbLength,
Usage,
ActualUsage,
Format,
Pool,
ActualPool,
refType,
phr)
{
}
}; // class CIndexBufferMT
// This derived version of the Index buffer class
// overrides lock/unlock to call the driver instead
class CDriverIndexBuffer : public CIndexBuffer
{
public:
STDMETHOD(Lock)(UINT cbOffsetToLock,
UINT cbSizeToLock,
BYTE **ppbData,
DWORD dwFlags);
STDMETHOD(Unlock)();
HRESULT LockI(DWORD dwFlags);
HRESULT UnlockI();
BYTE* Data() const
{
DXGASSERT(FALSE); // Direct pointer access not supported
return 0;
}
// Alloc CIndexBuffer to construct this object
friend CIndexBuffer;
protected:
CDriverIndexBuffer(CBaseDevice *pDevice,
DWORD cbLength,
DWORD Usage,
DWORD ActualUsage,
D3DFORMAT Format,
D3DPOOL Pool,
D3DPOOL ActualPool,
REF_TYPE refType,
HRESULT *phr);
~CDriverIndexBuffer();
BYTE* m_pbData; // stores cached pointer
}; // class CDriverIndexBuffer
class CDriverIndexBufferMT : public CDriverIndexBuffer
{
public:
STDMETHOD(Lock)(UINT cbOffsetToLock,
UINT cbSizeToLock,
BYTE **ppbData,
DWORD dwFlags)
{
API_ENTER(Device());
return CDriverIndexBuffer::Lock(cbOffsetToLock, cbSizeToLock, ppbData, dwFlags);
}
STDMETHOD(Unlock)()
{
API_ENTER(Device());
return CDriverIndexBuffer::Unlock();
}
friend CIndexBuffer;
protected:
CDriverIndexBufferMT(CBaseDevice *pDevice,
DWORD cbLength,
DWORD Usage,
DWORD ActualUsage,
D3DFORMAT Format,
D3DPOOL Pool,
D3DPOOL ActualPool,
REF_TYPE refType,
HRESULT *phr) :
CDriverIndexBuffer(pDevice,
cbLength,
Usage,
ActualUsage,
Format,
Pool,
ActualPool,
refType,
phr)
{
}
}; // class CIndexBufferMT
// This derived version of the Index buffer class
// overrides lock/unlock to call the driver instead
class CDriverManagedIndexBuffer : public CIndexBuffer
{
public:
STDMETHOD(Lock)(UINT cbOffsetToLock,
UINT cbSizeToLock,
BYTE **ppbData,
DWORD dwFlags);
STDMETHOD(Unlock)();
BYTE* Data() const
{
DXGASSERT(m_desc.Usage & D3DUSAGE_SOFTWAREPROCESSING);
DXGASSERT((m_desc.Usage & D3DUSAGE_WRITEONLY) == 0);
DXGASSERT(m_LockCount == 0);
DXGASSERT(m_pbData != 0);
return m_pbData;
}
// Alloc CIndexBuffer to construct this object
friend CIndexBuffer;
protected:
CDriverManagedIndexBuffer(CBaseDevice *pDevice,
DWORD cbLength,
DWORD Usage,
DWORD ActualUsage,
D3DFORMAT Format,
D3DPOOL Pool,
D3DPOOL ActualPool,
REF_TYPE refType,
HRESULT *phr);
HRESULT UpdateCachedPointer(CBaseDevice*);
friend HRESULT CResource::RestoreDriverManagementState(CBaseDevice*);
BYTE* m_pbData; // stores cached pointer
BOOL m_bDriverCalled;
}; // class CDriverManagedIndexBuffer
class CDriverManagedIndexBufferMT : public CDriverManagedIndexBuffer
{
public:
STDMETHOD(Lock)(UINT cbOffsetToLock,
UINT cbSizeToLock,
BYTE **ppbData,
DWORD dwFlags)
{
API_ENTER(Device());
return CDriverManagedIndexBuffer::Lock(cbOffsetToLock, cbSizeToLock, ppbData, dwFlags);
}
STDMETHOD(Unlock)()
{
API_ENTER(Device());
return CDriverManagedIndexBuffer::Unlock();
}
// Alloc CIndexBuffer to construct this object
friend CIndexBuffer;
protected:
CDriverManagedIndexBufferMT(CBaseDevice *pDevice,
DWORD cbLength,
DWORD Usage,
DWORD ActualUsage,
D3DFORMAT Format,
D3DPOOL Pool,
D3DPOOL ActualPool,
REF_TYPE refType,
HRESULT *phr) :
CDriverManagedIndexBuffer(pDevice,
cbLength,
Usage,
ActualUsage,
Format,
Pool,
ActualPool,
refType,
phr)
{
}
}; // class CDriverIndexBufferMT
#endif // __IBUFFER_HPP__
|
#include <iostream>
int main() {
int i = -1, &r = 0; // illegal, r must refer to an object
const int i1 = -1, &r1 = 0; // legal
const int *p1 = &i; // legal
const int i3 = i, &r2 = i; // legal
int *const p2 = &i; // legal
const int *const p3 = &i; // legal
const int &const r3; // illegal
return 0;
}
|
#include "Refureku/TypeInfo/Entity/Entity.h"
#include <utility> //std::forward
#include <algorithm> //std::find
#include "Refureku/TypeInfo/Archetypes/Struct.h"
using namespace rfk;
Entity::Entity(std::string&& name, uint64 id, EEntityKind kind) noexcept:
name{std::forward<std::string>(name)},
id{id},
kind{kind}
{
}
Property const* Entity::getProperty(Struct const& archetype, bool isChildClassValid) const noexcept
{
//Iterate over all props to find a matching property
if (isChildClassValid)
{
for (Property const* p : properties)
{
//Consider child classes as valid
if (archetype.isBaseOf(p->getArchetype()))
{
return p;
}
}
}
else
{
for (Property const* p : properties)
{
//Child classes are not considered
if (archetype == p->getArchetype())
{
return p;
}
}
}
return nullptr;
}
std::vector<Property const*> Entity::getProperties(Struct const& archetype, bool isChildClassValid) const noexcept
{
std::vector<Property const*> result;
//Iterate over all props to find a matching property
if (isChildClassValid)
{
for (Property const* p : properties)
{
//Consider child classes as valid
if (archetype.isBaseOf(p->getArchetype()))
{
result.emplace_back(p);
}
}
}
else
{
for (Property const* p : properties)
{
//Child classes are not considered
if (archetype == p->getArchetype())
{
result.emplace_back(p);
}
}
}
return result;
}
bool Entity::addProperty(Property const* toAddProperty) noexcept
{
if (!toAddProperty->getAllowMultiple())
{
//Check if a property of the same type is already in this entity,
//in which case we abort the add
if (std::find_if(properties.cbegin(), properties.cend(), [toAddProperty](Property const* ownedProperty) { return &toAddProperty->getArchetype() == &ownedProperty->getArchetype(); }) != properties.cend())
{
return false;
}
}
properties.emplace_back(toAddProperty);
return true;
}
void Entity::inheritProperties(Entity const& from) noexcept
{
for (Property const* property : from.properties)
{
if (property->getShouldInherit())
{
addProperty(property);
}
}
}
|
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int c, sorted = 0;
cin >> c;
vector<int> n;
vector<int> temp;
for(int i = 0; i < c; i++){
int input;
cin >> input;
n.push_back(input);
}
cout << "3\n";
for(int i = 1; i <= c / 4 + sorted; i++){
if(i == n[i - 1]){
sorted++;
continue;
}
temp.push_back(i);
temp.push_back(n[i - 1]);
cout << i << ' ' << n[i - 1] << ' ';
}
sort(temp.begin(), temp.end());
cout << '\n';
for(int i = c / 4 + 1; i <= c / 2; i++){
temp.push_back(i);
temp.push_back(n[i - 1]);
cout << i << ' ' << n[i - 1] << ' ';
}
sort(temp.begin(), temp.end());
cout << '\n';
for(int i = c / 2; i < c; i++){
cout << n[i] << ' ';
}
cout << '\n';
return 0;
}
|
/*BREAKING - Number Breaking
#number-theory #prime-numbers-1 #number-theory-13 #math-number-theory
Every number is multiplication of some prime numbers. Prime number is a number which is only divided by 1 and itself. Here you are given a number n. You have to find the prime numbers whose multiplication makes this number.
For example, 12 is multiplication of prime numbers 2 and 3. 15 is multiplication of 3 and 5.
Input
First Line will contain the number of test cases T. Then each line will contain a single integer n.
Constraints: 1≤T≤1000, 2≤n≤1000000.
Output
For each test case print a single line which contains test case number and the prime numbers in ascending order separated by a single space whose multiplication make this number.
Example
Input:
3
12
42
84
Output:
Case 1: 2 3
Case 2: 2 3 7
Case 3: 2 3 7
*/
#include <cstdio>
#define MAX 1000033
#define LIM 1001
#define ifComp(x) (flagArr[x>>6]&(1<<((x>>1)&31)))
#define isComp(x) (flagArr[x>>6]|=(1<<((x>>1)&31)))
void BitSeive(int* output)
{
int flagArr[MAX>>6] = {0};
int i,j,k;
for(i=3;i<LIM;i+=2)
if(!ifComp(i))
for(j=i*i,k=i<<1;j<MAX;j+=k)
isComp(j);
output[0] = 2;
for(i=3,j=1;i<MAX;i+=2)
if(!ifComp(i))
output[j++] = i;
}
int main()
{
int sieve[78500];
BitSeive(&sieve[0]);
int tests;
std::scanf("%d", &tests);
for (int i = 1; i <= tests; ++i)
{
int num;
std::scanf("%d", &num);
std::printf("Case %d:", i);
for (int idx = 0; idx < sizeof(sieve)/sizeof(sieve[0]) && num > 1; ++idx)
{
if (num % sieve[idx] == 0)
{
while (num % sieve[idx] == 0)
num /= sieve[idx];
std::printf(" %d", sieve[idx]);
}
}
std::printf("\n");
}
return 0;
}
|
#include "Person.h"
#include <iostream>
using namespace std;
Person::Person(string first,string last,
int arbitrary) : firstname(first),lastname(last),
arbitrarynumber(arbitrary)
{
cout << "constructing " << GetName() << endl;
}
Person::~Person()
{
cout << "destructing " << GetName() << endl;
}
string Person::GetName() const
{
return firstname + " " + lastname;
}
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// <experimental/filesystem>
// class path
// template <class charT, class traits>
// basic_ostream<charT, traits>&
// operator<<(basic_ostream<charT, traits>& os, const path& p);
//
// template <class charT, class traits>
// basic_istream<charT, traits>&
// operator>>(basic_istream<charT, traits>& is, path& p)
//
// TODO(EricWF) This test fails because "std::quoted" fails to compile
// for char16_t and char32_t types. Combine with path.io.pass.cpp when this
// passes.
// XFAIL: *
#include "filesystem_include.hpp"
#include <type_traits>
#include <sstream>
#include <cassert>
#include "test_macros.h"
#include "test_iterators.h"
#include "count_new.hpp"
#include "filesystem_test_helper.hpp"
MultiStringType InStr = MKSTR("abcdefg/\"hijklmnop\"/qrstuvwxyz/123456789");
MultiStringType OutStr = MKSTR("\"abcdefg/\\\"hijklmnop\\\"/qrstuvwxyz/123456789\"");
template <class CharT>
void doIOTest() {
using namespace fs;
using Ptr = const CharT*;
using StrStream = std::basic_stringstream<CharT>;
const char* const InCStr = InStr;
const Ptr E = OutStr;
const path p((const char*)InStr);
StrStream ss;
{ // test output
auto& ret = (ss << p);
assert(ss.str() == E);
assert(&ret == &ss);
}
{ // test input
path p_in;
auto& ret = ss >> p_in;
assert(p_in.native() == (const char*)InStr);
assert(&ret == &ss);
}
}
int main() {
doIOTest<char16_t>();
doIOTest<char32_t>();
}
|
#include "stdafx.h"
#include "StateManager.h"
#include "APIWrappers/Device.h"
namespace Boolka
{
bool StateManager::Initialize(Device& device)
{
if (!m_DescriptorHeapSRV.Initialize(device, 64, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE))
return false;
return true;
}
void StateManager::Unload()
{
m_DescriptorHeapSRV.Unload();
}
} // namespace Boolka
|
/*
* Copyright (c) 2017, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
/**
* @file
* This file includes definition for Thread border agent.
*/
#ifndef BORDER_AGENT_HPP_
#define BORDER_AGENT_HPP_
#include <stdint.h>
#include "mdns.hpp"
#include "ncp.hpp"
namespace ot {
namespace BorderRouter {
/**
* @addtogroup border-router-border-agent
*
* @brief
* This module includes definition for Thread border agent
*
* @{
*/
/**
* This class implements Thread border agent functionality.
*
*/
class BorderAgent
{
public:
/**
* The constructor to initialize the Thread border agent.
*
* @param[in] aNcp A pointer to the NCP controller.
*
*/
BorderAgent(Ncp::Controller *aNcp);
~BorderAgent(void);
/**
* This method initialize border agent service.
*
*/
void Init(void);
/**
* This method updates the fd_set and timeout for mainloop.
*
* @param[inout] aReadFdSet A reference to read file descriptors.
* @param[inout] aWriteFdSet A reference to write file descriptors.
* @param[inout] aErrorFdSet A reference to error file descriptors.
* @param[inout] aMaxFd A reference to the max file descriptor.
* @param[inout] aTimeout A reference to timeout.
*
*/
void UpdateFdSet(fd_set &aReadFdSet, fd_set &aWriteFdSet, fd_set &aErrorFdSet, int &aMaxFd, timeval &aTimeout);
/**
* This method performs border agent processing.
*
* @param[in] aReadFdSet A reference to read file descriptors.
* @param[in] aWriteFdSet A reference to write file descriptors.
* @param[in] aErrorFdSet A reference to error file descriptors.
*
*/
void Process(const fd_set &aReadFdSet, const fd_set &aWriteFdSet, const fd_set &aErrorFdSet);
private:
/**
* This method starts border agent service.
*
* @retval OTBR_ERROR_NONE Successfully started border agent.
* @retval OTBR_ERROR_ERRNO Failed to start border agent.
*
*/
otbrError Start(void);
/**
* This method stops border agent service.
*
*/
void Stop(void);
#if OTBR_ENABLE_NCP_WPANTUND
static void SendToCommissioner(void *aContext, int aEvent, va_list aArguments);
#endif
static void HandleMdnsState(void *aContext, Mdns::State aState)
{
static_cast<BorderAgent *>(aContext)->HandleMdnsState(aState);
}
void HandleMdnsState(Mdns::State aState);
void PublishService(void);
void StartPublishService(void);
void StopPublishService(void);
void SetNetworkName(const char *aNetworkName);
void SetExtPanId(const uint8_t *aExtPanId);
void SetThreadVersion(uint16_t aThreadVersion);
void HandleThreadState(bool aStarted);
void HandlePSKc(const uint8_t *aPSKc);
static void HandlePSKc(void *aContext, int aEvent, va_list aArguments);
static void HandleThreadState(void *aContext, int aEvent, va_list aArguments);
static void HandleNetworkName(void *aContext, int aEvent, va_list aArguments);
static void HandleExtPanId(void *aContext, int aEvent, va_list aArguments);
static void HandleThreadVersion(void *aContext, int aEvent, va_list aArguments);
Mdns::Publisher *mPublisher;
Ncp::Controller *mNcp;
#if OTBR_ENABLE_NCP_WPANTUND
int mSocket;
#endif
uint8_t mExtPanId[kSizeExtPanId];
bool mExtPanIdInitialized;
uint16_t mThreadVersion;
char mNetworkName[kSizeNetworkName + 1];
bool mThreadStarted;
bool mPSKcInitialized;
};
/**
* @}
*/
} // namespace BorderRouter
} // namespace ot
#endif // BORDER_AGENT_HPP_
|
/*******************************************************************************
* Copyright 2020-2021 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.
*
*
* SPDX-License-Identifier: Apache-2.0
*******************************************************************************/
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <vector>
#include <CL/sycl.hpp>
#include "cblas.h"
#include "oneapi/mkl/detail/config.hpp"
#include "oneapi/mkl.hpp"
#include "onemkl_blas_helper.hpp"
#include "reference_blas_templates.hpp"
#include "test_common.hpp"
#include "test_helper.hpp"
#include <gtest/gtest.h>
using namespace sycl;
using std::vector;
extern std::vector<sycl::device *> devices;
namespace {
template <typename fp, typename fp_scalar>
int test(device *dev, oneapi::mkl::layout layout) {
// Prepare data.
fp a, b, s, a_ref, b_ref, s_ref;
fp_scalar c, c_ref;
a = rand_scalar<fp>();
b = rand_scalar<fp>();
s = rand_scalar<fp>();
c = rand_scalar<fp_scalar>();
a_ref = a;
b_ref = b;
s_ref = s;
c_ref = c;
// Call Reference ROTG.
using fp_ref = typename ref_type_info<fp>::type;
::rotg((fp_ref *)&a_ref, (fp_ref *)&b_ref, (fp_scalar *)&c_ref, (fp_ref *)&s_ref);
// Call DPC++ ROTG.
// Catch asynchronous exceptions.
auto exception_handler = [](exception_list exceptions) {
for (std::exception_ptr const &e : exceptions) {
try {
std::rethrow_exception(e);
}
catch (exception const &e) {
std::cout << "Caught asynchronous SYCL exception during ROTG:\n"
<< e.what() << std::endl;
print_error_code(e);
}
}
};
queue main_queue(*dev, exception_handler);
buffer<fp, 1> a_buffer(&a, range<1>(1));
buffer<fp, 1> b_buffer(&b, range<1>(1));
buffer<fp_scalar, 1> c_buffer(&c, range<1>(1));
buffer<fp, 1> s_buffer(&s, range<1>(1));
try {
#ifdef CALL_RT_API
switch (layout) {
case oneapi::mkl::layout::column_major:
oneapi::mkl::blas::column_major::rotg(main_queue, a_buffer, b_buffer, c_buffer,
s_buffer);
break;
case oneapi::mkl::layout::row_major:
oneapi::mkl::blas::row_major::rotg(main_queue, a_buffer, b_buffer, c_buffer,
s_buffer);
break;
default: break;
}
#else
switch (layout) {
case oneapi::mkl::layout::column_major:
TEST_RUN_CT_SELECT(main_queue, oneapi::mkl::blas::column_major::rotg, a_buffer,
b_buffer, c_buffer, s_buffer);
break;
case oneapi::mkl::layout::row_major:
TEST_RUN_CT_SELECT(main_queue, oneapi::mkl::blas::row_major::rotg, a_buffer,
b_buffer, c_buffer, s_buffer);
break;
default: break;
}
#endif
}
catch (exception const &e) {
std::cout << "Caught synchronous SYCL exception during ROTG:\n" << e.what() << std::endl;
print_error_code(e);
}
catch (const oneapi::mkl::unimplemented &e) {
return test_skipped;
}
catch (const std::runtime_error &error) {
std::cout << "Error raised during execution of ROTG:\n" << error.what() << std::endl;
}
// Compare the results of reference implementation and DPC++ implementation.
auto a_accessor = a_buffer.template get_access<access::mode::read>();
bool good_a = check_equal(a_accessor[0], a_ref, 4, std::cout);
auto b_accessor = b_buffer.template get_access<access::mode::read>();
bool good_b = check_equal(b_accessor[0], b_ref, 4, std::cout);
auto s_accessor = s_buffer.template get_access<access::mode::read>();
bool good_s = check_equal(s_accessor[0], s_ref, 4, std::cout);
auto c_accessor = c_buffer.template get_access<access::mode::read>();
bool good_c = check_equal(c_accessor[0], c_ref, 4, std::cout);
bool good = good_a && good_b && good_c && good_s;
return (int)good;
}
class RotgTests : public ::testing::TestWithParam<std::tuple<sycl::device *, oneapi::mkl::layout>> {
};
TEST_P(RotgTests, RealSinglePrecision) {
EXPECT_TRUEORSKIP((test<float, float>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
EXPECT_TRUEORSKIP((test<float, float>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
EXPECT_TRUEORSKIP((test<float, float>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
}
TEST_P(RotgTests, RealDoublePrecision) {
EXPECT_TRUEORSKIP((test<double, double>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
EXPECT_TRUEORSKIP((test<double, double>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
EXPECT_TRUEORSKIP((test<double, double>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
}
TEST_P(RotgTests, ComplexSinglePrecision) {
EXPECT_TRUEORSKIP(
(test<std::complex<float>, float>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
EXPECT_TRUEORSKIP(
(test<std::complex<float>, float>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
EXPECT_TRUEORSKIP(
(test<std::complex<float>, float>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
}
TEST_P(RotgTests, ComplexDoublePrecision) {
EXPECT_TRUEORSKIP(
(test<std::complex<double>, double>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
EXPECT_TRUEORSKIP(
(test<std::complex<double>, double>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
EXPECT_TRUEORSKIP(
(test<std::complex<double>, double>(std::get<0>(GetParam()), std::get<1>(GetParam()))));
}
INSTANTIATE_TEST_SUITE_P(RotgTestSuite, RotgTests,
::testing::Combine(testing::ValuesIn(devices),
testing::Values(oneapi::mkl::layout::column_major,
oneapi::mkl::layout::row_major)),
::LayoutDeviceNamePrint());
} // anonymous namespace
|
/* plantcalc -- Power plant modelling
* (c) 2012 Michał Górny
* Released under the terms of the 2-clause BSD license
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "mediumsplittingjunction.hxx"
#include "../common/splittingjunction.ixx"
template class SplittingJunction<MediumPin>;
MediumSplittingJunction::MediumSplittingJunction(const char* name)
: SplittingJunction<MediumPin>(name),
_p1_eq(_in.p(), _out1.p()),
_p2_eq(_in.p(), _out2.p()),
_h1_eq(_in.h(), _out1.h()),
_h2_eq(_in.h(), _out2.h()),
_mass_eq(1.0, _in.D(),
1.0, _out1.D(),
1.0, _out2.D())
{
}
EquationSystem MediumSplittingJunction::equations()
{
EquationSystem ret;
ret.push_back(&_p1_eq);
ret.push_back(&_p2_eq);
ret.push_back(&_h1_eq);
ret.push_back(&_h2_eq);
ret.push_back(&_mass_eq);
return ret;
}
|
// 2006-10-12 Paolo Carlini <pcarlini@suse.de>
// Copyright (C) 2006 Free Software Foundation
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
// 21.3.7.9 inserters and extractors
#include <ostream>
#include <sstream>
#include <testsuite_hooks.h>
// libstdc++/28277
void test01()
{
using namespace std;
bool test __attribute__((unused)) = true;
wostringstream oss_01;
const wstring str_01(50, L'a');
oss_01.width(5000000);
const streamsize width = oss_01.width();
oss_01 << str_01;
VERIFY( oss_01.good() );
VERIFY( oss_01.str().size() == width );
}
int main()
{
test01();
return 0;
}
|
/***********************************************************
*
* Projekt: Strategicka hra
* Cast: Server hry - skilly
* Autor: Tomas Karban
*
* Popis: Bullet Attack skilla -- implementace typu skilly
*
***********************************************************/
#include "StdAfx.h"
#include "SBulletAttackSkillType.h"
#include "SBulletAttackSkill.h"
#include "Common\Map\MBulletAttackSkillType.h"
#include "..\AbstractDefenseSkill\SAbstractDefenseSkillType.h"
#include "GameServer\Civilization\Src\ZUnit.h"
#include "GameServer\GameServer\SNotifications.h"
#include "..\AbstractAttackSkill\ISysCallAttack.h"
#define SKILLDATA(pUnit) (SSBulletAttackSkill *)GetSkillData(pUnit)
#ifdef _DEBUG
#define ASSERT_VALID_UNIT(pUnitData) AssertValidUnit(pUnitData)
#else // _DEBUG
#define ASSERT_VALID_UNIT(pUnitData)
#endif // _DEBUG
// implementace interfacu volani ze skriptu
BEGIN_SKILLCALL_INTERFACE_MAP(CSBulletAttackSkillType, CSAbstractAttackSkillType)
SKILLCALL_BASECLASS, // IsActive()
SKILLCALL_BASECLASS, // GetName()
SKILLCALL_BASECLASS, // GetAttackableUnits()
SKILLCALL_BASECLASS, // CanAttackUnit()
SKILLCALL_BASECLASS, // GetAttackInteractionsMask()
SKILLCALL_BASECLASS, // GetAttackRadius()
SKILLCALL_BASECLASS, // GetAttackAltMin()
SKILLCALL_BASECLASS, // GetAttackAltMax()
SKILLCALL_METHOD(SCI_Fire)
END_SKILLCALL_INTERFACE_MAP ()
IMPLEMENT_DYNAMIC(CSBulletAttackSkillType, CSAbstractAttackSkillType);
IMPLEMENT_SKILL_TYPE(CSBulletAttackSkillType, 1, "BulletAttack");
////////////////////////////////////////////////////////////////////////
// Destruktor
////////////////////////////////////////////////////////////////////////
CSBulletAttackSkillType::~CSBulletAttackSkillType()
{
ASSERT(m_dwLoadTime == 0);
ASSERT(m_dwFirePeriod == 0);
ASSERT(m_nAttackIntensity == 0);
ASSERT(m_dwAppearanceID == 0);
ASSERT(m_dwAnimationOffset == 0);
ASSERT(m_dwAnimationLength == 0);
ASSERT(m_dwAnimationEnd == 0);
}
////////////////////////////////////////////////////////////////////////
// Inicializace a destrukce dat typu skilly
////////////////////////////////////////////////////////////////////////
// inicializuje data typu skilly z dat "pData" velikosti "dwDataSize"
// vyjimky: CPersistentLoadException
void CSBulletAttackSkillType::CreateSkillType(void *pData, DWORD dwDataSize)
{
// data musi mit ocekavanou velikost
LOAD_ASSERT(dwDataSize == sizeof(SMBulletAttackSkillType));
// pointer musi ukazovat na rozumne misto v pameti
ASSERT(::AfxIsValidAddress(pData, dwDataSize, FALSE));
// nacteme data, ktera ma predek
CSAbstractAttackSkillType::CreateSkillType(pData, sizeof(SMAbstractAttackSkillType));
// otestujeme jejich spravnost
LOAD_ASSERT(m_dwAttackRadius >= SM_BULLETATTACK_SKILLTYPE_RADIUS_MIN);
LOAD_ASSERT(m_dwAttackRadius <= SM_BULLETATTACK_SKILLTYPE_RADIUS_MAX);
LOAD_ASSERT(SM_BULLETATTACK_SKILLTYPE_ALTITUDE_MIN <= m_dwAttackMinAltitude);
LOAD_ASSERT(m_dwAttackMinAltitude <= m_dwAttackMaxAltitude);
LOAD_ASSERT(m_dwAttackMaxAltitude <= SM_BULLETATTACK_SKILLTYPE_ALTITUDE_MAX);
// nacteme cas pred prvnim vystrelem
m_dwLoadTime = ((SMBulletAttackSkillType *)pData)->m_dwLoadTime;
LOAD_ASSERT(m_dwLoadTime <= SM_BULLETATTACK_SKILLTYPE_LOADTIME_MAX);
// nacteme periodu strelby
m_dwFirePeriod = ((SMBulletAttackSkillType *)pData)->m_dwFirePeriod;
LOAD_ASSERT(m_dwFirePeriod <= SM_BULLETATTACK_SKILLTYPE_FIREPERIOD_MAX);
// nacteme silu utoku
m_nAttackIntensity = ((SMBulletAttackSkillType *)pData)->m_nAttackIntensity;
LOAD_ASSERT(m_nAttackIntensity >= SM_BULLETATTACK_SKILLTYPE_INTENSITY_MIN);
LOAD_ASSERT(m_nAttackIntensity <= SM_BULLETATTACK_SKILLTYPE_INTENSITY_MAX);
// nacteme ID vzhledu jednotky pri strelbe (nelze assertovat)
m_dwAppearanceID = ((SMBulletAttackSkillType *)pData)->m_dwAppearanceID;
LOAD_ASSERT(m_dwAppearanceID != 0);
// nacteme offset zacatku animace
m_dwAnimationOffset = ((SMBulletAttackSkillType *)pData)->m_dwAnimationOffset;
// offset zacatku animace musi byt alespon tak velky jako cas pred prvnim vystrelem
LOAD_ASSERT(m_dwAnimationOffset <= m_dwLoadTime);
// nacteme delku animace (nesmi byt nula)
m_dwAnimationLength = ((SMBulletAttackSkillType *)pData)->m_dwAnimationLength;
LOAD_ASSERT(m_dwAnimationLength >= SM_BULLETATTACK_SKILLTYPE_ANIMATIONLENGTH_MIN);
LOAD_ASSERT(m_dwAnimationLength <= m_dwFirePeriod);
LOAD_ASSERT(m_dwAnimationOffset <= m_dwAnimationLength);
// dopocitame si konec animace
m_dwAnimationEnd = m_dwFirePeriod - (m_dwAnimationLength - m_dwAnimationOffset);
}
// znici data typu skilly
void CSBulletAttackSkillType::DeleteSkillType()
{
m_dwLoadTime = 0;
m_dwFirePeriod = 0;
m_nAttackIntensity = 0;
m_dwAppearanceID = 0;
m_dwAnimationOffset = 0;
m_dwAnimationLength = 0;
m_dwAnimationEnd = 0;
CSAbstractAttackSkillType::DeleteSkillType();
}
////////////////////////////////////////////////////////////////////////
// Inicializace a uklid dat skilly u jednotky
////////////////////////////////////////////////////////////////////////
void CSBulletAttackSkillType::InitializeSkill(CSUnit *pUnit)
{
// prvne zavolame predka
CSAbstractAttackSkillType::InitializeSkill(pUnit);
// otestujeme spravnost pointeru pUnit
ASSERT(pUnit != NULL);
ASSERT_KINDOF(CSUnit, pUnit);
// sezen pointer na data skilly u jednotky
SSBulletAttackSkill *pUnitData = SKILLDATA(pUnit);
// otestuj pointer
ASSERT(::AfxIsValidAddress(pUnitData, sizeof(SSBulletAttackSkill), TRUE));
// vynuluj data u jednotky
pUnitData->m_dwRemainingTime = 0;
pUnitData->m_pAttackedUnit = NULL;
}
void CSBulletAttackSkillType::DestructSkill(CSUnit *pUnit)
{
// opatrne smazeme data u jednotky
// (kdyz se konci server a skilla je aktivni, tak po
// pauznuti hry se nevola DeactivateSkill(), proto
// zustanou zvednute reference...)
// otestujeme spravnost pointeru pUnit
ASSERT(pUnit != NULL);
ASSERT_KINDOF(CSUnit, pUnit);
// sezen pointer na data skilly u jednotky
SSBulletAttackSkill *pUnitData = SKILLDATA(pUnit);
// otestuj pointer
ASSERT(::AfxIsValidAddress(pUnitData, sizeof(SSBulletAttackSkill), TRUE));
// kdyz byla skilla aktivni, tak si drzela referenci
// na napadenou jednotku
if (pUnitData->m_pAttackedUnit != NULL)
pUnitData->m_pAttackedUnit->Release();
// nakonec zavolame predka
CSAbstractAttackSkillType::DestructSkill(pUnit);
}
////////////////////////////////////////////////////////////////////////
// Save/Load dat typu skilly
////////////////////////////////////////////////////////////////////////
void CSBulletAttackSkillType::PersistentSaveSkillType(CPersistentStorage &storage)
{
BRACE_BLOCK(storage);
// otestuj data typu skilly
ASSERT_VALID(this);
// prvne ulozime data predka
CSAbstractAttackSkillType::PersistentSaveSkillType(storage);
// pak ulozime svoje data
storage << m_dwLoadTime << m_dwFirePeriod << m_nAttackIntensity
<< m_dwAppearanceID << m_dwAnimationOffset << m_dwAnimationLength;
}
void CSBulletAttackSkillType::PersistentLoadSkillType(CPersistentStorage &storage)
{
BRACE_BLOCK(storage);
// nejprve natahneme data predka
CSAbstractAttackSkillType::PersistentLoadSkillType(storage);
// otestujeme, ze se natahly smysluplna data
LOAD_ASSERT(m_dwAttackRadius >= SM_BULLETATTACK_SKILLTYPE_RADIUS_MIN);
LOAD_ASSERT(m_dwAttackRadius <= SM_BULLETATTACK_SKILLTYPE_RADIUS_MAX);
LOAD_ASSERT(SM_BULLETATTACK_SKILLTYPE_ALTITUDE_MIN <= m_dwAttackMinAltitude);
LOAD_ASSERT(m_dwAttackMinAltitude <= m_dwAttackMaxAltitude);
LOAD_ASSERT(m_dwAttackMaxAltitude <= SM_BULLETATTACK_SKILLTYPE_ALTITUDE_MAX);
// natahneme svoje vlastni data ze souboru
storage >> m_dwLoadTime >> m_dwFirePeriod >> m_nAttackIntensity
>> m_dwAppearanceID >> m_dwAnimationOffset >> m_dwAnimationLength;
// otestujeme spravnost
LOAD_ASSERT(m_dwLoadTime <= SM_BULLETATTACK_SKILLTYPE_LOADTIME_MAX);
LOAD_ASSERT(m_dwFirePeriod <= SM_BULLETATTACK_SKILLTYPE_FIREPERIOD_MAX);
LOAD_ASSERT(m_nAttackIntensity >= SM_BULLETATTACK_SKILLTYPE_INTENSITY_MIN);
LOAD_ASSERT(m_nAttackIntensity <= SM_BULLETATTACK_SKILLTYPE_INTENSITY_MAX);
LOAD_ASSERT(m_dwAppearanceID != 0);
LOAD_ASSERT(m_dwAnimationOffset <= m_dwLoadTime);
LOAD_ASSERT(m_dwAnimationLength <= m_dwFirePeriod);
LOAD_ASSERT(m_dwAnimationOffset <= m_dwAnimationLength);
}
void CSBulletAttackSkillType::PersistentTranslatePointersSkillType(CPersistentStorage &storage)
{
// zavolame predka
CSAbstractAttackSkillType::PersistentTranslatePointersSkillType(storage);
// jinak nic...
}
void CSBulletAttackSkillType::PersistentInitSkillType()
{
// zavolame predka
CSAbstractAttackSkillType::PersistentInitSkillType();
// dopocitame konec animace
m_dwAnimationEnd = m_dwFirePeriod - (m_dwAnimationLength - m_dwAnimationOffset);
}
//////////////////////////////////////////////////////////////////////
// Save/Load dat skilly u jednotky
//////////////////////////////////////////////////////////////////////
void CSBulletAttackSkillType::PersistentSaveSkill(CPersistentStorage &storage, CSUnit *pUnit)
{
BRACE_BLOCK(storage);
// otestujeme spravnost pointeru pUnit
ASSERT(pUnit != NULL);
ASSERT_KINDOF(CSUnit, pUnit);
// sezen pointer na data skilly u jednotky
SSBulletAttackSkill *pUnitData = SKILLDATA(pUnit);
// otestuj pointer
ASSERT(AfxIsValidAddress(pUnitData, sizeof(SSBulletAttackSkill), TRUE));
// otestuj data skilly u jednotky
ASSERT_VALID_UNIT(pUnitData);
// nejprve zavolame predka
CSAbstractAttackSkillType::PersistentSaveSkill(storage, pUnit);
// pak ulozime data do souboru
storage << pUnitData->m_dwRemainingTime << pUnitData->m_pAttackedUnit;
}
void CSBulletAttackSkillType::PersistentLoadSkill(CPersistentStorage &storage, CSUnit *pUnit)
{
BRACE_BLOCK(storage);
// otestujeme spravnost pointeru pUnit
ASSERT(pUnit != NULL);
ASSERT_KINDOF(CSUnit, pUnit);
// sezen pointer na data skilly u jednotky
SSBulletAttackSkill *pUnitData = SKILLDATA(pUnit);
// otestuj pointer
ASSERT(AfxIsValidAddress(pUnitData, sizeof(SSBulletAttackSkill), TRUE));
// nejprve zavolame predka
CSAbstractAttackSkillType::PersistentLoadSkill(storage, pUnit);
// pak natahneme data ze souboru
storage >> pUnitData->m_dwRemainingTime >> (void *&)pUnitData->m_pAttackedUnit;
// otestujeme natazena data ...
// ... neni co testovat
}
void CSBulletAttackSkillType::PersistentTranslatePointersSkill(CPersistentStorage &storage, CSUnit *pUnit)
{
// otestujeme spravnost pointeru pUnit
ASSERT(pUnit != NULL);
ASSERT_KINDOF(CSUnit, pUnit);
// sezen pointer na data skilly u jednotky
SSBulletAttackSkill *pUnitData = SKILLDATA(pUnit);
// otestuj pointer
ASSERT(AfxIsValidAddress(pUnitData, sizeof(SSBulletAttackSkill), TRUE));
// nejprve zavolame predka
CSAbstractAttackSkillType::PersistentTranslatePointersSkill(storage, pUnit);
// mame v sobe ulozeny pointer na napadenou jednotku,
// takze kdyz je neNULL, tak ho nechame prelozit
pUnitData->m_pAttackedUnit = (CSUnit *) storage.TranslatePointer(pUnitData->m_pAttackedUnit);
// otestujeme, ze se to rozumne prelozilo
if (pUnitData->m_pAttackedUnit != NULL)
{
LOAD_ASSERT(pUnitData->m_pAttackedUnit->IsKindOf(RUNTIME_CLASS(CSUnit)));
// pridame refcount
// pUnitData->m_pAttackedUnit->AddRef();
}
}
void CSBulletAttackSkillType::PersistentInitSkill(CSUnit *pUnit)
{
// otestujeme parametr
ASSERT(pUnit != NULL);
ASSERT_KINDOF(CSUnit, pUnit);
// zavolame predka
CSAbstractAttackSkillType::PersistentInitSkill(pUnit);
}
////////////////////////////////////////////////////////////////////////
// Aktivace skilly (zapnuti DoTimeSlice)
////////////////////////////////////////////////////////////////////////
void CSBulletAttackSkillType::ActivateSkill(CSUnit *pUnit, CSUnit *pAttackedUnit, CISysCallAttack *pSysCall)
{
// otestujeme spravnost pointeru
ASSERT(pUnit != NULL);
ASSERT_KINDOF(CSUnit, pUnit);
ASSERT(pAttackedUnit != NULL);
ASSERT_KINDOF(CSUnit, pAttackedUnit);
ASSERT(pSysCall != NULL);
ASSERT_KINDOF(CISysCallAttack, pSysCall);
// sezeneme pointer na data skilly u jednotky
SSBulletAttackSkill *pUnitData = SKILLDATA(pUnit);
// otestujeme pointer
ASSERT(AfxIsValidAddress(pUnitData, sizeof(SSBulletAttackSkill), TRUE));
// otestujeme data skilly u jednotky
ASSERT_VALID_UNIT(pUnitData);
// je jiz attack skilla aktivni?
if (IsSkillActive(pUnit))
{
// utoci se na jednotku, na kterou ted chceme strilet?
if (pAttackedUnit == pUnitData->m_pAttackedUnit)
{
// nedelame nic, vzdyt uz utocime...
return;
}
else
{
// zastavime palbu (pozdeji zahajime palbu jinam...)
// BTW toto ustreli skript, ktery volal predchozi attack
DeactivateSkill(pUnit);
}
}
// OK, ted vime, ze skilla neni aktivni
// inicializujeme casovani strelby
if (g_cMap.GetTimeSlice() < pUnitData->m_dwRemainingTime)
{
pUnitData->m_dwRemainingTime -= g_cMap.GetTimeSlice();
}
else
{
pUnitData->m_dwRemainingTime = 0;
}
// pridame jeste cas, ktery potrebuje k priprave prvniho vystrelu
pUnitData->m_dwRemainingTime += m_dwLoadTime;
// nyni mame spocitany presne cas na nabiti pred prvnim vystrelem
// zvysime pocet referenci na jednotce, na kterou budeme strilet
pAttackedUnit->AddRef();
// ulozime si pointer na jednotku, na kterou budeme strilet
pUnitData->m_pAttackedUnit = pAttackedUnit;
// to je zatim cele, DoTimeSlice() bude odcitat, pri nule vypali
// a counter nastavi zpatky na delku periody
// zavolame predka (ten fyzicky na serveru aktivuje skillu)
CSAbstractAttackSkillType::ActivateSkill(pUnit, pSysCall);
}
////////////////////////////////////////////////////////////////////////
// Deaktivace skilly (vypnuti DoTimeSlice)
////////////////////////////////////////////////////////////////////////
void CSBulletAttackSkillType::DeactivateSkill(CSUnit *pUnit)
{
// otestujeme spravnost pointeru pUnit
ASSERT(pUnit != NULL);
// sezeneme pointer na data skilly u jednotky
SSBulletAttackSkill *pUnitData = SKILLDATA(pUnit);
// otestujeme pointer
ASSERT(AfxIsValidAddress(pUnitData, sizeof(SSBulletAttackSkill), TRUE));
// otestujeme data skilly u jednotky
ASSERT_VALID_UNIT(pUnitData);
// potrebujeme si k jednotce ulozit cislo timeslicu, kdy
// bude mozne tuto attack skillu zase aktivovat
// (presneji: kdyz to udela driv, tak mu akorat
// opozdime prvni vystrel -- to resi ActivateSkill() --
// aby se nedalo "sidit" opakovanym aktivovanim
// a deaktivovanim strilet rychleji)
pUnitData->m_dwRemainingTime += g_cMap.GetTimeSlice();
// snizime pocet referenci napadnute jednotky
pUnitData->m_pAttackedUnit->Release();
// vynulujeme pointer na napadenou jednotku
pUnitData->m_pAttackedUnit = NULL;
// zavolame predka (ten fyzicky na serveru deaktivuje skillu)
CSAbstractAttackSkillType::DeactivateSkill(pUnit);
}
////////////////////////////////////////////////////////////////////////
// DoTimeSlice
////////////////////////////////////////////////////////////////////////
void CSBulletAttackSkillType::DoTimeSlice(CSUnit *pUnit)
{
// otestujeme spravnost pointeru pUnit
ASSERT(pUnit != NULL);
// sezeneme pointer na data skilly u jednotky
SSBulletAttackSkill *pUnitData = SKILLDATA(pUnit);
// otestujeme pointer
ASSERT(AfxIsValidAddress(pUnitData, sizeof(SSBulletAttackSkill), TRUE));
// otestujeme data skilly u jednotky
ASSERT_VALID_UNIT(pUnitData);
ASSERT(pUnitData->m_pAttackedUnit != NULL);
// zjistime vzdalenost a vysku napadene jednotky
VERIFY(pUnitData->m_pAttackedUnit->PrivilegedThreadReaderLock());
CPointDW pointPosition = pUnitData->m_pAttackedUnit->GetPosition();
DWORD dwAltitude = pUnitData->m_pAttackedUnit->GetVerticalPosition();
pUnitData->m_pAttackedUnit->PrivilegedThreadReaderUnlock();
// kazdy timeslice nastavime smer jednotky na napadenou jednotku
if (g_cMap.IsMapPosition(pointPosition))
pUnit->SetDirection(pointPosition);
/*
// kdyz je counter vetsi nez nula, tak jen menime animace a testujeme, jestli
// uz nahodou neni napadena jednotka mrtva
if (pUnitData->m_dwRemainingTime > 0)
{
// pokud je delka vystrelu vetsi, nez delka animace,
// tak bude animace na chvili vypnuta a jen se bude testovat
// smrt nepritele
if (m_dwFirePeriod > m_dwAnimationLength)
{
// nemame nahodou ukoncit animaci predchoziho vystrelu?
if (pUnitData->m_dwRemainingTime == m_dwAnimationEnd)
{
pUnit->SetDefaultAppearanceID();
}
// kdyz zrovna neanimujeme (tj. zbyvajici cas je neco mezi vypnutim
// a zapnutim animace), tak testujeme smrt nepritele
if ((m_dwAnimationEnd <= pUnitData->m_dwRemainingTime) &&
(pUnitData->m_dwRemainingTime <= m_dwAnimationOffset) &&
(pUnitData->m_pAttackedUnit->GetLives() <= 0))
{
// nastavime vysledek syscallu na uspech
pUnitData->m_pSysCall->GetBag()->ReturnBool(true);
// ukoncit syscall
pUnitData->m_pSysCall->FinishWaiting(STATUS_SUCCESS);
// zapomenout na syscall (sam se zrusil)
pUnitData->m_pSysCall = NULL;
// nastavovat defaultni vzhled nemusime, to uz je hotove
// deaktivujeme attack skillu
DeactivateSkill(pUnit);
return;
}
// nemame nahodou zahajit animaci jednoho vystrelu?
if (pUnitData->m_dwRemainingTime == m_dwAnimationOffset)
{
pUnit->SetAppearanceID(m_dwAppearanceID);
}
}
else
{
// delka animace je stejna jako delka vystrelu, takze
// s animaci nedelame nic, jen testujeme, jestli neni
// nepratelska jednotka mrtva;
// to delame prave v okamziku, kdy animace "konci" a "zacina"
if ((pUnitData->m_dwRemainingTime == m_dwAnimationOffset) &&
(pUnitData->m_pAttackedUnit->GetLives() <= 0))
{
// nastavime vysledek syscallu na uspech
pUnitData->m_pSysCall->GetBag()->ReturnBool(true);
// ukoncit syscall
pUnitData->m_pSysCall->FinishWaiting(STATUS_SUCCESS);
// zapomenout na syscall (sam se zrusil)
pUnitData->m_pSysCall = NULL;
// musime nastavit defaultni vzhled
pUnit->SetDefaultAppearanceID();
// deaktivujeme attack skillu
DeactivateSkill(pUnit);
return;
}
}
pUnitData->m_dwRemainingTime--;
return;
}
*/
// kdyz je okamzik mezi dvema animacemi, tak testujeme vzdalenost a smrt nepritele
if ((m_dwAnimationEnd >= pUnitData->m_dwRemainingTime) &&
(pUnitData->m_dwRemainingTime >= m_dwAnimationOffset))
{
// je nepratelska jednotka mrtva?
if (pUnitData->m_pAttackedUnit->GetLives() <= 0)
{
// nastavime vysledek syscallu na uspech
pUnitData->m_pSysCall->GetBag()->ReturnBool(true);
// ukoncit syscall
pUnitData->m_pSysCall->FinishWaiting(STATUS_SUCCESS);
// zapomenout na syscall
pUnitData->m_pSysCall->Release();
pUnitData->m_pSysCall = NULL;
// nastavime defaultni vzhled
pUnit->SetDefaultAppearanceID();
// deaktivujeme attack skillu
DeactivateSkill(pUnit);
return;
}
// spocitame vzdalenost nepratelske jednotky
DWORD dwDistance = pointPosition.GetDistanceSquare(pUnit->GetPosition());
// otestujeme, jestli je jednotka porad jeste v dosahu
// nasi palby; kdyz neni, tak deaktivujeme skillu a nastavime
// v syscallu navratovou hodnotu
if ((dwDistance > m_dwAttackRadiusSquare) ||
(m_dwAttackMinAltitude > dwAltitude) ||
(m_dwAttackMaxAltitude < dwAltitude))
{
// nastavit spravnou navratovou hodnotu do syscallu
pUnitData->m_pSysCall->GetBag()->ReturnBool(false);
// ukoncit syscall
pUnitData->m_pSysCall->FinishWaiting(STATUS_SUCCESS);
// zapomenout na syscall
pUnitData->m_pSysCall->Release();
pUnitData->m_pSysCall = NULL;
// nastavime defaultni vzhled
pUnit->SetDefaultAppearanceID();
// deaktivujeme attack skillu
DeactivateSkill(pUnit);
return;
}
}
// otestujeme konec animace
// (toto se musi udelat PRED zahajenim animace; kdyz je
// totiz animace stejne dlouha jako delka vystrelu,
// tak by byla porad zapnuta a klient, kdyz by animaci
// explicitne neloopoval, tak by se provedla jen jednou)
if (pUnitData->m_dwRemainingTime == m_dwAnimationEnd)
{
// koncime animaci
pUnit->SetDefaultAppearanceID();
}
// otestujeme zacatek animace
if (pUnitData->m_dwRemainingTime == m_dwAnimationOffset)
{
// zaciname animovat
pUnit->SetAppearanceID(m_dwAppearanceID);
}
// otestujeme, jestli je spravny okamzik na samotny vystrel
if (pUnitData->m_dwRemainingTime > 0)
{
pUnitData->m_dwRemainingTime--;
return;
}
// OK. Jsme na nule. Jdeme palit. HURAAA!!!
// prvne zase nahodime counter pro dalsi vystrel, at se na to nezapomene
pUnitData->m_dwRemainingTime = m_dwFirePeriod;
// Ted prolezeme VSECHNY defense skilly, kazde rekneme,
// jak moc do ni strilime, ony nam vrati, kolik ubrani,
// takze se postupne bude snizovat sila naseho utoku.
// Nakonec, kdyz zbyde jeste nejaka utocna sila,
// tak sekneme primo do ziveho masa...
DWORD dwSkillIndex = 0;
CSSkillType *pSkillType;
int nAttackIntensity = m_nAttackIntensity;
// nejprve potrebujeme zamknout napadenou jednotku na zapis,
// protoze na ni budeme volat defense skilly, ktere mohou
// na jednotce neco delat, no a nakonec doufejme taky neco odecteme
VERIFY(pUnitData->m_pAttackedUnit->PrivilegedThreadWriterLock());
while ((pSkillType = pUnitData->m_pAttackedUnit->GetUnitType()->GetNextSkillType(dwSkillIndex, Group_Defense)) != NULL)
{
// paranoia
ASSERT_KINDOF(CSAbstractDefenseSkillType, pSkillType);
// nasli jsme nejakou defense skillu,
// zavolame na ni DoDefense()
nAttackIntensity -= ((CSAbstractDefenseSkillType *)pSkillType)->DoDefense(pUnitData->m_pAttackedUnit, pUnit, m_nAttackIntensity, Interaction_Bullet);
}
// vyborne, mame spocitano, kolik opravdu ublizi tento utok napadene jednotce,
// ted to odecteme; kdyz uz te jednotce nateklo do bot, tak ji server
// sam zabije, o to se nebudeme starat...
pUnitData->m_pAttackedUnit->DecreaseLives(nAttackIntensity);
// posleme jednotce notifikaci, ze se na ni pali
// ??? jak se ma resit viditelnost agresora?
NotifyAttackedUnit(pUnit, pUnitData->m_pAttackedUnit, nAttackIntensity);
// tak to je cely, co jsme s tou jednotkou chteli udelat,
// odemkneme a smytec...
pUnitData->m_pAttackedUnit->PrivilegedThreadWriterUnlock();
}
////////////////////////////////////////////////////////////////////////
// Full Info
////////////////////////////////////////////////////////////////////////
void CSBulletAttackSkillType::FillFullInfo(CSUnit *pUnit, CString &strInfo)
{
// je skilla enabled na dane jednotce?
if (IsEnabled(pUnit))
{
strInfo.Format("Bullet Attack:\n Period: %u\n Intensity: %i", m_dwFirePeriod, m_nAttackIntensity);
}
else
{
strInfo = "Bullet Attack:\n (disabled)";
}
}
void CSBulletAttackSkillType::FillEnemyFullInfo(CSUnit *pUnit, CString &strInfo)
{
// vyplnime jen fakt, ze jednotka ma bullet attack
strInfo = "Bullet Attack Skill";
}
////////////////////////////////////////////////////////////////////////
// Interface ze skriptu - metoda "Fire"
////////////////////////////////////////////////////////////////////////
ESyscallResult CSBulletAttackSkillType::SCI_Fire(CSUnit *pUnit, CIProcess *pProcess, CISyscall **ppSysCall, CIBag *pBag, CIDataStackItem *pReturn, CZUnit *pAttackedUnit)
{
// zkontrolujeme parametry
ASSERT(pUnit != NULL);
ASSERT_KINDOF(CSUnit, pUnit);
ASSERT(pAttackedUnit != NULL);
ASSERT_KINDOF(CZUnit, pAttackedUnit);
TRACE_SKILLCALL("@ BulletAttack.Fire(%d) called on unit %d", pAttackedUnit->GetSUnit()->GetID(), pUnit->GetID());
// vytvorime syscall
CISysCallAttack *pSysCall = new CISysCallAttack;
// vyplnime syscall daty
VERIFY(pSysCall->Create(pProcess, pUnit, this, pBag));
// aktivujeme skillu
ActivateSkill(pUnit, pAttackedUnit->GetSUnit(), pSysCall);
// vratime pointer syscall interpretu (je addrefovany z Create)
*ppSysCall = pSysCall;
// uspime proces, protoze to bude dlouho trvat
return SYSCALL_SUCCESS_SLEEP;
}
////////////////////////////////////////////////////////////////////////
// Debugovaci metody
////////////////////////////////////////////////////////////////////////
#ifdef _DEBUG
void CSBulletAttackSkillType::AssertValid() const
{
// zavolame predka
CSAbstractAttackSkillType::AssertValid();
ASSERT(m_dwLoadTime <= 1000);
ASSERT(m_dwFirePeriod <= 1000);
ASSERT(m_nAttackIntensity >= 1);
ASSERT(m_nAttackIntensity <= 10000);
ASSERT(m_dwAttackRadius >= 1);
ASSERT(m_dwAttackRadius <= 128);
ASSERT(m_dwAttackRadiusSquare == m_dwAttackRadius * m_dwAttackRadius);
}
void CSBulletAttackSkillType::AssertValidUnit(SSBulletAttackSkill *pUnitData) const
{
// zavolame predka
CSAbstractAttackSkillType::AssertValidUnit(pUnitData);
// pointer na napadenou jednotku je bud NULL nebo neco poradneho
if (pUnitData->m_pAttackedUnit != NULL)
ASSERT_KINDOF(CSUnit, pUnitData->m_pAttackedUnit);
}
void CSBulletAttackSkillType::Dump(CDumpContext &dc) const
{
// zavolame predka
CSAbstractAttackSkillType::Dump(dc);
dc << "Bullet attack skill type:" << endl;
dc << " load time: " << m_dwLoadTime << endl;
dc << " period: " << m_dwFirePeriod << endl;
dc << " intensity: " << m_nAttackIntensity << endl;
dc << " radius: " << m_dwAttackRadius << endl;
}
#endif // _DEBUG
|
//
// Created by secondwtq 15-8-5.
// Copyright (c) 2015 The Xoundation Project All rights reserved.
//
#ifndef MOZJS_SPDE_CASTER_STRING_HXX
#define MOZJS_SPDE_CASTER_STRING_HXX
#include "../../thirdpt/js_engine.hxx"
#include <string>
namespace xoundation {
namespace spd {
template <typename T>
struct caster;
template<>
struct caster<const char *> {
using actualT = const char *;
using backT = const char *;
using jsT = JS::Value;
inline static jsT tojs(JSContext *c, actualT src) {
// should this be undefined?
if (src == nullptr) {
return JS::UndefinedValue(); }
return STRING_TO_JSVAL(JS_NewStringCopyZ(c, src));
}
};
template<>
struct caster<std::string> {
using actualT = const std::string&;
using backT = std::string;
using jsT = JS::Value;
inline static jsT tojs(JSContext *c, actualT src) {
return STRING_TO_JSVAL(JS_NewStringCopyZ(c, src.c_str())); }
inline static backT back(JSContext *c, JS::HandleValue src) {
return JS_EncodeString(c, src.toString()); }
};
template<>
struct caster<std::string&> {
using actualT = const std::string&;
using backT = std::string;
using jsT = JS::Value;
inline static jsT tojs(JSContext *c, actualT src) {
return STRING_TO_JSVAL(JS_NewStringCopyZ(c, src.c_str())); }
inline static backT back(JSContext *c, JS::HandleValue src) {
return JS_EncodeString(c, src.toString()); }
};
template<>
struct caster<const std::string&> {
using actualT = const std::string&;
using backT = std::string;
using jsT = JS::Value;
inline static jsT tojs(JSContext *c, actualT src) {
return STRING_TO_JSVAL(JS_NewStringCopyZ(c, src.c_str())); }
inline static backT back(JSContext *c, JS::HandleValue src) {
const char *t = JS_EncodeString(c, src.toString());
std::string ret(t);
JS_free(c, const_cast<char *>(t));
return ret;
}
};
}
}
#endif // MOZJS_SPDE_CASTER_STRING_HXX
|
#pragma once
#include "Definitions.hpp"
namespace SDK
{
class PlayerInfo {
private:
DWORD __pad0[2];
public:
//Vector origin;
int m_nXuidLow;
int m_nXuidHigh;
char m_szPlayerName[128];
int m_nUserID;
char m_szSteamID[33];
UINT m_nSteam3ID;
char m_szFriendsName[128];
bool m_bIsFakePlayer;
bool m_bIsHLTV;
DWORD m_dwCustomFiles[4];
BYTE m_FilesDownloaded;
private:
int __pad1;
};
}
|
#ifndef BOOST_MPL_OR_HPP_INCLUDED
#define BOOST_MPL_OR_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: or.hpp 13472 2017-08-22 07:53:44Z richean $
// $Date: 2017-08-22 09:53:44 +0200 (Di, 22 Aug 2017) $
// $Revision: 13472 $
#include <boost/mpl/aux_/config/use_preprocessed.hpp>
#if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \
&& !defined(BOOST_MPL_PREPROCESSING_MODE)
# include <boost/mpl/bool.hpp>
# include <boost/mpl/aux_/nested_type_wknd.hpp>
# include <boost/mpl/aux_/na_spec.hpp>
# include <boost/mpl/aux_/lambda_support.hpp>
# include <boost/mpl/aux_/config/msvc.hpp>
// agurt, 19/may/04: workaround a conflict with <iso646.h> header's
// 'or' and 'and' macros, see http://tinyurl.com/3et69; 'defined(or)'
// has to be checked in a separate condition, otherwise GCC complains
// about 'or' being an alternative token
#if defined(_MSC_VER) && !defined(__clang__)
#ifndef __GCCXML__
#if defined(or)
# pragma push_macro("or")
# undef or
# define or(x)
#endif
#endif
#endif
# define BOOST_MPL_PREPROCESSED_HEADER or.hpp
# include <boost/mpl/aux_/include_preprocessed.hpp>
#if defined(_MSC_VER) && !defined(__clang__)
#ifndef __GCCXML__
#if defined(or)
# pragma pop_macro("or")
#endif
#endif
#endif
#else
# define AUX778076_OP_NAME or_
# define AUX778076_OP_VALUE1 true
# define AUX778076_OP_VALUE2 false
# include <boost/mpl/aux_/logical_op.hpp>
#endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif // BOOST_MPL_OR_HPP_INCLUDED
|
//===- Local.cpp - Functions to perform local transformations -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform various local transformations to the
// program.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LazyValueInfo.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Analysis/VectorUtils.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/DomTreeUpdater.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/GlobalObject.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstdint>
#include <iterator>
#include <map>
#include <utility>
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "local"
STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
//===----------------------------------------------------------------------===//
// Local constant propagation.
//
/// ConstantFoldTerminator - If a terminator instruction is predicated on a
/// constant value, convert it into an unconditional branch to the constant
/// destination. This is a nontrivial operation because the successors of this
/// basic block must have their PHI nodes updated.
/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
/// conditions and indirectbr addresses this might make dead if
/// DeleteDeadConditions is true.
bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
const TargetLibraryInfo *TLI,
DomTreeUpdater *DTU) {
Instruction *T = BB->getTerminator();
IRBuilder<> Builder(T);
// Branch - See if we are conditional jumping on constant
if (auto *BI = dyn_cast<BranchInst>(T)) {
if (BI->isUnconditional()) return false; // Can't optimize uncond branch
BasicBlock *Dest1 = BI->getSuccessor(0);
BasicBlock *Dest2 = BI->getSuccessor(1);
if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
// Are we branching on constant?
// YES. Change to unconditional branch...
BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
// Let the basic block know that we are letting go of it. Based on this,
// it will adjust it's PHI nodes.
OldDest->removePredecessor(BB);
// Replace the conditional branch with an unconditional one.
Builder.CreateBr(Destination);
BI->eraseFromParent();
if (DTU)
DTU->deleteEdgeRelaxed(BB, OldDest);
return true;
}
if (Dest2 == Dest1) { // Conditional branch to same location?
// This branch matches something like this:
// br bool %cond, label %Dest, label %Dest
// and changes it into: br label %Dest
// Let the basic block know that we are letting go of one copy of it.
assert(BI->getParent() && "Terminator not inserted in block!");
Dest1->removePredecessor(BI->getParent());
// Replace the conditional branch with an unconditional one.
Builder.CreateBr(Dest1);
Value *Cond = BI->getCondition();
BI->eraseFromParent();
if (DeleteDeadConditions)
RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
return true;
}
return false;
}
if (auto *SI = dyn_cast<SwitchInst>(T)) {
// If we are switching on a constant, we can convert the switch to an
// unconditional branch.
auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
BasicBlock *DefaultDest = SI->getDefaultDest();
BasicBlock *TheOnlyDest = DefaultDest;
// If the default is unreachable, ignore it when searching for TheOnlyDest.
if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
SI->getNumCases() > 0) {
TheOnlyDest = SI->case_begin()->getCaseSuccessor();
}
// Figure out which case it goes to.
for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
// Found case matching a constant operand?
if (i->getCaseValue() == CI) {
TheOnlyDest = i->getCaseSuccessor();
break;
}
// Check to see if this branch is going to the same place as the default
// dest. If so, eliminate it as an explicit compare.
if (i->getCaseSuccessor() == DefaultDest) {
MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
unsigned NCases = SI->getNumCases();
// Fold the case metadata into the default if there will be any branches
// left, unless the metadata doesn't match the switch.
if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
// Collect branch weights into a vector.
SmallVector<uint32_t, 8> Weights;
for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
++MD_i) {
auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Weights.push_back(CI->getValue().getZExtValue());
}
// Merge weight of this case to the default weight.
unsigned idx = i->getCaseIndex();
Weights[0] += Weights[idx+1];
// Remove weight for this case.
std::swap(Weights[idx+1], Weights.back());
Weights.pop_back();
SI->setMetadata(LLVMContext::MD_prof,
MDBuilder(BB->getContext()).
createBranchWeights(Weights));
}
// Remove this entry.
BasicBlock *ParentBB = SI->getParent();
DefaultDest->removePredecessor(ParentBB);
i = SI->removeCase(i);
e = SI->case_end();
if (DTU)
DTU->deleteEdgeRelaxed(ParentBB, DefaultDest);
continue;
}
// Otherwise, check to see if the switch only branches to one destination.
// We do this by reseting "TheOnlyDest" to null when we find two non-equal
// destinations.
if (i->getCaseSuccessor() != TheOnlyDest)
TheOnlyDest = nullptr;
// Increment this iterator as we haven't removed the case.
++i;
}
if (CI && !TheOnlyDest) {
// Branching on a constant, but not any of the cases, go to the default
// successor.
TheOnlyDest = SI->getDefaultDest();
}
// If we found a single destination that we can fold the switch into, do so
// now.
if (TheOnlyDest) {
// Insert the new branch.
Builder.CreateBr(TheOnlyDest);
BasicBlock *BB = SI->getParent();
std::vector <DominatorTree::UpdateType> Updates;
if (DTU)
Updates.reserve(SI->getNumSuccessors() - 1);
// Remove entries from PHI nodes which we no longer branch to...
for (BasicBlock *Succ : successors(SI)) {
// Found case matching a constant operand?
if (Succ == TheOnlyDest) {
TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
} else {
Succ->removePredecessor(BB);
if (DTU)
Updates.push_back({DominatorTree::Delete, BB, Succ});
}
}
// Delete the old switch.
Value *Cond = SI->getCondition();
SI->eraseFromParent();
if (DeleteDeadConditions)
RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
if (DTU)
DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
return true;
}
if (SI->getNumCases() == 1) {
// Otherwise, we can fold this switch into a conditional branch
// instruction if it has only one non-default destination.
auto FirstCase = *SI->case_begin();
Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
FirstCase.getCaseValue(), "cond");
// Insert the new branch.
BranchInst *NewBr = Builder.CreateCondBr(Cond,
FirstCase.getCaseSuccessor(),
SI->getDefaultDest());
MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
if (MD && MD->getNumOperands() == 3) {
ConstantInt *SICase =
mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
ConstantInt *SIDef =
mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
assert(SICase && SIDef);
// The TrueWeight should be the weight for the single case of SI.
NewBr->setMetadata(LLVMContext::MD_prof,
MDBuilder(BB->getContext()).
createBranchWeights(SICase->getValue().getZExtValue(),
SIDef->getValue().getZExtValue()));
}
// Update make.implicit metadata to the newly-created conditional branch.
MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
if (MakeImplicitMD)
NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
// Delete the old switch.
SI->eraseFromParent();
return true;
}
return false;
}
if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
// indirectbr blockaddress(@F, @BB) -> br label @BB
if (auto *BA =
dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
BasicBlock *TheOnlyDest = BA->getBasicBlock();
std::vector <DominatorTree::UpdateType> Updates;
if (DTU)
Updates.reserve(IBI->getNumDestinations() - 1);
// Insert the new branch.
Builder.CreateBr(TheOnlyDest);
for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
if (IBI->getDestination(i) == TheOnlyDest) {
TheOnlyDest = nullptr;
} else {
BasicBlock *ParentBB = IBI->getParent();
BasicBlock *DestBB = IBI->getDestination(i);
DestBB->removePredecessor(ParentBB);
if (DTU)
Updates.push_back({DominatorTree::Delete, ParentBB, DestBB});
}
}
Value *Address = IBI->getAddress();
IBI->eraseFromParent();
if (DeleteDeadConditions)
RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
// If we didn't find our destination in the IBI successor list, then we
// have undefined behavior. Replace the unconditional branch with an
// 'unreachable' instruction.
if (TheOnlyDest) {
BB->getTerminator()->eraseFromParent();
new UnreachableInst(BB->getContext(), BB);
}
if (DTU)
DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
return true;
}
}
return false;
}
//===----------------------------------------------------------------------===//
// Local dead code elimination.
//
/// isInstructionTriviallyDead - Return true if the result produced by the
/// instruction is not used, and the instruction has no side effects.
///
bool llvm::isInstructionTriviallyDead(Instruction *I,
const TargetLibraryInfo *TLI) {
if (!I->use_empty())
return false;
return wouldInstructionBeTriviallyDead(I, TLI);
}
bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
const TargetLibraryInfo *TLI) {
if (I->isTerminator())
return false;
// We don't want the landingpad-like instructions removed by anything this
// general.
if (I->isEHPad())
return false;
// We don't want debug info removed by anything this general, unless
// debug info is empty.
if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
if (DDI->getAddress())
return false;
return true;
}
if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
if (DVI->getValue())
return false;
return true;
}
if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
if (DLI->getLabel())
return false;
return true;
}
if (!I->mayHaveSideEffects())
return true;
// Special case intrinsics that "may have side effects" but can be deleted
// when dead.
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
// Safe to delete llvm.stacksave and launder.invariant.group if dead.
if (II->getIntrinsicID() == Intrinsic::stacksave ||
II->getIntrinsicID() == Intrinsic::launder_invariant_group)
return true;
// Lifetime intrinsics are dead when their right-hand is undef.
if (II->isLifetimeStartOrEnd())
return isa<UndefValue>(II->getArgOperand(1));
// Assumptions are dead if their condition is trivially true. Guards on
// true are operationally no-ops. In the future we can consider more
// sophisticated tradeoffs for guards considering potential for check
// widening, but for now we keep things simple.
if (II->getIntrinsicID() == Intrinsic::assume ||
II->getIntrinsicID() == Intrinsic::experimental_guard) {
if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
return !Cond->isZero();
return false;
}
}
if (isAllocLikeFn(I, TLI))
return true;
if (CallInst *CI = isFreeCall(I, TLI))
if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
return C->isNullValue() || isa<UndefValue>(C);
if (CallSite CS = CallSite(I))
if (isMathLibCallNoop(CS, TLI))
return true;
return false;
}
/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
/// trivially dead instruction, delete it. If that makes any of its operands
/// trivially dead, delete them too, recursively. Return true if any
/// instructions were deleted.
bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU) {
Instruction *I = dyn_cast<Instruction>(V);
if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
return false;
SmallVector<Instruction*, 16> DeadInsts;
DeadInsts.push_back(I);
RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU);
return true;
}
void llvm::RecursivelyDeleteTriviallyDeadInstructions(
SmallVectorImpl<Instruction *> &DeadInsts, const TargetLibraryInfo *TLI,
MemorySSAUpdater *MSSAU) {
// Process the dead instruction list until empty.
while (!DeadInsts.empty()) {
Instruction &I = *DeadInsts.pop_back_val();
assert(I.use_empty() && "Instructions with uses are not dead.");
assert(isInstructionTriviallyDead(&I, TLI) &&
"Live instruction found in dead worklist!");
// Don't lose the debug info while deleting the instructions.
salvageDebugInfo(I);
// Null out all of the instruction's operands to see if any operand becomes
// dead as we go.
for (Use &OpU : I.operands()) {
Value *OpV = OpU.get();
OpU.set(nullptr);
if (!OpV->use_empty())
continue;
// If the operand is an instruction that became dead as we nulled out the
// operand, and if it is 'trivially' dead, delete it in a future loop
// iteration.
if (Instruction *OpI = dyn_cast<Instruction>(OpV))
if (isInstructionTriviallyDead(OpI, TLI))
DeadInsts.push_back(OpI);
}
if (MSSAU)
MSSAU->removeMemoryAccess(&I);
I.eraseFromParent();
}
}
bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
findDbgUsers(DbgUsers, I);
for (auto *DII : DbgUsers) {
Value *Undef = UndefValue::get(I->getType());
DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
ValueAsMetadata::get(Undef)));
}
return !DbgUsers.empty();
}
/// areAllUsesEqual - Check whether the uses of a value are all the same.
/// This is similar to Instruction::hasOneUse() except this will also return
/// true when there are no uses or multiple uses that all refer to the same
/// value.
static bool areAllUsesEqual(Instruction *I) {
Value::user_iterator UI = I->user_begin();
Value::user_iterator UE = I->user_end();
if (UI == UE)
return true;
User *TheUse = *UI;
for (++UI; UI != UE; ++UI) {
if (*UI != TheUse)
return false;
}
return true;
}
/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
/// dead PHI node, due to being a def-use chain of single-use nodes that
/// either forms a cycle or is terminated by a trivially dead instruction,
/// delete it. If that makes any of its operands trivially dead, delete them
/// too, recursively. Return true if a change was made.
bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
const TargetLibraryInfo *TLI) {
SmallPtrSet<Instruction*, 4> Visited;
for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
I = cast<Instruction>(*I->user_begin())) {
if (I->use_empty())
return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
// If we find an instruction more than once, we're on a cycle that
// won't prove fruitful.
if (!Visited.insert(I).second) {
// Break the cycle and delete the instruction and its operands.
I->replaceAllUsesWith(UndefValue::get(I->getType()));
(void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
return true;
}
}
return false;
}
static bool
simplifyAndDCEInstruction(Instruction *I,
SmallSetVector<Instruction *, 16> &WorkList,
const DataLayout &DL,
const TargetLibraryInfo *TLI) {
if (isInstructionTriviallyDead(I, TLI)) {
salvageDebugInfo(*I);
// Null out all of the instruction's operands to see if any operand becomes
// dead as we go.
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Value *OpV = I->getOperand(i);
I->setOperand(i, nullptr);
if (!OpV->use_empty() || I == OpV)
continue;
// If the operand is an instruction that became dead as we nulled out the
// operand, and if it is 'trivially' dead, delete it in a future loop
// iteration.
if (Instruction *OpI = dyn_cast<Instruction>(OpV))
if (isInstructionTriviallyDead(OpI, TLI))
WorkList.insert(OpI);
}
I->eraseFromParent();
return true;
}
if (Value *SimpleV = SimplifyInstruction(I, DL)) {
// Add the users to the worklist. CAREFUL: an instruction can use itself,
// in the case of a phi node.
for (User *U : I->users()) {
if (U != I) {
WorkList.insert(cast<Instruction>(U));
}
}
// Replace the instruction with its simplified value.
bool Changed = false;
if (!I->use_empty()) {
I->replaceAllUsesWith(SimpleV);
Changed = true;
}
if (isInstructionTriviallyDead(I, TLI)) {
I->eraseFromParent();
Changed = true;
}
return Changed;
}
return false;
}
/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
/// simplify any instructions in it and recursively delete dead instructions.
///
/// This returns true if it changed the code, note that it can delete
/// instructions in other blocks as well in this block.
bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
const TargetLibraryInfo *TLI) {
bool MadeChange = false;
const DataLayout &DL = BB->getModule()->getDataLayout();
#ifndef NDEBUG
// In debug builds, ensure that the terminator of the block is never replaced
// or deleted by these simplifications. The idea of simplification is that it
// cannot introduce new instructions, and there is no way to replace the
// terminator of a block without introducing a new instruction.
AssertingVH<Instruction> TerminatorVH(&BB->back());
#endif
SmallSetVector<Instruction *, 16> WorkList;
// Iterate over the original function, only adding insts to the worklist
// if they actually need to be revisited. This avoids having to pre-init
// the worklist with the entire function's worth of instructions.
for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
BI != E;) {
assert(!BI->isTerminator());
Instruction *I = &*BI;
++BI;
// We're visiting this instruction now, so make sure it's not in the
// worklist from an earlier visit.
if (!WorkList.count(I))
MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
}
while (!WorkList.empty()) {
Instruction *I = WorkList.pop_back_val();
MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
}
return MadeChange;
}
//===----------------------------------------------------------------------===//
// Control Flow Graph Restructuring.
//
/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
/// method is called when we're about to delete Pred as a predecessor of BB. If
/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
///
/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
/// nodes that collapse into identity values. For example, if we have:
/// x = phi(1, 0, 0, 0)
/// y = and x, z
///
/// .. and delete the predecessor corresponding to the '1', this will attempt to
/// recursively fold the and to 0.
void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
DomTreeUpdater *DTU) {
// This only adjusts blocks with PHI nodes.
if (!isa<PHINode>(BB->begin()))
return;
// Remove the entries for Pred from the PHI nodes in BB, but do not simplify
// them down. This will leave us with single entry phi nodes and other phis
// that can be removed.
BB->removePredecessor(Pred, true);
WeakTrackingVH PhiIt = &BB->front();
while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
Value *OldPhiIt = PhiIt;
if (!recursivelySimplifyInstruction(PN))
continue;
// If recursive simplification ended up deleting the next PHI node we would
// iterate to, then our iterator is invalid, restart scanning from the top
// of the block.
if (PhiIt != OldPhiIt) PhiIt = &BB->front();
}
if (DTU)
DTU->deleteEdgeRelaxed(Pred, BB);
}
/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
/// predecessor is known to have one successor (DestBB!). Eliminate the edge
/// between them, moving the instructions in the predecessor into DestBB and
/// deleting the predecessor block.
void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
DomTreeUpdater *DTU) {
// If BB has single-entry PHI nodes, fold them.
while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
Value *NewVal = PN->getIncomingValue(0);
// Replace self referencing PHI with undef, it must be dead.
if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
PN->replaceAllUsesWith(NewVal);
PN->eraseFromParent();
}
BasicBlock *PredBB = DestBB->getSinglePredecessor();
assert(PredBB && "Block doesn't have a single predecessor!");
bool ReplaceEntryBB = false;
if (PredBB == &DestBB->getParent()->getEntryBlock())
ReplaceEntryBB = true;
// DTU updates: Collect all the edges that enter
// PredBB. These dominator edges will be redirected to DestBB.
SmallVector<DominatorTree::UpdateType, 32> Updates;
if (DTU) {
Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
Updates.push_back({DominatorTree::Delete, *I, PredBB});
// This predecessor of PredBB may already have DestBB as a successor.
if (llvm::find(successors(*I), DestBB) == succ_end(*I))
Updates.push_back({DominatorTree::Insert, *I, DestBB});
}
}
// Zap anything that took the address of DestBB. Not doing this will give the
// address an invalid value.
if (DestBB->hasAddressTaken()) {
BlockAddress *BA = BlockAddress::get(DestBB);
Constant *Replacement =
ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
BA->getType()));
BA->destroyConstant();
}
// Anything that branched to PredBB now branches to DestBB.
PredBB->replaceAllUsesWith(DestBB);
// Splice all the instructions from PredBB to DestBB.
PredBB->getTerminator()->eraseFromParent();
DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
new UnreachableInst(PredBB->getContext(), PredBB);
// If the PredBB is the entry block of the function, move DestBB up to
// become the entry block after we erase PredBB.
if (ReplaceEntryBB)
DestBB->moveAfter(PredBB);
if (DTU) {
assert(PredBB->getInstList().size() == 1 &&
isa<UnreachableInst>(PredBB->getTerminator()) &&
"The successor list of PredBB isn't empty before "
"applying corresponding DTU updates.");
DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
DTU->deleteBB(PredBB);
// Recalculation of DomTree is needed when updating a forward DomTree and
// the Entry BB is replaced.
if (ReplaceEntryBB && DTU->hasDomTree()) {
// The entry block was removed and there is no external interface for
// the dominator tree to be notified of this change. In this corner-case
// we recalculate the entire tree.
DTU->recalculate(*(DestBB->getParent()));
}
}
else {
PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
}
}
/// CanMergeValues - Return true if we can choose one of these values to use
/// in place of the other. Note that we will always choose the non-undef
/// value to keep.
static bool CanMergeValues(Value *First, Value *Second) {
return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
}
/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
/// almost-empty BB ending in an unconditional branch to Succ, into Succ.
///
/// Assumption: Succ is the single successor for BB.
static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
<< Succ->getName() << "\n");
// Shortcut, if there is only a single predecessor it must be BB and merging
// is always safe
if (Succ->getSinglePredecessor()) return true;
// Make a list of the predecessors of BB
SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
// Look at all the phi nodes in Succ, to see if they present a conflict when
// merging these blocks
for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
PHINode *PN = cast<PHINode>(I);
// If the incoming value from BB is again a PHINode in
// BB which has the same incoming value for *PI as PN does, we can
// merge the phi nodes and then the blocks can still be merged
PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
if (BBPN && BBPN->getParent() == BB) {
for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
BasicBlock *IBB = PN->getIncomingBlock(PI);
if (BBPreds.count(IBB) &&
!CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
PN->getIncomingValue(PI))) {
LLVM_DEBUG(dbgs()
<< "Can't fold, phi node " << PN->getName() << " in "
<< Succ->getName() << " is conflicting with "
<< BBPN->getName() << " with regard to common predecessor "
<< IBB->getName() << "\n");
return false;
}
}
} else {
Value* Val = PN->getIncomingValueForBlock(BB);
for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
// See if the incoming value for the common predecessor is equal to the
// one for BB, in which case this phi node will not prevent the merging
// of the block.
BasicBlock *IBB = PN->getIncomingBlock(PI);
if (BBPreds.count(IBB) &&
!CanMergeValues(Val, PN->getIncomingValue(PI))) {
LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
<< " in " << Succ->getName()
<< " is conflicting with regard to common "
<< "predecessor " << IBB->getName() << "\n");
return false;
}
}
}
}
return true;
}
using PredBlockVector = SmallVector<BasicBlock *, 16>;
using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
/// Determines the value to use as the phi node input for a block.
///
/// Select between \p OldVal any value that we know flows from \p BB
/// to a particular phi on the basis of which one (if either) is not
/// undef. Update IncomingValues based on the selected value.
///
/// \param OldVal The value we are considering selecting.
/// \param BB The block that the value flows in from.
/// \param IncomingValues A map from block-to-value for other phi inputs
/// that we have examined.
///
/// \returns the selected value.
static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
IncomingValueMap &IncomingValues) {
if (!isa<UndefValue>(OldVal)) {
assert((!IncomingValues.count(BB) ||
IncomingValues.find(BB)->second == OldVal) &&
"Expected OldVal to match incoming value from BB!");
IncomingValues.insert(std::make_pair(BB, OldVal));
return OldVal;
}
IncomingValueMap::const_iterator It = IncomingValues.find(BB);
if (It != IncomingValues.end()) return It->second;
return OldVal;
}
/// Create a map from block to value for the operands of a
/// given phi.
///
/// Create a map from block to value for each non-undef value flowing
/// into \p PN.
///
/// \param PN The phi we are collecting the map for.
/// \param IncomingValues [out] The map from block to value for this phi.
static void gatherIncomingValuesToPhi(PHINode *PN,
IncomingValueMap &IncomingValues) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
BasicBlock *BB = PN->getIncomingBlock(i);
Value *V = PN->getIncomingValue(i);
if (!isa<UndefValue>(V))
IncomingValues.insert(std::make_pair(BB, V));
}
}
/// Replace the incoming undef values to a phi with the values
/// from a block-to-value map.
///
/// \param PN The phi we are replacing the undefs in.
/// \param IncomingValues A map from block to value.
static void replaceUndefValuesInPhi(PHINode *PN,
const IncomingValueMap &IncomingValues) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *V = PN->getIncomingValue(i);
if (!isa<UndefValue>(V)) continue;
BasicBlock *BB = PN->getIncomingBlock(i);
IncomingValueMap::const_iterator It = IncomingValues.find(BB);
if (It == IncomingValues.end()) continue;
PN->setIncomingValue(i, It->second);
}
}
/// Replace a value flowing from a block to a phi with
/// potentially multiple instances of that value flowing from the
/// block's predecessors to the phi.
///
/// \param BB The block with the value flowing into the phi.
/// \param BBPreds The predecessors of BB.
/// \param PN The phi that we are updating.
static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
const PredBlockVector &BBPreds,
PHINode *PN) {
Value *OldVal = PN->removeIncomingValue(BB, false);
assert(OldVal && "No entry in PHI for Pred BB!");
IncomingValueMap IncomingValues;
// We are merging two blocks - BB, and the block containing PN - and
// as a result we need to redirect edges from the predecessors of BB
// to go to the block containing PN, and update PN
// accordingly. Since we allow merging blocks in the case where the
// predecessor and successor blocks both share some predecessors,
// and where some of those common predecessors might have undef
// values flowing into PN, we want to rewrite those values to be
// consistent with the non-undef values.
gatherIncomingValuesToPhi(PN, IncomingValues);
// If this incoming value is one of the PHI nodes in BB, the new entries
// in the PHI node are the entries from the old PHI.
if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
PHINode *OldValPN = cast<PHINode>(OldVal);
for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
// Note that, since we are merging phi nodes and BB and Succ might
// have common predecessors, we could end up with a phi node with
// identical incoming branches. This will be cleaned up later (and
// will trigger asserts if we try to clean it up now, without also
// simplifying the corresponding conditional branch).
BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
Value *PredVal = OldValPN->getIncomingValue(i);
Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
IncomingValues);
// And add a new incoming value for this predecessor for the
// newly retargeted branch.
PN->addIncoming(Selected, PredBB);
}
} else {
for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
// Update existing incoming values in PN for this
// predecessor of BB.
BasicBlock *PredBB = BBPreds[i];
Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
IncomingValues);
// And add a new incoming value for this predecessor for the
// newly retargeted branch.
PN->addIncoming(Selected, PredBB);
}
}
replaceUndefValuesInPhi(PN, IncomingValues);
}
/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
/// unconditional branch, and contains no instructions other than PHI nodes,
/// potential side-effect free intrinsics and the branch. If possible,
/// eliminate BB by rewriting all the predecessors to branch to the successor
/// block and return true. If we can't transform, return false.
bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
DomTreeUpdater *DTU) {
assert(BB != &BB->getParent()->getEntryBlock() &&
"TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
// We can't eliminate infinite loops.
BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
if (BB == Succ) return false;
// Check to see if merging these blocks would cause conflicts for any of the
// phi nodes in BB or Succ. If not, we can safely merge.
if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
// Check for cases where Succ has multiple predecessors and a PHI node in BB
// has uses which will not disappear when the PHI nodes are merged. It is
// possible to handle such cases, but difficult: it requires checking whether
// BB dominates Succ, which is non-trivial to calculate in the case where
// Succ has multiple predecessors. Also, it requires checking whether
// constructing the necessary self-referential PHI node doesn't introduce any
// conflicts; this isn't too difficult, but the previous code for doing this
// was incorrect.
//
// Note that if this check finds a live use, BB dominates Succ, so BB is
// something like a loop pre-header (or rarely, a part of an irreducible CFG);
// folding the branch isn't profitable in that case anyway.
if (!Succ->getSinglePredecessor()) {
BasicBlock::iterator BBI = BB->begin();
while (isa<PHINode>(*BBI)) {
for (Use &U : BBI->uses()) {
if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
if (PN->getIncomingBlock(U) != BB)
return false;
} else {
return false;
}
}
++BBI;
}
}
LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
SmallVector<DominatorTree::UpdateType, 32> Updates;
if (DTU) {
Updates.push_back({DominatorTree::Delete, BB, Succ});
// All predecessors of BB will be moved to Succ.
for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
Updates.push_back({DominatorTree::Delete, *I, BB});
// This predecessor of BB may already have Succ as a successor.
if (llvm::find(successors(*I), Succ) == succ_end(*I))
Updates.push_back({DominatorTree::Insert, *I, Succ});
}
}
if (isa<PHINode>(Succ->begin())) {
// If there is more than one pred of succ, and there are PHI nodes in
// the successor, then we need to add incoming edges for the PHI nodes
//
const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
// Loop over all of the PHI nodes in the successor of BB.
for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
PHINode *PN = cast<PHINode>(I);
redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
}
}
if (Succ->getSinglePredecessor()) {
// BB is the only predecessor of Succ, so Succ will end up with exactly
// the same predecessors BB had.
// Copy over any phi, debug or lifetime instruction.
BB->getTerminator()->eraseFromParent();
Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
BB->getInstList());
} else {
while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
// We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
assert(PN->use_empty() && "There shouldn't be any uses here!");
PN->eraseFromParent();
}
}
// If the unconditional branch we replaced contains llvm.loop metadata, we
// add the metadata to the branch instructions in the predecessors.
unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
Instruction *TI = BB->getTerminator();
if (TI)
if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
BasicBlock *Pred = *PI;
Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
}
// Everything that jumped to BB now goes to Succ.
BB->replaceAllUsesWith(Succ);
if (!Succ->hasName()) Succ->takeName(BB);
// Clear the successor list of BB to match updates applying to DTU later.
if (BB->getTerminator())
BB->getInstList().pop_back();
new UnreachableInst(BB->getContext(), BB);
assert(succ_empty(BB) && "The successor list of BB isn't empty before "
"applying corresponding DTU updates.");
if (DTU) {
DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
DTU->deleteBB(BB);
} else {
BB->eraseFromParent(); // Delete the old basic block.
}
return true;
}
/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
/// nodes in this block. This doesn't try to be clever about PHI nodes
/// which differ only in the order of the incoming values, but instcombine
/// orders them so it usually won't matter.
bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
// This implementation doesn't currently consider undef operands
// specially. Theoretically, two phis which are identical except for
// one having an undef where the other doesn't could be collapsed.
struct PHIDenseMapInfo {
static PHINode *getEmptyKey() {
return DenseMapInfo<PHINode *>::getEmptyKey();
}
static PHINode *getTombstoneKey() {
return DenseMapInfo<PHINode *>::getTombstoneKey();
}
static unsigned getHashValue(PHINode *PN) {
// Compute a hash value on the operands. Instcombine will likely have
// sorted them, which helps expose duplicates, but we have to check all
// the operands to be safe in case instcombine hasn't run.
return static_cast<unsigned>(hash_combine(
hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
hash_combine_range(PN->block_begin(), PN->block_end())));
}
static bool isEqual(PHINode *LHS, PHINode *RHS) {
if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
RHS == getEmptyKey() || RHS == getTombstoneKey())
return LHS == RHS;
return LHS->isIdenticalTo(RHS);
}
};
// Set of unique PHINodes.
DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
// Examine each PHI.
bool Changed = false;
for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
auto Inserted = PHISet.insert(PN);
if (!Inserted.second) {
// A duplicate. Replace this PHI with its duplicate.
PN->replaceAllUsesWith(*Inserted.first);
PN->eraseFromParent();
Changed = true;
// The RAUW can change PHIs that we already visited. Start over from the
// beginning.
PHISet.clear();
I = BB->begin();
}
}
return Changed;
}
/// enforceKnownAlignment - If the specified pointer points to an object that
/// we control, modify the object's alignment to PrefAlign. This isn't
/// often possible though. If alignment is important, a more reliable approach
/// is to simply align all global variables and allocation instructions to
/// their preferred alignment from the beginning.
static unsigned enforceKnownAlignment(Value *V, unsigned Align,
unsigned PrefAlign,
const DataLayout &DL) {
assert(PrefAlign > Align);
V = V->stripPointerCasts();
if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
// TODO: ideally, computeKnownBits ought to have used
// AllocaInst::getAlignment() in its computation already, making
// the below max redundant. But, as it turns out,
// stripPointerCasts recurses through infinite layers of bitcasts,
// while computeKnownBits is not allowed to traverse more than 6
// levels.
Align = std::max(AI->getAlignment(), Align);
if (PrefAlign <= Align)
return Align;
// If the preferred alignment is greater than the natural stack alignment
// then don't round up. This avoids dynamic stack realignment.
if (DL.exceedsNaturalStackAlignment(PrefAlign))
return Align;
AI->setAlignment(PrefAlign);
return PrefAlign;
}
if (auto *GO = dyn_cast<GlobalObject>(V)) {
// TODO: as above, this shouldn't be necessary.
Align = std::max(GO->getAlignment(), Align);
if (PrefAlign <= Align)
return Align;
// If there is a large requested alignment and we can, bump up the alignment
// of the global. If the memory we set aside for the global may not be the
// memory used by the final program then it is impossible for us to reliably
// enforce the preferred alignment.
if (!GO->canIncreaseAlignment())
return Align;
GO->setAlignment(PrefAlign);
return PrefAlign;
}
return Align;
}
unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
const DataLayout &DL,
const Instruction *CxtI,
AssumptionCache *AC,
const DominatorTree *DT) {
assert(V->getType()->isPointerTy() &&
"getOrEnforceKnownAlignment expects a pointer!");
KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
unsigned TrailZ = Known.countMinTrailingZeros();
// Avoid trouble with ridiculously large TrailZ values, such as
// those computed from a null pointer.
TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
// LLVM doesn't support alignments larger than this currently.
Align = std::min(Align, +Value::MaximumAlignment);
if (PrefAlign > Align)
Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
// We don't need to make any adjustment.
return Align;
}
///===---------------------------------------------------------------------===//
/// Dbg Intrinsic utilities
///
/// See if there is a dbg.value intrinsic for DIVar before I.
static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
Instruction *I) {
// Since we can't guarantee that the original dbg.declare instrinsic
// is removed by LowerDbgDeclare(), we need to make sure that we are
// not inserting the same dbg.value intrinsic over and over.
BasicBlock::InstListType::iterator PrevI(I);
if (PrevI != I->getParent()->getInstList().begin()) {
--PrevI;
if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
if (DVI->getValue() == I->getOperand(0) &&
DVI->getVariable() == DIVar &&
DVI->getExpression() == DIExpr)
return true;
}
return false;
}
/// See if there is a dbg.value intrinsic for DIVar for the PHI node.
static bool PhiHasDebugValue(DILocalVariable *DIVar,
DIExpression *DIExpr,
PHINode *APN) {
// Since we can't guarantee that the original dbg.declare instrinsic
// is removed by LowerDbgDeclare(), we need to make sure that we are
// not inserting the same dbg.value intrinsic over and over.
SmallVector<DbgValueInst *, 1> DbgValues;
findDbgValues(DbgValues, APN);
for (auto *DVI : DbgValues) {
assert(DVI->getValue() == APN);
if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
return true;
}
return false;
}
/// Check if the alloc size of \p ValTy is large enough to cover the variable
/// (or fragment of the variable) described by \p DII.
///
/// This is primarily intended as a helper for the different
/// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
/// converted describes an alloca'd variable, so we need to use the
/// alloc size of the value when doing the comparison. E.g. an i1 value will be
/// identified as covering an n-bit fragment, if the store size of i1 is at
/// least n bits.
static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
const DataLayout &DL = DII->getModule()->getDataLayout();
uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy);
if (auto FragmentSize = DII->getFragmentSizeInBits())
return ValueSize >= *FragmentSize;
// We can't always calculate the size of the DI variable (e.g. if it is a
// VLA). Try to use the size of the alloca that the dbg intrinsic describes
// intead.
if (DII->isAddressOfVariable())
if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
if (auto FragmentSize = AI->getAllocationSizeInBits(DL))
return ValueSize >= *FragmentSize;
// Could not determine size of variable. Conservatively return false.
return false;
}
/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
/// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
StoreInst *SI, DIBuilder &Builder) {
assert(DII->isAddressOfVariable());
auto *DIVar = DII->getVariable();
assert(DIVar && "Missing variable");
auto *DIExpr = DII->getExpression();
Value *DV = SI->getOperand(0);
if (!valueCoversEntireFragment(SI->getValueOperand()->getType(), DII)) {
// FIXME: If storing to a part of the variable described by the dbg.declare,
// then we want to insert a dbg.value for the corresponding fragment.
LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
<< *DII << '\n');
// For now, when there is a store to parts of the variable (but we do not
// know which part) we insert an dbg.value instrinsic to indicate that we
// know nothing about the variable's content.
DV = UndefValue::get(DV->getType());
if (!LdStHasDebugValue(DIVar, DIExpr, SI))
Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
SI);
return;
}
if (!LdStHasDebugValue(DIVar, DIExpr, SI))
Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
SI);
}
/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
/// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
LoadInst *LI, DIBuilder &Builder) {
auto *DIVar = DII->getVariable();
auto *DIExpr = DII->getExpression();
assert(DIVar && "Missing variable");
if (LdStHasDebugValue(DIVar, DIExpr, LI))
return;
if (!valueCoversEntireFragment(LI->getType(), DII)) {
// FIXME: If only referring to a part of the variable described by the
// dbg.declare, then we want to insert a dbg.value for the corresponding
// fragment.
LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
<< *DII << '\n');
return;
}
// We are now tracking the loaded value instead of the address. In the
// future if multi-location support is added to the IR, it might be
// preferable to keep tracking both the loaded value and the original
// address in case the alloca can not be elided.
Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
LI, DIVar, DIExpr, DII->getDebugLoc(), (Instruction *)nullptr);
DbgValue->insertAfter(LI);
}
/// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
/// llvm.dbg.declare or llvm.dbg.addr intrinsic.
void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
PHINode *APN, DIBuilder &Builder) {
auto *DIVar = DII->getVariable();
auto *DIExpr = DII->getExpression();
assert(DIVar && "Missing variable");
if (PhiHasDebugValue(DIVar, DIExpr, APN))
return;
if (!valueCoversEntireFragment(APN->getType(), DII)) {
// FIXME: If only referring to a part of the variable described by the
// dbg.declare, then we want to insert a dbg.value for the corresponding
// fragment.
LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
<< *DII << '\n');
return;
}
BasicBlock *BB = APN->getParent();
auto InsertionPt = BB->getFirstInsertionPt();
// The block may be a catchswitch block, which does not have a valid
// insertion point.
// FIXME: Insert dbg.value markers in the successors when appropriate.
if (InsertionPt != BB->end())
Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, DII->getDebugLoc(),
&*InsertionPt);
}
/// Determine whether this alloca is either a VLA or an array.
static bool isArray(AllocaInst *AI) {
return AI->isArrayAllocation() ||
AI->getType()->getElementType()->isArrayTy();
}
/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
/// of llvm.dbg.value intrinsics.
bool llvm::LowerDbgDeclare(Function &F) {
DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
SmallVector<DbgDeclareInst *, 4> Dbgs;
for (auto &FI : F)
for (Instruction &BI : FI)
if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
Dbgs.push_back(DDI);
if (Dbgs.empty())
return false;
for (auto &I : Dbgs) {
DbgDeclareInst *DDI = I;
AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
// If this is an alloca for a scalar variable, insert a dbg.value
// at each load and store to the alloca and erase the dbg.declare.
// The dbg.values allow tracking a variable even if it is not
// stored on the stack, while the dbg.declare can only describe
// the stack slot (and at a lexical-scope granularity). Later
// passes will attempt to elide the stack slot.
if (!AI || isArray(AI))
continue;
// A volatile load/store means that the alloca can't be elided anyway.
if (llvm::any_of(AI->users(), [](User *U) -> bool {
if (LoadInst *LI = dyn_cast<LoadInst>(U))
return LI->isVolatile();
if (StoreInst *SI = dyn_cast<StoreInst>(U))
return SI->isVolatile();
return false;
}))
continue;
for (auto &AIUse : AI->uses()) {
User *U = AIUse.getUser();
if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
if (AIUse.getOperandNo() == 1)
ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
} else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
} else if (CallInst *CI = dyn_cast<CallInst>(U)) {
// This is a call by-value or some other instruction that takes a
// pointer to the variable. Insert a *value* intrinsic that describes
// the variable by dereferencing the alloca.
auto *DerefExpr =
DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
DDI->getDebugLoc(), CI);
}
}
DDI->eraseFromParent();
}
return true;
}
/// Propagate dbg.value intrinsics through the newly inserted PHIs.
void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
SmallVectorImpl<PHINode *> &InsertedPHIs) {
assert(BB && "No BasicBlock to clone dbg.value(s) from.");
if (InsertedPHIs.size() == 0)
return;
// Map existing PHI nodes to their dbg.values.
ValueToValueMapTy DbgValueMap;
for (auto &I : *BB) {
if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
DbgValueMap.insert({Loc, DbgII});
}
}
if (DbgValueMap.size() == 0)
return;
// Then iterate through the new PHIs and look to see if they use one of the
// previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
// propagate the info through the new PHI.
LLVMContext &C = BB->getContext();
for (auto PHI : InsertedPHIs) {
BasicBlock *Parent = PHI->getParent();
// Avoid inserting an intrinsic into an EH block.
if (Parent->getFirstNonPHI()->isEHPad())
continue;
auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
for (auto VI : PHI->operand_values()) {
auto V = DbgValueMap.find(VI);
if (V != DbgValueMap.end()) {
auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
Instruction *NewDbgII = DbgII->clone();
NewDbgII->setOperand(0, PhiMAV);
auto InsertionPt = Parent->getFirstInsertionPt();
assert(InsertionPt != Parent->end() && "Ill-formed basic block");
NewDbgII->insertBefore(&*InsertionPt);
}
}
}
}
/// Finds all intrinsics declaring local variables as living in the memory that
/// 'V' points to. This may include a mix of dbg.declare and
/// dbg.addr intrinsics.
TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
// This function is hot. Check whether the value has any metadata to avoid a
// DenseMap lookup.
if (!V->isUsedByMetadata())
return {};
auto *L = LocalAsMetadata::getIfExists(V);
if (!L)
return {};
auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
if (!MDV)
return {};
TinyPtrVector<DbgVariableIntrinsic *> Declares;
for (User *U : MDV->users()) {
if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
if (DII->isAddressOfVariable())
Declares.push_back(DII);
}
return Declares;
}
void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
// This function is hot. Check whether the value has any metadata to avoid a
// DenseMap lookup.
if (!V->isUsedByMetadata())
return;
if (auto *L = LocalAsMetadata::getIfExists(V))
if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
for (User *U : MDV->users())
if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
DbgValues.push_back(DVI);
}
void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
Value *V) {
// This function is hot. Check whether the value has any metadata to avoid a
// DenseMap lookup.
if (!V->isUsedByMetadata())
return;
if (auto *L = LocalAsMetadata::getIfExists(V))
if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
for (User *U : MDV->users())
if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
DbgUsers.push_back(DII);
}
bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
Instruction *InsertBefore, DIBuilder &Builder,
bool DerefBefore, int Offset, bool DerefAfter) {
auto DbgAddrs = FindDbgAddrUses(Address);
for (DbgVariableIntrinsic *DII : DbgAddrs) {
DebugLoc Loc = DII->getDebugLoc();
auto *DIVar = DII->getVariable();
auto *DIExpr = DII->getExpression();
assert(DIVar && "Missing variable");
DIExpr = DIExpression::prepend(DIExpr, DerefBefore, Offset, DerefAfter);
// Insert llvm.dbg.declare immediately before InsertBefore, and remove old
// llvm.dbg.declare.
Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
if (DII == InsertBefore)
InsertBefore = InsertBefore->getNextNode();
DII->eraseFromParent();
}
return !DbgAddrs.empty();
}
bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
DIBuilder &Builder, bool DerefBefore,
int Offset, bool DerefAfter) {
return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
DerefBefore, Offset, DerefAfter);
}
static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
DIBuilder &Builder, int Offset) {
DebugLoc Loc = DVI->getDebugLoc();
auto *DIVar = DVI->getVariable();
auto *DIExpr = DVI->getExpression();
assert(DIVar && "Missing variable");
// This is an alloca-based llvm.dbg.value. The first thing it should do with
// the alloca pointer is dereference it. Otherwise we don't know how to handle
// it and give up.
if (!DIExpr || DIExpr->getNumElements() < 1 ||
DIExpr->getElement(0) != dwarf::DW_OP_deref)
return;
// Insert the offset immediately after the first deref.
// We could just change the offset argument of dbg.value, but it's unsigned...
if (Offset) {
SmallVector<uint64_t, 4> Ops;
Ops.push_back(dwarf::DW_OP_deref);
DIExpression::appendOffset(Ops, Offset);
Ops.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
DIExpr = Builder.createExpression(Ops);
}
Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
DVI->eraseFromParent();
}
void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
DIBuilder &Builder, int Offset) {
if (auto *L = LocalAsMetadata::getIfExists(AI))
if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
Use &U = *UI++;
if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
}
}
/// Wrap \p V in a ValueAsMetadata instance.
static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
return MetadataAsValue::get(C, ValueAsMetadata::get(V));
}
bool llvm::salvageDebugInfo(Instruction &I) {
SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
findDbgUsers(DbgUsers, &I);
if (DbgUsers.empty())
return false;
auto &M = *I.getModule();
auto &DL = M.getDataLayout();
auto &Ctx = I.getContext();
auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
auto doSalvage = [&](DbgVariableIntrinsic *DII, SmallVectorImpl<uint64_t> &Ops) {
auto *DIExpr = DII->getExpression();
if (!Ops.empty()) {
// Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
// are implicitly pointing out the value as a DWARF memory location
// description.
bool WithStackValue = isa<DbgValueInst>(DII);
DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
}
DII->setOperand(0, wrapMD(I.getOperand(0)));
DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
};
auto applyOffset = [&](DbgVariableIntrinsic *DII, uint64_t Offset) {
SmallVector<uint64_t, 8> Ops;
DIExpression::appendOffset(Ops, Offset);
doSalvage(DII, Ops);
};
auto applyOps = [&](DbgVariableIntrinsic *DII,
std::initializer_list<uint64_t> Opcodes) {
SmallVector<uint64_t, 8> Ops(Opcodes);
doSalvage(DII, Ops);
};
if (auto *CI = dyn_cast<CastInst>(&I)) {
if (!CI->isNoopCast(DL))
return false;
// No-op casts are irrelevant for debug info.
MetadataAsValue *CastSrc = wrapMD(I.getOperand(0));
for (auto *DII : DbgUsers) {
DII->setOperand(0, CastSrc);
LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
}
return true;
} else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
unsigned BitWidth =
M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
// Rewrite a constant GEP into a DIExpression. Since we are performing
// arithmetic to compute the variable's *value* in the DIExpression, we
// need to mark the expression with a DW_OP_stack_value.
APInt Offset(BitWidth, 0);
if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset))
for (auto *DII : DbgUsers)
applyOffset(DII, Offset.getSExtValue());
return true;
} else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
// Rewrite binary operations with constant integer operands.
auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
if (!ConstInt || ConstInt->getBitWidth() > 64)
return false;
uint64_t Val = ConstInt->getSExtValue();
for (auto *DII : DbgUsers) {
switch (BI->getOpcode()) {
case Instruction::Add:
applyOffset(DII, Val);
break;
case Instruction::Sub:
applyOffset(DII, -int64_t(Val));
break;
case Instruction::Mul:
applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
break;
case Instruction::SDiv:
applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
break;
case Instruction::SRem:
applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
break;
case Instruction::Or:
applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
break;
case Instruction::And:
applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
break;
case Instruction::Xor:
applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
break;
case Instruction::Shl:
applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
break;
case Instruction::LShr:
applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
break;
case Instruction::AShr:
applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
break;
default:
// TODO: Salvage constants from each kind of binop we know about.
return false;
}
}
return true;
} else if (isa<LoadInst>(&I)) {
MetadataAsValue *AddrMD = wrapMD(I.getOperand(0));
for (auto *DII : DbgUsers) {
// Rewrite the load into DW_OP_deref.
auto *DIExpr = DII->getExpression();
DIExpr = DIExpression::prepend(DIExpr, DIExpression::WithDeref);
DII->setOperand(0, AddrMD);
DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
}
return true;
}
return false;
}
/// A replacement for a dbg.value expression.
using DbgValReplacement = Optional<DIExpression *>;
/// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
/// possibly moving/deleting users to prevent use-before-def. Returns true if
/// changes are made.
static bool rewriteDebugUsers(
Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
// Find debug users of From.
SmallVector<DbgVariableIntrinsic *, 1> Users;
findDbgUsers(Users, &From);
if (Users.empty())
return false;
// Prevent use-before-def of To.
bool Changed = false;
SmallPtrSet<DbgVariableIntrinsic *, 1> DeleteOrSalvage;
if (isa<Instruction>(&To)) {
bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
for (auto *DII : Users) {
// It's common to see a debug user between From and DomPoint. Move it
// after DomPoint to preserve the variable update without any reordering.
if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n');
DII->moveAfter(&DomPoint);
Changed = true;
// Users which otherwise aren't dominated by the replacement value must
// be salvaged or deleted.
} else if (!DT.dominates(&DomPoint, DII)) {
DeleteOrSalvage.insert(DII);
}
}
}
// Update debug users without use-before-def risk.
for (auto *DII : Users) {
if (DeleteOrSalvage.count(DII))
continue;
LLVMContext &Ctx = DII->getContext();
DbgValReplacement DVR = RewriteExpr(*DII);
if (!DVR)
continue;
DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n');
Changed = true;
}
if (!DeleteOrSalvage.empty()) {
// Try to salvage the remaining debug users.
Changed |= salvageDebugInfo(From);
// Delete the debug users which weren't salvaged.
for (auto *DII : DeleteOrSalvage) {
if (DII->getVariableLocation() == &From) {
LLVM_DEBUG(dbgs() << "Erased UseBeforeDef: " << *DII << '\n');
DII->eraseFromParent();
Changed = true;
}
}
}
return Changed;
}
/// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
/// losslessly preserve the bits and semantics of the value. This predicate is
/// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
///
/// Note that Type::canLosslesslyBitCastTo is not suitable here because it
/// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
/// and also does not allow lossless pointer <-> integer conversions.
static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
Type *ToTy) {
// Trivially compatible types.
if (FromTy == ToTy)
return true;
// Handle compatible pointer <-> integer conversions.
if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
!DL.isNonIntegralPointerType(ToTy);
return SameSize && LosslessConversion;
}
// TODO: This is not exhaustive.
return false;
}
bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
Instruction &DomPoint, DominatorTree &DT) {
// Exit early if From has no debug users.
if (!From.isUsedByMetadata())
return false;
assert(&From != &To && "Can't replace something with itself");
Type *FromTy = From.getType();
Type *ToTy = To.getType();
auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
return DII.getExpression();
};
// Handle no-op conversions.
Module &M = *From.getModule();
const DataLayout &DL = M.getDataLayout();
if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
// Handle integer-to-integer widening and narrowing.
// FIXME: Use DW_OP_convert when it's available everywhere.
if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
assert(FromBits != ToBits && "Unexpected no-op conversion");
// When the width of the result grows, assume that a debugger will only
// access the low `FromBits` bits when inspecting the source variable.
if (FromBits < ToBits)
return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
// The width of the result has shrunk. Use sign/zero extension to describe
// the source variable's high bits.
auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
DILocalVariable *Var = DII.getVariable();
// Without knowing signedness, sign/zero extension isn't possible.
auto Signedness = Var->getSignedness();
if (!Signedness)
return None;
bool Signed = *Signedness == DIBasicType::Signedness::Signed;
if (!Signed) {
// In the unsigned case, assume that a debugger will initialize the
// high bits to 0 and do a no-op conversion.
return Identity(DII);
} else {
// In the signed case, the high bits are given by sign extension, i.e:
// (To >> (ToBits - 1)) * ((2 ^ FromBits) - 1)
// Calculate the high bits and OR them together with the low bits.
SmallVector<uint64_t, 8> Ops({dwarf::DW_OP_dup, dwarf::DW_OP_constu,
(ToBits - 1), dwarf::DW_OP_shr,
dwarf::DW_OP_lit0, dwarf::DW_OP_not,
dwarf::DW_OP_mul, dwarf::DW_OP_or});
return DIExpression::appendToStack(DII.getExpression(), Ops);
}
};
return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
}
// TODO: Floating-point conversions, vectors.
return false;
}
unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
unsigned NumDeadInst = 0;
// Delete the instructions backwards, as it has a reduced likelihood of
// having to update as many def-use and use-def chains.
Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
while (EndInst != &BB->front()) {
// Delete the next to last instruction.
Instruction *Inst = &*--EndInst->getIterator();
if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
EndInst = Inst;
continue;
}
if (!isa<DbgInfoIntrinsic>(Inst))
++NumDeadInst;
Inst->eraseFromParent();
}
return NumDeadInst;
}
unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
bool PreserveLCSSA, DomTreeUpdater *DTU) {
BasicBlock *BB = I->getParent();
std::vector <DominatorTree::UpdateType> Updates;
// Loop over all of the successors, removing BB's entry from any PHI
// nodes.
if (DTU)
Updates.reserve(BB->getTerminator()->getNumSuccessors());
for (BasicBlock *Successor : successors(BB)) {
Successor->removePredecessor(BB, PreserveLCSSA);
if (DTU)
Updates.push_back({DominatorTree::Delete, BB, Successor});
}
// Insert a call to llvm.trap right before this. This turns the undefined
// behavior into a hard fail instead of falling through into random code.
if (UseLLVMTrap) {
Function *TrapFn =
Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
CallTrap->setDebugLoc(I->getDebugLoc());
}
auto *UI = new UnreachableInst(I->getContext(), I);
UI->setDebugLoc(I->getDebugLoc());
// All instructions after this are dead.
unsigned NumInstrsRemoved = 0;
BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
while (BBI != BBE) {
if (!BBI->use_empty())
BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
BB->getInstList().erase(BBI++);
++NumInstrsRemoved;
}
if (DTU)
DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
return NumInstrsRemoved;
}
/// changeToCall - Convert the specified invoke into a normal call.
static void changeToCall(InvokeInst *II, DomTreeUpdater *DTU = nullptr) {
SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
SmallVector<OperandBundleDef, 1> OpBundles;
II->getOperandBundlesAsDefs(OpBundles);
CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
"", II);
NewCall->takeName(II);
NewCall->setCallingConv(II->getCallingConv());
NewCall->setAttributes(II->getAttributes());
NewCall->setDebugLoc(II->getDebugLoc());
NewCall->copyMetadata(*II);
II->replaceAllUsesWith(NewCall);
// Follow the call by a branch to the normal destination.
BasicBlock *NormalDestBB = II->getNormalDest();
BranchInst::Create(NormalDestBB, II);
// Update PHI nodes in the unwind destination
BasicBlock *BB = II->getParent();
BasicBlock *UnwindDestBB = II->getUnwindDest();
UnwindDestBB->removePredecessor(BB);
II->eraseFromParent();
if (DTU)
DTU->deleteEdgeRelaxed(BB, UnwindDestBB);
}
BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
BasicBlock *UnwindEdge) {
BasicBlock *BB = CI->getParent();
// Convert this function call into an invoke instruction. First, split the
// basic block.
BasicBlock *Split =
BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
// Delete the unconditional branch inserted by splitBasicBlock
BB->getInstList().pop_back();
// Create the new invoke instruction.
SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
SmallVector<OperandBundleDef, 1> OpBundles;
CI->getOperandBundlesAsDefs(OpBundles);
// Note: we're round tripping operand bundles through memory here, and that
// can potentially be avoided with a cleverer API design that we do not have
// as of this time.
InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge,
InvokeArgs, OpBundles, CI->getName(), BB);
II->setDebugLoc(CI->getDebugLoc());
II->setCallingConv(CI->getCallingConv());
II->setAttributes(CI->getAttributes());
// Make sure that anything using the call now uses the invoke! This also
// updates the CallGraph if present, because it uses a WeakTrackingVH.
CI->replaceAllUsesWith(II);
// Delete the original call
Split->getInstList().pop_front();
return Split;
}
static bool markAliveBlocks(Function &F,
SmallPtrSetImpl<BasicBlock *> &Reachable,
DomTreeUpdater *DTU = nullptr) {
SmallVector<BasicBlock*, 128> Worklist;
BasicBlock *BB = &F.front();
Worklist.push_back(BB);
Reachable.insert(BB);
bool Changed = false;
do {
BB = Worklist.pop_back_val();
// Do a quick scan of the basic block, turning any obviously unreachable
// instructions into LLVM unreachable insts. The instruction combining pass
// canonicalizes unreachable insts into stores to null or undef.
for (Instruction &I : *BB) {
if (auto *CI = dyn_cast<CallInst>(&I)) {
Value *Callee = CI->getCalledValue();
// Handle intrinsic calls.
if (Function *F = dyn_cast<Function>(Callee)) {
auto IntrinsicID = F->getIntrinsicID();
// Assumptions that are known to be false are equivalent to
// unreachable. Also, if the condition is undefined, then we make the
// choice most beneficial to the optimizer, and choose that to also be
// unreachable.
if (IntrinsicID == Intrinsic::assume) {
if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
// Don't insert a call to llvm.trap right before the unreachable.
changeToUnreachable(CI, false, false, DTU);
Changed = true;
break;
}
} else if (IntrinsicID == Intrinsic::experimental_guard) {
// A call to the guard intrinsic bails out of the current
// compilation unit if the predicate passed to it is false. If the
// predicate is a constant false, then we know the guard will bail
// out of the current compile unconditionally, so all code following
// it is dead.
//
// Note: unlike in llvm.assume, it is not "obviously profitable" for
// guards to treat `undef` as `false` since a guard on `undef` can
// still be useful for widening.
if (match(CI->getArgOperand(0), m_Zero()))
if (!isa<UnreachableInst>(CI->getNextNode())) {
changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
false, DTU);
Changed = true;
break;
}
}
} else if ((isa<ConstantPointerNull>(Callee) &&
!NullPointerIsDefined(CI->getFunction())) ||
isa<UndefValue>(Callee)) {
changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
Changed = true;
break;
}
if (CI->doesNotReturn()) {
// If we found a call to a no-return function, insert an unreachable
// instruction after it. Make sure there isn't *already* one there
// though.
if (!isa<UnreachableInst>(CI->getNextNode())) {
// Don't insert a call to llvm.trap right before the unreachable.
changeToUnreachable(CI->getNextNode(), false, false, DTU);
Changed = true;
}
break;
}
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
// Store to undef and store to null are undefined and used to signal
// that they should be changed to unreachable by passes that can't
// modify the CFG.
// Don't touch volatile stores.
if (SI->isVolatile()) continue;
Value *Ptr = SI->getOperand(1);
if (isa<UndefValue>(Ptr) ||
(isa<ConstantPointerNull>(Ptr) &&
!NullPointerIsDefined(SI->getFunction(),
SI->getPointerAddressSpace()))) {
changeToUnreachable(SI, true, false, DTU);
Changed = true;
break;
}
}
}
Instruction *Terminator = BB->getTerminator();
if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
// Turn invokes that call 'nounwind' functions into ordinary calls.
Value *Callee = II->getCalledValue();
if ((isa<ConstantPointerNull>(Callee) &&
!NullPointerIsDefined(BB->getParent())) ||
isa<UndefValue>(Callee)) {
changeToUnreachable(II, true, false, DTU);
Changed = true;
} else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
if (II->use_empty() && II->onlyReadsMemory()) {
// jump to the normal destination branch.
BasicBlock *NormalDestBB = II->getNormalDest();
BasicBlock *UnwindDestBB = II->getUnwindDest();
BranchInst::Create(NormalDestBB, II);
UnwindDestBB->removePredecessor(II->getParent());
II->eraseFromParent();
if (DTU)
DTU->deleteEdgeRelaxed(BB, UnwindDestBB);
} else
changeToCall(II, DTU);
Changed = true;
}
} else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
// Remove catchpads which cannot be reached.
struct CatchPadDenseMapInfo {
static CatchPadInst *getEmptyKey() {
return DenseMapInfo<CatchPadInst *>::getEmptyKey();
}
static CatchPadInst *getTombstoneKey() {
return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
}
static unsigned getHashValue(CatchPadInst *CatchPad) {
return static_cast<unsigned>(hash_combine_range(
CatchPad->value_op_begin(), CatchPad->value_op_end()));
}
static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
RHS == getEmptyKey() || RHS == getTombstoneKey())
return LHS == RHS;
return LHS->isIdenticalTo(RHS);
}
};
// Set of unique CatchPads.
SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
HandlerSet;
detail::DenseSetEmpty Empty;
for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
E = CatchSwitch->handler_end();
I != E; ++I) {
BasicBlock *HandlerBB = *I;
auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
if (!HandlerSet.insert({CatchPad, Empty}).second) {
CatchSwitch->removeHandler(I);
--I;
--E;
Changed = true;
}
}
}
Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
for (BasicBlock *Successor : successors(BB))
if (Reachable.insert(Successor).second)
Worklist.push_back(Successor);
} while (!Worklist.empty());
return Changed;
}
void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
Instruction *TI = BB->getTerminator();
if (auto *II = dyn_cast<InvokeInst>(TI)) {
changeToCall(II, DTU);
return;
}
Instruction *NewTI;
BasicBlock *UnwindDest;
if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
UnwindDest = CRI->getUnwindDest();
} else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
auto *NewCatchSwitch = CatchSwitchInst::Create(
CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
CatchSwitch->getName(), CatchSwitch);
for (BasicBlock *PadBB : CatchSwitch->handlers())
NewCatchSwitch->addHandler(PadBB);
NewTI = NewCatchSwitch;
UnwindDest = CatchSwitch->getUnwindDest();
} else {
llvm_unreachable("Could not find unwind successor");
}
NewTI->takeName(TI);
NewTI->setDebugLoc(TI->getDebugLoc());
UnwindDest->removePredecessor(BB);
TI->replaceAllUsesWith(NewTI);
TI->eraseFromParent();
if (DTU)
DTU->deleteEdgeRelaxed(BB, UnwindDest);
}
/// removeUnreachableBlocks - Remove blocks that are not reachable, even
/// if they are in a dead cycle. Return true if a change was made, false
/// otherwise. If `LVI` is passed, this function preserves LazyValueInfo
/// after modifying the CFG.
bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI,
DomTreeUpdater *DTU,
MemorySSAUpdater *MSSAU) {
// RetDec - new code start
// Do not remove unreachable BBs if specific named metadata are present in
// the module.
//
if (F.getParent()->getNamedMetadata("llvmToAsmGlobalVariableName")) {
return false;
}
// RetDec - new code end
SmallPtrSet<BasicBlock*, 16> Reachable;
bool Changed = markAliveBlocks(F, Reachable, DTU);
// If there are unreachable blocks in the CFG...
if (Reachable.size() == F.size())
return Changed;
assert(Reachable.size() < F.size());
NumRemoved += F.size()-Reachable.size();
SmallPtrSet<BasicBlock *, 16> DeadBlockSet;
for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ++I) {
auto *BB = &*I;
if (Reachable.count(BB))
continue;
DeadBlockSet.insert(BB);
}
if (MSSAU)
MSSAU->removeBlocks(DeadBlockSet);
// Loop over all of the basic blocks that are not reachable, dropping all of
// their internal references. Update DTU and LVI if available.
std::vector<DominatorTree::UpdateType> Updates;
for (auto *BB : DeadBlockSet) {
for (BasicBlock *Successor : successors(BB)) {
if (!DeadBlockSet.count(Successor))
Successor->removePredecessor(BB);
if (DTU)
Updates.push_back({DominatorTree::Delete, BB, Successor});
}
if (LVI)
LVI->eraseBlock(BB);
BB->dropAllReferences();
}
for (Function::iterator I = ++F.begin(); I != F.end();) {
auto *BB = &*I;
if (Reachable.count(BB)) {
++I;
continue;
}
if (DTU) {
// Remove the terminator of BB to clear the successor list of BB.
if (BB->getTerminator())
BB->getInstList().pop_back();
new UnreachableInst(BB->getContext(), BB);
assert(succ_empty(BB) && "The successor list of BB isn't empty before "
"applying corresponding DTU updates.");
++I;
} else {
I = F.getBasicBlockList().erase(I);
}
}
if (DTU) {
DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
bool Deleted = false;
for (auto *BB : DeadBlockSet) {
if (DTU->isBBPendingDeletion(BB))
--NumRemoved;
else
Deleted = true;
DTU->deleteBB(BB);
}
if (!Deleted)
return false;
}
return true;
}
void llvm::combineMetadata(Instruction *K, const Instruction *J,
ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
K->dropUnknownNonDebugMetadata(KnownIDs);
K->getAllMetadataOtherThanDebugLoc(Metadata);
for (const auto &MD : Metadata) {
unsigned Kind = MD.first;
MDNode *JMD = J->getMetadata(Kind);
MDNode *KMD = MD.second;
switch (Kind) {
default:
K->setMetadata(Kind, nullptr); // Remove unknown metadata
break;
case LLVMContext::MD_dbg:
llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
case LLVMContext::MD_tbaa:
K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
break;
case LLVMContext::MD_alias_scope:
K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
break;
case LLVMContext::MD_noalias:
case LLVMContext::MD_mem_parallel_loop_access:
K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
break;
case LLVMContext::MD_access_group:
K->setMetadata(LLVMContext::MD_access_group,
intersectAccessGroups(K, J));
break;
case LLVMContext::MD_range:
// If K does move, use most generic range. Otherwise keep the range of
// K.
if (DoesKMove)
// FIXME: If K does move, we should drop the range info and nonnull.
// Currently this function is used with DoesKMove in passes
// doing hoisting/sinking and the current behavior of using the
// most generic range is correct in those cases.
K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
break;
case LLVMContext::MD_fpmath:
K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
break;
case LLVMContext::MD_invariant_load:
// Only set the !invariant.load if it is present in both instructions.
K->setMetadata(Kind, JMD);
break;
case LLVMContext::MD_nonnull:
// If K does move, keep nonull if it is present in both instructions.
if (DoesKMove)
K->setMetadata(Kind, JMD);
break;
case LLVMContext::MD_invariant_group:
// Preserve !invariant.group in K.
break;
case LLVMContext::MD_align:
K->setMetadata(Kind,
MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
break;
case LLVMContext::MD_dereferenceable:
case LLVMContext::MD_dereferenceable_or_null:
K->setMetadata(Kind,
MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
break;
}
}
// Set !invariant.group from J if J has it. If both instructions have it
// then we will just pick it from J - even when they are different.
// Also make sure that K is load or store - f.e. combining bitcast with load
// could produce bitcast with invariant.group metadata, which is invalid.
// FIXME: we should try to preserve both invariant.group md if they are
// different, but right now instruction can only have one invariant.group.
if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
if (isa<LoadInst>(K) || isa<StoreInst>(K))
K->setMetadata(LLVMContext::MD_invariant_group, JMD);
}
void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
bool KDominatesJ) {
unsigned KnownIDs[] = {
LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
LLVMContext::MD_noalias, LLVMContext::MD_range,
LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
LLVMContext::MD_invariant_group, LLVMContext::MD_align,
LLVMContext::MD_dereferenceable,
LLVMContext::MD_dereferenceable_or_null,
LLVMContext::MD_access_group};
combineMetadata(K, J, KnownIDs, KDominatesJ);
}
void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
auto *ReplInst = dyn_cast<Instruction>(Repl);
if (!ReplInst)
return;
// Patch the replacement so that it is not more restrictive than the value
// being replaced.
// Note that if 'I' is a load being replaced by some operation,
// for example, by an arithmetic operation, then andIRFlags()
// would just erase all math flags from the original arithmetic
// operation, which is clearly not wanted and not needed.
if (!isa<LoadInst>(I))
ReplInst->andIRFlags(I);
// FIXME: If both the original and replacement value are part of the
// same control-flow region (meaning that the execution of one
// guarantees the execution of the other), then we can combine the
// noalias scopes here and do better than the general conservative
// answer used in combineMetadata().
// In general, GVN unifies expressions over different control-flow
// regions, and so we need a conservative combination of the noalias
// scopes.
static const unsigned KnownIDs[] = {
LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
LLVMContext::MD_noalias, LLVMContext::MD_range,
LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
LLVMContext::MD_access_group};
combineMetadata(ReplInst, I, KnownIDs, false);
}
template <typename RootType, typename DominatesFn>
static unsigned replaceDominatedUsesWith(Value *From, Value *To,
const RootType &Root,
const DominatesFn &Dominates) {
assert(From->getType() == To->getType());
unsigned Count = 0;
for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
UI != UE;) {
Use &U = *UI++;
if (!Dominates(Root, U))
continue;
U.set(To);
LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
<< "' as " << *To << " in " << *U << "\n");
++Count;
}
return Count;
}
unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
assert(From->getType() == To->getType());
auto *BB = From->getParent();
unsigned Count = 0;
for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
UI != UE;) {
Use &U = *UI++;
auto *I = cast<Instruction>(U.getUser());
if (I->getParent() == BB)
continue;
U.set(To);
++Count;
}
return Count;
}
unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
DominatorTree &DT,
const BasicBlockEdge &Root) {
auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
return DT.dominates(Root, U);
};
return ::replaceDominatedUsesWith(From, To, Root, Dominates);
}
unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
DominatorTree &DT,
const BasicBlock *BB) {
auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
auto *I = cast<Instruction>(U.getUser())->getParent();
return DT.properlyDominates(BB, I);
};
return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
}
bool llvm::callsGCLeafFunction(ImmutableCallSite CS,
const TargetLibraryInfo &TLI) {
// Check if the function is specifically marked as a gc leaf function.
if (CS.hasFnAttr("gc-leaf-function"))
return true;
if (const Function *F = CS.getCalledFunction()) {
if (F->hasFnAttribute("gc-leaf-function"))
return true;
if (auto IID = F->getIntrinsicID())
// Most LLVM intrinsics do not take safepoints.
return IID != Intrinsic::experimental_gc_statepoint &&
IID != Intrinsic::experimental_deoptimize;
}
// Lib calls can be materialized by some passes, and won't be
// marked as 'gc-leaf-function.' All available Libcalls are
// GC-leaf.
LibFunc LF;
if (TLI.getLibFunc(CS, LF)) {
return TLI.has(LF);
}
return false;
}
void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
LoadInst &NewLI) {
auto *NewTy = NewLI.getType();
// This only directly applies if the new type is also a pointer.
if (NewTy->isPointerTy()) {
NewLI.setMetadata(LLVMContext::MD_nonnull, N);
return;
}
// The only other translation we can do is to integral loads with !range
// metadata.
if (!NewTy->isIntegerTy())
return;
MDBuilder MDB(NewLI.getContext());
const Value *Ptr = OldLI.getPointerOperand();
auto *ITy = cast<IntegerType>(NewTy);
auto *NullInt = ConstantExpr::getPtrToInt(
ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
NewLI.setMetadata(LLVMContext::MD_range,
MDB.createRange(NonNullInt, NullInt));
}
void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
MDNode *N, LoadInst &NewLI) {
auto *NewTy = NewLI.getType();
// Give up unless it is converted to a pointer where there is a single very
// valuable mapping we can do reliably.
// FIXME: It would be nice to propagate this in more ways, but the type
// conversions make it hard.
if (!NewTy->isPointerTy())
return;
unsigned BitWidth = DL.getIndexTypeSizeInBits(NewTy);
if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
MDNode *NN = MDNode::get(OldLI.getContext(), None);
NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
}
}
void llvm::dropDebugUsers(Instruction &I) {
SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
findDbgUsers(DbgUsers, &I);
for (auto *DII : DbgUsers)
DII->eraseFromParent();
}
void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
BasicBlock *BB) {
// Since we are moving the instructions out of its basic block, we do not
// retain their original debug locations (DILocations) and debug intrinsic
// instructions (dbg.values).
//
// Doing so would degrade the debugging experience and adversely affect the
// accuracy of profiling information.
//
// Currently, when hoisting the instructions, we take the following actions:
// - Remove their dbg.values.
// - Set their debug locations to the values from the insertion point.
//
// As per PR39141 (comment #8), the more fundamental reason why the dbg.values
// need to be deleted, is because there will not be any instructions with a
// DILocation in either branch left after performing the transformation. We
// can only insert a dbg.value after the two branches are joined again.
//
// See PR38762, PR39243 for more details.
//
// TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
// encode predicated DIExpressions that yield different results on different
// code paths.
for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
Instruction *I = &*II;
I->dropUnknownNonDebugMetadata();
if (I->isUsedByMetadata())
dropDebugUsers(*I);
if (isa<DbgVariableIntrinsic>(I)) {
// Remove DbgInfo Intrinsics.
II = I->eraseFromParent();
continue;
}
I->setDebugLoc(InsertPt->getDebugLoc());
++II;
}
DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
BB->begin(),
BB->getTerminator()->getIterator());
}
namespace {
/// A potential constituent of a bitreverse or bswap expression. See
/// collectBitParts for a fuller explanation.
struct BitPart {
BitPart(Value *P, unsigned BW) : Provider(P) {
Provenance.resize(BW);
}
/// The Value that this is a bitreverse/bswap of.
Value *Provider;
/// The "provenance" of each bit. Provenance[A] = B means that bit A
/// in Provider becomes bit B in the result of this expression.
SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
enum { Unset = -1 };
};
} // end anonymous namespace
/// Analyze the specified subexpression and see if it is capable of providing
/// pieces of a bswap or bitreverse. The subexpression provides a potential
/// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
/// the output of the expression came from a corresponding bit in some other
/// value. This function is recursive, and the end result is a mapping of
/// bitnumber to bitnumber. It is the caller's responsibility to validate that
/// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
///
/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
/// that the expression deposits the low byte of %X into the high byte of the
/// result and that all other bits are zero. This expression is accepted and a
/// BitPart is returned with Provider set to %X and Provenance[24-31] set to
/// [0-7].
///
/// To avoid revisiting values, the BitPart results are memoized into the
/// provided map. To avoid unnecessary copying of BitParts, BitParts are
/// constructed in-place in the \c BPS map. Because of this \c BPS needs to
/// store BitParts objects, not pointers. As we need the concept of a nullptr
/// BitParts (Value has been analyzed and the analysis failed), we an Optional
/// type instead to provide the same functionality.
///
/// Because we pass around references into \c BPS, we must use a container that
/// does not invalidate internal references (std::map instead of DenseMap).
static const Optional<BitPart> &
collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
std::map<Value *, Optional<BitPart>> &BPS) {
auto I = BPS.find(V);
if (I != BPS.end())
return I->second;
auto &Result = BPS[V] = None;
auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
if (Instruction *I = dyn_cast<Instruction>(V)) {
// If this is an or instruction, it may be an inner node of the bswap.
if (I->getOpcode() == Instruction::Or) {
auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
MatchBitReversals, BPS);
auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
MatchBitReversals, BPS);
if (!A || !B)
return Result;
// Try and merge the two together.
if (!A->Provider || A->Provider != B->Provider)
return Result;
Result = BitPart(A->Provider, BitWidth);
for (unsigned i = 0; i < A->Provenance.size(); ++i) {
if (A->Provenance[i] != BitPart::Unset &&
B->Provenance[i] != BitPart::Unset &&
A->Provenance[i] != B->Provenance[i])
return Result = None;
if (A->Provenance[i] == BitPart::Unset)
Result->Provenance[i] = B->Provenance[i];
else
Result->Provenance[i] = A->Provenance[i];
}
return Result;
}
// If this is a logical shift by a constant, recurse then shift the result.
if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
unsigned BitShift =
cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
// Ensure the shift amount is defined.
if (BitShift > BitWidth)
return Result;
auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
MatchBitReversals, BPS);
if (!Res)
return Result;
Result = Res;
// Perform the "shift" on BitProvenance.
auto &P = Result->Provenance;
if (I->getOpcode() == Instruction::Shl) {
P.erase(std::prev(P.end(), BitShift), P.end());
P.insert(P.begin(), BitShift, BitPart::Unset);
} else {
P.erase(P.begin(), std::next(P.begin(), BitShift));
P.insert(P.end(), BitShift, BitPart::Unset);
}
return Result;
}
// If this is a logical 'and' with a mask that clears bits, recurse then
// unset the appropriate bits.
if (I->getOpcode() == Instruction::And &&
isa<ConstantInt>(I->getOperand(1))) {
APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
// Check that the mask allows a multiple of 8 bits for a bswap, for an
// early exit.
unsigned NumMaskedBits = AndMask.countPopulation();
if (!MatchBitReversals && NumMaskedBits % 8 != 0)
return Result;
auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
MatchBitReversals, BPS);
if (!Res)
return Result;
Result = Res;
for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
// If the AndMask is zero for this bit, clear the bit.
if ((AndMask & Bit) == 0)
Result->Provenance[i] = BitPart::Unset;
return Result;
}
// If this is a zext instruction zero extend the result.
if (I->getOpcode() == Instruction::ZExt) {
auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
MatchBitReversals, BPS);
if (!Res)
return Result;
Result = BitPart(Res->Provider, BitWidth);
auto NarrowBitWidth =
cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
for (unsigned i = 0; i < NarrowBitWidth; ++i)
Result->Provenance[i] = Res->Provenance[i];
for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
Result->Provenance[i] = BitPart::Unset;
return Result;
}
}
// Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
// the input value to the bswap/bitreverse.
Result = BitPart(V, BitWidth);
for (unsigned i = 0; i < BitWidth; ++i)
Result->Provenance[i] = i;
return Result;
}
static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
unsigned BitWidth) {
if (From % 8 != To % 8)
return false;
// Convert from bit indices to byte indices and check for a byte reversal.
From >>= 3;
To >>= 3;
BitWidth >>= 3;
return From == BitWidth - To - 1;
}
static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
unsigned BitWidth) {
return From == BitWidth - To - 1;
}
bool llvm::recognizeBSwapOrBitReverseIdiom(
Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
SmallVectorImpl<Instruction *> &InsertedInsts) {
if (Operator::getOpcode(I) != Instruction::Or)
return false;
if (!MatchBSwaps && !MatchBitReversals)
return false;
IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
if (!ITy || ITy->getBitWidth() > 128)
return false; // Can't do vectors or integers > 128 bits.
unsigned BW = ITy->getBitWidth();
unsigned DemandedBW = BW;
IntegerType *DemandedTy = ITy;
if (I->hasOneUse()) {
if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
DemandedTy = cast<IntegerType>(Trunc->getType());
DemandedBW = DemandedTy->getBitWidth();
}
}
// Try to find all the pieces corresponding to the bswap.
std::map<Value *, Optional<BitPart>> BPS;
auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
if (!Res)
return false;
auto &BitProvenance = Res->Provenance;
// Now, is the bit permutation correct for a bswap or a bitreverse? We can
// only byteswap values with an even number of bytes.
bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
for (unsigned i = 0; i < DemandedBW; ++i) {
OKForBSwap &=
bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
OKForBitReverse &=
bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
}
Intrinsic::ID Intrin;
if (OKForBSwap && MatchBSwaps)
Intrin = Intrinsic::bswap;
else if (OKForBitReverse && MatchBitReversals)
Intrin = Intrinsic::bitreverse;
else
return false;
if (ITy != DemandedTy) {
Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
Value *Provider = Res->Provider;
IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
// We may need to truncate the provider.
if (DemandedTy != ProviderTy) {
auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
"trunc", I);
InsertedInsts.push_back(Trunc);
Provider = Trunc;
}
auto *CI = CallInst::Create(F, Provider, "rev", I);
InsertedInsts.push_back(CI);
auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
InsertedInsts.push_back(ExtInst);
return true;
}
Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
return true;
}
// CodeGen has special handling for some string functions that may replace
// them with target-specific intrinsics. Since that'd skip our interceptors
// in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
// we mark affected calls as NoBuiltin, which will disable optimization
// in CodeGen.
void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
CallInst *CI, const TargetLibraryInfo *TLI) {
Function *F = CI->getCalledFunction();
LibFunc Func;
if (F && !F->hasLocalLinkage() && F->hasName() &&
TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
!F->doesNotAccessMemory())
CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
}
bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
// We can't have a PHI with a metadata type.
if (I->getOperand(OpIdx)->getType()->isMetadataTy())
return false;
// Early exit.
if (!isa<Constant>(I->getOperand(OpIdx)))
return true;
switch (I->getOpcode()) {
default:
return true;
case Instruction::Call:
case Instruction::Invoke:
// Can't handle inline asm. Skip it.
if (isa<InlineAsm>(ImmutableCallSite(I).getCalledValue()))
return false;
// Many arithmetic intrinsics have no issue taking a
// variable, however it's hard to distingish these from
// specials such as @llvm.frameaddress that require a constant.
if (isa<IntrinsicInst>(I))
return false;
// Constant bundle operands may need to retain their constant-ness for
// correctness.
if (ImmutableCallSite(I).isBundleOperand(OpIdx))
return false;
return true;
case Instruction::ShuffleVector:
// Shufflevector masks are constant.
return OpIdx != 2;
case Instruction::Switch:
case Instruction::ExtractValue:
// All operands apart from the first are constant.
return OpIdx == 0;
case Instruction::InsertValue:
// All operands apart from the first and the second are constant.
return OpIdx < 2;
case Instruction::Alloca:
// Static allocas (constant size in the entry block) are handled by
// prologue/epilogue insertion so they're free anyway. We definitely don't
// want to make them non-constant.
return !cast<AllocaInst>(I)->isStaticAlloca();
case Instruction::GetElementPtr:
if (OpIdx == 0)
return true;
gep_type_iterator It = gep_type_begin(I);
for (auto E = std::next(It, OpIdx); It != E; ++It)
if (It.isStruct())
return false;
return true;
}
}
|
/*
* 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 "pagespeed/kernel/sharedmem/shared_mem_cache_test_base.h"
#include <unistd.h>
#include <cstddef> // for size_t
#include <map>
#include <utility>
#include "base/logging.h" // for Check_EQImpl, CHECK_EQ
#include "pagespeed/kernel/base/function.h"
#include "pagespeed/kernel/base/shared_string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/base/thread_system.h"
#include "pagespeed/kernel/cache/cache_interface.h"
#include "pagespeed/kernel/sharedmem/shared_mem_cache.h"
#include "pagespeed/kernel/sharedmem/shared_mem_cache_snapshot.pb.h"
#include "pagespeed/kernel/util/platform.h"
namespace net_instaweb {
namespace {
const char kSegment[] = "cache";
const char kAltSegment[] = "alt_cache";
const int kSectors = 2;
const int kSectorBlocks = 2000;
const int kSectorEntries = 256;
const int kSpinRuns = 100;
// Tests don't actually rely on this value, it just needs to be >0.
const int kSnapshotIntervalMs = 1000;
// In some tests we have tight consumer/producer spinloops assuming they'll get
// preempted to let other end proceed. Valgrind does not actually do that
// sometimes.
void YieldToThread() {
usleep(1);
}
} // namespace
SharedMemCacheTestBase::SharedMemCacheTestBase(SharedMemTestEnv* env)
: test_env_(env),
shmem_runtime_(env->CreateSharedMemRuntime()),
thread_system_(Platform::CreateThreadSystem()),
handler_(thread_system_->NewMutex()),
timer_(thread_system_->NewMutex(), 0),
sanity_checks_enabled_(true) {
cache_.reset(MakeCache());
EXPECT_TRUE(cache_->Initialize());
// Compute a large string for tests --- one large enough to take multiple
// blocks (2 complete blocks, plus 43 bytes in a 3rd one, where 43
// is a completely arbitrary small integer smaller than the block size)
for (size_t c = 0; c < kBlockSize * 2 + 43; ++c) {
large_.push_back('A' + (c % 26));
}
// Now a gigantic one, which goes close to the size limit, which is 1/32nd
// of sector size.
for (size_t c = 0; c < kBlockSize * kSectorBlocks / 40 + 43; ++c) {
gigantic_.push_back('a' + (c % 26));
}
}
SharedMemCache<SharedMemCacheTestBase::kBlockSize>*
SharedMemCacheTestBase::MakeCache() {
return new SharedMemCache<kBlockSize>(shmem_runtime_.get(), kSegment, &timer_,
&hasher_, kSectors, kSectorEntries,
kSectorBlocks, &handler_);
}
void SharedMemCacheTestBase::TearDown() {
cache_->GlobalCleanup(shmem_runtime_.get(), kSegment, &handler_);
CacheTestBase::TearDown();
}
void SharedMemCacheTestBase::ResetCache() {
cache_->GlobalCleanup(shmem_runtime_.get(), kSegment, &handler_);
cache_.reset(MakeCache());
EXPECT_TRUE(cache_->Initialize());
}
bool SharedMemCacheTestBase::CreateChild(TestMethod method) {
Function* fn = new MemberFunction0<SharedMemCacheTestBase>(method, this);
return test_env_->CreateChild(fn);
}
void SharedMemCacheTestBase::SanityCheck() {
if (sanity_checks_enabled_) {
cache_->SanityCheck();
}
}
void SharedMemCacheTestBase::TestBasic() {
CheckNotFound("404");
CheckDelete("404");
CheckNotFound("404");
CheckPut("200", "OK");
CheckGet("200", "OK");
CheckNotFound("404");
CheckPut("002", "KO!");
CheckGet("002", "KO!");
CheckGet("200", "OK");
CheckNotFound("404");
CheckDelete("002");
CheckNotFound("002");
CheckNotFound("404");
CheckGet("200", "OK");
CheckPut("big", large_);
CheckGet("big", large_);
// Make sure this at least doesn't blow up.
cache_->DumpStats();
}
void SharedMemCacheTestBase::TestReinsert() {
CheckPut("key", "val");
CheckGet("key", "val");
// Insert the same size.
CheckPut("key", "alv");
CheckGet("key", "alv");
// Insert larger one..
CheckPut("key", large_);
CheckGet("key", large_);
// Now shrink it down again.
CheckPut("key", "small");
CheckGet("key", "small");
// ... And make it huge.
CheckPut("key", gigantic_);
CheckGet("key", gigantic_);
// Now try with empty value
CheckPut("key", "");
CheckGet("key", "");
}
void SharedMemCacheTestBase::TestReplacement() {
sanity_checks_enabled_ = false; // To expensive for that much work.
// Make sure we can allocate spec from replacement, too, but that it doesn't
// affect very recent files (barring collisions). All 3 entries below should
// fit into one sector.
// Now throw in tons of small files, to make sure we load the
// directory heavily.
for (int n = 0; n < kSectorEntries * 4; ++n) {
GoogleString key1 = IntegerToString(n);
CheckPut(key1, key1);
timer_.AdvanceMs(1);
CheckPut(key1, key1);
CheckGet(key1, key1);
}
cache_->SanityCheck();
for (int n = 0; n < 100; n += 3) {
GoogleString key1 = IntegerToString(n);
GoogleString key2 = IntegerToString(n + 1);
GoogleString key3 = IntegerToString(n + 2);
CheckPut(key1, large_);
timer_.AdvanceMs(1);
CheckPut(key2, key2);
timer_.AdvanceMs(1);
CheckPut(key3, gigantic_);
timer_.AdvanceMs(1);
CheckGet(key1, large_);
CheckGet(key2, key2);
CheckGet(key3, gigantic_);
CheckDelete(key2.c_str());
timer_.AdvanceMs(1);
CheckNotFound(key2.c_str());
}
cache_->SanityCheck();
}
void SharedMemCacheTestBase::TestReaderWriter() {
CreateChild(&SharedMemCacheTestBase::TestReaderWriterChild);
for (int i = 0; i < kSpinRuns; ++i) {
// Wait until the child puts in a proper value for 'key'
CacheTestBase::Callback callback;
while (callback.state() != CacheInterface::kAvailable) {
cache_->Get("key", callback.Reset());
ASSERT_EQ(true, callback.called());
YieldToThread();
}
EXPECT_EQ(large_, callback.value().Value());
CheckDelete("key");
CheckPut("key2", "val2");
}
test_env_->WaitForChildren();
}
void SharedMemCacheTestBase::TestReaderWriterChild() {
scoped_ptr<SharedMemCache<kBlockSize> > child_cache(MakeCache());
if (!child_cache->Attach()) {
test_env_->ChildFailed();
}
SharedString val(large_);
for (int i = 0; i < kSpinRuns; ++i) {
child_cache->Put("key", val);
// Now wait until the parent puts in what we expect for 'key2'
CacheTestBase::Callback callback;
while (callback.state() != CacheInterface::kAvailable) {
child_cache->Get("key2", callback.Reset());
ASSERT_EQ(true, callback.called());
YieldToThread();
}
if (callback.value().Value() != "val2") {
test_env_->ChildFailed();
}
child_cache->Delete("key2");
}
}
void SharedMemCacheTestBase::TestConflict() {
const int kAssociativity = SharedMemCache<kBlockSize>::kAssociativity;
// We create a cache with 1 sector, and kAssociativity entries, since it
// makes it easy to get a conflict and replacement.
scoped_ptr<SharedMemCache<kBlockSize> > small_cache(
new SharedMemCache<kBlockSize>(shmem_runtime_.get(), kAltSegment, &timer_,
&hasher_, 1 /* sectors*/,
kAssociativity /* entries / sector */,
kSectorBlocks, &handler_));
ASSERT_TRUE(small_cache->Initialize());
// Insert kAssociativity + 1 entries.
for (int c = 0; c <= kAssociativity; ++c) {
GoogleString key = IntegerToString(c);
CheckPut(small_cache.get(), key, key);
}
// Now make sure the final one is available.
// It would seem like one could predict replacement order exactly, but
// with us only having kAssoc possible key values, it's quite likely
// that the constructed key set will not have full associativity.
GoogleString last(IntegerToString(kAssociativity));
CheckGet(small_cache.get(), last, last);
small_cache->GlobalCleanup(shmem_runtime_.get(), kAltSegment, &handler_);
}
void SharedMemCacheTestBase::TestEvict() {
// We create a cache with 1 sector as it makes it easier to reason
// about how much room is left.
scoped_ptr<SharedMemCache<kBlockSize> > small_cache(
new SharedMemCache<kBlockSize>(shmem_runtime_.get(), kAltSegment, &timer_,
&hasher_, 1 /* sectors*/,
kSectorBlocks * 4 /* entries / sector */,
kSectorBlocks, &handler_));
ASSERT_TRUE(small_cache->Initialize());
// Insert large_ kSectorBlocks times. Since large_ is ~3 blocks in size,
// we will need to evict older entries eventually.
for (int c = 0; c < kSectorBlocks; ++c) {
GoogleString key = IntegerToString(c);
CheckPut(small_cache.get(), key, large_);
CheckGet(small_cache.get(), key, large_);
}
small_cache->GlobalCleanup(shmem_runtime_.get(), kAltSegment, &handler_);
}
void SharedMemCacheTestBase::CheckDumpsEqual(
const SharedMemCacheDump& a, const SharedMemCacheDump& b,
const char* test_label) {
ASSERT_EQ(a.entry_size(), b.entry_size()) << test_label;
for (int i = 0; i < a.entry_size(); ++i) {
EXPECT_EQ(a.entry(i).value(), b.entry(i).value()) << test_label;
EXPECT_EQ(a.entry(i).raw_key(), b.entry(i).raw_key()) << test_label;
EXPECT_EQ(a.entry(i).last_use_timestamp_ms(),
b.entry(i).last_use_timestamp_ms()) << test_label;
}
}
void SharedMemCacheTestBase::TestSnapshot() {
const int kEntries = 10;
const int64 kLastWriteMs = 1234567;
// Put in 10 values: key0 ... key9 set to val0 ... val9, each with timestamp
// corresponding to their number.
for (int i = 0; i < kEntries; ++i) {
CheckPut(StrCat("key", IntegerToString(i)),
StrCat("val", IntegerToString(i)));
timer_.AdvanceMs(1);
}
SharedMemCacheDump dump;
for (int i = 0; i < kSectors; ++i) {
// We explicitly SetLastWriteMsForTesting so we can build a snapshot with
// where every sector is included but entries all have different
// timestamps.
Cache()->SetLastWriteMsForTesting(i, kLastWriteMs);
EXPECT_TRUE(Cache()->AddSectorToSnapshot(i, kLastWriteMs, &dump));
}
// Make sure we can still access the cache. Also move the time forward, so we
// can check timestamps are using old values after restoring the snapshot.
for (int i = 0; i < kEntries; ++i) {
CheckGet(StrCat("key", IntegerToString(i)),
StrCat("val", IntegerToString(i)));
timer_.AdvanceMs(1);
}
// Now check the dump contents. We can't inspect the keys directly, but
// we can at least check values and timestamps.
std::map<GoogleString, int64> value_to_timestamp;
EXPECT_EQ(kEntries, dump.entry_size());
for (int i = 0; i < dump.entry_size(); ++i) {
const SharedMemCacheDumpEntry& entry = dump.entry(i);
value_to_timestamp[entry.value()] = entry.last_use_timestamp_ms();
}
// Make sure size is right (e.g. no dupes).
EXPECT_EQ(static_cast<size_t>(kEntries), value_to_timestamp.size());
// Now see that the correspondence is right.
for (std::map<GoogleString, int64>::iterator i = value_to_timestamp.begin();
i != value_to_timestamp.end(); ++i) {
EXPECT_EQ(i->first, StrCat("val", Integer64ToString(i->second)));
}
// Now round-trip to new object via string serialization
GoogleString encoded_dump;
Cache()->MarshalSnapshot(dump, &encoded_dump);
SharedMemCacheDump decoded_dump;
Cache()->DemarshalSnapshot(encoded_dump, &decoded_dump);
CheckDumpsEqual(dump, decoded_dump, "dump vs decoded_dump");
// Now make a new cache, which should initially be empty.
ResetCache();
for (int i = 0; i < kEntries; ++i) {
CheckNotFound(StrCat("key", IntegerToString(i)).c_str());
}
// Restore it from decoded_dump
Cache()->RestoreSnapshot(decoded_dump);
// Save yet another dump. This is basically the best we can do to make sure
// that the timestamps got restored properly.
SharedMemCacheDump roundtrip_dump;
for (int i = 0; i < kSectors; ++i) {
Cache()->SetLastWriteMsForTesting(i, kLastWriteMs);
EXPECT_TRUE(
Cache()->AddSectorToSnapshot(i, kLastWriteMs, &roundtrip_dump));
EXPECT_EQ(timer_.NowMs(), Cache()->GetLastWriteMsForTesting(i));
}
CheckDumpsEqual(dump, roundtrip_dump, "dump vs. roundtrip_dump");
// Check to make sure all values are OK.
for (int i = 0; i < kEntries; ++i) {
CheckGet(StrCat("key", IntegerToString(i)),
StrCat("val", IntegerToString(i)));
}
// Test that if checkpoint timestamps don't match we don't make a dump or
// update the sector's last_checkpoint_ms.
SharedMemCacheDump dump_ts_mismatch;
int sector_num = 0;
Cache()->SetLastWriteMsForTesting(sector_num, kLastWriteMs);
EXPECT_FALSE(Cache()->AddSectorToSnapshot(
sector_num, kLastWriteMs - 1, &dump_ts_mismatch));
EXPECT_EQ(kLastWriteMs, Cache()->GetLastWriteMsForTesting(sector_num));
EXPECT_EQ(0, dump_ts_mismatch.entry_size());
}
void SharedMemCacheTestBase::CheckDelete(const char* key) {
cache_->Delete(key);
SanityCheck();
}
void SharedMemCacheTestBase::TestRegisterSnapshotFileCache() {
// Test that we handle setting the file cache to multiple paths by picking the
// one that's first alphabetically.
scoped_ptr<FileCacheTestWrapper> file_cache_wrapper_abc(
new FileCacheTestWrapper(
"/abc", thread_system_.get(), &timer_, &handler_));
cache_->RegisterSnapshotFileCache(file_cache_wrapper_abc->file_cache(),
kSnapshotIntervalMs);
CHECK_EQ(cache_->snapshot_path(), "/abc");
CHECK_EQ(cache_->file_cache(), file_cache_wrapper_abc->file_cache());
// Alphabetically before /abc, so replaces it.
scoped_ptr<FileCacheTestWrapper> file_cache_wrapper_abb(
new FileCacheTestWrapper(
"/abb", thread_system_.get(), &timer_, &handler_));
cache_->RegisterSnapshotFileCache(file_cache_wrapper_abb->file_cache(),
kSnapshotIntervalMs);
CHECK_EQ(cache_->snapshot_path(), "/abb");
CHECK_EQ(cache_->file_cache(), file_cache_wrapper_abb->file_cache());
// Not before /abb, so doesn't replace it.
scoped_ptr<FileCacheTestWrapper> file_cache_wrapper_acb(
new FileCacheTestWrapper(
"/acb", thread_system_.get(), &timer_, &handler_));
cache_->RegisterSnapshotFileCache(file_cache_wrapper_acb->file_cache(),
kSnapshotIntervalMs);
CHECK_EQ(cache_->snapshot_path(), "/abb");
CHECK_EQ(cache_->file_cache(), file_cache_wrapper_abb->file_cache());
// Before /abb, so does replace it.
scoped_ptr<FileCacheTestWrapper> file_cache_wrapper_aab(
new FileCacheTestWrapper(
"/aab", thread_system_.get(), &timer_, &handler_));
cache_->RegisterSnapshotFileCache(file_cache_wrapper_aab->file_cache(),
kSnapshotIntervalMs);
CHECK_EQ(cache_->snapshot_path(), "/aab");
CHECK_EQ(cache_->file_cache(), file_cache_wrapper_aab->file_cache());
// The cache was constructed with a filename of kSegment, and a match on
// filename should always win here.
scoped_ptr<FileCacheTestWrapper> file_cache_wrapper_ksegment(
new FileCacheTestWrapper(
kSegment, thread_system_.get(), &timer_, &handler_));
cache_->RegisterSnapshotFileCache(file_cache_wrapper_ksegment->file_cache(),
kSnapshotIntervalMs);
CHECK_EQ(cache_->snapshot_path(), kSegment);
CHECK_EQ(cache_->file_cache(), file_cache_wrapper_ksegment->file_cache());
// Before kSegment, but doesn't replace it because kSegment was a filename
// match.
scoped_ptr<FileCacheTestWrapper> file_cache_wrapper_aaa(
new FileCacheTestWrapper(
"/aaa", thread_system_.get(), &timer_, &handler_));
cache_->RegisterSnapshotFileCache(file_cache_wrapper_aaa->file_cache(),
kSnapshotIntervalMs);
CHECK_EQ(cache_->snapshot_path(), kSegment);
CHECK_EQ(cache_->file_cache(), file_cache_wrapper_ksegment->file_cache());
}
void SharedMemCacheTestBase::TestCheckpointAndRestore() {
const GoogleString kPath = "/a-path";
// Setup.
cache_.reset(new SharedMemCache<kBlockSize>(
shmem_runtime_.get(), kPath, &timer_, &hasher_, kSectors,
kSectorEntries, kSectorBlocks, &handler_));
scoped_ptr<FileCacheTestWrapper> file_cache_wrapper(
new FileCacheTestWrapper(
kPath, thread_system_.get(), &timer_, &handler_));
cache_->RegisterSnapshotFileCache(file_cache_wrapper->file_cache(),
kSnapshotIntervalMs);
EXPECT_EQ(cache_->file_cache(), file_cache_wrapper->file_cache());
EXPECT_TRUE(cache_->Initialize());
// Now we're set up and can start testing.
// Put something in the cache.
CheckPut("200", "OK");
CheckGet("200", "OK");
const int64 kLastWriteMs = 1234567;
for (int sector_num = 0; sector_num < kSectors; ++sector_num) {
// Explicitly set kLastWriteMs so we don't have to worry about it.
cache_->SetLastWriteMsForTesting(sector_num, kLastWriteMs);
cache_->WriteOutSnapshotForTesting(sector_num, kLastWriteMs);
}
// Check that it did get written out.
for (int sector_num = 0; sector_num < kSectors; ++sector_num) {
EXPECT_EQ(timer_.NowMs(), cache_->GetLastWriteMsForTesting(sector_num));
}
// Reset the cache, but don't set a file system. We expect not to load
// anything.
cache_.reset(new SharedMemCache<kBlockSize>(
shmem_runtime_.get(), kPath, &timer_, &hasher_, kSectors,
kSectorEntries, kSectorBlocks, &handler_));
EXPECT_TRUE(cache_->Initialize());
CheckNotFound("200");
// Reset the cache, set a file system, but change the shmcache's path. This
// is similar to the case where a default shm cache and an explicitly
// configured one share the same file cache path. We expect not to load
// anything, because the path is part of the key.
cache_.reset(new SharedMemCache<kBlockSize>(
shmem_runtime_.get(), "default-shm-cache", &timer_, &hasher_, kSectors,
kSectorEntries, kSectorBlocks, &handler_));
cache_->RegisterSnapshotFileCache(file_cache_wrapper->file_cache(),
kSnapshotIntervalMs);
EXPECT_TRUE(cache_->Initialize());
CheckNotFound("200");
// Now reset the cache, but do set the file system. Everything should be
// loaded back in.
cache_.reset(new SharedMemCache<kBlockSize>(
shmem_runtime_.get(), kPath, &timer_, &hasher_, kSectors,
kSectorEntries, kSectorBlocks, &handler_));
cache_->RegisterSnapshotFileCache(file_cache_wrapper->file_cache(),
kSnapshotIntervalMs);
EXPECT_TRUE(cache_->Initialize());
CheckGet("200", "OK");
// If the files are deleted the cache is still fine.
file_cache_wrapper->filesystem()->Clear();
CheckGet("200", "OK");
// But you can't reload from an empty filesystem.
cache_.reset(new SharedMemCache<kBlockSize>(
shmem_runtime_.get(), kPath, &timer_, &hasher_, kSectors,
kSectorEntries, kSectorBlocks, &handler_));
cache_->RegisterSnapshotFileCache(file_cache_wrapper->file_cache(),
kSnapshotIntervalMs);
EXPECT_TRUE(cache_->Initialize());
CheckNotFound("200");
}
} // namespace net_instaweb
|
/*
* Copyright 2015-2019 CNRS-UM LIRMM, CNRS-AIST JRL
*/
#include <mc_control/MCController.h>
#include <mc_rbdyn/RobotLoader.h>
#include <mc_rbdyn/RobotModule.h>
#include <mc_rtc/constants.h>
#include <mc_rtc/ConfigurationHelpers.h>
#include <mc_rtc/config.h>
#include <mc_rtc/gui/Schema.h>
#include <mc_rtc/io_utils.h>
#include <mc_rtc/logging.h>
#include <mc_tasks/MetaTaskLoader.h>
#include <RBDyn/FK.h>
#include <RBDyn/FV.h>
#include <array>
#include <fstream>
namespace mc_control
{
MCController::MCController(std::shared_ptr<mc_rbdyn::RobotModule> robot, double dt) : MCController(robot, dt, {}) {}
MCController::MCController(std::shared_ptr<mc_rbdyn::RobotModule> robot,
double dt,
const mc_rtc::Configuration & config)
: MCController({robot, mc_rbdyn::RobotLoader::get_robot_module("env",
std::string(mc_rtc::MC_ENV_DESCRIPTION_PATH),
std::string("ground"))},
dt,
config)
{
}
MCController::MCController(const std::vector<std::shared_ptr<mc_rbdyn::RobotModule>> & robots_modules, double dt)
: MCController(robots_modules, dt, {})
{
}
MCController::MCController(const std::vector<std::shared_ptr<mc_rbdyn::RobotModule>> & robots_modules,
double dt,
const mc_rtc::Configuration & config)
: qpsolver(std::make_shared<mc_solver::QPSolver>(dt)),
logger_(std::make_shared<mc_rtc::Logger>(mc_rtc::Logger::Policy::NON_THREADED, "", "")),
gui_(std::make_shared<mc_rtc::gui::StateBuilder>()), config_(config), timeStep(dt)
{
/* Load robots */
qpsolver->logger(logger_);
qpsolver->gui(gui_);
for(auto rm : robots_modules)
{
loadRobot(rm, rm->name);
}
if(gui_)
{
gui_->addElement({"Global", "Add task"},
mc_rtc::gui::Schema("Add MetaTask", "MetaTask", [this](const mc_rtc::Configuration & config) {
try
{
auto t = mc_tasks::MetaTaskLoader::load(this->solver(), config);
this->solver().addTask(t);
}
catch(...)
{
mc_rtc::log::error("Failed to load MetaTask from request\n{}", config.dump(true));
}
}));
}
/* Initialize constraints and tasks */
std::array<double, 3> damper = {0.1, 0.01, 0.5};
contactConstraint = mc_solver::ContactConstraint(timeStep, mc_solver::ContactConstraint::Velocity);
dynamicsConstraint = mc_solver::DynamicsConstraint(robots(), 0, timeStep, damper, 0.5);
kinematicsConstraint = mc_solver::KinematicsConstraint(robots(), 0, timeStep, damper, 0.5);
selfCollisionConstraint = mc_solver::CollisionsConstraint(robots(), 0, 0, timeStep);
selfCollisionConstraint.addCollisions(solver(), robots_modules[0]->minimalSelfCollisions());
compoundJointConstraint.reset(new mc_solver::CompoundJointConstraint(robots(), 0, timeStep));
postureTask = std::make_shared<mc_tasks::PostureTask>(solver(), 0, 10.0, 5.0);
mc_rtc::log::info("MCController(base) ready");
}
MCController::~MCController() {}
mc_rbdyn::Robot & MCController::loadRobot(mc_rbdyn::RobotModulePtr rm, const std::string & name)
{
loadRobot(rm, name, realRobots(), false);
return loadRobot(rm, name, robots(), true);
}
mc_rbdyn::Robot & MCController::loadRobot(mc_rbdyn::RobotModulePtr rm,
const std::string & name,
mc_rbdyn::Robots & robots,
bool updateNrVars)
{
assert(rm);
auto & r = robots.load(name, *rm);
r.mbc().gravity = mc_rtc::constants::gravity;
r.forwardKinematics();
r.forwardVelocity();
if(gui_ && updateNrVars)
{
auto data = gui_->data();
if(!data.has("robots"))
{
data.array("robots");
}
if(!data.has("bodies"))
{
data.add("bodies");
}
if(!data.has("surfaces"))
{
data.add("surfaces");
}
data("robots").push(r.name());
auto bs = data("bodies").array(r.name());
for(const auto & b : r.mb().bodies())
{
bs.push(b.name());
}
data("surfaces").add(r.name(), r.availableSurfaces());
auto name = r.name();
gui()->addElement({"Robots"}, mc_rtc::gui::Robot(r.name(), [name, this]() -> const mc_rbdyn::Robot & {
return this->robot(name);
}));
}
if(updateNrVars)
{
solver().updateNrVars();
}
return r;
}
void MCController::removeRobot(const std::string & name)
{
robots().removeRobot(name);
solver().updateNrVars();
}
void MCController::createObserverPipelines(const mc_rtc::Configuration & config)
{
if(config.has("EnabledObservers") || config.has("RunObservers") || config.has("UpdateObservers"))
{
mc_rtc::log::error_and_throw<std::runtime_error>(
"[{}] The observer pipeline can no longer be configured by \"EnabledObservers\", \"RunObservers\" and "
"\"UpdateObservers\".\nMultiple "
"pipelines are now supported, allowing for estimation of multiple robots and/or multiple observations of the "
"same robot.\nFor details on upgrading, please refer to:\n"
"- The observer pipelines tutorial: https://jrl-umi3218.github.io/mc_rtc/tutorials/recipes/observers.html\n"
"- The JSON Schema documentation: https://jrl-umi3218.github.io/mc_rtc/json.html#Observers/ObserverPipelines",
name_);
}
if(!config.has("ObserverPipelines"))
{
mc_rtc::log::warning("[MCController::{}] No state observation pipeline configured: the state of the real robots "
"will not be estimated",
name_);
return;
}
auto pipelineConfigs = mc_rtc::fromVectorOrElement(config, "ObserverPipelines", std::vector<mc_rtc::Configuration>{});
for(const auto & pipelineConfig : pipelineConfigs)
{
observerPipelines_.emplace_back(*this);
auto & pipeline = observerPipelines_.back();
pipeline.create(pipelineConfig, timeStep);
if(pipelineConfig("log", true))
{
pipeline.addToLogger(logger());
}
if(pipelineConfig("gui", false))
{
pipeline.addToGUI(*gui());
}
}
}
bool MCController::resetObserverPipelines()
{
std::string desc;
for(auto & pipeline : observerPipelines_)
{
pipeline.reset();
if(desc.size())
{
desc += "\n";
}
desc += "- " + pipeline.desc();
}
if(desc.size())
{
mc_rtc::log::success("[MCController::{}] State observation pipelines:\n{}", name_, desc);
}
return true;
}
bool MCController::runObserverPipelines()
{
bool success = true;
for(auto & pipeline : observerPipelines_)
{
success = pipeline.run() && success;
}
return success;
}
bool MCController::hasObserverPipeline(const std::string & name) const
{
return std::find_if(observerPipelines_.begin(), observerPipelines_.end(),
[&name](const mc_observers::ObserverPipeline & pipeline) { return pipeline.name() == name; })
!= observerPipelines_.end();
}
const std::vector<mc_observers::ObserverPipeline> & MCController::observerPipelines() const
{
return observerPipelines_;
}
std::vector<mc_observers::ObserverPipeline> & MCController::observerPipelines()
{
return observerPipelines_;
}
const mc_observers::ObserverPipeline & MCController::observerPipeline(const std::string & name) const
{
auto pipelineIt =
std::find_if(observerPipelines_.begin(), observerPipelines_.end(),
[&name](const mc_observers::ObserverPipeline & pipeline) { return pipeline.name() == name; });
if(pipelineIt != observerPipelines_.end())
{
return *pipelineIt;
}
else
{
mc_rtc::log::error_and_throw<std::runtime_error>("Observer pipeline {} does not exist", name);
}
}
mc_observers::ObserverPipeline & MCController::observerPipeline(const std::string & name)
{
return const_cast<mc_observers::ObserverPipeline &>(static_cast<const MCController *>(this)->observerPipeline(name));
}
bool MCController::hasObserverPipeline() const
{
return !observerPipelines_.empty();
}
const mc_observers::ObserverPipeline & MCController::observerPipeline() const
{
if(!hasObserverPipeline())
{
mc_rtc::log::error_and_throw<std::runtime_error>("Controller {} does not have a default observer pipeline", name_);
}
return observerPipeline(observerPipelines_.front().name());
}
mc_observers::ObserverPipeline & MCController::observerPipeline()
{
return const_cast<mc_observers::ObserverPipeline &>(static_cast<const MCController *>(this)->observerPipeline());
}
bool MCController::run()
{
return run(mc_solver::FeedbackType::None);
}
bool MCController::run(mc_solver::FeedbackType fType)
{
if(!qpsolver->run(fType))
{
mc_rtc::log::error("QP failed to run()");
return false;
}
return true;
}
const mc_solver::QPResultMsg & MCController::send(const double & t)
{
return qpsolver->send(t);
}
void MCController::reset(const ControllerResetData & reset_data)
{
std::vector<std::string> supported;
supported_robots(supported);
if(supported.size() && std::find(supported.cbegin(), supported.cend(), robot().name()) == supported.end())
{
mc_rtc::log::error_and_throw<std::runtime_error>(
"[MCController] The main robot {} is not supported by this controller. Supported robots are: [{}]",
robot().name(), mc_rtc::io::to_string(supported));
}
robot().mbc().zero(robot().mb());
robot().mbc().q = reset_data.q;
postureTask->posture(reset_data.q);
robot().forwardKinematics();
robot().forwardVelocity();
}
const mc_rbdyn::Robots & MCController::robots() const
{
return qpsolver->robots();
}
mc_rbdyn::Robots & MCController::robots()
{
return qpsolver->robots();
}
const mc_rbdyn::Robot & MCController::robot() const
{
return qpsolver->robot();
}
mc_rbdyn::Robot & MCController::robot()
{
return qpsolver->robot();
}
const mc_rbdyn::Robot & MCController::robot(const std::string & name) const
{
return robots().robot(name);
}
mc_rbdyn::Robot & MCController::robot(const std::string & name)
{
return robots().robot(name);
}
const mc_rbdyn::Robots & MCController::realRobots() const
{
return solver().realRobots();
}
mc_rbdyn::Robots & MCController::realRobots()
{
return solver().realRobots();
}
const mc_rbdyn::Robot & MCController::realRobot() const
{
return realRobots().robot();
}
mc_rbdyn::Robot & MCController::realRobot()
{
return realRobots().robot();
}
const mc_rbdyn::Robot & MCController::realRobot(const std::string & name) const
{
return realRobots().robot(name);
}
mc_rbdyn::Robot & MCController::realRobot(const std::string & name)
{
return realRobots().robot(name);
}
const mc_rbdyn::Robot & MCController::env() const
{
return qpsolver->env();
}
mc_rbdyn::Robot & MCController::env()
{
return qpsolver->env();
}
const mc_solver::QPSolver & MCController::solver() const
{
assert(qpsolver);
return *qpsolver;
}
mc_solver::QPSolver & MCController::solver()
{
assert(qpsolver);
return *qpsolver;
}
mc_rtc::Logger & MCController::logger()
{
return *logger_;
}
void MCController::supported_robots(std::vector<std::string> & out) const
{
out = {};
}
void MCController::stop() {}
Gripper & MCController::gripper(const std::string & robot, const std::string & gripper)
{
return robots().robot(robot).gripper(gripper);
}
} // namespace mc_control
|
/****************************************************************************
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.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 "deprecated/CCDictionary.h"
#include <type_traits>
#include "base/ccUTF8.h"
#include "platform/CCFileUtils.h"
#include "deprecated/CCString.h"
#include "deprecated/CCBool.h"
#include "deprecated/CCInteger.h"
#include "deprecated/CCFloat.h"
#include "deprecated/CCDouble.h"
#include "deprecated/CCArray.h"
using namespace std;
NS_CC_BEGIN
// -----------------------------------------------------------------------
// DictElement
DictElement::DictElement(const char* pszKey, Ref* pObject)
{
CCASSERT(pszKey && strlen(pszKey) > 0, "Invalid key value.");
_intKey = 0;
const char* pStart = pszKey;
size_t len = strlen(pszKey);
if (len > MAX_KEY_LEN )
{
char* pEnd = (char*)&pszKey[len-1];
pStart = pEnd - (MAX_KEY_LEN-1);
}
strcpy(_strKey, pStart);
_object = pObject;
memset(&hh, 0, sizeof(hh));
}
DictElement::DictElement(intptr_t iKey, Ref* pObject)
{
_strKey[0] = '\0';
_intKey = iKey;
_object = pObject;
memset(&hh, 0, sizeof(hh));
}
DictElement::~DictElement()
{
CCLOGINFO("deallocing DictElement: %p", this);
}
// -----------------------------------------------------------------------
// __Dictionary
__Dictionary::__Dictionary()
: _elements(nullptr)
, _dictType(kDictUnknown)
{
}
__Dictionary::~__Dictionary()
{
CCLOGINFO("deallocing __Dictionary: %p", this);
removeAllObjects();
}
unsigned int __Dictionary::count()
{
return HASH_COUNT(_elements);
}
__Array* __Dictionary::allKeys()
{
int iKeyCount = this->count();
if (iKeyCount <= 0) return nullptr;
__Array* array = __Array::createWithCapacity(iKeyCount);
DictElement *pElement, *tmp;
if (_dictType == kDictStr)
{
HASH_ITER(hh, _elements, pElement, tmp)
{
__String* pOneKey = new (std::nothrow) __String(pElement->_strKey);
array->addObject(pOneKey);
CC_SAFE_RELEASE(pOneKey);
}
}
else if (_dictType == kDictInt)
{
HASH_ITER(hh, _elements, pElement, tmp)
{
__Integer* pOneKey = new (std::nothrow) __Integer(static_cast<int>(pElement->_intKey));
array->addObject(pOneKey);
CC_SAFE_RELEASE(pOneKey);
}
}
return array;
}
__Array* __Dictionary::allKeysForObject(Ref* object)
{
int iKeyCount = this->count();
if (iKeyCount <= 0) return nullptr;
__Array* array = __Array::create();
DictElement *pElement, *tmp;
if (_dictType == kDictStr)
{
HASH_ITER(hh, _elements, pElement, tmp)
{
if (object == pElement->_object)
{
__String* pOneKey = new (std::nothrow) __String(pElement->_strKey);
array->addObject(pOneKey);
CC_SAFE_RELEASE(pOneKey);
}
}
}
else if (_dictType == kDictInt)
{
HASH_ITER(hh, _elements, pElement, tmp)
{
if (object == pElement->_object)
{
__Integer* pOneKey = new (std::nothrow) __Integer(static_cast<int>(pElement->_intKey));
array->addObject(pOneKey);
CC_SAFE_RELEASE(pOneKey);
}
}
}
return array;
}
Ref* __Dictionary::objectForKey(const std::string& key)
{
// if dictionary wasn't initialized, return nullptr directly.
if (_dictType == kDictUnknown) return nullptr;
// __Dictionary only supports one kind of key, string or integer.
// This method uses string as key, therefore we should make sure that the key type of this __Dictionary is string.
CCASSERT(_dictType == kDictStr, "this dictionary does not use string as key.");
Ref* pRetObject = nullptr;
DictElement *pElement = nullptr;
HASH_FIND_STR(_elements, key.c_str(), pElement);
if (pElement != nullptr)
{
pRetObject = pElement->_object;
}
return pRetObject;
}
Ref* __Dictionary::objectForKey(intptr_t key)
{
// if dictionary wasn't initialized, return nullptr directly.
if (_dictType == kDictUnknown) return nullptr;
// __Dictionary only supports one kind of key, string or integer.
// This method uses integer as key, therefore we should make sure that the key type of this __Dictionary is integer.
CCASSERT(_dictType == kDictInt, "this dictionary does not use integer as key.");
Ref* pRetObject = nullptr;
DictElement *pElement = nullptr;
HASH_FIND_PTR(_elements, &key, pElement);
if (pElement != nullptr)
{
pRetObject = pElement->_object;
}
return pRetObject;
}
const __String* __Dictionary::valueForKey(const std::string& key)
{
__String* pStr = dynamic_cast<__String*>(objectForKey(key));
if (pStr == nullptr)
{
pStr = __String::create("");
}
return pStr;
}
const __String* __Dictionary::valueForKey(intptr_t key)
{
__String* pStr = dynamic_cast<__String*>(objectForKey(key));
if (pStr == nullptr)
{
pStr = __String::create("");
}
return pStr;
}
void __Dictionary::setObject(Ref* pObject, const std::string& key)
{
CCASSERT(!key.empty() && pObject != nullptr, "Invalid Argument!");
if (_dictType == kDictUnknown)
{
_dictType = kDictStr;
}
CCASSERT(_dictType == kDictStr, "this dictionary doesn't use string as key.");
DictElement *pElement = nullptr;
HASH_FIND_STR(_elements, key.c_str(), pElement);
if (pElement == nullptr)
{
setObjectUnSafe(pObject, key);
}
else if (pElement->_object != pObject)
{
Ref* pTmpObj = pElement->_object;
pTmpObj->retain();
removeObjectForElememt(pElement);
setObjectUnSafe(pObject, key);
pTmpObj->release();
}
}
void __Dictionary::setObject(Ref* pObject, intptr_t key)
{
CCASSERT(pObject != nullptr, "Invalid Argument!");
if (_dictType == kDictUnknown)
{
_dictType = kDictInt;
}
CCASSERT(_dictType == kDictInt, "this dictionary doesn't use integer as key.");
DictElement *pElement = nullptr;
HASH_FIND_PTR(_elements, &key, pElement);
if (pElement == nullptr)
{
setObjectUnSafe(pObject, key);
}
else if (pElement->_object != pObject)
{
Ref* pTmpObj = pElement->_object;
pTmpObj->retain();
removeObjectForElememt(pElement);
setObjectUnSafe(pObject, key);
pTmpObj->release();
}
}
void __Dictionary::removeObjectForKey(const std::string& key)
{
if (_dictType == kDictUnknown)
{
return;
}
CCASSERT(_dictType == kDictStr, "this dictionary doesn't use string as its key");
CCASSERT(!key.empty(), "Invalid Argument!");
DictElement *pElement = nullptr;
HASH_FIND_STR(_elements, key.c_str(), pElement);
removeObjectForElememt(pElement);
}
void __Dictionary::removeObjectForKey(intptr_t key)
{
if (_dictType == kDictUnknown)
{
return;
}
CCASSERT(_dictType == kDictInt, "this dictionary doesn't use integer as its key");
DictElement *pElement = nullptr;
HASH_FIND_PTR(_elements, &key, pElement);
removeObjectForElememt(pElement);
}
void __Dictionary::setObjectUnSafe(Ref* pObject, const std::string& key)
{
pObject->retain();
DictElement* pElement = new (std::nothrow) DictElement(key.c_str(), pObject);
HASH_ADD_STR(_elements, _strKey, pElement);
}
void __Dictionary::setObjectUnSafe(Ref* pObject, const intptr_t key)
{
pObject->retain();
DictElement* pElement = new (std::nothrow) DictElement(key, pObject);
HASH_ADD_PTR(_elements, _intKey, pElement);
}
void __Dictionary::removeObjectsForKeys(__Array* pKey__Array)
{
Ref* pObj = nullptr;
CCARRAY_FOREACH(pKey__Array, pObj)
{
__String* pStr = static_cast<__String*>(pObj);
removeObjectForKey(pStr->getCString());
}
}
void __Dictionary::removeObjectForElememt(DictElement* pElement)
{
if (pElement != nullptr)
{
HASH_DEL(_elements, pElement);
pElement->_object->release();
CC_SAFE_DELETE(pElement);
}
}
void __Dictionary::removeAllObjects()
{
DictElement *pElement, *tmp;
HASH_ITER(hh, _elements, pElement, tmp)
{
HASH_DEL(_elements, pElement);
pElement->_object->release();
CC_SAFE_DELETE(pElement);
}
}
Ref* __Dictionary::randomObject()
{
if (_dictType == kDictUnknown)
{
return nullptr;
}
Ref* key = allKeys()->getRandomObject();
if (_dictType == kDictInt)
{
return objectForKey( static_cast<__Integer*>(key)->getValue());
}
else if (_dictType == kDictStr)
{
return objectForKey( static_cast<__String*>(key)->getCString());
}
else
{
return nullptr;
}
}
__Dictionary* __Dictionary::create()
{
__Dictionary* ret = new (std::nothrow) __Dictionary();
if (ret && ret->init() )
{
ret->autorelease();
}
return ret;
}
bool __Dictionary::init()
{
return true;
}
__Dictionary* __Dictionary::createWithDictionary(__Dictionary* srcDict)
{
return srcDict->clone();
}
static __Array* visitArray(const ValueVector& array);
static __Dictionary* visitDict(const ValueMap& dict)
{
__Dictionary* ret = new (std::nothrow) __Dictionary();
ret->init();
for (auto iter = dict.begin(); iter != dict.end(); ++iter)
{
if (iter->second.getType() == Value::Type::MAP)
{
const ValueMap& subDict = iter->second.asValueMap();
auto sub = visitDict(subDict);
ret->setObject(sub, iter->first);
sub->release();
}
else if (iter->second.getType() == Value::Type::VECTOR)
{
const ValueVector& arr = iter->second.asValueVector();
auto sub = visitArray(arr);
ret->setObject(sub, iter->first);
sub->release();
}
else
{
auto str = new (std::nothrow) __String(iter->second.asString());
ret->setObject(str, iter->first);
str->release();
}
}
return ret;
}
static __Array* visitArray(const ValueVector& array)
{
__Array* ret = new (std::nothrow) __Array();
ret->init();
for(const auto &value : array) {
if (value.getType() == Value::Type::MAP)
{
const ValueMap& subDict = value.asValueMap();
auto sub = visitDict(subDict);
ret->addObject(sub);
sub->release();
}
else if (value.getType() == Value::Type::VECTOR)
{
const ValueVector& arr = value.asValueVector();
auto sub = visitArray(arr);
ret->addObject(sub);
sub->release();
}
else
{
auto str = new (std::nothrow) __String(value.asString());
ret->addObject(str);
str->release();
}
}
return ret;
}
__Dictionary* __Dictionary::createWithContentsOfFileThreadSafe(const char *pFileName)
{
return visitDict(FileUtils::getInstance()->getValueMapFromFile(pFileName));
}
void __Dictionary::acceptVisitor(DataVisitor &visitor)
{
return visitor.visit(this);
}
__Dictionary* __Dictionary::createWithContentsOfFile(const char *pFileName)
{
auto ret = createWithContentsOfFileThreadSafe(pFileName);
if (ret != nullptr)
{
ret->autorelease();
}
return ret;
}
static ValueMap ccdictionary_to_valuemap(__Dictionary* dict);
static ValueVector ccarray_to_valuevector(__Array* arr)
{
ValueVector ret;
Ref* obj;
CCARRAY_FOREACH(arr, obj)
{
Value arrElement;
__String* strVal = nullptr;
__Dictionary* dictVal = nullptr;
__Array* arrVal = nullptr;
__Double* doubleVal = nullptr;
__Bool* boolVal = nullptr;
__Float* floatVal = nullptr;
__Integer* intVal = nullptr;
if ((strVal = dynamic_cast<__String *>(obj))) {
arrElement = Value(strVal->getCString());
} else if ((dictVal = dynamic_cast<__Dictionary*>(obj))) {
arrElement = ccdictionary_to_valuemap(dictVal);
} else if ((arrVal = dynamic_cast<__Array*>(obj))) {
arrElement = ccarray_to_valuevector(arrVal);
} else if ((doubleVal = dynamic_cast<__Double*>(obj))) {
arrElement = Value(doubleVal->getValue());
} else if ((floatVal = dynamic_cast<__Float*>(obj))) {
arrElement = Value(floatVal->getValue());
} else if ((intVal = dynamic_cast<__Integer*>(obj))) {
arrElement = Value(intVal->getValue());
} else if ((boolVal = dynamic_cast<__Bool*>(obj))) {
arrElement = boolVal->getValue() ? Value(true) : Value(false);
} else {
CCASSERT(false, "the type isn't supported.");
}
ret.push_back(arrElement);
}
return ret;
}
static ValueMap ccdictionary_to_valuemap(__Dictionary* dict)
{
ValueMap ret;
DictElement* pElement = nullptr;
CCDICT_FOREACH(dict, pElement)
{
Ref* obj = pElement->getObject();
__String* strVal = nullptr;
__Dictionary* dictVal = nullptr;
__Array* arrVal = nullptr;
__Double* doubleVal = nullptr;
__Bool* boolVal = nullptr;
__Float* floatVal = nullptr;
__Integer* intVal = nullptr;
Value dictElement;
if ((strVal = dynamic_cast<__String *>(obj))) {
dictElement = Value(strVal->getCString());
} else if ((dictVal = dynamic_cast<__Dictionary*>(obj))) {
dictElement = ccdictionary_to_valuemap(dictVal);
} else if ((arrVal = dynamic_cast<__Array*>(obj))) {
dictElement = ccarray_to_valuevector(arrVal);
} else if ((doubleVal = dynamic_cast<__Double*>(obj))) {
dictElement = Value(doubleVal->getValue());
} else if ((floatVal = dynamic_cast<__Float*>(obj))) {
dictElement = Value(floatVal->getValue());
} else if ((intVal = dynamic_cast<__Integer*>(obj))) {
dictElement = Value(intVal->getValue());
} else if ((boolVal = dynamic_cast<__Bool*>(obj))) {
dictElement = boolVal->getValue() ? Value(true) : Value(false);
} else {
CCASSERT(false, "the type isn't supported.");
}
const char* key = pElement->getStrKey();
if (key && strlen(key) > 0)
{
ret[key] = dictElement;
}
}
return ret;
}
bool __Dictionary::writeToFile(const char *fullPath)
{
ValueMap dict = ccdictionary_to_valuemap(this);
return FileUtils::getInstance()->writeToFile(dict, fullPath);
}
__Dictionary* __Dictionary::clone() const
{
__Dictionary* newDict = __Dictionary::create();
DictElement* element = nullptr;
Ref* tmpObj = nullptr;
Clonable* obj = nullptr;
if (_dictType == kDictInt)
{
DictElement* tmp = nullptr;
HASH_ITER(hh, _elements, element, tmp)
{
obj = dynamic_cast<Clonable*>(element->getObject());
if (obj)
{
tmpObj = dynamic_cast<Ref*>(obj->clone());
if (tmpObj)
{
newDict->setObject(tmpObj, element->getIntKey());
}
}
else
{
CCLOGWARN("%s isn't clonable.", typeid(std::remove_pointer<decltype(element->getObject())>::type).name());
}
}
}
else if (_dictType == kDictStr)
{
DictElement* tmp = nullptr;
HASH_ITER(hh, _elements, element, tmp)
{
obj = dynamic_cast<Clonable*>(element->getObject());
if (obj)
{
tmpObj = dynamic_cast<Ref*>(obj->clone());
if (tmpObj)
{
newDict->setObject(tmpObj, element->getStrKey());
}
}
else
{
CCLOGWARN("%s isn't clonable.", typeid(std::remove_pointer<decltype(element->getObject())>::type).name());
}
}
}
return newDict;
}
NS_CC_END
|
#include "PoolMalloc.hh"
//#include "CUtilities.h"
#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
static const size_t POOLBLOCKSIZE = 10*1024*1024;
/// Print current line and exit
#define DIE() \
do { \
fprintf(stderr,"Aborted. File: %s, Line: %d\n",__FILE__,__LINE__); \
exit(EXIT_FAILURE); \
} while(0)
/// Print a message and then DIE()
#define DIEM(m) do { fprintf(stderr,m"\n"); DIE(); } while(0)
/// DIE() if the pointer is NULL
#define DIENULL(p) do { if ( !(p) ) { DIEM("Out of memory"); } } while(0)
/// Malloc memory, DIE() if NULL
#define MALLOC(p,t,s) DIENULL( (p) = (t) malloc(s) )
/// Malloc memory for objects of type t, DIE() if NULL
#define NEW(p,t) MALLOC(p, t*, sizeof(t))
#include <cstdlib>
struct PoolNode_t
{
char *block;
size_t offset;
size_t remaining;
size_t size;
PoolNode_t *next;
};
//============================================================ PoolMalloc_t ====
//------------------------------------------------------------ PoolMalloc_t ----
PoolMalloc_t::PoolMalloc_t()
{
head_m = NULL;
}
//----------------------------------------------------------- ~PoolMalloc_t ----
PoolMalloc_t::~PoolMalloc_t()
{
pfree();
}
//-------------------------------------------------------------------- free ----
void PoolMalloc_t::pfree()
{
PoolNode_t * next;
while ( head_m )
{
next = head_m->next;
free(head_m->block);
free(head_m);
head_m = next;
}
head_m = NULL;
}
//------------------------------------------------------------------ malloc ----
///
/// Parcel memory from big byte buckets. Return all memory with 8 byte
/// alignment to silence the bus errors on Alpha and Solaris.
///
void * PoolMalloc_t::pmalloc(size_t size)
{
size_t remainder = size % 8;
//-- Make sure the next block is 8 byte aligned
if ( remainder ) size += 8 - remainder;
if ( head_m == NULL || size > head_m->remaining )
{
size_t blockSize = POOLBLOCKSIZE;
if ( size > blockSize ) blockSize = size;
PoolNode_t *newHead;
NEW(newHead, PoolNode_t);
MALLOC(newHead->block, char*, blockSize);
newHead->size = blockSize;
newHead->remaining = blockSize;
newHead->offset = 0;
newHead->next = head_m;
head_m = newHead;
}
void *retval = head_m->block + head_m->offset;
head_m->offset += size;
head_m->remaining -= size;
return retval;
}
//------------------------------------------------------------------ strdup ----
char * PoolMalloc_t::pstrdup(const char * s)
{
size_t size = strlen(s) + 1;
char *retval = (char *) pmalloc(size);
memcpy(retval, s, size);
return retval;
}
|
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal \file
*
* \brief Implements GPU bonded lists for non-GPU builds
*
* \author Mark Abraham <mark.j.abraham@gmail.com>
*
* \ingroup module_listed_forces
*/
#include "gmxpre.h"
#include "config.h"
#include <string>
#include "gromacs/listed_forces/gpubonded.h"
#include "gromacs/mdtypes/inputrec.h"
#include "gromacs/topology/topology.h"
#include "gromacs/utility/stringutil.h"
namespace gmx
{
//! Returns whether there are any interactions in ilists suitable for a GPU.
static bool someInteractionsCanRunOnGpu(const InteractionLists& ilists)
{
for (int fType : fTypesOnGpu)
{
if (!ilists[fType].iatoms.empty())
{
// Perturbation is not implemented in the GPU bonded
// kernels. If all the interactions were actually
// perturbed, then that will be detected later on each
// domain, and work will never run on the GPU. This is
// very unlikely to occur, and has little run-time cost,
// so we don't complicate the code by catering for it
// here.
return true;
}
}
return false;
}
//! Returns whether there are any bonded interactions in the global topology suitable for a GPU.
static bool bondedInteractionsCanRunOnGpu(const gmx_mtop_t& mtop)
{
// Check the regular molecule types
for (const auto& moltype : mtop.moltype)
{
if (someInteractionsCanRunOnGpu(moltype.ilist))
{
return true;
}
}
// Check the inter-molecular interactions.
if (mtop.intermolecular_ilist)
{
if (someInteractionsCanRunOnGpu(*mtop.intermolecular_ilist))
{
return true;
}
}
return false;
}
/*! \brief Help build a descriptive message in \c error if there are
* \c errorReasons why bondeds on a GPU are not supported.
*
* \returns Whether the lack of errorReasons indicate there is support. */
static bool addMessageIfNotSupported(ArrayRef<const std::string> errorReasons, std::string* error)
{
bool isSupported = errorReasons.empty();
if (!isSupported && error)
{
*error = "Bonded interactions cannot run on GPUs: ";
*error += joinStrings(errorReasons, "; ") + ".";
}
return isSupported;
}
bool buildSupportsGpuBondeds(std::string* error)
{
std::vector<std::string> errorReasons;
if (GMX_DOUBLE)
{
errorReasons.emplace_back("not supported with double precision");
}
if (GMX_GPU_OPENCL)
{
errorReasons.emplace_back("not supported with OpenCL build of GROMACS");
}
else if (!GMX_GPU)
{
errorReasons.emplace_back("not supported with CPU-only build of GROMACS");
}
return addMessageIfNotSupported(errorReasons, error);
}
bool inputSupportsGpuBondeds(const t_inputrec& ir, const gmx_mtop_t& mtop, std::string* error)
{
std::vector<std::string> errorReasons;
if (!bondedInteractionsCanRunOnGpu(mtop))
{
errorReasons.emplace_back("No supported bonded interactions are present");
}
if (!EI_DYNAMICS(ir.eI))
{
errorReasons.emplace_back(
"Cannot compute bonded interactions on a GPU, because GPU implementation requires "
"a dynamical integrator (md, sd, etc).");
}
if (EI_MIMIC(ir.eI))
{
errorReasons.emplace_back("MiMiC");
}
if (ir.useMts)
{
errorReasons.emplace_back("Cannot run with multiple time stepping");
}
if (ir.opts.ngener > 1)
{
errorReasons.emplace_back("Cannot run with multiple energy groups");
}
return addMessageIfNotSupported(errorReasons, error);
}
#if !GMX_GPU_CUDA
class GpuBonded::Impl
{
};
GpuBonded::GpuBonded(const gmx_ffparams_t& /* ffparams */,
const float /* electrostaticsScaleFactor */,
const DeviceContext& /* deviceContext */,
const DeviceStream& /* deviceStream */,
gmx_wallcycle* /* wcycle */) :
impl_(nullptr)
{
}
GpuBonded::~GpuBonded() = default;
void GpuBonded::updateInteractionListsAndDeviceBuffers(ArrayRef<const int> /* nbnxnAtomOrder */,
const InteractionDefinitions& /* idef */,
void* /* xqDevice */,
DeviceBuffer<RVec> /* forceDevice */,
DeviceBuffer<RVec> /* fshiftDevice */)
{
}
void GpuBonded::setPbc(PbcType /* pbcType */, const matrix /* box */, bool /* canMoleculeSpanPbc */)
{
}
bool GpuBonded::haveInteractions() const
{
return !impl_;
}
void GpuBonded::launchKernel(const gmx::StepWorkload& /* stepWork */) {}
void GpuBonded::setPbcAndlaunchKernel(PbcType /* pbcType */,
const matrix /* box */,
bool /* canMoleculeSpanPbc */,
const gmx::StepWorkload& /* stepWork */)
{
}
void GpuBonded::launchEnergyTransfer() {}
void GpuBonded::waitAccumulateEnergyTerms(gmx_enerdata_t* /* enerd */) {}
void GpuBonded::clearEnergies() {}
#endif // !GMX_GPU_CUDA
} // namespace gmx
|
//===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
//
// 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 defines the ASTImporter class which imports AST nodes from one
// context into another context.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTImporter.h"
#include "clang/AST/ASTImporterSharedState.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTDiagnostic.h"
#include "clang/AST/ASTStructuralEquivalence.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclAccessPair.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclFriend.h"
#include "clang/AST/DeclGroup.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/LambdaCapture.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
#include "clang/AST/TypeVisitor.h"
#include "clang/AST/UnresolvedSet.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/ExceptionSpecificationType.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Specifiers.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MemoryBuffer.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>
namespace clang {
using llvm::make_error;
using llvm::Error;
using llvm::Expected;
using ExpectedType = llvm::Expected<QualType>;
using ExpectedStmt = llvm::Expected<Stmt *>;
using ExpectedExpr = llvm::Expected<Expr *>;
using ExpectedDecl = llvm::Expected<Decl *>;
using ExpectedSLoc = llvm::Expected<SourceLocation>;
using ExpectedName = llvm::Expected<DeclarationName>;
std::string ImportError::toString() const {
// FIXME: Improve error texts.
switch (Error) {
case NameConflict:
return "NameConflict";
case UnsupportedConstruct:
return "UnsupportedConstruct";
case Unknown:
return "Unknown error";
}
llvm_unreachable("Invalid error code.");
return "Invalid error code.";
}
void ImportError::log(raw_ostream &OS) const {
OS << toString();
}
std::error_code ImportError::convertToErrorCode() const {
llvm_unreachable("Function not implemented.");
}
char ImportError::ID;
template <class T>
SmallVector<Decl *, 2>
getCanonicalForwardRedeclChain(Redeclarable<T>* D) {
SmallVector<Decl *, 2> Redecls;
for (auto *R : D->getFirstDecl()->redecls()) {
if (R != D->getFirstDecl())
Redecls.push_back(R);
}
Redecls.push_back(D->getFirstDecl());
std::reverse(Redecls.begin(), Redecls.end());
return Redecls;
}
SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) {
if (auto *FD = dyn_cast<FunctionDecl>(D))
return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
if (auto *VD = dyn_cast<VarDecl>(D))
return getCanonicalForwardRedeclChain<VarDecl>(VD);
if (auto *TD = dyn_cast<TagDecl>(D))
return getCanonicalForwardRedeclChain<TagDecl>(TD);
llvm_unreachable("Bad declaration kind");
}
void updateFlags(const Decl *From, Decl *To) {
// Check if some flags or attrs are new in 'From' and copy into 'To'.
// FIXME: Other flags or attrs?
if (From->isUsed(false) && !To->isUsed(false))
To->setIsUsed();
}
class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
ASTImporter &Importer;
// Use this instead of Importer.importInto .
template <typename ImportT>
LLVM_NODISCARD Error importInto(ImportT &To, const ImportT &From) {
return Importer.importInto(To, From);
}
// Use this to import pointers of specific type.
template <typename ImportT>
LLVM_NODISCARD Error importInto(ImportT *&To, ImportT *From) {
auto ToOrErr = Importer.Import(From);
if (ToOrErr)
To = cast_or_null<ImportT>(*ToOrErr);
return ToOrErr.takeError();
}
// Call the import function of ASTImporter for a baseclass of type `T` and
// cast the return value to `T`.
template <typename T>
Expected<T *> import(T *From) {
auto ToOrErr = Importer.Import(From);
if (!ToOrErr)
return ToOrErr.takeError();
return cast_or_null<T>(*ToOrErr);
}
template <typename T>
Expected<T *> import(const T *From) {
return import(const_cast<T *>(From));
}
// Call the import function of ASTImporter for type `T`.
template <typename T>
Expected<T> import(const T &From) {
return Importer.Import(From);
}
// Import an Optional<T> by importing the contained T, if any.
template<typename T>
Expected<Optional<T>> import(Optional<T> From) {
if (!From)
return Optional<T>();
return import(*From);
}
// Helper for chaining together multiple imports. If an error is detected,
// subsequent imports will return default constructed nodes, so that failure
// can be detected with a single conditional branch after a sequence of
// imports.
template <typename T> T importChecked(Error &Err, const T &From) {
// Don't attempt to import nodes if we hit an error earlier.
if (Err)
return T{};
Expected<T> MaybeVal = import(From);
if (!MaybeVal) {
Err = MaybeVal.takeError();
return T{};
}
return *MaybeVal;
}
ExplicitSpecifier importExplicitSpecifier(Error &Err,
ExplicitSpecifier ESpec);
// Wrapper for an overload set.
template <typename ToDeclT> struct CallOverloadedCreateFun {
template <typename... Args> decltype(auto) operator()(Args &&... args) {
return ToDeclT::Create(std::forward<Args>(args)...);
}
};
// Always use these functions to create a Decl during import. There are
// certain tasks which must be done after the Decl was created, e.g. we
// must immediately register that as an imported Decl. The parameter `ToD`
// will be set to the newly created Decl or if had been imported before
// then to the already imported Decl. Returns a bool value set to true if
// the `FromD` had been imported before.
template <typename ToDeclT, typename FromDeclT, typename... Args>
LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
Args &&... args) {
// There may be several overloads of ToDeclT::Create. We must make sure
// to call the one which would be chosen by the arguments, thus we use a
// wrapper for the overload set.
CallOverloadedCreateFun<ToDeclT> OC;
return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
std::forward<Args>(args)...);
}
// Use this overload if a special Type is needed to be created. E.g if we
// want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
// then:
// TypedefNameDecl *ToTypedef;
// GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
typename... Args>
LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
Args &&... args) {
CallOverloadedCreateFun<NewDeclT> OC;
return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
std::forward<Args>(args)...);
}
// Use this version if a special create function must be
// used, e.g. CXXRecordDecl::CreateLambda .
template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
typename... Args>
LLVM_NODISCARD bool
GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
FromDeclT *FromD, Args &&... args) {
if (Importer.getImportDeclErrorIfAny(FromD)) {
ToD = nullptr;
return true; // Already imported but with error.
}
ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
if (ToD)
return true; // Already imported.
ToD = CreateFun(std::forward<Args>(args)...);
// Keep track of imported Decls.
Importer.RegisterImportedDecl(FromD, ToD);
InitializeImportedDecl(FromD, ToD);
return false; // A new Decl is created.
}
void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
ToD->IdentifierNamespace = FromD->IdentifierNamespace;
if (FromD->isUsed())
ToD->setIsUsed();
if (FromD->isImplicit())
ToD->setImplicit();
}
// Check if we have found an existing definition. Returns with that
// definition if yes, otherwise returns null.
Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
const FunctionDecl *Definition = nullptr;
if (D->doesThisDeclarationHaveABody() &&
FoundFunction->hasBody(Definition))
return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
return nullptr;
}
void addDeclToContexts(Decl *FromD, Decl *ToD) {
if (Importer.isMinimalImport()) {
// In minimal import case the decl must be added even if it is not
// contained in original context, for LLDB compatibility.
// FIXME: Check if a better solution is possible.
if (!FromD->getDescribedTemplate() &&
FromD->getFriendObjectKind() == Decl::FOK_None)
ToD->getLexicalDeclContext()->addDeclInternal(ToD);
return;
}
DeclContext *FromDC = FromD->getDeclContext();
DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
DeclContext *ToDC = ToD->getDeclContext();
DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
bool Visible = false;
if (FromDC->containsDeclAndLoad(FromD)) {
ToDC->addDeclInternal(ToD);
Visible = true;
}
if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) {
ToLexicalDC->addDeclInternal(ToD);
Visible = true;
}
// If the Decl was added to any context, it was made already visible.
// Otherwise it is still possible that it should be visible.
if (!Visible) {
if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) {
auto *ToNamed = cast<NamedDecl>(ToD);
DeclContextLookupResult FromLookup =
FromDC->lookup(FromNamed->getDeclName());
for (NamedDecl *ND : FromLookup)
if (ND == FromNamed) {
ToDC->makeDeclVisibleInContext(ToNamed);
break;
}
}
}
}
public:
explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit;
using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit;
using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit;
// Importing types
ExpectedType VisitType(const Type *T);
ExpectedType VisitAtomicType(const AtomicType *T);
ExpectedType VisitBuiltinType(const BuiltinType *T);
ExpectedType VisitDecayedType(const DecayedType *T);
ExpectedType VisitComplexType(const ComplexType *T);
ExpectedType VisitPointerType(const PointerType *T);
ExpectedType VisitBlockPointerType(const BlockPointerType *T);
ExpectedType VisitLValueReferenceType(const LValueReferenceType *T);
ExpectedType VisitRValueReferenceType(const RValueReferenceType *T);
ExpectedType VisitMemberPointerType(const MemberPointerType *T);
ExpectedType VisitConstantArrayType(const ConstantArrayType *T);
ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T);
ExpectedType VisitVariableArrayType(const VariableArrayType *T);
ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
// FIXME: DependentSizedExtVectorType
ExpectedType VisitVectorType(const VectorType *T);
ExpectedType VisitExtVectorType(const ExtVectorType *T);
ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
ExpectedType VisitFunctionProtoType(const FunctionProtoType *T);
ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
ExpectedType VisitParenType(const ParenType *T);
ExpectedType VisitTypedefType(const TypedefType *T);
ExpectedType VisitTypeOfExprType(const TypeOfExprType *T);
// FIXME: DependentTypeOfExprType
ExpectedType VisitTypeOfType(const TypeOfType *T);
ExpectedType VisitDecltypeType(const DecltypeType *T);
ExpectedType VisitUnaryTransformType(const UnaryTransformType *T);
ExpectedType VisitAutoType(const AutoType *T);
ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T);
// FIXME: DependentDecltypeType
ExpectedType VisitRecordType(const RecordType *T);
ExpectedType VisitEnumType(const EnumType *T);
ExpectedType VisitAttributedType(const AttributedType *T);
ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
ExpectedType VisitSubstTemplateTypeParmType(
const SubstTemplateTypeParmType *T);
ExpectedType VisitTemplateSpecializationType(
const TemplateSpecializationType *T);
ExpectedType VisitElaboratedType(const ElaboratedType *T);
ExpectedType VisitDependentNameType(const DependentNameType *T);
ExpectedType VisitPackExpansionType(const PackExpansionType *T);
ExpectedType VisitDependentTemplateSpecializationType(
const DependentTemplateSpecializationType *T);
ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
// Importing declarations
Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
SourceLocation &Loc);
Error ImportDeclParts(
NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
Error ImportDeclarationNameLoc(
const DeclarationNameInfo &From, DeclarationNameInfo &To);
Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
Error ImportDeclContext(
Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
Expected<CXXCastPath> ImportCastPath(CastExpr *E);
Expected<APValue> ImportAPValue(const APValue &FromValue);
using Designator = DesignatedInitExpr::Designator;
/// What we should import from the definition.
enum ImportDefinitionKind {
/// Import the default subset of the definition, which might be
/// nothing (if minimal import is set) or might be everything (if minimal
/// import is not set).
IDK_Default,
/// Import everything.
IDK_Everything,
/// Import only the bare bones needed to establish a valid
/// DeclContext.
IDK_Basic
};
bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
return IDK == IDK_Everything ||
(IDK == IDK_Default && !Importer.isMinimalImport());
}
Error ImportInitializer(VarDecl *From, VarDecl *To);
Error ImportDefinition(
RecordDecl *From, RecordDecl *To,
ImportDefinitionKind Kind = IDK_Default);
Error ImportDefinition(
EnumDecl *From, EnumDecl *To,
ImportDefinitionKind Kind = IDK_Default);
Error ImportDefinition(
ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
ImportDefinitionKind Kind = IDK_Default);
Error ImportDefinition(
ObjCProtocolDecl *From, ObjCProtocolDecl *To,
ImportDefinitionKind Kind = IDK_Default);
Error ImportTemplateArguments(
const TemplateArgument *FromArgs, unsigned NumFromArgs,
SmallVectorImpl<TemplateArgument> &ToArgs);
Expected<TemplateArgument>
ImportTemplateArgument(const TemplateArgument &From);
template <typename InContainerTy>
Error ImportTemplateArgumentListInfo(
const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
template<typename InContainerTy>
Error ImportTemplateArgumentListInfo(
SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
const InContainerTy &Container, TemplateArgumentListInfo &Result);
using TemplateArgsTy = SmallVector<TemplateArgument, 8>;
using FunctionTemplateAndArgsTy =
std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
Expected<FunctionTemplateAndArgsTy>
ImportFunctionTemplateWithTemplateArgsFromSpecialization(
FunctionDecl *FromFD);
Error ImportTemplateParameterLists(const DeclaratorDecl *FromD,
DeclaratorDecl *ToD);
Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
ParmVarDecl *ToParam);
template <typename T>
bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
bool Complain = true);
bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
bool Complain = true);
bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
bool IsStructuralMatch(FunctionTemplateDecl *From,
FunctionTemplateDecl *To);
bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To);
bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
ExpectedDecl VisitDecl(Decl *D);
ExpectedDecl VisitImportDecl(ImportDecl *D);
ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
ExpectedDecl VisitLabelDecl(LabelDecl *D);
ExpectedDecl VisitEnumDecl(EnumDecl *D);
ExpectedDecl VisitRecordDecl(RecordDecl *D);
ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D);
ExpectedDecl VisitFieldDecl(FieldDecl *D);
ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
ExpectedDecl VisitFriendDecl(FriendDecl *D);
ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
ExpectedDecl VisitVarDecl(VarDecl *D);
ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
ExpectedDecl VisitUsingDecl(UsingDecl *D);
ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
ExpectedDecl
VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
Expected<ObjCTypeParamList *>
ImportObjCTypeParamList(ObjCTypeParamList *list);
ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
ExpectedDecl VisitClassTemplateSpecializationDecl(
ClassTemplateSpecializationDecl *D);
ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
// Importing statements
ExpectedStmt VisitStmt(Stmt *S);
ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
ExpectedStmt VisitDeclStmt(DeclStmt *S);
ExpectedStmt VisitNullStmt(NullStmt *S);
ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
ExpectedStmt VisitCaseStmt(CaseStmt *S);
ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
ExpectedStmt VisitLabelStmt(LabelStmt *S);
ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
ExpectedStmt VisitIfStmt(IfStmt *S);
ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
ExpectedStmt VisitWhileStmt(WhileStmt *S);
ExpectedStmt VisitDoStmt(DoStmt *S);
ExpectedStmt VisitForStmt(ForStmt *S);
ExpectedStmt VisitGotoStmt(GotoStmt *S);
ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
ExpectedStmt VisitContinueStmt(ContinueStmt *S);
ExpectedStmt VisitBreakStmt(BreakStmt *S);
ExpectedStmt VisitReturnStmt(ReturnStmt *S);
// FIXME: MSAsmStmt
// FIXME: SEHExceptStmt
// FIXME: SEHFinallyStmt
// FIXME: SEHTryStmt
// FIXME: SEHLeaveStmt
// FIXME: CapturedStmt
ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
// FIXME: MSDependentExistsStmt
ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
// Importing expressions
ExpectedStmt VisitExpr(Expr *E);
ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
ExpectedStmt VisitChooseExpr(ChooseExpr *E);
ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E);
ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E);
ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
ExpectedStmt VisitStringLiteral(StringLiteral *E);
ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
ExpectedStmt VisitConstantExpr(ConstantExpr *E);
ExpectedStmt VisitParenExpr(ParenExpr *E);
ExpectedStmt VisitParenListExpr(ParenListExpr *E);
ExpectedStmt VisitStmtExpr(StmtExpr *E);
ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
ExpectedStmt VisitMemberExpr(MemberExpr *E);
ExpectedStmt VisitCallExpr(CallExpr *E);
ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
ExpectedStmt VisitInitListExpr(InitListExpr *E);
ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E);
template<typename IIter, typename OIter>
Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
using ItemT = std::remove_reference_t<decltype(*Obegin)>;
for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
Expected<ItemT> ToOrErr = import(*Ibegin);
if (!ToOrErr)
return ToOrErr.takeError();
*Obegin = *ToOrErr;
}
return Error::success();
}
// Import every item from a container structure into an output container.
// If error occurs, stops at first error and returns the error.
// The output container should have space for all needed elements (it is not
// expanded, new items are put into from the beginning).
template<typename InContainerTy, typename OutContainerTy>
Error ImportContainerChecked(
const InContainerTy &InContainer, OutContainerTy &OutContainer) {
return ImportArrayChecked(
InContainer.begin(), InContainer.end(), OutContainer.begin());
}
template<typename InContainerTy, typename OIter>
Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
}
Error ImportOverriddenMethods(CXXMethodDecl *ToMethod,
CXXMethodDecl *FromMethod);
Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
FunctionDecl *FromFD);
// Returns true if the given function has a placeholder return type and
// that type is declared inside the body of the function.
// E.g. auto f() { struct X{}; return X(); }
bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D);
};
template <typename InContainerTy>
Error ASTNodeImporter::ImportTemplateArgumentListInfo(
SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
const InContainerTy &Container, TemplateArgumentListInfo &Result) {
auto ToLAngleLocOrErr = import(FromLAngleLoc);
if (!ToLAngleLocOrErr)
return ToLAngleLocOrErr.takeError();
auto ToRAngleLocOrErr = import(FromRAngleLoc);
if (!ToRAngleLocOrErr)
return ToRAngleLocOrErr.takeError();
TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
return Err;
Result = ToTAInfo;
return Error::success();
}
template <>
Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
return ImportTemplateArgumentListInfo(
From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
}
template <>
Error ASTNodeImporter::ImportTemplateArgumentListInfo<
ASTTemplateArgumentListInfo>(
const ASTTemplateArgumentListInfo &From,
TemplateArgumentListInfo &Result) {
return ImportTemplateArgumentListInfo(
From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
}
Expected<ASTNodeImporter::FunctionTemplateAndArgsTy>
ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
FunctionDecl *FromFD) {
assert(FromFD->getTemplatedKind() ==
FunctionDecl::TK_FunctionTemplateSpecialization);
FunctionTemplateAndArgsTy Result;
auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
return std::move(Err);
// Import template arguments.
auto TemplArgs = FTSInfo->TemplateArguments->asArray();
if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
std::get<1>(Result)))
return std::move(Err);
return Result;
}
template <>
Expected<TemplateParameterList *>
ASTNodeImporter::import(TemplateParameterList *From) {
SmallVector<NamedDecl *, 4> To(From->size());
if (Error Err = ImportContainerChecked(*From, To))
return std::move(Err);
ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
if (!ToRequiresClause)
return ToRequiresClause.takeError();
auto ToTemplateLocOrErr = import(From->getTemplateLoc());
if (!ToTemplateLocOrErr)
return ToTemplateLocOrErr.takeError();
auto ToLAngleLocOrErr = import(From->getLAngleLoc());
if (!ToLAngleLocOrErr)
return ToLAngleLocOrErr.takeError();
auto ToRAngleLocOrErr = import(From->getRAngleLoc());
if (!ToRAngleLocOrErr)
return ToRAngleLocOrErr.takeError();
return TemplateParameterList::Create(
Importer.getToContext(),
*ToTemplateLocOrErr,
*ToLAngleLocOrErr,
To,
*ToRAngleLocOrErr,
*ToRequiresClause);
}
template <>
Expected<TemplateArgument>
ASTNodeImporter::import(const TemplateArgument &From) {
switch (From.getKind()) {
case TemplateArgument::Null:
return TemplateArgument();
case TemplateArgument::Type: {
ExpectedType ToTypeOrErr = import(From.getAsType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
return TemplateArgument(*ToTypeOrErr);
}
case TemplateArgument::Integral: {
ExpectedType ToTypeOrErr = import(From.getIntegralType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
return TemplateArgument(From, *ToTypeOrErr);
}
case TemplateArgument::Declaration: {
Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
if (!ToOrErr)
return ToOrErr.takeError();
ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
return TemplateArgument(*ToOrErr, *ToTypeOrErr);
}
case TemplateArgument::NullPtr: {
ExpectedType ToTypeOrErr = import(From.getNullPtrType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
}
case TemplateArgument::Template: {
Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
if (!ToTemplateOrErr)
return ToTemplateOrErr.takeError();
return TemplateArgument(*ToTemplateOrErr);
}
case TemplateArgument::TemplateExpansion: {
Expected<TemplateName> ToTemplateOrErr =
import(From.getAsTemplateOrTemplatePattern());
if (!ToTemplateOrErr)
return ToTemplateOrErr.takeError();
return TemplateArgument(
*ToTemplateOrErr, From.getNumTemplateExpansions());
}
case TemplateArgument::Expression:
if (ExpectedExpr ToExpr = import(From.getAsExpr()))
return TemplateArgument(*ToExpr);
else
return ToExpr.takeError();
case TemplateArgument::Pack: {
SmallVector<TemplateArgument, 2> ToPack;
ToPack.reserve(From.pack_size());
if (Error Err = ImportTemplateArguments(
From.pack_begin(), From.pack_size(), ToPack))
return std::move(Err);
return TemplateArgument(
llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
}
}
llvm_unreachable("Invalid template argument kind");
}
template <>
Expected<TemplateArgumentLoc>
ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
if (!ArgOrErr)
return ArgOrErr.takeError();
TemplateArgument Arg = *ArgOrErr;
TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
TemplateArgumentLocInfo ToInfo;
if (Arg.getKind() == TemplateArgument::Expression) {
ExpectedExpr E = import(FromInfo.getAsExpr());
if (!E)
return E.takeError();
ToInfo = TemplateArgumentLocInfo(*E);
} else if (Arg.getKind() == TemplateArgument::Type) {
if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
else
return TSIOrErr.takeError();
} else {
auto ToTemplateQualifierLocOrErr =
import(FromInfo.getTemplateQualifierLoc());
if (!ToTemplateQualifierLocOrErr)
return ToTemplateQualifierLocOrErr.takeError();
auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
if (!ToTemplateNameLocOrErr)
return ToTemplateNameLocOrErr.takeError();
auto ToTemplateEllipsisLocOrErr =
import(FromInfo.getTemplateEllipsisLoc());
if (!ToTemplateEllipsisLocOrErr)
return ToTemplateEllipsisLocOrErr.takeError();
ToInfo = TemplateArgumentLocInfo(
Importer.getToContext(), *ToTemplateQualifierLocOrErr,
*ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
}
return TemplateArgumentLoc(Arg, ToInfo);
}
template <>
Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
if (DG.isNull())
return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
size_t NumDecls = DG.end() - DG.begin();
SmallVector<Decl *, 1> ToDecls;
ToDecls.reserve(NumDecls);
for (Decl *FromD : DG) {
if (auto ToDOrErr = import(FromD))
ToDecls.push_back(*ToDOrErr);
else
return ToDOrErr.takeError();
}
return DeclGroupRef::Create(Importer.getToContext(),
ToDecls.begin(),
NumDecls);
}
template <>
Expected<ASTNodeImporter::Designator>
ASTNodeImporter::import(const Designator &D) {
if (D.isFieldDesignator()) {
IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
if (!ToDotLocOrErr)
return ToDotLocOrErr.takeError();
ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
if (!ToFieldLocOrErr)
return ToFieldLocOrErr.takeError();
return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
}
ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
if (!ToLBracketLocOrErr)
return ToLBracketLocOrErr.takeError();
ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
if (!ToRBracketLocOrErr)
return ToRBracketLocOrErr.takeError();
if (D.isArrayDesignator())
return Designator(D.getFirstExprIndex(),
*ToLBracketLocOrErr, *ToRBracketLocOrErr);
ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
if (!ToEllipsisLocOrErr)
return ToEllipsisLocOrErr.takeError();
assert(D.isArrayRangeDesignator());
return Designator(
D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
*ToRBracketLocOrErr);
}
template <>
Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
VarDecl *Var = nullptr;
if (From.capturesVariable()) {
if (auto VarOrErr = import(From.getCapturedVar()))
Var = *VarOrErr;
else
return VarOrErr.takeError();
}
auto LocationOrErr = import(From.getLocation());
if (!LocationOrErr)
return LocationOrErr.takeError();
SourceLocation EllipsisLoc;
if (From.isPackExpansion())
if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
return std::move(Err);
return LambdaCapture(
*LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
EllipsisLoc);
}
template <typename T>
bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(T *Found, T *From) {
if (Found->getLinkageInternal() != From->getLinkageInternal())
return false;
if (From->hasExternalFormalLinkage())
return Found->hasExternalFormalLinkage();
if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
return false;
if (From->isInAnonymousNamespace())
return Found->isInAnonymousNamespace();
else
return !Found->isInAnonymousNamespace() &&
!Found->hasExternalFormalLinkage();
}
template <>
bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found,
TypedefNameDecl *From) {
if (Found->getLinkageInternal() != From->getLinkageInternal())
return false;
if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
}
} // namespace clang
//----------------------------------------------------------------------------
// Import Types
//----------------------------------------------------------------------------
using namespace clang;
ExpectedType ASTNodeImporter::VisitType(const Type *T) {
Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
<< T->getTypeClassName();
return make_error<ImportError>(ImportError::UnsupportedConstruct);
}
ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
if (!UnderlyingTypeOrErr)
return UnderlyingTypeOrErr.takeError();
return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
}
ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
switch (T->getKind()) {
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
case BuiltinType::Id: \
return Importer.getToContext().SingletonId;
#include "clang/Basic/OpenCLImageTypes.def"
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
case BuiltinType::Id: \
return Importer.getToContext().Id##Ty;
#include "clang/Basic/OpenCLExtensionTypes.def"
#define SVE_TYPE(Name, Id, SingletonId) \
case BuiltinType::Id: \
return Importer.getToContext().SingletonId;
#include "clang/Basic/AArch64SVEACLETypes.def"
#define PPC_VECTOR_TYPE(Name, Id, Size) \
case BuiltinType::Id: \
return Importer.getToContext().Id##Ty;
#include "clang/Basic/PPCTypes.def"
#define SHARED_SINGLETON_TYPE(Expansion)
#define BUILTIN_TYPE(Id, SingletonId) \
case BuiltinType::Id: return Importer.getToContext().SingletonId;
#include "clang/AST/BuiltinTypes.def"
// FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
// context supports C++.
// FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
// context supports ObjC.
case BuiltinType::Char_U:
// The context we're importing from has an unsigned 'char'. If we're
// importing into a context with a signed 'char', translate to
// 'unsigned char' instead.
if (Importer.getToContext().getLangOpts().CharIsSigned)
return Importer.getToContext().UnsignedCharTy;
return Importer.getToContext().CharTy;
case BuiltinType::Char_S:
// The context we're importing from has an unsigned 'char'. If we're
// importing into a context with a signed 'char', translate to
// 'unsigned char' instead.
if (!Importer.getToContext().getLangOpts().CharIsSigned)
return Importer.getToContext().SignedCharTy;
return Importer.getToContext().CharTy;
case BuiltinType::WChar_S:
case BuiltinType::WChar_U:
// FIXME: If not in C++, shall we translate to the C equivalent of
// wchar_t?
return Importer.getToContext().WCharTy;
}
llvm_unreachable("Invalid BuiltinType Kind!");
}
ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
if (!ToOriginalTypeOrErr)
return ToOriginalTypeOrErr.takeError();
return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
}
ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
ExpectedType ToElementTypeOrErr = import(T->getElementType());
if (!ToElementTypeOrErr)
return ToElementTypeOrErr.takeError();
return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
}
ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
if (!ToPointeeTypeOrErr)
return ToPointeeTypeOrErr.takeError();
return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr,
T->getKind());
}
ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
// FIXME: Check for blocks support in "to" context.
ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
if (!ToPointeeTypeOrErr)
return ToPointeeTypeOrErr.takeError();
return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
}
ExpectedType
ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
// FIXME: Check for C++ support in "to" context.
ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
if (!ToPointeeTypeOrErr)
return ToPointeeTypeOrErr.takeError();
return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
}
ExpectedType
ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
// FIXME: Check for C++0x support in "to" context.
ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
if (!ToPointeeTypeOrErr)
return ToPointeeTypeOrErr.takeError();
return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
}
ExpectedType
ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
// FIXME: Check for C++ support in "to" context.
ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
if (!ToPointeeTypeOrErr)
return ToPointeeTypeOrErr.takeError();
ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0));
if (!ClassTypeOrErr)
return ClassTypeOrErr.takeError();
return Importer.getToContext().getMemberPointerType(
*ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr());
}
ExpectedType
ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
Error Err = Error::success();
auto ToElementType = importChecked(Err, T->getElementType());
auto ToSizeExpr = importChecked(Err, T->getSizeExpr());
if (Err)
return std::move(Err);
return Importer.getToContext().getConstantArrayType(
ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
T->getIndexTypeCVRQualifiers(), T->getKind());
}
ExpectedType
ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
ExpectedType ToElementTypeOrErr = import(T->getElementType());
if (!ToElementTypeOrErr)
return ToElementTypeOrErr.takeError();
return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
T->getSizeModifier(),
T->getIndexTypeCVRQualifiers(),
T->getKind());
}
ExpectedType
ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
Error Err = Error::success();
QualType ToElementType = importChecked(Err, T->getElementType());
Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
if (Err)
return std::move(Err);
return Importer.getToContext().getVariableArrayType(
ToElementType, ToSizeExpr, T->getSizeModifier(),
T->getIndexTypeCVRQualifiers(), ToBracketsRange);
}
ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
const DependentSizedArrayType *T) {
Error Err = Error::success();
QualType ToElementType = importChecked(Err, T->getElementType());
Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
if (Err)
return std::move(Err);
// SizeExpr may be null if size is not specified directly.
// For example, 'int a[]'.
return Importer.getToContext().getDependentSizedArrayType(
ToElementType, ToSizeExpr, T->getSizeModifier(),
T->getIndexTypeCVRQualifiers(), ToBracketsRange);
}
ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
ExpectedType ToElementTypeOrErr = import(T->getElementType());
if (!ToElementTypeOrErr)
return ToElementTypeOrErr.takeError();
return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
T->getNumElements(),
T->getVectorKind());
}
ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
ExpectedType ToElementTypeOrErr = import(T->getElementType());
if (!ToElementTypeOrErr)
return ToElementTypeOrErr.takeError();
return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
T->getNumElements());
}
ExpectedType
ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
// FIXME: What happens if we're importing a function without a prototype
// into C++? Should we make it variadic?
ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
if (!ToReturnTypeOrErr)
return ToReturnTypeOrErr.takeError();
return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
T->getExtInfo());
}
ExpectedType
ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
if (!ToReturnTypeOrErr)
return ToReturnTypeOrErr.takeError();
// Import argument types
SmallVector<QualType, 4> ArgTypes;
for (const auto &A : T->param_types()) {
ExpectedType TyOrErr = import(A);
if (!TyOrErr)
return TyOrErr.takeError();
ArgTypes.push_back(*TyOrErr);
}
// Import exception types
SmallVector<QualType, 4> ExceptionTypes;
for (const auto &E : T->exceptions()) {
ExpectedType TyOrErr = import(E);
if (!TyOrErr)
return TyOrErr.takeError();
ExceptionTypes.push_back(*TyOrErr);
}
FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
Error Err = Error::success();
FunctionProtoType::ExtProtoInfo ToEPI;
ToEPI.ExtInfo = FromEPI.ExtInfo;
ToEPI.Variadic = FromEPI.Variadic;
ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
ToEPI.TypeQuals = FromEPI.TypeQuals;
ToEPI.RefQualifier = FromEPI.RefQualifier;
ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
ToEPI.ExceptionSpec.NoexceptExpr =
importChecked(Err, FromEPI.ExceptionSpec.NoexceptExpr);
ToEPI.ExceptionSpec.SourceDecl =
importChecked(Err, FromEPI.ExceptionSpec.SourceDecl);
ToEPI.ExceptionSpec.SourceTemplate =
importChecked(Err, FromEPI.ExceptionSpec.SourceTemplate);
ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
if (Err)
return std::move(Err);
return Importer.getToContext().getFunctionType(
*ToReturnTypeOrErr, ArgTypes, ToEPI);
}
ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
const UnresolvedUsingType *T) {
Error Err = Error::success();
auto ToD = importChecked(Err, T->getDecl());
auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
if (Err)
return std::move(Err);
return Importer.getToContext().getTypeDeclType(
ToD, cast_or_null<TypeDecl>(ToPrevD));
}
ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
if (!ToInnerTypeOrErr)
return ToInnerTypeOrErr.takeError();
return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
}
ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
if (!ToDeclOrErr)
return ToDeclOrErr.takeError();
return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
}
ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
if (!ToExprOrErr)
return ToExprOrErr.takeError();
return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
}
ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
if (!ToUnderlyingTypeOrErr)
return ToUnderlyingTypeOrErr.takeError();
return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
}
ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
// FIXME: Make sure that the "to" context supports C++0x!
ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
if (!ToExprOrErr)
return ToExprOrErr.takeError();
ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
if (!ToUnderlyingTypeOrErr)
return ToUnderlyingTypeOrErr.takeError();
return Importer.getToContext().getDecltypeType(
*ToExprOrErr, *ToUnderlyingTypeOrErr);
}
ExpectedType
ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
if (!ToBaseTypeOrErr)
return ToBaseTypeOrErr.takeError();
ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
if (!ToUnderlyingTypeOrErr)
return ToUnderlyingTypeOrErr.takeError();
return Importer.getToContext().getUnaryTransformType(
*ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
}
ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
// FIXME: Make sure that the "to" context supports C++11!
ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
if (!ToDeducedTypeOrErr)
return ToDeducedTypeOrErr.takeError();
ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept());
if (!ToTypeConstraintConcept)
return ToTypeConstraintConcept.takeError();
SmallVector<TemplateArgument, 2> ToTemplateArgs;
ArrayRef<TemplateArgument> FromTemplateArgs = T->getTypeConstraintArguments();
if (Error Err = ImportTemplateArguments(FromTemplateArgs.data(),
FromTemplateArgs.size(),
ToTemplateArgs))
return std::move(Err);
return Importer.getToContext().getAutoType(
*ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false,
/*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept),
ToTemplateArgs);
}
ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
const InjectedClassNameType *T) {
Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
if (!ToDeclOrErr)
return ToDeclOrErr.takeError();
ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
if (!ToInjTypeOrErr)
return ToInjTypeOrErr.takeError();
// FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
// See comments in InjectedClassNameType definition for details
// return Importer.getToContext().getInjectedClassNameType(D, InjType);
enum {
TypeAlignmentInBits = 4,
TypeAlignment = 1 << TypeAlignmentInBits
};
return QualType(new (Importer.getToContext(), TypeAlignment)
InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
}
ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
if (!ToDeclOrErr)
return ToDeclOrErr.takeError();
return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
}
ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
if (!ToDeclOrErr)
return ToDeclOrErr.takeError();
return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
}
ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
if (!ToModifiedTypeOrErr)
return ToModifiedTypeOrErr.takeError();
ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
if (!ToEquivalentTypeOrErr)
return ToEquivalentTypeOrErr.takeError();
return Importer.getToContext().getAttributedType(T->getAttrKind(),
*ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
}
ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
const TemplateTypeParmType *T) {
Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
if (!ToDeclOrErr)
return ToDeclOrErr.takeError();
return Importer.getToContext().getTemplateTypeParmType(
T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
}
ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
const SubstTemplateTypeParmType *T) {
ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
if (!ReplacedOrErr)
return ReplacedOrErr.takeError();
const TemplateTypeParmType *Replaced =
cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr());
ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
if (!ToReplacementTypeOrErr)
return ToReplacementTypeOrErr.takeError();
return Importer.getToContext().getSubstTemplateTypeParmType(
Replaced, (*ToReplacementTypeOrErr).getCanonicalType());
}
ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
const TemplateSpecializationType *T) {
auto ToTemplateOrErr = import(T->getTemplateName());
if (!ToTemplateOrErr)
return ToTemplateOrErr.takeError();
SmallVector<TemplateArgument, 2> ToTemplateArgs;
if (Error Err = ImportTemplateArguments(
T->getArgs(), T->getNumArgs(), ToTemplateArgs))
return std::move(Err);
QualType ToCanonType;
if (!QualType(T, 0).isCanonical()) {
QualType FromCanonType
= Importer.getFromContext().getCanonicalType(QualType(T, 0));
if (ExpectedType TyOrErr = import(FromCanonType))
ToCanonType = *TyOrErr;
else
return TyOrErr.takeError();
}
return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
ToTemplateArgs,
ToCanonType);
}
ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
// Note: the qualifier in an ElaboratedType is optional.
auto ToQualifierOrErr = import(T->getQualifier());
if (!ToQualifierOrErr)
return ToQualifierOrErr.takeError();
ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
if (!ToNamedTypeOrErr)
return ToNamedTypeOrErr.takeError();
Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
if (!ToOwnedTagDeclOrErr)
return ToOwnedTagDeclOrErr.takeError();
return Importer.getToContext().getElaboratedType(T->getKeyword(),
*ToQualifierOrErr,
*ToNamedTypeOrErr,
*ToOwnedTagDeclOrErr);
}
ExpectedType
ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
ExpectedType ToPatternOrErr = import(T->getPattern());
if (!ToPatternOrErr)
return ToPatternOrErr.takeError();
return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
T->getNumExpansions(),
/*ExpactPack=*/false);
}
ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
const DependentTemplateSpecializationType *T) {
auto ToQualifierOrErr = import(T->getQualifier());
if (!ToQualifierOrErr)
return ToQualifierOrErr.takeError();
IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
SmallVector<TemplateArgument, 2> ToPack;
ToPack.reserve(T->getNumArgs());
if (Error Err = ImportTemplateArguments(
T->getArgs(), T->getNumArgs(), ToPack))
return std::move(Err);
return Importer.getToContext().getDependentTemplateSpecializationType(
T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
}
ExpectedType
ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
auto ToQualifierOrErr = import(T->getQualifier());
if (!ToQualifierOrErr)
return ToQualifierOrErr.takeError();
IdentifierInfo *Name = Importer.Import(T->getIdentifier());
QualType Canon;
if (T != T->getCanonicalTypeInternal().getTypePtr()) {
if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
Canon = (*TyOrErr).getCanonicalType();
else
return TyOrErr.takeError();
}
return Importer.getToContext().getDependentNameType(T->getKeyword(),
*ToQualifierOrErr,
Name, Canon);
}
ExpectedType
ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
if (!ToDeclOrErr)
return ToDeclOrErr.takeError();
return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
}
ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
if (!ToBaseTypeOrErr)
return ToBaseTypeOrErr.takeError();
SmallVector<QualType, 4> TypeArgs;
for (auto TypeArg : T->getTypeArgsAsWritten()) {
if (ExpectedType TyOrErr = import(TypeArg))
TypeArgs.push_back(*TyOrErr);
else
return TyOrErr.takeError();
}
SmallVector<ObjCProtocolDecl *, 4> Protocols;
for (auto *P : T->quals()) {
if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
Protocols.push_back(*ProtocolOrErr);
else
return ProtocolOrErr.takeError();
}
return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
Protocols,
T->isKindOfTypeAsWritten());
}
ExpectedType
ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
if (!ToPointeeTypeOrErr)
return ToPointeeTypeOrErr.takeError();
return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
}
//----------------------------------------------------------------------------
// Import Declarations
//----------------------------------------------------------------------------
Error ASTNodeImporter::ImportDeclParts(
NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
// Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
// example: int struct_in_proto(struct data_t{int a;int b;} *d);
// FIXME: We could support these constructs by importing a different type of
// this parameter and by importing the original type of the parameter only
// after the FunctionDecl is created. See
// VisitFunctionDecl::UsedDifferentProtoType.
DeclContext *OrigDC = D->getDeclContext();
FunctionDecl *FunDecl;
if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
FunDecl->hasBody()) {
auto getLeafPointeeType = [](const Type *T) {
while (T->isPointerType() || T->isArrayType()) {
T = T->getPointeeOrArrayElementType();
}
return T;
};
for (const ParmVarDecl *P : FunDecl->parameters()) {
const Type *LeafT =
getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
auto *RT = dyn_cast<RecordType>(LeafT);
if (RT && RT->getDecl() == D) {
Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
<< D->getDeclKindName();
return make_error<ImportError>(ImportError::UnsupportedConstruct);
}
}
}
// Import the context of this declaration.
if (Error Err = ImportDeclContext(D, DC, LexicalDC))
return Err;
// Import the name of this declaration.
if (Error Err = importInto(Name, D->getDeclName()))
return Err;
// Import the location of this declaration.
if (Error Err = importInto(Loc, D->getLocation()))
return Err;
ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
if (ToD)
if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
return Err;
return Error::success();
}
Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclarationName &Name,
NamedDecl *&ToD, SourceLocation &Loc) {
// Import the name of this declaration.
if (Error Err = importInto(Name, D->getDeclName()))
return Err;
// Import the location of this declaration.
if (Error Err = importInto(Loc, D->getLocation()))
return Err;
ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
if (ToD)
if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
return Err;
return Error::success();
}
Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
if (!FromD)
return Error::success();
if (!ToD)
if (Error Err = importInto(ToD, FromD))
return Err;
if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
!ToRecord->getDefinition()) {
if (Error Err = ImportDefinition(FromRecord, ToRecord))
return Err;
}
}
return Error::success();
}
if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
if (Error Err = ImportDefinition(FromEnum, ToEnum))
return Err;
}
}
return Error::success();
}
return Error::success();
}
Error
ASTNodeImporter::ImportDeclarationNameLoc(
const DeclarationNameInfo &From, DeclarationNameInfo& To) {
// NOTE: To.Name and To.Loc are already imported.
// We only have to import To.LocInfo.
switch (To.getName().getNameKind()) {
case DeclarationName::Identifier:
case DeclarationName::ObjCZeroArgSelector:
case DeclarationName::ObjCOneArgSelector:
case DeclarationName::ObjCMultiArgSelector:
case DeclarationName::CXXUsingDirective:
case DeclarationName::CXXDeductionGuideName:
return Error::success();
case DeclarationName::CXXOperatorName: {
if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
To.setCXXOperatorNameRange(*ToRangeOrErr);
else
return ToRangeOrErr.takeError();
return Error::success();
}
case DeclarationName::CXXLiteralOperatorName: {
if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
To.setCXXLiteralOperatorNameLoc(*LocOrErr);
else
return LocOrErr.takeError();
return Error::success();
}
case DeclarationName::CXXConstructorName:
case DeclarationName::CXXDestructorName:
case DeclarationName::CXXConversionFunctionName: {
if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
To.setNamedTypeInfo(*ToTInfoOrErr);
else
return ToTInfoOrErr.takeError();
return Error::success();
}
}
llvm_unreachable("Unknown name kind.");
}
Error
ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
if (Importer.isMinimalImport() && !ForceImport) {
auto ToDCOrErr = Importer.ImportContext(FromDC);
return ToDCOrErr.takeError();
}
// We use strict error handling in case of records and enums, but not
// with e.g. namespaces.
//
// FIXME Clients of the ASTImporter should be able to choose an
// appropriate error handling strategy for their needs. For instance,
// they may not want to mark an entire namespace as erroneous merely
// because there is an ODR error with two typedefs. As another example,
// the client may allow EnumConstantDecls with same names but with
// different values in two distinct translation units.
bool AccumulateChildErrors = isa<TagDecl>(FromDC);
Error ChildErrors = Error::success();
for (auto *From : FromDC->decls()) {
ExpectedDecl ImportedOrErr = import(From);
// If we are in the process of ImportDefinition(...) for a RecordDecl we
// want to make sure that we are also completing each FieldDecl. There
// are currently cases where this does not happen and this is correctness
// fix since operations such as code generation will expect this to be so.
if (ImportedOrErr) {
FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From);
Decl *ImportedDecl = *ImportedOrErr;
FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl);
if (FieldFrom && FieldTo) {
RecordDecl *FromRecordDecl = nullptr;
RecordDecl *ToRecordDecl = nullptr;
// If we have a field that is an ArrayType we need to check if the array
// element is a RecordDecl and if so we need to import the defintion.
if (FieldFrom->getType()->isArrayType()) {
// getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
FromRecordDecl = FieldFrom->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
ToRecordDecl = FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
}
if (!FromRecordDecl || !ToRecordDecl) {
const RecordType *RecordFrom =
FieldFrom->getType()->getAs<RecordType>();
const RecordType *RecordTo = FieldTo->getType()->getAs<RecordType>();
if (RecordFrom && RecordTo) {
FromRecordDecl = RecordFrom->getDecl();
ToRecordDecl = RecordTo->getDecl();
}
}
if (FromRecordDecl && ToRecordDecl) {
if (FromRecordDecl->isCompleteDefinition() &&
!ToRecordDecl->isCompleteDefinition()) {
Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl);
if (Err && AccumulateChildErrors)
ChildErrors = joinErrors(std::move(ChildErrors), std::move(Err));
else
consumeError(std::move(Err));
}
}
}
} else {
if (AccumulateChildErrors)
ChildErrors =
joinErrors(std::move(ChildErrors), ImportedOrErr.takeError());
else
consumeError(ImportedOrErr.takeError());
}
}
// We reorder declarations in RecordDecls because they may have another order
// in the "to" context than they have in the "from" context. This may happen
// e.g when we import a class like this:
// struct declToImport {
// int a = c + b;
// int b = 1;
// int c = 2;
// };
// During the import of `a` we import first the dependencies in sequence,
// thus the order would be `c`, `b`, `a`. We will get the normal order by
// first removing the already imported members and then adding them in the
// order as they apper in the "from" context.
//
// Keeping field order is vital because it determines structure layout.
//
// Here and below, we cannot call field_begin() method and its callers on
// ToDC if it has an external storage. Calling field_begin() will
// automatically load all the fields by calling
// LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
// call ASTImporter::Import(). This is because the ExternalASTSource
// interface in LLDB is implemented by the means of the ASTImporter. However,
// calling an import at this point would result in an uncontrolled import, we
// must avoid that.
const auto *FromRD = dyn_cast<RecordDecl>(FromDC);
if (!FromRD)
return ChildErrors;
auto ToDCOrErr = Importer.ImportContext(FromDC);
if (!ToDCOrErr) {
consumeError(std::move(ChildErrors));
return ToDCOrErr.takeError();
}
DeclContext *ToDC = *ToDCOrErr;
// Remove all declarations, which may be in wrong order in the
// lexical DeclContext and then add them in the proper order.
for (auto *D : FromRD->decls()) {
if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) {
assert(D && "DC contains a null decl");
Decl *ToD = Importer.GetAlreadyImportedOrNull(D);
// Remove only the decls which we successfully imported.
if (ToD) {
assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
// Remove the decl from its wrong place in the linked list.
ToDC->removeDecl(ToD);
// Add the decl to the end of the linked list.
// This time it will be at the proper place because the enclosing for
// loop iterates in the original (good) order of the decls.
ToDC->addDeclInternal(ToD);
}
}
}
return ChildErrors;
}
Error ASTNodeImporter::ImportDeclContext(
Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
if (!ToDCOrErr)
return ToDCOrErr.takeError();
ToDC = *ToDCOrErr;
if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
auto ToLexicalDCOrErr = Importer.ImportContext(
FromD->getLexicalDeclContext());
if (!ToLexicalDCOrErr)
return ToLexicalDCOrErr.takeError();
ToLexicalDC = *ToLexicalDCOrErr;
} else
ToLexicalDC = ToDC;
return Error::success();
}
Error ASTNodeImporter::ImportImplicitMethods(
const CXXRecordDecl *From, CXXRecordDecl *To) {
assert(From->isCompleteDefinition() && To->getDefinition() == To &&
"Import implicit methods to or from non-definition");
for (CXXMethodDecl *FromM : From->methods())
if (FromM->isImplicit()) {
Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
if (!ToMOrErr)
return ToMOrErr.takeError();
}
return Error::success();
}
static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
ASTImporter &Importer) {
if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
else
return ToTypedefOrErr.takeError();
}
return Error::success();
}
Error ASTNodeImporter::ImportDefinition(
RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
auto DefinitionCompleter = [To]() {
// There are cases in LLDB when we first import a class without its
// members. The class will have DefinitionData, but no members. Then,
// importDefinition is called from LLDB, which tries to get the members, so
// when we get here, the class already has the DefinitionData set, so we
// must unset the CompleteDefinition here to be able to complete again the
// definition.
To->setCompleteDefinition(false);
To->completeDefinition();
};
if (To->getDefinition() || To->isBeingDefined()) {
if (Kind == IDK_Everything ||
// In case of lambdas, the class already has a definition ptr set, but
// the contained decls are not imported yet. Also, isBeingDefined was
// set in CXXRecordDecl::CreateLambda. We must import the contained
// decls here and finish the definition.
(To->isLambda() && shouldForceImportDeclContext(Kind))) {
if (To->isLambda()) {
auto *FromCXXRD = cast<CXXRecordDecl>(From);
SmallVector<LambdaCapture, 8> ToCaptures;
ToCaptures.reserve(FromCXXRD->capture_size());
for (const auto &FromCapture : FromCXXRD->captures()) {
if (auto ToCaptureOrErr = import(FromCapture))
ToCaptures.push_back(*ToCaptureOrErr);
else
return ToCaptureOrErr.takeError();
}
cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(),
ToCaptures);
}
Error Result = ImportDeclContext(From, /*ForceImport=*/true);
// Finish the definition of the lambda, set isBeingDefined to false.
if (To->isLambda())
DefinitionCompleter();
return Result;
}
return Error::success();
}
To->startDefinition();
// Complete the definition even if error is returned.
// The RecordDecl may be already part of the AST so it is better to
// have it in complete state even if something is wrong with it.
auto DefinitionCompleterScopeExit =
llvm::make_scope_exit(DefinitionCompleter);
if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
return Err;
// Add base classes.
auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
#define FIELD(Name, Width, Merge) \
ToData.Name = FromData.Name;
#include "clang/AST/CXXRecordDeclDefinitionBits.def"
// Copy over the data stored in RecordDeclBits
ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
SmallVector<CXXBaseSpecifier *, 4> Bases;
for (const auto &Base1 : FromCXX->bases()) {
ExpectedType TyOrErr = import(Base1.getType());
if (!TyOrErr)
return TyOrErr.takeError();
SourceLocation EllipsisLoc;
if (Base1.isPackExpansion()) {
if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
EllipsisLoc = *LocOrErr;
else
return LocOrErr.takeError();
}
// Ensure that we have a definition for the base.
if (Error Err =
ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
return Err;
auto RangeOrErr = import(Base1.getSourceRange());
if (!RangeOrErr)
return RangeOrErr.takeError();
auto TSIOrErr = import(Base1.getTypeSourceInfo());
if (!TSIOrErr)
return TSIOrErr.takeError();
Bases.push_back(
new (Importer.getToContext()) CXXBaseSpecifier(
*RangeOrErr,
Base1.isVirtual(),
Base1.isBaseOfClass(),
Base1.getAccessSpecifierAsWritten(),
*TSIOrErr,
EllipsisLoc));
}
if (!Bases.empty())
ToCXX->setBases(Bases.data(), Bases.size());
}
if (shouldForceImportDeclContext(Kind))
if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
return Err;
return Error::success();
}
Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) {
if (To->getAnyInitializer())
return Error::success();
Expr *FromInit = From->getInit();
if (!FromInit)
return Error::success();
ExpectedExpr ToInitOrErr = import(FromInit);
if (!ToInitOrErr)
return ToInitOrErr.takeError();
To->setInit(*ToInitOrErr);
if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
// FIXME: Also import the initializer value.
}
// FIXME: Other bits to merge?
return Error::success();
}
Error ASTNodeImporter::ImportDefinition(
EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
if (To->getDefinition() || To->isBeingDefined()) {
if (Kind == IDK_Everything)
return ImportDeclContext(From, /*ForceImport=*/true);
return Error::success();
}
To->startDefinition();
if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
return Err;
ExpectedType ToTypeOrErr =
import(Importer.getFromContext().getTypeDeclType(From));
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
if (!ToPromotionTypeOrErr)
return ToPromotionTypeOrErr.takeError();
if (shouldForceImportDeclContext(Kind))
if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
return Err;
// FIXME: we might need to merge the number of positive or negative bits
// if the enumerator lists don't match.
To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
From->getNumPositiveBits(),
From->getNumNegativeBits());
return Error::success();
}
Error ASTNodeImporter::ImportTemplateArguments(
const TemplateArgument *FromArgs, unsigned NumFromArgs,
SmallVectorImpl<TemplateArgument> &ToArgs) {
for (unsigned I = 0; I != NumFromArgs; ++I) {
if (auto ToOrErr = import(FromArgs[I]))
ToArgs.push_back(*ToOrErr);
else
return ToOrErr.takeError();
}
return Error::success();
}
// FIXME: Do not forget to remove this and use only 'import'.
Expected<TemplateArgument>
ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
return import(From);
}
template <typename InContainerTy>
Error ASTNodeImporter::ImportTemplateArgumentListInfo(
const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
for (const auto &FromLoc : Container) {
if (auto ToLocOrErr = import(FromLoc))
ToTAInfo.addArgument(*ToLocOrErr);
else
return ToLocOrErr.takeError();
}
return Error::success();
}
static StructuralEquivalenceKind
getStructuralEquivalenceKind(const ASTImporter &Importer) {
return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
: StructuralEquivalenceKind::Default;
}
bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
StructuralEquivalenceContext Ctx(
Importer.getFromContext(), Importer.getToContext(),
Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
false, Complain);
return Ctx.IsEquivalent(From, To);
}
bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
RecordDecl *ToRecord, bool Complain) {
// Eliminate a potential failure point where we attempt to re-import
// something we're trying to import while completing ToRecord.
Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
if (ToOrigin) {
auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
if (ToOriginRecord)
ToRecord = ToOriginRecord;
}
StructuralEquivalenceContext Ctx(Importer.getFromContext(),
ToRecord->getASTContext(),
Importer.getNonEquivalentDecls(),
getStructuralEquivalenceKind(Importer),
false, Complain);
return Ctx.IsEquivalent(FromRecord, ToRecord);
}
bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
bool Complain) {
StructuralEquivalenceContext Ctx(
Importer.getFromContext(), Importer.getToContext(),
Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
false, Complain);
return Ctx.IsEquivalent(FromVar, ToVar);
}
bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
// Eliminate a potential failure point where we attempt to re-import
// something we're trying to import while completing ToEnum.
if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum))
if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin))
ToEnum = ToOriginEnum;
StructuralEquivalenceContext Ctx(
Importer.getFromContext(), Importer.getToContext(),
Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
return Ctx.IsEquivalent(FromEnum, ToEnum);
}
bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From,
FunctionTemplateDecl *To) {
StructuralEquivalenceContext Ctx(
Importer.getFromContext(), Importer.getToContext(),
Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
false, false);
return Ctx.IsEquivalent(From, To);
}
bool ASTNodeImporter::IsStructuralMatch(FunctionDecl *From, FunctionDecl *To) {
StructuralEquivalenceContext Ctx(
Importer.getFromContext(), Importer.getToContext(),
Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
false, false);
return Ctx.IsEquivalent(From, To);
}
bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
EnumConstantDecl *ToEC) {
const llvm::APSInt &FromVal = FromEC->getInitVal();
const llvm::APSInt &ToVal = ToEC->getInitVal();
return FromVal.isSigned() == ToVal.isSigned() &&
FromVal.getBitWidth() == ToVal.getBitWidth() &&
FromVal == ToVal;
}
bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
ClassTemplateDecl *To) {
StructuralEquivalenceContext Ctx(Importer.getFromContext(),
Importer.getToContext(),
Importer.getNonEquivalentDecls(),
getStructuralEquivalenceKind(Importer));
return Ctx.IsEquivalent(From, To);
}
bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
VarTemplateDecl *To) {
StructuralEquivalenceContext Ctx(Importer.getFromContext(),
Importer.getToContext(),
Importer.getNonEquivalentDecls(),
getStructuralEquivalenceKind(Importer));
return Ctx.IsEquivalent(From, To);
}
ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) {
Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
<< D->getDeclKindName();
return make_error<ImportError>(ImportError::UnsupportedConstruct);
}
ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) {
Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
<< D->getDeclKindName();
return make_error<ImportError>(ImportError::UnsupportedConstruct);
}
ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
// Import the context of this declaration.
DeclContext *DC, *LexicalDC;
if (Error Err = ImportDeclContext(D, DC, LexicalDC))
return std::move(Err);
// Import the location of this declaration.
ExpectedSLoc LocOrErr = import(D->getLocation());
if (!LocOrErr)
return LocOrErr.takeError();
EmptyDecl *ToD;
if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
return ToD;
ToD->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToD);
return ToD;
}
ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
TranslationUnitDecl *ToD =
Importer.getToContext().getTranslationUnitDecl();
Importer.MapImported(D, ToD);
return ToD;
}
ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
ExpectedSLoc LocOrErr = import(D->getLocation());
if (!LocOrErr)
return LocOrErr.takeError();
auto ColonLocOrErr = import(D->getColonLoc());
if (!ColonLocOrErr)
return ColonLocOrErr.takeError();
// Import the context of this declaration.
auto DCOrErr = Importer.ImportContext(D->getDeclContext());
if (!DCOrErr)
return DCOrErr.takeError();
DeclContext *DC = *DCOrErr;
AccessSpecDecl *ToD;
if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
DC, *LocOrErr, *ColonLocOrErr))
return ToD;
// Lexical DeclContext and Semantic DeclContext
// is always the same for the accessSpec.
ToD->setLexicalDeclContext(DC);
DC->addDeclInternal(ToD);
return ToD;
}
ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
auto DCOrErr = Importer.ImportContext(D->getDeclContext());
if (!DCOrErr)
return DCOrErr.takeError();
DeclContext *DC = *DCOrErr;
DeclContext *LexicalDC = DC;
Error Err = Error::success();
auto ToLocation = importChecked(Err, D->getLocation());
auto ToRParenLoc = importChecked(Err, D->getRParenLoc());
auto ToAssertExpr = importChecked(Err, D->getAssertExpr());
auto ToMessage = importChecked(Err, D->getMessage());
if (Err)
return std::move(Err);
StaticAssertDecl *ToD;
if (GetImportedOrCreateDecl(
ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
ToRParenLoc, D->isFailed()))
return ToD;
ToD->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToD);
return ToD;
}
ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
// Import the major distinguishing characteristics of this namespace.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
NamespaceDecl *MergeWithNamespace = nullptr;
if (!Name) {
// This is an anonymous namespace. Adopt an existing anonymous
// namespace if we can.
// FIXME: Not testable.
if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
MergeWithNamespace = TU->getAnonymousNamespace();
else
MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
} else {
SmallVector<NamedDecl *, 4> ConflictingDecls;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace))
continue;
if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
MergeWithNamespace = FoundNS;
ConflictingDecls.clear();
break;
}
ConflictingDecls.push_back(FoundDecl);
}
if (!ConflictingDecls.empty()) {
ExpectedName NameOrErr = Importer.HandleNameConflict(
Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
ConflictingDecls.size());
if (NameOrErr)
Name = NameOrErr.get();
else
return NameOrErr.takeError();
}
}
ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
if (!BeginLocOrErr)
return BeginLocOrErr.takeError();
ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
if (!RBraceLocOrErr)
return RBraceLocOrErr.takeError();
// Create the "to" namespace, if needed.
NamespaceDecl *ToNamespace = MergeWithNamespace;
if (!ToNamespace) {
if (GetImportedOrCreateDecl(
ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
*BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
/*PrevDecl=*/nullptr))
return ToNamespace;
ToNamespace->setRBraceLoc(*RBraceLocOrErr);
ToNamespace->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToNamespace);
// If this is an anonymous namespace, register it as the anonymous
// namespace within its context.
if (!Name) {
if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
TU->setAnonymousNamespace(ToNamespace);
else
cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
}
}
Importer.MapImported(D, ToNamespace);
if (Error Err = ImportDeclContext(D))
return std::move(Err);
return ToNamespace;
}
ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
// Import the major distinguishing characteristics of this namespace.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *LookupD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
return std::move(Err);
if (LookupD)
return LookupD;
// NOTE: No conflict resolution is done for namespace aliases now.
Error Err = Error::success();
auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc());
auto ToAliasLoc = importChecked(Err, D->getAliasLoc());
auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc());
auto ToNamespace = importChecked(Err, D->getNamespace());
if (Err)
return std::move(Err);
IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
NamespaceAliasDecl *ToD;
if (GetImportedOrCreateDecl(
ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
return ToD;
ToD->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToD);
return ToD;
}
ExpectedDecl
ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
// Import the major distinguishing characteristics of this typedef.
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
// Do not import the DeclContext, we will import it once the TypedefNameDecl
// is created.
if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
DeclContext *DC = cast_or_null<DeclContext>(
Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext())));
DeclContext *LexicalDC =
cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
cast<Decl>(D->getLexicalDeclContext())));
// If this typedef is not in block scope, determine whether we've
// seen a typedef with the same name (that we can merge with) or any
// other entity by that name (which name lookup could conflict with).
// Note: Repeated typedefs are not valid in C99:
// 'typedef int T; typedef int T;' is invalid
// We do not care about this now.
if (DC && !DC->isFunctionOrMethod()) {
SmallVector<NamedDecl *, 4> ConflictingDecls;
unsigned IDNS = Decl::IDNS_Ordinary;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(IDNS))
continue;
if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
continue;
QualType FromUT = D->getUnderlyingType();
QualType FoundUT = FoundTypedef->getUnderlyingType();
if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
// If the "From" context has a complete underlying type but we
// already have a complete underlying type then return with that.
if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
return Importer.MapImported(D, FoundTypedef);
// FIXME Handle redecl chain. When you do that make consistent changes
// in ASTImporterLookupTable too.
} else {
ConflictingDecls.push_back(FoundDecl);
}
}
}
if (!ConflictingDecls.empty()) {
ExpectedName NameOrErr = Importer.HandleNameConflict(
Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
if (NameOrErr)
Name = NameOrErr.get();
else
return NameOrErr.takeError();
}
}
Error Err = Error::success();
auto ToUnderlyingType = importChecked(Err, D->getUnderlyingType());
auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
if (Err)
return std::move(Err);
// Create the new typedef node.
// FIXME: ToUnderlyingType is not used.
(void)ToUnderlyingType;
TypedefNameDecl *ToTypedef;
if (IsAlias) {
if (GetImportedOrCreateDecl<TypeAliasDecl>(
ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
Name.getAsIdentifierInfo(), ToTypeSourceInfo))
return ToTypedef;
} else if (GetImportedOrCreateDecl<TypedefDecl>(
ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
Name.getAsIdentifierInfo(), ToTypeSourceInfo))
return ToTypedef;
// Import the DeclContext and set it to the Typedef.
if ((Err = ImportDeclContext(D, DC, LexicalDC)))
return std::move(Err);
ToTypedef->setDeclContext(DC);
ToTypedef->setLexicalDeclContext(LexicalDC);
// Add to the lookupTable because we could not do that in MapImported.
Importer.AddToLookupTable(ToTypedef);
ToTypedef->setAccess(D->getAccess());
// Templated declarations should not appear in DeclContext.
TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
LexicalDC->addDeclInternal(ToTypedef);
return ToTypedef;
}
ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
return VisitTypedefNameDecl(D, /*IsAlias=*/false);
}
ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
return VisitTypedefNameDecl(D, /*IsAlias=*/true);
}
ExpectedDecl
ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
// Import the major distinguishing characteristics of this typedef.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *FoundD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
return std::move(Err);
if (FoundD)
return FoundD;
// If this typedef is not in block scope, determine whether we've
// seen a typedef with the same name (that we can merge with) or any
// other entity by that name (which name lookup could conflict with).
if (!DC->isFunctionOrMethod()) {
SmallVector<NamedDecl *, 4> ConflictingDecls;
unsigned IDNS = Decl::IDNS_Ordinary;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(IDNS))
continue;
if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
return Importer.MapImported(D, FoundAlias);
ConflictingDecls.push_back(FoundDecl);
}
if (!ConflictingDecls.empty()) {
ExpectedName NameOrErr = Importer.HandleNameConflict(
Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
if (NameOrErr)
Name = NameOrErr.get();
else
return NameOrErr.takeError();
}
}
Error Err = Error::success();
auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl());
if (Err)
return std::move(Err);
TypeAliasTemplateDecl *ToAlias;
if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
Name, ToTemplateParameters, ToTemplatedDecl))
return ToAlias;
ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
ToAlias->setAccess(D->getAccess());
ToAlias->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToAlias);
return ToAlias;
}
ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
// Import the major distinguishing characteristics of this label.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
assert(LexicalDC->isFunctionOrMethod());
LabelDecl *ToLabel;
if (D->isGnuLocal()) {
ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
if (!BeginLocOrErr)
return BeginLocOrErr.takeError();
if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
Name.getAsIdentifierInfo(), *BeginLocOrErr))
return ToLabel;
} else {
if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
Name.getAsIdentifierInfo()))
return ToLabel;
}
Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
if (!ToStmtOrErr)
return ToStmtOrErr.takeError();
ToLabel->setStmt(*ToStmtOrErr);
ToLabel->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToLabel);
return ToLabel;
}
ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
// Import the major distinguishing characteristics of this enum.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
// Figure out what enum name we're looking for.
unsigned IDNS = Decl::IDNS_Tag;
DeclarationName SearchName = Name;
if (!SearchName && D->getTypedefNameForAnonDecl()) {
if (Error Err = importInto(
SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
return std::move(Err);
IDNS = Decl::IDNS_Ordinary;
} else if (Importer.getToContext().getLangOpts().CPlusPlus)
IDNS |= Decl::IDNS_Ordinary;
// We may already have an enum of the same name; try to find and match it.
EnumDecl *PrevDecl = nullptr;
if (!DC->isFunctionOrMethod() && SearchName) {
SmallVector<NamedDecl *, 4> ConflictingDecls;
auto FoundDecls =
Importer.findDeclsInToCtx(DC, SearchName);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(IDNS))
continue;
if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
FoundDecl = Tag->getDecl();
}
if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
if (!hasSameVisibilityContextAndLinkage(FoundEnum, D))
continue;
if (IsStructuralMatch(D, FoundEnum)) {
EnumDecl *FoundDef = FoundEnum->getDefinition();
if (D->isThisDeclarationADefinition() && FoundDef)
return Importer.MapImported(D, FoundDef);
PrevDecl = FoundEnum->getMostRecentDecl();
break;
}
ConflictingDecls.push_back(FoundDecl);
}
}
if (!ConflictingDecls.empty()) {
ExpectedName NameOrErr = Importer.HandleNameConflict(
SearchName, DC, IDNS, ConflictingDecls.data(),
ConflictingDecls.size());
if (NameOrErr)
Name = NameOrErr.get();
else
return NameOrErr.takeError();
}
}
Error Err = Error::success();
auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
auto ToIntegerType = importChecked(Err, D->getIntegerType());
auto ToBraceRange = importChecked(Err, D->getBraceRange());
if (Err)
return std::move(Err);
// Create the enum declaration.
EnumDecl *D2;
if (GetImportedOrCreateDecl(
D2, D, Importer.getToContext(), DC, ToBeginLoc,
Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
D->isScopedUsingClassTag(), D->isFixed()))
return D2;
D2->setQualifierInfo(ToQualifierLoc);
D2->setIntegerType(ToIntegerType);
D2->setBraceRange(ToBraceRange);
D2->setAccess(D->getAccess());
D2->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(D2);
// Import the definition
if (D->isCompleteDefinition())
if (Error Err = ImportDefinition(D, D2))
return std::move(Err);
return D2;
}
ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
bool IsFriendTemplate = false;
if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
IsFriendTemplate =
DCXX->getDescribedClassTemplate() &&
DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
Decl::FOK_None;
}
// Import the major distinguishing characteristics of this record.
DeclContext *DC = nullptr, *LexicalDC = nullptr;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD = nullptr;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
// Figure out what structure name we're looking for.
unsigned IDNS = Decl::IDNS_Tag;
DeclarationName SearchName = Name;
if (!SearchName && D->getTypedefNameForAnonDecl()) {
if (Error Err = importInto(
SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
return std::move(Err);
IDNS = Decl::IDNS_Ordinary;
} else if (Importer.getToContext().getLangOpts().CPlusPlus)
IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
// We may already have a record of the same name; try to find and match it.
RecordDecl *PrevDecl = nullptr;
if (!DC->isFunctionOrMethod() && !D->isLambda()) {
SmallVector<NamedDecl *, 4> ConflictingDecls;
auto FoundDecls =
Importer.findDeclsInToCtx(DC, SearchName);
if (!FoundDecls.empty()) {
// We're going to have to compare D against potentially conflicting Decls,
// so complete it.
if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
D->getASTContext().getExternalSource()->CompleteType(D);
}
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(IDNS))
continue;
Decl *Found = FoundDecl;
if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
Found = Tag->getDecl();
}
if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
// Do not emit false positive diagnostic in case of unnamed
// struct/union and in case of anonymous structs. Would be false
// because there may be several anonymous/unnamed structs in a class.
// E.g. these are both valid:
// struct A { // unnamed structs
// struct { struct A *next; } entry0;
// struct { struct A *next; } entry1;
// };
// struct X { struct { int a; }; struct { int b; }; }; // anon structs
if (!SearchName)
if (!IsStructuralMatch(D, FoundRecord, false))
continue;
if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
continue;
if (IsStructuralMatch(D, FoundRecord)) {
RecordDecl *FoundDef = FoundRecord->getDefinition();
if (D->isThisDeclarationADefinition() && FoundDef) {
// FIXME: Structural equivalence check should check for same
// user-defined methods.
Importer.MapImported(D, FoundDef);
if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
assert(FoundCXX && "Record type mismatch");
if (!Importer.isMinimalImport())
// FoundDef may not have every implicit method that D has
// because implicit methods are created only if they are used.
if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
return std::move(Err);
}
}
PrevDecl = FoundRecord->getMostRecentDecl();
break;
}
ConflictingDecls.push_back(FoundDecl);
} // kind is RecordDecl
} // for
if (!ConflictingDecls.empty() && SearchName) {
ExpectedName NameOrErr = Importer.HandleNameConflict(
SearchName, DC, IDNS, ConflictingDecls.data(),
ConflictingDecls.size());
if (NameOrErr)
Name = NameOrErr.get();
else
return NameOrErr.takeError();
}
}
ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
if (!BeginLocOrErr)
return BeginLocOrErr.takeError();
// Create the record declaration.
RecordDecl *D2 = nullptr;
CXXRecordDecl *D2CXX = nullptr;
if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
if (DCXX->isLambda()) {
auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
if (!TInfoOrErr)
return TInfoOrErr.takeError();
if (GetImportedOrCreateSpecialDecl(
D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(),
DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
return D2CXX;
ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
if (!CDeclOrErr)
return CDeclOrErr.takeError();
D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr,
DCXX->hasKnownLambdaInternalLinkage());
} else if (DCXX->isInjectedClassName()) {
// We have to be careful to do a similar dance to the one in
// Sema::ActOnStartCXXMemberDeclarations
const bool DelayTypeCreation = true;
if (GetImportedOrCreateDecl(
D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
*BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
return D2CXX;
Importer.getToContext().getTypeDeclType(
D2CXX, dyn_cast<CXXRecordDecl>(DC));
} else {
if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
D->getTagKind(), DC, *BeginLocOrErr, Loc,
Name.getAsIdentifierInfo(),
cast_or_null<CXXRecordDecl>(PrevDecl)))
return D2CXX;
}
D2 = D2CXX;
D2->setAccess(D->getAccess());
D2->setLexicalDeclContext(LexicalDC);
addDeclToContexts(D, D2);
if (ClassTemplateDecl *FromDescribed =
DCXX->getDescribedClassTemplate()) {
ClassTemplateDecl *ToDescribed;
if (Error Err = importInto(ToDescribed, FromDescribed))
return std::move(Err);
D2CXX->setDescribedClassTemplate(ToDescribed);
if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
// In a record describing a template the type should be an
// InjectedClassNameType (see Sema::CheckClassTemplate). Update the
// previously set type to the correct value here (ToDescribed is not
// available at record create).
// FIXME: The previous type is cleared but not removed from
// ASTContext's internal storage.
CXXRecordDecl *Injected = nullptr;
for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
auto *Record = dyn_cast<CXXRecordDecl>(Found);
if (Record && Record->isInjectedClassName()) {
Injected = Record;
break;
}
}
// Create an injected type for the whole redecl chain.
SmallVector<Decl *, 2> Redecls =
getCanonicalForwardRedeclChain(D2CXX);
for (auto *R : Redecls) {
auto *RI = cast<CXXRecordDecl>(R);
RI->setTypeForDecl(nullptr);
// Below we create a new injected type and assign that to the
// canonical decl, subsequent declarations in the chain will reuse
// that type.
Importer.getToContext().getInjectedClassNameType(
RI, ToDescribed->getInjectedClassNameSpecialization());
}
// Set the new type for the previous injected decl too.
if (Injected) {
Injected->setTypeForDecl(nullptr);
Importer.getToContext().getTypeDeclType(Injected, D2CXX);
}
}
} else if (MemberSpecializationInfo *MemberInfo =
DCXX->getMemberSpecializationInfo()) {
TemplateSpecializationKind SK =
MemberInfo->getTemplateSpecializationKind();
CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
else
return ToInstOrErr.takeError();
if (ExpectedSLoc POIOrErr =
import(MemberInfo->getPointOfInstantiation()))
D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
*POIOrErr);
else
return POIOrErr.takeError();
}
} else {
if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
D->getTagKind(), DC, *BeginLocOrErr, Loc,
Name.getAsIdentifierInfo(), PrevDecl))
return D2;
D2->setLexicalDeclContext(LexicalDC);
addDeclToContexts(D, D2);
}
if (auto BraceRangeOrErr = import(D->getBraceRange()))
D2->setBraceRange(*BraceRangeOrErr);
else
return BraceRangeOrErr.takeError();
if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
D2->setQualifierInfo(*QualifierLocOrErr);
else
return QualifierLocOrErr.takeError();
if (D->isAnonymousStructOrUnion())
D2->setAnonymousStructOrUnion(true);
if (D->isCompleteDefinition())
if (Error Err = ImportDefinition(D, D2, IDK_Default))
return std::move(Err);
return D2;
}
ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
// Import the major distinguishing characteristics of this enumerator.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
// Determine whether there are any other declarations with the same name and
// in the same context.
if (!LexicalDC->isFunctionOrMethod()) {
SmallVector<NamedDecl *, 4> ConflictingDecls;
unsigned IDNS = Decl::IDNS_Ordinary;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(IDNS))
continue;
if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
if (IsStructuralMatch(D, FoundEnumConstant))
return Importer.MapImported(D, FoundEnumConstant);
ConflictingDecls.push_back(FoundDecl);
}
}
if (!ConflictingDecls.empty()) {
ExpectedName NameOrErr = Importer.HandleNameConflict(
Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
if (NameOrErr)
Name = NameOrErr.get();
else
return NameOrErr.takeError();
}
}
ExpectedType TypeOrErr = import(D->getType());
if (!TypeOrErr)
return TypeOrErr.takeError();
ExpectedExpr InitOrErr = import(D->getInitExpr());
if (!InitOrErr)
return InitOrErr.takeError();
EnumConstantDecl *ToEnumerator;
if (GetImportedOrCreateDecl(
ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
return ToEnumerator;
ToEnumerator->setAccess(D->getAccess());
ToEnumerator->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToEnumerator);
return ToEnumerator;
}
Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD,
DeclaratorDecl *ToD) {
unsigned int Num = FromD->getNumTemplateParameterLists();
if (Num == 0)
return Error::success();
SmallVector<TemplateParameterList *, 2> ToTPLists(Num);
for (unsigned int I = 0; I < Num; ++I)
if (Expected<TemplateParameterList *> ToTPListOrErr =
import(FromD->getTemplateParameterList(I)))
ToTPLists[I] = *ToTPListOrErr;
else
return ToTPListOrErr.takeError();
ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
return Error::success();
}
Error ASTNodeImporter::ImportTemplateInformation(
FunctionDecl *FromFD, FunctionDecl *ToFD) {
switch (FromFD->getTemplatedKind()) {
case FunctionDecl::TK_NonTemplate:
case FunctionDecl::TK_FunctionTemplate:
return Error::success();
case FunctionDecl::TK_MemberSpecialization: {
TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
if (Expected<FunctionDecl *> InstFDOrErr =
import(FromFD->getInstantiatedFromMemberFunction()))
ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
else
return InstFDOrErr.takeError();
if (ExpectedSLoc POIOrErr = import(
FromFD->getMemberSpecializationInfo()->getPointOfInstantiation()))
ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
else
return POIOrErr.takeError();
return Error::success();
}
case FunctionDecl::TK_FunctionTemplateSpecialization: {
auto FunctionAndArgsOrErr =
ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
if (!FunctionAndArgsOrErr)
return FunctionAndArgsOrErr.takeError();
TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
TemplateArgumentListInfo ToTAInfo;
const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
if (FromTAArgsAsWritten)
if (Error Err = ImportTemplateArgumentListInfo(
*FromTAArgsAsWritten, ToTAInfo))
return Err;
ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
if (!POIOrErr)
return POIOrErr.takeError();
if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
return Err;
TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
ToFD->setFunctionTemplateSpecialization(
std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
return Error::success();
}
case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
auto *FromInfo = FromFD->getDependentSpecializationInfo();
UnresolvedSet<8> TemplDecls;
unsigned NumTemplates = FromInfo->getNumTemplates();
for (unsigned I = 0; I < NumTemplates; I++) {
if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
import(FromInfo->getTemplate(I)))
TemplDecls.addDecl(*ToFTDOrErr);
else
return ToFTDOrErr.takeError();
}
// Import TemplateArgumentListInfo.
TemplateArgumentListInfo ToTAInfo;
if (Error Err = ImportTemplateArgumentListInfo(
FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
llvm::makeArrayRef(
FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
ToTAInfo))
return Err;
ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
TemplDecls, ToTAInfo);
return Error::success();
}
}
llvm_unreachable("All cases should be covered!");
}
Expected<FunctionDecl *>
ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
auto FunctionAndArgsOrErr =
ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
if (!FunctionAndArgsOrErr)
return FunctionAndArgsOrErr.takeError();
FunctionTemplateDecl *Template;
TemplateArgsTy ToTemplArgs;
std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
void *InsertPos = nullptr;
auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
return FoundSpec;
}
Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD,
FunctionDecl *ToFD) {
if (Stmt *FromBody = FromFD->getBody()) {
if (ExpectedStmt ToBodyOrErr = import(FromBody))
ToFD->setBody(*ToBodyOrErr);
else
return ToBodyOrErr.takeError();
}
return Error::success();
}
// Returns true if the given D has a DeclContext up to the TranslationUnitDecl
// which is equal to the given DC.
static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
const DeclContext *DCi = D->getDeclContext();
while (DCi != D->getTranslationUnitDecl()) {
if (DCi == DC)
return true;
DCi = DCi->getParent();
}
return false;
}
bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
QualType FromTy = D->getType();
const FunctionProtoType *FromFPT = FromTy->getAs<FunctionProtoType>();
assert(FromFPT && "Must be called on FunctionProtoType");
if (AutoType *AutoT = FromFPT->getReturnType()->getContainedAutoType()) {
QualType DeducedT = AutoT->getDeducedType();
if (const RecordType *RecordT =
DeducedT.isNull() ? nullptr : dyn_cast<RecordType>(DeducedT)) {
RecordDecl *RD = RecordT->getDecl();
assert(RD);
if (isAncestorDeclContextOf(D, RD)) {
assert(RD->getLexicalDeclContext() == RD->getDeclContext());
return true;
}
}
}
if (const TypedefType *TypedefT =
dyn_cast<TypedefType>(FromFPT->getReturnType())) {
TypedefNameDecl *TD = TypedefT->getDecl();
assert(TD);
if (isAncestorDeclContextOf(D, TD)) {
assert(TD->getLexicalDeclContext() == TD->getDeclContext());
return true;
}
}
return false;
}
ExplicitSpecifier
ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
Expr *ExplicitExpr = ESpec.getExpr();
if (ExplicitExpr)
ExplicitExpr = importChecked(Err, ESpec.getExpr());
return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
}
ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
auto RedeclIt = Redecls.begin();
// Import the first part of the decl chain. I.e. import all previous
// declarations starting from the canonical decl.
for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
if (!ToRedeclOrErr)
return ToRedeclOrErr.takeError();
}
assert(*RedeclIt == D);
// Import the major distinguishing characteristics of this function.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
FunctionDecl *FoundByLookup = nullptr;
FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
// If this is a function template specialization, then try to find the same
// existing specialization in the "to" context. The lookup below will not
// find any specialization, but would find the primary template; thus, we
// have to skip normal lookup in case of specializations.
// FIXME handle member function templates (TK_MemberSpecialization) similarly?
if (D->getTemplatedKind() ==
FunctionDecl::TK_FunctionTemplateSpecialization) {
auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
if (!FoundFunctionOrErr)
return FoundFunctionOrErr.takeError();
if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
return Def;
FoundByLookup = FoundFunction;
}
}
// Try to find a function in our own ("to") context with the same name, same
// type, and in the same context as the function we're importing.
else if (!LexicalDC->isFunctionOrMethod()) {
SmallVector<NamedDecl *, 4> ConflictingDecls;
unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(IDNS))
continue;
if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
if (!hasSameVisibilityContextAndLinkage(FoundFunction, D))
continue;
if (IsStructuralMatch(D, FoundFunction)) {
if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
return Def;
FoundByLookup = FoundFunction;
break;
}
// FIXME: Check for overloading more carefully, e.g., by boosting
// Sema::IsOverload out to the AST library.
// Function overloading is okay in C++.
if (Importer.getToContext().getLangOpts().CPlusPlus)
continue;
// Complain about inconsistent function types.
Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
<< Name << D->getType() << FoundFunction->getType();
Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
<< FoundFunction->getType();
ConflictingDecls.push_back(FoundDecl);
}
}
if (!ConflictingDecls.empty()) {
ExpectedName NameOrErr = Importer.HandleNameConflict(
Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
if (NameOrErr)
Name = NameOrErr.get();
else
return NameOrErr.takeError();
}
}
// We do not allow more than one in-class declaration of a function. This is
// because AST clients like VTableBuilder asserts on this. VTableBuilder
// assumes there is only one in-class declaration. Building a redecl
// chain would result in more than one in-class declaration for
// overrides (even if they are part of the same redecl chain inside the
// derived class.)
if (FoundByLookup) {
if (isa<CXXMethodDecl>(FoundByLookup)) {
if (D->getLexicalDeclContext() == D->getDeclContext()) {
if (!D->doesThisDeclarationHaveABody()) {
if (FunctionTemplateDecl *DescribedD =
D->getDescribedFunctionTemplate()) {
// Handle a "templated" function together with its described
// template. This avoids need for a similar check at import of the
// described template.
assert(FoundByLookup->getDescribedFunctionTemplate() &&
"Templated function mapped to non-templated?");
Importer.MapImported(DescribedD,
FoundByLookup->getDescribedFunctionTemplate());
}
return Importer.MapImported(D, FoundByLookup);
} else {
// Let's continue and build up the redecl chain in this case.
// FIXME Merge the functions into one decl.
}
}
}
}
DeclarationNameInfo NameInfo(Name, Loc);
// Import additional name location/type info.
if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
return std::move(Err);
QualType FromTy = D->getType();
// Set to true if we do not import the type of the function as is. There are
// cases when the original type would result in an infinite recursion during
// the import. To avoid an infinite recursion when importing, we create the
// FunctionDecl with a simplified function type and update it only after the
// relevant AST nodes are already imported.
bool UsedDifferentProtoType = false;
if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
QualType FromReturnTy = FromFPT->getReturnType();
// Functions with auto return type may define a struct inside their body
// and the return type could refer to that struct.
// E.g.: auto foo() { struct X{}; return X(); }
// To avoid an infinite recursion when importing, create the FunctionDecl
// with a simplified return type.
if (hasAutoReturnTypeDeclaredInside(D)) {
FromReturnTy = Importer.getFromContext().VoidTy;
UsedDifferentProtoType = true;
}
FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
// FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
// FunctionDecl that we are importing the FunctionProtoType for.
// To avoid an infinite recursion when importing, create the FunctionDecl
// with a simplified function type.
if (FromEPI.ExceptionSpec.SourceDecl ||
FromEPI.ExceptionSpec.SourceTemplate ||
FromEPI.ExceptionSpec.NoexceptExpr) {
FunctionProtoType::ExtProtoInfo DefaultEPI;
FromEPI = DefaultEPI;
UsedDifferentProtoType = true;
}
FromTy = Importer.getFromContext().getFunctionType(
FromReturnTy, FromFPT->getParamTypes(), FromEPI);
}
Error Err = Error::success();
auto T = importChecked(Err, FromTy);
auto TInfo = importChecked(Err, D->getTypeSourceInfo());
auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
auto ToEndLoc = importChecked(Err, D->getEndLoc());
auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
auto TrailingRequiresClause =
importChecked(Err, D->getTrailingRequiresClause());
if (Err)
return std::move(Err);
// Import the function parameters.
SmallVector<ParmVarDecl *, 8> Parameters;
for (auto P : D->parameters()) {
if (Expected<ParmVarDecl *> ToPOrErr = import(P))
Parameters.push_back(*ToPOrErr);
else
return ToPOrErr.takeError();
}
// Create the imported function.
FunctionDecl *ToFunction = nullptr;
if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
ExplicitSpecifier ESpec =
importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier());
if (Err)
return std::move(Err);
if (GetImportedOrCreateDecl<CXXConstructorDecl>(
ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->isInlineSpecified(),
D->isImplicit(), D->getConstexprKind(),
InheritedConstructor(), // FIXME: Properly import inherited
// constructor info
TrailingRequiresClause))
return ToFunction;
} else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
Error Err = Error::success();
auto ToOperatorDelete = importChecked(
Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg());
if (Err)
return std::move(Err);
if (GetImportedOrCreateDecl<CXXDestructorDecl>(
ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
D->isImplicit(), D->getConstexprKind(), TrailingRequiresClause))
return ToFunction;
CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
} else if (CXXConversionDecl *FromConversion =
dyn_cast<CXXConversionDecl>(D)) {
ExplicitSpecifier ESpec =
importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier());
if (Err)
return std::move(Err);
if (GetImportedOrCreateDecl<CXXConversionDecl>(
ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(), ESpec,
D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
return ToFunction;
} else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
if (GetImportedOrCreateDecl<CXXMethodDecl>(
ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
Method->isInlineSpecified(), D->getConstexprKind(),
SourceLocation(), TrailingRequiresClause))
return ToFunction;
} else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) {
ExplicitSpecifier ESpec =
importExplicitSpecifier(Err, Guide->getExplicitSpecifier());
if (Err)
return std::move(Err);
if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
NameInfo, T, TInfo, ToEndLoc))
return ToFunction;
cast<CXXDeductionGuideDecl>(ToFunction)
->setIsCopyDeductionCandidate(Guide->isCopyDeductionCandidate());
} else {
if (GetImportedOrCreateDecl(
ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
NameInfo, T, TInfo, D->getStorageClass(), D->isInlineSpecified(),
D->hasWrittenPrototype(), D->getConstexprKind(),
TrailingRequiresClause))
return ToFunction;
}
// Connect the redecl chain.
if (FoundByLookup) {
auto *Recent = const_cast<FunctionDecl *>(
FoundByLookup->getMostRecentDecl());
ToFunction->setPreviousDecl(Recent);
// FIXME Probably we should merge exception specifications. E.g. In the
// "To" context the existing function may have exception specification with
// noexcept-unevaluated, while the newly imported function may have an
// evaluated noexcept. A call to adjustExceptionSpec() on the imported
// decl and its redeclarations may be required.
}
ToFunction->setQualifierInfo(ToQualifierLoc);
ToFunction->setAccess(D->getAccess());
ToFunction->setLexicalDeclContext(LexicalDC);
ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
ToFunction->setTrivial(D->isTrivial());
ToFunction->setPure(D->isPure());
ToFunction->setDefaulted(D->isDefaulted());
ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted());
ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
ToFunction->setRangeEnd(ToEndLoc);
// Set the parameters.
for (auto *Param : Parameters) {
Param->setOwningFunction(ToFunction);
ToFunction->addDeclInternal(Param);
}
ToFunction->setParams(Parameters);
// We need to complete creation of FunctionProtoTypeLoc manually with setting
// params it refers to.
if (TInfo) {
if (auto ProtoLoc =
TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
ProtoLoc.setParam(I, Parameters[I]);
}
}
// Import the describing template function, if any.
if (FromFT) {
auto ToFTOrErr = import(FromFT);
if (!ToFTOrErr)
return ToFTOrErr.takeError();
}
// Import Ctor initializers.
if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
// Import first, then allocate memory and copy if there was no error.
if (Error Err = ImportContainerChecked(
FromConstructor->inits(), CtorInitializers))
return std::move(Err);
auto **Memory =
new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
ToCtor->setCtorInitializers(Memory);
ToCtor->setNumCtorInitializers(NumInitializers);
}
}
if (D->doesThisDeclarationHaveABody()) {
Error Err = ImportFunctionDeclBody(D, ToFunction);
if (Err)
return std::move(Err);
}
// Import and set the original type in case we used another type.
if (UsedDifferentProtoType) {
if (ExpectedType TyOrErr = import(D->getType()))
ToFunction->setType(*TyOrErr);
else
return TyOrErr.takeError();
}
// FIXME: Other bits to merge?
// If it is a template, import all related things.
if (Error Err = ImportTemplateInformation(D, ToFunction))
return std::move(Err);
addDeclToContexts(D, ToFunction);
if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
FromCXXMethod))
return std::move(Err);
// Import the rest of the chain. I.e. import all subsequent declarations.
for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
if (!ToRedeclOrErr)
return ToRedeclOrErr.takeError();
}
return ToFunction;
}
ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
return VisitFunctionDecl(D);
}
ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
return VisitCXXMethodDecl(D);
}
ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
return VisitCXXMethodDecl(D);
}
ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
return VisitCXXMethodDecl(D);
}
ExpectedDecl
ASTNodeImporter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
return VisitFunctionDecl(D);
}
ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
// Import the major distinguishing characteristics of a variable.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
// Determine whether we've already imported this field.
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
// For anonymous fields, match up by index.
if (!Name &&
ASTImporter::getFieldIndex(D) !=
ASTImporter::getFieldIndex(FoundField))
continue;
if (Importer.IsStructurallyEquivalent(D->getType(),
FoundField->getType())) {
Importer.MapImported(D, FoundField);
// In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
// initializer of a FieldDecl might not had been instantiated in the
// "To" context. However, the "From" context might instantiated that,
// thus we have to merge that.
if (Expr *FromInitializer = D->getInClassInitializer()) {
// We don't have yet the initializer set.
if (FoundField->hasInClassInitializer() &&
!FoundField->getInClassInitializer()) {
if (ExpectedExpr ToInitializerOrErr = import(FromInitializer))
FoundField->setInClassInitializer(*ToInitializerOrErr);
else {
// We can't return error here,
// since we already mapped D as imported.
// FIXME: warning message?
consumeError(ToInitializerOrErr.takeError());
return FoundField;
}
}
}
return FoundField;
}
// FIXME: Why is this case not handled with calling HandleNameConflict?
Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
<< Name << D->getType() << FoundField->getType();
Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
<< FoundField->getType();
return make_error<ImportError>(ImportError::NameConflict);
}
}
Error Err = Error::success();
auto ToType = importChecked(Err, D->getType());
auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
auto ToBitWidth = importChecked(Err, D->getBitWidth());
auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
auto ToInitializer = importChecked(Err, D->getInClassInitializer());
if (Err)
return std::move(Err);
FieldDecl *ToField;
if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
ToType, ToTInfo, ToBitWidth, D->isMutable(),
D->getInClassInitStyle()))
return ToField;
ToField->setAccess(D->getAccess());
ToField->setLexicalDeclContext(LexicalDC);
if (ToInitializer)
ToField->setInClassInitializer(ToInitializer);
ToField->setImplicit(D->isImplicit());
LexicalDC->addDeclInternal(ToField);
return ToField;
}
ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
// Import the major distinguishing characteristics of a variable.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
// Determine whether we've already imported this field.
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
// For anonymous indirect fields, match up by index.
if (!Name &&
ASTImporter::getFieldIndex(D) !=
ASTImporter::getFieldIndex(FoundField))
continue;
if (Importer.IsStructurallyEquivalent(D->getType(),
FoundField->getType(),
!Name.isEmpty())) {
Importer.MapImported(D, FoundField);
return FoundField;
}
// If there are more anonymous fields to check, continue.
if (!Name && I < N-1)
continue;
// FIXME: Why is this case not handled with calling HandleNameConflict?
Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
<< Name << D->getType() << FoundField->getType();
Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
<< FoundField->getType();
return make_error<ImportError>(ImportError::NameConflict);
}
}
// Import the type.
auto TypeOrErr = import(D->getType());
if (!TypeOrErr)
return TypeOrErr.takeError();
auto **NamedChain =
new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
unsigned i = 0;
for (auto *PI : D->chain())
if (Expected<NamedDecl *> ToD = import(PI))
NamedChain[i++] = *ToD;
else
return ToD.takeError();
llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
IndirectFieldDecl *ToIndirectField;
if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
// FIXME here we leak `NamedChain` which is allocated before
return ToIndirectField;
ToIndirectField->setAccess(D->getAccess());
ToIndirectField->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToIndirectField);
return ToIndirectField;
}
/// Used as return type of getFriendCountAndPosition.
struct FriendCountAndPosition {
/// Number of similar looking friends.
unsigned int TotalCount;
/// Index of the specific FriendDecl.
unsigned int IndexOfDecl;
};
template <class T>
static FriendCountAndPosition getFriendCountAndPosition(
const FriendDecl *FD,
llvm::function_ref<T(const FriendDecl *)> GetCanTypeOrDecl) {
unsigned int FriendCount = 0;
llvm::Optional<unsigned int> FriendPosition;
const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
T TypeOrDecl = GetCanTypeOrDecl(FD);
for (const FriendDecl *FoundFriend : RD->friends()) {
if (FoundFriend == FD) {
FriendPosition = FriendCount;
++FriendCount;
} else if (!FoundFriend->getFriendDecl() == !FD->getFriendDecl() &&
GetCanTypeOrDecl(FoundFriend) == TypeOrDecl) {
++FriendCount;
}
}
assert(FriendPosition && "Friend decl not found in own parent.");
return {FriendCount, *FriendPosition};
}
static FriendCountAndPosition getFriendCountAndPosition(const FriendDecl *FD) {
if (FD->getFriendType())
return getFriendCountAndPosition<QualType>(FD, [](const FriendDecl *F) {
if (TypeSourceInfo *TSI = F->getFriendType())
return TSI->getType().getCanonicalType();
llvm_unreachable("Wrong friend object type.");
});
else
return getFriendCountAndPosition<Decl *>(FD, [](const FriendDecl *F) {
if (Decl *D = F->getFriendDecl())
return D->getCanonicalDecl();
llvm_unreachable("Wrong friend object type.");
});
}
ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
// Import the major distinguishing characteristics of a declaration.
DeclContext *DC, *LexicalDC;
if (Error Err = ImportDeclContext(D, DC, LexicalDC))
return std::move(Err);
// Determine whether we've already imported this decl.
// FriendDecl is not a NamedDecl so we cannot use lookup.
// We try to maintain order and count of redundant friend declarations.
const auto *RD = cast<CXXRecordDecl>(DC);
FriendDecl *ImportedFriend = RD->getFirstFriend();
SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
while (ImportedFriend) {
bool Match = false;
if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
Match =
IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
/*Complain=*/false);
} else if (D->getFriendType() && ImportedFriend->getFriendType()) {
Match = Importer.IsStructurallyEquivalent(
D->getFriendType()->getType(),
ImportedFriend->getFriendType()->getType(), /*Complain=*/false);
}
if (Match)
ImportedEquivalentFriends.push_back(ImportedFriend);
ImportedFriend = ImportedFriend->getNextFriend();
}
FriendCountAndPosition CountAndPosition = getFriendCountAndPosition(D);
assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&
"Class with non-matching friends is imported, ODR check wrong?");
if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
return Importer.MapImported(
D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
// Not found. Create it.
// The declarations will be put into order later by ImportDeclContext.
FriendDecl::FriendUnion ToFU;
if (NamedDecl *FriendD = D->getFriendDecl()) {
NamedDecl *ToFriendD;
if (Error Err = importInto(ToFriendD, FriendD))
return std::move(Err);
if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
!(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
ToFriendD->setObjectOfFriendDecl(false);
ToFU = ToFriendD;
} else { // The friend is a type, not a decl.
if (auto TSIOrErr = import(D->getFriendType()))
ToFU = *TSIOrErr;
else
return TSIOrErr.takeError();
}
SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
for (unsigned I = 0; I < D->NumTPLists; I++) {
if (auto ListOrErr = import(FromTPLists[I]))
ToTPLists[I] = *ListOrErr;
else
return ListOrErr.takeError();
}
auto LocationOrErr = import(D->getLocation());
if (!LocationOrErr)
return LocationOrErr.takeError();
auto FriendLocOrErr = import(D->getFriendLoc());
if (!FriendLocOrErr)
return FriendLocOrErr.takeError();
FriendDecl *FrD;
if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
*LocationOrErr, ToFU,
*FriendLocOrErr, ToTPLists))
return FrD;
FrD->setAccess(D->getAccess());
FrD->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(FrD);
return FrD;
}
ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
// Import the major distinguishing characteristics of an ivar.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
// Determine whether we've already imported this ivar
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
if (Importer.IsStructurallyEquivalent(D->getType(),
FoundIvar->getType())) {
Importer.MapImported(D, FoundIvar);
return FoundIvar;
}
Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
<< Name << D->getType() << FoundIvar->getType();
Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
<< FoundIvar->getType();
return make_error<ImportError>(ImportError::NameConflict);
}
}
Error Err = Error::success();
auto ToType = importChecked(Err, D->getType());
auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
auto ToBitWidth = importChecked(Err, D->getBitWidth());
auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
if (Err)
return std::move(Err);
ObjCIvarDecl *ToIvar;
if (GetImportedOrCreateDecl(
ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
ToType, ToTypeSourceInfo,
D->getAccessControl(),ToBitWidth, D->getSynthesize()))
return ToIvar;
ToIvar->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToIvar);
return ToIvar;
}
ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
auto RedeclIt = Redecls.begin();
// Import the first part of the decl chain. I.e. import all previous
// declarations starting from the canonical decl.
for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
ExpectedDecl RedeclOrErr = import(*RedeclIt);
if (!RedeclOrErr)
return RedeclOrErr.takeError();
}
assert(*RedeclIt == D);
// Import the major distinguishing characteristics of a variable.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
// Try to find a variable in our own ("to") context with the same name and
// in the same context as the variable we're importing.
VarDecl *FoundByLookup = nullptr;
if (D->isFileVarDecl()) {
SmallVector<NamedDecl *, 4> ConflictingDecls;
unsigned IDNS = Decl::IDNS_Ordinary;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(IDNS))
continue;
if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
if (!hasSameVisibilityContextAndLinkage(FoundVar, D))
continue;
if (Importer.IsStructurallyEquivalent(D->getType(),
FoundVar->getType())) {
// The VarDecl in the "From" context has a definition, but in the
// "To" context we already have a definition.
VarDecl *FoundDef = FoundVar->getDefinition();
if (D->isThisDeclarationADefinition() && FoundDef)
// FIXME Check for ODR error if the two definitions have
// different initializers?
return Importer.MapImported(D, FoundDef);
// The VarDecl in the "From" context has an initializer, but in the
// "To" context we already have an initializer.
const VarDecl *FoundDInit = nullptr;
if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
// FIXME Diagnose ODR error if the two initializers are different?
return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
FoundByLookup = FoundVar;
break;
}
const ArrayType *FoundArray
= Importer.getToContext().getAsArrayType(FoundVar->getType());
const ArrayType *TArray
= Importer.getToContext().getAsArrayType(D->getType());
if (FoundArray && TArray) {
if (isa<IncompleteArrayType>(FoundArray) &&
isa<ConstantArrayType>(TArray)) {
// Import the type.
if (auto TyOrErr = import(D->getType()))
FoundVar->setType(*TyOrErr);
else
return TyOrErr.takeError();
FoundByLookup = FoundVar;
break;
} else if (isa<IncompleteArrayType>(TArray) &&
isa<ConstantArrayType>(FoundArray)) {
FoundByLookup = FoundVar;
break;
}
}
Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
<< Name << D->getType() << FoundVar->getType();
Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
<< FoundVar->getType();
ConflictingDecls.push_back(FoundDecl);
}
}
if (!ConflictingDecls.empty()) {
ExpectedName NameOrErr = Importer.HandleNameConflict(
Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
if (NameOrErr)
Name = NameOrErr.get();
else
return NameOrErr.takeError();
}
}
Error Err = Error::success();
auto ToType = importChecked(Err, D->getType());
auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
if (Err)
return std::move(Err);
// Create the imported variable.
VarDecl *ToVar;
if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
ToInnerLocStart, Loc,
Name.getAsIdentifierInfo(),
ToType, ToTypeSourceInfo,
D->getStorageClass()))
return ToVar;
ToVar->setQualifierInfo(ToQualifierLoc);
ToVar->setAccess(D->getAccess());
ToVar->setLexicalDeclContext(LexicalDC);
if (FoundByLookup) {
auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
ToVar->setPreviousDecl(Recent);
}
// Import the described template, if any.
if (D->getDescribedVarTemplate()) {
auto ToVTOrErr = import(D->getDescribedVarTemplate());
if (!ToVTOrErr)
return ToVTOrErr.takeError();
}
if (Error Err = ImportInitializer(D, ToVar))
return std::move(Err);
if (D->isConstexpr())
ToVar->setConstexpr(true);
addDeclToContexts(D, ToVar);
// Import the rest of the chain. I.e. import all subsequent declarations.
for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
ExpectedDecl RedeclOrErr = import(*RedeclIt);
if (!RedeclOrErr)
return RedeclOrErr.takeError();
}
return ToVar;
}
ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
// Parameters are created in the translation unit's context, then moved
// into the function declaration's context afterward.
DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
Error Err = Error::success();
auto ToDeclName = importChecked(Err, D->getDeclName());
auto ToLocation = importChecked(Err, D->getLocation());
auto ToType = importChecked(Err, D->getType());
if (Err)
return std::move(Err);
// Create the imported parameter.
ImplicitParamDecl *ToParm = nullptr;
if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
ToLocation, ToDeclName.getAsIdentifierInfo(),
ToType, D->getParameterKind()))
return ToParm;
return ToParm;
}
Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl(
const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
ToParam->setKNRPromoted(FromParam->isKNRPromoted());
if (FromParam->hasUninstantiatedDefaultArg()) {
if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
else
return ToDefArgOrErr.takeError();
} else if (FromParam->hasUnparsedDefaultArg()) {
ToParam->setUnparsedDefaultArg();
} else if (FromParam->hasDefaultArg()) {
if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
ToParam->setDefaultArg(*ToDefArgOrErr);
else
return ToDefArgOrErr.takeError();
}
return Error::success();
}
ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
// Parameters are created in the translation unit's context, then moved
// into the function declaration's context afterward.
DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
Error Err = Error::success();
auto ToDeclName = importChecked(Err, D->getDeclName());
auto ToLocation = importChecked(Err, D->getLocation());
auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
auto ToType = importChecked(Err, D->getType());
auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
if (Err)
return std::move(Err);
ParmVarDecl *ToParm;
if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
ToInnerLocStart, ToLocation,
ToDeclName.getAsIdentifierInfo(), ToType,
ToTypeSourceInfo, D->getStorageClass(),
/*DefaultArg*/ nullptr))
return ToParm;
// Set the default argument. It should be no problem if it was already done.
// Do not import the default expression before GetImportedOrCreateDecl call
// to avoid possible infinite import loop because circular dependency.
if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
return std::move(Err);
if (D->isObjCMethodParameter()) {
ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
} else {
ToParm->setScopeInfo(D->getFunctionScopeDepth(),
D->getFunctionScopeIndex());
}
return ToParm;
}
ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
// Import the major distinguishing characteristics of a method.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
continue;
// Check return types.
if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
FoundMethod->getReturnType())) {
Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
<< D->isInstanceMethod() << Name << D->getReturnType()
<< FoundMethod->getReturnType();
Importer.ToDiag(FoundMethod->getLocation(),
diag::note_odr_objc_method_here)
<< D->isInstanceMethod() << Name;
return make_error<ImportError>(ImportError::NameConflict);
}
// Check the number of parameters.
if (D->param_size() != FoundMethod->param_size()) {
Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
<< D->isInstanceMethod() << Name
<< D->param_size() << FoundMethod->param_size();
Importer.ToDiag(FoundMethod->getLocation(),
diag::note_odr_objc_method_here)
<< D->isInstanceMethod() << Name;
return make_error<ImportError>(ImportError::NameConflict);
}
// Check parameter types.
for (ObjCMethodDecl::param_iterator P = D->param_begin(),
PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
P != PEnd; ++P, ++FoundP) {
if (!Importer.IsStructurallyEquivalent((*P)->getType(),
(*FoundP)->getType())) {
Importer.FromDiag((*P)->getLocation(),
diag::warn_odr_objc_method_param_type_inconsistent)
<< D->isInstanceMethod() << Name
<< (*P)->getType() << (*FoundP)->getType();
Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
<< (*FoundP)->getType();
return make_error<ImportError>(ImportError::NameConflict);
}
}
// Check variadic/non-variadic.
// Check the number of parameters.
if (D->isVariadic() != FoundMethod->isVariadic()) {
Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
<< D->isInstanceMethod() << Name;
Importer.ToDiag(FoundMethod->getLocation(),
diag::note_odr_objc_method_here)
<< D->isInstanceMethod() << Name;
return make_error<ImportError>(ImportError::NameConflict);
}
// FIXME: Any other bits we need to merge?
return Importer.MapImported(D, FoundMethod);
}
}
Error Err = Error::success();
auto ToEndLoc = importChecked(Err, D->getEndLoc());
auto ToReturnType = importChecked(Err, D->getReturnType());
auto ToReturnTypeSourceInfo =
importChecked(Err, D->getReturnTypeSourceInfo());
if (Err)
return std::move(Err);
ObjCMethodDecl *ToMethod;
if (GetImportedOrCreateDecl(
ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(),
D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(),
D->getImplementationControl(), D->hasRelatedResultType()))
return ToMethod;
// FIXME: When we decide to merge method definitions, we'll need to
// deal with implicit parameters.
// Import the parameters
SmallVector<ParmVarDecl *, 5> ToParams;
for (auto *FromP : D->parameters()) {
if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
ToParams.push_back(*ToPOrErr);
else
return ToPOrErr.takeError();
}
// Set the parameters.
for (auto *ToParam : ToParams) {
ToParam->setOwningFunction(ToMethod);
ToMethod->addDeclInternal(ToParam);
}
SmallVector<SourceLocation, 12> FromSelLocs;
D->getSelectorLocs(FromSelLocs);
SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
return std::move(Err);
ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
ToMethod->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToMethod);
// Implicit params are declared when Sema encounters the definition but this
// never happens when the method is imported. Manually declare the implicit
// params now that the MethodDecl knows its class interface.
if (D->getSelfDecl())
ToMethod->createImplicitParams(Importer.getToContext(),
ToMethod->getClassInterface());
return ToMethod;
}
ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
// Import the major distinguishing characteristics of a category.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
Error Err = Error::success();
auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc());
auto ToLocation = importChecked(Err, D->getLocation());
auto ToColonLoc = importChecked(Err, D->getColonLoc());
auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
if (Err)
return std::move(Err);
ObjCTypeParamDecl *Result;
if (GetImportedOrCreateDecl(
Result, D, Importer.getToContext(), DC, D->getVariance(),
ToVarianceLoc, D->getIndex(),
ToLocation, Name.getAsIdentifierInfo(),
ToColonLoc, ToTypeSourceInfo))
return Result;
Result->setLexicalDeclContext(LexicalDC);
return Result;
}
ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
// Import the major distinguishing characteristics of a category.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
ObjCInterfaceDecl *ToInterface;
if (Error Err = importInto(ToInterface, D->getClassInterface()))
return std::move(Err);
// Determine if we've already encountered this category.
ObjCCategoryDecl *MergeWithCategory
= ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
ObjCCategoryDecl *ToCategory = MergeWithCategory;
if (!ToCategory) {
Error Err = Error::success();
auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
if (Err)
return std::move(Err);
if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
ToAtStartLoc, Loc,
ToCategoryNameLoc,
Name.getAsIdentifierInfo(), ToInterface,
/*TypeParamList=*/nullptr,
ToIvarLBraceLoc,
ToIvarRBraceLoc))
return ToCategory;
ToCategory->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToCategory);
// Import the type parameter list after MapImported, to avoid
// loops when bringing in their DeclContext.
if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
ToCategory->setTypeParamList(*PListOrErr);
else
return PListOrErr.takeError();
// Import protocols
SmallVector<ObjCProtocolDecl *, 4> Protocols;
SmallVector<SourceLocation, 4> ProtocolLocs;
ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
= D->protocol_loc_begin();
for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
FromProtoEnd = D->protocol_end();
FromProto != FromProtoEnd;
++FromProto, ++FromProtoLoc) {
if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
Protocols.push_back(*ToProtoOrErr);
else
return ToProtoOrErr.takeError();
if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
ProtocolLocs.push_back(*ToProtoLocOrErr);
else
return ToProtoLocOrErr.takeError();
}
// FIXME: If we're merging, make sure that the protocol list is the same.
ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
ProtocolLocs.data(), Importer.getToContext());
} else {
Importer.MapImported(D, ToCategory);
}
// Import all of the members of this category.
if (Error Err = ImportDeclContext(D))
return std::move(Err);
// If we have an implementation, import it as well.
if (D->getImplementation()) {
if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
import(D->getImplementation()))
ToCategory->setImplementation(*ToImplOrErr);
else
return ToImplOrErr.takeError();
}
return ToCategory;
}
Error ASTNodeImporter::ImportDefinition(
ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) {
if (To->getDefinition()) {
if (shouldForceImportDeclContext(Kind))
if (Error Err = ImportDeclContext(From))
return Err;
return Error::success();
}
// Start the protocol definition
To->startDefinition();
// Import protocols
SmallVector<ObjCProtocolDecl *, 4> Protocols;
SmallVector<SourceLocation, 4> ProtocolLocs;
ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc =
From->protocol_loc_begin();
for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
FromProtoEnd = From->protocol_end();
FromProto != FromProtoEnd;
++FromProto, ++FromProtoLoc) {
if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
Protocols.push_back(*ToProtoOrErr);
else
return ToProtoOrErr.takeError();
if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
ProtocolLocs.push_back(*ToProtoLocOrErr);
else
return ToProtoLocOrErr.takeError();
}
// FIXME: If we're merging, make sure that the protocol list is the same.
To->setProtocolList(Protocols.data(), Protocols.size(),
ProtocolLocs.data(), Importer.getToContext());
if (shouldForceImportDeclContext(Kind)) {
// Import all of the members of this protocol.
if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
return Err;
}
return Error::success();
}
ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
// If this protocol has a definition in the translation unit we're coming
// from, but this particular declaration is not that definition, import the
// definition and map to that.
ObjCProtocolDecl *Definition = D->getDefinition();
if (Definition && Definition != D) {
if (ExpectedDecl ImportedDefOrErr = import(Definition))
return Importer.MapImported(D, *ImportedDefOrErr);
else
return ImportedDefOrErr.takeError();
}
// Import the major distinguishing characteristics of a protocol.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
ObjCProtocolDecl *MergeWithProtocol = nullptr;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
continue;
if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
break;
}
ObjCProtocolDecl *ToProto = MergeWithProtocol;
if (!ToProto) {
auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
if (!ToAtBeginLocOrErr)
return ToAtBeginLocOrErr.takeError();
if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
Name.getAsIdentifierInfo(), Loc,
*ToAtBeginLocOrErr,
/*PrevDecl=*/nullptr))
return ToProto;
ToProto->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToProto);
}
Importer.MapImported(D, ToProto);
if (D->isThisDeclarationADefinition())
if (Error Err = ImportDefinition(D, ToProto))
return std::move(Err);
return ToProto;
}
ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
DeclContext *DC, *LexicalDC;
if (Error Err = ImportDeclContext(D, DC, LexicalDC))
return std::move(Err);
ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
if (!ExternLocOrErr)
return ExternLocOrErr.takeError();
ExpectedSLoc LangLocOrErr = import(D->getLocation());
if (!LangLocOrErr)
return LangLocOrErr.takeError();
bool HasBraces = D->hasBraces();
LinkageSpecDecl *ToLinkageSpec;
if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
*ExternLocOrErr, *LangLocOrErr,
D->getLanguage(), HasBraces))
return ToLinkageSpec;
if (HasBraces) {
ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
if (!RBraceLocOrErr)
return RBraceLocOrErr.takeError();
ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
}
ToLinkageSpec->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToLinkageSpec);
return ToLinkageSpec;
}
ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD = nullptr;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
Error Err = Error::success();
auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
if (Err)
return std::move(Err);
DeclarationNameInfo NameInfo(Name, ToLoc);
if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
return std::move(Err);
UsingDecl *ToUsing;
if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
ToUsingLoc, ToQualifierLoc, NameInfo,
D->hasTypename()))
return ToUsing;
ToUsing->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToUsing);
if (NamedDecl *FromPattern =
Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
Importer.getToContext().setInstantiatedFromUsingDecl(
ToUsing, *ToPatternOrErr);
else
return ToPatternOrErr.takeError();
}
for (UsingShadowDecl *FromShadow : D->shadows()) {
if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
ToUsing->addShadowDecl(*ToShadowOrErr);
else
// FIXME: We return error here but the definition is already created
// and available with lookups. How to fix this?..
return ToShadowOrErr.takeError();
}
return ToUsing;
}
ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD = nullptr;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
Expected<UsingDecl *> ToUsingOrErr = import(D->getUsingDecl());
if (!ToUsingOrErr)
return ToUsingOrErr.takeError();
Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
if (!ToTargetOrErr)
return ToTargetOrErr.takeError();
UsingShadowDecl *ToShadow;
if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
*ToUsingOrErr, *ToTargetOrErr))
return ToShadow;
ToShadow->setLexicalDeclContext(LexicalDC);
ToShadow->setAccess(D->getAccess());
if (UsingShadowDecl *FromPattern =
Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
Importer.getToContext().setInstantiatedFromUsingShadowDecl(
ToShadow, *ToPatternOrErr);
else
// FIXME: We return error here but the definition is already created
// and available with lookups. How to fix this?..
return ToPatternOrErr.takeError();
}
LexicalDC->addDeclInternal(ToShadow);
return ToShadow;
}
ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD = nullptr;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
if (!ToComAncestorOrErr)
return ToComAncestorOrErr.takeError();
Error Err = Error::success();
auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace());
auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
auto ToNamespaceKeyLocation =
importChecked(Err, D->getNamespaceKeyLocation());
auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
auto ToIdentLocation = importChecked(Err, D->getIdentLocation());
if (Err)
return std::move(Err);
UsingDirectiveDecl *ToUsingDir;
if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
ToUsingLoc,
ToNamespaceKeyLocation,
ToQualifierLoc,
ToIdentLocation,
ToNominatedNamespace, *ToComAncestorOrErr))
return ToUsingDir;
ToUsingDir->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToUsingDir);
return ToUsingDir;
}
ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
UnresolvedUsingValueDecl *D) {
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD = nullptr;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
Error Err = Error::success();
auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
if (Err)
return std::move(Err);
DeclarationNameInfo NameInfo(Name, ToLoc);
if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
return std::move(Err);
UnresolvedUsingValueDecl *ToUsingValue;
if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
ToUsingLoc, ToQualifierLoc, NameInfo,
ToEllipsisLoc))
return ToUsingValue;
ToUsingValue->setAccess(D->getAccess());
ToUsingValue->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToUsingValue);
return ToUsingValue;
}
ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
UnresolvedUsingTypenameDecl *D) {
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD = nullptr;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
Error Err = Error::success();
auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc());
auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
if (Err)
return std::move(Err);
UnresolvedUsingTypenameDecl *ToUsing;
if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
ToUsingLoc, ToTypenameLoc,
ToQualifierLoc, Loc, Name, ToEllipsisLoc))
return ToUsing;
ToUsing->setAccess(D->getAccess());
ToUsing->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToUsing);
return ToUsing;
}
ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
Decl* ToD = nullptr;
switch (D->getBuiltinTemplateKind()) {
case BuiltinTemplateKind::BTK__make_integer_seq:
ToD = Importer.getToContext().getMakeIntegerSeqDecl();
break;
case BuiltinTemplateKind::BTK__type_pack_element:
ToD = Importer.getToContext().getTypePackElementDecl();
break;
}
assert(ToD && "BuiltinTemplateDecl of unsupported kind!");
Importer.MapImported(D, ToD);
return ToD;
}
Error ASTNodeImporter::ImportDefinition(
ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) {
if (To->getDefinition()) {
// Check consistency of superclass.
ObjCInterfaceDecl *FromSuper = From->getSuperClass();
if (FromSuper) {
if (auto FromSuperOrErr = import(FromSuper))
FromSuper = *FromSuperOrErr;
else
return FromSuperOrErr.takeError();
}
ObjCInterfaceDecl *ToSuper = To->getSuperClass();
if ((bool)FromSuper != (bool)ToSuper ||
(FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
Importer.ToDiag(To->getLocation(),
diag::warn_odr_objc_superclass_inconsistent)
<< To->getDeclName();
if (ToSuper)
Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
<< To->getSuperClass()->getDeclName();
else
Importer.ToDiag(To->getLocation(),
diag::note_odr_objc_missing_superclass);
if (From->getSuperClass())
Importer.FromDiag(From->getSuperClassLoc(),
diag::note_odr_objc_superclass)
<< From->getSuperClass()->getDeclName();
else
Importer.FromDiag(From->getLocation(),
diag::note_odr_objc_missing_superclass);
}
if (shouldForceImportDeclContext(Kind))
if (Error Err = ImportDeclContext(From))
return Err;
return Error::success();
}
// Start the definition.
To->startDefinition();
// If this class has a superclass, import it.
if (From->getSuperClass()) {
if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
To->setSuperClass(*SuperTInfoOrErr);
else
return SuperTInfoOrErr.takeError();
}
// Import protocols
SmallVector<ObjCProtocolDecl *, 4> Protocols;
SmallVector<SourceLocation, 4> ProtocolLocs;
ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc =
From->protocol_loc_begin();
for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
FromProtoEnd = From->protocol_end();
FromProto != FromProtoEnd;
++FromProto, ++FromProtoLoc) {
if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
Protocols.push_back(*ToProtoOrErr);
else
return ToProtoOrErr.takeError();
if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
ProtocolLocs.push_back(*ToProtoLocOrErr);
else
return ToProtoLocOrErr.takeError();
}
// FIXME: If we're merging, make sure that the protocol list is the same.
To->setProtocolList(Protocols.data(), Protocols.size(),
ProtocolLocs.data(), Importer.getToContext());
// Import categories. When the categories themselves are imported, they'll
// hook themselves into this interface.
for (auto *Cat : From->known_categories()) {
auto ToCatOrErr = import(Cat);
if (!ToCatOrErr)
return ToCatOrErr.takeError();
}
// If we have an @implementation, import it as well.
if (From->getImplementation()) {
if (Expected<ObjCImplementationDecl *> ToImplOrErr =
import(From->getImplementation()))
To->setImplementation(*ToImplOrErr);
else
return ToImplOrErr.takeError();
}
// Import all of the members of this class.
if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
return Err;
return Error::success();
}
Expected<ObjCTypeParamList *>
ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
if (!list)
return nullptr;
SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
for (auto *fromTypeParam : *list) {
if (auto toTypeParamOrErr = import(fromTypeParam))
toTypeParams.push_back(*toTypeParamOrErr);
else
return toTypeParamOrErr.takeError();
}
auto LAngleLocOrErr = import(list->getLAngleLoc());
if (!LAngleLocOrErr)
return LAngleLocOrErr.takeError();
auto RAngleLocOrErr = import(list->getRAngleLoc());
if (!RAngleLocOrErr)
return RAngleLocOrErr.takeError();
return ObjCTypeParamList::create(Importer.getToContext(),
*LAngleLocOrErr,
toTypeParams,
*RAngleLocOrErr);
}
ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
// If this class has a definition in the translation unit we're coming from,
// but this particular declaration is not that definition, import the
// definition and map to that.
ObjCInterfaceDecl *Definition = D->getDefinition();
if (Definition && Definition != D) {
if (ExpectedDecl ImportedDefOrErr = import(Definition))
return Importer.MapImported(D, *ImportedDefOrErr);
else
return ImportedDefOrErr.takeError();
}
// Import the major distinguishing characteristics of an @interface.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
// Look for an existing interface with the same name.
ObjCInterfaceDecl *MergeWithIface = nullptr;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
continue;
if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
break;
}
// Create an interface declaration, if one does not already exist.
ObjCInterfaceDecl *ToIface = MergeWithIface;
if (!ToIface) {
ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
if (!AtBeginLocOrErr)
return AtBeginLocOrErr.takeError();
if (GetImportedOrCreateDecl(
ToIface, D, Importer.getToContext(), DC,
*AtBeginLocOrErr, Name.getAsIdentifierInfo(),
/*TypeParamList=*/nullptr,
/*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
return ToIface;
ToIface->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToIface);
}
Importer.MapImported(D, ToIface);
// Import the type parameter list after MapImported, to avoid
// loops when bringing in their DeclContext.
if (auto ToPListOrErr =
ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
ToIface->setTypeParamList(*ToPListOrErr);
else
return ToPListOrErr.takeError();
if (D->isThisDeclarationADefinition())
if (Error Err = ImportDefinition(D, ToIface))
return std::move(Err);
return ToIface;
}
ExpectedDecl
ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
ObjCCategoryDecl *Category;
if (Error Err = importInto(Category, D->getCategoryDecl()))
return std::move(Err);
ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
if (!ToImpl) {
DeclContext *DC, *LexicalDC;
if (Error Err = ImportDeclContext(D, DC, LexicalDC))
return std::move(Err);
Error Err = Error::success();
auto ToLocation = importChecked(Err, D->getLocation());
auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
if (Err)
return std::move(Err);
if (GetImportedOrCreateDecl(
ToImpl, D, Importer.getToContext(), DC,
Importer.Import(D->getIdentifier()), Category->getClassInterface(),
ToLocation, ToAtStartLoc, ToCategoryNameLoc))
return ToImpl;
ToImpl->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToImpl);
Category->setImplementation(ToImpl);
}
Importer.MapImported(D, ToImpl);
if (Error Err = ImportDeclContext(D))
return std::move(Err);
return ToImpl;
}
ExpectedDecl
ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
// Find the corresponding interface.
ObjCInterfaceDecl *Iface;
if (Error Err = importInto(Iface, D->getClassInterface()))
return std::move(Err);
// Import the superclass, if any.
ObjCInterfaceDecl *Super;
if (Error Err = importInto(Super, D->getSuperClass()))
return std::move(Err);
ObjCImplementationDecl *Impl = Iface->getImplementation();
if (!Impl) {
// We haven't imported an implementation yet. Create a new @implementation
// now.
DeclContext *DC, *LexicalDC;
if (Error Err = ImportDeclContext(D, DC, LexicalDC))
return std::move(Err);
Error Err = Error::success();
auto ToLocation = importChecked(Err, D->getLocation());
auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc());
auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
if (Err)
return std::move(Err);
if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
DC, Iface, Super,
ToLocation,
ToAtStartLoc,
ToSuperClassLoc,
ToIvarLBraceLoc,
ToIvarRBraceLoc))
return Impl;
Impl->setLexicalDeclContext(LexicalDC);
// Associate the implementation with the class it implements.
Iface->setImplementation(Impl);
Importer.MapImported(D, Iface->getImplementation());
} else {
Importer.MapImported(D, Iface->getImplementation());
// Verify that the existing @implementation has the same superclass.
if ((Super && !Impl->getSuperClass()) ||
(!Super && Impl->getSuperClass()) ||
(Super && Impl->getSuperClass() &&
!declaresSameEntity(Super->getCanonicalDecl(),
Impl->getSuperClass()))) {
Importer.ToDiag(Impl->getLocation(),
diag::warn_odr_objc_superclass_inconsistent)
<< Iface->getDeclName();
// FIXME: It would be nice to have the location of the superclass
// below.
if (Impl->getSuperClass())
Importer.ToDiag(Impl->getLocation(),
diag::note_odr_objc_superclass)
<< Impl->getSuperClass()->getDeclName();
else
Importer.ToDiag(Impl->getLocation(),
diag::note_odr_objc_missing_superclass);
if (D->getSuperClass())
Importer.FromDiag(D->getLocation(),
diag::note_odr_objc_superclass)
<< D->getSuperClass()->getDeclName();
else
Importer.FromDiag(D->getLocation(),
diag::note_odr_objc_missing_superclass);
return make_error<ImportError>(ImportError::NameConflict);
}
}
// Import all of the members of this @implementation.
if (Error Err = ImportDeclContext(D))
return std::move(Err);
return Impl;
}
ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
// Import the major distinguishing characteristics of an @property.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
// Check whether we have already imported this property.
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
// Check property types.
if (!Importer.IsStructurallyEquivalent(D->getType(),
FoundProp->getType())) {
Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
<< Name << D->getType() << FoundProp->getType();
Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
<< FoundProp->getType();
return make_error<ImportError>(ImportError::NameConflict);
}
// FIXME: Check property attributes, getters, setters, etc.?
// Consider these properties to be equivalent.
Importer.MapImported(D, FoundProp);
return FoundProp;
}
}
Error Err = Error::success();
auto ToType = importChecked(Err, D->getType());
auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
auto ToAtLoc = importChecked(Err, D->getAtLoc());
auto ToLParenLoc = importChecked(Err, D->getLParenLoc());
if (Err)
return std::move(Err);
// Create the new property.
ObjCPropertyDecl *ToProperty;
if (GetImportedOrCreateDecl(
ToProperty, D, Importer.getToContext(), DC, Loc,
Name.getAsIdentifierInfo(), ToAtLoc,
ToLParenLoc, ToType,
ToTypeSourceInfo, D->getPropertyImplementation()))
return ToProperty;
auto ToGetterName = importChecked(Err, D->getGetterName());
auto ToSetterName = importChecked(Err, D->getSetterName());
auto ToGetterNameLoc = importChecked(Err, D->getGetterNameLoc());
auto ToSetterNameLoc = importChecked(Err, D->getSetterNameLoc());
auto ToGetterMethodDecl = importChecked(Err, D->getGetterMethodDecl());
auto ToSetterMethodDecl = importChecked(Err, D->getSetterMethodDecl());
auto ToPropertyIvarDecl = importChecked(Err, D->getPropertyIvarDecl());
if (Err)
return std::move(Err);
ToProperty->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToProperty);
ToProperty->setPropertyAttributes(D->getPropertyAttributes());
ToProperty->setPropertyAttributesAsWritten(
D->getPropertyAttributesAsWritten());
ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
return ToProperty;
}
ExpectedDecl
ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
ObjCPropertyDecl *Property;
if (Error Err = importInto(Property, D->getPropertyDecl()))
return std::move(Err);
DeclContext *DC, *LexicalDC;
if (Error Err = ImportDeclContext(D, DC, LexicalDC))
return std::move(Err);
auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
// Import the ivar (for an @synthesize).
ObjCIvarDecl *Ivar = nullptr;
if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
return std::move(Err);
ObjCPropertyImplDecl *ToImpl
= InImpl->FindPropertyImplDecl(Property->getIdentifier(),
Property->getQueryKind());
if (!ToImpl) {
Error Err = Error::success();
auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
auto ToLocation = importChecked(Err, D->getLocation());
auto ToPropertyIvarDeclLoc =
importChecked(Err, D->getPropertyIvarDeclLoc());
if (Err)
return std::move(Err);
if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
ToBeginLoc,
ToLocation, Property,
D->getPropertyImplementation(), Ivar,
ToPropertyIvarDeclLoc))
return ToImpl;
ToImpl->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToImpl);
} else {
// Check that we have the same kind of property implementation (@synthesize
// vs. @dynamic).
if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
Importer.ToDiag(ToImpl->getLocation(),
diag::warn_odr_objc_property_impl_kind_inconsistent)
<< Property->getDeclName()
<< (ToImpl->getPropertyImplementation()
== ObjCPropertyImplDecl::Dynamic);
Importer.FromDiag(D->getLocation(),
diag::note_odr_objc_property_impl_kind)
<< D->getPropertyDecl()->getDeclName()
<< (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
return make_error<ImportError>(ImportError::NameConflict);
}
// For @synthesize, check that we have the same
if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
Ivar != ToImpl->getPropertyIvarDecl()) {
Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
diag::warn_odr_objc_synthesize_ivar_inconsistent)
<< Property->getDeclName()
<< ToImpl->getPropertyIvarDecl()->getDeclName()
<< Ivar->getDeclName();
Importer.FromDiag(D->getPropertyIvarDeclLoc(),
diag::note_odr_objc_synthesize_ivar_here)
<< D->getPropertyIvarDecl()->getDeclName();
return make_error<ImportError>(ImportError::NameConflict);
}
// Merge the existing implementation with the new implementation.
Importer.MapImported(D, ToImpl);
}
return ToImpl;
}
ExpectedDecl
ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
// For template arguments, we adopt the translation unit as our declaration
// context. This context will be fixed when the actual template declaration
// is created.
ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
if (!BeginLocOrErr)
return BeginLocOrErr.takeError();
ExpectedSLoc LocationOrErr = import(D->getLocation());
if (!LocationOrErr)
return LocationOrErr.takeError();
TemplateTypeParmDecl *ToD = nullptr;
if (GetImportedOrCreateDecl(
ToD, D, Importer.getToContext(),
Importer.getToContext().getTranslationUnitDecl(),
*BeginLocOrErr, *LocationOrErr,
D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
D->wasDeclaredWithTypename(), D->isParameterPack(),
D->hasTypeConstraint()))
return ToD;
// Import the type-constraint
if (const TypeConstraint *TC = D->getTypeConstraint()) {
Error Err = Error::success();
auto ToNNS = importChecked(Err, TC->getNestedNameSpecifierLoc());
auto ToName = importChecked(Err, TC->getConceptNameInfo().getName());
auto ToNameLoc = importChecked(Err, TC->getConceptNameInfo().getLoc());
auto ToFoundDecl = importChecked(Err, TC->getFoundDecl());
auto ToNamedConcept = importChecked(Err, TC->getNamedConcept());
auto ToIDC = importChecked(Err, TC->getImmediatelyDeclaredConstraint());
if (Err)
return std::move(Err);
TemplateArgumentListInfo ToTAInfo;
const auto *ASTTemplateArgs = TC->getTemplateArgsAsWritten();
if (ASTTemplateArgs)
if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs,
ToTAInfo))
return std::move(Err);
ToD->setTypeConstraint(ToNNS, DeclarationNameInfo(ToName, ToNameLoc),
ToFoundDecl, ToNamedConcept,
ASTTemplateArgs ?
ASTTemplateArgumentListInfo::Create(Importer.getToContext(),
ToTAInfo) : nullptr,
ToIDC);
}
if (D->hasDefaultArgument()) {
Expected<TypeSourceInfo *> ToDefaultArgOrErr =
import(D->getDefaultArgumentInfo());
if (!ToDefaultArgOrErr)
return ToDefaultArgOrErr.takeError();
ToD->setDefaultArgument(*ToDefaultArgOrErr);
}
return ToD;
}
ExpectedDecl
ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
Error Err = Error::success();
auto ToDeclName = importChecked(Err, D->getDeclName());
auto ToLocation = importChecked(Err, D->getLocation());
auto ToType = importChecked(Err, D->getType());
auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
if (Err)
return std::move(Err);
NonTypeTemplateParmDecl *ToD = nullptr;
if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(),
Importer.getToContext().getTranslationUnitDecl(),
ToInnerLocStart, ToLocation, D->getDepth(),
D->getPosition(),
ToDeclName.getAsIdentifierInfo(), ToType,
D->isParameterPack(), ToTypeSourceInfo))
return ToD;
if (D->hasDefaultArgument()) {
ExpectedExpr ToDefaultArgOrErr = import(D->getDefaultArgument());
if (!ToDefaultArgOrErr)
return ToDefaultArgOrErr.takeError();
ToD->setDefaultArgument(*ToDefaultArgOrErr);
}
return ToD;
}
ExpectedDecl
ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
// Import the name of this declaration.
auto NameOrErr = import(D->getDeclName());
if (!NameOrErr)
return NameOrErr.takeError();
// Import the location of this declaration.
ExpectedSLoc LocationOrErr = import(D->getLocation());
if (!LocationOrErr)
return LocationOrErr.takeError();
// Import template parameters.
auto TemplateParamsOrErr = import(D->getTemplateParameters());
if (!TemplateParamsOrErr)
return TemplateParamsOrErr.takeError();
TemplateTemplateParmDecl *ToD = nullptr;
if (GetImportedOrCreateDecl(
ToD, D, Importer.getToContext(),
Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
D->getDepth(), D->getPosition(), D->isParameterPack(),
(*NameOrErr).getAsIdentifierInfo(), *TemplateParamsOrErr))
return ToD;
if (D->hasDefaultArgument()) {
Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
import(D->getDefaultArgument());
if (!ToDefaultArgOrErr)
return ToDefaultArgOrErr.takeError();
ToD->setDefaultArgument(Importer.getToContext(), *ToDefaultArgOrErr);
}
return ToD;
}
// Returns the definition for a (forward) declaration of a TemplateDecl, if
// it has any definition in the redecl chain.
template <typename T> static auto getTemplateDefinition(T *D) -> T * {
assert(D->getTemplatedDecl() && "Should be called on templates only");
auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
if (!ToTemplatedDef)
return nullptr;
auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
return cast_or_null<T>(TemplateWithDef);
}
ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
// Import the major distinguishing characteristics of this class template.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
ClassTemplateDecl *FoundByLookup = nullptr;
// We may already have a template of the same name; try to find and match it.
if (!DC->isFunctionOrMethod()) {
SmallVector<NamedDecl *, 4> ConflictingDecls;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary |
Decl::IDNS_TagFriend))
continue;
Decl *Found = FoundDecl;
auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
if (FoundTemplate) {
if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
continue;
if (IsStructuralMatch(D, FoundTemplate)) {
ClassTemplateDecl *TemplateWithDef =
getTemplateDefinition(FoundTemplate);
if (D->isThisDeclarationADefinition() && TemplateWithDef)
return Importer.MapImported(D, TemplateWithDef);
if (!FoundByLookup)
FoundByLookup = FoundTemplate;
// Search in all matches because there may be multiple decl chains,
// see ASTTests test ImportExistingFriendClassTemplateDef.
continue;
}
ConflictingDecls.push_back(FoundDecl);
}
}
if (!ConflictingDecls.empty()) {
ExpectedName NameOrErr = Importer.HandleNameConflict(
Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
ConflictingDecls.size());
if (NameOrErr)
Name = NameOrErr.get();
else
return NameOrErr.takeError();
}
}
CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
auto TemplateParamsOrErr = import(D->getTemplateParameters());
if (!TemplateParamsOrErr)
return TemplateParamsOrErr.takeError();
// Create the declaration that is being templated.
CXXRecordDecl *ToTemplated;
if (Error Err = importInto(ToTemplated, FromTemplated))
return std::move(Err);
// Create the class template declaration itself.
ClassTemplateDecl *D2;
if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
*TemplateParamsOrErr, ToTemplated))
return D2;
ToTemplated->setDescribedClassTemplate(D2);
D2->setAccess(D->getAccess());
D2->setLexicalDeclContext(LexicalDC);
addDeclToContexts(D, D2);
if (FoundByLookup) {
auto *Recent =
const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
// It is possible that during the import of the class template definition
// we start the import of a fwd friend decl of the very same class template
// and we add the fwd friend decl to the lookup table. But the ToTemplated
// had been created earlier and by that time the lookup could not find
// anything existing, so it has no previous decl. Later, (still during the
// import of the fwd friend decl) we start to import the definition again
// and this time the lookup finds the previous fwd friend class template.
// In this case we must set up the previous decl for the templated decl.
if (!ToTemplated->getPreviousDecl()) {
assert(FoundByLookup->getTemplatedDecl() &&
"Found decl must have its templated decl set");
CXXRecordDecl *PrevTemplated =
FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
if (ToTemplated != PrevTemplated)
ToTemplated->setPreviousDecl(PrevTemplated);
}
D2->setPreviousDecl(Recent);
}
if (FromTemplated->isCompleteDefinition() &&
!ToTemplated->isCompleteDefinition()) {
// FIXME: Import definition!
}
return D2;
}
ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl(
ClassTemplateSpecializationDecl *D) {
ClassTemplateDecl *ClassTemplate;
if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
return std::move(Err);
// Import the context of this declaration.
DeclContext *DC, *LexicalDC;
if (Error Err = ImportDeclContext(D, DC, LexicalDC))
return std::move(Err);
// Import template arguments.
SmallVector<TemplateArgument, 2> TemplateArgs;
if (Error Err = ImportTemplateArguments(
D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
return std::move(Err);
// Try to find an existing specialization with these template arguments and
// template parameter list.
void *InsertPos = nullptr;
ClassTemplateSpecializationDecl *PrevDecl = nullptr;
ClassTemplatePartialSpecializationDecl *PartialSpec =
dyn_cast<ClassTemplatePartialSpecializationDecl>(D);
// Import template parameters.
TemplateParameterList *ToTPList = nullptr;
if (PartialSpec) {
auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
if (!ToTPListOrErr)
return ToTPListOrErr.takeError();
ToTPList = *ToTPListOrErr;
PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs,
*ToTPListOrErr,
InsertPos);
} else
PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
if (PrevDecl) {
if (IsStructuralMatch(D, PrevDecl)) {
CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition();
if (D->isThisDeclarationADefinition() && PrevDefinition) {
Importer.MapImported(D, PrevDefinition);
// Import those default field initializers which have been
// instantiated in the "From" context, but not in the "To" context.
for (auto *FromField : D->fields()) {
auto ToOrErr = import(FromField);
if (!ToOrErr)
return ToOrErr.takeError();
}
// Import those methods which have been instantiated in the
// "From" context, but not in the "To" context.
for (CXXMethodDecl *FromM : D->methods()) {
auto ToOrErr = import(FromM);
if (!ToOrErr)
return ToOrErr.takeError();
}
// TODO Import instantiated default arguments.
// TODO Import instantiated exception specifications.
//
// Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
// what else could be fused during an AST merge.
return PrevDefinition;
}
} else { // ODR violation.
// FIXME HandleNameConflict
return make_error<ImportError>(ImportError::NameConflict);
}
}
// Import the location of this declaration.
ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
if (!BeginLocOrErr)
return BeginLocOrErr.takeError();
ExpectedSLoc IdLocOrErr = import(D->getLocation());
if (!IdLocOrErr)
return IdLocOrErr.takeError();
// Create the specialization.
ClassTemplateSpecializationDecl *D2 = nullptr;
if (PartialSpec) {
// Import TemplateArgumentListInfo.
TemplateArgumentListInfo ToTAInfo;
const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
return std::move(Err);
QualType CanonInjType;
if (Error Err = importInto(
CanonInjType, PartialSpec->getInjectedSpecializationType()))
return std::move(Err);
CanonInjType = CanonInjType.getCanonicalType();
if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
D2, D, Importer.getToContext(), D->getTagKind(), DC,
*BeginLocOrErr, *IdLocOrErr, ToTPList, ClassTemplate,
llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
ToTAInfo, CanonInjType,
cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
return D2;
// Update InsertPos, because preceding import calls may have invalidated
// it by adding new specializations.
auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(D2);
if (!ClassTemplate->findPartialSpecialization(TemplateArgs, ToTPList,
InsertPos))
// Add this partial specialization to the class template.
ClassTemplate->AddPartialSpecialization(PartSpec2, InsertPos);
} else { // Not a partial specialization.
if (GetImportedOrCreateDecl(
D2, D, Importer.getToContext(), D->getTagKind(), DC,
*BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
PrevDecl))
return D2;
// Update InsertPos, because preceding import calls may have invalidated
// it by adding new specializations.
if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
// Add this specialization to the class template.
ClassTemplate->AddSpecialization(D2, InsertPos);
}
D2->setSpecializationKind(D->getSpecializationKind());
// Set the context of this specialization/instantiation.
D2->setLexicalDeclContext(LexicalDC);
// Add to the DC only if it was an explicit specialization/instantiation.
if (D2->isExplicitInstantiationOrSpecialization()) {
LexicalDC->addDeclInternal(D2);
}
if (auto BraceRangeOrErr = import(D->getBraceRange()))
D2->setBraceRange(*BraceRangeOrErr);
else
return BraceRangeOrErr.takeError();
// Import the qualifier, if any.
if (auto LocOrErr = import(D->getQualifierLoc()))
D2->setQualifierInfo(*LocOrErr);
else
return LocOrErr.takeError();
if (auto *TSI = D->getTypeAsWritten()) {
if (auto TInfoOrErr = import(TSI))
D2->setTypeAsWritten(*TInfoOrErr);
else
return TInfoOrErr.takeError();
if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
D2->setTemplateKeywordLoc(*LocOrErr);
else
return LocOrErr.takeError();
if (auto LocOrErr = import(D->getExternLoc()))
D2->setExternLoc(*LocOrErr);
else
return LocOrErr.takeError();
}
if (D->getPointOfInstantiation().isValid()) {
if (auto POIOrErr = import(D->getPointOfInstantiation()))
D2->setPointOfInstantiation(*POIOrErr);
else
return POIOrErr.takeError();
}
D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
if (D->isCompleteDefinition())
if (Error Err = ImportDefinition(D, D2))
return std::move(Err);
return D2;
}
ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
// Import the major distinguishing characteristics of this variable template.
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
// We may already have a template of the same name; try to find and match it.
assert(!DC->isFunctionOrMethod() &&
"Variable templates cannot be declared at function scope");
SmallVector<NamedDecl *, 4> ConflictingDecls;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
VarTemplateDecl *FoundByLookup = nullptr;
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
continue;
if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(FoundDecl)) {
// Use the templated decl, some linkage flags are set only there.
if (!hasSameVisibilityContextAndLinkage(FoundTemplate->getTemplatedDecl(),
D->getTemplatedDecl()))
continue;
if (IsStructuralMatch(D, FoundTemplate)) {
// The Decl in the "From" context has a definition, but in the
// "To" context we already have a definition.
VarTemplateDecl *FoundDef = getTemplateDefinition(FoundTemplate);
if (D->isThisDeclarationADefinition() && FoundDef)
// FIXME Check for ODR error if the two definitions have
// different initializers?
return Importer.MapImported(D, FoundDef);
FoundByLookup = FoundTemplate;
break;
}
ConflictingDecls.push_back(FoundDecl);
}
}
if (!ConflictingDecls.empty()) {
ExpectedName NameOrErr = Importer.HandleNameConflict(
Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
ConflictingDecls.size());
if (NameOrErr)
Name = NameOrErr.get();
else
return NameOrErr.takeError();
}
VarDecl *DTemplated = D->getTemplatedDecl();
// Import the type.
// FIXME: Value not used?
ExpectedType TypeOrErr = import(DTemplated->getType());
if (!TypeOrErr)
return TypeOrErr.takeError();
// Create the declaration that is being templated.
VarDecl *ToTemplated;
if (Error Err = importInto(ToTemplated, DTemplated))
return std::move(Err);
// Create the variable template declaration itself.
auto TemplateParamsOrErr = import(D->getTemplateParameters());
if (!TemplateParamsOrErr)
return TemplateParamsOrErr.takeError();
VarTemplateDecl *ToVarTD;
if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
Name, *TemplateParamsOrErr, ToTemplated))
return ToVarTD;
ToTemplated->setDescribedVarTemplate(ToVarTD);
ToVarTD->setAccess(D->getAccess());
ToVarTD->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToVarTD);
if (FoundByLookup) {
auto *Recent =
const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl());
if (!ToTemplated->getPreviousDecl()) {
auto *PrevTemplated =
FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
if (ToTemplated != PrevTemplated)
ToTemplated->setPreviousDecl(PrevTemplated);
}
ToVarTD->setPreviousDecl(Recent);
}
if (DTemplated->isThisDeclarationADefinition() &&
!ToTemplated->isThisDeclarationADefinition()) {
// FIXME: Import definition!
}
return ToVarTD;
}
ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl(
VarTemplateSpecializationDecl *D) {
// If this record has a definition in the translation unit we're coming from,
// but this particular declaration is not that definition, import the
// definition and map to that.
VarDecl *Definition = D->getDefinition();
if (Definition && Definition != D) {
if (ExpectedDecl ImportedDefOrErr = import(Definition))
return Importer.MapImported(D, *ImportedDefOrErr);
else
return ImportedDefOrErr.takeError();
}
VarTemplateDecl *VarTemplate = nullptr;
if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
return std::move(Err);
// Import the context of this declaration.
DeclContext *DC, *LexicalDC;
if (Error Err = ImportDeclContext(D, DC, LexicalDC))
return std::move(Err);
// Import the location of this declaration.
ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
if (!BeginLocOrErr)
return BeginLocOrErr.takeError();
auto IdLocOrErr = import(D->getLocation());
if (!IdLocOrErr)
return IdLocOrErr.takeError();
// Import template arguments.
SmallVector<TemplateArgument, 2> TemplateArgs;
if (Error Err = ImportTemplateArguments(
D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
return std::move(Err);
// Try to find an existing specialization with these template arguments.
void *InsertPos = nullptr;
VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
TemplateArgs, InsertPos);
if (D2) {
// We already have a variable template specialization with these template
// arguments.
// FIXME: Check for specialization vs. instantiation errors.
if (VarDecl *FoundDef = D2->getDefinition()) {
if (!D->isThisDeclarationADefinition() ||
IsStructuralMatch(D, FoundDef)) {
// The record types structurally match, or the "from" translation
// unit only had a forward declaration anyway; call it the same
// variable.
return Importer.MapImported(D, FoundDef);
}
}
} else {
// Import the type.
QualType T;
if (Error Err = importInto(T, D->getType()))
return std::move(Err);
auto TInfoOrErr = import(D->getTypeSourceInfo());
if (!TInfoOrErr)
return TInfoOrErr.takeError();
TemplateArgumentListInfo ToTAInfo;
if (Error Err = ImportTemplateArgumentListInfo(
D->getTemplateArgsInfo(), ToTAInfo))
return std::move(Err);
using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
// Create a new specialization.
if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
// Import TemplateArgumentListInfo
TemplateArgumentListInfo ArgInfos;
const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
// NOTE: FromTAArgsAsWritten and template parameter list are non-null.
if (Error Err = ImportTemplateArgumentListInfo(
*FromTAArgsAsWritten, ArgInfos))
return std::move(Err);
auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
if (!ToTPListOrErr)
return ToTPListOrErr.takeError();
PartVarSpecDecl *ToPartial;
if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
*BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
VarTemplate, T, *TInfoOrErr,
D->getStorageClass(), TemplateArgs, ArgInfos))
return ToPartial;
if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
FromPartial->getInstantiatedFromMember()))
ToPartial->setInstantiatedFromMember(*ToInstOrErr);
else
return ToInstOrErr.takeError();
if (FromPartial->isMemberSpecialization())
ToPartial->setMemberSpecialization();
D2 = ToPartial;
} else { // Full specialization
if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
*BeginLocOrErr, *IdLocOrErr, VarTemplate,
T, *TInfoOrErr,
D->getStorageClass(), TemplateArgs))
return D2;
}
if (D->getPointOfInstantiation().isValid()) {
if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
D2->setPointOfInstantiation(*POIOrErr);
else
return POIOrErr.takeError();
}
D2->setSpecializationKind(D->getSpecializationKind());
D2->setTemplateArgsInfo(ToTAInfo);
// Add this specialization to the class template.
VarTemplate->AddSpecialization(D2, InsertPos);
// Import the qualifier, if any.
if (auto LocOrErr = import(D->getQualifierLoc()))
D2->setQualifierInfo(*LocOrErr);
else
return LocOrErr.takeError();
if (D->isConstexpr())
D2->setConstexpr(true);
// Add the specialization to this context.
D2->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(D2);
D2->setAccess(D->getAccess());
}
if (Error Err = ImportInitializer(D, D2))
return std::move(Err);
return D2;
}
ExpectedDecl
ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
DeclContext *DC, *LexicalDC;
DeclarationName Name;
SourceLocation Loc;
NamedDecl *ToD;
if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
return std::move(Err);
if (ToD)
return ToD;
const FunctionTemplateDecl *FoundByLookup = nullptr;
// Try to find a function in our own ("to") context with the same name, same
// type, and in the same context as the function we're importing.
// FIXME Split this into a separate function.
if (!LexicalDC->isFunctionOrMethod()) {
unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
for (auto *FoundDecl : FoundDecls) {
if (!FoundDecl->isInIdentifierNamespace(IDNS))
continue;
if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
continue;
if (IsStructuralMatch(D, FoundTemplate)) {
FunctionTemplateDecl *TemplateWithDef =
getTemplateDefinition(FoundTemplate);
if (D->isThisDeclarationADefinition() && TemplateWithDef)
return Importer.MapImported(D, TemplateWithDef);
FoundByLookup = FoundTemplate;
break;
// TODO: handle conflicting names
}
}
}
}
auto ParamsOrErr = import(D->getTemplateParameters());
if (!ParamsOrErr)
return ParamsOrErr.takeError();
FunctionDecl *TemplatedFD;
if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
return std::move(Err);
FunctionTemplateDecl *ToFunc;
if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
*ParamsOrErr, TemplatedFD))
return ToFunc;
TemplatedFD->setDescribedFunctionTemplate(ToFunc);
ToFunc->setAccess(D->getAccess());
ToFunc->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(ToFunc);
if (FoundByLookup) {
auto *Recent =
const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
if (!TemplatedFD->getPreviousDecl()) {
assert(FoundByLookup->getTemplatedDecl() &&
"Found decl must have its templated decl set");
auto *PrevTemplated =
FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
if (TemplatedFD != PrevTemplated)
TemplatedFD->setPreviousDecl(PrevTemplated);
}
ToFunc->setPreviousDecl(Recent);
}
return ToFunc;
}
//----------------------------------------------------------------------------
// Import Statements
//----------------------------------------------------------------------------
ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) {
Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
<< S->getStmtClassName();
return make_error<ImportError>(ImportError::UnsupportedConstruct);
}
ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
if (Importer.returnWithErrorInTest())
return make_error<ImportError>(ImportError::UnsupportedConstruct);
SmallVector<IdentifierInfo *, 4> Names;
for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
// ToII is nullptr when no symbolic name is given for output operand
// see ParseStmtAsm::ParseAsmOperandsOpt
Names.push_back(ToII);
}
for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
// ToII is nullptr when no symbolic name is given for input operand
// see ParseStmtAsm::ParseAsmOperandsOpt
Names.push_back(ToII);
}
SmallVector<StringLiteral *, 4> Clobbers;
for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
Clobbers.push_back(*ClobberOrErr);
else
return ClobberOrErr.takeError();
}
SmallVector<StringLiteral *, 4> Constraints;
for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
Constraints.push_back(*OutputOrErr);
else
return OutputOrErr.takeError();
}
for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
Constraints.push_back(*InputOrErr);
else
return InputOrErr.takeError();
}
SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() +
S->getNumLabels());
if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
return std::move(Err);
if (Error Err =
ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
return std::move(Err);
if (Error Err = ImportArrayChecked(
S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
return std::move(Err);
ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
if (!AsmLocOrErr)
return AsmLocOrErr.takeError();
auto AsmStrOrErr = import(S->getAsmString());
if (!AsmStrOrErr)
return AsmStrOrErr.takeError();
ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
if (!RParenLocOrErr)
return RParenLocOrErr.takeError();
return new (Importer.getToContext()) GCCAsmStmt(
Importer.getToContext(),
*AsmLocOrErr,
S->isSimple(),
S->isVolatile(),
S->getNumOutputs(),
S->getNumInputs(),
Names.data(),
Constraints.data(),
Exprs.data(),
*AsmStrOrErr,
S->getNumClobbers(),
Clobbers.data(),
S->getNumLabels(),
*RParenLocOrErr);
}
ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
Error Err = Error::success();
auto ToDG = importChecked(Err, S->getDeclGroup());
auto ToBeginLoc = importChecked(Err, S->getBeginLoc());
auto ToEndLoc = importChecked(Err, S->getEndLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
}
ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) {
ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc());
if (!ToSemiLocOrErr)
return ToSemiLocOrErr.takeError();
return new (Importer.getToContext()) NullStmt(
*ToSemiLocOrErr, S->hasLeadingEmptyMacro());
}
ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
SmallVector<Stmt *, 8> ToStmts(S->size());
if (Error Err = ImportContainerChecked(S->body(), ToStmts))
return std::move(Err);
ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc());
if (!ToLBracLocOrErr)
return ToLBracLocOrErr.takeError();
ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc());
if (!ToRBracLocOrErr)
return ToRBracLocOrErr.takeError();
ExpectedSLoc ToCheckedSpecifierLocOrErr = import(S->getCheckedSpecifierLoc());
if (!ToCheckedSpecifierLocOrErr)
return ToCheckedSpecifierLocOrErr.takeError();
ExpectedSLoc ToSpecifierModifierorErr = import(S->getSpecifierModifierLoc());
if (!ToSpecifierModifierorErr)
return ToSpecifierModifierorErr.takeError();
return CompoundStmt::Create(
Importer.getToContext(), ToStmts,
*ToLBracLocOrErr, *ToRBracLocOrErr,
S->getWrittenCheckedSpecifier(),
S->getCheckedSpecifier(),
*ToCheckedSpecifierLocOrErr, *ToSpecifierModifierorErr);
}
ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
Error Err = Error::success();
auto ToLHS = importChecked(Err, S->getLHS());
auto ToRHS = importChecked(Err, S->getRHS());
auto ToSubStmt = importChecked(Err, S->getSubStmt());
auto ToCaseLoc = importChecked(Err, S->getCaseLoc());
auto ToEllipsisLoc = importChecked(Err, S->getEllipsisLoc());
auto ToColonLoc = importChecked(Err, S->getColonLoc());
if (Err)
return std::move(Err);
auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS,
ToCaseLoc, ToEllipsisLoc, ToColonLoc);
ToStmt->setSubStmt(ToSubStmt);
return ToStmt;
}
ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
Error Err = Error::success();
auto ToDefaultLoc = importChecked(Err, S->getDefaultLoc());
auto ToColonLoc = importChecked(Err, S->getColonLoc());
auto ToSubStmt = importChecked(Err, S->getSubStmt());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) DefaultStmt(
ToDefaultLoc, ToColonLoc, ToSubStmt);
}
ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
Error Err = Error::success();
auto ToIdentLoc = importChecked(Err, S->getIdentLoc());
auto ToLabelDecl = importChecked(Err, S->getDecl());
auto ToSubStmt = importChecked(Err, S->getSubStmt());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) LabelStmt(
ToIdentLoc, ToLabelDecl, ToSubStmt);
}
ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc());
if (!ToAttrLocOrErr)
return ToAttrLocOrErr.takeError();
ArrayRef<const Attr*> FromAttrs(S->getAttrs());
SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs))
return std::move(Err);
ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
if (!ToSubStmtOrErr)
return ToSubStmtOrErr.takeError();
return AttributedStmt::Create(
Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr);
}
ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) {
Error Err = Error::success();
auto ToIfLoc = importChecked(Err, S->getIfLoc());
auto ToInit = importChecked(Err, S->getInit());
auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
auto ToCond = importChecked(Err, S->getCond());
auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
auto ToThen = importChecked(Err, S->getThen());
auto ToElseLoc = importChecked(Err, S->getElseLoc());
auto ToElse = importChecked(Err, S->getElse());
if (Err)
return std::move(Err);
return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->isConstexpr(),
ToInit, ToConditionVariable, ToCond, ToLParenLoc,
ToRParenLoc, ToThen, ToElseLoc, ToElse);
}
ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
Error Err = Error::success();
auto ToInit = importChecked(Err, S->getInit());
auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
auto ToCond = importChecked(Err, S->getCond());
auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
auto ToBody = importChecked(Err, S->getBody());
auto ToSwitchLoc = importChecked(Err, S->getSwitchLoc());
if (Err)
return std::move(Err);
auto *ToStmt =
SwitchStmt::Create(Importer.getToContext(), ToInit, ToConditionVariable,
ToCond, ToLParenLoc, ToRParenLoc);
ToStmt->setBody(ToBody);
ToStmt->setSwitchLoc(ToSwitchLoc);
// Now we have to re-chain the cases.
SwitchCase *LastChainedSwitchCase = nullptr;
for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
SC = SC->getNextSwitchCase()) {
Expected<SwitchCase *> ToSCOrErr = import(SC);
if (!ToSCOrErr)
return ToSCOrErr.takeError();
if (LastChainedSwitchCase)
LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr);
else
ToStmt->setSwitchCaseList(*ToSCOrErr);
LastChainedSwitchCase = *ToSCOrErr;
}
return ToStmt;
}
ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
Error Err = Error::success();
auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
auto ToCond = importChecked(Err, S->getCond());
auto ToBody = importChecked(Err, S->getBody());
auto ToWhileLoc = importChecked(Err, S->getWhileLoc());
auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
if (Err)
return std::move(Err);
return WhileStmt::Create(Importer.getToContext(), ToConditionVariable, ToCond,
ToBody, ToWhileLoc, ToLParenLoc, ToRParenLoc);
}
ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) {
Error Err = Error::success();
auto ToBody = importChecked(Err, S->getBody());
auto ToCond = importChecked(Err, S->getCond());
auto ToDoLoc = importChecked(Err, S->getDoLoc());
auto ToWhileLoc = importChecked(Err, S->getWhileLoc());
auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) DoStmt(
ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc);
}
ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) {
Error Err = Error::success();
auto ToInit = importChecked(Err, S->getInit());
auto ToCond = importChecked(Err, S->getCond());
auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
auto ToInc = importChecked(Err, S->getInc());
auto ToBody = importChecked(Err, S->getBody());
auto ToForLoc = importChecked(Err, S->getForLoc());
auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) ForStmt(
Importer.getToContext(),
ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc,
ToRParenLoc);
}
ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
Error Err = Error::success();
auto ToLabel = importChecked(Err, S->getLabel());
auto ToGotoLoc = importChecked(Err, S->getGotoLoc());
auto ToLabelLoc = importChecked(Err, S->getLabelLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) GotoStmt(
ToLabel, ToGotoLoc, ToLabelLoc);
}
ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
Error Err = Error::success();
auto ToGotoLoc = importChecked(Err, S->getGotoLoc());
auto ToStarLoc = importChecked(Err, S->getStarLoc());
auto ToTarget = importChecked(Err, S->getTarget());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) IndirectGotoStmt(
ToGotoLoc, ToStarLoc, ToTarget);
}
ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
ExpectedSLoc ToContinueLocOrErr = import(S->getContinueLoc());
if (!ToContinueLocOrErr)
return ToContinueLocOrErr.takeError();
return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr);
}
ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
auto ToBreakLocOrErr = import(S->getBreakLoc());
if (!ToBreakLocOrErr)
return ToBreakLocOrErr.takeError();
return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr);
}
ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
Error Err = Error::success();
auto ToReturnLoc = importChecked(Err, S->getReturnLoc());
auto ToRetValue = importChecked(Err, S->getRetValue());
auto ToNRVOCandidate = importChecked(Err, S->getNRVOCandidate());
if (Err)
return std::move(Err);
return ReturnStmt::Create(Importer.getToContext(), ToReturnLoc, ToRetValue,
ToNRVOCandidate);
}
ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
Error Err = Error::success();
auto ToCatchLoc = importChecked(Err, S->getCatchLoc());
auto ToExceptionDecl = importChecked(Err, S->getExceptionDecl());
auto ToHandlerBlock = importChecked(Err, S->getHandlerBlock());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) CXXCatchStmt (
ToCatchLoc, ToExceptionDecl, ToHandlerBlock);
}
ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
ExpectedSLoc ToTryLocOrErr = import(S->getTryLoc());
if (!ToTryLocOrErr)
return ToTryLocOrErr.takeError();
ExpectedStmt ToTryBlockOrErr = import(S->getTryBlock());
if (!ToTryBlockOrErr)
return ToTryBlockOrErr.takeError();
SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
CXXCatchStmt *FromHandler = S->getHandler(HI);
if (auto ToHandlerOrErr = import(FromHandler))
ToHandlers[HI] = *ToHandlerOrErr;
else
return ToHandlerOrErr.takeError();
}
return CXXTryStmt::Create(
Importer.getToContext(), *ToTryLocOrErr,*ToTryBlockOrErr, ToHandlers);
}
ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Error Err = Error::success();
auto ToInit = importChecked(Err, S->getInit());
auto ToRangeStmt = importChecked(Err, S->getRangeStmt());
auto ToBeginStmt = importChecked(Err, S->getBeginStmt());
auto ToEndStmt = importChecked(Err, S->getEndStmt());
auto ToCond = importChecked(Err, S->getCond());
auto ToInc = importChecked(Err, S->getInc());
auto ToLoopVarStmt = importChecked(Err, S->getLoopVarStmt());
auto ToBody = importChecked(Err, S->getBody());
auto ToForLoc = importChecked(Err, S->getForLoc());
auto ToCoawaitLoc = importChecked(Err, S->getCoawaitLoc());
auto ToColonLoc = importChecked(Err, S->getColonLoc());
auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) CXXForRangeStmt(
ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt,
ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc);
}
ExpectedStmt
ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Error Err = Error::success();
auto ToElement = importChecked(Err, S->getElement());
auto ToCollection = importChecked(Err, S->getCollection());
auto ToBody = importChecked(Err, S->getBody());
auto ToForLoc = importChecked(Err, S->getForLoc());
auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement,
ToCollection,
ToBody,
ToForLoc,
ToRParenLoc);
}
ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Error Err = Error::success();
auto ToAtCatchLoc = importChecked(Err, S->getAtCatchLoc());
auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
auto ToCatchParamDecl = importChecked(Err, S->getCatchParamDecl());
auto ToCatchBody = importChecked(Err, S->getCatchBody());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) ObjCAtCatchStmt (
ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody);
}
ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
ExpectedSLoc ToAtFinallyLocOrErr = import(S->getAtFinallyLoc());
if (!ToAtFinallyLocOrErr)
return ToAtFinallyLocOrErr.takeError();
ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody());
if (!ToAtFinallyStmtOrErr)
return ToAtFinallyStmtOrErr.takeError();
return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr,
*ToAtFinallyStmtOrErr);
}
ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Error Err = Error::success();
auto ToAtTryLoc = importChecked(Err, S->getAtTryLoc());
auto ToTryBody = importChecked(Err, S->getTryBody());
auto ToFinallyStmt = importChecked(Err, S->getFinallyStmt());
if (Err)
return std::move(Err);
SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
if (ExpectedStmt ToCatchStmtOrErr = import(FromCatchStmt))
ToCatchStmts[CI] = *ToCatchStmtOrErr;
else
return ToCatchStmtOrErr.takeError();
}
return ObjCAtTryStmt::Create(Importer.getToContext(),
ToAtTryLoc, ToTryBody,
ToCatchStmts.begin(), ToCatchStmts.size(),
ToFinallyStmt);
}
ExpectedStmt
ASTNodeImporter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Error Err = Error::success();
auto ToAtSynchronizedLoc = importChecked(Err, S->getAtSynchronizedLoc());
auto ToSynchExpr = importChecked(Err, S->getSynchExpr());
auto ToSynchBody = importChecked(Err, S->getSynchBody());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
}
ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
ExpectedSLoc ToThrowLocOrErr = import(S->getThrowLoc());
if (!ToThrowLocOrErr)
return ToThrowLocOrErr.takeError();
ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr());
if (!ToThrowExprOrErr)
return ToThrowExprOrErr.takeError();
return new (Importer.getToContext()) ObjCAtThrowStmt(
*ToThrowLocOrErr, *ToThrowExprOrErr);
}
ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt(
ObjCAutoreleasePoolStmt *S) {
ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc());
if (!ToAtLocOrErr)
return ToAtLocOrErr.takeError();
ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
if (!ToSubStmtOrErr)
return ToSubStmtOrErr.takeError();
return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr,
*ToSubStmtOrErr);
}
//----------------------------------------------------------------------------
// Import Expressions
//----------------------------------------------------------------------------
ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) {
Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node)
<< E->getStmtClassName();
return make_error<ImportError>(ImportError::UnsupportedConstruct);
}
ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
Error Err = Error::success();
auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
auto ToSubExpr = importChecked(Err, E->getSubExpr());
auto ToWrittenTypeInfo = importChecked(Err, E->getWrittenTypeInfo());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
auto ToType = importChecked(Err, E->getType());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) VAArgExpr(
ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType,
E->isMicrosoftABI());
}
ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) {
Error Err = Error::success();
auto ToCond = importChecked(Err, E->getCond());
auto ToLHS = importChecked(Err, E->getLHS());
auto ToRHS = importChecked(Err, E->getRHS());
auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
auto ToType = importChecked(Err, E->getType());
if (Err)
return std::move(Err);
ExprValueKind VK = E->getValueKind();
ExprObjectKind OK = E->getObjectKind();
// The value of CondIsTrue only matters if the value is not
// condition-dependent.
bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue();
return new (Importer.getToContext())
ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK,
ToRParenLoc, CondIsTrue);
}
ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
ExpectedType TypeOrErr = import(E->getType());
if (!TypeOrErr)
return TypeOrErr.takeError();
ExpectedSLoc BeginLocOrErr = import(E->getBeginLoc());
if (!BeginLocOrErr)
return BeginLocOrErr.takeError();
return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr);
}
ExpectedStmt
ASTNodeImporter::VisitGenericSelectionExpr(GenericSelectionExpr *E) {
Error Err = Error::success();
auto ToGenericLoc = importChecked(Err, E->getGenericLoc());
auto *ToControllingExpr = importChecked(Err, E->getControllingExpr());
auto ToDefaultLoc = importChecked(Err, E->getDefaultLoc());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
if (Err)
return std::move(Err);
ArrayRef<const TypeSourceInfo *> FromAssocTypes(E->getAssocTypeSourceInfos());
SmallVector<TypeSourceInfo *, 1> ToAssocTypes(FromAssocTypes.size());
if (Error Err = ImportContainerChecked(FromAssocTypes, ToAssocTypes))
return std::move(Err);
ArrayRef<const Expr *> FromAssocExprs(E->getAssocExprs());
SmallVector<Expr *, 1> ToAssocExprs(FromAssocExprs.size());
if (Error Err = ImportContainerChecked(FromAssocExprs, ToAssocExprs))
return std::move(Err);
const ASTContext &ToCtx = Importer.getToContext();
if (E->isResultDependent()) {
return GenericSelectionExpr::Create(
ToCtx, ToGenericLoc, ToControllingExpr,
llvm::makeArrayRef(ToAssocTypes), llvm::makeArrayRef(ToAssocExprs),
ToDefaultLoc, ToRParenLoc, E->containsUnexpandedParameterPack());
}
return GenericSelectionExpr::Create(
ToCtx, ToGenericLoc, ToControllingExpr, llvm::makeArrayRef(ToAssocTypes),
llvm::makeArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
E->containsUnexpandedParameterPack(), E->getResultIndex());
}
ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
Error Err = Error::success();
auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
auto ToType = importChecked(Err, E->getType());
auto ToFunctionName = importChecked(Err, E->getFunctionName());
if (Err)
return std::move(Err);
return PredefinedExpr::Create(Importer.getToContext(), ToBeginLoc, ToType,
E->getIdentKind(), ToFunctionName);
}
ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
Error Err = Error::success();
auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
auto ToDecl = importChecked(Err, E->getDecl());
auto ToLocation = importChecked(Err, E->getLocation());
auto ToType = importChecked(Err, E->getType());
if (Err)
return std::move(Err);
NamedDecl *ToFoundD = nullptr;
if (E->getDecl() != E->getFoundDecl()) {
auto FoundDOrErr = import(E->getFoundDecl());
if (!FoundDOrErr)
return FoundDOrErr.takeError();
ToFoundD = *FoundDOrErr;
}
TemplateArgumentListInfo ToTAInfo;
TemplateArgumentListInfo *ToResInfo = nullptr;
if (E->hasExplicitTemplateArgs()) {
if (Error Err =
ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
E->template_arguments(), ToTAInfo))
return std::move(Err);
ToResInfo = &ToTAInfo;
}
auto *ToE = DeclRefExpr::Create(
Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl,
E->refersToEnclosingVariableOrCapture(), ToLocation, ToType,
E->getValueKind(), ToFoundD, ToResInfo, E->isNonOdrUse());
if (E->hadMultipleCandidates())
ToE->setHadMultipleCandidates(true);
return ToE;
}
ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
ExpectedType TypeOrErr = import(E->getType());
if (!TypeOrErr)
return TypeOrErr.takeError();
return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr);
}
ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
ExpectedExpr ToInitOrErr = import(E->getInit());
if (!ToInitOrErr)
return ToInitOrErr.takeError();
ExpectedSLoc ToEqualOrColonLocOrErr = import(E->getEqualOrColonLoc());
if (!ToEqualOrColonLocOrErr)
return ToEqualOrColonLocOrErr.takeError();
SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1);
// List elements from the second, the first is Init itself
for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) {
if (ExpectedExpr ToArgOrErr = import(E->getSubExpr(I)))
ToIndexExprs[I - 1] = *ToArgOrErr;
else
return ToArgOrErr.takeError();
}
SmallVector<Designator, 4> ToDesignators(E->size());
if (Error Err = ImportContainerChecked(E->designators(), ToDesignators))
return std::move(Err);
return DesignatedInitExpr::Create(
Importer.getToContext(), ToDesignators,
ToIndexExprs, *ToEqualOrColonLocOrErr,
E->usesGNUSyntax(), *ToInitOrErr);
}
ExpectedStmt
ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedSLoc ToLocationOrErr = import(E->getLocation());
if (!ToLocationOrErr)
return ToLocationOrErr.takeError();
return new (Importer.getToContext()) CXXNullPtrLiteralExpr(
*ToTypeOrErr, *ToLocationOrErr);
}
ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedSLoc ToLocationOrErr = import(E->getLocation());
if (!ToLocationOrErr)
return ToLocationOrErr.takeError();
return IntegerLiteral::Create(
Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
}
ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedSLoc ToLocationOrErr = import(E->getLocation());
if (!ToLocationOrErr)
return ToLocationOrErr.takeError();
return FloatingLiteral::Create(
Importer.getToContext(), E->getValue(), E->isExact(),
*ToTypeOrErr, *ToLocationOrErr);
}
ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) {
auto ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
if (!ToSubExprOrErr)
return ToSubExprOrErr.takeError();
return new (Importer.getToContext()) ImaginaryLiteral(
*ToSubExprOrErr, *ToTypeOrErr);
}
ExpectedStmt ASTNodeImporter::VisitFixedPointLiteral(FixedPointLiteral *E) {
auto ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedSLoc ToLocationOrErr = import(E->getLocation());
if (!ToLocationOrErr)
return ToLocationOrErr.takeError();
return new (Importer.getToContext()) FixedPointLiteral(
Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr,
Importer.getToContext().getFixedPointScale(*ToTypeOrErr));
}
ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedSLoc ToLocationOrErr = import(E->getLocation());
if (!ToLocationOrErr)
return ToLocationOrErr.takeError();
return new (Importer.getToContext()) CharacterLiteral(
E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr);
}
ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated());
if (Error Err = ImportArrayChecked(
E->tokloc_begin(), E->tokloc_end(), ToLocations.begin()))
return std::move(Err);
return StringLiteral::Create(
Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(),
*ToTypeOrErr, ToLocations.data(), ToLocations.size());
}
ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
Error Err = Error::success();
auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
auto ToType = importChecked(Err, E->getType());
auto ToInitializer = importChecked(Err, E->getInitializer());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) CompoundLiteralExpr(
ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(),
ToInitializer, E->isFileScope());
}
ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
Error Err = Error::success();
auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
auto ToType = importChecked(Err, E->getType());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
if (Err)
return std::move(Err);
SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs());
if (Error Err = ImportArrayChecked(
E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
ToExprs.begin()))
return std::move(Err);
return new (Importer.getToContext()) AtomicExpr(
ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc);
}
ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
Error Err = Error::success();
auto ToAmpAmpLoc = importChecked(Err, E->getAmpAmpLoc());
auto ToLabelLoc = importChecked(Err, E->getLabelLoc());
auto ToLabel = importChecked(Err, E->getLabel());
auto ToType = importChecked(Err, E->getType());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) AddrLabelExpr(
ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType);
}
ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) {
Error Err = Error::success();
auto ToSubExpr = importChecked(Err, E->getSubExpr());
auto ToResult = importChecked(Err, E->getAPValueResult());
if (Err)
return std::move(Err);
return ConstantExpr::Create(Importer.getToContext(), ToSubExpr, ToResult);
}
ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
Error Err = Error::success();
auto ToLParen = importChecked(Err, E->getLParen());
auto ToRParen = importChecked(Err, E->getRParen());
auto ToSubExpr = importChecked(Err, E->getSubExpr());
if (Err)
return std::move(Err);
return new (Importer.getToContext())
ParenExpr(ToLParen, ToRParen, ToSubExpr);
}
ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
SmallVector<Expr *, 4> ToExprs(E->getNumExprs());
if (Error Err = ImportContainerChecked(E->exprs(), ToExprs))
return std::move(Err);
ExpectedSLoc ToLParenLocOrErr = import(E->getLParenLoc());
if (!ToLParenLocOrErr)
return ToLParenLocOrErr.takeError();
ExpectedSLoc ToRParenLocOrErr = import(E->getRParenLoc());
if (!ToRParenLocOrErr)
return ToRParenLocOrErr.takeError();
return ParenListExpr::Create(Importer.getToContext(), *ToLParenLocOrErr,
ToExprs, *ToRParenLocOrErr);
}
ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
Error Err = Error::success();
auto ToSubStmt = importChecked(Err, E->getSubStmt());
auto ToType = importChecked(Err, E->getType());
auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext())
StmtExpr(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc,
E->getTemplateDepth());
}
ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
Error Err = Error::success();
auto ToSubExpr = importChecked(Err, E->getSubExpr());
auto ToType = importChecked(Err, E->getType());
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
if (Err)
return std::move(Err);
return UnaryOperator::Create(
Importer.getToContext(), ToSubExpr, E->getOpcode(), ToType,
E->getValueKind(), E->getObjectKind(), ToOperatorLoc, E->canOverflow(),
E->getFPOptionsOverride());
}
ExpectedStmt
ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
if (Err)
return std::move(Err);
if (E->isArgumentType()) {
Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr =
import(E->getArgumentTypeInfo());
if (!ToArgumentTypeInfoOrErr)
return ToArgumentTypeInfoOrErr.takeError();
return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc,
ToRParenLoc);
}
ExpectedExpr ToArgumentExprOrErr = import(E->getArgumentExpr());
if (!ToArgumentExprOrErr)
return ToArgumentExprOrErr.takeError();
return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc);
}
ExpectedStmt ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
Error Err = Error::success();
auto ToLHS = importChecked(Err, E->getLHS());
auto ToRHS = importChecked(Err, E->getRHS());
auto ToType = importChecked(Err, E->getType());
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
if (Err)
return std::move(Err);
return BinaryOperator::Create(
Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType,
E->getValueKind(), E->getObjectKind(), ToOperatorLoc,
E->getFPFeatures(Importer.getFromContext().getLangOpts()));
}
ExpectedStmt ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
Error Err = Error::success();
auto ToCond = importChecked(Err, E->getCond());
auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc());
auto ToLHS = importChecked(Err, E->getLHS());
auto ToColonLoc = importChecked(Err, E->getColonLoc());
auto ToRHS = importChecked(Err, E->getRHS());
auto ToType = importChecked(Err, E->getType());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) ConditionalOperator(
ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType,
E->getValueKind(), E->getObjectKind());
}
ExpectedStmt
ASTNodeImporter::VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
Error Err = Error::success();
auto ToCommon = importChecked(Err, E->getCommon());
auto ToOpaqueValue = importChecked(Err, E->getOpaqueValue());
auto ToCond = importChecked(Err, E->getCond());
auto ToTrueExpr = importChecked(Err, E->getTrueExpr());
auto ToFalseExpr = importChecked(Err, E->getFalseExpr());
auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc());
auto ToColonLoc = importChecked(Err, E->getColonLoc());
auto ToType = importChecked(Err, E->getType());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) BinaryConditionalOperator(
ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr,
ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(),
E->getObjectKind());
}
ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
Error Err = Error::success();
auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
auto ToQueriedTypeSourceInfo =
importChecked(Err, E->getQueriedTypeSourceInfo());
auto ToDimensionExpression = importChecked(Err, E->getDimensionExpression());
auto ToEndLoc = importChecked(Err, E->getEndLoc());
auto ToType = importChecked(Err, E->getType());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) ArrayTypeTraitExpr(
ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(),
ToDimensionExpression, ToEndLoc, ToType);
}
ExpectedStmt ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
Error Err = Error::success();
auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
auto ToQueriedExpression = importChecked(Err, E->getQueriedExpression());
auto ToEndLoc = importChecked(Err, E->getEndLoc());
auto ToType = importChecked(Err, E->getType());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) ExpressionTraitExpr(
ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(),
ToEndLoc, ToType);
}
ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
Error Err = Error::success();
auto ToLocation = importChecked(Err, E->getLocation());
auto ToType = importChecked(Err, E->getType());
auto ToSourceExpr = importChecked(Err, E->getSourceExpr());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) OpaqueValueExpr(
ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr);
}
ExpectedStmt ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Error Err = Error::success();
auto ToLHS = importChecked(Err, E->getLHS());
auto ToRHS = importChecked(Err, E->getRHS());
auto ToType = importChecked(Err, E->getType());
auto ToRBracketLoc = importChecked(Err, E->getRBracketLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) ArraySubscriptExpr(
ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(),
ToRBracketLoc);
}
ExpectedStmt
ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
Error Err = Error::success();
auto ToLHS = importChecked(Err, E->getLHS());
auto ToRHS = importChecked(Err, E->getRHS());
auto ToType = importChecked(Err, E->getType());
auto ToComputationLHSType = importChecked(Err, E->getComputationLHSType());
auto ToComputationResultType =
importChecked(Err, E->getComputationResultType());
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
if (Err)
return std::move(Err);
return CompoundAssignOperator::Create(
Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType,
E->getValueKind(), E->getObjectKind(), ToOperatorLoc,
E->getFPFeatures(Importer.getFromContext().getLangOpts()),
ToComputationLHSType, ToComputationResultType);
}
Expected<CXXCastPath>
ASTNodeImporter::ImportCastPath(CastExpr *CE) {
CXXCastPath Path;
for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
if (auto SpecOrErr = import(*I))
Path.push_back(*SpecOrErr);
else
return SpecOrErr.takeError();
}
return Path;
}
ExpectedStmt ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
if (!ToSubExprOrErr)
return ToSubExprOrErr.takeError();
Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
if (!ToBasePathOrErr)
return ToBasePathOrErr.takeError();
return ImplicitCastExpr::Create(
Importer.getToContext(), *ToTypeOrErr, E->getCastKind(), *ToSubExprOrErr,
&(*ToBasePathOrErr), E->getValueKind(), E->getFPFeatures());
}
ExpectedStmt ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToSubExpr = importChecked(Err, E->getSubExpr());
auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten());
if (Err)
return std::move(Err);
Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
if (!ToBasePathOrErr)
return ToBasePathOrErr.takeError();
CXXCastPath *ToBasePath = &(*ToBasePathOrErr);
switch (E->getStmtClass()) {
case Stmt::CStyleCastExprClass: {
auto *CCE = cast<CStyleCastExpr>(E);
ExpectedSLoc ToLParenLocOrErr = import(CCE->getLParenLoc());
if (!ToLParenLocOrErr)
return ToLParenLocOrErr.takeError();
ExpectedSLoc ToRParenLocOrErr = import(CCE->getRParenLoc());
if (!ToRParenLocOrErr)
return ToRParenLocOrErr.takeError();
return CStyleCastExpr::Create(
Importer.getToContext(), ToType, E->getValueKind(), E->getCastKind(),
ToSubExpr, ToBasePath, CCE->getFPFeatures(), ToTypeInfoAsWritten,
*ToLParenLocOrErr, *ToRParenLocOrErr);
}
case Stmt::CXXFunctionalCastExprClass: {
auto *FCE = cast<CXXFunctionalCastExpr>(E);
ExpectedSLoc ToLParenLocOrErr = import(FCE->getLParenLoc());
if (!ToLParenLocOrErr)
return ToLParenLocOrErr.takeError();
ExpectedSLoc ToRParenLocOrErr = import(FCE->getRParenLoc());
if (!ToRParenLocOrErr)
return ToRParenLocOrErr.takeError();
return CXXFunctionalCastExpr::Create(
Importer.getToContext(), ToType, E->getValueKind(), ToTypeInfoAsWritten,
E->getCastKind(), ToSubExpr, ToBasePath, FCE->getFPFeatures(),
*ToLParenLocOrErr, *ToRParenLocOrErr);
}
case Stmt::ObjCBridgedCastExprClass: {
auto *OCE = cast<ObjCBridgedCastExpr>(E);
ExpectedSLoc ToLParenLocOrErr = import(OCE->getLParenLoc());
if (!ToLParenLocOrErr)
return ToLParenLocOrErr.takeError();
ExpectedSLoc ToBridgeKeywordLocOrErr = import(OCE->getBridgeKeywordLoc());
if (!ToBridgeKeywordLocOrErr)
return ToBridgeKeywordLocOrErr.takeError();
return new (Importer.getToContext()) ObjCBridgedCastExpr(
*ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(),
*ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr);
}
default:
llvm_unreachable("Cast expression of unsupported type!");
return make_error<ImportError>(ImportError::UnsupportedConstruct);
}
}
ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) {
SmallVector<OffsetOfNode, 4> ToNodes;
for (int I = 0, N = E->getNumComponents(); I < N; ++I) {
const OffsetOfNode &FromNode = E->getComponent(I);
SourceLocation ToBeginLoc, ToEndLoc;
if (FromNode.getKind() != OffsetOfNode::Base) {
Error Err = Error::success();
ToBeginLoc = importChecked(Err, FromNode.getBeginLoc());
ToEndLoc = importChecked(Err, FromNode.getEndLoc());
if (Err)
return std::move(Err);
}
switch (FromNode.getKind()) {
case OffsetOfNode::Array:
ToNodes.push_back(
OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc));
break;
case OffsetOfNode::Base: {
auto ToBSOrErr = import(FromNode.getBase());
if (!ToBSOrErr)
return ToBSOrErr.takeError();
ToNodes.push_back(OffsetOfNode(*ToBSOrErr));
break;
}
case OffsetOfNode::Field: {
auto ToFieldOrErr = import(FromNode.getField());
if (!ToFieldOrErr)
return ToFieldOrErr.takeError();
ToNodes.push_back(OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc));
break;
}
case OffsetOfNode::Identifier: {
IdentifierInfo *ToII = Importer.Import(FromNode.getFieldName());
ToNodes.push_back(OffsetOfNode(ToBeginLoc, ToII, ToEndLoc));
break;
}
}
}
SmallVector<Expr *, 4> ToExprs(E->getNumExpressions());
for (int I = 0, N = E->getNumExpressions(); I < N; ++I) {
ExpectedExpr ToIndexExprOrErr = import(E->getIndexExpr(I));
if (!ToIndexExprOrErr)
return ToIndexExprOrErr.takeError();
ToExprs[I] = *ToIndexExprOrErr;
}
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
if (Err)
return std::move(Err);
return OffsetOfExpr::Create(
Importer.getToContext(), ToType, ToOperatorLoc, ToTypeSourceInfo, ToNodes,
ToExprs, ToRParenLoc);
}
ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToOperand = importChecked(Err, E->getOperand());
auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
auto ToEndLoc = importChecked(Err, E->getEndLoc());
if (Err)
return std::move(Err);
CanThrowResult ToCanThrow;
if (E->isValueDependent())
ToCanThrow = CT_Dependent;
else
ToCanThrow = E->getValue() ? CT_Can : CT_Cannot;
return new (Importer.getToContext()) CXXNoexceptExpr(
ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc);
}
ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) {
Error Err = Error::success();
auto ToSubExpr = importChecked(Err, E->getSubExpr());
auto ToType = importChecked(Err, E->getType());
auto ToThrowLoc = importChecked(Err, E->getThrowLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) CXXThrowExpr(
ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope());
}
ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
ExpectedSLoc ToUsedLocOrErr = import(E->getUsedLocation());
if (!ToUsedLocOrErr)
return ToUsedLocOrErr.takeError();
auto ToParamOrErr = import(E->getParam());
if (!ToParamOrErr)
return ToParamOrErr.takeError();
auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext());
if (!UsedContextOrErr)
return UsedContextOrErr.takeError();
// Import the default arg if it was not imported yet.
// This is needed because it can happen that during the import of the
// default expression (from VisitParmVarDecl) the same ParmVarDecl is
// encountered here. The default argument for a ParmVarDecl is set in the
// ParmVarDecl only after it is imported (set in VisitParmVarDecl if not here,
// see VisitParmVarDecl).
ParmVarDecl *ToParam = *ToParamOrErr;
if (!ToParam->getDefaultArg()) {
Optional<ParmVarDecl *> FromParam = Importer.getImportedFromDecl(ToParam);
assert(FromParam && "ParmVarDecl was not imported?");
if (Error Err = ImportDefaultArgOfParmVarDecl(*FromParam, ToParam))
return std::move(Err);
}
return CXXDefaultArgExpr::Create(Importer.getToContext(), *ToUsedLocOrErr,
*ToParamOrErr, *UsedContextOrErr);
}
ExpectedStmt
ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) CXXScalarValueInitExpr(
ToType, ToTypeSourceInfo, ToRParenLoc);
}
ExpectedStmt
ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
if (!ToSubExprOrErr)
return ToSubExprOrErr.takeError();
auto ToDtorOrErr = import(E->getTemporary()->getDestructor());
if (!ToDtorOrErr)
return ToDtorOrErr.takeError();
ASTContext &ToCtx = Importer.getToContext();
CXXTemporary *Temp = CXXTemporary::Create(ToCtx, *ToDtorOrErr);
return CXXBindTemporaryExpr::Create(ToCtx, Temp, *ToSubExprOrErr);
}
ExpectedStmt
ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
Error Err = Error::success();
auto ToConstructor = importChecked(Err, E->getConstructor());
auto ToType = importChecked(Err, E->getType());
auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange());
if (Err)
return std::move(Err);
SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
return std::move(Err);
return CXXTemporaryObjectExpr::Create(
Importer.getToContext(), ToConstructor, ToType, ToTypeSourceInfo, ToArgs,
ToParenOrBraceRange, E->hadMultipleCandidates(),
E->isListInitialization(), E->isStdInitListInitialization(),
E->requiresZeroInitialization());
}
ExpectedDecl ASTNodeImporter::VisitLifetimeExtendedTemporaryDecl(
LifetimeExtendedTemporaryDecl *D) {
DeclContext *DC, *LexicalDC;
if (Error Err = ImportDeclContext(D, DC, LexicalDC))
return std::move(Err);
Error Err = Error::success();
auto Temporary = importChecked(Err, D->getTemporaryExpr());
auto ExtendingDecl = importChecked(Err, D->getExtendingDecl());
if (Err)
return std::move(Err);
// FIXME: Should ManglingNumber get numbers associated with 'to' context?
LifetimeExtendedTemporaryDecl *To;
if (GetImportedOrCreateDecl(To, D, Temporary, ExtendingDecl,
D->getManglingNumber()))
return To;
To->setLexicalDeclContext(LexicalDC);
LexicalDC->addDeclInternal(To);
return To;
}
ExpectedStmt
ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
Expr *ToTemporaryExpr = importChecked(
Err, E->getLifetimeExtendedTemporaryDecl() ? nullptr : E->getSubExpr());
auto ToMaterializedDecl =
importChecked(Err, E->getLifetimeExtendedTemporaryDecl());
if (Err)
return std::move(Err);
if (!ToTemporaryExpr)
ToTemporaryExpr = cast<Expr>(ToMaterializedDecl->getTemporaryExpr());
auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr(
ToType, ToTemporaryExpr, E->isBoundToLvalueReference(),
ToMaterializedDecl);
return ToMTE;
}
ExpectedStmt ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToPattern = importChecked(Err, E->getPattern());
auto ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) PackExpansionExpr(
ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions());
}
ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Error Err = Error::success();
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
auto ToPack = importChecked(Err, E->getPack());
auto ToPackLoc = importChecked(Err, E->getPackLoc());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
if (Err)
return std::move(Err);
Optional<unsigned> Length;
if (!E->isValueDependent())
Length = E->getPackLength();
SmallVector<TemplateArgument, 8> ToPartialArguments;
if (E->isPartiallySubstituted()) {
if (Error Err = ImportTemplateArguments(
E->getPartialArguments().data(),
E->getPartialArguments().size(),
ToPartialArguments))
return std::move(Err);
}
return SizeOfPackExpr::Create(
Importer.getToContext(), ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc,
Length, ToPartialArguments);
}
ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) {
Error Err = Error::success();
auto ToOperatorNew = importChecked(Err, E->getOperatorNew());
auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete());
auto ToTypeIdParens = importChecked(Err, E->getTypeIdParens());
auto ToArraySize = importChecked(Err, E->getArraySize());
auto ToInitializer = importChecked(Err, E->getInitializer());
auto ToType = importChecked(Err, E->getType());
auto ToAllocatedTypeSourceInfo =
importChecked(Err, E->getAllocatedTypeSourceInfo());
auto ToSourceRange = importChecked(Err, E->getSourceRange());
auto ToDirectInitRange = importChecked(Err, E->getDirectInitRange());
if (Err)
return std::move(Err);
SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs());
if (Error Err =
ImportContainerChecked(E->placement_arguments(), ToPlacementArgs))
return std::move(Err);
return CXXNewExpr::Create(
Importer.getToContext(), E->isGlobalNew(), ToOperatorNew,
ToOperatorDelete, E->passAlignment(), E->doesUsualArrayDeleteWantSize(),
ToPlacementArgs, ToTypeIdParens, ToArraySize, E->getInitializationStyle(),
ToInitializer, ToType, ToAllocatedTypeSourceInfo, ToSourceRange,
ToDirectInitRange);
}
ExpectedStmt ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete());
auto ToArgument = importChecked(Err, E->getArgument());
auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) CXXDeleteExpr(
ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(),
E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument,
ToBeginLoc);
}
ExpectedStmt ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToLocation = importChecked(Err, E->getLocation());
auto ToConstructor = importChecked(Err, E->getConstructor());
auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange());
if (Err)
return std::move(Err);
SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
return std::move(Err);
return CXXConstructExpr::Create(
Importer.getToContext(), ToType, ToLocation, ToConstructor,
E->isElidable(), ToArgs, E->hadMultipleCandidates(),
E->isListInitialization(), E->isStdInitListInitialization(),
E->requiresZeroInitialization(), E->getConstructionKind(),
ToParenOrBraceRange);
}
ExpectedStmt ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) {
ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
if (!ToSubExprOrErr)
return ToSubExprOrErr.takeError();
SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects());
if (Error Err = ImportContainerChecked(E->getObjects(), ToObjects))
return std::move(Err);
return ExprWithCleanups::Create(
Importer.getToContext(), *ToSubExprOrErr, E->cleanupsHaveSideEffects(),
ToObjects);
}
ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
Error Err = Error::success();
auto ToCallee = importChecked(Err, E->getCallee());
auto ToType = importChecked(Err, E->getType());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
if (Err)
return std::move(Err);
SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
return std::move(Err);
return CXXMemberCallExpr::Create(Importer.getToContext(), ToCallee, ToArgs,
ToType, E->getValueKind(), ToRParenLoc,
E->getFPFeatures());
}
ExpectedStmt ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedSLoc ToLocationOrErr = import(E->getLocation());
if (!ToLocationOrErr)
return ToLocationOrErr.takeError();
return new (Importer.getToContext()) CXXThisExpr(
*ToLocationOrErr, *ToTypeOrErr, E->isImplicit());
}
ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedSLoc ToLocationOrErr = import(E->getLocation());
if (!ToLocationOrErr)
return ToLocationOrErr.takeError();
return new (Importer.getToContext()) CXXBoolLiteralExpr(
E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
}
ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
Error Err = Error::success();
auto ToBase = importChecked(Err, E->getBase());
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
auto ToMemberDecl = importChecked(Err, E->getMemberDecl());
auto ToType = importChecked(Err, E->getType());
auto ToDecl = importChecked(Err, E->getFoundDecl().getDecl());
auto ToName = importChecked(Err, E->getMemberNameInfo().getName());
auto ToLoc = importChecked(Err, E->getMemberNameInfo().getLoc());
if (Err)
return std::move(Err);
DeclAccessPair ToFoundDecl =
DeclAccessPair::make(ToDecl, E->getFoundDecl().getAccess());
DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc);
TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
if (E->hasExplicitTemplateArgs()) {
if (Error Err =
ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
E->template_arguments(), ToTAInfo))
return std::move(Err);
ResInfo = &ToTAInfo;
}
return MemberExpr::Create(Importer.getToContext(), ToBase, E->isArrow(),
ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
ToMemberDecl, ToFoundDecl, ToMemberNameInfo,
ResInfo, ToType, E->getValueKind(),
E->getObjectKind(), E->isNonOdrUse());
}
ExpectedStmt
ASTNodeImporter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
Error Err = Error::success();
auto ToBase = importChecked(Err, E->getBase());
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
auto ToScopeTypeInfo = importChecked(Err, E->getScopeTypeInfo());
auto ToColonColonLoc = importChecked(Err, E->getColonColonLoc());
auto ToTildeLoc = importChecked(Err, E->getTildeLoc());
if (Err)
return std::move(Err);
PseudoDestructorTypeStorage Storage;
if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) {
IdentifierInfo *ToII = Importer.Import(FromII);
ExpectedSLoc ToDestroyedTypeLocOrErr = import(E->getDestroyedTypeLoc());
if (!ToDestroyedTypeLocOrErr)
return ToDestroyedTypeLocOrErr.takeError();
Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr);
} else {
if (auto ToTIOrErr = import(E->getDestroyedTypeInfo()))
Storage = PseudoDestructorTypeStorage(*ToTIOrErr);
else
return ToTIOrErr.takeError();
}
return new (Importer.getToContext()) CXXPseudoDestructorExpr(
Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc,
ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage);
}
ExpectedStmt ASTNodeImporter::VisitCXXDependentScopeMemberExpr(
CXXDependentScopeMemberExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
auto ToFirstQualifierFoundInScope =
importChecked(Err, E->getFirstQualifierFoundInScope());
if (Err)
return std::move(Err);
Expr *ToBase = nullptr;
if (!E->isImplicitAccess()) {
if (ExpectedExpr ToBaseOrErr = import(E->getBase()))
ToBase = *ToBaseOrErr;
else
return ToBaseOrErr.takeError();
}
TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
if (E->hasExplicitTemplateArgs()) {
if (Error Err =
ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
E->template_arguments(), ToTAInfo))
return std::move(Err);
ResInfo = &ToTAInfo;
}
auto ToMember = importChecked(Err, E->getMember());
auto ToMemberLoc = importChecked(Err, E->getMemberLoc());
if (Err)
return std::move(Err);
DeclarationNameInfo ToMemberNameInfo(ToMember, ToMemberLoc);
// Import additional name location/type info.
if (Error Err =
ImportDeclarationNameLoc(E->getMemberNameInfo(), ToMemberNameInfo))
return std::move(Err);
return CXXDependentScopeMemberExpr::Create(
Importer.getToContext(), ToBase, ToType, E->isArrow(), ToOperatorLoc,
ToQualifierLoc, ToTemplateKeywordLoc, ToFirstQualifierFoundInScope,
ToMemberNameInfo, ResInfo);
}
ExpectedStmt
ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
Error Err = Error::success();
auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
auto ToDeclName = importChecked(Err, E->getDeclName());
auto ToNameLoc = importChecked(Err, E->getNameInfo().getLoc());
auto ToLAngleLoc = importChecked(Err, E->getLAngleLoc());
auto ToRAngleLoc = importChecked(Err, E->getRAngleLoc());
if (Err)
return std::move(Err);
DeclarationNameInfo ToNameInfo(ToDeclName, ToNameLoc);
if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
return std::move(Err);
TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc);
TemplateArgumentListInfo *ResInfo = nullptr;
if (E->hasExplicitTemplateArgs()) {
if (Error Err =
ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
return std::move(Err);
ResInfo = &ToTAInfo;
}
return DependentScopeDeclRefExpr::Create(
Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc,
ToNameInfo, ResInfo);
}
ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr(
CXXUnresolvedConstructExpr *E) {
Error Err = Error::success();
auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
auto ToType = importChecked(Err, E->getType());
auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
if (Err)
return std::move(Err);
SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
if (Error Err =
ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin()))
return std::move(Err);
return CXXUnresolvedConstructExpr::Create(
Importer.getToContext(), ToType, ToTypeSourceInfo, ToLParenLoc,
llvm::makeArrayRef(ToArgs), ToRParenLoc);
}
ExpectedStmt
ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
Expected<CXXRecordDecl *> ToNamingClassOrErr = import(E->getNamingClass());
if (!ToNamingClassOrErr)
return ToNamingClassOrErr.takeError();
auto ToQualifierLocOrErr = import(E->getQualifierLoc());
if (!ToQualifierLocOrErr)
return ToQualifierLocOrErr.takeError();
Error Err = Error::success();
auto ToName = importChecked(Err, E->getName());
auto ToNameLoc = importChecked(Err, E->getNameLoc());
if (Err)
return std::move(Err);
DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
// Import additional name location/type info.
if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
return std::move(Err);
UnresolvedSet<8> ToDecls;
for (auto *D : E->decls())
if (auto ToDOrErr = import(D))
ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
else
return ToDOrErr.takeError();
if (E->hasExplicitTemplateArgs()) {
TemplateArgumentListInfo ToTAInfo;
if (Error Err = ImportTemplateArgumentListInfo(
E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(),
ToTAInfo))
return std::move(Err);
ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc());
if (!ToTemplateKeywordLocOrErr)
return ToTemplateKeywordLocOrErr.takeError();
return UnresolvedLookupExpr::Create(
Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
*ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo,
ToDecls.begin(), ToDecls.end());
}
return UnresolvedLookupExpr::Create(
Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
ToNameInfo, E->requiresADL(), E->isOverloaded(), ToDecls.begin(),
ToDecls.end());
}
ExpectedStmt
ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
auto ToName = importChecked(Err, E->getName());
auto ToNameLoc = importChecked(Err, E->getNameLoc());
if (Err)
return std::move(Err);
DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
// Import additional name location/type info.
if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
return std::move(Err);
UnresolvedSet<8> ToDecls;
for (Decl *D : E->decls())
if (auto ToDOrErr = import(D))
ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
else
return ToDOrErr.takeError();
TemplateArgumentListInfo ToTAInfo;
TemplateArgumentListInfo *ResInfo = nullptr;
if (E->hasExplicitTemplateArgs()) {
TemplateArgumentListInfo FromTAInfo;
E->copyTemplateArgumentsInto(FromTAInfo);
if (Error Err = ImportTemplateArgumentListInfo(FromTAInfo, ToTAInfo))
return std::move(Err);
ResInfo = &ToTAInfo;
}
Expr *ToBase = nullptr;
if (!E->isImplicitAccess()) {
if (ExpectedExpr ToBaseOrErr = import(E->getBase()))
ToBase = *ToBaseOrErr;
else
return ToBaseOrErr.takeError();
}
return UnresolvedMemberExpr::Create(
Importer.getToContext(), E->hasUnresolvedUsing(), ToBase, ToType,
E->isArrow(), ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
ToNameInfo, ResInfo, ToDecls.begin(), ToDecls.end());
}
ExpectedStmt ASTNodeImporter::VisitCallExpr(CallExpr *E) {
Error Err = Error::success();
auto ToCallee = importChecked(Err, E->getCallee());
auto ToType = importChecked(Err, E->getType());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
if (Err)
return std::move(Err);
unsigned NumArgs = E->getNumArgs();
llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
return std::move(Err);
if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
return CXXOperatorCallExpr::Create(
Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, ToType,
OCE->getValueKind(), ToRParenLoc, OCE->getFPFeatures(),
OCE->getADLCallKind());
}
return CallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, ToType,
E->getValueKind(), ToRParenLoc, E->getFPFeatures(),
/*MinNumArgs=*/0, E->getADLCallKind());
}
ExpectedStmt ASTNodeImporter::VisitLambdaExpr(LambdaExpr *E) {
CXXRecordDecl *FromClass = E->getLambdaClass();
auto ToClassOrErr = import(FromClass);
if (!ToClassOrErr)
return ToClassOrErr.takeError();
CXXRecordDecl *ToClass = *ToClassOrErr;
auto ToCallOpOrErr = import(E->getCallOperator());
if (!ToCallOpOrErr)
return ToCallOpOrErr.takeError();
SmallVector<Expr *, 8> ToCaptureInits(E->capture_size());
if (Error Err = ImportContainerChecked(E->capture_inits(), ToCaptureInits))
return std::move(Err);
Error Err = Error::success();
auto ToIntroducerRange = importChecked(Err, E->getIntroducerRange());
auto ToCaptureDefaultLoc = importChecked(Err, E->getCaptureDefaultLoc());
auto ToEndLoc = importChecked(Err, E->getEndLoc());
if (Err)
return std::move(Err);
return LambdaExpr::Create(Importer.getToContext(), ToClass, ToIntroducerRange,
E->getCaptureDefault(), ToCaptureDefaultLoc,
E->hasExplicitParameters(),
E->hasExplicitResultType(), ToCaptureInits,
ToEndLoc, E->containsUnexpandedParameterPack());
}
ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) {
Error Err = Error::success();
auto ToLBraceLoc = importChecked(Err, E->getLBraceLoc());
auto ToRBraceLoc = importChecked(Err, E->getRBraceLoc());
auto ToType = importChecked(Err, E->getType());
if (Err)
return std::move(Err);
SmallVector<Expr *, 4> ToExprs(E->getNumInits());
if (Error Err = ImportContainerChecked(E->inits(), ToExprs))
return std::move(Err);
ASTContext &ToCtx = Importer.getToContext();
InitListExpr *To = new (ToCtx) InitListExpr(
ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc);
To->setType(ToType);
if (E->hasArrayFiller()) {
if (ExpectedExpr ToFillerOrErr = import(E->getArrayFiller()))
To->setArrayFiller(*ToFillerOrErr);
else
return ToFillerOrErr.takeError();
}
if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) {
if (auto ToFDOrErr = import(FromFD))
To->setInitializedFieldInUnion(*ToFDOrErr);
else
return ToFDOrErr.takeError();
}
if (InitListExpr *SyntForm = E->getSyntacticForm()) {
if (auto ToSyntFormOrErr = import(SyntForm))
To->setSyntacticForm(*ToSyntFormOrErr);
else
return ToSyntFormOrErr.takeError();
}
// Copy InitListExprBitfields, which are not handled in the ctor of
// InitListExpr.
To->sawArrayRangeDesignator(E->hadArrayRangeDesignator());
return To;
}
ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr(
CXXStdInitializerListExpr *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
if (!ToSubExprOrErr)
return ToSubExprOrErr.takeError();
return new (Importer.getToContext()) CXXStdInitializerListExpr(
*ToTypeOrErr, *ToSubExprOrErr);
}
ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr(
CXXInheritedCtorInitExpr *E) {
Error Err = Error::success();
auto ToLocation = importChecked(Err, E->getLocation());
auto ToType = importChecked(Err, E->getType());
auto ToConstructor = importChecked(Err, E->getConstructor());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) CXXInheritedCtorInitExpr(
ToLocation, ToType, ToConstructor, E->constructsVBase(),
E->inheritedFromVBase());
}
ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToCommonExpr = importChecked(Err, E->getCommonExpr());
auto ToSubExpr = importChecked(Err, E->getSubExpr());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) ArrayInitLoopExpr(
ToType, ToCommonExpr, ToSubExpr);
}
ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr);
}
ExpectedStmt ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
ExpectedSLoc ToBeginLocOrErr = import(E->getBeginLoc());
if (!ToBeginLocOrErr)
return ToBeginLocOrErr.takeError();
auto ToFieldOrErr = import(E->getField());
if (!ToFieldOrErr)
return ToFieldOrErr.takeError();
auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext());
if (!UsedContextOrErr)
return UsedContextOrErr.takeError();
return CXXDefaultInitExpr::Create(
Importer.getToContext(), *ToBeginLocOrErr, *ToFieldOrErr, *UsedContextOrErr);
}
ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToSubExpr = importChecked(Err, E->getSubExpr());
auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten());
auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
auto ToAngleBrackets = importChecked(Err, E->getAngleBrackets());
if (Err)
return std::move(Err);
ExprValueKind VK = E->getValueKind();
CastKind CK = E->getCastKind();
auto ToBasePathOrErr = ImportCastPath(E);
if (!ToBasePathOrErr)
return ToBasePathOrErr.takeError();
if (auto CCE = dyn_cast<CXXStaticCastExpr>(E)) {
return CXXStaticCastExpr::Create(
Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
ToTypeInfoAsWritten, CCE->getFPFeatures(), ToOperatorLoc, ToRParenLoc,
ToAngleBrackets);
} else if (isa<CXXDynamicCastExpr>(E)) {
return CXXDynamicCastExpr::Create(
Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
} else if (isa<CXXReinterpretCastExpr>(E)) {
return CXXReinterpretCastExpr::Create(
Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
} else if (isa<CXXConstCastExpr>(E)) {
return CXXConstCastExpr::Create(
Importer.getToContext(), ToType, VK, ToSubExpr, ToTypeInfoAsWritten,
ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
} else {
llvm_unreachable("Unknown cast type");
return make_error<ImportError>();
}
}
ExpectedStmt ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr(
SubstNonTypeTemplateParmExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToExprLoc = importChecked(Err, E->getExprLoc());
auto ToParameter = importChecked(Err, E->getParameter());
auto ToReplacement = importChecked(Err, E->getReplacement());
if (Err)
return std::move(Err);
return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr(
ToType, E->getValueKind(), ToExprLoc, ToParameter,
E->isReferenceParameter(), ToReplacement);
}
ExpectedStmt ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) {
Error Err = Error::success();
auto ToType = importChecked(Err, E->getType());
auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
auto ToEndLoc = importChecked(Err, E->getEndLoc());
if (Err)
return std::move(Err);
SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs());
if (Error Err = ImportContainerChecked(E->getArgs(), ToArgs))
return std::move(Err);
// According to Sema::BuildTypeTrait(), if E is value-dependent,
// Value is always false.
bool ToValue = (E->isValueDependent() ? false : E->getValue());
return TypeTraitExpr::Create(
Importer.getToContext(), ToType, ToBeginLoc, E->getTrait(), ToArgs,
ToEndLoc, ToValue);
}
ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
ExpectedType ToTypeOrErr = import(E->getType());
if (!ToTypeOrErr)
return ToTypeOrErr.takeError();
auto ToSourceRangeOrErr = import(E->getSourceRange());
if (!ToSourceRangeOrErr)
return ToSourceRangeOrErr.takeError();
if (E->isTypeOperand()) {
if (auto ToTSIOrErr = import(E->getTypeOperandSourceInfo()))
return new (Importer.getToContext()) CXXTypeidExpr(
*ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr);
else
return ToTSIOrErr.takeError();
}
ExpectedExpr ToExprOperandOrErr = import(E->getExprOperand());
if (!ToExprOperandOrErr)
return ToExprOperandOrErr.takeError();
return new (Importer.getToContext()) CXXTypeidExpr(
*ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr);
}
ExpectedStmt ASTNodeImporter::VisitCXXFoldExpr(CXXFoldExpr *E) {
Error Err = Error::success();
QualType ToType = importChecked(Err, E->getType());
UnresolvedLookupExpr *ToCallee = importChecked(Err, E->getCallee());
SourceLocation ToLParenLoc = importChecked(Err, E->getLParenLoc());
Expr *ToLHS = importChecked(Err, E->getLHS());
SourceLocation ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc());
Expr *ToRHS = importChecked(Err, E->getRHS());
SourceLocation ToRParenLoc = importChecked(Err, E->getRParenLoc());
if (Err)
return std::move(Err);
return new (Importer.getToContext())
CXXFoldExpr(ToType, ToCallee, ToLParenLoc, ToLHS, E->getOperator(),
ToEllipsisLoc, ToRHS, ToRParenLoc, E->getNumExpansions());
}
Error ASTNodeImporter::ImportOverriddenMethods(CXXMethodDecl *ToMethod,
CXXMethodDecl *FromMethod) {
Error ImportErrors = Error::success();
for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) {
if (auto ImportedOrErr = import(FromOverriddenMethod))
ToMethod->getCanonicalDecl()->addOverriddenMethod(cast<CXXMethodDecl>(
(*ImportedOrErr)->getCanonicalDecl()));
else
ImportErrors =
joinErrors(std::move(ImportErrors), ImportedOrErr.takeError());
}
return ImportErrors;
}
ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
ASTContext &FromContext, FileManager &FromFileManager,
bool MinimalImport,
std::shared_ptr<ASTImporterSharedState> SharedState)
: SharedState(SharedState), ToContext(ToContext), FromContext(FromContext),
ToFileManager(ToFileManager), FromFileManager(FromFileManager),
Minimal(MinimalImport), ODRHandling(ODRHandlingType::Conservative) {
// Create a default state without the lookup table: LLDB case.
if (!SharedState) {
this->SharedState = std::make_shared<ASTImporterSharedState>();
}
ImportedDecls[FromContext.getTranslationUnitDecl()] =
ToContext.getTranslationUnitDecl();
}
ASTImporter::~ASTImporter() = default;
Optional<unsigned> ASTImporter::getFieldIndex(Decl *F) {
assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) &&
"Try to get field index for non-field.");
auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
if (!Owner)
return None;
unsigned Index = 0;
for (const auto *D : Owner->decls()) {
if (D == F)
return Index;
if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
++Index;
}
llvm_unreachable("Field was not found in its parent context.");
return None;
}
ASTImporter::FoundDeclsTy
ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) {
// We search in the redecl context because of transparent contexts.
// E.g. a simple C language enum is a transparent context:
// enum E { A, B };
// Now if we had a global variable in the TU
// int A;
// then the enum constant 'A' and the variable 'A' violates ODR.
// We can diagnose this only if we search in the redecl context.
DeclContext *ReDC = DC->getRedeclContext();
if (SharedState->getLookupTable()) {
ASTImporterLookupTable::LookupResult LookupResult =
SharedState->getLookupTable()->lookup(ReDC, Name);
return FoundDeclsTy(LookupResult.begin(), LookupResult.end());
} else {
DeclContext::lookup_result NoloadLookupResult = ReDC->noload_lookup(Name);
FoundDeclsTy Result(NoloadLookupResult.begin(), NoloadLookupResult.end());
// We must search by the slow case of localUncachedLookup because that is
// working even if there is no LookupPtr for the DC. We could use
// DC::buildLookup() to create the LookupPtr, but that would load external
// decls again, we must avoid that case.
// Also, even if we had the LookupPtr, we must find Decls which are not
// in the LookupPtr, so we need the slow case.
// These cases are handled in ASTImporterLookupTable, but we cannot use
// that with LLDB since that traverses through the AST which initiates the
// load of external decls again via DC::decls(). And again, we must avoid
// loading external decls during the import.
if (Result.empty())
ReDC->localUncachedLookup(Name, Result);
return Result;
}
}
void ASTImporter::AddToLookupTable(Decl *ToD) {
SharedState->addDeclToLookup(ToD);
}
Expected<Decl *> ASTImporter::ImportImpl(Decl *FromD) {
// Import the decl using ASTNodeImporter.
ASTNodeImporter Importer(*this);
return Importer.Visit(FromD);
}
void ASTImporter::RegisterImportedDecl(Decl *FromD, Decl *ToD) {
MapImported(FromD, ToD);
}
llvm::Expected<ExprWithCleanups::CleanupObject>
ASTImporter::Import(ExprWithCleanups::CleanupObject From) {
if (auto *CLE = From.dyn_cast<CompoundLiteralExpr *>()) {
if (Expected<Expr *> R = Import(CLE))
return ExprWithCleanups::CleanupObject(cast<CompoundLiteralExpr>(*R));
}
// FIXME: Handle BlockDecl when we implement importing BlockExpr in
// ASTNodeImporter.
return make_error<ImportError>(ImportError::UnsupportedConstruct);
}
Expected<QualType> ASTImporter::Import(QualType FromT) {
if (FromT.isNull())
return QualType{};
const Type *FromTy = FromT.getTypePtr();
// Check whether we've already imported this type.
llvm::DenseMap<const Type *, const Type *>::iterator Pos
= ImportedTypes.find(FromTy);
if (Pos != ImportedTypes.end())
return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
// Import the type
ASTNodeImporter Importer(*this);
ExpectedType ToTOrErr = Importer.Visit(FromTy);
if (!ToTOrErr)
return ToTOrErr.takeError();
// Record the imported type.
ImportedTypes[FromTy] = (*ToTOrErr).getTypePtr();
return ToContext.getQualifiedType(*ToTOrErr, FromT.getLocalQualifiers());
}
Expected<TypeSourceInfo *> ASTImporter::Import(TypeSourceInfo *FromTSI) {
if (!FromTSI)
return FromTSI;
// FIXME: For now we just create a "trivial" type source info based
// on the type and a single location. Implement a real version of this.
ExpectedType TOrErr = Import(FromTSI->getType());
if (!TOrErr)
return TOrErr.takeError();
ExpectedSLoc BeginLocOrErr = Import(FromTSI->getTypeLoc().getBeginLoc());
if (!BeginLocOrErr)
return BeginLocOrErr.takeError();
return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr);
}
Expected<Attr *> ASTImporter::Import(const Attr *FromAttr) {
Attr *ToAttr = nullptr;
SourceRange ToRange;
if (Error Err = importInto(ToRange, FromAttr->getRange()))
return std::move(Err);
// FIXME: Is there some kind of AttrVisitor to use here?
switch (FromAttr->getKind()) {
case attr::Aligned: {
auto *From = cast<AlignedAttr>(FromAttr);
AlignedAttr *To;
auto CreateAlign = [&](bool IsAlignmentExpr, void *Alignment) {
return AlignedAttr::Create(ToContext, IsAlignmentExpr, Alignment, ToRange,
From->getSyntax(),
From->getSemanticSpelling());
};
if (From->isAlignmentExpr()) {
if (auto ToEOrErr = Import(From->getAlignmentExpr()))
To = CreateAlign(true, *ToEOrErr);
else
return ToEOrErr.takeError();
} else {
if (auto ToTOrErr = Import(From->getAlignmentType()))
To = CreateAlign(false, *ToTOrErr);
else
return ToTOrErr.takeError();
}
To->setInherited(From->isInherited());
To->setPackExpansion(From->isPackExpansion());
To->setImplicit(From->isImplicit());
ToAttr = To;
break;
}
case attr::Format: {
const auto *From = cast<FormatAttr>(FromAttr);
FormatAttr *To;
IdentifierInfo *ToAttrType = Import(From->getType());
To = FormatAttr::Create(ToContext, ToAttrType, From->getFormatIdx(),
From->getFirstArg(), ToRange, From->getSyntax());
To->setInherited(From->isInherited());
ToAttr = To;
break;
}
default:
// FIXME: 'clone' copies every member but some of them should be imported.
// Handle other Attrs that have parameters that should be imported.
ToAttr = FromAttr->clone(ToContext);
ToAttr->setRange(ToRange);
break;
}
assert(ToAttr && "Attribute should be created.");
return ToAttr;
}
Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const {
auto Pos = ImportedDecls.find(FromD);
if (Pos != ImportedDecls.end())
return Pos->second;
else
return nullptr;
}
TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) {
auto FromDPos = ImportedFromDecls.find(ToD);
if (FromDPos == ImportedFromDecls.end())
return nullptr;
return FromDPos->second->getTranslationUnitDecl();
}
Expected<Decl *> ASTImporter::Import(Decl *FromD) {
if (!FromD)
return nullptr;
// Push FromD to the stack, and remove that when we return.
ImportPath.push(FromD);
auto ImportPathBuilder =
llvm::make_scope_exit([this]() { ImportPath.pop(); });
// Check whether there was a previous failed import.
// If yes return the existing error.
if (auto Error = getImportDeclErrorIfAny(FromD))
return make_error<ImportError>(*Error);
// Check whether we've already imported this declaration.
Decl *ToD = GetAlreadyImportedOrNull(FromD);
if (ToD) {
// Already imported (possibly from another TU) and with an error.
if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
setImportDeclError(FromD, *Error);
return make_error<ImportError>(*Error);
}
// If FromD has some updated flags after last import, apply it.
updateFlags(FromD, ToD);
// If we encounter a cycle during an import then we save the relevant part
// of the import path associated to the Decl.
if (ImportPath.hasCycleAtBack())
SavedImportPaths[FromD].push_back(ImportPath.copyCycleAtBack());
return ToD;
}
// Import the declaration.
ExpectedDecl ToDOrErr = ImportImpl(FromD);
if (!ToDOrErr) {
// Failed to import.
auto Pos = ImportedDecls.find(FromD);
if (Pos != ImportedDecls.end()) {
// Import failed after the object was created.
// Remove all references to it.
auto *ToD = Pos->second;
ImportedDecls.erase(Pos);
// ImportedDecls and ImportedFromDecls are not symmetric. It may happen
// (e.g. with namespaces) that several decls from the 'from' context are
// mapped to the same decl in the 'to' context. If we removed entries
// from the LookupTable here then we may end up removing them multiple
// times.
// The Lookuptable contains decls only which are in the 'to' context.
// Remove from the Lookuptable only if it is *imported* into the 'to'
// context (and do not remove it if it was added during the initial
// traverse of the 'to' context).
auto PosF = ImportedFromDecls.find(ToD);
if (PosF != ImportedFromDecls.end()) {
SharedState->removeDeclFromLookup(ToD);
ImportedFromDecls.erase(PosF);
}
// FIXME: AST may contain remaining references to the failed object.
// However, the ImportDeclErrors in the shared state contains all the
// failed objects together with their error.
}
// Error encountered for the first time.
// After takeError the error is not usable any more in ToDOrErr.
// Get a copy of the error object (any more simple solution for this?).
ImportError ErrOut;
handleAllErrors(ToDOrErr.takeError(),
[&ErrOut](const ImportError &E) { ErrOut = E; });
setImportDeclError(FromD, ErrOut);
// Set the error for the mapped to Decl, which is in the "to" context.
if (Pos != ImportedDecls.end())
SharedState->setImportDeclError(Pos->second, ErrOut);
// Set the error for all nodes which have been created before we
// recognized the error.
for (const auto &Path : SavedImportPaths[FromD])
for (Decl *FromDi : Path) {
setImportDeclError(FromDi, ErrOut);
//FIXME Should we remove these Decls from ImportedDecls?
// Set the error for the mapped to Decl, which is in the "to" context.
auto Ii = ImportedDecls.find(FromDi);
if (Ii != ImportedDecls.end())
SharedState->setImportDeclError(Ii->second, ErrOut);
// FIXME Should we remove these Decls from the LookupTable,
// and from ImportedFromDecls?
}
SavedImportPaths.erase(FromD);
// Do not return ToDOrErr, error was taken out of it.
return make_error<ImportError>(ErrOut);
}
ToD = *ToDOrErr;
// FIXME: Handle the "already imported with error" case. We can get here
// nullptr only if GetImportedOrCreateDecl returned nullptr (after a
// previously failed create was requested).
// Later GetImportedOrCreateDecl can be updated to return the error.
if (!ToD) {
auto Err = getImportDeclErrorIfAny(FromD);
assert(Err);
return make_error<ImportError>(*Err);
}
// We could import from the current TU without error. But previously we
// already had imported a Decl as `ToD` from another TU (with another
// ASTImporter object) and with an error.
if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
setImportDeclError(FromD, *Error);
return make_error<ImportError>(*Error);
}
// Make sure that ImportImpl registered the imported decl.
assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?");
if (FromD->hasAttrs())
for (const Attr *FromAttr : FromD->getAttrs()) {
auto ToAttrOrErr = Import(FromAttr);
if (ToAttrOrErr)
ToD->addAttr(*ToAttrOrErr);
else
return ToAttrOrErr.takeError();
}
// Notify subclasses.
Imported(FromD, ToD);
updateFlags(FromD, ToD);
SavedImportPaths.erase(FromD);
return ToDOrErr;
}
Expected<DeclContext *> ASTImporter::ImportContext(DeclContext *FromDC) {
if (!FromDC)
return FromDC;
ExpectedDecl ToDCOrErr = Import(cast<Decl>(FromDC));
if (!ToDCOrErr)
return ToDCOrErr.takeError();
auto *ToDC = cast<DeclContext>(*ToDCOrErr);
// When we're using a record/enum/Objective-C class/protocol as a context, we
// need it to have a definition.
if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
auto *FromRecord = cast<RecordDecl>(FromDC);
if (ToRecord->isCompleteDefinition())
return ToDC;
// If FromRecord is not defined we need to force it to be.
// Simply calling CompleteDecl(...) for a RecordDecl will break some cases
// it will start the definition but we never finish it.
// If there are base classes they won't be imported and we will
// be missing anything that we inherit from those bases.
if (FromRecord->getASTContext().getExternalSource() &&
!FromRecord->isCompleteDefinition())
FromRecord->getASTContext().getExternalSource()->CompleteType(FromRecord);
if (FromRecord->isCompleteDefinition())
if (Error Err = ASTNodeImporter(*this).ImportDefinition(
FromRecord, ToRecord, ASTNodeImporter::IDK_Basic))
return std::move(Err);
} else if (auto *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
auto *FromEnum = cast<EnumDecl>(FromDC);
if (ToEnum->isCompleteDefinition()) {
// Do nothing.
} else if (FromEnum->isCompleteDefinition()) {
if (Error Err = ASTNodeImporter(*this).ImportDefinition(
FromEnum, ToEnum, ASTNodeImporter::IDK_Basic))
return std::move(Err);
} else {
CompleteDecl(ToEnum);
}
} else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
auto *FromClass = cast<ObjCInterfaceDecl>(FromDC);
if (ToClass->getDefinition()) {
// Do nothing.
} else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
if (Error Err = ASTNodeImporter(*this).ImportDefinition(
FromDef, ToClass, ASTNodeImporter::IDK_Basic))
return std::move(Err);
} else {
CompleteDecl(ToClass);
}
} else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
auto *FromProto = cast<ObjCProtocolDecl>(FromDC);
if (ToProto->getDefinition()) {
// Do nothing.
} else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
if (Error Err = ASTNodeImporter(*this).ImportDefinition(
FromDef, ToProto, ASTNodeImporter::IDK_Basic))
return std::move(Err);
} else {
CompleteDecl(ToProto);
}
}
return ToDC;
}
Expected<Expr *> ASTImporter::Import(Expr *FromE) {
if (ExpectedStmt ToSOrErr = Import(cast_or_null<Stmt>(FromE)))
return cast_or_null<Expr>(*ToSOrErr);
else
return ToSOrErr.takeError();
}
Expected<Stmt *> ASTImporter::Import(Stmt *FromS) {
if (!FromS)
return nullptr;
// Check whether we've already imported this statement.
llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
if (Pos != ImportedStmts.end())
return Pos->second;
// Import the statement.
ASTNodeImporter Importer(*this);
ExpectedStmt ToSOrErr = Importer.Visit(FromS);
if (!ToSOrErr)
return ToSOrErr;
if (auto *ToE = dyn_cast<Expr>(*ToSOrErr)) {
auto *FromE = cast<Expr>(FromS);
// Copy ExprBitfields, which may not be handled in Expr subclasses
// constructors.
ToE->setValueKind(FromE->getValueKind());
ToE->setObjectKind(FromE->getObjectKind());
ToE->setDependence(FromE->getDependence());
}
// Record the imported statement object.
ImportedStmts[FromS] = *ToSOrErr;
return ToSOrErr;
}
Expected<NestedNameSpecifier *>
ASTImporter::Import(NestedNameSpecifier *FromNNS) {
if (!FromNNS)
return nullptr;
NestedNameSpecifier *Prefix = nullptr;
if (Error Err = importInto(Prefix, FromNNS->getPrefix()))
return std::move(Err);
switch (FromNNS->getKind()) {
case NestedNameSpecifier::Identifier:
assert(FromNNS->getAsIdentifier() && "NNS should contain identifier.");
return NestedNameSpecifier::Create(ToContext, Prefix,
Import(FromNNS->getAsIdentifier()));
case NestedNameSpecifier::Namespace:
if (ExpectedDecl NSOrErr = Import(FromNNS->getAsNamespace())) {
return NestedNameSpecifier::Create(ToContext, Prefix,
cast<NamespaceDecl>(*NSOrErr));
} else
return NSOrErr.takeError();
case NestedNameSpecifier::NamespaceAlias:
if (ExpectedDecl NSADOrErr = Import(FromNNS->getAsNamespaceAlias()))
return NestedNameSpecifier::Create(ToContext, Prefix,
cast<NamespaceAliasDecl>(*NSADOrErr));
else
return NSADOrErr.takeError();
case NestedNameSpecifier::Global:
return NestedNameSpecifier::GlobalSpecifier(ToContext);
case NestedNameSpecifier::Super:
if (ExpectedDecl RDOrErr = Import(FromNNS->getAsRecordDecl()))
return NestedNameSpecifier::SuperSpecifier(ToContext,
cast<CXXRecordDecl>(*RDOrErr));
else
return RDOrErr.takeError();
case NestedNameSpecifier::TypeSpec:
case NestedNameSpecifier::TypeSpecWithTemplate:
if (Expected<QualType> TyOrErr =
Import(QualType(FromNNS->getAsType(), 0u))) {
bool TSTemplate =
FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate;
return NestedNameSpecifier::Create(ToContext, Prefix, TSTemplate,
TyOrErr->getTypePtr());
} else {
return TyOrErr.takeError();
}
}
llvm_unreachable("Invalid nested name specifier kind");
}
Expected<NestedNameSpecifierLoc>
ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
// Copied from NestedNameSpecifier mostly.
SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
NestedNameSpecifierLoc NNS = FromNNS;
// Push each of the nested-name-specifiers's onto a stack for
// serialization in reverse order.
while (NNS) {
NestedNames.push_back(NNS);
NNS = NNS.getPrefix();
}
NestedNameSpecifierLocBuilder Builder;
while (!NestedNames.empty()) {
NNS = NestedNames.pop_back_val();
NestedNameSpecifier *Spec = nullptr;
if (Error Err = importInto(Spec, NNS.getNestedNameSpecifier()))
return std::move(Err);
NestedNameSpecifier::SpecifierKind Kind = Spec->getKind();
SourceLocation ToLocalBeginLoc, ToLocalEndLoc;
if (Kind != NestedNameSpecifier::Super) {
if (Error Err = importInto(ToLocalBeginLoc, NNS.getLocalBeginLoc()))
return std::move(Err);
if (Kind != NestedNameSpecifier::Global)
if (Error Err = importInto(ToLocalEndLoc, NNS.getLocalEndLoc()))
return std::move(Err);
}
switch (Kind) {
case NestedNameSpecifier::Identifier:
Builder.Extend(getToContext(), Spec->getAsIdentifier(), ToLocalBeginLoc,
ToLocalEndLoc);
break;
case NestedNameSpecifier::Namespace:
Builder.Extend(getToContext(), Spec->getAsNamespace(), ToLocalBeginLoc,
ToLocalEndLoc);
break;
case NestedNameSpecifier::NamespaceAlias:
Builder.Extend(getToContext(), Spec->getAsNamespaceAlias(),
ToLocalBeginLoc, ToLocalEndLoc);
break;
case NestedNameSpecifier::TypeSpec:
case NestedNameSpecifier::TypeSpecWithTemplate: {
SourceLocation ToTLoc;
if (Error Err = importInto(ToTLoc, NNS.getTypeLoc().getBeginLoc()))
return std::move(Err);
TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo(
QualType(Spec->getAsType(), 0), ToTLoc);
if (Kind == NestedNameSpecifier::TypeSpecWithTemplate)
// ToLocalBeginLoc is here the location of the 'template' keyword.
Builder.Extend(getToContext(), ToLocalBeginLoc, TSI->getTypeLoc(),
ToLocalEndLoc);
else
// No location for 'template' keyword here.
Builder.Extend(getToContext(), SourceLocation{}, TSI->getTypeLoc(),
ToLocalEndLoc);
break;
}
case NestedNameSpecifier::Global:
Builder.MakeGlobal(getToContext(), ToLocalBeginLoc);
break;
case NestedNameSpecifier::Super: {
auto ToSourceRangeOrErr = Import(NNS.getSourceRange());
if (!ToSourceRangeOrErr)
return ToSourceRangeOrErr.takeError();
Builder.MakeSuper(getToContext(), Spec->getAsRecordDecl(),
ToSourceRangeOrErr->getBegin(),
ToSourceRangeOrErr->getEnd());
}
}
}
return Builder.getWithLocInContext(getToContext());
}
Expected<TemplateName> ASTImporter::Import(TemplateName From) {
switch (From.getKind()) {
case TemplateName::Template:
if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl()))
return TemplateName(cast<TemplateDecl>(*ToTemplateOrErr));
else
return ToTemplateOrErr.takeError();
case TemplateName::OverloadedTemplate: {
OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
UnresolvedSet<2> ToTemplates;
for (auto *I : *FromStorage) {
if (auto ToOrErr = Import(I))
ToTemplates.addDecl(cast<NamedDecl>(*ToOrErr));
else
return ToOrErr.takeError();
}
return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
ToTemplates.end());
}
case TemplateName::AssumedTemplate: {
AssumedTemplateStorage *FromStorage = From.getAsAssumedTemplateName();
auto DeclNameOrErr = Import(FromStorage->getDeclName());
if (!DeclNameOrErr)
return DeclNameOrErr.takeError();
return ToContext.getAssumedTemplateName(*DeclNameOrErr);
}
case TemplateName::QualifiedTemplate: {
QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
auto QualifierOrErr = Import(QTN->getQualifier());
if (!QualifierOrErr)
return QualifierOrErr.takeError();
if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl()))
return ToContext.getQualifiedTemplateName(
*QualifierOrErr, QTN->hasTemplateKeyword(),
cast<TemplateDecl>(*ToTemplateOrErr));
else
return ToTemplateOrErr.takeError();
}
case TemplateName::DependentTemplate: {
DependentTemplateName *DTN = From.getAsDependentTemplateName();
auto QualifierOrErr = Import(DTN->getQualifier());
if (!QualifierOrErr)
return QualifierOrErr.takeError();
if (DTN->isIdentifier()) {
return ToContext.getDependentTemplateName(*QualifierOrErr,
Import(DTN->getIdentifier()));
}
return ToContext.getDependentTemplateName(*QualifierOrErr,
DTN->getOperator());
}
case TemplateName::SubstTemplateTemplateParm: {
SubstTemplateTemplateParmStorage *Subst =
From.getAsSubstTemplateTemplateParm();
ExpectedDecl ParamOrErr = Import(Subst->getParameter());
if (!ParamOrErr)
return ParamOrErr.takeError();
auto ReplacementOrErr = Import(Subst->getReplacement());
if (!ReplacementOrErr)
return ReplacementOrErr.takeError();
return ToContext.getSubstTemplateTemplateParm(
cast<TemplateTemplateParmDecl>(*ParamOrErr), *ReplacementOrErr);
}
case TemplateName::SubstTemplateTemplateParmPack: {
SubstTemplateTemplateParmPackStorage *SubstPack
= From.getAsSubstTemplateTemplateParmPack();
ExpectedDecl ParamOrErr = Import(SubstPack->getParameterPack());
if (!ParamOrErr)
return ParamOrErr.takeError();
ASTNodeImporter Importer(*this);
auto ArgPackOrErr =
Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
if (!ArgPackOrErr)
return ArgPackOrErr.takeError();
return ToContext.getSubstTemplateTemplateParmPack(
cast<TemplateTemplateParmDecl>(*ParamOrErr), *ArgPackOrErr);
}
}
llvm_unreachable("Invalid template name kind");
}
Expected<SourceLocation> ASTImporter::Import(SourceLocation FromLoc) {
if (FromLoc.isInvalid())
return SourceLocation{};
SourceManager &FromSM = FromContext.getSourceManager();
bool IsBuiltin = FromSM.isWrittenInBuiltinFile(FromLoc);
std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin);
if (!ToFileIDOrErr)
return ToFileIDOrErr.takeError();
SourceManager &ToSM = ToContext.getSourceManager();
return ToSM.getComposedLoc(*ToFileIDOrErr, Decomposed.second);
}
Expected<SourceRange> ASTImporter::Import(SourceRange FromRange) {
SourceLocation ToBegin, ToEnd;
if (Error Err = importInto(ToBegin, FromRange.getBegin()))
return std::move(Err);
if (Error Err = importInto(ToEnd, FromRange.getEnd()))
return std::move(Err);
return SourceRange(ToBegin, ToEnd);
}
Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) {
llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(FromID);
if (Pos != ImportedFileIDs.end())
return Pos->second;
SourceManager &FromSM = FromContext.getSourceManager();
SourceManager &ToSM = ToContext.getSourceManager();
const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
// Map the FromID to the "to" source manager.
FileID ToID;
if (FromSLoc.isExpansion()) {
const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion();
ExpectedSLoc ToSpLoc = Import(FromEx.getSpellingLoc());
if (!ToSpLoc)
return ToSpLoc.takeError();
ExpectedSLoc ToExLocS = Import(FromEx.getExpansionLocStart());
if (!ToExLocS)
return ToExLocS.takeError();
unsigned TokenLen = FromSM.getFileIDSize(FromID);
SourceLocation MLoc;
if (FromEx.isMacroArgExpansion()) {
MLoc = ToSM.createMacroArgExpansionLoc(*ToSpLoc, *ToExLocS, TokenLen);
} else {
if (ExpectedSLoc ToExLocE = Import(FromEx.getExpansionLocEnd()))
MLoc = ToSM.createExpansionLoc(*ToSpLoc, *ToExLocS, *ToExLocE, TokenLen,
FromEx.isExpansionTokenRange());
else
return ToExLocE.takeError();
}
ToID = ToSM.getFileID(MLoc);
} else {
const SrcMgr::ContentCache *Cache = &FromSLoc.getFile().getContentCache();
if (!IsBuiltin && !Cache->BufferOverridden) {
// Include location of this file.
ExpectedSLoc ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
if (!ToIncludeLoc)
return ToIncludeLoc.takeError();
// Every FileID that is not the main FileID needs to have a valid include
// location so that the include chain points to the main FileID. When
// importing the main FileID (which has no include location), we need to
// create a fake include location in the main file to keep this property
// intact.
SourceLocation ToIncludeLocOrFakeLoc = *ToIncludeLoc;
if (FromID == FromSM.getMainFileID())
ToIncludeLocOrFakeLoc = ToSM.getLocForStartOfFile(ToSM.getMainFileID());
if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
// FIXME: We probably want to use getVirtualFile(), so we don't hit the
// disk again
// FIXME: We definitely want to re-use the existing MemoryBuffer, rather
// than mmap the files several times.
auto Entry =
ToFileManager.getOptionalFileRef(Cache->OrigEntry->getName());
// FIXME: The filename may be a virtual name that does probably not
// point to a valid file and we get no Entry here. In this case try with
// the memory buffer below.
if (Entry)
ToID = ToSM.createFileID(*Entry, ToIncludeLocOrFakeLoc,
FromSLoc.getFile().getFileCharacteristic());
}
}
if (ToID.isInvalid() || IsBuiltin) {
// FIXME: We want to re-use the existing MemoryBuffer!
llvm::Optional<llvm::MemoryBufferRef> FromBuf =
Cache->getBufferOrNone(FromContext.getDiagnostics(),
FromSM.getFileManager(), SourceLocation{});
if (!FromBuf)
return llvm::make_error<ImportError>(ImportError::Unknown);
std::unique_ptr<llvm::MemoryBuffer> ToBuf =
llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
FromBuf->getBufferIdentifier());
ToID = ToSM.createFileID(std::move(ToBuf),
FromSLoc.getFile().getFileCharacteristic());
}
}
assert(ToID.isValid() && "Unexpected invalid fileID was created.");
ImportedFileIDs[FromID] = ToID;
if (FileIDImportHandler)
FileIDImportHandler(ToID, FromID);
return ToID;
}
Expected<CXXCtorInitializer *> ASTImporter::Import(CXXCtorInitializer *From) {
ExpectedExpr ToExprOrErr = Import(From->getInit());
if (!ToExprOrErr)
return ToExprOrErr.takeError();
auto LParenLocOrErr = Import(From->getLParenLoc());
if (!LParenLocOrErr)
return LParenLocOrErr.takeError();
auto RParenLocOrErr = Import(From->getRParenLoc());
if (!RParenLocOrErr)
return RParenLocOrErr.takeError();
if (From->isBaseInitializer()) {
auto ToTInfoOrErr = Import(From->getTypeSourceInfo());
if (!ToTInfoOrErr)
return ToTInfoOrErr.takeError();
SourceLocation EllipsisLoc;
if (From->isPackExpansion())
if (Error Err = importInto(EllipsisLoc, From->getEllipsisLoc()))
return std::move(Err);
return new (ToContext) CXXCtorInitializer(
ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr,
*ToExprOrErr, *RParenLocOrErr, EllipsisLoc);
} else if (From->isMemberInitializer()) {
ExpectedDecl ToFieldOrErr = Import(From->getMember());
if (!ToFieldOrErr)
return ToFieldOrErr.takeError();
auto MemberLocOrErr = Import(From->getMemberLocation());
if (!MemberLocOrErr)
return MemberLocOrErr.takeError();
return new (ToContext) CXXCtorInitializer(
ToContext, cast_or_null<FieldDecl>(*ToFieldOrErr), *MemberLocOrErr,
*LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
} else if (From->isIndirectMemberInitializer()) {
ExpectedDecl ToIFieldOrErr = Import(From->getIndirectMember());
if (!ToIFieldOrErr)
return ToIFieldOrErr.takeError();
auto MemberLocOrErr = Import(From->getMemberLocation());
if (!MemberLocOrErr)
return MemberLocOrErr.takeError();
return new (ToContext) CXXCtorInitializer(
ToContext, cast_or_null<IndirectFieldDecl>(*ToIFieldOrErr),
*MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
} else if (From->isDelegatingInitializer()) {
auto ToTInfoOrErr = Import(From->getTypeSourceInfo());
if (!ToTInfoOrErr)
return ToTInfoOrErr.takeError();
return new (ToContext)
CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr,
*ToExprOrErr, *RParenLocOrErr);
} else {
// FIXME: assert?
return make_error<ImportError>();
}
}
Expected<CXXBaseSpecifier *>
ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) {
auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec);
if (Pos != ImportedCXXBaseSpecifiers.end())
return Pos->second;
Expected<SourceRange> ToSourceRange = Import(BaseSpec->getSourceRange());
if (!ToSourceRange)
return ToSourceRange.takeError();
Expected<TypeSourceInfo *> ToTSI = Import(BaseSpec->getTypeSourceInfo());
if (!ToTSI)
return ToTSI.takeError();
ExpectedSLoc ToEllipsisLoc = Import(BaseSpec->getEllipsisLoc());
if (!ToEllipsisLoc)
return ToEllipsisLoc.takeError();
CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
*ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc);
ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
return Imported;
}
llvm::Expected<APValue> ASTImporter::Import(const APValue &FromValue) {
ASTNodeImporter Importer(*this);
return Importer.ImportAPValue(FromValue);
}
Error ASTImporter::ImportDefinition(Decl *From) {
ExpectedDecl ToOrErr = Import(From);
if (!ToOrErr)
return ToOrErr.takeError();
Decl *To = *ToOrErr;
auto *FromDC = cast<DeclContext>(From);
ASTNodeImporter Importer(*this);
if (auto *ToRecord = dyn_cast<RecordDecl>(To)) {
if (!ToRecord->getDefinition()) {
return Importer.ImportDefinition(
cast<RecordDecl>(FromDC), ToRecord,
ASTNodeImporter::IDK_Everything);
}
}
if (auto *ToEnum = dyn_cast<EnumDecl>(To)) {
if (!ToEnum->getDefinition()) {
return Importer.ImportDefinition(
cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything);
}
}
if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
if (!ToIFace->getDefinition()) {
return Importer.ImportDefinition(
cast<ObjCInterfaceDecl>(FromDC), ToIFace,
ASTNodeImporter::IDK_Everything);
}
}
if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
if (!ToProto->getDefinition()) {
return Importer.ImportDefinition(
cast<ObjCProtocolDecl>(FromDC), ToProto,
ASTNodeImporter::IDK_Everything);
}
}
return Importer.ImportDeclContext(FromDC, true);
}
Expected<DeclarationName> ASTImporter::Import(DeclarationName FromName) {
if (!FromName)
return DeclarationName{};
switch (FromName.getNameKind()) {
case DeclarationName::Identifier:
return DeclarationName(Import(FromName.getAsIdentifierInfo()));
case DeclarationName::ObjCZeroArgSelector:
case DeclarationName::ObjCOneArgSelector:
case DeclarationName::ObjCMultiArgSelector:
if (auto ToSelOrErr = Import(FromName.getObjCSelector()))
return DeclarationName(*ToSelOrErr);
else
return ToSelOrErr.takeError();
case DeclarationName::CXXConstructorName: {
if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
return ToContext.DeclarationNames.getCXXConstructorName(
ToContext.getCanonicalType(*ToTyOrErr));
else
return ToTyOrErr.takeError();
}
case DeclarationName::CXXDestructorName: {
if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
return ToContext.DeclarationNames.getCXXDestructorName(
ToContext.getCanonicalType(*ToTyOrErr));
else
return ToTyOrErr.takeError();
}
case DeclarationName::CXXDeductionGuideName: {
if (auto ToTemplateOrErr = Import(FromName.getCXXDeductionGuideTemplate()))
return ToContext.DeclarationNames.getCXXDeductionGuideName(
cast<TemplateDecl>(*ToTemplateOrErr));
else
return ToTemplateOrErr.takeError();
}
case DeclarationName::CXXConversionFunctionName: {
if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
return ToContext.DeclarationNames.getCXXConversionFunctionName(
ToContext.getCanonicalType(*ToTyOrErr));
else
return ToTyOrErr.takeError();
}
case DeclarationName::CXXOperatorName:
return ToContext.DeclarationNames.getCXXOperatorName(
FromName.getCXXOverloadedOperator());
case DeclarationName::CXXLiteralOperatorName:
return ToContext.DeclarationNames.getCXXLiteralOperatorName(
Import(FromName.getCXXLiteralIdentifier()));
case DeclarationName::CXXUsingDirective:
// FIXME: STATICS!
return DeclarationName::getUsingDirectiveName();
}
llvm_unreachable("Invalid DeclarationName Kind!");
}
IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
if (!FromId)
return nullptr;
IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
if (!ToId->getBuiltinID() && FromId->getBuiltinID())
ToId->setBuiltinID(FromId->getBuiltinID());
return ToId;
}
Expected<Selector> ASTImporter::Import(Selector FromSel) {
if (FromSel.isNull())
return Selector{};
SmallVector<IdentifierInfo *, 4> Idents;
Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
}
llvm::Expected<APValue>
ASTNodeImporter::ImportAPValue(const APValue &FromValue) {
APValue Result;
llvm::Error Err = llvm::Error::success();
auto ImportLoop = [&](const APValue *From, APValue *To, unsigned Size) {
for (unsigned Idx = 0; Idx < Size; Idx++) {
APValue Tmp = importChecked(Err, From[Idx]);
To[Idx] = Tmp;
}
};
switch (FromValue.getKind()) {
case APValue::None:
case APValue::Indeterminate:
case APValue::Int:
case APValue::Float:
case APValue::FixedPoint:
case APValue::ComplexInt:
case APValue::ComplexFloat:
Result = FromValue;
break;
case APValue::Vector: {
Result.MakeVector();
MutableArrayRef<APValue> Elts =
Result.setVectorUninit(FromValue.getVectorLength());
ImportLoop(((const APValue::Vec *)(const char *)&FromValue.Data)->Elts,
Elts.data(), FromValue.getVectorLength());
break;
}
case APValue::Array:
Result.MakeArray(FromValue.getArrayInitializedElts(),
FromValue.getArraySize());
ImportLoop(((const APValue::Arr *)(const char *)&FromValue.Data)->Elts,
((const APValue::Arr *)(const char *)&Result.Data)->Elts,
FromValue.getArrayInitializedElts());
break;
case APValue::Struct:
Result.MakeStruct(FromValue.getStructNumBases(),
FromValue.getStructNumFields());
ImportLoop(
((const APValue::StructData *)(const char *)&FromValue.Data)->Elts,
((const APValue::StructData *)(const char *)&Result.Data)->Elts,
FromValue.getStructNumBases() + FromValue.getStructNumFields());
break;
case APValue::Union: {
Result.MakeUnion();
const Decl *ImpFDecl = importChecked(Err, FromValue.getUnionField());
APValue ImpValue = importChecked(Err, FromValue.getUnionValue());
if (Err)
return std::move(Err);
Result.setUnion(cast<FieldDecl>(ImpFDecl), ImpValue);
break;
}
case APValue::AddrLabelDiff: {
Result.MakeAddrLabelDiff();
const Expr *ImpLHS = importChecked(Err, FromValue.getAddrLabelDiffLHS());
const Expr *ImpRHS = importChecked(Err, FromValue.getAddrLabelDiffRHS());
if (Err)
return std::move(Err);
Result.setAddrLabelDiff(cast<AddrLabelExpr>(ImpLHS),
cast<AddrLabelExpr>(ImpRHS));
break;
}
case APValue::MemberPointer: {
const Decl *ImpMemPtrDecl =
importChecked(Err, FromValue.getMemberPointerDecl());
if (Err)
return std::move(Err);
MutableArrayRef<const CXXRecordDecl *> ToPath =
Result.setMemberPointerUninit(
cast<const ValueDecl>(ImpMemPtrDecl),
FromValue.isMemberPointerToDerivedMember(),
FromValue.getMemberPointerPath().size());
llvm::ArrayRef<const CXXRecordDecl *> FromPath =
Result.getMemberPointerPath();
for (unsigned Idx = 0; Idx < FromValue.getMemberPointerPath().size();
Idx++) {
const Decl *ImpDecl = importChecked(Err, FromPath[Idx]);
if (Err)
return std::move(Err);
ToPath[Idx] = cast<const CXXRecordDecl>(ImpDecl->getCanonicalDecl());
}
break;
}
case APValue::LValue:
APValue::LValueBase Base;
QualType FromElemTy;
if (FromValue.getLValueBase()) {
assert(!FromValue.getLValueBase().is<DynamicAllocLValue>() &&
"in C++20 dynamic allocation are transient so they shouldn't "
"appear in the AST");
if (!FromValue.getLValueBase().is<TypeInfoLValue>()) {
if (const auto *E =
FromValue.getLValueBase().dyn_cast<const Expr *>()) {
FromElemTy = E->getType();
const Expr *ImpExpr = importChecked(Err, E);
if (Err)
return std::move(Err);
Base = APValue::LValueBase(ImpExpr,
FromValue.getLValueBase().getCallIndex(),
FromValue.getLValueBase().getVersion());
} else {
FromElemTy =
FromValue.getLValueBase().get<const ValueDecl *>()->getType();
const Decl *ImpDecl = importChecked(
Err, FromValue.getLValueBase().get<const ValueDecl *>());
if (Err)
return std::move(Err);
Base = APValue::LValueBase(cast<ValueDecl>(ImpDecl),
FromValue.getLValueBase().getCallIndex(),
FromValue.getLValueBase().getVersion());
}
} else {
FromElemTy = FromValue.getLValueBase().getTypeInfoType();
QualType ImpTypeInfo = importChecked(
Err,
QualType(FromValue.getLValueBase().get<TypeInfoLValue>().getType(),
0));
QualType ImpType =
importChecked(Err, FromValue.getLValueBase().getTypeInfoType());
if (Err)
return std::move(Err);
Base = APValue::LValueBase::getTypeInfo(
TypeInfoLValue(ImpTypeInfo.getTypePtr()), ImpType);
}
}
CharUnits Offset = FromValue.getLValueOffset();
unsigned PathLength = FromValue.getLValuePath().size();
Result.MakeLValue();
if (FromValue.hasLValuePath()) {
MutableArrayRef<APValue::LValuePathEntry> ToPath = Result.setLValueUninit(
Base, Offset, PathLength, FromValue.isLValueOnePastTheEnd(),
FromValue.isNullPointer());
llvm::ArrayRef<APValue::LValuePathEntry> FromPath =
FromValue.getLValuePath();
for (unsigned LoopIdx = 0; LoopIdx < PathLength; LoopIdx++) {
if (FromElemTy->isRecordType()) {
const Decl *FromDecl =
FromPath[LoopIdx].getAsBaseOrMember().getPointer();
const Decl *ImpDecl = importChecked(Err, FromDecl);
if (Err)
return std::move(Err);
if (auto *RD = dyn_cast<CXXRecordDecl>(FromDecl))
FromElemTy = Importer.FromContext.getRecordType(RD);
else
FromElemTy = cast<ValueDecl>(FromDecl)->getType();
ToPath[LoopIdx] = APValue::LValuePathEntry(APValue::BaseOrMemberType(
ImpDecl, FromPath[LoopIdx].getAsBaseOrMember().getInt()));
} else {
FromElemTy =
Importer.FromContext.getAsArrayType(FromElemTy)->getElementType();
ToPath[LoopIdx] = APValue::LValuePathEntry::ArrayIndex(
FromPath[LoopIdx].getAsArrayIndex());
}
}
} else
Result.setLValue(Base, Offset, APValue::NoLValuePath{},
FromValue.isNullPointer());
}
if (Err)
return std::move(Err);
return Result;
}
Expected<DeclarationName> ASTImporter::HandleNameConflict(DeclarationName Name,
DeclContext *DC,
unsigned IDNS,
NamedDecl **Decls,
unsigned NumDecls) {
if (ODRHandling == ODRHandlingType::Conservative)
// Report error at any name conflict.
return make_error<ImportError>(ImportError::NameConflict);
else
// Allow to create the new Decl with the same name.
return Name;
}
DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
if (LastDiagFromFrom)
ToContext.getDiagnostics().notePriorDiagnosticFrom(
FromContext.getDiagnostics());
LastDiagFromFrom = false;
return ToContext.getDiagnostics().Report(Loc, DiagID);
}
DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
if (!LastDiagFromFrom)
FromContext.getDiagnostics().notePriorDiagnosticFrom(
ToContext.getDiagnostics());
LastDiagFromFrom = true;
return FromContext.getDiagnostics().Report(Loc, DiagID);
}
void ASTImporter::CompleteDecl (Decl *D) {
if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
if (!ID->getDefinition())
ID->startDefinition();
}
else if (auto *PD = dyn_cast<ObjCProtocolDecl>(D)) {
if (!PD->getDefinition())
PD->startDefinition();
}
else if (auto *TD = dyn_cast<TagDecl>(D)) {
if (!TD->getDefinition() && !TD->isBeingDefined()) {
TD->startDefinition();
TD->setCompleteDefinition(true);
}
}
else {
assert(0 && "CompleteDecl called on a Decl that can't be completed");
}
}
Decl *ASTImporter::MapImported(Decl *From, Decl *To) {
llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(From);
assert((Pos == ImportedDecls.end() || Pos->second == To) &&
"Try to import an already imported Decl");
if (Pos != ImportedDecls.end())
return Pos->second;
ImportedDecls[From] = To;
// This mapping should be maintained only in this function. Therefore do not
// check for additional consistency.
ImportedFromDecls[To] = From;
// In the case of TypedefNameDecl we create the Decl first and only then we
// import and set its DeclContext. So, the DC is still not set when we reach
// here from GetImportedOrCreateDecl.
if (To->getDeclContext())
AddToLookupTable(To);
return To;
}
llvm::Optional<ImportError>
ASTImporter::getImportDeclErrorIfAny(Decl *FromD) const {
auto Pos = ImportDeclErrors.find(FromD);
if (Pos != ImportDeclErrors.end())
return Pos->second;
else
return Optional<ImportError>();
}
void ASTImporter::setImportDeclError(Decl *From, ImportError Error) {
auto InsertRes = ImportDeclErrors.insert({From, Error});
(void)InsertRes;
// Either we set the error for the first time, or we already had set one and
// now we want to set the same error.
assert(InsertRes.second || InsertRes.first->second.Error == Error.Error);
}
bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
bool Complain) {
llvm::DenseMap<const Type *, const Type *>::iterator Pos =
ImportedTypes.find(From.getTypePtr());
if (Pos != ImportedTypes.end()) {
if (ExpectedType ToFromOrErr = Import(From)) {
if (ToContext.hasSameType(*ToFromOrErr, To))
return true;
} else {
llvm::consumeError(ToFromOrErr.takeError());
}
}
StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
getStructuralEquivalenceKind(*this), false,
Complain);
return Ctx.IsEquivalent(From, To);
}
|
#include <iostream>
using namespace std;
int T, a, b;
int main()
{
ios_base::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
cin >> T;
while (T--) {
cin >> a >> b;
if (a < b) {
if ((b-a) % 2)
cout << "1\n";
else
cout << "2\n";
} else if (a > b) {
if ((a-b) % 2)
cout << "2\n";
else
cout << "1\n";
} else {
cout << "0\n";
}
}
return 0;
}
|
// Copyright (c) 2019-2019, Nejcraft
// Copyright (c) 2014-2019, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT 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.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include "gtest/gtest.h"
#include <sstream>
#include "wallet/wallet.h"
#include "rpc/core_rpc_server.h"
#include "cryptonote_basic/account.h"
#include "net/http_client_abstract_invoke.h"
using namespace std;
using namespace epee::misc_utils;
using namespace cryptonote;
string daemon_address = "http://localhost:23400";
#define ACCS 5
TEST(Transfers, Transfers)
{
log_space::get_set_log_detalisation_level(true, LOG_LEVEL_3);
log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL);
cout << "TESTING: transfers" << endl;
net_utils::http::http_simple_client http_client;
wallet miner, accs[100], receiver;
miner.generate();
ASSERT_TRUE(miner.init());
ASSERT_TRUE(miner.store("miner.b2wallet"));
cout << "miner: " << miner.get_account().get_public_address_str(false) << endl;
for (int i = 0; i < ACCS; i++) {
ostringstream s;
s << "acc" << setw(2) << setfill('0') << i << ".b2wallet";
accs[i].generate();
assert(accs[i].init());
assert(accs[i].store(s.str()));
}
receiver.generate();
assert(receiver.init());
receiver.store("receiver.b2wallet");
{
COMMAND_RPC_START_MINE::request req;
req.miner_address = miner.get_account().get_public_address_str(false);
req.threads_count = 1;
COMMAND_RPC_START_MINE::response res;
bool r = net_utils::http::invoke_http_json_remote_command(daemon_address + "/start_mine", req, res, http_client);
ASSERT_TRUE(r);
}
string s;
//getline(cin, s);
sleep_no_w(1000);
ASSERT_TRUE(miner.refresh());
cout << "miner balance: " << miner.balance() << endl;
vector<pair<account_public_address, uint64_t>> d_accs;
for (int i = 0; i < ACCS; i++)
d_accs.push_back(make_pair(accs[i].get_account().get_keys().m_account_address, 1));
ASSERT_TRUE(miner.transfer(d_accs));
//getline(cin, s);
sleep_no_w(1000);
for (int i = 0; i < ACCS; i++) {
ASSERT_TRUE(accs[i].refresh());
ASSERT_TRUE(accs[i].transfer(receiver.get_account().get_keys().m_account_address, 1));
}
//getline(cin, s);
cout << "wait for block" << endl;
sleep_no_w(10000);
receiver.refresh();
ASSERT_TRUE(receiver.balance() == ACCS);
cout << "OK" << endl;
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: MultiplayerScoreProvider
#include "GlobalNamespace/MultiplayerScoreProvider.hpp"
// Including type: MultiplayerController
#include "GlobalNamespace/MultiplayerController.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: MultiplayerPlayersManager
class MultiplayerPlayersManager;
// Forward declaring type: MultiplayerLayoutProvider
class MultiplayerLayoutProvider;
// Forward declaring type: MultiplayerConnectedPlayerFacade
class MultiplayerConnectedPlayerFacade;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: Dictionary`2<TKey, TValue>
template<typename TKey, typename TValue>
class Dictionary_2;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: MultiplayerVerticalPlayerMovementManager
class MultiplayerVerticalPlayerMovementManager;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::MultiplayerVerticalPlayerMovementManager);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::MultiplayerVerticalPlayerMovementManager*, "", "MultiplayerVerticalPlayerMovementManager");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x64
#pragma pack(push, 1)
// Autogenerated type: MultiplayerVerticalPlayerMovementManager
// [TokenAttribute] Offset: FFFFFFFF
class MultiplayerVerticalPlayerMovementManager : public ::UnityEngine::MonoBehaviour {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// [TooltipAttribute] Offset: 0x12555E4
// private System.Single _movementRange
// Size: 0x4
// Offset: 0x18
float movementRange;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _duelMovementRange
// Size: 0x4
// Offset: 0x1C
float duelMovementRange;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _maxMoveSpeedMetersPerSecond
// Size: 0x4
// Offset: 0x20
float maxMoveSpeedMetersPerSecond;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _accelerationMetersPerSecondSquared
// Size: 0x4
// Offset: 0x24
float accelerationMetersPerSecondSquared;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _decelerationMetersPerSecondSquared
// Size: 0x4
// Offset: 0x28
float decelerationMetersPerSecondSquared;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _minScoreDifference
// Size: 0x4
// Offset: 0x2C
float minScoreDifference;
// Field size check
static_assert(sizeof(float) == 0x4);
// [InjectAttribute] Offset: 0x1255680
// private readonly MultiplayerPlayersManager _multiplayerPlayersManager
// Size: 0x8
// Offset: 0x30
::GlobalNamespace::MultiplayerPlayersManager* multiplayerPlayersManager;
// Field size check
static_assert(sizeof(::GlobalNamespace::MultiplayerPlayersManager*) == 0x8);
// [InjectAttribute] Offset: 0x1255690
// private readonly MultiplayerScoreProvider _scoreProvider
// Size: 0x8
// Offset: 0x38
::GlobalNamespace::MultiplayerScoreProvider* scoreProvider;
// Field size check
static_assert(sizeof(::GlobalNamespace::MultiplayerScoreProvider*) == 0x8);
// [InjectAttribute] Offset: 0x12556A0
// private readonly MultiplayerLayoutProvider _layoutProvider
// Size: 0x8
// Offset: 0x40
::GlobalNamespace::MultiplayerLayoutProvider* layoutProvider;
// Field size check
static_assert(sizeof(::GlobalNamespace::MultiplayerLayoutProvider*) == 0x8);
// [InjectAttribute] Offset: 0x12556B0
// private readonly MultiplayerController _multiplayerController
// Size: 0x8
// Offset: 0x48
::GlobalNamespace::MultiplayerController* multiplayerController;
// Field size check
static_assert(sizeof(::GlobalNamespace::MultiplayerController*) == 0x8);
// private readonly System.Collections.Generic.List`1<MultiplayerScoreProvider/RankedPlayer> _reusablePlayersList
// Size: 0x8
// Offset: 0x50
::System::Collections::Generic::List_1<::GlobalNamespace::MultiplayerScoreProvider::RankedPlayer*>* reusablePlayersList;
// Field size check
static_assert(sizeof(::System::Collections::Generic::List_1<::GlobalNamespace::MultiplayerScoreProvider::RankedPlayer*>*) == 0x8);
// private readonly System.Collections.Generic.Dictionary`2<MultiplayerConnectedPlayerFacade,System.Single> _currentSpeedsDictionary
// Size: 0x8
// Offset: 0x58
::System::Collections::Generic::Dictionary_2<::GlobalNamespace::MultiplayerConnectedPlayerFacade*, float>* currentSpeedsDictionary;
// Field size check
static_assert(sizeof(::System::Collections::Generic::Dictionary_2<::GlobalNamespace::MultiplayerConnectedPlayerFacade*, float>*) == 0x8);
// private System.Single _lastFrameBaseScore
// Size: 0x4
// Offset: 0x60
float lastFrameBaseScore;
// Field size check
static_assert(sizeof(float) == 0x4);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: private System.Single _movementRange
float& dyn__movementRange();
// Get instance field reference: private System.Single _duelMovementRange
float& dyn__duelMovementRange();
// Get instance field reference: private System.Single _maxMoveSpeedMetersPerSecond
float& dyn__maxMoveSpeedMetersPerSecond();
// Get instance field reference: private System.Single _accelerationMetersPerSecondSquared
float& dyn__accelerationMetersPerSecondSquared();
// Get instance field reference: private System.Single _decelerationMetersPerSecondSquared
float& dyn__decelerationMetersPerSecondSquared();
// Get instance field reference: private System.Single _minScoreDifference
float& dyn__minScoreDifference();
// Get instance field reference: private readonly MultiplayerPlayersManager _multiplayerPlayersManager
::GlobalNamespace::MultiplayerPlayersManager*& dyn__multiplayerPlayersManager();
// Get instance field reference: private readonly MultiplayerScoreProvider _scoreProvider
::GlobalNamespace::MultiplayerScoreProvider*& dyn__scoreProvider();
// Get instance field reference: private readonly MultiplayerLayoutProvider _layoutProvider
::GlobalNamespace::MultiplayerLayoutProvider*& dyn__layoutProvider();
// Get instance field reference: private readonly MultiplayerController _multiplayerController
::GlobalNamespace::MultiplayerController*& dyn__multiplayerController();
// Get instance field reference: private readonly System.Collections.Generic.List`1<MultiplayerScoreProvider/RankedPlayer> _reusablePlayersList
::System::Collections::Generic::List_1<::GlobalNamespace::MultiplayerScoreProvider::RankedPlayer*>*& dyn__reusablePlayersList();
// Get instance field reference: private readonly System.Collections.Generic.Dictionary`2<MultiplayerConnectedPlayerFacade,System.Single> _currentSpeedsDictionary
::System::Collections::Generic::Dictionary_2<::GlobalNamespace::MultiplayerConnectedPlayerFacade*, float>*& dyn__currentSpeedsDictionary();
// Get instance field reference: private System.Single _lastFrameBaseScore
float& dyn__lastFrameBaseScore();
// protected System.Void Start()
// Offset: 0x146CD84
void Start();
// protected System.Void OnDestroy()
// Offset: 0x146CE48
void OnDestroy();
// protected System.Void Update()
// Offset: 0x146CF24
void Update();
// private System.Void HandleStateChanged(MultiplayerController/State state)
// Offset: 0x146CE38
void HandleStateChanged(::GlobalNamespace::MultiplayerController::State state);
// public System.Void .ctor()
// Offset: 0x146D808
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MultiplayerVerticalPlayerMovementManager* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::MultiplayerVerticalPlayerMovementManager::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MultiplayerVerticalPlayerMovementManager*, creationType>()));
}
}; // MultiplayerVerticalPlayerMovementManager
#pragma pack(pop)
static check_size<sizeof(MultiplayerVerticalPlayerMovementManager), 96 + sizeof(float)> __GlobalNamespace_MultiplayerVerticalPlayerMovementManagerSizeCheck;
static_assert(sizeof(MultiplayerVerticalPlayerMovementManager) == 0x64);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerVerticalPlayerMovementManager::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerVerticalPlayerMovementManager::*)()>(&GlobalNamespace::MultiplayerVerticalPlayerMovementManager::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerVerticalPlayerMovementManager*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerVerticalPlayerMovementManager::OnDestroy
// Il2CppName: OnDestroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerVerticalPlayerMovementManager::*)()>(&GlobalNamespace::MultiplayerVerticalPlayerMovementManager::OnDestroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerVerticalPlayerMovementManager*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerVerticalPlayerMovementManager::Update
// Il2CppName: Update
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerVerticalPlayerMovementManager::*)()>(&GlobalNamespace::MultiplayerVerticalPlayerMovementManager::Update)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerVerticalPlayerMovementManager*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerVerticalPlayerMovementManager::HandleStateChanged
// Il2CppName: HandleStateChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerVerticalPlayerMovementManager::*)(::GlobalNamespace::MultiplayerController::State)>(&GlobalNamespace::MultiplayerVerticalPlayerMovementManager::HandleStateChanged)> {
static const MethodInfo* get() {
static auto* state = &::il2cpp_utils::GetClassFromName("", "MultiplayerController/State")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerVerticalPlayerMovementManager*), "HandleStateChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{state});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerVerticalPlayerMovementManager::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
#pragma once
namespace Skye {
enum class ShaderDataType : uint8_t
{
None = 0, Float, Float2, Float3, Float4, Mat3, Mat4, Int, Int2, Int3, Int4, Bool
};
static uint32_t ShaderDataTypeSize(ShaderDataType type)
{
switch (type)
{
case ShaderDataType::Float: return 4;
case ShaderDataType::Float2: return 4 * 2;
case ShaderDataType::Float3: return 4 * 3;
case ShaderDataType::Float4: return 4 * 4;
case ShaderDataType::Mat3: return 4 * 3 * 3;
case ShaderDataType::Mat4: return 4 * 4 * 4;
case ShaderDataType::Int: return 4;
case ShaderDataType::Int2: return 4 * 2;
case ShaderDataType::Int3: return 4 * 3;
case ShaderDataType::Int4: return 4 * 4;
case ShaderDataType::Bool: return 1;
}
SK_CORE_ASSERT(false, "Unknown ShaderDataType!");
return 0;
}
struct BufferElement
{
std::string Name; // The name of the buffer element data (i.e. a_Position)
ShaderDataType Type; // The type of the buffer element data
uint32_t Size; // How large each buffer element data
uint32_t Offset; // The byte offset to the next vector/item in the buffer
bool Normalized; // Whether this buffer element is normalized
BufferElement() {};
BufferElement(ShaderDataType type, const std::string& name, bool normalized = false)
: Name(name), Type(type), Size(ShaderDataTypeSize(type)), Offset(0), Normalized(normalized)
{
}
uint32_t GetComponentCount() const
{
switch (Type)
{
case ShaderDataType::Float: return 1;
case ShaderDataType::Float2: return 2;
case ShaderDataType::Float3: return 3;
case ShaderDataType::Float4: return 4;
case ShaderDataType::Mat3: return 3 * 3;
case ShaderDataType::Mat4: return 4 * 4;
case ShaderDataType::Int: return 1;
case ShaderDataType::Int2: return 2;
case ShaderDataType::Int3: return 3;
case ShaderDataType::Int4: return 4;
case ShaderDataType::Bool: return 1;
}
SK_CORE_ASSERT(false, "Unknown ShaderDataType!");
return 0;
}
};
class BufferLayout
{
public:
BufferLayout() {};
BufferLayout(const std::initializer_list<BufferElement>& elements)
: m_Elements(elements)
{
CalculateOffsetsAndStride();
}
inline uint32_t GetStride() const { return m_Stride; }
inline const std::vector<BufferElement>& GetElements() const { return m_Elements; }
std::vector<BufferElement>::iterator begin() { return m_Elements.begin(); }
std::vector<BufferElement>::iterator end() { return m_Elements.end(); }
std::vector<BufferElement>::const_iterator begin() const { return m_Elements.begin(); }
std::vector<BufferElement>::const_iterator end() const { return m_Elements.end(); }
private:
void CalculateOffsetsAndStride()
{
uint32_t offset = 0;
m_Stride = 0;
for (auto& element : m_Elements)
{
element.Offset = offset;
offset += element.Size;
m_Stride += element.Size;
}
}
private:
std::vector<BufferElement> m_Elements;
uint32_t m_Stride = 0;
};
class VertexBuffer
{
public:
virtual ~VertexBuffer() = default;
virtual void Bind() const = 0;
virtual void Unbind() const = 0;
virtual void SetData(const void* data, uint32_t size) = 0;
virtual void SetLayout(const BufferLayout& layout) = 0;
virtual const BufferLayout& GetLayout() const = 0;
static Ref<VertexBuffer> Create(uint32_t size);
static Ref<VertexBuffer> Create(float* vertices, uint32_t size);
};
class IndexBuffer
{
public:
virtual ~IndexBuffer() = default;
virtual void Bind() const = 0;
virtual void Unbind() const = 0;
virtual uint32_t GetCount() const = 0;
static Ref<IndexBuffer> Create(uint32_t* indices, uint32_t count);
};
}
|
/*
* D3D12Device.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "D3D12Device.h"
#include "../DXCommon/DXCore.h"
namespace LLGL
{
/* ----- Device creation ----- */
bool D3D12Device::CreateDXDevice(HRESULT& hr, IDXGIAdapter* adapter, const std::vector<D3D_FEATURE_LEVEL>& featureLevels)
{
for (auto level : featureLevels)
{
/* Try to create D3D12 device with current feature level */
hr = D3D12CreateDevice(adapter, level, IID_PPV_ARGS(device_.ReleaseAndGetAddressOf()));
if (SUCCEEDED(hr))
{
/* Store selected feature level */
featureLevel_ = level;
#ifdef LLGL_DEBUG
if (SUCCEEDED(device_.As(&infoQueue_)))
DenyLowSeverityWarnings();
#endif
return true;
}
}
return false;
}
ComPtr<ID3D12CommandQueue> D3D12Device::CreateDXCommandQueue(D3D12_COMMAND_LIST_TYPE type)
{
ComPtr<ID3D12CommandQueue> cmdQueue;
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
{
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
queueDesc.Type = type;
}
auto hr = device_->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(cmdQueue.ReleaseAndGetAddressOf()));
DXThrowIfCreateFailed(hr, "ID3D12CommandQueue");
return cmdQueue;
}
ComPtr<ID3D12CommandAllocator> D3D12Device::CreateDXCommandAllocator(D3D12_COMMAND_LIST_TYPE type)
{
ComPtr<ID3D12CommandAllocator> commandAlloc;
auto hr = device_->CreateCommandAllocator(type, IID_PPV_ARGS(commandAlloc.ReleaseAndGetAddressOf()));
DXThrowIfCreateFailed(hr, "ID3D12CommandAllocator");
return commandAlloc;
}
ComPtr<ID3D12GraphicsCommandList> D3D12Device::CreateDXCommandList(D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* cmdAllocator)
{
ComPtr<ID3D12GraphicsCommandList> commandList;
auto hr = device_->CreateCommandList(0, type, cmdAllocator, nullptr, IID_PPV_ARGS(commandList.ReleaseAndGetAddressOf()));
DXThrowIfCreateFailed(hr, "ID3D12GraphicsCommandList");
return commandList;
}
ComPtr<ID3D12PipelineState> D3D12Device::CreateDXGraphicsPipelineState(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc)
{
ComPtr<ID3D12PipelineState> pipelineState;
auto hr = device_->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(pipelineState.ReleaseAndGetAddressOf()));
DXThrowIfCreateFailed(hr, "ID3D12PipelineState");
return pipelineState;
}
ComPtr<ID3D12PipelineState> D3D12Device::CreateDXComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc)
{
ComPtr<ID3D12PipelineState> pipelineState;
auto hr = device_->CreateComputePipelineState(&desc, IID_PPV_ARGS(pipelineState.ReleaseAndGetAddressOf()));
DXThrowIfCreateFailed(hr, "ID3D12PipelineState");
return pipelineState;
}
ComPtr<ID3D12DescriptorHeap> D3D12Device::CreateDXDescriptorHeap(const D3D12_DESCRIPTOR_HEAP_DESC& desc)
{
ComPtr<ID3D12DescriptorHeap> descHeap;
auto hr = device_->CreateDescriptorHeap(&desc, IID_PPV_ARGS(descHeap.ReleaseAndGetAddressOf()));
DXThrowIfCreateFailed(hr, "ID3D12DescriptorHeap");
return descHeap;
}
ComPtr<ID3D12QueryHeap> D3D12Device::CreateDXQueryHeap(const D3D12_QUERY_HEAP_DESC& desc)
{
ComPtr<ID3D12QueryHeap> queryHeap;
auto hr = device_->CreateQueryHeap(&desc, IID_PPV_ARGS(queryHeap.ReleaseAndGetAddressOf()));
DXThrowIfCreateFailed(hr, "ID3D12QueryHeap");
return queryHeap;
}
/* ----- Data queries ----- */
DXGI_SAMPLE_DESC D3D12Device::FindSuitableSampleDesc(DXGI_FORMAT format, UINT maxSampleCount) const
{
D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS feature;
feature.Format = format;
feature.Flags = D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE;
feature.NumQualityLevels = 0;
for (; maxSampleCount > 1u; --maxSampleCount)
{
feature.SampleCount = maxSampleCount;
if (device_->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &feature, sizeof(feature)) == S_OK)
{
if (feature.NumQualityLevels > 0)
return { feature.SampleCount, feature.NumQualityLevels - 1 };
}
}
return { 1u, 0u };
}
DXGI_SAMPLE_DESC D3D12Device::FindSuitableSampleDesc(std::size_t numFormats, const DXGI_FORMAT* formats, UINT maxSampleCount) const
{
DXGI_SAMPLE_DESC sampleDesc = { maxSampleCount, 0 };
for (std::size_t i = 0; i < numFormats; ++i)
{
if (formats[i] != DXGI_FORMAT_UNKNOWN)
sampleDesc = FindSuitableSampleDesc(formats[i], sampleDesc.Count);
}
return sampleDesc;
}
/*
* ======= Private: =======
*/
#ifdef LLGL_DEBUG
void D3D12Device::DenyLowSeverityWarnings()
{
/*
Disable D3D debug warnings when RTVs or DSVs are cleared with different values
than the resource was initialized with, as this can happen constantly.
*/
D3D12_MESSAGE_SEVERITY severities[] =
{
D3D12_MESSAGE_SEVERITY_INFO,
};
D3D12_MESSAGE_ID denyIDs[] =
{
D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE,
D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE,
};
D3D12_INFO_QUEUE_FILTER filter = {};
{
filter.DenyList.NumSeverities = sizeof(severities)/sizeof(severities[0]);
filter.DenyList.pSeverityList = severities;
filter.DenyList.NumIDs = sizeof(denyIDs)/sizeof(denyIDs[0]);
filter.DenyList.pIDList = denyIDs;
}
infoQueue_->PushStorageFilter(&filter);
}
#endif // /LLGL_DEBUG
} // /namespace LLGL
// ================================================================================
|
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CXformDynamicGet2DynamicTableScan.cpp
//
// @doc:
// Implementation of transform
//---------------------------------------------------------------------------
#include "gpopt/xforms/CXformDynamicGet2DynamicTableScan.h"
#include "gpos/base.h"
#include "gpopt/metadata/CTableDescriptor.h"
#include "gpopt/operators/ops.h"
using namespace gpopt;
//---------------------------------------------------------------------------
// @function:
// CXformDynamicGet2DynamicTableScan::CXformDynamicGet2DynamicTableScan
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CXformDynamicGet2DynamicTableScan::CXformDynamicGet2DynamicTableScan(
CMemoryPool *mp)
: CXformImplementation(
// pattern
GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CLogicalDynamicGet(mp)))
{
}
//---------------------------------------------------------------------------
// @function:
// CXformDynamicGet2DynamicTableScan::Transform
//
// @doc:
// Actual transformation
//
//---------------------------------------------------------------------------
void
CXformDynamicGet2DynamicTableScan::Transform(CXformContext *pxfctxt,
CXformResult *pxfres,
CExpression *pexpr) const
{
GPOS_ASSERT(NULL != pxfctxt);
GPOS_ASSERT(FPromising(pxfctxt->Pmp(), this, pexpr));
GPOS_ASSERT(FCheckPattern(pexpr));
CLogicalDynamicGet *popGet = CLogicalDynamicGet::PopConvert(pexpr->Pop());
CMemoryPool *mp = pxfctxt->Pmp();
// create/extract components for alternative
CName *pname = GPOS_NEW(mp) CName(mp, popGet->Name());
CTableDescriptor *ptabdesc = popGet->Ptabdesc();
ptabdesc->AddRef();
CColRefArray *pdrgpcrOutput = popGet->PdrgpcrOutput();
GPOS_ASSERT(NULL != pdrgpcrOutput);
pdrgpcrOutput->AddRef();
CColRef2dArray *pdrgpdrgpcrPart = popGet->PdrgpdrgpcrPart();
pdrgpdrgpcrPart->AddRef();
popGet->Ppartcnstr()->AddRef();
popGet->PpartcnstrRel()->AddRef();
// create alternative expression
CExpression *pexprAlt = GPOS_NEW(mp)
CExpression(mp, GPOS_NEW(mp) CPhysicalDynamicTableScan(
mp, popGet->IsPartial(), pname, ptabdesc,
popGet->UlOpId(), popGet->ScanId(), pdrgpcrOutput,
pdrgpdrgpcrPart, popGet->UlSecondaryScanId(),
popGet->Ppartcnstr(), popGet->PpartcnstrRel()));
// add alternative to transformation result
pxfres->Add(pexprAlt);
}
// EOF
|
#include <GL/glut.h> // Header File For The GLUT Library
#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
#include <unistd.h>
void display(){
glClearColor(1.0f, 0.5f, 0.5f, 1.0f); // Seta Background
glClear(GL_COLOR_BUFFER_BIT); // Limpa o collor buffer
glTranslatef(0.0f,0.0f,-6.0f); //muda a perspectiva
glutSwapBuffers(); // Renderizar
}
int main(int argc, char** argv) {
glutInit(&argc, argv); // Initialize GLUT
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);
glutCreateWindow("Pratica 02 - Inserir plano de fundo"); // Cria Janela com nome especificado
glutInitWindowSize(640, 640); // Seta resolução
glutInitWindowPosition(0, 0); // Posição inicial na tela
glutDisplayFunc(display);
glutIdleFunc(&display);
glutMainLoop();
return 0;
}
|
/* Integration test kernel for whether pipe handles work
(C) 2019 Niall Douglas <http://www.nedproductions.biz/> (2 commits)
File Created: Nov 2019
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 in the accompanying file
Licence.txt or 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.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include "../test_kernel_decl.hpp"
#include <future>
#include <unordered_set>
static inline void TestBlockingPipeHandle()
{
namespace llfio = LLFIO_V2_NAMESPACE;
auto readerthread = std::async([] { // This immediately blocks in blocking mode
llfio::pipe_handle reader = llfio::pipe_handle::pipe_create("llfio-pipe-handle-test").value();
llfio::byte buffer[64];
auto read = reader.read(0, {{buffer, 64}}).value();
BOOST_REQUIRE(read == 5);
BOOST_CHECK(0 == memcmp(buffer, "hello", 5));
reader.close().value();
});
auto begin = std::chrono::steady_clock::now();
while(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - begin).count() < 100)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if(std::future_status::ready == readerthread.wait_for(std::chrono::seconds(0)))
{
readerthread.get(); // rethrow exception
}
llfio::pipe_handle writer;
begin = std::chrono::steady_clock::now();
while(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - begin).count() < 1000)
{
auto r = llfio::pipe_handle::pipe_open("llfio-pipe-handle-test");
if(r)
{
writer = std::move(r.value());
break;
}
}
BOOST_REQUIRE(writer.is_valid());
auto written = writer.write(0, {{(const llfio::byte *) "hello", 5}}).value();
BOOST_REQUIRE(written == 5);
writer.barrier().value();
writer.close().value();
readerthread.get();
}
static inline void TestNonBlockingPipeHandle()
{
namespace llfio = LLFIO_V2_NAMESPACE;
llfio::pipe_handle reader = llfio::pipe_handle::pipe_create("llfio-pipe-handle-test", llfio::pipe_handle::caching::all, llfio::pipe_handle::flag::multiplexable).value();
llfio::byte buffer[64];
{ // no writer, so non-blocking read should time out
auto read = reader.read(0, {{buffer, 64}}, std::chrono::milliseconds(0));
BOOST_REQUIRE(read.has_error());
BOOST_REQUIRE(read.error() == llfio::errc::timed_out);
}
{ // no writer, so blocking read should time out
auto read = reader.read(0, {{buffer, 64}}, std::chrono::seconds(1));
BOOST_REQUIRE(read.has_error());
BOOST_REQUIRE(read.error() == llfio::errc::timed_out);
}
llfio::pipe_handle writer = llfio::pipe_handle::pipe_open("llfio-pipe-handle-test", llfio::pipe_handle::caching::all, llfio::pipe_handle::flag::multiplexable).value();
auto written = writer.write(0, {{(const llfio::byte *) "hello", 5}}).value();
BOOST_REQUIRE(written == 5);
// writer.barrier().value(); // would block until pipe drained by reader
// writer.close().value(); // would cause all further reads to fail due to pipe broken
auto read = reader.read(0, {{buffer, 64}}, std::chrono::milliseconds(0));
BOOST_REQUIRE(read.value() == 5);
BOOST_CHECK(0 == memcmp(buffer, "hello", 5));
writer.barrier().value(); // must not block nor fail
writer.close().value();
reader.close().value();
}
#if LLFIO_ENABLE_TEST_IO_MULTIPLEXERS
static inline void TestMultiplexedPipeHandle()
{
static constexpr size_t MAX_PIPES = 64;
namespace llfio = LLFIO_V2_NAMESPACE;
auto test_multiplexer = [](llfio::io_multiplexer_ptr multiplexer) {
std::vector<llfio::pipe_handle> read_pipes, write_pipes;
std::vector<size_t> received_for(MAX_PIPES);
struct checking_receiver final : public llfio::io_multiplexer::io_operation_state_visitor
{
size_t myindex;
std::unique_ptr<llfio::byte[]> io_state_ptr;
std::vector<size_t> &received_for;
union {
llfio::byte _buffer[sizeof(size_t)];
size_t _index;
};
llfio::pipe_handle::buffer_type buffer;
llfio::io_multiplexer::io_operation_state *io_state{nullptr};
checking_receiver(size_t _myindex, llfio::io_multiplexer_ptr &multiplexer, std::vector<size_t> &r)
: myindex(_myindex)
, io_state_ptr(std::make_unique<llfio::byte[]>(multiplexer->io_state_requirements().first))
, received_for(r)
, buffer(_buffer, sizeof(_buffer))
{
memset(_buffer, 0, sizeof(_buffer));
}
checking_receiver(const checking_receiver &) = delete;
checking_receiver(checking_receiver &&o) = default;
checking_receiver &operator=(const checking_receiver &) = delete;
checking_receiver &operator=(checking_receiver &&) = default;
~checking_receiver()
{
if(io_state != nullptr)
{
if(!is_finished(io_state->current_state()))
{
abort();
}
io_state->~io_operation_state();
io_state = nullptr;
}
}
// Initiated the read
llfio::result<void> read_begin(llfio::io_multiplexer_ptr &multiplexer, llfio::io_handle &h)
{
if(io_state != nullptr)
{
BOOST_REQUIRE(is_finished(io_state->current_state()));
io_state->~io_operation_state();
io_state = nullptr;
}
buffer = {_buffer, sizeof(_buffer)};
io_state = multiplexer->construct_and_init_io_operation({io_state_ptr.get(), 4096 /*lies*/}, &h, this, {}, {}, llfio::pipe_handle::io_request<llfio::pipe_handle::buffers_type>({&buffer, 1}, 0));
return llfio::success();
}
// Called if the read did not complete immediately
virtual void read_initiated(llfio::io_multiplexer::io_operation_state::lock_guard & /*g*/, llfio::io_operation_state_type /*former*/) override { std::cout << " Pipe " << myindex << " will complete read later" << std::endl; }
// Called when the read completes
virtual bool read_completed(llfio::io_multiplexer::io_operation_state::lock_guard & /*g*/, llfio::io_operation_state_type former, llfio::pipe_handle::io_result<llfio::pipe_handle::buffers_type> &&res) override
{
if(is_initialised(former))
{
std::cout << " Pipe " << myindex << " read completes immediately" << std::endl;
}
else
{
std::cout << " Pipe " << myindex << " read completes asynchronously" << std::endl;
}
BOOST_CHECK(res.has_value());
if(res)
{
BOOST_REQUIRE(res.value().size() == 1);
BOOST_CHECK(res.value()[0].data() == _buffer);
BOOST_CHECK(res.value()[0].size() == sizeof(size_t));
BOOST_REQUIRE(_index < MAX_PIPES);
BOOST_CHECK(_index == myindex);
received_for[_index]++;
}
return true;
}
// Called when the state for the read can be disposed
virtual void read_finished(llfio::io_multiplexer::io_operation_state::lock_guard & /*g*/, llfio::io_operation_state_type former) override
{
std::cout << " Pipe " << myindex << " read finishes" << std::endl;
BOOST_REQUIRE(former == llfio::io_operation_state_type::read_completed);
}
};
std::vector<checking_receiver> async_reads;
for(size_t n = 0; n < MAX_PIPES; n++)
{
auto ret = llfio::pipe_handle::anonymous_pipe(llfio::pipe_handle::caching::reads, llfio::pipe_handle::flag::multiplexable).value();
ret.first.set_multiplexer(multiplexer.get()).value();
async_reads.push_back(checking_receiver(n, multiplexer, received_for));
read_pipes.push_back(std::move(ret.first));
write_pipes.push_back(std::move(ret.second));
}
auto writerthread = std::async([&] {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
for(size_t n = MAX_PIPES - 1; n < MAX_PIPES; n--)
{
auto r = write_pipes[n].write(0, {{(llfio::byte *) &n, sizeof(n)}});
if(!r)
{
abort();
}
}
});
// Start the pipe reads. They cannot move in memory until complete
for(size_t n = 0; n < MAX_PIPES; n++)
{
async_reads[n].read_begin(multiplexer, read_pipes[n]).value();
}
// Wait for all reads to complete
for(size_t n = 0; n < MAX_PIPES; n++)
{
// Spin until this i/o completes
for(;;)
{
auto state = multiplexer->check_io_operation(async_reads[n].io_state);
if(is_completed(state) || is_finished(state))
{
break;
}
}
}
for(size_t n = 0; n < MAX_PIPES; n++)
{
BOOST_CHECK(received_for[n] == 1);
}
// Wait for all reads to finish
for(size_t n = 0; n < MAX_PIPES; n++)
{
llfio::io_operation_state_type state;
while(!is_finished(state = async_reads[n].io_state->current_state()))
{
multiplexer->check_for_any_completed_io().value();
}
}
writerthread.get();
};
#ifdef _WIN32
std::cout << "\nSingle threaded IOCP, immediate completions:\n";
test_multiplexer(llfio::test::multiplexer_win_iocp(1, false).value());
std::cout << "\nSingle threaded IOCP, reactor completions:\n";
test_multiplexer(llfio::test::multiplexer_win_iocp(1, true).value());
std::cout << "\nMultithreaded IOCP, immediate completions:\n";
test_multiplexer(llfio::test::multiplexer_win_iocp(2, false).value());
std::cout << "\nMultithreaded IOCP, reactor completions:\n";
test_multiplexer(llfio::test::multiplexer_win_iocp(2, true).value());
#else
#error Not implemented yet
#endif
}
#if LLFIO_ENABLE_COROUTINES
static inline void TestCoroutinedPipeHandle()
{
static constexpr size_t MAX_PIPES = 70;
namespace llfio = LLFIO_V2_NAMESPACE;
auto test_multiplexer = [](llfio::io_multiplexer_ptr multiplexer) {
struct coroutine
{
llfio::pipe_handle read_pipe, write_pipe;
size_t received_for{0};
explicit coroutine(llfio::pipe_handle &&r, llfio::pipe_handle &&w)
: read_pipe(std::move(r))
, write_pipe(std::move(w))
{
}
llfio::eager<llfio::result<void>> operator()()
{
union {
llfio::byte _buffer[sizeof(size_t)];
size_t _index;
};
llfio::pipe_handle::buffer_type buffer;
for(;;)
{
buffer = {_buffer, sizeof(_buffer)};
// This will never return if the coroutine gets cancelled
auto r = co_await read_pipe.co_read({{&buffer, 1}, 0});
if(!r)
{
co_return std::move(r).error();
}
BOOST_CHECK(r.value().size() == 1);
BOOST_CHECK(r.value()[0].size() == sizeof(_buffer));
received_for+=_index;
}
}
};
std::vector<coroutine> coroutines;
for(size_t n = 0; n < MAX_PIPES; n++)
{
auto ret = llfio::pipe_handle::anonymous_pipe(llfio::pipe_handle::caching::reads, llfio::pipe_handle::flag::multiplexable).value();
ret.first.set_multiplexer(multiplexer.get()).value();
coroutines.push_back(coroutine(std::move(ret.first), std::move(ret.second)));
}
// Start the coroutines, all of whom will begin a read and then suspend
std::vector<llfio::optional<llfio::eager<llfio::result<void>>>> states(MAX_PIPES);
for(size_t n = 0; n < MAX_PIPES; n++)
{
states[n].emplace(coroutines[n]());
}
// Write to all the pipes, then pump coroutine resumption until all completions done
size_t count = 0, failures = 0;
for(size_t i = 1; i <= 10; i++)
{
std::cout << "\nWrite no " << i << std::endl;
for(size_t n = MAX_PIPES - 1; n < MAX_PIPES; n--)
{
coroutines[n].write_pipe.write(0, {{(llfio::byte *) &i, sizeof(i)}}).value();
}
// Take a copy of all pending i/o
for(;;)
{
// Have the kernel tell me when an i/o completion is ready
auto r = multiplexer->check_for_any_completed_io();
if(r.value().initiated_ios_completed == 0)
{
break;
}
}
count += i;
for(size_t n = 0; n < MAX_PIPES; n++)
{
if(coroutines[n].received_for != count)
{
std::cout << "Coroutine " << n << " has count " << coroutines[n].received_for << " instead of " << count << std::endl;
failures++;
}
BOOST_CHECK(coroutines[n].received_for == count);
}
BOOST_REQUIRE(failures == 0);
}
// Rethrow any failures
for(size_t n = 0; n < MAX_PIPES; n++)
{
if(states[n]->await_ready())
{
states[n]->await_resume().value();
}
}
// Destruction of coroutines when they are suspended must work.
// This will cancel any pending i/o and immediately exit the
// coroutines
states.clear();
// Now clear all the coroutines
coroutines.clear();
};
#ifdef _WIN32
std::cout << "\nSingle threaded IOCP, immediate completions:\n";
test_multiplexer(llfio::test::multiplexer_win_iocp(1, false).value());
std::cout << "\nSingle threaded IOCP, reactor completions:\n";
test_multiplexer(llfio::test::multiplexer_win_iocp(1, true).value());
std::cout << "\nMultithreaded IOCP, immediate completions:\n";
test_multiplexer(llfio::test::multiplexer_win_iocp(2, false).value());
std::cout << "\nMultithreaded IOCP, reactor completions:\n";
test_multiplexer(llfio::test::multiplexer_win_iocp(2, true).value());
#else
#error Not implemented yet
#endif
}
#endif
#endif
KERNELTEST_TEST_KERNEL(integration, llfio, pipe_handle, blocking, "Tests that blocking llfio::pipe_handle works as expected", TestBlockingPipeHandle())
KERNELTEST_TEST_KERNEL(integration, llfio, pipe_handle, nonblocking, "Tests that nonblocking llfio::pipe_handle works as expected", TestNonBlockingPipeHandle())
#if LLFIO_ENABLE_TEST_IO_MULTIPLEXERS
KERNELTEST_TEST_KERNEL(integration, llfio, pipe_handle, multiplexed, "Tests that multiplexed llfio::pipe_handle works as expected", TestMultiplexedPipeHandle())
#if LLFIO_ENABLE_COROUTINES
KERNELTEST_TEST_KERNEL(integration, llfio, pipe_handle, coroutined, "Tests that coroutined llfio::pipe_handle works as expected", TestCoroutinedPipeHandle())
#endif
#endif
|
#include "../../H3D/OpenGL/GLMultithreading.hpp"
/////////////////////////////////////////////////////////////////
// Implementation of globalCallWorkerThread
/////////////////////////////////////////////////////////////////
namespace h3d {
namespace GL {
globalCallWorkerThread::globalCallWorkerThread() {}
globalCallWorkerThread::~globalCallWorkerThread() {}
void globalCallWorkerThread::m_callFunction(GLContext &context,bool* condition)
{
GL::Packages::ALL_PACKAGES* __restrict pPacket;
bool temp_condition = *condition;
while (temp_condition == true)
{
{
std::lock_guard<std::mutex> mut(m_mutex_queue);
while (!m_queue.empty()) {
//m_queue.front().execute((GL::base*)0);
m_queue.pop_front();
}
}
}
}
void globalCallWorkerThread::startup(GLContext &context)
{
//m_callThread = std::thread(m_callFunction, context,(bool*)&m_callFunctionRunning);
}
void globalCallWorkerThread::shutdown()
{
m_callThread.join();
}
void globalCallWorkerThread::execute(void)
{
}
void globalCallWorkerThread::setState(GLenum cap, GLboolean value)
{
m_mutex_setState.lock();
switch (cap)
{
case GL_DEPTH_TEST:
if (m_state.texture_2d == value) return;
m_state.texture_2d = value; break;
if (m_state.depth_test == value) return;
m_state.depth_test = value; break;
if (m_state.stencil_test == value) return;
m_state.stencil_test = value; break;
if (m_state.depth_clamp == value) return;
m_state.depth_clamp = value; break;
default: break;
}
m_mutex_setState.unlock();
const h3d::GL::Packages::gl_ENABLE_DISABLE* __restrict pPacket =
m_nextPacket<h3d::GL::Packages::gl_ENABLE_DISABLE>();
}
}
}
/////////////////////////////////////////////////////////////////
|
// license:BSD-3-Clause
// copyright-holders:Nathan Woods, Raphael Nabet, Miodrag Milanovic
/*********************************************************************
Code to interface the image code with harddisk core.
Raphael Nabet 2003
Update: 23-Feb-2004 - Unlike floppy disks, for which we support
myriad formats on many systems, it is my intention for MESS to
standardize on the CHD file format for hard drives so I made a few
changes to support this
*********************************************************************/
#include "emu.h"
#include "harddriv.h"
#include "emuopts.h"
#include "harddisk.h"
#include "romload.h"
#include "opresolv.h"
OPTION_GUIDE_START(hd_option_guide)
OPTION_INT('C', "cylinders", "Cylinders")
OPTION_INT('H', "heads", "Heads")
OPTION_INT('S', "sectors", "Sectors")
OPTION_INT('L', "sectorlength", "Sector Bytes")
OPTION_INT('K', "hunksize", "Hunk Bytes")
OPTION_GUIDE_END
static char const *const hd_option_spec =
"C1-[512]-1024;H1/2/[4]/8;S1-[16]-64;L128/256/[512]/1024;K512/1024/2048/[4096]";
// device type definition
DEFINE_DEVICE_TYPE(HARDDISK, harddisk_image_device, "harddisk_image", "Harddisk")
//-------------------------------------------------
// harddisk_image_device - constructor
//-------------------------------------------------
harddisk_image_device::harddisk_image_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: harddisk_image_device(mconfig, HARDDISK, tag, owner, clock)
{
}
//-------------------------------------------------
// harddisk_image_device - constructor for subclasses
//-------------------------------------------------
harddisk_image_device::harddisk_image_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, type, tag, owner, clock),
device_image_interface(mconfig, *this),
m_chd(nullptr),
m_hard_disk_handle(nullptr),
m_device_image_load(*this),
m_device_image_unload(*this),
m_interface(nullptr)
{
}
//-------------------------------------------------
// harddisk_image_device - destructor
//-------------------------------------------------
harddisk_image_device::~harddisk_image_device()
{
}
//-------------------------------------------------
// device_config_complete - perform any
// operations now that the configuration is
// complete
//-------------------------------------------------
void harddisk_image_device::device_config_complete()
{
add_format("chd", "CHD Hard drive", "chd,hd,hdv,2mg,hdi", hd_option_spec);
}
const util::option_guide &harddisk_image_device::create_option_guide() const
{
return hd_option_guide;
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void harddisk_image_device::device_start()
{
m_device_image_load.resolve();
m_device_image_unload.resolve();
m_chd = nullptr;
// try to locate the CHD from a DISK_REGION
chd_file *handle = machine().rom_load().get_disk_handle(tag());
if (handle != nullptr)
{
m_hard_disk_handle = hard_disk_open(handle);
}
else
{
m_hard_disk_handle = nullptr;
}
}
void harddisk_image_device::device_stop()
{
if (m_hard_disk_handle != nullptr)
{
hard_disk_close(m_hard_disk_handle);
m_hard_disk_handle = nullptr;
}
}
image_init_result harddisk_image_device::call_load()
{
image_init_result our_result;
our_result = internal_load_hd();
/* Check if there is an image_load callback defined */
if (!m_device_image_load.isnull())
{
/* Let the override do some additional work/checks */
our_result = m_device_image_load(*this);
}
return our_result;
}
image_init_result harddisk_image_device::call_create(int create_format, util::option_resolution *create_args)
{
if (!create_args)
throw emu_fatalerror("harddisk_image_device::call_create: Expected create_args to not be nullptr");
const uint32_t cylinders = create_args->lookup_int('C');
const uint32_t heads = create_args->lookup_int('H');
const uint32_t sectors = create_args->lookup_int('S');
const uint32_t sectorsize = create_args->lookup_int('L');
const uint32_t hunksize = create_args->lookup_int('K');
const uint32_t totalsectors = cylinders * heads * sectors;
/* create the CHD file */
chd_codec_type compression[4] = { CHD_CODEC_NONE };
util::core_file::ptr proxy;
std::error_condition err = util::core_file::open_proxy(image_core_file(), proxy);
if (!err)
err = m_origchd.create(std::move(proxy), uint64_t(totalsectors) * uint64_t(sectorsize), hunksize, sectorsize, compression);
if (err)
return image_init_result::FAIL;
/* if we created the image and hence, have metadata to set, set the metadata */
err = m_origchd.write_metadata(HARD_DISK_METADATA_TAG, 0, string_format(HARD_DISK_METADATA_FORMAT, cylinders, heads, sectors, sectorsize));
m_origchd.close();
if (err)
return image_init_result::FAIL;
return internal_load_hd();
}
void harddisk_image_device::call_unload()
{
/* Check if there is an image_unload callback defined */
if (!m_device_image_unload.isnull())
m_device_image_unload(*this);
if (m_hard_disk_handle)
{
hard_disk_close(m_hard_disk_handle);
m_hard_disk_handle = nullptr;
}
if (m_chd)
{
m_origchd.close();
m_diffchd.close();
}
m_chd = nullptr;
}
/*-------------------------------------------------
open_disk_diff - open a DISK diff file
-------------------------------------------------*/
static std::error_condition open_disk_diff(emu_options &options, const char *name, chd_file &source, chd_file &diff_chd)
{
std::string fname = std::string(name).append(".dif");
/* try to open the diff */
//printf("Opening differencing image file: %s\n", fname.c_str());
emu_file diff_file(options.diff_directory(), OPEN_FLAG_READ | OPEN_FLAG_WRITE);
std::error_condition filerr = diff_file.open(fname);
if (!filerr)
{
std::string fullpath(diff_file.fullpath());
diff_file.close();
//printf("Opening differencing image file: %s\n", fullpath.c_str());
return diff_chd.open(fullpath, true, &source);
}
/* didn't work; try creating it instead */
//printf("Creating differencing image: %s\n", fname.c_str());
diff_file.set_openflags(OPEN_FLAG_READ | OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS);
filerr = diff_file.open(fname);
if (!filerr)
{
std::string fullpath(diff_file.fullpath());
diff_file.close();
/* create the CHD */
//printf("Creating differencing image file: %s\n", fupointllpath.c_str());
chd_codec_type compression[4] = { CHD_CODEC_NONE };
std::error_condition err = diff_chd.create(fullpath, source.logical_bytes(), source.hunk_bytes(), compression, source);
if (err)
return err;
return diff_chd.clone_all_metadata(source);
}
return std::errc::no_such_file_or_directory;
}
image_init_result harddisk_image_device::internal_load_hd()
{
std::error_condition err;
m_chd = nullptr;
uint8_t header[64];
if (m_hard_disk_handle)
{
hard_disk_close(m_hard_disk_handle);
m_hard_disk_handle = nullptr;
}
/* open the CHD file */
if (loaded_through_softlist())
{
m_chd = machine().rom_load().get_disk_handle(device().subtag("harddriv").c_str());
}
else
{
fseek(0, SEEK_SET);
fread(header, 64);
fseek(0, SEEK_SET);
if (!memcmp("MComprHD", header, 8))
{
util::core_file::ptr proxy;
err = util::core_file::open_proxy(image_core_file(), proxy);
if (!err)
err = m_origchd.open(std::move(proxy), true);
if (!err)
{
m_chd = &m_origchd;
}
else if (err == chd_file::error::FILE_NOT_WRITEABLE)
{
err = util::core_file::open_proxy(image_core_file(), proxy);
if (!err)
err = m_origchd.open(std::move(proxy), false);
if (!err)
{
err = open_disk_diff(device().machine().options(), basename_noext(), m_origchd, m_diffchd);
if (!err)
{
m_chd = &m_diffchd;
}
}
}
}
}
if (m_chd)
{
/* open the hard disk file */
m_hard_disk_handle = hard_disk_open(m_chd);
if (m_hard_disk_handle)
return image_init_result::PASS;
}
else
{
if (is_open())
{
uint32_t skip = 0;
// check for 2MG format
if (!memcmp(header, "2IMG", 4))
{
skip = header[0x18] | (header[0x19] << 8) | (header[0x1a] << 16) | (header[0x1b] << 24);
osd_printf_verbose("harddriv: detected 2MG, creator is %c%c%c%c, data at %08x\n", header[4], header[5], header[6], header[7], skip);
}
// check for HDI format
else if (is_filetype("hdi"))
{
skip = header[0x8] | (header[0x9] << 8) | (header[0xa] << 16) | (header[0xb] << 24);
uint32_t data_size = header[0xc] | (header[0xd] << 8) | (header[0xe] << 16) | (header[0xf] << 24);
if (data_size == length() - skip)
{
osd_printf_verbose("harddriv: detected Anex86 HDI, data at %08x\n", skip);
}
else
{
skip = 0;
}
}
m_hard_disk_handle = hard_disk_open(image_core_file(), skip);
if (m_hard_disk_handle)
return image_init_result::PASS;
}
return image_init_result::FAIL;
}
/* if we had an error, close out the CHD */
m_origchd.close();
m_diffchd.close();
m_chd = nullptr;
seterror(err, nullptr);
return image_init_result::FAIL;
}
/*************************************
*
* Get the CHD file (from the src/chd.c core)
* after an image has been opened with the hd core
*
*************************************/
chd_file *harddisk_image_device::get_chd_file()
{
chd_file *result = nullptr;
hard_disk_file *hd_file = get_hard_disk_file();
if (hd_file)
result = hard_disk_get_chd(hd_file);
return result;
}
|
// TProgressDialog.cpp : implementation file
//
#include "stdafx.h"
#include "RNAstructure.h"
#include "TProgressDialog.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// TProgressDialog
IMPLEMENT_DYNCREATE(TProgressDialog, CMDIChildWnd)
//caption is a pointer to the window's caption
TProgressDialog::TProgressDialog()
{
CMDIChildWnd::CMDIChildWnd();
}
TProgressDialog::~TProgressDialog()
{
delete progressbar;
}
BEGIN_MESSAGE_MAP(TProgressDialog, CMDIChildWnd)
//{{AFX_MSG_MAP(TProgressDialog)
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// TProgressDialog message handlers
//call this function with the percent completed
void TProgressDialog::update(int frac) {
progressbar->SetPos(frac);
UpdateWindow();
}
int TProgressDialog::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMDIChildWnd::OnCreate(lpCreateStruct) == -1) return -1;
progressbar = new CProgressCtrl();
progressbar->Create(WS_CHILD|WS_VISIBLE|WS_BORDER|PBS_SMOOTH,CRect(5,15,180,45),this,IDC_PROGRESSBAR);
progressbar->SetStep(1);
return 0;
}
|
/*
__ _____ _____ _____
__| | __| | | | JSON for Modern C++ (test suite)
| | |__ | | | | | | version 3.10.4
|_____|_____|_____|_|___| https://github.com/nlohmann/json
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.
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 "doctest_compatibility.h"
#include <nlohmann/json.hpp>
using nlohmann::json;
TEST_CASE("other constructors and destructor")
{
SECTION("copy constructor")
{
SECTION("object")
{
json j {{"foo", 1}, {"bar", false}};
json k(j); // NOLINT(performance-unnecessary-copy-initialization)
CHECK(j == k);
}
SECTION("array")
{
json j {"foo", 1, 42.23, false};
json k(j); // NOLINT(performance-unnecessary-copy-initialization)
CHECK(j == k);
}
SECTION("null")
{
json j(nullptr);
json k(j); // NOLINT(performance-unnecessary-copy-initialization)
CHECK(j == k);
}
SECTION("boolean")
{
json j(true);
json k(j); // NOLINT(performance-unnecessary-copy-initialization)
CHECK(j == k);
}
SECTION("string")
{
json j("Hello world");
json k(j); // NOLINT(performance-unnecessary-copy-initialization)
CHECK(j == k);
}
SECTION("number (integer)")
{
json j(42);
json k(j); // NOLINT(performance-unnecessary-copy-initialization)
CHECK(j == k);
}
SECTION("number (unsigned)")
{
json j(42u);
json k(j); // NOLINT(performance-unnecessary-copy-initialization)
CHECK(j == k);
}
SECTION("number (floating-point)")
{
json j(42.23);
json k(j); // NOLINT(performance-unnecessary-copy-initialization)
CHECK(j == k);
}
SECTION("binary")
{
json j = json::binary({1, 2, 3});
json k(j); // NOLINT(performance-unnecessary-copy-initialization)
CHECK(j == k);
}
}
SECTION("move constructor")
{
json j {{"foo", "bar"}, {"baz", {1, 2, 3, 4}}, {"a", 42u}, {"b", 42.23}, {"c", nullptr}};
CHECK(j.type() == json::value_t::object);
json k(std::move(j));
CHECK(k.type() == json::value_t::object);
CHECK(j.type() == json::value_t::null); // NOLINT: access after move is OK here
}
SECTION("copy assignment")
{
SECTION("object")
{
json j {{"foo", 1}, {"bar", false}};
json k;
k = j;
CHECK(j == k);
}
SECTION("array")
{
json j {"foo", 1, 42.23, false};
json k;
k = j;
CHECK(j == k);
}
SECTION("null")
{
json j(nullptr);
json k;
k = j;
CHECK(j == k);
}
SECTION("boolean")
{
json j(true);
json k;
k = j;
CHECK(j == k);
}
SECTION("string")
{
json j("Hello world");
json k;
k = j;
CHECK(j == k);
}
SECTION("number (integer)")
{
json j(42);
json k;
k = j;
CHECK(j == k);
}
SECTION("number (unsigned)")
{
json j(42u);
json k;
k = j;
CHECK(j == k);
}
SECTION("number (floating-point)")
{
json j(42.23);
json k;
k = j;
CHECK(j == k);
}
SECTION("binary")
{
json j = json::binary({1, 2, 3});
json k;
k = j;
CHECK(j == k);
}
}
SECTION("destructor")
{
SECTION("object")
{
auto* j = new json {{"foo", 1}, {"bar", false}}; // NOLINT(cppcoreguidelines-owning-memory)
delete j; // NOLINT(cppcoreguidelines-owning-memory)
}
SECTION("array")
{
auto* j = new json {"foo", 1, 1u, false, 23.42}; // NOLINT(cppcoreguidelines-owning-memory)
delete j; // NOLINT(cppcoreguidelines-owning-memory)
}
SECTION("string")
{
auto* j = new json("Hello world"); // NOLINT(cppcoreguidelines-owning-memory)
delete j; // NOLINT(cppcoreguidelines-owning-memory)
}
}
}
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include "../../../inc/MarlinConfigPre.h"
#if HAS_GRAPHICAL_TFT
extern const uint8_t confirm_64x64x4[2048] = {
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x78, 0xA8, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7C, 0xFC, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xCF, 0xFF, 0xC7, 0x78, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7C, 0xFF, 0xFF, 0xFB, 0x77, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xCF, 0xFF, 0xFF, 0xFF, 0xB7, 0x78, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x87, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA, 0x55, 0x78, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x78, 0xA8, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x78, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x94, 0x44, 0x68, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x8D, 0xFB, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA, 0x44, 0x45, 0x78, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x78, 0xDF, 0xFF, 0xB7, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x87, 0x8D, 0xFF, 0xFF, 0xFB, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF9, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x78, 0xDF, 0xFF, 0xFF, 0xFF, 0xB7, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xA4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x87, 0x8D, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF9, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x87, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB7, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xA4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x87, 0x8C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0x77, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x76, 0xAF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xA7, 0x78, 0x88, 0x88, 0x88, 0x77, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xA4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x86, 0x4B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0x77, 0x88, 0x88, 0x87, 0x8C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x64, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB7, 0x78, 0x88, 0x77, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xA4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0x77, 0x87, 0x7C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF9, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x64, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB7, 0x78, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xA4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0x7C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x65, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x5B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x64, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x5B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x64, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF9, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x65, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xA4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x65, 0xBF, 0xFF, 0xFF, 0xFF, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4B, 0xFF, 0xFF, 0xFA, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x64, 0xBF, 0xFF, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4B, 0xFA, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x65, 0x75, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x65, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88
};
#endif // HAS_GRAPHICAL_TFT
|
#include "stdafx.h"
// Include
#include "UIMgr.h"
// General
#include "UIButton3t.h"
UIButton3t::UIButton3t(IUIMgr* _uimgr) :
UIButton(_uimgr)
{
for (uint32 i = 0; i < 4; i++)
{
buttonsImages[i] = nullptr;
}
}
UIButton3t::~UIButton3t()
{
int x = 0;
}
void UIButton3t::Init(cvec2 _position, cstring _textureName)
{
base::Init(_position, nullptr);
}
void UIButton3t::OnRenderUI()
{
m_SecondImage = nullptr;
switch (buttonStatus)
{
case BUTTON_NORMAL:
m_Image = buttonsImages[0];
break;
case BUTTON_PRESSED:
m_Image = buttonsImages[1];
break;
case BUTTON_HOVER:
m_Image = buttonsImages[0];
m_SecondImage = buttonsImages[2];
break;
case BUTTON_DISABLED:
m_Image = buttonsImages[3];
break;
}
base::OnRenderUI();
}
|
/*
* balanced_diet_stat.cpp
*
* (C) Denis Anikin 2020
*
* Statistics for the balanced diet
*
*/
#include <vector>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <iomanip>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <fstream>
#include <sstream>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
#include "balanced_diet.h"
#include "balanced_diet_mfp.h"
namespace balanced_diet
{
void divide_into_words_tabs(const std::string &str, std::vector<std::string> &words)
{
auto i = str.begin();
while (i != str.end())
{
auto j = std::find(i, str.end(), '\t');
if (j == str.end())
{
words.push_back(std::string(i, str.end()));
break;
}
else
words.push_back(std::string(i, j));
while (*j == '\t')
++j;
i = j;
}
}
bool is_separator(char c)
{
return c == ' ' || c == ',' || c == '/' || c == '"' || c == '\'' || c == '-' || c == '(' || c == ')' || c == '*'
|| (c >= '0' && c <= '9') || c == '{' || c == '}' || c == '.' || c == '&' || c == '%';
}
void divide_into_words2(const std::string &str, std::vector<std::string> &words)
{
auto i = str.begin();
while (i != str.end())
{
auto j = i;
while (!is_separator(*j) && j != str.end())
++j;
if (j == str.end())
{
words.push_back(std::string(i, str.end()));
break;
}
else
words.push_back(std::string(i, j));
while (is_separator(*j))
++j;
i = j;
}
}
void dish_satiety_info::add(int uid, float influence,
float cal, float prot, float fat, float fiber, float carbs, float sodium, float sugar, float potass)
{
influence_ += influence;
// Add influence per a user per this food
if (user_influence_.find(uid) == user_influence_.end())
user_influence_.insert({uid, {0, 0}});
user_influence_[uid].first += influence;
++user_influence_[uid].second;
if (influence >= 0)
++n_dish_good_days_;
else
++n_dish_bad_days_;
cal_ += cal;
prot_ += prot;
fat_ += fat;
fiber_ += fiber;
carbs_ += carbs;
sodium_ += sodium;
sugar_ += sugar;
potass_ += potass;
if (cal)
{
prot_cal_ratio_ += 4.0 * prot / cal;
fat_cal_ratio_ += 9.0 * fat / cal;
fiber_cal_ratio_ += 4.0 * fiber / cal;
sugar_cal_ratio_ += 4.0 * sugar / cal;
sodium_cal_ratio_ += sodium / cal;
potass_cal_ratio_ += potass / cal;
++cardinality_;
}
}
void dish_satiety_info::add_meal_xe(float pe, float fe, float fbe)
{
meal_pe_ += pe;
meal_fe_ += fe;
meal_fbe_ += fbe;
++num_meals_;
}
void dish_satiety_info::make_avg(const std::vector<mfp_user> &mfp_users)
{
if (!user_influence_.empty())
{
// For influence take average from user first and then overall average
// That's to avoid bias towards users who eat some particular food a lot
influence_ = 0;
for (auto &u : user_influence_)
{
influence_ += u.second.first / u.second.second;
// Determine amount of good and bad users who had this dish
// Note: good user is a user who overall reach the goal and the bad one is vice versa
if (mfp_users[u.first].user_total_fact_calories)
{
if (mfp_users[u.first].user_total_fact_calories <= mfp_users[u.first].user_total_goal_calories)
++n_total_good_users_;
else
++n_total_bad_users_;
}
}
influence_ /= user_influence_.size();
//influence_ /= cardinality_;
cal_ /= cardinality_;
prot_ /= cardinality_;
fat_ /= cardinality_;
fiber_ /= cardinality_;
carbs_ /= cardinality_;
sodium_ /= cardinality_;
sugar_ /= cardinality_;
potass_ /= cardinality_;
prot_cal_ratio_ /= cardinality_;
fat_cal_ratio_ /= cardinality_;
fiber_cal_ratio_ /= cardinality_;
sugar_cal_ratio_ /= cardinality_;
sodium_cal_ratio_ /= cardinality_;
potass_cal_ratio_ /= cardinality_;
}
if (num_meals_)
{
meal_pe_ /= num_meals_;
meal_fe_ /= num_meals_;
meal_fbe_ /= num_meals_;
}
}
int mfp_foods::get_dish_id_by_name(const std::string &dish_name)
{
// Determine the dish id
int dish_id;
// If the dish with this name exists then take its id from the map
auto it = dish_name_to_id_.find(dish_name);
if (it != dish_name_to_id_.end())
dish_id = it->second;
// Otherwise create a new dish with id and update the map
else
{
all_dishes_.push_back({});
dish_id = all_dishes_.size()-1;
all_dishes_[dish_id].dish_name_ = dish_name;
dish_name_to_id_.insert({dish_name, dish_id});
}
return dish_id;
}
dish_satiety_info &mfp_foods::get_dish_by_name(const std::string &dish_name)
{
return all_dishes_[get_dish_id_by_name(dish_name)];
}
void mfp_foods::upload_stat(std::istream &is)
{
struct dish_word___
{
std::string dish_word_;
int word_cardinality_ = 0;
int word_good_days_ = 0;
int word_bad_days_ = 0;
std::unordered_set<int> dish_word_users_;
float word_user_prot_cal_ratio_ = 0;
float word_user_fat_cal_ratio_ = 0;
float word_user_fiber_cal_ratio_ = 0;
float word_user_average_fact_calories_ = 0;
}; // struct dish_word___
std::unordered_map<std::string, dish_word___> hash_dish_words;
int n_good_days = 0, n_bad_days = 0;
std::string line;
std::vector<std::string> words;
int j = 0;
while (getline(is, line))
{
//std::cerr << "line: " << line << std::endl;
words.clear();
divide_into_words_tabs(line, words);
int uid = std::stoi(words[0]);
std::string date = words[1];
// Total
float total_fact_cal = 0;
float total_goal_cal = 0;
json j_summary = json::parse(words[3]);
auto &j_total = j_summary["total"];
auto &j_goal = j_summary["goal"];
for (auto &j : j_total)
{
if (j["name"] == "Calories")
total_fact_cal += (int)j["value"];
}
for (auto &j : j_goal)
{
if (j["name"] == "Calories")
total_goal_cal += (int)j["value"];
}
float goal_overfulfilment_percent = (total_goal_cal - total_fact_cal) / total_goal_cal;
// Update per user stat and save info per this day per this user
mfp_users_.resize(uid + 1);
mfp_users_[uid].user_total_fact_calories += total_fact_cal;
mfp_users_[uid].user_total_goal_calories += total_goal_cal;
mfp_users_[uid].days_.push_back({.date_ = date, .total_fact_calories_ = total_fact_cal, .total_goal_calories_ = total_goal_cal});
if (total_goal_cal > 1000 && total_fact_cal > 1000)
{
if (goal_overfulfilment_percent >= 0)
++n_good_days;
else
++n_bad_days;
}
// Insert an entry to the day meal
all_day_meals_.push_back({});
mfp_day_meal ¤t_day_meal = all_day_meals_[all_day_meals_.size()-1];
current_day_meal.total_fact_calories_ = total_fact_cal;
current_day_meal.total_goal_calories_ = total_goal_cal;
// Iterate all meals for this user for this day
json j_meals = json::parse(words[2]);
for (auto &meal : j_meals)
{
//std::cerr << "meal: " << meal << std::endl;
auto &dishes = meal["dishes"];
// Iterate all dishes within a meal
for (auto &dish : dishes)
{
std::string dish_name = dish["name"];
int cal = 0, prot = 0, fat = 0, fiber = 0, carbs = 0, sodium = 0, sugar = 0, potass = 0;
auto &nutrients = dish["nutritions"];
for (auto &nutrient : nutrients)
{
if (nutrient["name"] == "Calories")
cal = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Protein")
prot = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Fat")
fat = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Fiber")
fiber = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Carbs")
carbs = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Sodium")
sodium = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Sugar")
sugar = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Potass.")
potass = std::stoi((std::string)nutrient["value"]);
}
// Calculate dish satiety - that's average influence
// Consider only realistic goals and facts
// Also skip mistakes with calories
if (total_goal_cal > 1000 && total_fact_cal > 1000 && cal > 0 && cal >= prot * 4 && cal >= fat * 9.1)
{
float dish_influence = goal_overfulfilment_percent * cal / total_fact_cal;
if (0
//dish_name == "Dean Street Townhouse - Full English Breakfast, 1 plate" ||
//dish_name == "Mcdonalds - Pancakes 3 With Syrup, 3 pancakes" ||
//dish_name == "Costco - Blueberry Muffin, 1 muffin" ||
//dish_name == "Pilsbury - Cinnamon Rolls / Icing, 3 roll" ||
//dish_name == "Homemade - Bacon Egg and Cheese Sandwich ( White Bread), 1 sandwich" ||
//dish_name == "Homemade - Blueberry Pancakes With Syrup, 4 pancakes"
) // "Breastfeeding - 3-6 Month Old Baby, 1 day")//"Dunkin Donuts - Large Hot Coffee Black, 20 oz")
{
std::cerr << "DISH [" << uid << "]-" << words[1] << "(" << dish_name
<< ") : goal_overfulfilment_percent=" << goal_overfulfilment_percent <<
", cal=" << cal << ", prot=" << prot << ", total_fact_cal=" << total_fact_cal << ", dish_influence=" << dish_influence <<
", total_goal_cal=" << total_goal_cal << std::endl;
}
// Add this dish to the day meal
int dish_id = get_dish_id_by_name(dish_name);
current_day_meal.day_meal_dish_ids_.push_back(dish_id);
mfp_users_[uid].days_[mfp_users_[uid].days_.size() - 1].dish_ids_.push_back(dish_id);
// Add info per this dish
all_dishes_[dish_id].add(uid, dish_influence, cal, prot, fat, fiber, carbs, sodium, sugar, potass);
// Divide the dish name into words and pairs of adjacent words
std::vector<std::string> dish_words_temp, dish_words;
divide_into_words2(dish_name, dish_words_temp);
dish_words = dish_words_temp;
for (int i = 0; i < dish_words_temp.size() - 1; ++i)
dish_words.push_back(dish_words_temp[i] + " " + dish_words_temp[i+1]);
//std::cerr << "dish_name=" << dish_name << std::endl;
// Save the info per each word
/*for (auto &w : dish_words)
{
std::string l_str;
lower_str(w, l_str);
auto &w_info = hash_dish_words[l_str];
++w_info.word_cardinality_;
if (dish_influence >= 0)
++w_info.word_good_days_;
else
++w_info.word_bad_days_;
w_info.dish_word_ = l_str;
//std::cerr << "dish_word: " << w << std::endl;
w_info.dish_word_users_.insert(uid);
}*/
//return;
} // if (total_goal_cal > 1000 && total_fact_cal > 1000 && cal > 0 && cal >= prot * 4 && cal >= fat * 9.1)
//std::cerr << "dish name: " << dish_name << ", cal=" << cal <<
// ", dish_influence: " << std::setprecision(2) << dish_influence * 100 << std::endl;
}
} // for (auto &meal : j_meals)
// Determine PE for this meal
float meal_cal = 0, meal_prot = 0, meal_fat = 0, meal_fiber = 0;
for (auto &meal : j_meals)
{
auto &dishes = meal["dishes"];
for (auto &dish : dishes)
{
int cal = 0, prot = 0, fat = 0, fiber = 0, carbs = 0, sodium = 0, sugar = 0;
auto &nutrients = dish["nutritions"];
for (auto &nutrient : nutrients)
{
if (nutrient["name"] == "Calories")
cal = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Protein")
prot = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Fat")
fat = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Fiber")
fiber = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Carbs")
carbs = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Sodium")
sodium = std::stoi((std::string)nutrient["value"]);
else
if (nutrient["name"] == "Sugar")
sugar = std::stoi((std::string)nutrient["value"]);
}
if (total_goal_cal > 1000 && total_fact_cal > 1000 && cal > 0 && cal >= prot * 4 && cal >= fat * 9.1)
{
meal_cal += cal;
meal_prot += prot;
meal_fat += fat;
meal_fiber += fiber;
}
}
} // for (auto &meal : j_meals)
// Add meal PE for all dishes within this meal
float pe = 4.0 * meal_prot / meal_cal;
float fe = 9.0 * meal_fat / meal_cal;
float fbe = 4.0 * meal_fiber / meal_cal;
if (meal_cal)
{
for (auto &meal : j_meals)
{
auto &dishes = meal["dishes"];
for (auto &dish : dishes)
{
std::string dish_name = dish["name"];
get_dish_by_name(dish_name).add_meal_xe(pe, fe, fbe);
}
}
}
//std::cerr << "total_fact_cal=" << (int)total_fact_cal << ", total_goal_cal=" << (int)total_goal_cal
// << ", goal_completion_percent=" << (int)(goal_overfulfilment_percent * 100.0) << std::endl;
//std::cerr << "0: " << words[0] << ", 1: " << words[1] << ", 2: " << words[2] << ", 3: " << words[3] << std::endl;
//break;
//if (++j >= 100000)
// break;
} // while (getline(is, line))
int total_cardinality = 0;
for (int dish_id = 0; dish_id < all_dishes_.size(); ++dish_id)
{
dish_satiety_info &d = all_dishes_[dish_id];
total_cardinality += d.cardinality_;
d.make_avg(mfp_users_);
// Consider only representative foods. Like only ones that were consumed by at least five users
if (d.user_influence_.size() >= 10)
{
if (0)//(d.first == "Dunkin Donuts - Large Hot Coffee Black, 20 oz")
{
std::cerr << "Dunkin Donuts - Large Hot Coffee Black, 20 oz: influence_=" << d.influence_ <<
", cal_=" << d.cal_ << ", cardinality_=" << d.cardinality_ << std::endl;
}
float dish_rank = 1.0 * d.n_dish_bad_days_ / (d.n_dish_good_days_ + d.n_dish_bad_days_);
float user_rank = 1.0 * d.n_total_bad_users_ / d.n_total_good_users_;
float user_normal_rank = user_rank / (1.0 * 778 / 9116);
//dish_satiety_top_.insert({dish_rank/*d.second.influence_*/, d.second});
//dish_satiety_top_.insert({d.second.influence_, d.second});
dish_satiety_top_.insert({user_normal_rank, dish_id});
}
} // for (int dish_id = 0; dish_id < all_dishes_.size(); ++dish_id)
std::cerr << "total dishes: " << all_dishes_.size()
<< ", not unique dishes: " << total_cardinality
<< ", total dishes in top: " << dish_satiety_top_.size() << std::endl;
// Check which users have reached their goals for the second half of data
int n_improved_users = 0;
int n_appeared_dishes = 0;
int n_disappeared_dishes = 0;
float avg_appeared_pe = 0;
float avg_disappeared_pe = 0;
float avg_appeared_fe = 0;
float avg_disappeared_fe = 0;
float avg_appeared_fbe = 0;
float avg_disappeared_fbe = 0;
std::unordered_map<int, int> all_appeared_dishes, all_disappeared_dishes;
for (auto &u : mfp_users_)
{
float first_goal = 0;
float first_fact = 0;
float second_goal = 0;
float second_fact = 0;
float first_pe = 0, second_pe = 0;
int n_first = 0, n_second = 0;
for (int i = 0; i < u.days_.size(); ++i)
{
auto &d = u.days_[i];
if (i <= 6)
//if (i <= u.days_.size() / 2)
{
first_goal += d.total_goal_calories_;
first_fact += d.total_fact_calories_;
for (auto dish_id : d.dish_ids_)
{
auto &dish = all_dishes_[dish_id];
first_pe += dish.prot_cal_ratio_;
++n_first;
}
}
else
{
second_goal += d.total_goal_calories_;
second_fact += d.total_fact_calories_;
for (auto dish_id : d.dish_ids_)
{
auto &dish = all_dishes_[dish_id];
second_pe += dish.prot_cal_ratio_;
++n_second;
}
}
}
first_pe /= n_first;
second_pe /= n_second;
//if (first_fact > first_goal && second_fact <= second_goal)
// Determine the goal not as with fit in calories but as having more portein loaded food
if (second_pe >= first_pe * 1.2)
{
++n_improved_users;
// Save appeared and disappeared dish ids for an improved user
std::unordered_set<int> first_dish_ids, second_dish_ids;
for (int i = 0; i < u.days_.size(); ++i)
{
auto &d = u.days_[i];
if (i <= 6)
//if (i <= u.days_.size() / 2)
{
for (auto dish_id : d.dish_ids_)
first_dish_ids.insert(dish_id);
}
else
{
for (auto dish_id : d.dish_ids_)
second_dish_ids.insert(dish_id);
}
}
for (auto dish_id : first_dish_ids)
if (second_dish_ids.find(dish_id) == second_dish_ids.end())
{
++all_disappeared_dishes[dish_id];
u.disappeared_dish_ids_.insert(dish_id);
}
for (auto dish_id : second_dish_ids)
if (first_dish_ids.find(dish_id) == first_dish_ids.end())
{
++all_appeared_dishes[dish_id];
u.appeared_dish_ids_.insert(dish_id);
}
n_appeared_dishes += u.appeared_dish_ids_.size();
n_disappeared_dishes += u.disappeared_dish_ids_.size();
/*
// Determine average ratios for appeared and dispeared dishes
for (auto dish_id : u.appeared_dish_ids_)
{
auto &dish = all_dishes_[dish_id];
avg_appeared_pe += dish.prot_cal_ratio_;
avg_appeared_fe += dish.fat_cal_ratio_;
avg_appeared_fbe += dish.fiber_cal_ratio_;
}
for (auto dish_id : u.disappeared_dish_ids_)
{
auto &dish = all_dishes_[dish_id];
avg_disappeared_pe += dish.prot_cal_ratio_;
avg_disappeared_fe += dish.fat_cal_ratio_;
avg_disappeared_fbe += dish.fiber_cal_ratio_;
}*/
} // if (first_fact > first_goal && second_fact <= second_goal)
} // for (auto &u : mfp_users_)
// Determine average ratios for appeared and dispeared dishes
for (auto &x : all_appeared_dishes)
{
int dish_id = x.first;
auto &dish = all_dishes_[dish_id];
avg_appeared_pe += dish.prot_cal_ratio_;
avg_appeared_fe += dish.fat_cal_ratio_;
avg_appeared_fbe += dish.fiber_cal_ratio_;
}
for (auto &x : all_disappeared_dishes)
{
int dish_id = x.first;
auto &dish = all_dishes_[dish_id];
avg_disappeared_pe += dish.prot_cal_ratio_;
avg_disappeared_fe += dish.fat_cal_ratio_;
avg_disappeared_fbe += dish.fiber_cal_ratio_;
}
/* avg_appeared_pe /= n_appeared_dishes;
avg_appeared_fe /= n_appeared_dishes;
avg_appeared_fbe /= n_appeared_dishes;
avg_disappeared_pe /= n_disappeared_dishes;
avg_disappeared_fe /= n_disappeared_dishes;
avg_disappeared_fbe /= n_disappeared_dishes;*/
avg_appeared_pe /= all_appeared_dishes.size();
avg_appeared_fe /= all_appeared_dishes.size();
avg_appeared_fbe /= all_appeared_dishes.size();
avg_disappeared_pe /= all_disappeared_dishes.size();
avg_disappeared_fe /= all_disappeared_dishes.size();
avg_disappeared_fbe /= all_disappeared_dishes.size();
std::cerr << "Total users: " << mfp_users_.size()
<< ", improved users: " << n_improved_users
<< ", n_appeared_dishes: " << n_appeared_dishes
<< ", n_disappeared_dishes: " << n_disappeared_dishes
<< ", unique appeared dishes: " << all_appeared_dishes.size()
<< ", unique disappeared dishes: " << all_disappeared_dishes.size()
<< ", avg_appeared_pe: " << avg_appeared_pe
<< ", avg_disappeared_pe: " << avg_disappeared_pe
<< ", avg_appeared_fe: " << avg_appeared_fe
<< ", avg_disappeared_fe: " << avg_disappeared_fe
<< ", avg_appeared_fbe: " << avg_appeared_fbe
<< ", avg_disappeared_fbe: " << avg_disappeared_fbe
<< std::endl;
// Don't count dishes that are both appeared and disappeared
for (auto it = all_appeared_dishes.begin(); it != all_appeared_dishes.end();)
{
auto it2 = all_disappeared_dishes.find(it->first);
if (it2 != all_disappeared_dishes.end())
{
auto save = it;
++save;
all_appeared_dishes.erase(it);
all_disappeared_dishes.erase(it2);
it = save;
}
else
++it;
}
// Determine average ratios for appeared and dispeared dishes after clearing both appeared and disappeared dishes
avg_appeared_pe = 0;
avg_disappeared_pe = 0;
avg_appeared_fe = 0;
avg_disappeared_fe = 0;
avg_appeared_fbe = 0;
avg_disappeared_fbe = 0;
for (auto &x : all_appeared_dishes)
{
int dish_id = x.first;
auto &dish = all_dishes_[dish_id];
avg_appeared_pe += dish.prot_cal_ratio_;
avg_appeared_fe += dish.fat_cal_ratio_;
avg_appeared_fbe += dish.fiber_cal_ratio_;
}
for (auto &x : all_disappeared_dishes)
{
int dish_id = x.first;
auto &dish = all_dishes_[dish_id];
avg_disappeared_pe += dish.prot_cal_ratio_;
avg_disappeared_fe += dish.fat_cal_ratio_;
avg_disappeared_fbe += dish.fiber_cal_ratio_;
}
avg_appeared_pe /= all_appeared_dishes.size();
avg_appeared_fe /= all_appeared_dishes.size();
avg_appeared_fbe /= all_appeared_dishes.size();
avg_disappeared_pe /= all_disappeared_dishes.size();
avg_disappeared_fe /= all_disappeared_dishes.size();
avg_disappeared_fbe /= all_disappeared_dishes.size();
std::cerr << "After clearing both appeared and disappeared: "
<< " unique appeared dishes: " << all_appeared_dishes.size()
<< ", unique disappeared dishes: " << all_disappeared_dishes.size()
<< ", avg_appeared_pe: " << avg_appeared_pe
<< ", avg_disappeared_pe: " << avg_disappeared_pe
<< ", avg_appeared_fe: " << avg_appeared_fe
<< ", avg_disappeared_fe: " << avg_disappeared_fe
<< ", avg_appeared_fbe: " << avg_appeared_fbe
<< ", avg_disappeared_fbe: " << avg_disappeared_fbe
<< std::endl;
// Build top for often appearing and disappearing dishes
std::vector<std::pair<int, int> > top_appeared_dishes, top_disappeared_dishes;
top_appeared_dishes.resize(all_appeared_dishes.size());
top_disappeared_dishes.resize(all_disappeared_dishes.size());
std::copy(all_appeared_dishes.begin(), all_appeared_dishes.end(), top_appeared_dishes.begin());
std::copy(all_disappeared_dishes.begin(), all_disappeared_dishes.end(), top_disappeared_dishes.begin());
std::sort(top_appeared_dishes.begin(), top_appeared_dishes.end(), [](const std::pair<int, int> &a, const std::pair<int, int> &b){
return a.second > b.second;
});
std::sort(top_disappeared_dishes.begin(), top_disappeared_dishes.end(), [](const std::pair<int, int> &a, const std::pair<int, int> &b){
return a.second > b.second;
});
/*
// Output the top
std::cerr << "TOP APPEARED DISHES:" << std::endl << std::endl;
for (auto &x : top_appeared_dishes)
{
int dish_id = x.first;
auto &dish = all_dishes_[dish_id];
std::cerr << "[" << x.second << "] " << dish.dish_name_ << std::endl;
}
std::cerr << "TOP DISAPPEARED DISHES:" << std::endl << std::endl;
for (auto &x : top_disappeared_dishes)
{
int dish_id = x.first;
auto &dish = all_dishes_[dish_id];
std::cerr << "[" << x.second << "] " << dish.dish_name_ << std::endl;
}*/
// Fill day_meal_ids_ for popular foods
int links_from_dish_to_meal = 0;
int links_from_meal_to_dish = 0;
for (int day_meal_id = 0; day_meal_id < all_day_meals_.size(); ++day_meal_id)
{
auto &day_meal = all_day_meals_[day_meal_id];
links_from_meal_to_dish += day_meal.day_meal_dish_ids_.size();
for (auto dish_id : day_meal.day_meal_dish_ids_)
{
dish_satiety_info &d = all_dishes_[dish_id];
if (d.user_influence_.size() >= 10)
{
// Link the day meal to the dish
d.day_meal_ids_.push_back(day_meal_id);
++links_from_dish_to_meal;
}
} // for (auto dish_id : day_meal.day_meal_dish_ids_)
} // for (int day_meal_id = 0; day_meal_id < all_day_meals_.size(); ++day_meal_id)
// Sort all day_meal_ids in order of decrease of the goal overfulfillment
for (auto &dish : all_dishes_)
{
auto &meals = dish.day_meal_ids_;
if (!meals.empty())
{
std::sort(meals.begin(), meals.end(), [this](int day_meal_id1, int day_meal_id2) {
auto &day_meal1 = all_day_meals_[day_meal_id1];
auto &day_meal2 = all_day_meals_[day_meal_id2];
float goal_overfulfilment_percent1 = (day_meal1.total_goal_calories_ - day_meal1.total_fact_calories_) / day_meal1.total_goal_calories_;
float goal_overfulfilment_percent2 = (day_meal2.total_goal_calories_ - day_meal2.total_fact_calories_) / day_meal2.total_goal_calories_;
return goal_overfulfilment_percent1 > goal_overfulfilment_percent2;
});
}
}
std::cerr << "total day meals: " << all_day_meals_.size()
<< ", total links from dish to meal: " << links_from_dish_to_meal
<< ", links_from_meal_to_dish: " << links_from_meal_to_dish << std::endl;
// Create a map of macro nutrients to dishes
/*std::multimap<std::string, std::string> temp_macro_nutrient_to_dish_map;
for (auto &d : dish_satiety_top_)
{
char key[256];
sprintf(key, "%03d-%02d-%02d-%02d-%02d-%02d-%02d",
((int)(d.second.cal_ / 10)) * 10,
((int)(d.second.prot_ / 2)) * 2,
((int)(d.second.fat_ / 4)) * 4,
((int)(d.second.carbs_ / 2)) * 2,
(int)(d.second.fiber_),
((int)(d.second.sugar_ / 2)) * 2,
((int)(d.second.sodium_ / 10)) * 10
);
temp_macro_nutrient_to_dish_map.insert({key, d.second.dish_name_});
}
std::cerr << "Macro nutrients to dishes:" << std::endl;
for (auto &m : temp_macro_nutrient_to_dish_map)
std::cerr << "[" << m.first << "] " << m.second << std::endl;*/
int n_total_good_users = 0;
int n_total_bad_users = 0;
for (auto &u : mfp_users_)
{
if (u.user_total_fact_calories)
{
if (u.user_total_fact_calories <= u.user_total_goal_calories)
++n_total_good_users;
else
++n_total_bad_users;
}
}
float average_user_rank = 1.0 * n_total_bad_users / n_total_good_users;
std::cerr << "total good users: " << n_total_good_users
<< ", total bad users: " << n_total_bad_users
<< ", average user rank: " << average_user_rank
<< std::endl;
//std::cerr << std::endl << "WORST:" << std::endl << std::endl;
// Output top dishes
float avg_pe = 0, avg_avg_meal_pe = 0, avg_avg_meal_fe = 0, avg_avg_meal_fbe = 0;
float avg_plus_pe = 0;
float avg_minus_pe = 0;
float avg_plus_fe = 0;
float avg_minus_fe = 0;
float avg_plus_fbe = 0;
float avg_minus_fbe = 0;
float rank_avg_plus_pe = 0;
float rank_avg_minus_pe = 0;
float rank_avg_plus_fe = 0;
float rank_avg_minus_fe = 0;
float rank_avg_plus_fbe = 0;
float rank_avg_minus_fbe = 0;
float user_rank_avg_plus_pe = 0;
float user_rank_avg_minus_pe = 0;
float user_rank_avg_plus_fe = 0;
float user_rank_avg_minus_fe = 0;
float user_rank_avg_plus_fbe = 0;
float user_rank_avg_minus_fbe = 0;
float user_rank_avg_plus_suge = 0;
float user_rank_avg_minus_suge = 0;
float user_rank_avg_plus_sode = 0;
float user_rank_avg_minus_sode = 0;
float user_rank_avg_plus_pote = 0;
float user_rank_avg_minus_pote = 0;
float avg_meal_plus_pe = 0;
float avg_meal_minus_pe = 0;
float avg_meal_plus_fbe = 0;
float avg_meal_minus_fbe = 0;
int n_plus = 0, n_minus = 0;
int i = 0;
/*for (auto &t : dish_satiety_top)
{
std::cerr << "[" << t.second.user_influence_.size() << "] " << t.second.dish_name_ << ", avg cal=" << (int)t.second.cal_ << ", avg prot=" << t.second.prot_
<< ", PE=" << std::setprecision(2) << t.second.prot_cal_ratio_ << " : " << (int)(t.first*100)
<< ", avg meal PE=" << std::setprecision(2) << t.second.meal_pe_
<< ", avg meal FE=" << std::setprecision(2) << t.second.meal_fe_
<< ", avg meal FBE=" << std::setprecision(2) << t.second.meal_fbe_
<< std::endl;
avg_pe += t.second.prot_cal_ratio_;
avg_avg_meal_pe += t.second.meal_pe_;
avg_avg_meal_fe += t.second.meal_fe_;
avg_avg_meal_fbe += t.second.meal_fbe_;
if (++i > 30)
break;
}
std::cerr << "AVG PE=" << avg_pe / i
<< ", AVG avg meal PE=" << avg_avg_meal_pe / i
<< ", AVG avg meal FE=" << avg_avg_meal_fe / i
<< ", AVG avg meal FBE=" << avg_avg_meal_fbe / i
<< std::endl;*/
std::cerr << std::endl << "BEST:" << std::endl << std::endl;
i = 0;
avg_pe = 0;
avg_avg_meal_pe = 0;
avg_avg_meal_fe = 0;
avg_avg_meal_fbe = 0;
int n_rank_good_dishes = 0;
int n_user_rank_good_dishes = 0;
for (auto t = dish_satiety_top_.begin(); t != dish_satiety_top_.end(); ++t)
{
dish_satiety_info &dish = all_dishes_[t->second];
float dish_influence = dish.influence_;
float dish_absolute_rank = 1.0 * dish.n_dish_bad_days_ / (dish.n_dish_good_days_ + dish.n_dish_bad_days_);
float rank = 100.0 * dish_absolute_rank / 0.27;
float user_rank = 1.0 * dish.n_total_bad_users_ / dish.n_total_good_users_;
if ((int)rank <= 100)
{
rank_avg_plus_pe += dish.prot_cal_ratio_;
rank_avg_plus_fe += dish.fat_cal_ratio_;
rank_avg_plus_fbe += dish.fiber_cal_ratio_;
++n_rank_good_dishes;
}
else
{
rank_avg_minus_pe += dish.prot_cal_ratio_;
rank_avg_minus_fe += dish.fat_cal_ratio_;
rank_avg_minus_fbe += dish.fiber_cal_ratio_;
}
if (user_rank <= average_user_rank)
{
user_rank_avg_plus_pe += dish.prot_cal_ratio_;
user_rank_avg_plus_fe += dish.fat_cal_ratio_;
user_rank_avg_plus_fbe += dish.fiber_cal_ratio_;
user_rank_avg_plus_suge += dish.sugar_cal_ratio_;
user_rank_avg_plus_sode += dish.sodium_cal_ratio_;
user_rank_avg_plus_pote += dish.potass_cal_ratio_;
++n_user_rank_good_dishes;
}
else
{
user_rank_avg_minus_pe += dish.prot_cal_ratio_;
user_rank_avg_minus_fe += dish.fat_cal_ratio_;
user_rank_avg_minus_fbe += dish.fiber_cal_ratio_;
user_rank_avg_minus_suge += dish.sugar_cal_ratio_;
user_rank_avg_minus_sode += dish.sodium_cal_ratio_;
user_rank_avg_minus_pote += dish.potass_cal_ratio_;
}
/*std::cerr << "[" << dish.user_influence_.size() << "] " << dish.dish_name_ << ", avg cal=" << (int)dish.cal_ << ", avg prot=" << dish.prot_
<< ", PE=" << std::setprecision(2) << dish.prot_cal_ratio_
<< ", FE=" << std::setprecision(2) << dish.fat_cal_ratio_
<< ", FBE=" << std::setprecision(2) << dish.fiber_cal_ratio_
<< " : " << (int)(dish_influence*100) << "(" << (int)(100.0 * t->first / 0.27) << "%)"
<< ", avg meal PE=" << std::setprecision(2) << dish.meal_pe_
<< ", avg meal FE=" << std::setprecision(2) << dish.meal_fe_
<< ", avg meal FBE=" << std::setprecision(2) << dish.meal_fbe_
<< ", G=" << std::setprecision(2) << dish.n_dish_good_days_
<< ", B=" << std::setprecision(2) << dish.n_dish_bad_days_
<< std::endl;*/
avg_pe += dish.prot_cal_ratio_;
avg_avg_meal_pe += dish.meal_pe_;
avg_avg_meal_fe += dish.meal_fe_;
avg_avg_meal_fbe += dish.meal_fbe_;
/*if (dish.fat_cal_ratio_ > 1 || dish.prot_cal_ratio_ < 0)
{
std::cout << "[" << dish.user_influence_.size() << "] " << dish.dish_name_ << ", avg cal=" << (int)dish.cal_ << ", avg prot=" << dish.prot_
<< ", PE=" << std::setprecision(2) << dish.prot_cal_ratio_
<< ", FE=" << std::setprecision(2) << dish.fat_cal_ratio_
<< ", FBE=" << std::setprecision(2) << dish.fiber_cal_ratio_
<< " : " << (int)(dish_influence*100)
<< ", avg meal PE=" << std::setprecision(2) << dish.meal_pe_
<< ", avg meal FE=" << std::setprecision(2) << dish.meal_fe_
<< ", avg meal FBE=" << std::setprecision(2) << dish.meal_fbe_
<< std::endl;
}*/
if (dish_influence >= 0)
{
avg_plus_pe += dish.prot_cal_ratio_;
avg_plus_fe += dish.fat_cal_ratio_;
avg_plus_fbe += dish.fiber_cal_ratio_;
avg_meal_plus_pe += dish.meal_pe_;
avg_meal_plus_fbe += dish.meal_fbe_;
++n_plus;
}
else
{
avg_minus_pe += dish.prot_cal_ratio_;
avg_minus_fe += dish.fat_cal_ratio_;
avg_minus_fbe += dish.fiber_cal_ratio_;
avg_meal_minus_pe += dish.meal_pe_;
avg_meal_minus_fbe += dish.meal_fbe_;
++n_minus;
}
//if (i > 10000)
// break;
++i;
} // for (auto t = dish_satiety_top_.begin(); t != dish_satiety_top_.end(); ++t)
std::cerr << "AVG PE=" << avg_pe / i
<< ", AVG avg meal PE=" << avg_avg_meal_pe / i
<< ", AVG avg meal FE=" << avg_avg_meal_fe / i
<< ", AVG avg meal FBE=" << avg_avg_meal_fbe / i
<< std::endl;
std::cerr << "AVG +PE=" << avg_plus_pe / n_plus
<< ", AVG -PE=" << avg_minus_pe / n_minus
<< ", AVG avg meal +PE=" << avg_meal_plus_pe / n_plus
<< ", AVG avg meal -PE=" << avg_meal_minus_pe / n_minus
<< ", AVG avg meal +FBE=" << avg_meal_plus_fbe / n_plus
<< ", AVG avg meal -FBE=" << avg_meal_minus_fbe / n_minus
<< std::endl;
std::cerr << "AVG +FE=" << avg_plus_fe / n_plus
<< ", AVG -FE=" << avg_minus_fe / n_minus
<< ", AVG +FBE=" << avg_plus_fbe / n_plus
<< ", AVG -FBE=" << avg_minus_fbe / n_minus
<< std::endl;
std::cerr << "RANK AVG +PE=" << rank_avg_plus_pe / n_rank_good_dishes
<< ", RANK AVG -PE=" << rank_avg_minus_pe / (dish_satiety_top_.size() - n_rank_good_dishes)
<< ", RANK AVG +FE=" << rank_avg_plus_fe / n_rank_good_dishes
<< ", RANK AVG -FE=" << rank_avg_minus_fe / (dish_satiety_top_.size() - n_rank_good_dishes)
<< ", RANK AVG +FBE=" << rank_avg_plus_fbe / n_rank_good_dishes
<< ", RANK AVG -FBE=" << rank_avg_minus_fbe / (dish_satiety_top_.size() - n_rank_good_dishes)
<< std::endl;
std::cerr << "USER RANK AVG +PE=" << user_rank_avg_plus_pe / n_user_rank_good_dishes
<< ", USER RANK AVG -PE=" << user_rank_avg_minus_pe / (dish_satiety_top_.size() - n_user_rank_good_dishes)
<< ", USER RANK AVG +FE=" << user_rank_avg_plus_fe / n_user_rank_good_dishes
<< ", USER RANK AVG -FE=" << user_rank_avg_minus_fe / (dish_satiety_top_.size() - n_user_rank_good_dishes)
<< ", USER RANK AVG +FBE=" << user_rank_avg_plus_fbe / n_user_rank_good_dishes
<< ", USER RANK AVG -FBE=" << user_rank_avg_minus_fbe / (dish_satiety_top_.size() - n_user_rank_good_dishes)
<< ", USER RANK AVG +SUGE=" << user_rank_avg_plus_suge / n_user_rank_good_dishes
<< ", USER RANK AVG -SUGE=" << user_rank_avg_minus_suge / (dish_satiety_top_.size() - n_user_rank_good_dishes)
<< ", USER RANK AVG +SODE=" << user_rank_avg_plus_sode / n_user_rank_good_dishes
<< ", USER RANK AVG -SODE=" << user_rank_avg_minus_sode / (dish_satiety_top_.size() - n_user_rank_good_dishes)
<< ", USER RANK AVG +POTE=" << user_rank_avg_plus_pote / n_user_rank_good_dishes
<< ", USER RANK AVG -POTE=" << user_rank_avg_minus_pote / (dish_satiety_top_.size() - n_user_rank_good_dishes)
<< std::endl;
float g_avg_pe = 0, g_avg_avg_meal_pe = 0, g_avg_avg_meal_fe = 0, g_avg_avg_meal_fbe = 0;
for (auto &t : dish_satiety_top_)
{
dish_satiety_info &dish = all_dishes_[t.second];;
g_avg_pe += dish.prot_cal_ratio_;
g_avg_avg_meal_pe += dish.meal_pe_;
g_avg_avg_meal_fe += dish.meal_fe_;
g_avg_avg_meal_fbe += dish.meal_fbe_;
} // for (auto &t : dish_satiety_top_)
std::cerr << "Total dishes=" << dish_satiety_top_.size() << std::endl;
std::cerr << "Total good dishes=" << n_rank_good_dishes << std::endl;
std::cerr << "GRAND AVG PE=" << g_avg_pe / dish_satiety_top_.size()
<< ", GRAND AVG avg meal PE=" << g_avg_avg_meal_pe / dish_satiety_top_.size()
<< ", GRAND AVG avg meal FE=" << g_avg_avg_meal_fe / dish_satiety_top_.size()
<< ", GRAND AVG avg meal FBE=" << g_avg_avg_meal_fbe / dish_satiety_top_.size()
<< ", Total good days=" << n_good_days
<< ", Total bad days=" << n_bad_days
<< ", Average bad/good ratio=" << 1.0 * n_bad_days / (n_good_days + n_bad_days)
<< std::endl;
std::cerr << std::endl;
/*std::cerr << "WORDS:" << std::endl << std::endl;
// Output the top of words
std::multimap<float, dish_word___*> word_top;
for (auto &w : hash_dish_words)
{
// Consder only representative dish words
if (w.second.word_cardinality_ >= 10 && w.second.dish_word_users_.size() >= 30)
{
//float word_rank = 1.0 * w.second.word_bad_days_ / (w.second.word_good_days_ + w.second.word_bad_days_);
float word_rank = 0;
for (auto &u : w.second.dish_word_users_)
if (mfp_users_[u].user_total_fact_calories > mfp_users_[u].user_total_goal_calories)
++word_rank;
word_rank /= w.second.dish_word_users_.size();
// Determine prot/fat/fiber to cal ratio for users who had dishes with this word
auto &word = w.second;
int n = 0;
for (auto u : w.second.dish_word_users_)
{
for (auto &d : mfp_users_[u].days_)
{
for (int dish_id : d.dish_ids_)
{
auto &dish = all_dishes_[dish_id];
word.word_user_prot_cal_ratio_ += dish.prot_cal_ratio_;
word.word_user_fat_cal_ratio_ += dish.fat_cal_ratio_;
word.word_user_fiber_cal_ratio_ += dish.fiber_cal_ratio_;
++n;
}
}
word.word_user_average_fact_calories_ += mfp_users_[u].user_total_fact_calories / mfp_users_[u].days_.size();
}
word.word_user_prot_cal_ratio_ /= n;
word.word_user_fat_cal_ratio_ /= n;
word.word_user_fiber_cal_ratio_ /= n;
word.word_user_average_fact_calories_ /= w.second.dish_word_users_.size();
word_top.insert({word_rank, &w.second});
}
}
for (auto &w : word_top)
{
std::cerr << "[" << w.second->word_cardinality_ << "] " << w.second->dish_word_
<< ", rank=" << w.first
<< ", G=" << w.second->word_good_days_
<< ", B=" << w.second->word_bad_days_
<< ", prot_cal_ratio=" << w.second->word_user_prot_cal_ratio_
<< ", fat_cal_ratio=" << w.second->word_user_fat_cal_ratio_
<< ", fiber_cal_ratio=" << w.second->word_user_fiber_cal_ratio_
<< ", avg_day_calories=" << w.second->word_user_average_fact_calories_
<< std::endl;
}
std::cerr << "Total words:" << word_top.size() << std::endl;*/
}
void mfp_foods::output_dish(int dish_id,
const dish_satiety_info &dish,
bool output_user_list,
int dish_cardinality,
std::ostream &output)
{
float dish_absolute_rank = 1.0 * dish.n_dish_bad_days_ / (dish.n_dish_good_days_ + dish.n_dish_bad_days_);
float rank = 100.0 * dish_absolute_rank / 0.27;
float dish_influence = dish.influence_;
float user_rank = (dish.n_total_good_users_)?
(1.0 * dish.n_total_bad_users_ / dish.n_total_good_users_) : 1000000000;
output << "{";
output << "\"dish_id\":" << dish_id << ",";
if (dish_cardinality != -1)
output << "\"dish_cardinality\":" << dish_cardinality << ",";
output << "\"unique_users\":" << dish.user_influence_.size() << ",";
output << "\"rank\":" << rank << ",";
output << "\"influence\":" << dish_influence << ",";
output << "\"user_rank\":" << user_rank << ",";
output << "\"user_normal_rank\":" << user_rank / (1.0 * 778 / 9116) << ",";
output << "\"cal\":" << dish.cal_ << ",";
output << "\"prot\":" << dish.prot_ << ",";
output << "\"fat\":" << dish.fat_ << ",";
output << "\"carbs\":" << dish.carbs_ << ",";
output << "\"fiber\":" << dish.fiber_ << ",";
output << "\"sugar\":" << dish.sugar_ << ",";
output << "\"sodium\":" << dish.sodium_ << ",";
std::string js_escaped;
json_escape(dish.dish_name_, js_escaped);
output << "\"dish_name\":\"" << js_escaped << "\",";
std::stringstream ss;
ss << "avg cal=" << (int)dish.cal_ << ", avg prot=" << dish.prot_
<< ", PE=" << std::setprecision(2) << dish.prot_cal_ratio_
<< ", FE=" << std::setprecision(2) << dish.fat_cal_ratio_
<< ", FBE=" << std::setprecision(2) << dish.fiber_cal_ratio_
<< " : " << std::setprecision(2) << dish.influence_*100.0 << "(" << (int)(rank) << "%)"
<< ", avg meal PE=" << std::setprecision(2) << dish.meal_pe_
<< ", avg meal FE=" << std::setprecision(2) << dish.meal_fe_
<< ", avg meal FBE=" << std::setprecision(2) << dish.meal_fbe_
<< ", G=" << std::setprecision(2) << dish.n_dish_good_days_
<< ", B=" << std::setprecision(2) << dish.n_dish_bad_days_
;
output << "\"dish_info\":\"" << ss.str() << "\"";
if (output_user_list)
{
output << ", \"users\":\"";
for (auto &u : dish.user_influence_)
output << " " << u.first << "[" << u.second.first << "," << u.second.second << "]";
output << "\"";
}
output << "}" << std::endl;
}
void mfp_foods::suggest_food_from_stat(std::vector<std::string> &search_string_include,
std::vector<std::string> &search_string_exclude,
std::vector<std::string> &search_string_include_exact,
std::vector<std::string> &search_string_exclude_exact,
int limit_after_sort,
float min_food_rank,
float max_food_rank,
float protein_to_calorie_percent,
float fiber_to_calorie_percent,
float min_pfind,
std::ostream &output)
{
output << "{\"event\":\"suggest_food_from_stat\",\"data\":[" << std::endl;
int k = 0;
std::string lower_dish_name_temp_;
bool first = true;
if (limit_after_sort == -1)
limit_after_sort = 1000;
//for (auto t = dish_satiety_top_.rbegin(); t != dish_satiety_top_.rend(); ++t)
for (auto t = dish_satiety_top_.begin(); t != dish_satiety_top_.end(); ++t)
{
int dish_id = t->second;
dish_satiety_info &dish = all_dishes_[dish_id];
const std::string &dish_name = dish.dish_name_;
//if (rank > 100)
// continue;
// Filter
lower_dish_name_temp_.clear();
bool is_filtered = false;
if (!search_string_include.empty())
{
is_filtered = false;
lower_str(dish_name, lower_dish_name_temp_);
// Search for presence of ALL words
for (auto &x : search_string_include)
{
// The word is not absent - filter the food
if (lower_dish_name_temp_.find(x) == std::string::npos)
{
/*if (food_id > 1000000)
std::cerr << "filtered out: lower_food_name_temp_=" << lower_food_name_temp_ <<
", x=" << x << std::endl;*/
is_filtered = true;
break;
}
}
if (is_filtered)
continue;
} // if (!search_string_include.empty())
// Search for exact match
for (auto &x : search_string_include_exact)
{
// The word is not absent - filter the food
if (dish_name.find(x) == std::string::npos)
{
is_filtered = true;
break;
}
}
if (is_filtered)
continue;
if (!search_string_exclude.empty())
{
if (lower_dish_name_temp_.empty())
lower_str(dish_name, lower_dish_name_temp_);
// Search for absence of ALL words
for (auto &x : search_string_exclude)
{
// The word is present - filter the food
if (lower_dish_name_temp_.find(x) != std::string::npos)
{
is_filtered = true;
break;
}
}
if (is_filtered)
continue;
} // if (!search_string_exclude.empty())
// Search for exact mismatch
for (auto &x : search_string_exclude_exact)
{
// The word is present - filter the food
if (dish_name.find(x) != std::string::npos)
{
is_filtered = true;
break;
}
}
if (is_filtered)
continue;
// Output the dish
if (!first) output << ","; first = false;
output_dish(dish_id, dish, true, -1, output);
if (++k >= limit_after_sort)
break;
} // for (auto t = dish_satiety_top_.begin(); t != dish_satiety_top_.end(); ++t)
output << "]}" << std::endl;
}
void mfp_foods::all_meals_with_dish(int dish_id,
const std::string &dish_name,
int limit_after_sort,
std::ostream &output)
{
output << "{\"event\":\"all_meals_with_dish\",\"data\":[" << std::endl;
if (dish_id == -1)
dish_id = get_dish_id_by_name(dish_name);
std::cerr << "dish_id=" << dish_id << ", all_day_meals_.size()=" << all_day_meals_.size() <<
", dish_name='" << dish_name << "', all_dishes_[dish_id].day_meal_ids_.size()=" <<
all_dishes_[dish_id].day_meal_ids_.size() << std::endl;
bool first = true;
int k = 0;
for (auto day_meal_id : all_dishes_[dish_id].day_meal_ids_)
{
auto &day_meal = all_day_meals_[day_meal_id];
// Output the day meal info
if (!first) output << ","; first = false;
float goal_overfulfilment_percent = (day_meal.total_goal_calories_ - day_meal.total_fact_calories_) / day_meal.total_goal_calories_;
output << "{\"total_fact_calories\": " << day_meal.total_fact_calories_ << ","
<< "\"total_goal_calories\": " << day_meal.total_goal_calories_ << ","
<< "\"goal_overfulfilment_percent\": " << goal_overfulfilment_percent << ","
<< "\"foods\":[";
// Output all foods within this meal
bool first2 = true;
for (auto dish_id : day_meal.day_meal_dish_ids_)
{
dish_satiety_info &dish = all_dishes_[dish_id];
if (!first2) output << ","; first2 = false;
output_dish(dish_id, dish, false, -1, output);
}
output << "]}" << std::endl;
if (limit_after_sort != -1)
{
if (k++ >= limit_after_sort)
break;
}
} // for (auto &meal : all_dishes_[dish_id].day_meal_ids_)
output << "], \"dish_substitution\":[" << std::endl;
// Check if this dish is disappeared from somebody's menu - and for all those users get all the appeared
// dishes, sort them in order of appearance and show them as a substitution top
std::map<int, int> appeared_top;
for (auto &u : mfp_users_)
{
auto it = u.disappeared_dish_ids_.find(dish_id);
if (it != u.disappeared_dish_ids_.end())
{
// This dish disappeared from this user's menu - add all appeared dishes to the list
for (auto dish_id : u.appeared_dish_ids_)
++appeared_top[dish_id];
}
}
// Now sort top by appearance
std::vector<std::pair<int, int> > sorted_appeared_top;
sorted_appeared_top.resize(appeared_top.size());
std::copy(appeared_top.begin(), appeared_top.end(), sorted_appeared_top.begin());
std::sort(sorted_appeared_top.begin(), sorted_appeared_top.end(), [](const std::pair<int, int> &a, const std::pair<int, int> &b){
return a.second > b.second;
});
// Output the top
first = true;
k = 0;
for (auto &x : sorted_appeared_top)
{
int dish_id = x.first;
auto &dish = all_dishes_[dish_id];
if (!first) output << ","; first = false;
output_dish(dish_id, dish, false, x.second, output);
if (k++ >= 10)
break;
}
output << "]}" << std::endl;
}
} // namespace balanced_diet
|
#include <VulkanPlayground\Includes.h>
class ModelLitTestMeshApp : public VulkanApplication3DLight
{
void ResetScene() override
{
CalcPositionMatrix({ 0, 20, 0 }, { -1.0f, -0.4f, 0 }, 0, 25, model.GetModelSize());
SetupLighting({ 0, -45, 8 }, 0.5f, 0.5f, 0.75f, 16.0f, model.GetModelSize());
SetLineMode(false);
}
void SetLineMode(bool val)
{
lineMode = val;
pipeline.SetPolygonMode(lineMode ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL);
pipeline.Recreate();
}
void SetupObjects(VulkanSystem& system, RenderPass& renderPass, VkExtent2D workingExtent) override
{
model.LoadToGpu(system, VulkanPlayground::GetModelFile("Basics", "voyager.dae"), Attribs::PosNormTex);
descriptor.AddUniformBuffer(system, 0, mvpUBO, "MVP");
descriptor.AddTexture(system, 2, texture, VulkanPlayground::GetModelFile("Basics", "voyager_bc3_unorm.ktx"), VK_FORMAT_BC3_UNORM_BLOCK);
descriptor.AddUniformBuffer(system, 1, lightUBO, "Lighting", VK_SHADER_STAGE_FRAGMENT_BIT);
CreateDescriptor(system, descriptor, "Drawing");
pipeline.SetupVertexDescription(Attribs::PosNormTex);
pipeline.LoadShader(system, "LitTestMesh");
CreatePipeline(system, renderPass, pipeline, descriptor, workingExtent, "TestModel");
};
void DrawScene(VkCommandBuffer commandBuffer) override
{
pipeline.Bind(commandBuffer, descriptor);
model.Draw(commandBuffer);
}
void ProcessKeyPresses(const EventData& eventData) override
{
if (eventData.KeyPressed('L'))
SetLineMode(!lineMode);
}
private:
Pipeline pipeline;
Descriptor descriptor;
Model model;
Texture texture;
bool lineMode;
};
DECLARE_APP(ModelLitTestMesh)
|
//deprecated
#include "fft.h"
#include "matrix.h"
#include <cmath>
#include <iostream>
#include <iomanip>
#include <complex>
using namespace std;
using namespace toefl;
int main()
{
cout << "Test \n";
double dx;
size_t rows = 1;
size_t cols = 10;
Matrix<double, TL_DFT> m2(rows,cols);
Matrix<complex<double>, TL_NONE> m2_( rows, cols/2+1, TL_VOID);
fftw_plan forward_plan = plan_dft_1d_r2c(rows, cols, m2.getPtr(), fftw_cast(m2.getPtr()), FFTW_MEASURE);
fftw_plan backward_plan = plan_dft_1d_c2r(rows, cols, fftw_cast(m2.getPtr()), m2.getPtr(), FFTW_MEASURE);
dx = 1./10.;
for( size_t i = 0; i < m2.rows(); i++)
for ( size_t j=0; j < m2.cols(); j++)
m2(i, j) = cos( 2*(i+1)*M_PI*j*dx);
cout << "Trafo of:\n";
cout << setprecision(2) << fixed;
cout << m2 <<endl;
cout << "forward trafo\n";
fftw_execute_dft_r2c( forward_plan, m2.getPtr(), fftw_cast(m2.getPtr()));
swap_fields( m2, m2_);
cout << "result should be one cosine mode\n";
cout << m2_ <<endl;
swap_fields( m2, m2_);
try{
fftw_execute_dft_c2r( backward_plan, fftw_cast(m2.getPtr()), m2.getPtr());}
catch(Message& m){m.display();}
cout << "backtrafo\n";
cout << m2 <<endl;
fftw_destroy_plan( forward_plan);
fftw_destroy_plan( backward_plan);
fftw_cleanup();
return 0;
}
|
#include "ofxTouchBoard.h"
void ofxTouchBoard::setup(int deviceId){
serial.setup(deviceId);
init();
}
void ofxTouchBoard::setup(){
serial.setup();
init();
}
void ofxTouchBoard::init(){
ofAddListener(ofEvents().exit, this, &ofxTouchBoard::exit);
serial.startThread(false);
electrodes.resize(ofxTB::ELECTRODES_NB);
graphHeight = 200;
graphBarSpace = 10;
graphBarWidth = 20;
jitter = 0.0;
bBoardThresholds = true;
setupThresholds();
touchStatus = vector<bool>(ofxTB::ELECTRODES_NB, false);
}
void ofxTouchBoard::setupThresholds(){
touchThresholds.resize(ofxTB::ELECTRODES_NB);
releaseThresholds.resize(ofxTB::ELECTRODES_NB);
for(int i = 0; i < ofxTB::ELECTRODES_NB; ++i){
ofParameter<float> t;
t.set("TTHS" + ofToString(i), 0.15625, 0.0, 1.0);
ofParameter<float> r;
r.set("RTHS" + ofToString(i), 0.078125, 0.0, 1.0);
touchThresholds[i] = t;
releaseThresholds[i] = r;
touchThresholdsParams.add(touchThresholds[i]);
releaseThresholdsParams.add(releaseThresholds[i]);
}
}
void ofxTouchBoard::update(){
serial.lock();
vector<ofxTB::Electrode> rawData(serial.getNormalizedData());
serial.unlock();
if(electrodes.size() == rawData.size()){
for(int i = 0; i < electrodes.size(); ++i){
electrodes[i].touch = rawData[i].touch;
electrodes[i].diff = (1.0 - jitter) * rawData[i].diff + jitter * electrodes[i].diff;
electrodes[i].bval = (1.0 - jitter) * rawData[i].bval + jitter * electrodes[i].bval;
electrodes[i].fdat = (1.0 - jitter) * rawData[i].fdat + jitter * electrodes[i].fdat;
electrodes[i].tths = rawData[i].tths;
electrodes[i].rths = rawData[i].rths;
}
}
else{
ofLog() << "electrodes.size() != rawData.size()";
}
updateStatus();
}
void ofxTouchBoard::updateStatus(){
for(int i = 0; i < touchStatus.size(); ++i){
bool touchEvent;
bool releaseEvent;
if(bBoardThresholds){
touchEvent = electrodes[i].touch && !touchStatus[i];
releaseEvent = !electrodes[i].touch && touchStatus[i];
}
else{
touchEvent = electrodes[i].diff > touchThresholds[i] && !touchStatus[i];
releaseEvent = electrodes[i].diff < releaseThresholds[i] && touchStatus[i];
}
if(touchEvent){
touchStatus[i] = true;
// ofLog() << "touch " << i;
ofNotifyEvent(touched, i, this);
}
if(releaseEvent){
touchStatus[i] = false;
// ofLog() << "release " << i;
ofNotifyEvent(released, i, this);
}
}
}
void ofxTouchBoard::logData(){
serial.logData();
}
void ofxTouchBoard::draw(float x, float y){
for(int i = 0; i < electrodes.size(); ++i){
ofxTB::Electrode e(electrodes[i]);
// Draw filter data graph bar
ofSetColor(ofColor(35, 255, 106, 100));
drawGraphBar(x, y, i, e.fdat, graphBarWidth/2.0, -graphBarWidth/4.0);
// Draw base value graph bar
ofSetColor(ofColor(35, 106, 255, 100));
drawGraphBar(x, y, i, e.bval, graphBarWidth/2.0, graphBarWidth/4.0);
}
}
void ofxTouchBoard::drawGraphBar(float x0, float y0, int i, float val, float width, float xOffset){
float y = y0 - (val * graphHeight)/2.0;
float x = x0 + graphBarWidth + xOffset + (graphBarWidth + graphBarSpace) * i;
ofDrawPlane(x, y, width, val * graphHeight);
}
void ofxTouchBoard::printData(float x, float y){
printData(electrodes, x, y);
}
void ofxTouchBoard::printRawData(float x, float y){
serial.lock();
vector<ofxTB::Electrode> raw(serial.getData());
serial.unlock();
printData(raw, x, y);
}
void ofxTouchBoard::printData(vector<ofxTB::Electrode>& e, float x, float y){
float charWidth = 11;
float charHeight = 15;
float xOffset = x;
float yOffset = y + charHeight;
float colWidth = 30;
float rowHeight = 20;
ofDrawBitmapString("E", x, yOffset);
xOffset += 2 * charWidth;
ofDrawBitmapString("TOUCH", xOffset, yOffset);
xOffset += 5 * charWidth;
ofDrawBitmapString("TTHS", xOffset, yOffset);
xOffset += 4 * charWidth;
ofDrawBitmapString("RTHS", xOffset, yOffset);
xOffset += 4 * charWidth;
ofDrawBitmapString("FDAT", xOffset, yOffset);
xOffset += 4 * charWidth;
ofDrawBitmapString("BVAL", xOffset, yOffset);
xOffset += 4 * charWidth;
ofDrawBitmapString("DIFF", xOffset, yOffset);
yOffset += charHeight;
for(int i = 0; i < e.size(); ++i){
xOffset = x;
printDataLine(i, xOffset, yOffset);
xOffset += 2 * charWidth;
printDataLine(e[i].touch, xOffset, yOffset);
xOffset += 5 * charWidth;
printDataLine(e[i].tths, xOffset, yOffset);
xOffset += 4 * charWidth;
printDataLine(e[i].rths, xOffset, yOffset);
xOffset += 4 * charWidth;
printDataLine(e[i].fdat, xOffset, yOffset);
xOffset += 4 * charWidth;
printDataLine(e[i].bval, xOffset, yOffset);
xOffset += 4 * charWidth;
printDataLine(e[i].diff, xOffset, yOffset);
yOffset += charHeight;
}
}
void ofxTouchBoard::printDataLine(float val, float x, float y){
ofDrawBitmapString(ofToString(ofxTB::trunc(val, 2)), x, y);
}
void ofxTouchBoard::printDataLine(int val, float x, float y){
ofDrawBitmapString(ofToString(val), x, y);
}
void ofxTouchBoard::exit(ofEventArgs& e){
serial.waitForThread();
}
void ofxTouchBoard::useBoardThresholds(bool b){
bBoardThresholds = b;
}
const vector<ofxTB::Electrode>& ofxTouchBoard::getData(){
return electrodes;
}
const vector<ofxTB::Electrode>& ofxTouchBoard::getRawData(){
return serial.getData();
}
const vector<ofParameter<float> >& ofxTouchBoard::getTouchThresholds(){
return touchThresholds;
}
const vector<ofParameter<float> >& ofxTouchBoard::getReleaseThresholds(){
return releaseThresholds;
}
const ofParameterGroup& ofxTouchBoard::getTouchThresholdsParams(){
return touchThresholdsParams;
}
const ofParameterGroup& ofxTouchBoard::getReleaseThresholdsParams(){
return releaseThresholdsParams;
}
const vector<bool>& ofxTouchBoard::getTouchStatus(){
return touchStatus;
}
|
#pragma once
// ================================================================================================
// File: VkToolbox/Utils.hpp
// Author: Guilherme R. Lampert
// Created on: 07/01/17
// Brief: Miscellaneous helper code.
// ================================================================================================
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <memory>
#include <type_traits>
#include <utility>
class str;
namespace VkToolbox
{
constexpr float PI = 3.1415926535897931f;
constexpr float HalfPI = PI / 2.0f;
constexpr float TwoPI = 2.0f * PI;
constexpr float DegToRad = PI / 180.0f;
constexpr float RadToDeg = 180.0f / PI;
// Width and height pair.
struct Size2D
{
int width;
int height;
};
inline bool operator == (const Size2D & a, const Size2D & b)
{
return (a.width == b.width && a.height == b.height);
}
inline bool operator != (const Size2D & a, const Size2D & b)
{
return !(a == b);
}
// Width, height and depth triplet.
struct Size3D
{
int width;
int height;
int depth;
};
inline bool operator == (const Size3D & a, const Size3D & b)
{
return (a.width == b.width && a.height == b.height && a.depth == b.depth);
}
inline bool operator != (const Size3D & a, const Size3D & b)
{
return !(a == b);
}
namespace CT
{
// Compile-time maximum of an arbitrary number of values:
template<typename T>
constexpr T maxOf2(T a, T b) { return (a > b) ? a : b; }
template<typename T>
constexpr T maxOfN(T x) { return x; }
template<typename T, typename... Args>
constexpr T maxOfN(T x, Args... args) { return maxOf2(x, maxOfN(args...)); }
} // namespace CT
// Test if types T and U are both signed, at compile time.
template<typename T, typename U>
using IsSameSignedness = typename std::integral_constant<bool, std::is_signed<T>::value == std::is_signed<U>::value>::type;
// narrowCast(): A checked version of static_cast() that asserts if the cast changed the value.
// This is based on the "Guidelines Support Library (GSL)".
template<typename T, typename U>
inline T narrowCast(const U u)
{
const T t = static_cast<T>(u);
#if DEBUG
if (static_cast<U>(t) != u)
{
assert(false && "Integer value was truncated!");
}
if (!IsSameSignedness<T, U>{} && ((t < T{}) != (u < U{})))
{
assert(false && "Integer value sign overflow!");
}
#endif // DEBUG
return t;
}
// Statically infer the length in T elements of the C-style array.
template<typename T, std::size_t Size>
constexpr std::size_t arrayLength(const T (&)[Size])
{
return Size;
}
// Clamp the input value between min and max (inclusive range) - in-place version.
template<typename T>
inline void clamp(T * inOutVal, const T minVal, const T maxVal)
{
if ((*inOutVal) < minVal) { (*inOutVal) = minVal; }
else if ((*inOutVal) > maxVal) { (*inOutVal) = maxVal; }
}
// Returns the new clamped value.
template<typename T>
inline T clamp(const T inVal, const T minVal, const T maxVal)
{
if (inVal < minVal) { return minVal; }
else if (inVal > maxVal) { return maxVal; }
else { return inVal; }
}
// Test if an integer is a power of two. Always false if the number is negative.
template<typename T>
inline bool isPowerOfTwo(const T x)
{
return (x > 0) && ((x & (x - 1)) == 0);
}
// Round down an integer to a power of two. The output is never greater than the input.
template<typename T>
inline T roundDownToPowerOfTwo(const T x)
{
T p2;
for (p2 = 1; (p2 * 2) <= x; p2 <<= 1) { }
return p2;
}
// Rounds an integer to its next power of two. Example: 37 => 64.
template<typename T>
inline T roundUpToPowerOfTwo(T x)
{
if (x == 0)
{
return 1;
}
--x;
for (T i = 1; i < sizeof(T) * 8; i <<= 1)
{
x = x | x >> i;
}
return ++x;
}
// Adds the minimum extra needed to the size for pointer alignment.
// This size can then be used to malloc some memory and then have
// the pointer aligned with alignPtr().
template<typename T>
inline T alignSize(const T size, const T alignment)
{
assert(isPowerOfTwo(alignment));
return size + (alignment - 1);
}
// Aligned if the pointer is evenly divisible by the alignment value.
// Same as '(ptr % align) == 0' (The '&' trick works with PoT alignments only!).
inline bool isAlignedPtr(const void * ptr, const std::size_t alignment)
{
assert(isPowerOfTwo(alignment));
return (reinterpret_cast<std::uintptr_t>(ptr) & (alignment - 1)) == 0;
}
// Align the pointer address to a given byte boundary.
// This should normally be used in conjunction with alignSize().
template<typename T>
inline T * alignPtr(const T * ptr, const std::size_t alignment)
{
assert(isPowerOfTwo(alignment));
// Cast to integer and align:
const std::uintptr_t uintPtr = reinterpret_cast<std::uintptr_t>(ptr);
const std::uintptr_t alignedPtr = (uintPtr + (alignment - 1)) & ~(alignment - 1);
// Re-cast to pointer, validate and return:
T * userPtr = reinterpret_cast<T *>(alignedPtr);
assert(isAlignedPtr(userPtr, alignment));
return userPtr;
}
// Angle canonicalization for Degrees (180-360):
inline float normalizeAngle360(float degrees)
{
if (degrees >= 360.0f || degrees < 0.0f)
{
degrees -= std::floor(degrees * (1.0f / 360.0f)) * 360.0f;
}
return degrees;
}
inline float normalizeAngle180(float degrees)
{
degrees = normalizeAngle360(degrees);
if (degrees > 180.0f)
{
degrees -= 360.0f;
}
return degrees;
}
// Angle canonicalization for Radians (PI-2PI):
inline float normalizeAngleTwoPI(float radians)
{
if (radians >= TwoPI || radians < 0.0f)
{
radians -= std::floor(radians * (1.0f / TwoPI)) * TwoPI;
}
return radians;
}
inline float normalizeAnglePI(float radians)
{
radians = normalizeAngleTwoPI(radians);
if (radians > PI)
{
radians -= TwoPI;
}
return radians;
}
// Test of a C string is a prefix of another. Strings must not be null!
inline bool strStartsWith(const char * const str, const char * const prefix)
{
assert(str != nullptr && prefix != nullptr);
return std::strncmp(str, prefix, std::strlen(prefix)) == 0;
}
// Test if the file exists.
bool probeFile(const char * filename);
// Get the CWD.
const char * currentPath(str * inOutPathStr);
// Open and load a file into memory, appending a null byte at the end to make it a valid C-style string.
// outFileSize is mandatory and must not be null.
std::unique_ptr<char[]> loadTextFile(const char * inFilename, std::size_t * outFileSize);
// "Portable" fopen, since VS deprecates std::fopen and warns about it.
FILE * openFile(const char * filename, const char * mode);
// Shorthand helpers to dump a struct (or array of structs) to file. Assumes T is POD.
template<typename T>
inline bool writeStructToFile(FILE * file, const T & data)
{
const auto n = std::fwrite(&data, sizeof(T), 1, file);
assert(n == 1); return (n == 1);
}
template<typename T>
inline bool writeArrayToFile(FILE * file, const T * const data, const std::size_t count)
{
const auto n = std::fwrite(data, sizeof(T), count, file);
assert(n == count); return (n == count);
}
// Helpers read back the binary dump of a struct (or array of structs) from file. Assumes T is POD.
template<typename T>
inline bool readStructFromFile(FILE * file, T * outData)
{
const auto n = std::fread(outData, sizeof(T), 1, file);
assert(n == 1); return (n == 1);
}
template<typename T>
inline bool readArrayFromFile(FILE * file, T * outData, const std::size_t count)
{
const auto n = std::fread(outData, sizeof(T), count, file);
assert(n == count); return (n == count);
}
// So we don't have to be fclosein' all the time.
class ScopedFileHandle final
{
FILE * m_fileHandle;
public:
ScopedFileHandle(const ScopedFileHandle & other) = delete;
ScopedFileHandle & operator = (const ScopedFileHandle & other) = delete;
ScopedFileHandle(FILE * fh)
: m_fileHandle{ fh }
{ }
~ScopedFileHandle()
{
close();
}
void close()
{
if (m_fileHandle != nullptr)
{
std::fclose(m_fileHandle);
m_fileHandle = nullptr;
}
}
operator FILE*() const { return m_fileHandle; }
};
} // namespace VkToolbox
|
#include "SensorFusionEditorIntegrationPCH.h"
#include "SSensorMappingViewportToolBar.h"
#define LOCTEXT_NAMESPACE "SensorFusionToolkit"
void SSensorMappingViewportToolBar::Construct(const FArguments& InArgs, TSharedPtr<class ICommonEditorViewportToolbarInfoProvider> InInfoProvider)
{
this->SensorFusionToolkit = InArgs._SensorFusionToolkit;
/*
struct LocalViewportToolbarBuilder
{
static void FillToolbar(FToolBarBuilder& ToolbarBuilder)
{
ToolbarBuilder.BeginSection("Command");
{
ToolbarBuilder.AddToolBarButton(FSensorMappingEditorCommands::Get().SetShowPivot);
ToolbarBuilder.AddToolBarButton(FSensorMappingEditorCommands::Get().SetShowSkeletonOnly);
}
ToolbarBuilder.EndSection();
ToolbarBuilder.BeginSection("Camera");
{
ToolbarBuilder.AddToolBarButton(FSensorMappingEditorCommands::Get().ResetCamera);
}
ToolbarBuilder.EndSection();
}
};
this->ChildSlot
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("NoBorder"))
.ColorAndOpacity(this, &SViewportToolBar::OnGetColorAndOpacity)
.ForegroundColor(FEditorStyle::GetSlateColor("DefaultForeground"))
];
*/
SCommonEditorViewportToolbarBase::Construct(SCommonEditorViewportToolbarBase::FArguments(), InInfoProvider);
}
#undef LOCTEXT_NAMESPACE
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.