text:
// Copyright (c) 2015, Ruslan Baratov
// All rights reserved.

#include <boost/filesystem.hpp>

#include <android_native_app_glue.h>
#include <android/log.h>

void android_main(struct android_app* state) {
  app_dummy(); // Make sure glue isn't stripped

  namespace fs = boost::filesystem;

  __android_log_print(
      ANDROID_LOG_INFO,
      "BoostFilesystemExample",
      fs::current_path().c_str()
  );

  ANativeActivity_finish(state->activity);
}

ext: cpp

max_stars_repo_name: fantasticfears/hunter

max_issues_repo_name: koinos/hunter

max_forks_repo_name: koinos/hunter


text:
#include "adm/elements/audio_pack_format_id.hpp"
#include <boost/format.hpp>
#include <regex>
#include <sstream>
#include "adm/detail/hex_values.hpp"

namespace adm {

  // ---- Defaults ---- //
  const TypeDescriptor AudioPackFormatId::channelTypeDefault_ =
      TypeDefinition::UNDEFINED;
  const AudioPackFormatIdValue AudioPackFormatId::valueDefault_ =
      AudioPackFormatIdValue(0);

  // ---- Getter ---- //
  TypeDescriptor AudioPackFormatId::get(
      detail::ParameterTraits<TypeDescriptor>::tag) const {
    return boost::get_optional_value_or(channelType_, channelTypeDefault_);
  }
  AudioPackFormatIdValue AudioPackFormatId::get(
      detail::ParameterTraits<AudioPackFormatIdValue>::tag) const {
    return boost::get_optional_value_or(value_, valueDefault_);
  }

  // ---- Has ---- //
  bool AudioPackFormatId::has(
      detail::ParameterTraits<TypeDescriptor>::tag) const {
    return true;
  }
  bool AudioPackFormatId::has(
      detail::ParameterTraits<AudioPackFormatIdValue>::tag) const {
    return true;
  }

  // ---- isDefault ---- //
  bool AudioPackFormatId::isDefault(
      detail::ParameterTraits<TypeDescriptor>::tag) const {
    return channelType_ == boost::none;
  }
  bool AudioPackFormatId::isDefault(
      detail::ParameterTraits<AudioPackFormatIdValue>::tag) const {
    return value_ == boost::none;
  }

  // ---- Setter ---- //
  void AudioPackFormatId::set(TypeDescriptor channelType) {
    channelType_ = channelType;
  }
  void AudioPackFormatId::set(AudioPackFormatIdValue value) { value_ = value; }

  // ---- Unsetter ---- //
  void AudioPackFormatId::unset(detail::ParameterTraits<TypeDescriptor>::tag) {
    channelType_ = boost::none;
  }
  void AudioPackFormatId::unset(
      detail::ParameterTraits<AudioPackFormatIdValue>::tag) {
    value_ = boost::none;
  }

  // ---- Operators ---- //
  bool AudioPackFormatId::operator==(const AudioPackFormatId& other) const {
    return get<TypeDescriptor>() == other.get<TypeDescriptor>() &&
           get<AudioPackFormatIdValue>() == other.get<AudioPackFormatIdValue>();
  }

  bool AudioPackFormatId::operator!=(const AudioPackFormatId& other) const {
    return !(*this == other);
  }

  bool AudioPackFormatId::operator<(const AudioPackFormatId& other) const {
    return formatId(*this) < formatId(other);
  }

  // ---- Common ---- //
  void AudioPackFormatId::print(std::ostream& os) const {
    os << boost::str(
        boost::format("AP_%1%%2%") % formatTypeLabel(get<TypeDescriptor>()) %
        detail::formatHexValue(get<AudioPackFormatIdValue>().get()));
  }

  AudioPackFormatId parseAudioPackFormatId(const std::string& id) {
    const std::regex r("AP_([0-9a-fA-F]{4})([0-9a-fA-F]{4})");
    std::smatch idMatch;
    if (std::regex_match(id, idMatch, r)) {
      auto type = parseTypeLabel(idMatch[1]);
      auto value = detail::parseHexValue(idMatch[2], 4);
      return AudioPackFormatId(type, AudioPackFormatIdValue(value));
    } else {
      std::stringstream errorString;
      errorString << "invalid AudioPackFormatId: " << id;
      throw std::runtime_error(errorString.str());
    }
  }

  std::string formatId(AudioPackFormatId id) {
    std::stringstream idStream;
    id.print(idStream);
    return idStream.str();
  }

}  // namespace adm

max_stars_repo_name: tomjnixon/libadm

max_issues_repo_name: tomjnixon/libadm

max_forks_repo_name: tomjnixon/libadm


text:
/*
 *          Copyright Andrey Semashev 2007 - 2013.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   mutable_constant.hpp
 * \author Andrey Semashev
 * \date   06.11.2007
 *
 * The header contains implementation of a mutable constant attribute.
 */

#ifndef BOOST_LOG_ATTRIBUTES_MUTABLE_CONSTANT_HPP_INCLUDED_
#define BOOST_LOG_ATTRIBUTES_MUTABLE_CONSTANT_HPP_INCLUDED_

#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/static_assert.hpp>
#include <boost/mpl/if.hpp>
#include <boost/move/core.hpp>
#include <boost/move/utility.hpp>
#include <boost/type_traits/is_void.hpp>
#include <boost/log/detail/config.hpp>
#include <boost/log/detail/locks.hpp>
#include <boost/log/attributes/attribute.hpp>
#include <boost/log/attributes/attribute_cast.hpp>
#include <boost/log/attributes/attribute_value_impl.hpp>
#include <boost/log/detail/header.hpp>

#ifdef BOOST_LOG_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace attributes {

/*!
 * \brief A class of an attribute that holds a single constant value with ability to change it
 *
 * The mutable_constant attribute stores a single value of type, specified as the first template argument.
 * This value is returned on each attribute value acquisition.
 *
 * The attribute also allows to modify the stored value, even if the attribute is registered in an attribute set.
 * In order to ensure thread safety of such modifications the \c mutable_constant class is also parametrized
 * with three additional template arguments: mutex type, scoped write and scoped read lock types. If not specified,
 * the lock types are automatically deduced based on the mutex type.
 *
 * The implementation may avoid using these types to actually create and use the mutex, if a more efficient synchronization method is
 * available (such as atomic operations on the value type). By default no synchronization is done.
 */
#ifdef BOOST_LOG_DOXYGEN_PASS
template< typename T, typename MutexT = void, typename ScopedWriteLockT = auto, typename ScopedReadLockT = auto >
#else // BOOST_LOG_DOXYGEN_PASS
template<
    typename T,
    typename MutexT = void,
    typename ScopedWriteLockT =
#ifndef BOOST_LOG_NO_THREADS
        typename mpl::if_c<
            boost::log::aux::is_exclusively_lockable< MutexT >::value,
            boost::log::aux::exclusive_lock_guard< MutexT >,
            void
        >::type,
#else
        void,
#endif // BOOST_LOG_NO_THREADS
    typename ScopedReadLockT =
#ifndef BOOST_LOG_NO_THREADS
        typename mpl::if_c<
            boost::log::aux::is_shared_lockable< MutexT >::value,
            boost::log::aux::shared_lock_guard< MutexT >,
            ScopedWriteLockT
        >::type
#else
        ScopedWriteLockT
#endif // BOOST_LOG_NO_THREADS
#endif // BOOST_LOG_DOXYGEN_PASS
>
class mutable_constant :
    public attribute
{
public:
    //! The attribute value type
    typedef T value_type;

protected:
    //! Factory implementation
    class BOOST_LOG_VISIBLE impl :
        public attribute::impl
    {
    private:
        //! Mutex type
        typedef MutexT mutex_type;
        //! Shared lock type
        typedef ScopedReadLockT scoped_read_lock;
        //! Exclusive lock type
        typedef ScopedWriteLockT scoped_write_lock;
        BOOST_STATIC_ASSERT_MSG(!(is_void< mutex_type >::value || is_void< scoped_read_lock >::value || is_void< scoped_write_lock >::value), "Boost.Log: Mutex and both lock types either must not be void or must all be void");
        //! Attribute value wrapper
        typedef attribute_value_impl< value_type > attr_value;

    private:
        //! Thread protection mutex
        mutable mutex_type m_Mutex;
        //! Pointer to the actual attribute value
        intrusive_ptr< attr_value > m_Value;

    public:
        /*!
         * Initializing constructor
         */
        explicit impl(value_type const& value) : m_Value(new attr_value(value))
        {
        }
        /*!
         * Initializing constructor
         */
        explicit impl(BOOST_RV_REF(value_type) value) : m_Value(new attr_value(boost::move(value)))
        {
        }

        attribute_value get_value()
        {
            scoped_read_lock lock(m_Mutex);
            return attribute_value(m_Value);
        }

        void set(value_type const& value)
        {
            intrusive_ptr< attr_value > p = new attr_value(value);
            scoped_write_lock lock(m_Mutex);
            m_Value.swap(p);
        }

        void set(BOOST_RV_REF(value_type) value)
        {
            intrusive_ptr< attr_value > p = new attr_value(boost::move(value));
            scoped_write_lock lock(m_Mutex);
            m_Value.swap(p);
        }

        value_type get() const
        {
            scoped_read_lock lock(m_Mutex);
            return m_Value->get();
        }
    };

public:
    /*!
     * Constructor with the stored value initialization
     */
    explicit mutable_constant(value_type const& value) : attribute(new impl(value))
    {
    }
    /*!
     * Constructor with the stored value initialization
     */
    explicit mutable_constant(BOOST_RV_REF(value_type) value) : attribute(new impl(boost::move(value)))
    {
    }
    /*!
     * Constructor for casting support
     */
    explicit mutable_constant(cast_source const& source) : attribute(source.as< impl >())
    {
    }

    /*!
     * The method sets a new attribute value. The implementation exclusively locks the mutex in order
     * to protect the value assignment.
     */
    void set(value_type const& value)
    {
        get_impl()->set(value);
    }

    /*!
     * The method sets a new attribute value.
     */
    void set(BOOST_RV_REF(value_type) value)
    {
        get_impl()->set(boost::move(value));
    }

    /*!
     * The method acquires the current attribute value. The implementation non-exclusively locks the mutex in order
     * to protect the value acquisition.
     */
    value_type get() const
    {
        return get_impl()->get();
    }

protected:
    /*!
     * \returns Pointer to the factory implementation
     */
    impl* get_impl() const
    {
        return static_cast< impl* >(attribute::get_impl());
    }
};

/*!
 * \brief Specialization for unlocked case
 *
 * This version of attribute does not perform thread synchronization to access the stored value.
 */
template< typename T >
class mutable_constant< T, void, void, void > :
    public attribute
{
public:
    //! The attribute value type
    typedef T value_type;

protected:
    //! Factory implementation
    class BOOST_LOG_VISIBLE impl :
        public attribute::impl
    {
    private:
        //! Attribute value wrapper
        typedef attribute_value_impl< value_type > attr_value;

    private:
        //! The actual value
        intrusive_ptr< attr_value > m_Value;

    public:
        /*!
         * Initializing constructor
         */
        explicit impl(value_type const& value) : m_Value(new attr_value(value))
        {
        }
        /*!
         * Initializing constructor
         */
        explicit impl(BOOST_RV_REF(value_type) value) : m_Value(new attr_value(boost::move(value)))
        {
        }

        attribute_value get_value()
        {
            return attribute_value(m_Value);
        }

        void set(value_type const& value)
        {
            m_Value = new attr_value(value);
        }
        void set(BOOST_RV_REF(value_type) value)
        {
            m_Value = new attr_value(boost::move(value));
        }

        value_type get() const
        {
            return m_Value->get();
        }
    };

public:
    /*!
     * Constructor with the stored value initialization
     */
    explicit mutable_constant(value_type const& value) : attribute(new impl(value))
    {
    }
    /*!
     * Constructor with the stored value initialization
     */
    explicit mutable_constant(BOOST_RV_REF(value_type) value) : attribute(new impl(boost::move(value)))
    {
    }
    /*!
     * Constructor for casting support
     */
    explicit mutable_constant(cast_source const& source) : attribute(source.as< impl >())
    {
    }

    /*!
     * The method sets a new attribute value.
     */
    void set(value_type const& value)
    {
        get_impl()->set(value);
    }

    /*!
     * The method sets a new attribute value.
     */
    void set(BOOST_RV_REF(value_type) value)
    {
        get_impl()->set(boost::move(value));
    }

    /*!
     * The method acquires the current attribute value.
     */
    value_type get() const
    {
        return get_impl()->get();
    }

protected:
    /*!
     * \returns Pointer to the factory implementation
     */
    impl* get_impl() const
    {
        return static_cast< impl* >(attribute::get_impl());
    }
};

} // namespace attributes

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#include <boost/log/detail/footer.hpp>

#endif // BOOST_LOG_ATTRIBUTES_MUTABLE_CONSTANT_HPP_INCLUDED_

ext: hpp

max_issues_repo_name: graehl/boost

max_forks_repo_name: graehl/boost


text:
// Republish old robot state message (jan 2013) as new message

#include <stdio.h>
#include <inttypes.h>
#include <iostream>
#include <Eigen/Dense>
#include <boost/shared_ptr.hpp>
#include <boost/assign/std/vector.hpp>

#include <lcm/lcm-cpp.hpp>
#include <lcmtypes/drc_lcmtypes.hpp>
#include <ConciseArgs>

using namespace std;
using namespace Eigen;

class Pass{
  public:
    Pass(boost::shared_ptr<lcm::LCM> &lcm_, bool verbose_,
         std::string incoming_channel_);

    ~Pass(){
    }
  private:
    boost::shared_ptr<lcm::LCM> lcm_;
    bool verbose_;
    std::string incoming_channel_;

    void robotStateOldHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  drc::robot_state_prefeb2013_t* msg);

    int vis_counter_; // used for visualization
    int printf_counter_; // used for terminal feedback
};

Pass::Pass(boost::shared_ptr<lcm::LCM> &lcm_, bool verbose_,
         std::string incoming_channel_):
    lcm_(lcm_), verbose_(verbose_),
    incoming_channel_(incoming_channel_){

  lcm_->subscribe("OLD_TRUE_ROBOT_STATE",&Pass::robotStateOldHandler,this);

  vis_counter_ =0;
  printf_counter_ =0;

  cout << "Finished setting up\n";
}

void Pass::robotStateOldHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  drc::robot_state_prefeb2013_t* msg){
  std::cout << "got data\n";

  drc::robot_state_t msg_out;

  msg_out.utime = msg->utime;
  msg_out.robot_name = msg->robot_name;
  msg_out.origin_position= msg->origin_position;
  msg_out.origin_twist = msg->origin_twist;
  msg_out.origin_cov = msg->origin_cov;
  msg_out.num_joints =1;
  msg_out.joint_name= msg->joint_name;
  msg_out.joint_position = msg->joint_position;
  msg_out.joint_velocity = msg->joint_velocity;
  msg_out.measured_effort = msg->measured_effort;
  msg_out.joint_cov = msg->joint_cov;
  msg_out.contacts.num_contacts=0;

  lcm_->publish( ("TRUE_ROBOT_STATE") , &msg_out);

}

int main( int argc, char** argv ){
  ConciseArgs parser(argc, argv, "lidar-passthrough");
  bool verbose=false;
  string incoming_channel="OLD_TRUE_ROBOT_STATE";
  parser.add(verbose, "v", "verbose", "Verbosity");
  parser.add(incoming_channel, "l", "incoming_channel", "Incoming LIDAR channel");
  parser.parse();
  cout << verbose << " is verbose\n";
  cout << incoming_channel << " is incoming_channel\n";

  boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);
  if(!lcm->good()){
    std::cerr <<"ERROR: lcm is not good()" <<std::endl;
  }

  Pass app(lcm,verbose,incoming_channel);
  cout << "Ready to filter lidar points" << endl << "============================" << endl;
  while(0 == lcm->handle());
  return 0;
}

max_stars_repo_name: liangfok/oh-distro

max_issues_repo_name: liangfok/oh-distro

max_forks_repo_name: liangfok/oh-distro


text: #include <boost/date_time/gregorian/greg_month.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// (C) Copyright 2016-2021 Xilinx, Inc.
// All Rights Reserved.
//
// 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 "preprocess.h"

#include <iostream>
#include <fstream>
#include <sstream>
#include <set>
#include <string>
#include <boost/tokenizer.hpp>

#include "array_linearize.h"
#include "codegen.h"
#include "mars_ir.h"
#include "mars_ir_v2.h"
#include "mars_message.h"
#include "mars_opt.h"
#include "program_analysis.h"
#include "rose.h"
#include "math.h"

#include "array_delinearize.h"
#include "comm_opt.h"
#include "function_inline.h"
#include "postwrap_process.h"
#include "stream_ir.h"
#include "report.h"
using MarsProgramAnalysis::CMarsExpression;
using MarsProgramAnalysis::CMarsRangeExpr;
using MarsProgramAnalysis::CMarsVariable;
using std::ifstream;
using std::istringstream;
using std::unordered_set;
#undef DEBUG
#define DISABLE_DEBUG 1
#if DISABLE_DEBUG
#define DEBUG(stmts)
#else
#define DEBUG(stmts)                                                           \
  do {                                                                         \
    stmts;                                                                     \
  } while (false)
#endif

extern int check_kernel_argument_number(CSageCodeGen *codegen,
                                        vector<void *> vec_kernels,
                                        string tool);
int check_kernel_argument_number_top(CSageCodeGen *codegen, void *pTopFunc,
                                     string tool);
//  bool check_uniquify_function(CSageCodeGen *codegen, void *TopFunc);
bool check_kernel_name(CSageCodeGen *codegen, void *TopFunc, bool pure_kernel);
extern int check_const_array_size(CSageCodeGen *codegen, void *TopFunc);

extern void GetTLDMInfo_withPointer4(void *sg_node, void *pArg);

extern int constant_propagation_top(CSageCodeGen *codegen, void *pTopFunc,
                                    const CInputOptions &option,
                                    bool assert_generation);

int kernel_file_list_gen(CSageCodeGen *codegen, void *pTopFunc, int tool = 0) {
  printf("    Enter kernel_file_list_gen...\n");
  string kernel_list_file = "__merlin_kernel_list.h";
  if (test_file_for_read(kernel_list_file) != 0) {
#ifdef PROJ_DEBUG
    cerr << "file " << kernel_list_file << " has existed.\n";
#endif
    return 0;
  }
  {
    string cmd = "rm -rf " + kernel_list_file;
    system(cmd.c_str());
  }
  FILE *fp = fopen(kernel_list_file.c_str(), "w");
  size_t i;
  vector<pair<void *, string>> vecTldmPragmas;
  codegen->TraverseSimple(pTopFunc, "preorder", GetTLDMInfo_withPointer4,
                          &vecTldmPragmas);
  set<string> set_strings;
  //  printf("number = %d\n",vecTldmPragmas.size());
  for (i = 0; i < vecTldmPragmas.size(); i++) {
    string sFilter;
    string sCmd;
    map<string, pair<vector<string>, vector<string>>> mapParams;
    tldm_pragma_parse_whole(vecTldmPragmas[i].second, &sFilter, &sCmd,
                            &mapParams);
    //  printf("Enter func_inline_top sFilter %s\n\n\n",sFilter.c_str());
    //  printf("Enter func_inline_top sCmd %s\n\n\n",sCmd.c_str());
    boost::algorithm::to_upper(sFilter);
    boost::algorithm::to_upper(sCmd);

    if (CMOST_PRAGMA != sFilter && ACCEL_PRAGMA != sFilter &&
        TLDM_PRAGMA != sFilter) {
      continue;
    }
    if (CMOST_KERNEL != sCmd) {
      continue;
    }

    void *sg_kernel = nullptr;
    if (CMOST_TASK == sCmd) {
      void *sg_kernel_call = codegen->find_kernel_call(vecTldmPragmas[i].first);
      assert(sg_kernel_call);
      void *sg_task = sg_kernel_call;
      sg_kernel = codegen->GetFuncDeclByCall(sg_task);
    } else if (CMOST_KERNEL == sCmd) {
      void *next_stmt = codegen->GetNextStmt(vecTldmPragmas[i].first);
      if (codegen->IsFunctionDeclaration(next_stmt) != 0) {
        sg_kernel = next_stmt;
      } else if (codegen->IsExprStatement(next_stmt) != 0) {
        void *sg_call = codegen->GetFuncCallInStmt(next_stmt);
        sg_kernel = codegen->GetFuncDeclByCall(sg_call);
        //  } else {
        //    string msg = "Did not get a function declaration right after
        //    pragma:\n"; msg += "#pragma " + vecTldmPragmas[i].second;
        //    dump_critical_message("KWRAP", "ERROR", msg, 301, 1);
        //    throw std::exception();
      }
    }
    if (sg_kernel == nullptr) {
      continue;
    }

    string func_name = codegen->GetFuncName(sg_kernel);
    string user_kernel_name;
    if (!mapParams["name"].first.empty()) {
      user_kernel_name = mapParams["name"].first[0];
    } else {
      user_kernel_name = func_name;
    }
    string top_file_name = codegen->get_file(sg_kernel);
    string add_string = "//  " + top_file_name + "\n";
    set<string> set_files;
    if (tool == 1) {
      set_files.insert(top_file_name);
    } else {
      set_strings.insert(add_string);
    }
    SetVector<void *> sub_decls;
    SetVector<void *> sub_calls;
    codegen->GetSubFuncDeclsRecursively(sg_kernel, &sub_decls, &sub_calls);
    for (auto sub_decl : sub_decls) {
      if (codegen->GetFuncBody(sub_decl) == nullptr) {
        continue;
      }
      string sub_func_name = codegen->GetFuncName(sub_decl);
      string sub_file_name = codegen->get_file(sub_decl);
      string add_string = "//  " + sub_file_name + "\n";
      if (tool == 1) {
        set_files.insert(sub_file_name);
      } else {
        set_strings.insert(add_string);
      }
    }
    if (tool == 1) {
      string add_string = "//  " + func_name + "=";
      for (auto one_file : set_files) {
        add_string += one_file + " ";
      }
      add_string += "\n";
      set_strings.insert(add_string);
    }
  }
  for (auto add_string : set_strings) {
    //  printf("func_name = %s\n",top_file_name.c_str());
    fprintf(fp, "%s", add_string.c_str());
    //  printf("func call size = %d\n",vecCalls.size());

    //  for (size_t i=0; i < vecCalls.size(); i++) {
    //    check_single_file(codegen, vecCalls[i], top_file_name);
    //  }
  }
  fclose(fp);
  return 1;
}

vector<void *> get_top_kernels(CSageCodeGen *codegen, void *pTopFunc) {
  vector<pair<void *, string>> vecTldmPragmas;
  codegen->TraverseSimple(pTopFunc, "preorder", GetTLDMInfo_withPointer4,
                          &vecTldmPragmas);
  //  printf("number = %d\n",vecTldmPragmas.size());
  vector<void *> vecTopKernels;
  for (size_t i = 0; i < vecTldmPragmas.size(); i++) {
    string sFilter;
    string sCmd;
    map<string, pair<vector<string>, vector<string>>> mapParams;
    tldm_pragma_parse_whole(vecTldmPragmas[i].second, &sFilter, &sCmd,
                            &mapParams);
    //  printf("Enter func_inline_top sFilter %s\n\n\n",sFilter.c_str());
    //  printf("Enter func_inline_top sCmd %s\n\n\n",sCmd.c_str());
    boost::algorithm::to_upper(sFilter);
    boost::algorithm::to_upper(sCmd);

    if (CMOST_PRAGMA != sFilter && ACCEL_PRAGMA != sFilter &&
        TLDM_PRAGMA != sFilter) {
      continue;
    }
    if (CMOST_TASK == sCmd) {
      void *sg_kernel_call = codegen->find_kernel_call(vecTldmPragmas[i].first);
      if (sg_kernel_call != nullptr) {
        void *kernel = codegen->GetFuncDeclByCall(sg_kernel_call);
        if (kernel != nullptr) {
          vecTopKernels.push_back(kernel);
        }
      }
      continue;
    }
    if (CMOST_KERNEL == sCmd) {
      void *sg_kernel_call = codegen->find_kernel_call(vecTldmPragmas[i].first);
      if (sg_kernel_call != nullptr) {
        void *kernel = codegen->GetFuncDeclByCall(sg_kernel_call);
        if (kernel != nullptr) {
          vecTopKernels.push_back(kernel);
        }
      }

      void *sg_kernel = codegen->GetNextStmt(vecTldmPragmas[i].first);
      if ((codegen->IsFunctionDeclaration(sg_kernel) != 0) &&
          (codegen->GetFuncBody(sg_kernel) != nullptr)) {
        if (std::find(vecTopKernels.begin(), vecTopKernels.end(), sg_kernel) ==
            vecTopKernels.end()) {
          vecTopKernels.push_back(sg_kernel);
        }
      }
      continue;
    }
  }
  return vecTopKernels;
}

int preprocess_top(CSageCodeGen *codegen, void *pTopFunc,
                   const CInputOptions &options) {
  PreProcess instance(codegen, pTopFunc, options);
  instance.run();
  return 0;
}

void PreProcess::init() {
  if ("naive_hls" == mOptions.get_option_key_value("-a", "naive_hls")) {
    mNaive_tag = true;
    cout << "[MARS-PARALLEL-MSG] Naive HLS mode.\n";
  }
    mXilinx_flow = true;
    cout << "[MARS-PARALLEL-MSG] Enable xilinx flow mode.\n";
  if ("on" == mOptions.get_option_key_value("-a", "pure_kernel")) {
    mPure_kernel = true;
    cout << "[MARS-PARALLEL-MSG] Enable pure kernel mode.\n";
  }

  string effort_level = mOptions.get_option_key_value("-a", "effort");
  if (effort_level == "low") {
    mEffort = LOW;
  } else if (effort_level == "standard") {
    mEffort = STANDARD;
  } else if (effort_level == "medium") {
    mEffort = MEDIUM;
  } else if (effort_level == "high") {
    mEffort = HIGH;
  }
}

void PreProcess::build_mars_ir(bool check_pragma, bool pragma_in_loop,
                               bool build_node) {
  //  build Mars IR
  mMars_ir.clear();
  mMars_ir.get_mars_ir(m_ast, mTopFunc, mOptions, build_node, check_pragma,
                       pragma_in_loop);

  mValid &= !mMars_ir.isErrorOut();
}

void PreProcess::build_mars_ir_v2(bool build_node) {
  //  build Mars IR v2
  mMars_ir_v2.clear();
  mMars_ir_v2.build_mars_ir(m_ast, mTopFunc, false, build_node);
}

void PreProcess::clear_mars_ir() {
  //  clear Mars IR
  mMars_ir.clear();
}

bool PreProcess::run() {
  cout << "==============================================" << std::endl;
  cout << "-----=# Pragma Process Optimization Start#=----\n";
  cout << "==============================================" << std::endl
       << std::endl;

  bool Changed = false;

  //  generate kernel list
  kernel_file_list_gen(m_ast, mTopFunc, static_cast<int>(mXilinx_flow));

  if (!mNaive_tag) {
    m_ast->fix_defuse_issues(nullptr, false);
  }

  //  if (m_ast->IsMixedCAndCPlusPlusDesign() != 0) {
  //    dump_critical_message(PROCS_ERROR_9);
  //    mValid = false;
  //  }

  Changed |= preprocessing();

  //  //////////////////////////////////////////  /
  //  1. Checkers for pragmas
  //  //////////////////////////////////////////  /
  build_mars_ir(mPure_kernel, false, true);

  //  mValid &= check_address_of_port_array(m_ast, mTopFunc);

  RemoveKernelFunDeclStaticModifier();
  //  //////////////////////////////////////////  /
  //  2. Checkers for C++ syntax in kernel
  //  //////////////////////////////////////////  /
  //  check_valid_top(m_ast, mTopFunc);
  build_mars_ir_v2(false);

  //  checkMemberFunction();

  //  if (mPure_kernel) {
  //    checkOverloadInKernelFunction();
  //    PreCheckLocalVariableWithNonConstantDimension();
  //  } else {
  //    PostCheckLocalVariableWithNonConstantDimension();
  //  }
  //

  if (!mNaive_tag) {
    map<void *, string> loop2file;
    map<void *, string> loop2line;
    clear_mars_ir();
    build_mars_ir(false, false, true);

    Changed |= CanonicalizeLoop(&loop2file, &loop2line);

    if (Changed) {
      m_ast->reset_func_decl_cache();
      m_ast->reset_func_call_cache();
      m_ast->init_defuse_range_analysis();
      clear_mars_ir();
      build_mars_ir(false, false, true);
    }

    checkNonCanonicalLoop(&loop2file, &loop2line);

    std::ifstream my_file("conflict_type_def");
    if (my_file.good()) {
      my_file.close();
      system("rm -f conflict_type_def");
      throw std::exception();
    }
    Changed |= StandardizeLoop();

    if (Changed) {
      m_ast->reset_func_decl_cache();
      m_ast->reset_func_call_cache();
      m_ast->init_defuse_range_analysis();
    }
  }
  check_result();
  //  //////////////////////////////////////////  /
  //  3. Checkers for SW/HW interface
  //  //////////////////////////////////////////  /

  //  //////////////////////////////////////////  /
  //  4. Checkers for QoR limitations
  //  //////////////////////////////////////////  /
  clear_mars_ir();
  build_mars_ir(false, false, true);

  Changed |= processPragma(false);

  Changed |= postprocessing();

  if (!mNaive_tag) {
    parse_aggregate_init();
  }

  check_result();

  //  Youxiang 20170330 check partital range
  //  check_range_analysis();

  return Changed;
}

bool PreProcess::insertParallelPragma(CMirNode *node,
                                      set<CMirNode *> *p_visited) {
  bool Changed = false;
  if (p_visited->count(node) <= 0) {
    p_visited->insert(node);
  } else {
    return false;
  }
  vector<CMirNode *> child = node->get_all_child(true);
  for (size_t i = 0; i != child.size(); ++i) {
    Changed |= insertParallelPragma(child[i], p_visited);
  }
  if (node->is_function) {
    if (mXilinx_flow) {
      //  PR1028
      string new_pragma = std::string(HLS_PRAGMA) + " INLINE ";
      void *sg_pragma = m_ast->CreatePragma(new_pragma, node->ref);
      m_ast->PrependChild(node->ref, sg_pragma);
    }
    return Changed;
  }

  for (size_t i = 0; i < node->pragma_table.size(); i++) {
    auto decl = node->pragma_table[i];
    CAnalPragma ana_pragma(m_ast);
    bool errorOut;
    ana_pragma.PragmasFrontendProcessing(decl, &errorOut, false, true);
    if (ana_pragma.is_line_buffer() || ana_pragma.is_hls_pragma()) {
      continue;
    }
    string pragmaString = m_ast->GetPragmaString(decl);
    m_ast->AddComment_v1(node->ref, "Original: #pragma " + pragmaString);
    m_ast->RemoveStmt(decl);
  }

  node->pragma_table.clear();

  void *sg_loop = m_ast->TraceUpToLoopScope(node->ref);
  if ((m_ast->IsDoWhileStatement(sg_loop) != 0) ||
      (m_ast->IsWhileStatement(sg_loop) != 0)) {
    string str_loop = m_ast->UnparseToString(sg_loop).substr(0, 20);
    string loop_info =
        "'" + str_loop + "' " + getUserCodeFileLocation(m_ast, sg_loop, true);
    dump_critical_message(PROCS_WARNING_36(loop_info));
    return Changed;
  }

  if (checkPragmaLocation(node)) {
    return Changed;
  }

  string new_pragma =
      std::string(ACCEL_PRAGMA) + " " + CMOST_PARALLEL + " " + CMOST_complete;
  void *sg_pragma = m_ast->CreatePragma(new_pragma, node->ref);
  m_ast->PrependChild(node->ref, sg_pragma);
  CAnalPragma ana_pragma(m_ast);
  ana_pragma.set_pragma_type(CMOST_PARALLEL);
  ana_pragma.add_attribute(CMOST_complete, "");
  node->add_pragma(ana_pragma);
  node->pragma_table.push_back(sg_pragma);
  return true;
}

bool PreProcess::processPragma(bool pragma_in_loop) {
  bool Changed = false;

  // Transform HLS pipeline into ACCEL pipeline flatten
  Changed |= parseHLSPragma(pragma_in_loop);
  if (Changed) {
    clear_mars_ir();
    build_mars_ir(false, pragma_in_loop, true);
  }

  vector<CMirNode *> all_nodes;
  mMars_ir.get_topological_order_nodes(&all_nodes);
  set<CMirNode *> visited;
  for (size_t i = 0; i != all_nodes.size(); ++i) {
    CMirNode *node = all_nodes[i];
    if (visited.count(node) > 0) {
      continue;
    }
    Changed |= processPragma(node, false, &visited);
  }

  return Changed;
}

bool PreProcess::processPragma(CMirNode *node, bool flatten,
                               set<CMirNode *> *p_visited) {
  bool Changed = false;
  vector<CMirNode *> childs = node->get_all_child();
  if (flatten) {
    Changed |= insertParallelPragma(node, p_visited);
    return Changed;
  }
  p_visited->insert(node);
  bool current_flatten = false;
  if (!node->is_function) {
    current_flatten = ((node->has_opt_pragmas()) != 0) &&
                      !node->get_attribute(CMOST_flatten_option).empty();
    bool is_fgpip = true;
    if (current_flatten) {
      if (m_ast->ContainsUnsupportedLoop(node->ref, true)) {
        void *sg_loop = m_ast->TraceUpToLoopScope(node->ref);
        string str_loop = m_ast->UnparseToString(sg_loop).substr(0, 20);
        string loop_info = "'" + str_loop + "' " +
                           getUserCodeFileLocation(m_ast, sg_loop, true);
        dump_critical_message(PROCS_WARNING_31(loop_info));
        is_fgpip = false;
      }
    }
    Changed |= generateNewPragma(node, is_fgpip);
  }
  flatten |= current_flatten;
  for (size_t i = 0; i != childs.size(); ++i) {
    Changed |= processPragma(childs[i], flatten, p_visited);
  }
  return Changed;
}

bool PreProcess::generateNewPragma(CMirNode *node, bool is_fgpip) {
  bool Changed = false;

  for (size_t i = 0; i < node->pragma_table.size(); i++) {
    auto decl = node->pragma_table[i];
    if (m_ast->is_floating_node(decl) != 0) {
      continue;
    }
    CAnalPragma ana_pragma(m_ast);
    bool errorOut;
    ana_pragma.PragmasFrontendProcessing(decl, &errorOut, false, true);
    if (ana_pragma.is_line_buffer() || ana_pragma.is_hls_pragma()) {
      continue;
    }
    string pragmaString = m_ast->GetPragmaString(decl);
    m_ast->AddComment_v1(node->ref, "Original: #pragma " + pragmaString);
    m_ast->RemoveStmt(decl);
    Changed = true;
  }
  node->pragma_table.clear();

  bool exclusive = !node->get_attribute(CMOST_exclusive_option).empty();
  node->remove_attribute(CMOST_flatten_option);
  node->remove_attribute(CMOST_exclusive_option);
  if (checkPragmaLocation(node)) {
    return Changed;
  }
  auto vec_pragma = node->get_all_pragmas();
  for (int i = static_cast<int>(vec_pragma.size() - 1); i >= 0; --i) {
    CAnalPragma curr_pragma = vec_pragma[i];
    if (curr_pragma.is_pipeline() && is_fgpip) {
      //  genreated new PIPELINE pragma
      CAnalPragma new_pragma = curr_pragma;
      new_pragma.set_pragma_type(CMOST_PIPELINE);
      new_pragma.remove_attribute(CMOST_parallel_factor);
      new_pragma.remove_attribute(CMOST_complete);
      new_pragma.remove_attribute(CMOST_REDUCTION);
      new_pragma.remove_attribute(CMOST_LINE_BUFFER);
      new_pragma.remove_attribute(CMOST_reduction_scheme);
      void *sg_pragma = new_pragma.update_pragma(nullptr, false, node->ref);
      node->pragma_table.push_back(sg_pragma);
      m_ast->PrependChild(node->ref, sg_pragma);
      //  generate new reduction/line_buffer pragma
      string reduc_var = curr_pragma.get_attribute(CMOST_REDUCTION);
      string linebuf_var = curr_pragma.get_attribute(CMOST_LINE_BUFFER);
      string scheme_str = curr_pragma.get_attribute(CMOST_reduction_scheme);
      if (!reduc_var.empty()) {
        CAnalPragma tmp_pragma(m_ast);
        tmp_pragma.set_pragma_type(CMOST_REDUCTION);
        tmp_pragma.add_attribute(CMOST_variable, reduc_var);
        string scheme;
        if (!scheme_str.empty()) {
          if (scheme_str == CMOST_block || scheme_str == CMOST_cyclic) {
            scheme = scheme_str;
          } else {
            scheme = "auto";
          }
        } else {
          scheme = "auto";
        }
        tmp_pragma.add_attribute(CMOST_scheme, scheme);
        void *sg_reduction_pragma =
            tmp_pragma.update_pragma(nullptr, false, node->ref);
        node->pragma_table.push_back(sg_reduction_pragma);
        m_ast->PrependChild(node->ref, sg_reduction_pragma);
      }
      if (!linebuf_var.empty()) {
        CAnalPragma tmp_pragma(m_ast);
        tmp_pragma.set_pragma_type(CMOST_LINE_BUFFER);
        tmp_pragma.add_attribute(CMOST_variable, linebuf_var);
        void *sg_pragma = tmp_pragma.update_pragma(nullptr, false, node->ref);
        node->pragma_table.push_back(sg_pragma);
        m_ast->PrependChild(node->ref, sg_pragma);
      }
      Changed = true;
    }
    //  generate new PARALLEL pragma
    //  ACCEL flatten does not parallel the parent loop itself
    //  but only parallel its sub loops recursively
    if (curr_pragma.is_parallel() && !exclusive) {
      CAnalPragma new_pragma = curr_pragma;
      new_pragma.set_pragma_type(CMOST_PARALLEL);
      new_pragma.remove_attribute(CMOST_ii);
      new_pragma.remove_attribute(CMOST_REDUCTION);
      new_pragma.remove_attribute(CMOST_reduction_scheme);
      new_pragma.remove_attribute(CMOST_LINE_BUFFER);
      string reduc_var = curr_pragma.get_attribute(CMOST_REDUCTION);
      string linebuf_var = curr_pragma.get_attribute(CMOST_LINE_BUFFER);
      string scheme_str = curr_pragma.get_attribute(CMOST_reduction_scheme);
      void *sg_pragma = new_pragma.update_pragma(nullptr, false, node->ref);
      m_ast->PrependChild(node->ref, sg_pragma);
      node->pragma_table.push_back(sg_pragma);
      new_pragma.remove_attribute(CMOST_parallel_factor);
      //  generate new reduction/line_buffer pragma
      if (!reduc_var.empty()) {
        CAnalPragma tmp_pragma(m_ast);
        tmp_pragma.set_pragma_type(CMOST_REDUCTION);
        tmp_pragma.add_attribute(CMOST_variable, reduc_var);
        string scheme;
        if (!scheme_str.empty()) {
          if (scheme_str == CMOST_block || scheme_str == CMOST_cyclic) {
            scheme = scheme_str;
          } else {
            scheme = "auto";
          }
        } else {
          scheme = "auto";
        }
        tmp_pragma.add_attribute(CMOST_scheme, scheme);
        void *sg_reduction_pragma =
            tmp_pragma.update_pragma(nullptr, false, node->ref);
        node->pragma_table.push_back(sg_reduction_pragma);
        m_ast->PrependChild(node->ref, sg_reduction_pragma);
      }
      if (!linebuf_var.empty()) {
        CAnalPragma tmp_pragma(m_ast);
        tmp_pragma.set_pragma_type(CMOST_LINE_BUFFER);
        tmp_pragma.add_attribute(CMOST_variable, linebuf_var);
        void *sg_pragma = tmp_pragma.update_pragma(nullptr, false, node->ref);
        node->pragma_table.push_back(sg_pragma);
        m_ast->PrependChild(node->ref, sg_pragma);
      }
      Changed = true;
    }
    if (curr_pragma.is_loop_tiling()) {
      //  generate new TILING pragma
      CAnalPragma new_pragma = curr_pragma;
      void *sg_pragma = new_pragma.update_pragma(nullptr, false, node->ref);
      m_ast->PrependChild(node->ref, sg_pragma);
      node->pragma_table.push_back(sg_pragma);
      Changed = true;
    }
    // generate new FALSE_DEP/reduction/line_buffer pragma
    if (curr_pragma.is_false_dep() || curr_pragma.is_reduction()) {
      // Yuxin: May 26, currently we dont move in line buffer pragma
      // since it is applied under a scope
      // curr_pragma.is_line_buffer()
      CAnalPragma new_pragma = curr_pragma;
      string var_str = curr_pragma.get_attribute(CMOST_variable);
      if (curr_pragma.is_false_dep()) {
        new_pragma.set_pragma_type(CMOST_false_dep);
      } else if (curr_pragma.is_reduction()) {
        new_pragma.set_pragma_type(CMOST_REDUCTION);
      }

      if (!var_str.empty()) {
        new_pragma.add_attribute(CMOST_variable, var_str);
      }
      void *sg_pragma = new_pragma.update_pragma(nullptr, false, node->ref);
      m_ast->PrependChild(node->ref, sg_pragma);
      node->pragma_table.push_back(sg_pragma);
      Changed = true;
    }
  }
  return Changed;
}

bool PreProcess::preprocessing() {
  bool Changed = false;
  SgProject *project = static_cast<SgProject *>(mTopFunc);
  map<void *, void *> unrolled_loop2pragma;
  set<void *> unrolled_loops;
  bool errorOut = false;
  for (size_t i = 0; i < project->get_fileList().size(); i++) {
    SgSourceFile *file = isSgSourceFile(project->get_fileList()[i]);
    if ((m_ast->IsFromInputFile(file) == 0) ||
        m_ast->isWithInHeaderFile(file)) {
      continue;
    }
    //  1. check missing assert.h header file
    //    checkAssertHeader(file);

    //  2. add missing bracket
    m_ast->add_missing_brace(file);
    //  4. remove pragma within while, do-while loop structures
    Rose_STL_Container<SgNode *> pragmaStmts =
        NodeQuery::querySubTree(file, V_SgPragmaDeclaration);
    for (auto pragma : pragmaStmts) {
      SgPragmaDeclaration *decl = isSgPragmaDeclaration(pragma);
      ROSE_ASSERT(decl);
      CAnalPragma ana_pragma(m_ast);
      if (ana_pragma.PragmasFrontendProcessing(decl, &errorOut, false)) {
        if (!ana_pragma.is_loop_related()) {
          continue;
        }
        void *loop = m_ast->GetSpecifiedLoopByPragma(decl);
        string pragmaString = decl->get_pragma()->get_pragma();
        std::ostringstream oss;
        oss << "\"" << pragmaString << "\" "
            << getUserCodeFileLocation(m_ast, decl, true);
        string pragma_info = oss.str();
        if ((m_ast->IsDoWhileStatement(loop) != 0) ||
            (m_ast->IsWhileStatement(loop) != 0)) {
          if (ana_pragma.is_pipeline() || ana_pragma.is_hls_pragma()) {
            continue;
          }
          dump_critical_message(PROCS_WARNING_5(pragma_info));
          m_ast->AddComment("Original: #pragma " + pragmaString,
                            m_ast->GetScope(decl));
          m_ast->RemoveStmt(decl);
        } else if (loop == nullptr) {
          if (ana_pragma.is_hls_pragma()) {
            continue;
          }
          if (ana_pragma.is_reduction() || ana_pragma.is_line_buffer()) {
            continue;
          }
          dump_critical_message(PROCS_WARNING_6(pragma_info));
          m_ast->AddComment("Original: #pragma " + pragmaString,
                            m_ast->GetScope(decl));
          m_ast->RemoveStmt(decl);
        }
      }
    }
    Changed |= m_ast->simplify_pointer_access(file);
    //  6. remove double brace
    m_ast->remove_double_brace();

    //  7. remove redundant continue statement
    vector<void *> vec_all_loops;
    vector<void *> vec_sub_loops;
    m_ast->GetNodesByType_int(file, "preorder", V_SgForStatement,
                              &vec_sub_loops);
    vec_all_loops.insert(vec_all_loops.end(), vec_sub_loops.begin(),
                         vec_sub_loops.end());
    m_ast->GetNodesByType_int(file, "preorder", V_SgWhileStmt, &vec_sub_loops);
    vec_all_loops.insert(vec_all_loops.end(), vec_sub_loops.begin(),
                         vec_sub_loops.end());
    m_ast->GetNodesByType_int(file, "preorder", V_SgDoWhileStmt,
                              &vec_sub_loops);
    vec_all_loops.insert(vec_all_loops.end(), vec_sub_loops.begin(),
                         vec_sub_loops.end());
    for (auto loop : vec_all_loops) {
      void *body = m_ast->GetLoopBody(loop);
      if (body != nullptr) {
        if (m_ast->RemoveRedundantContinueStmt(body) != 0) {
          Changed = true;
        }
      }
    }
    //  8. replace a->b with (*a).b
    vector<void *> vec_arrow_exp;
    m_ast->GetNodesByType_int(file, "postorder", V_SgArrowExp, &vec_arrow_exp);
    for (auto &arrow_op : vec_arrow_exp) {
      void *rhs, *lhs;
      m_ast->GetExpOperand(arrow_op, &lhs, &rhs);
      void *new_lhs =
          m_ast->CreateExp(V_SgPointerDerefExp, m_ast->CopyExp(lhs));
      void *new_dot_exp =
          m_ast->CreateExp(V_SgDotExp, new_lhs, m_ast->CopyExp(rhs));
      m_ast->ReplaceExp(arrow_op, new_dot_exp);
      Changed = true;
    }
  }

  mValid &= !errorOut;

  return Changed;
}

bool PreProcess::postprocessing() {
  bool Changed = false;
  SgProject *project = static_cast<SgProject *>(mTopFunc);
  for (size_t i = 0; i < project->get_fileList().size(); i++) {
    SgSourceFile *file = isSgSourceFile(project->get_fileList()[i]);
    if ((m_ast->IsFromInputFile(file) == 0) ||
        m_ast->isWithInHeaderFile(file)) {
      continue;
    }
    //  1. replace sizeof(exp)
    Changed |= m_ast->replace_sizeof(file);
    //  2. split condition expression
    bool LocalChanged;
    do {
      LocalChanged = false;
      vector<void *> vec_cond_exp;
      m_ast->GetNodesByType_int(file, "preorder", V_SgConditionalExp,
                                &vec_cond_exp);
      for (auto cond_exp : vec_cond_exp) {
        void *func_decl = m_ast->TraceUpToFuncDecl(cond_exp);
        if ((func_decl == nullptr) ||
            (((m_ast->IsFromInputFile(func_decl) == 0) &&
              !m_ast->IsTransformation(func_decl)) ||
             m_ast->isWithInHeaderFile(func_decl))) {
          continue;
        }
        SgConditionalExp *sg_cond_exp =
            isSgConditionalExp(static_cast<SgNode *>(cond_exp));
        void *stmt = m_ast->TraceUpToStatement(cond_exp);
        if ((m_ast->IsLoopInit(stmt) != 0) || (m_ast->IsLoopTest(stmt) != 0)) {
          continue;
        }
        if (m_ast->IsVariableDecl(stmt)) {
          void *var_decl = stmt;
          if (m_ast->IsStatic(var_decl) &&
              m_ast->IsConstType(m_ast->GetTypebyVar(
                  m_ast->GetVariableInitializedName(var_decl))))
            // do not convert constant expression into non-constant expression
            continue;
        }
        if (m_ast->is_lvalue(sg_cond_exp) != 0) {
          continue;
        }

        SgType *sg_type = sg_cond_exp->get_type();
        while ((isSgTypedefType(sg_type) != nullptr) ||
               (isSgModifierType(sg_type) != nullptr)) {
          sg_type = isSgType(
              static_cast<SgNode *>(m_ast->GetBaseTypeOneLayer(sg_type)));
        }
        //  Fix Bug1908 anonymous struct type
        if ((isSgTemplateType(sg_type) != nullptr) ||
            (isSgTypeOfType(sg_type) != nullptr) ||
            (isSgTypeVoid(sg_type) != nullptr) ||
            (isSgReferenceType(sg_type) != nullptr) ||
            (isSgArrayType(sg_type) != nullptr) ||
            (isSgFunctionType(sg_type) != nullptr)) {
          continue;
        }
        bool is_assert = false;
        vector<void *> vec_calls;
        m_ast->GetNodesByType_int(sg_cond_exp, "preorder", V_SgFunctionCallExp,
                                  &vec_calls);
        for (auto call : vec_calls) {
          if (m_ast->IsAssertFailCall(call)) {
            is_assert = true;
            break;
          }
        }
        if (is_assert) {
          continue;
        }
        m_ast->ReplaceExpWithStmt(sg_cond_exp);
        Changed = true;
        LocalChanged = true;
        break;
      }
    } while (LocalChanged);
  }

  return Changed;
}

bool PreProcess::checkPragmaLocation(CMirNode *node) {
  void *scope = node->ref;
  void *sg_loop = m_ast->GetParent(scope);
  assert(m_ast->IsForStatement(sg_loop) || m_ast->IsWhileStatement(sg_loop) ||
         m_ast->IsDoWhileStatement(sg_loop));
  if (m_ast->IsForStatement(sg_loop) != 0) {
    if (m_ast->isWithInHeaderFile(sg_loop)) {
      string sFileName = m_ast->GetFileInfo_filename(sg_loop, 1);
      if (mHeaderFileReported.count(sFileName) > 0) {
        return true;
      }
      mHeaderFileReported.insert(sFileName);
      string str_label = m_ast->get_internal_loop_label(sg_loop);
      string loc = getUserCodeFileLocation(m_ast, sg_loop, true);
      dump_critical_message(PROCS_WARNING_1(loc));
      return true;
    }
  } else if ((m_ast->IsWhileStatement(sg_loop) != 0) ||
             (m_ast->IsDoWhileStatement(sg_loop) != 0)) {
    //  FIXME:
    if (m_ast->isWithInHeaderFile(sg_loop)) {
      return true;
    }
  }
  return false;
}

bool PreProcess::CanonicalizeLoop(map<void *, string> *p_loop2file,
                                  map<void *, string> *p_loop2line) {
  bool ret = false;
  vector<CMirNode *> vec_nodes;
  mMars_ir.get_topological_order_nodes(&vec_nodes);

  for (int i = static_cast<int>(vec_nodes.size() - 1); i > 0; i--) {
    CMirNode *node = vec_nodes[i];
    if (node->is_function) {
      continue;
    }
    void *loop_body = node->ref;
    void *sg_loop = m_ast->GetParent(loop_body);
    int ret1 = m_ast->CanonicalizeForLoop(&sg_loop, true);
    string sFileName = m_ast->GetFileInfo_filename(sg_loop, 1);
    string sFileLine = my_itoa(m_ast->GetFileInfo_line(sg_loop));

    if (p_loop2file->find(sg_loop) == p_loop2file->end()) {
      (*p_loop2file)[sg_loop] = sFileName;
    }
    if (p_loop2line->find(sg_loop) == p_loop2line->end()) {
      (*p_loop2line)[sg_loop] = sFileLine;
    }
    ret |= ret1;
  }
  return ret;
}

bool PreProcess::StandardizeLoop() {
  vector<CMirNode *> vec_nodes;
  mMars_ir.get_topological_order_nodes(&vec_nodes);
  bool ret = false;

  for (int i = static_cast<int>(vec_nodes.size() - 1); i > 0; i--) {
    CMirNode *node = vec_nodes[i];
    if (node->is_function) {
      continue;
    }
    void *loop_body = node->ref;
    void *sg_loop = m_ast->GetParent(loop_body);
    ret |= m_ast->StandardizeForLoop(&sg_loop);
  }
  return ret;
}

void PreProcess::checkNonCanonicalLoop(map<void *, string> *p_loop2file,
                                       map<void *, string> *p_loop2line) {
  vector<CMirNode *> kernels;
  set<CMirNode *> all_nodes;
  vector<CMirNode *> all_nodes_vec;
  mMars_ir.get_all_kernel_nodes(&kernels, &all_nodes, &all_nodes_vec);
  bool hint_tag = false;
  for (size_t i = 0; i != all_nodes_vec.size(); ++i) {
    CMirNode *node = all_nodes_vec[i];
    if (node->is_function) {
      continue;
    }
    void *loop_body = node->ref;
    void *sg_loop = m_ast->GetParent(loop_body);
    string sFileName = m_ast->GetFileInfo_filename(sg_loop, 1);
    if (p_loop2file->find(sg_loop) != p_loop2file->end()) {
      sFileName = (*p_loop2file)[sg_loop];
    } else {
      sFileName = m_ast->GetFileInfo_filename(sg_loop, 1);
    }
    string sFileLine = my_itoa(m_ast->GetFileInfo_line(sg_loop));
    //  FIXME: str_loc is null
    string str_loc = getUserCodeFileLocation(m_ast, sg_loop, true);
    string str_loop = m_ast->UnparseToString(sg_loop).substr(0, 20);
    void *iv;
    void *lb;
    void *ub;
    void *step;
    void *body;
    bool inc_dir;
    bool inclusive_bound;
    bool ret = m_ast->IsCanonicalForLoop(sg_loop, &iv, &lb, &ub, &step, &body,
                                         &inc_dir, &inclusive_bound) != 0;
    int64_t nStep = 0;
    if (ret) {
      ret = (m_ast->GetLoopStepValueFromExpr(step, &nStep) != 0);
    }

    bool ret1 = ret;
    //  Yuxin: commented on Dec 04 2016, step 1: canonicalize; step 2: check the
    //  rest non-canonical loops

    if (!ret1) {
    } else {
      bool has_loop_bound_spec = false;
      Rose_STL_Container<SgNode *> pragmaStmts = NodeQuery::querySubTree(
          static_cast<SgNode *>(sg_loop), V_SgPragmaDeclaration);
      for (size_t j = 0; j != pragmaStmts.size(); ++j) {
        void *sg_pragma = pragmaStmts[j];
        void *loop_scope = m_ast->TraceUpToLoopScope(sg_pragma);
        if (loop_scope != sg_loop) {
          continue;
        }
        if (mMars_ir.isHLSTripCount(sg_pragma)) {
          has_loop_bound_spec = true;
          break;
        }
      }
      if (has_loop_bound_spec) {
        continue;
      }
      CMarsRangeExpr var_range = CMarsVariable(sg_loop, m_ast).get_range();
      if ((var_range.is_const_ub() == 0) || (var_range.is_const_lb() == 0)) {
        CMirNode *parent_node = node->get_parent();
        while ((parent_node != nullptr) && !parent_node->is_kernel) {
          if (parent_node->get_parent() != nullptr) {
            parent_node = parent_node->get_parent();
          } else {
            vector<CMirNode *> preds = parent_node->get_all_predecessor();
            if (!preds.empty()) {
              parent_node = preds[0];
            } else {
              parent_node = nullptr;
            }
          }
        }
        var_range.refine_range_in_scope(
            parent_node != nullptr ? parent_node->ref : nullptr, sg_loop);
      }

      if ((var_range.is_const_ub() == 0) || (var_range.is_const_lb() == 0)) {
        //  FIXME: meta locationt info does not work for non-canonical loop,
        //  Yuxin Nov 30
        string loop_info = "'" + str_loop + "' " + str_loc;
        dump_critical_message(PROCS_WARNING_3(loop_info));
        hint_tag = true;
      }
    }
  }
  if (hint_tag) {
    dump_critical_message(PROCS_INFO_2);
  }
}

void PreProcess::RemoveKernelFunDeclStaticModifier() {
  auto kernels = get_top_kernels(m_ast, mTopFunc);

  for (auto kernel : kernels) {
    vector<void *> all_decls = m_ast->GetAllFuncDecl(kernel);

    for (auto decl : all_decls) {
      //  Youxiang: 20170601 remove static modifier of top kernel
      //  functions
      m_ast->UnSetStatic(decl);
    }
  }
}

int PreProcess::remove_dummy_return_top(CSageCodeGen *codegen, void *pTopFunc) {
  printf("    Enter removing dummy return...\n");
  vector<void *> vecTopKernels = get_top_kernels(codegen, pTopFunc);

  bool has_real_return = false;
  for (auto &func : vecTopKernels) {
    void *func_body = codegen->GetFuncBody(func);
    if (func_body == nullptr) {
      continue;
    }
    vector<void *> ret_stmts;
    codegen->GetNodesByType_int(func_body, "preorder", V_SgReturnStmt,
                                &ret_stmts);
    if (ret_stmts.empty()) {
      continue;
    }
    bool local_has_real_return = false;
    if (ret_stmts.size() > 1) {
      has_real_return = local_has_real_return = true;
    } else {
      void *ret_stmt = ret_stmts[0];
      if (codegen->GetChildStmtIdx(func_body, ret_stmt) !=
          codegen->GetChildStmtNum(func_body) - 1) {
        has_real_return = local_has_real_return = true;
      } else if (codegen->IsDummyReturnStmt(ret_stmt) != 0) {
        codegen->RemoveChild(ret_stmt);
      }
    }
  }
  return 0;
}

void PreProcess::check_multiple_nodes() {
  bool switch_low = false;
  //  for each edge
  set<void *> visited;
  for (auto &edge : mMars_ir_v2.get_all_edges()) {
    //  0. check if the array is an host interface
    void *array = edge->GetPort();
    if (visited.count(array) > 0) {
      continue;
    }
    visited.insert(array);
    //  1. # of access is two
    vector<CMarsEdge *> edges_of_array;
    for (auto &edge_t : mMars_ir_v2.get_all_edges()) {
      void *array_t = edge_t->GetPort();
      if (array_t == array) {
        edges_of_array.push_back(edge_t);
      }
    }
    assert(!edges_of_array.empty());
    vector<CMarsNode *> all_nodes;
    set<CMarsNode *> all_nodes_set;
    for (auto &edge : edges_of_array) {
      CMarsNode *node0 = edge->GetNode(0);
      CMarsNode *node1 = edge->GetNode(1);
      if (all_nodes_set.count(node0) <= 0) {
        all_nodes_set.insert(node0);
        all_nodes.push_back(node0);
      }
      if (all_nodes_set.count(node1) <= 0) {
        all_nodes_set.insert(node1);
        all_nodes.push_back(node1);
      }
    }
    string var_name = m_ast->GetVariableName(array);
    if (m_ast->IsScalarType(array) != 0) {
#if PROJDEBUG
      cout << "Cannot split scalar variable \'" << var_name << "\'"
           << " because its def/use is inaccurate" << endl;
#endif
      continue;
    }
    //  sort all the nodes according to original schedule vector
    sort(all_nodes.begin(), all_nodes.end(),
         [](CMarsNode *node0, CMarsNode *node1) {
           return !(node0->is_after(node1));
         });

    //  at least a write access
    //
    //  check read access
    string var_info =
        "\'" + var_name + "\' " + getUserCodeFileLocation(m_ast, array, true);
    for (auto node : all_nodes) {
      if (!node->port_is_read(array)) {
        continue;
      }
      if (mMars_ir_v2.has_definite_coarse_grained_def(node, array)) {
        continue;
      }
      if (mMars_ir_v2.is_kernel_port(array)) {
#if PROJDEBUG
        cout << "Cannot support synchronization on host interface \'"
             << var_name << "\'" << endl;
#endif
        switch_low = true;
        dump_critical_message(PROCS_WARNING_25(var_info));
        break;
      }
#if PROJDEBUG
      void *scope = node->get_scope();
      cout << "Cannot find definition of read access on shared memory \'"
           << var_name << "\' in scope \'" << m_ast->_up(scope) << " \'"
           << endl;
#endif
      dump_critical_message(PROCS_WARNING_24(var_info));
      switch_low = true;
      break;
    }
  }
}

void PreProcess::check_func_inline_legality(CSageCodeGen *codegen,
                                            void *pTopFunc) {
  printf("    Enter check function inline legality...\n\n");

  vector<void *> kernels = get_top_kernels(codegen, pTopFunc);
  int kernel_num = kernels.size();

  for (int j = 0; j < kernel_num; ++j) {
    SetVector<void *> sub_funcs;
    SetVector<void *> sub_calls;
    codegen->GetSubFuncDeclsRecursively(kernels[j], &sub_funcs, &sub_calls);
    for (auto &sub_decl : sub_funcs) {
      vector<void *> all_calls;
      codegen->GetFuncCallsFromDecl(sub_decl, nullptr, &all_calls);

      for (int i = static_cast<int>(all_calls.size() - 1); i >= 0; i--) {
        func_inline(codegen, all_calls[i], mEffort, false, true);
      }
    }
  }
}

int check_const_array_size(CSageCodeGen *codegen, void *pTopFunc) {
  printf("    Check constant array size...\n");

  auto kernels = get_top_kernels(codegen, pTopFunc);
  for (auto kernel : kernels) {
    //  get all variable reference from function declaration cross function
    vector<void *> vec_refs;
    codegen->GetNodesByType(kernel, "preorder", "SgVarRefExp", &vec_refs, false,
                            true);
    for (auto ref : vec_refs) {
      void *var_init = codegen->GetVariableInitializedName(ref);
      void *type = codegen->GetTypebyVar(var_init);
      if (codegen->IsConstType(type) == 0) {
        continue;
      }
      if (codegen->IsArrayType(type) == 0) {
        continue;
      }
      cout << "find one const variable = " << codegen->UnparseToString(var_init)
           << endl;
      void *basic_type;
      vector<size_t> basic_size;
      codegen->get_type_dimension(type, &basic_type, &basic_size, var_init);
      basic_type = codegen->GetBaseType(basic_type, true);
      int64_t total_size = 1;
      for (auto size : basic_size) {
        total_size *= size;
      }
      int sizeof_type = codegen->get_bitwidth_from_type_str(
          codegen->UnparseToString(basic_type));
      total_size *=
          codegen->get_sizeof_arbitrary_precision_integer(sizeof_type);
      if (total_size > MAX_CONST_BYTE) {
        string msg1 = "'" + codegen->UnparseToString(var_init) + "'";
        msg1 += getUserCodeFileLocation(codegen, var_init, true);
        string msg2 = std::to_string(total_size);
        dump_critical_message(PROCS_WARNING_41(msg1, msg2));
      }
      cout << "Total size = " << total_size << endl;
    }
  }
  return 0;
}

int local_static_replace(CSageCodeGen *codegen, void *func_decl,
                         set<void *> *visited) {
  vector<void *> all_vars;
  codegen->GetNodesByType_int(func_decl, "preorder", V_SgVariableDeclaration,
                              &all_vars);

  string func_name = codegen->GetFuncName(func_decl, false);
  bool Changed = false;
  for (auto var : all_vars) {
    if (!codegen->IsStatic(var)) {
      continue;
    }
    void *var_init = codegen->GetVariableInitializedName(var);
    vector<void *> vec_refs;
    codegen->get_ref_in_scope(var_init, func_decl, &vec_refs);
    if (vec_refs.empty()) {
      Changed = true;
      codegen->RemoveStmt(var);
      continue;
    }

    //  check whether we can move local static variable into global scope
    void *var_initializer = codegen->GetInitializer(var_init);
    void *var_initializer_rhs = codegen->GetInitializerOperand(var_init);
    if ((var_initializer != nullptr) && (var_initializer_rhs == nullptr)) {
      continue;
    }
    bool have_local_ref = false;
    if (var_initializer_rhs != nullptr) {
      vector<void *> sub_vec_refs;
      codegen->GetNodesByType_int(var_initializer_rhs, "preorder",
                                  V_SgVarRefExp, &sub_vec_refs);
      for (auto ref : sub_vec_refs) {
        auto init = codegen->GetVariableInitializedName(ref);
        if ((codegen->IsLocalInitName(init) != 0) ||
            (codegen->IsArgumentInitName(init) != 0)) {
          have_local_ref = true;
          break;
        }
      }
    }
    //  FIXME: variable name may conflict with existing variable names
    string new_var_name = func_name + "_" + codegen->GetVariableName(var_init);
    new_var_name = codegen->legalizeName(new_var_name);
    codegen->get_valid_global_name(codegen->GetGlobal(func_decl),
                                   &new_var_name);
    void *new_var_decl = codegen->CreateVariableDecl(
        codegen->GetTypebyVar(var_init), new_var_name,
        (var_initializer_rhs != nullptr) && !have_local_ref
            ? codegen->CopyExp(var_initializer_rhs)
            : nullptr,
        codegen->GetGlobal(func_decl));
    void *insert_pos = func_decl;
    while (codegen->IsPragmaDecl(codegen->GetPreviousStmt(insert_pos)) != 0) {
      insert_pos = codegen->GetPreviousStmt(insert_pos);
    }
    codegen->InsertStmt(new_var_decl, insert_pos);
    codegen->SetStatic(new_var_decl);
    void *new_var_init = codegen->GetVariableInitializedName(new_var_decl);

    for (auto ref : vec_refs) {
      codegen->ReplaceExp(ref, codegen->CreateVariableRef(new_var_init));
    }
    if (have_local_ref) {
      string new_var_flag_name = new_var_name + "_flag";
      new_var_flag_name = codegen->legalizeName(new_var_flag_name);
      codegen->get_valid_global_name(codegen->GetGlobal(func_decl),
                                     &new_var_flag_name);
      void *flag_decl = codegen->CreateVariableDecl(
          "int", new_var_flag_name,
          (var_initializer_rhs != nullptr) && !have_local_ref
              ? codegen->CopyExp(var_initializer_rhs)
              : nullptr,
          codegen->GetGlobal(func_decl));
      codegen->SetStatic(flag_decl);
      codegen->InsertStmt(flag_decl, new_var_decl);
      void *flag_init = codegen->GetVariableInitializedName(flag_decl);

      void *basic_block = codegen->CreateBasicBlock(nullptr, false, nullptr);
      void *new_var_assign = codegen->CreateStmt(
          V_SgAssignStatement, codegen->CreateVariableRef(new_var_init),
          codegen->CopyExp(var_initializer_rhs));
      codegen->AppendChild(basic_block, new_var_assign);

      void *flag_assign = codegen->CreateStmt(
          V_SgAssignStatement, codegen->CreateVariableRef(flag_init),
          codegen->CreateConst(1));
      codegen->AppendChild(basic_block, flag_assign);

      void *flag_not_cond =
          codegen->CreateExp(V_SgNotOp, codegen->CreateVariableRef(flag_init));
      void *if_stmt =
          codegen->CreateIfStmt(flag_not_cond, basic_block, nullptr);
      codegen->InsertStmt(if_stmt, var);
    }

    codegen->RemoveStmt(var);
    Changed = true;
  }
  SetVector<void *> sub_funcs;
  SetVector<void *> sub_calls;
  codegen->GetSubFuncDeclsRecursively(func_decl, &sub_funcs, &sub_calls);
  for (auto sub_decl : sub_funcs) {
    if (visited->count(sub_decl) > 0) {
      continue;
    }
    visited->insert(sub_decl);
    Changed |= local_static_replace(codegen, sub_decl, visited);
  }
  return static_cast<int>(Changed);
}

void PreProcess::check_empty_kernel() {
  bool empty = mMars_ir_v2.get_all_nodes().empty();
  if (empty) {
    dump_critical_message(PROCS_ERROR_40);
  }
}

void PreProcess::parse_aggregate_init() {
  clear_mars_ir();
  build_mars_ir(false, true, true);

  vector<CMirNode *> all_nodes;
  mMars_ir.get_topological_order_nodes(&all_nodes);
  set<SgBasicBlock *> fg_set;
  for (size_t i = 0; i != all_nodes.size(); ++i) {
    CMirNode *node = all_nodes[i];
    if (node->is_fine_grain) {
      fg_set.insert(node->ref);
    }
  }

  m_ast->parse_aggregate();

  clear_mars_ir();
  build_mars_ir(false, true, true);

  vector<CMirNode *> all_nodes1;
  //    set<void *> visited;
  set<CMirNode *> visited;
  mMars_ir.get_topological_order_nodes(&all_nodes1);
  for (size_t i = 0; i != all_nodes1.size(); ++i) {
    CMirNode *node = all_nodes1[i];
    if (!node->is_fine_grain && fg_set.find(node->ref) != fg_set.end()) {
      vector<CMirNode *> child = node->get_all_child();
      for (size_t i = 0; i != child.size(); ++i) {
        CMirNode *node_c = child[i];
        if (visited.find(child[i]) == visited.end()) {
          visited.insert(child[i]);
          if (node_c->has_opt_pragmas() == 0) {
            string new_pragma = std::string(ACCEL_PRAGMA) + " " +
                                CMOST_PARALLEL + " " + CMOST_complete;
            void *sg_pragma = m_ast->CreatePragma(new_pragma, node_c->ref);
            m_ast->PrependChild(node_c->ref, sg_pragma);
            CAnalPragma ana_pragma(m_ast);
            ana_pragma.set_pragma_type(CMOST_PARALLEL);
            ana_pragma.add_attribute(CMOST_complete, "");
            node_c->add_pragma(ana_pragma);
            node_c->pragma_table.push_back(sg_pragma);
          }
        }
      }
    }
  }
}

void PreProcess::check_range_analysis() {
  auto top_kernels = get_top_kernels(m_ast, mTopFunc);
  set<void *> all_kernels;
  for (auto kernel : top_kernels) {
    all_kernels.insert(kernel);
    SetVector<void *> sub_kernels;
    SetVector<void *> sub_calls;
    m_ast->GetSubFuncDeclsRecursively(kernel, &sub_kernels, &sub_calls);
    all_kernels.insert(sub_kernels.begin(), sub_kernels.end());
  }

  int ret = constant_propagation_top(m_ast, mTopFunc, mOptions, true);
  if (ret != 0) {
    m_ast->reset_range_analysis();
  }

  auto range_map = MarsProgramAnalysis::get_range_analysis(m_ast);
  map<string, void *> loc_map;
  //  Sort by file location
  for (auto var_range : range_map) {
    void *var = var_range.first;
    string var_info = "\'" + m_ast->_up(var) + "\'";
    var_info += " " + getUserCodeFileLocation(m_ast, var, true);
    loc_map[var_info] = var;
  }
  for (auto var_loc : loc_map) {
    string var_info = var_loc.first;
    void *var = var_loc.second;
    CMarsRangeExpr range = range_map[var];
    if (isSgVarRefExp(static_cast<SgNode *>(var)) != nullptr) {
      continue;
    }
    void *func_decl = m_ast->TraceUpToFuncDecl(var);
    if ((func_decl == nullptr) || all_kernels.count(func_decl) <= 0) {
      continue;
    }
    if ((range.has_lb() != 0) && (range.has_ub() != 0)) {
      continue;
    }
    if ((range.has_lb() == 0) && (range.has_ub() == 0)) {
      continue;
    }
    bool no_lb = range.has_lb() == 0;
    dump_critical_message(SYNCHK_WARNING_3(no_lb, var_info));
  }
}

void PreProcess::check_result() {
  if (!mValid || (mXilinx_flow && !mValidXilinx)) {
    throw std::exception();
  }
}

bool PreProcess::parseHLSPragma(bool pragma_in_loop) {
  bool Changed = false;
  vector<void *> vec_pragmas;
  m_ast->GetNodesByType_int(mTopFunc, "preorder", V_SgPragmaDeclaration,
                            &vec_pragmas);
  vector<void *> remove_pragmas;
  for (size_t i = 0; i < vec_pragmas.size(); i++) {
    auto pragma = vec_pragmas[i];
    bool errorOut = false;
    CAnalPragma ana_pragma(m_ast);
    if (ana_pragma.PragmasFrontendProcessing(pragma, &errorOut, false, true)) {
      if (ana_pragma.get_vendor_type() != HLS_PRAGMA)
        continue;
      if (ana_pragma.get_pragma_type() != HLS_PIPELINE)
        continue;
      string ii_str = ana_pragma.get_attribute(HLS_PIPELINE_II);
      void *sg_loop = m_ast->TraceUpToLoopScope(pragma);
      if (sg_loop == nullptr)
        continue;
      void *sg_pragma = nullptr;
      if (ii_str == "") {
        string new_pragma = "ACCEL PIPELINE FLATTEN";
        sg_pragma = m_ast->CreatePragma(
            new_pragma, pragma_in_loop ? m_ast->GetLoopBody(sg_loop)
                                       : m_ast->GetScope(sg_loop));
      } else {
        string new_pragma = "ACCEL PIPELINE FLATTEN II=" + ii_str;
        sg_pragma = m_ast->CreatePragma(
            new_pragma, pragma_in_loop ? m_ast->GetLoopBody(sg_loop)
                                       : m_ast->GetScope(sg_loop));
      }
      if (sg_pragma != nullptr) {
        if (pragma_in_loop)
          m_ast->PrependChild(m_ast->GetLoopBody(sg_loop), sg_pragma);
        else
          m_ast->InsertStmt(sg_pragma, sg_loop);
        m_ast->RemoveStmt(pragma);
        Changed = true;
      }
    }
  }
  return Changed;
}

max_stars_repo_name: Xilinx/merlin-compiler

max_issues_repo_name: Xilinx/merlin-compiler

max_forks_repo_name: Xilinx/merlin-compiler


text:
// OpenTissue, A toolbox for physical based simulation and animation.
// Copyright (C) 2007 Department of Computer Science, University of Copenhagen
//
#include <OpenTissue/configuration.h>
#include <OpenTissue/core/spline/spline.h>

#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>

// Boost Test declaration and Checking macros
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/floating_point_comparison.hpp>

typedef OpenTissue::spline::MathTypes<double, size_t>    math_types;
typedef math_types::vector_type                                vector_type;
typedef std::vector<double>                                    knot_container;
typedef std::vector<vector_type>                               point_container;

typedef OpenTissue::spline::NUBSpline<knot_container, point_container> spline_type;

BOOST_AUTO_TEST_SUITE(opentissue_spline_compute_point_on_spline);

BOOST_AUTO_TEST_CASE(test_compute_point_on_spline)
{
  knot_container U;

  U.push_back(0.0);
  U.push_back(0.0);
  U.push_back(0.0);  //k = 3
  U.push_back(1.0);
  U.push_back(2.0);
  U.push_back(3.0);
  U.push_back(4.0);  // n = 6  => |P| = 7
  U.push_back(5.0);
  U.push_back(5.0);
  U.push_back(5.0);  // m = 9  => |U| = 10

  // Indices of basis functions belongs to the interval [0..n]

  point_container P;
  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;
  vector_type p1(2);  p1(0) = 1.0; p1(1) = 0.0;
  vector_type p2(2);  p2(0) = 2.0; p2(1) = 0.0;
  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;
  vector_type p4(2);  p4(0) = 4.0; p4(1) = 0.0;
  vector_type p5(2);  p5(0) = 5.0; p5(1) = 0.0;
  vector_type p6(2);  p6(0) = 6.0; p6(1) = 0.0;

  P.push_back(p0);
  P.push_back(p1);
  P.push_back(p2);
  P.push_back(p3);
  P.push_back(p4);
  P.push_back(p5);
  P.push_back(p6);

  spline_type spline(3,U,P);

  double const tolerance = 0.00001;

  vector_type q0(2);
  vector_type q1(2);
  vector_type q2(2);
  vector_type q3(2);
  vector_type q4(2);
  vector_type q5(2);
  vector_type q6(2);

  double const du = 5.0/6.0;
  double u = 0.0;
  OpenTissue::spline::compute_point_on_spline(u, spline, q0);
  u += du;
  OpenTissue::spline::compute_point_on_spline(u, spline, q1);
  u += du;
  OpenTissue::spline::compute_point_on_spline(u, spline, q2);
  u += du;
  OpenTissue::spline::compute_point_on_spline(u, spline, q3);
  u += du;
  OpenTissue::spline::compute_point_on_spline(u, spline, q4);
  u += du;
  OpenTissue::spline::compute_point_on_spline(u, spline, q5);
  u += du;
  OpenTissue::spline::compute_point_on_spline(u, spline, q6);

  BOOST_CHECK_CLOSE( p0(0), q0(0), tolerance );
  BOOST_CHECK_CLOSE( p0(1), q0(1), tolerance );

  BOOST_CHECK_CLOSE( q0(1), 0.0, tolerance );
  BOOST_CHECK_CLOSE( q1(1), 0.0, tolerance );
  BOOST_CHECK_CLOSE( q2(1), 0.0, tolerance );
  BOOST_CHECK_CLOSE( q3(1), 0.0, tolerance );
  BOOST_CHECK_CLOSE( q4(1), 0.0, tolerance );
  BOOST_CHECK_CLOSE( q5(1), 0.0, tolerance );
  BOOST_CHECK_CLOSE( q6(1), 0.0, tolerance );

  BOOST_CHECK( q1(0) > q0(0));
  BOOST_CHECK( q2(0) > q1(0));
  BOOST_CHECK( q3(0) > q2(0));
  BOOST_CHECK( q4(0) > q3(0));
  BOOST_CHECK( q5(0) > q4(0));
  BOOST_CHECK( q6(0) > q5(0));

  BOOST_CHECK_CLOSE( p6(0), q6(0), tolerance );
  BOOST_CHECK_CLOSE( p6(1), q6(1), tolerance );
}

BOOST_AUTO_TEST_CASE(test_bezier_curve_case)
{
  knot_container U;

  U.push_back(0.0);
  U.push_back(0.0);
  U.push_back(0.0);
  U.push_back(0.0);
  U.push_back(1.0);
  U.push_back(1.0);
  U.push_back(1.0);
  U.push_back(1.0);

  // k = 4
  // n = 3  => |P| = 4
  // m = 7  => |U| = 8

  point_container P;
  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;
  vector_type p1(2);  p1(0) = 1.0; p1(1) = 1.0;
  vector_type p2(2);  p2(0) = 2.0; p2(1) = 1.0;
  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;

  P.push_back(p0);
  P.push_back(p1);
  P.push_back(p2);
  P.push_back(p3);

  spline_type bezier(4,U,P);

  double const tolerance = 10e-15;

  // Now we have constructed the equivalent of a bezier curve
  //
  //   B(t) =     a t^3 +   b t^2 + c t + d
  //   B'(t) =  3 a t^2 + 2 b t   + c
  //
  //   B(0) = p0  = d
  //   B(1) = p3  = a + b + c + d
  //   B'(0) = 3*(p1-p0) = c
  //   B'(1) = 3*(p1-p0) = 3 a + 2 b + c
  //
  //  working out the equations one would get
  vector_type a = -1*p0 + 3*p1 - 3*p2 + 1*p3;
  vector_type b =  3*p0 - 6*p1 + 3*p2;
  vector_type c = -3*p0 + 3*p1;
  vector_type d =  1*p0;

  double u = 0.0;
  int const N = 11;
  double const du = 1.0 / (N-1);
  for(int i=0;i<N;++i)
  {
    vector_type p(2);
    OpenTissue::spline::compute_point_on_spline(u, bezier, p);
    vector_type q(2);
    q = (u*u*u)*a + (u*u)*b + u*c + d;
    BOOST_CHECK( std::fabs( p(0) - q(0) ) < tolerance );
    BOOST_CHECK( std::fabs( p(1) - q(1) ) < tolerance );
    u += du;
  }
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: ricortiz/OpenTissue

max_issues_repo_name: ricortiz/OpenTissue

max_forks_repo_name: ricortiz/OpenTissue


text:
//
// Copyright 2021 Autodesk
//
// 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 <mayaUsd/fileio/shading/shadingModeImporter.h>
#include <mayaUsd/fileio/shading/shadingModeRegistry.h>

#include <boost/python/class.hpp>
#include <boost/python/def.hpp>

PXR_NAMESPACE_USING_DIRECTIVE

class ShadingModeRegistry
{
public:
    static void RegisterImportConversion(
        const TfToken& materialConversion,
        const TfToken& renderContext,
        const TfToken& niceName,
        const TfToken& description)
    {
        UsdMayaShadingModeRegistry::GetInstance().RegisterImportConversion(
            materialConversion, renderContext, niceName, description);
    }

    static void RegisterExportConversion(
        const TfToken& materialConversion,
        const TfToken& renderContext,
        const TfToken& niceName,
        const TfToken& description)
    {
        UsdMayaShadingModeRegistry::GetInstance().RegisterExportConversion(
            materialConversion, renderContext, niceName, description);
    }
};

//----------------------------------------------------------------------------------------------------------------------
void wrapShadingModeImportContext()
{
    boost::python::class_<UsdMayaShadingModeImportContext>(
        "ShadingModeImportContext", boost::python::no_init)
        .def("GetCreatedObject", &UsdMayaShadingModeImportContext::GetCreatedObject)
        //        .def("AddCreatedObject",&UsdMayaShadingModeImportContext::AddCreatedObject) //
        //        overloads
        .def("CreateShadingEngine", &UsdMayaShadingModeImportContext::CreateShadingEngine)
        .def("GetShadingEngineName", &UsdMayaShadingModeImportContext::GetShadingEngineName)
        .def("GetSurfaceShaderPlugName", &UsdMayaShadingModeImportContext::GetSurfaceShaderPlugName)
        .def("GetVolumeShaderPlugName", &UsdMayaShadingModeImportContext::GetVolumeShaderPlugName)
        .def(
            "GetDisplacementShaderPlugName",
            &UsdMayaShadingModeImportContext::GetDisplacementShaderPlugName)
        .def("SetSurfaceShaderPlugName", &UsdMayaShadingModeImportContext::SetSurfaceShaderPlugName)
        .def("SetVolumeShaderPlugName", &UsdMayaShadingModeImportContext::SetVolumeShaderPlugName)
        .def(
            "SetDisplacementShaderPlugName",
            &UsdMayaShadingModeImportContext::SetDisplacementShaderPlugName)
        .def(
            "GetPrimReaderContext",
            &UsdMayaShadingModeImportContext::GetPrimReaderContext,
            boost::python::return_value_policy<boost::python::return_by_value>());
}

//----------------------------------------------------------------------------------------------------------------------
void wrapShadingMode()
{
    boost::python::class_<ShadingModeRegistry>("ShadingModeRegistry", boost::python::no_init)
        .def("RegisterImportConversion", &ShadingModeRegistry::RegisterImportConversion)
        .staticmethod("RegisterImportConversion")
        .def("RegisterExportConversion", &ShadingModeRegistry::RegisterExportConversion)
        .staticmethod("RegisterExportConversion");
}

max_stars_repo_name: sun-frog/maya-usd

max_issues_repo_name: sun-frog/maya-usd

max_forks_repo_name: sun-frog/maya-usd


text:
//
// blocking_udp_echo_client.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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 <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <thread>
#include <chrono>
#include <random>

using boost::asio::ip::udp;

enum { max_length = 200 };

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 5)
    {
      std::cerr << "Usage: blocking_udp_echo_client <host> <port> <latency_ms> <num_repetitions>\n";
      return 1;
    }

    boost::asio::io_service io_context;

    udp::socket s(io_context, udp::endpoint(udp::v4(), 0));

    udp::resolver resolver(io_context);
    udp::endpoint endpoint = *resolver.resolve({udp::v4(), argv[1], argv[2]});
    const int latency_ms = atoi(argv[3]);
    const int num_rep = atoi(argv[4]);

    std::random_device rd{};
    std::mt19937 gen{rd()};
    std::normal_distribution<> d{latency_ms,5};

    char request[max_length] = "Message from RPI";
    size_t request_length = max_length;
    for(int i = 0; i < num_rep; ++i){
      s.send_to(boost::asio::buffer(request, request_length), endpoint);
      const int val = d(gen);
      std::cout << "Val generated =  " << val << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(val));
    }
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

max_stars_repo_name: mirazabal/Dynamic-buffer-TMC

max_issues_repo_name: mirazabal/Dynamic-buffer-TMC

max_forks_repo_name: mirazabal/Dynamic-buffer-TMC


text: #include <boost/process/cmd.hpp>


text:
// March, 2019, brought this class from CTLM 1.0 code
// for compatibility

//#include "stdafx.h"
//#include "winacq.h"
#include "RawFans.h"
#include <boost/assert.hpp>
#include <stdlib.h>     /* calloc, exit, free */

const int  RawFans::ByteCount[] = { 1284 * 2, 1797 * 2, 3849 * 2, 6072 * 2 };
const int  RawFans::OversamplingFactor[] = { 1, 4, 16, 29 };
const int  RawFans::LogicalDwellSampleCount[] = { 171, 171, 171, 171, 171, 171, 256 };

#ifdef CAMERADWELLATEND

#pragma message("      NOTE:  Compiling for Camera integration at end of fan!")
#pragma message("             RawFans::StandardDwellAcqOrder[] = {0,1,2,3,4,5,6);")

const long RawFans::StandardDwellAcqOrder[] = { 0,1,2,3,4,5,6 };

#else
const long RawFans::StandardDwellAcqOrder[] = { 0,1,2,6,3,4,5 };
#endif

const int RawFans::nActiveDwells = 7;

typedef unsigned short BUFFERTYPE;

RawFans::RawFans()
{
	m_size = 0;
	m_bufferSize = 0;
	buffer = 0;
	for (int i = 0; i < sizeof(m_AdcSampleCount) / sizeof(m_AdcSampleCount[0]); ++i)
	{
		m_AdcSampleCount[i] = 1;
		m_AdcMultiplier[i] = 4.0;
		m_AdcScaling[i] = 0.25;		// Reconstruction scales fanlets by this factor
									// to achieve 14-bit ADC-equivelent signal magnitudes.
	}
}

RawFans::~RawFans()
{
	delete[] buffer;
}

void RawFans::SampleFactor(int oversamplingIndex, int fanCount)
{
	BOOST_ASSERT((oversamplingIndex >= 0) &&
		(oversamplingIndex < (sizeof(ByteCount) / sizeof(ByteCount[0]))));
	int newBufferSize = ByteCount[oversamplingIndex] / 2 * fanCount;
	if (newBufferSize > m_bufferSize) {	// The buffer only grows...
		delete[] buffer;
		buffer = new BUFFERTYPE[newBufferSize];
		m_bufferSize = newBufferSize;
	}
	m_size = ByteCount[oversamplingIndex] / sizeof(BUFFERTYPE);
	m_AdcSampleCount[5] = OversamplingFactor[oversamplingIndex];
	m_AdcMultiplier[5] = 4.0 / OversamplingFactor[oversamplingIndex];

	int offset = 2;	// Skip over the fan header.

	for (int physicalDwell = 0; physicalDwell < nActiveDwells; ++physicalDwell) {
		int logicalDwell = StandardDwellAcqOrder[physicalDwell];
		m_LogicalDwellToPhysicalOffset[logicalDwell] = offset;
		offset += LogicalDwellSampleCount[logicalDwell] * m_AdcSampleCount[logicalDwell];
	}
}

int RawFans::Size()
{
	return m_size;
}

#pragma optimize( "gt", on)

void RawFans::ConvertToLogicalFans(unsigned short *dest, int fanCount)
{
//#if 0
//#include "Util.h"
//#pragma message("     Included dump of raw fans to Dat/rawfans.data!")
//	DumpToFile("rawfans.data", (void *)buffer, fanCount * m_size * 2);
//#endif

	RawFans rawf;
	//rawf.SampleFactor(CWinacqApp::OversampleFactorIndex, 0); // Defer buffer allocation until number of fans in a chunk is known
	int RawFanSize = rawf.Size();				// But, we need the size now.

	int outi = 0;

	for (int fan = 0; fan < fanCount; ++fan)
	{

		int fani = m_size * fan;

		dest[outi++] = buffer[fani + 0];	// Copy the header
		dest[outi++] = buffer[fani + 1];

		for (int dwell = 0; dwell < nActiveDwells; ++dwell)
		{
			double multiplier = m_AdcMultiplier[dwell];
			int overSampleFactor = m_AdcSampleCount[dwell];
			int sampleCount = LogicalDwellSampleCount[dwell];
			int ini = fani + m_LogicalDwellToPhysicalOffset[dwell];

			if (overSampleFactor == 1)
			{

				for (; sampleCount--; )
				{
					dest[outi++] = (unsigned short)(buffer[ini++] * multiplier);
				}

			}
			else
			{
				register long acc;
				register BUFFERTYPE *in;

				for (; sampleCount--; )
				{

					acc = 0;
					in = buffer + ini;
					switch (overSampleFactor)
					{
					case 32:
						acc += *in++; acc += *in++;
						acc += *in++;
					case 29:
						acc += *in++;
						acc += *in++; acc += *in++;
						acc += *in++; acc += *in++;
						acc += *in++; acc += *in++;
						acc += *in++; acc += *in++;
						acc += *in++; acc += *in++;
						acc += *in++; acc += *in++;
					case 16:
						acc += *in++; acc += *in++;
						acc += *in++; acc += *in++;
						acc += *in++; acc += *in++;
						acc += *in++; acc += *in++;
					case 8:
						acc += *in++; acc += *in++;
						acc += *in++; acc += *in++;
					case 4:
						acc += *in++; acc += *in++;
					case 2:
						acc += *in++; acc += *in++;
						ini += overSampleFactor;
						break;
					default:
						for (int sample = overSampleFactor; sample--; )
						{
							acc += buffer[ini++];
						}
						break;
					}
					dest[outi++] = (unsigned short)(acc * multiplier);
				}
			}
		}
		//
		// Patch up the CCD cameras to minimize the effects of the off-by-one
		// error in RLCA079C. The first pixel of the 1st camera is missing. The
		// sample which is supposed to be the last pixel of the first camera contains
		// the first sample of the second camera, and the sample which is supposed to
		// contain the last pixel of the second camera contains a unidentified value.
		// Here, we just eliminate the inter-camera crosstalk and the discontinuity
		// at the end, and let reconstruction's calibration take care of the 1-pixel
		// shift.
		//
		dest[outi - 1] = dest[outi - 2];  // Eliminate discontinuity.
		dest[outi - 129] = dest[outi - 130]; // Eliminate inter-camera crosstalk
	}
}

Chunk::Chunk(int wordCount)
{
	buf = (unsigned short *)calloc(wordCount, sizeof(unsigned short));
	BOOST_ASSERT(buf);
}

Chunk::~Chunk()
{
	if (buf) free(buf);
}