<commit_before>// Copyright (c) 2013, Cloudera, inc.

#include <boost/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <tr1/memory>

#include "blocking_queue.h"

using std::tr1::shared_ptr;

namespace kudu {

BlockingQueue<int32_t> test1_queue(5);

void InsertSomeThings(void) {
  ASSERT_TRUE(test1_queue.Put(1));
  ASSERT_TRUE(test1_queue.Put(2));
  ASSERT_TRUE(test1_queue.Put(3));
}

TEST(BlockingQueueTest, Test1) {
  boost::thread inserter_thread(InsertSomeThings);
  int32_t i;
  ASSERT_TRUE(test1_queue.BlockingGet(&i));
  ASSERT_EQ(1, i);
  ASSERT_TRUE(test1_queue.BlockingGet(&i));
  ASSERT_EQ(2, i);
  ASSERT_TRUE(test1_queue.BlockingGet(&i));
  ASSERT_EQ(3, i);
}

TEST(BlockingQueueTest, TestTooManyInsertions) {
  BlockingQueue<int32_t> test_queue(2);
  ASSERT_TRUE(test_queue.Put(123));
  ASSERT_TRUE(test_queue.Put(123));
  ASSERT_FALSE(test_queue.Put(123));
}

TEST(BlockingQueueTest, TestGetFromShutdownQueue) {
  BlockingQueue<int64_t> test_queue(2);
  ASSERT_TRUE(test_queue.Put(123));
  test_queue.Shutdown();
  ASSERT_FALSE(test_queue.Put(456));
  int64_t i;
  ASSERT_TRUE(test_queue.BlockingGet(&i));
  ASSERT_EQ(123, i);
  ASSERT_FALSE(test_queue.BlockingGet(&i));
}

TEST(BlockingQueueTest, TestGscopedPtrMethods) {
  BlockingQueue<int*> test_queue(2);
  gscoped_ptr<int> input_int(new int(123));
  ASSERT_TRUE(test_queue.Put(&input_int));
  gscoped_ptr<int> output_int;
  ASSERT_TRUE(test_queue.BlockingGet(&output_int));
  ASSERT_EQ(123, *output_int.get());
  test_queue.Shutdown();
}

class MultiThreadTest {
public:
  typedef std::vector<std::tr1::shared_ptr<boost::thread> > thread_vec_t;

  MultiThreadTest()
    : iterations_(4),
      nthreads_(5),
      queue_(iterations_),
      num_inserters_(nthreads_)
  {
  }

  void InserterThread(int arg) {
    for (int i = 0; i < iterations_; i++) {
      ASSERT_TRUE(queue_.Put(arg));
    }
    boost::lock_guard<boost::mutex> guard(lock_);
    if (--num_inserters_ == 0) {
      queue_.Shutdown();
    }
  }

  void RemoverThread() {
    for (int i = 0; i < iterations_; i++) {
      int32_t arg;
      bool got = queue_.BlockingGet(&arg);
      if (!got) {
        arg = -1;
      }
      boost::lock_guard<boost::mutex> guard(lock_);
      gotten_[arg] = gotten_[arg] + 1;
    }
  }

  void Run() {
    for (int i = 0; i < nthreads_; i++) {
      threads_.push_back(shared_ptr<boost::thread>(
              new boost::thread(boost::bind(
                &MultiThreadTest::InserterThread, this, i))));
      threads_.push_back(shared_ptr<boost::thread>(
              new boost::thread(boost::bind(
                &MultiThreadTest::RemoverThread, this))));
    }
    // We add an extra thread to ensure that there aren't enough elements in
    // the queue to go around.  This way, we test removal after Shutdown.
    threads_.push_back(shared_ptr<boost::thread>(
            new boost::thread(boost::bind(
              &MultiThreadTest::RemoverThread, this))));
    for (int i = 0; i < nthreads_; i++) {
      threads_[i]->join();
    }
    // Let's check to make sure we got what we should have.
    boost::lock_guard<boost::mutex> guard(lock_);
    for (int i = 0; i < nthreads_; i++) {
      ASSERT_EQ(iterations_, gotten_[i]);
    }
    // And there were nthreads_ * (iterations_ + 1)  elements removed, but only
    // nthreads_ * iterations_ elements added.  So some removers hit the shutdown
    // case.
    ASSERT_EQ(iterations_, gotten_[-1]);
  }

  int iterations_;
  int nthreads_;
  BlockingQueue<int32_t> queue_;
  boost::mutex lock_;
  std::map<int32_t, int> gotten_;
  thread_vec_t threads_;
  int num_inserters_;
};

TEST(BlockingQueueTest, TestMultipleThreads) {
  MultiThreadTest test;
  test.Run();
}

}  // namespace kudu
<commit_msg>Fix build failure on clang with boost 1.41<commit_after>// Copyright (c) 2013, Cloudera, inc.

#include <boost/thread/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <tr1/memory>

#include "blocking_queue.h"

using std::tr1::shared_ptr;

namespace kudu {

BlockingQueue<int32_t> test1_queue(5);

void InsertSomeThings(void) {
  ASSERT_TRUE(test1_queue.Put(1));
  ASSERT_TRUE(test1_queue.Put(2));
  ASSERT_TRUE(test1_queue.Put(3));
}

TEST(BlockingQueueTest, Test1) {
  boost::thread inserter_thread(InsertSomeThings);
  int32_t i;
  ASSERT_TRUE(test1_queue.BlockingGet(&i));
  ASSERT_EQ(1, i);
  ASSERT_TRUE(test1_queue.BlockingGet(&i));
  ASSERT_EQ(2, i);
  ASSERT_TRUE(test1_queue.BlockingGet(&i));
  ASSERT_EQ(3, i);
}

TEST(BlockingQueueTest, TestTooManyInsertions) {
  BlockingQueue<int32_t> test_queue(2);
  ASSERT_TRUE(test_queue.Put(123));
  ASSERT_TRUE(test_queue.Put(123));
  ASSERT_FALSE(test_queue.Put(123));
}

TEST(BlockingQueueTest, TestGetFromShutdownQueue) {
  BlockingQueue<int64_t> test_queue(2);
  ASSERT_TRUE(test_queue.Put(123));
  test_queue.Shutdown();
  ASSERT_FALSE(test_queue.Put(456));
  int64_t i;
  ASSERT_TRUE(test_queue.BlockingGet(&i));
  ASSERT_EQ(123, i);
  ASSERT_FALSE(test_queue.BlockingGet(&i));
}

TEST(BlockingQueueTest, TestGscopedPtrMethods) {
  BlockingQueue<int*> test_queue(2);
  gscoped_ptr<int> input_int(new int(123));
  ASSERT_TRUE(test_queue.Put(&input_int));
  gscoped_ptr<int> output_int;
  ASSERT_TRUE(test_queue.BlockingGet(&output_int));
  ASSERT_EQ(123, *output_int.get());
  test_queue.Shutdown();
}

class MultiThreadTest {
public:
  typedef std::vector<std::tr1::shared_ptr<boost::thread> > thread_vec_t;

  MultiThreadTest()
    : iterations_(4),
      nthreads_(5),
      queue_(iterations_),
      num_inserters_(nthreads_)
  {
  }

  void InserterThread(int arg) {
    for (int i = 0; i < iterations_; i++) {
      ASSERT_TRUE(queue_.Put(arg));
    }
    boost::lock_guard<boost::mutex> guard(lock_);
    if (--num_inserters_ == 0) {
      queue_.Shutdown();
    }
  }

  void RemoverThread() {
    for (int i = 0; i < iterations_; i++) {
      int32_t arg;
      bool got = queue_.BlockingGet(&arg);
      if (!got) {
        arg = -1;
      }
      boost::lock_guard<boost::mutex> guard(lock_);
      gotten_[arg] = gotten_[arg] + 1;
    }
  }

  void Run() {
    for (int i = 0; i < nthreads_; i++) {
      threads_.push_back(shared_ptr<boost::thread>(
              new boost::thread(boost::bind(
                &MultiThreadTest::InserterThread, this, i))));
      threads_.push_back(shared_ptr<boost::thread>(
              new boost::thread(boost::bind(
                &MultiThreadTest::RemoverThread, this))));
    }
    // We add an extra thread to ensure that there aren't enough elements in
    // the queue to go around.  This way, we test removal after Shutdown.
    threads_.push_back(shared_ptr<boost::thread>(
            new boost::thread(boost::bind(
              &MultiThreadTest::RemoverThread, this))));
    for (int i = 0; i < nthreads_; i++) {
      threads_[i]->join();
    }
    // Let's check to make sure we got what we should have.
    boost::lock_guard<boost::mutex> guard(lock_);
    for (int i = 0; i < nthreads_; i++) {
      ASSERT_EQ(iterations_, gotten_[i]);
    }
    // And there were nthreads_ * (iterations_ + 1)  elements removed, but only
    // nthreads_ * iterations_ elements added.  So some removers hit the shutdown
    // case.
    ASSERT_EQ(iterations_, gotten_[-1]);
  }

  int iterations_;
  int nthreads_;
  BlockingQueue<int32_t> queue_;
  boost::mutex lock_;
  std::map<int32_t, int> gotten_;
  thread_vec_t threads_;
  int num_inserters_;
};

TEST(BlockingQueueTest, TestMultipleThreads) {
  MultiThreadTest test;
  test.Run();
}

}  // namespace kudu
<|endoftext|>


<commit_before>/** \copyright
 * Copyright (c) 2015, Balazs Racz
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are  permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * \file JSWebsocketclient.hxx
 *
 * A node.js compatible server component that exports a TCP listening server
 * with a GridConnect hub.
 *
 * @author Balazs Racz
 * @date 13 Sep 2015
 */

#ifndef _UTILS_JSWEBSOCKETCLIENT_HXX_
#define _UTILS_JSWEBSOCKETCLIENT_HXX_

#ifdef __EMSCRIPTEN__

#include <emscripten.h>
#include <emscripten/val.h>

#include "utils/Hub.hxx"
#include "utils/JSHubPort.hxx"

class JSWebsocketClient
{
public:
    JSWebsocketClient(CanHubFlow* hflow, string server_js)
        : canHub_(hflow) {
        string script = "Module.ws_server = " + server_js + ";\n";
        emscripten_run_script(script.c_str());
        EM_ASM_(
            {
                try {
                    var WS = window.WebSocket || window.MozWebSocket;
                } catch (err) {
                    var WS = require('websocket').w3cwebsocket;
                }
                /*var is_node = window ? false : true;
                if (!is_node) {
                    console.log('using browser');
                } else {
                    console.log('using nodejs');
                    }*/
                console.log('connecting to ws server: ', Module.ws_server);
                var connection = new WS(Module.ws_server);
                var client_port = new Module.JSHubPort($0,
                            function(gc_text)
                            {
                                var json = JSON.stringify(
                                    {type : 'gc_can_frame', data : gc_text});
                                if (connection.readyState == 1) {
                                    connection.send(json);
                                } else {
                                    console.log('Not sending frame ', gc_text,
                                                ' because connection state = ',
                                                connection.readyState);
                                }
                            });
                connection.onopen = function() {
                    console.log('ws connection established. starting stack.');
                    try {
                        Module.startStack();
                    } catch (e) {
                        if (e === 'SimulateInfiniteLoop') {
                            console.log('stack started.');
                        } else {
                            console.log('unknown exception ', e);
                            throw e;
                        }
                    }
                };
                connection.onerror = function (eee) {
                    console.log('Connection error: ', eee);
                };
                connection.onmessage = function(message) {
                    try
                    {
                        var json = JSON.parse(message.data);
                    }
                    catch (e)
                    {
                        console.log(
                            'This doesn\'t look like a valid JSON: ',
                            message.data);
                        return;
                    }
                    if (json.type === 'gc_can_frame')
                    {
                        // Send can frame data to the hub port
                        client_port.recv(json.data);
                    } else {
                        console.log('Received data of unknown type: ',
                                    json.type);
                    }
                };
            }, (unsigned long)canHub_);
    }

private:
    CanHubFlow *canHub_;
};

#endif // __EMSCRIPTEN__
#endif // _UTILS_JSWEBSOCKETCLIENT_HXX_
<commit_msg>Implement reconnecting support in the websocket client.<commit_after>/** \copyright
 * Copyright (c) 2015, Balazs Racz
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are  permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * \file JSWebsocketclient.hxx
 *
 * A node.js compatible server component that exports a TCP listening server
 * with a GridConnect hub.
 *
 * @author Balazs Racz
 * @date 13 Sep 2015
 */

#ifndef _UTILS_JSWEBSOCKETCLIENT_HXX_
#define _UTILS_JSWEBSOCKETCLIENT_HXX_

#ifdef __EMSCRIPTEN__

#include <emscripten.h>
#include <emscripten/val.h>

#include "utils/Hub.hxx"
#include "utils/JSHubPort.hxx"

class JSWebsocketClient
{
public:
    JSWebsocketClient(CanHubFlow* hflow, string server_js)
        : canHub_(hflow) {
        string script = "Module.ws_server = " + server_js + ";\n";
        emscripten_run_script(script.c_str());
        EM_ASM_(
            {
                var server_address = Module.ws_server;
                try {
                    var WS = window.WebSocket || window.MozWebSocket;
                } catch (err) {
                    var WS = require('websocket').w3cwebsocket;
                }
                /*var is_node = window ? false : true;
                if (!is_node) {
                    console.log('using browser');
                } else {
                    console.log('using nodejs');
                    }*/
                var reconnect;
                reconnect = function() {
                console.log('NNNN connecting to ws server: ', server_address);
                var connection = new WS(server_address);
                var portnum;
                var client_port = new Module.JSHubPort($0,
                            function(gc_text)
                            {
                                var json = JSON.stringify(
                                    {type : 'gc_can_frame', data : gc_text});
                                if (connection.readyState == 1) {
                                    connection.send(json);
                                } else {
                                    console.log('Not sending frame ', gc_text,
                                                ' because connection',portnum,'state = ',
                                                connection.readyState);
                                }
                            });
                portnum = client_port.get_port_num();
                connection.onopen = function() {
                    console.log('ws connection',portnum,'established. starting stack.');
                    try {
                        Module.startStack();
                    } catch (e) {
                        if (e === 'SimulateInfiniteLoop') {
                            console.log('stack started.');
                        } else {
                            console.log('unknown exception ', e);
                            throw e;
                        }
                    }
                };
                connection.onerror = function (eee) {
                    console.log('Connection',portnum,'error: ', eee);
                    //client_port.abandon();
                    //connection.close();
                    //setTimeout(reconnect, 1000);
                };
                connection.onclose = function () {
                    console.log('Websocket',portnum,'closed.');
                    client_port.abandon();
                    connection.close();
                    delete connection;
                    console.log('Scheduling reconnect.');
                    setTimeout(reconnect, 1000);
                };
                connection.onmessage = function(message) {
                    try
                    {
                        var json = JSON.parse(message.data);
                    }
                    catch (e)
                    {
                        console.log(
                            'This doesn\'t look like a valid JSON: ',
                            message.data);
                        return;
                    }
                    if (json.type === 'gc_can_frame')
                    {
                        // Send can frame data to the hub port
                        client_port.recv(json.data);
                    } else {
                        console.log('Received data of unknown type: ',
                                    json.type);
                    }
                };
                };
                reconnect();
            }, (unsigned long)canHub_);
    }

private:
    CanHubFlow *canHub_;
};

#endif // __EMSCRIPTEN__
#endif // _UTILS_JSWEBSOCKETCLIENT_HXX_
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Intel(r) 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.
 *
 */
#ifndef VMF_COMPRESSOR_HPP
#define VMF_COMPRESSOR_HPP

/*!
* \file compressor.hpp
* \brief %Compressor header file
*/

#include <map>
#include "vmf/metadataschema.hpp"

namespace vmf
{

/*! \class Compressor
 * \brief Interface for all compression algorithms
 */
class VMF_EXPORT Compressor
{
public:
    /*!
     * \brief Compresses data
     * \param [in] input input text data
     * \param [out] output where to put binary compressed data
     */
    virtual void compress(const vmf_string& input, vmf_rawbuffer& output) = 0;

    /*!
     * \brief Decompresses data
     * \param [in] input binary compressed input data
     * \param [out] output where to put decompressed text data
     */
    virtual void decompress(const vmf_rawbuffer& input, vmf_string& output) = 0;

    /*!
     * \brief Creates a new instance of the compressor
     * \return Smart pointer to Compressor instance
     */
    virtual std::shared_ptr<Compressor> createNewInstance() const = 0;

    /*!
     * \brief Gets the ID of current algorithm
     */
    virtual vmf_string getId() = 0;

    /*!
     * \brief Default destructor
     */
    virtual ~Compressor() { }

    /*!
     * \brief Registers new algorithm before its use in decompression.
     * \param compressor Pointer to the implementation of the algorithm
     * \throw IncorrectParamException is thrown for a compressor with already registered ID
     */
    static void registerNew(std::shared_ptr<Compressor> compressor);

    /*!
     * \brief Unregisters previously registered compression algorithm
     * \param id String ID of the compression algorithm
     * \throw IncorrectParamException is thrown for unknown (not built-in and not-registered) IDs
     */
    static void unregister(const vmf_string& id);

    /*!
     * \brief Creates new instance of previously registered compressor identified by ID
     * \param id String identifying compression algorithm
     * \return Smart pointer to Compressor instance
     * \throw IncorrectParamException is thrown for unknown (not built-in and not-registered) IDs
     */
    static std::shared_ptr<Compressor> create(const vmf_string& id);

    /*!
     * \brief Returns a list of currently registered compressors,
     * both built-in ones or user-defined
     * \return A list of registered compressors IDs
     */
    static std::vector<vmf_string> getRegisteredIds();
};

} /* vmf */

#endif /* VMF_COMPRESSOR_HPP */
<commit_msg>typo fixed<commit_after>/*
 * Copyright 2015 Intel(r) 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.
 *
 */
#ifndef VMF_COMPRESSOR_HPP
#define VMF_COMPRESSOR_HPP

/*!
* \file compressor.hpp
* \brief %Compressor header file
*/

#include <map>
#include "vmf/metadataschema.hpp"

namespace vmf
{

/*! \class Compressor
 * \brief Interface for all compression algorithms
 */
class VMF_EXPORT Compressor
{
public:
    /*!
     * \brief Compresses data
     * \param [in] input input text data
     * \param [out] output where to put binary compressed data
     */
    virtual void compress(const vmf_string& input, vmf_rawbuffer& output) = 0;

    /*!
     * \brief Decompresses data
     * \param [in] input binary compressed input data
     * \param [out] output where to put decompressed text data
     */
    virtual void decompress(const vmf_rawbuffer& input, vmf_string& output) = 0;

    /*!
     * \brief Creates a new instance of the compressor
     * \return Smart pointer to Compressor instance
     */
    virtual std::shared_ptr<Compressor> createNewInstance() const = 0;

    /*!
     * \brief Gets the ID of current algorithm
     */
    virtual vmf_string getId() = 0;

    /*!
     * \brief Default destructor
     */
    virtual ~Compressor() { }

    /*!
     * \brief Registers new algorithm before its use in decompression.
     * \param compressor Pointer to the implementation of the algorithm
     * \throw IncorrectParamException is thrown for a compressor with already registered ID
     */
    static void registerNew(std::shared_ptr<Compressor> compressor);

    /*!
     * \brief Unregisters previously registered compression algorithm
     * \param id String ID of the compression algorithm
     * \throw IncorrectParamException is thrown for unknown or built-in IDs
     */
    static void unregister(const vmf_string& id);

    /*!
     * \brief Creates new instance of previously registered compressor identified by ID
     * \param id String identifying compression algorithm
     * \return Smart pointer to Compressor instance
     * \throw IncorrectParamException is thrown for unknown (not built-in and not-registered) IDs
     */
    static std::shared_ptr<Compressor> create(const vmf_string& id);

    /*!
     * \brief Returns a list of currently registered compressors,
     * both built-in ones or user-defined
     * \return A list of registered compressors IDs
     */
    static std::vector<vmf_string> getRegisteredIds();
};

} /* vmf */

#endif /* VMF_COMPRESSOR_HPP */
<|endoftext|>


<commit_before>//===-- Function.cpp - Implement the Global object classes ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Function class for the VMCore library.
//
//===----------------------------------------------------------------------===//

#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/ParameterAttributes.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/Support/LeakDetector.h"
#include "llvm/Support/StringPool.h"
#include "SymbolTableListTraitsImpl.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;

BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
  BasicBlock *Ret = new BasicBlock();
  // This should not be garbage monitored.
  LeakDetector::removeGarbageObject(Ret);
  return Ret;
}

iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
  return F->getBasicBlockList();
}

Argument *ilist_traits<Argument>::createSentinel() {
  Argument *Ret = new Argument(Type::Int32Ty);
  // This should not be garbage monitored.
  LeakDetector::removeGarbageObject(Ret);
  return Ret;
}

iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
  return F->getArgumentList();
}

// Explicit instantiations of SymbolTableListTraits since some of the methods
// are not in the public header file...
template class SymbolTableListTraits<Argument, Function>;
template class SymbolTableListTraits<BasicBlock, Function>;

//===----------------------------------------------------------------------===//
// Argument Implementation
//===----------------------------------------------------------------------===//

Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
  : Value(Ty, Value::ArgumentVal) {
  Parent = 0;

  // Make sure that we get added to a function
  LeakDetector::addGarbageObject(this);

  if (Par)
    Par->getArgumentList().push_back(this);
  setName(Name);
}

void Argument::setParent(Function *parent) {
  if (getParent())
    LeakDetector::addGarbageObject(this);
  Parent = parent;
  if (getParent())
    LeakDetector::removeGarbageObject(this);
}

/// getArgNo - Return the index of this formal argument in its containing
/// function.  For example in "void foo(int a, float b)" a is 0 and b is 1.
unsigned Argument::getArgNo() const {
  const Function *F = getParent();
  assert(F && "Argument is not in a function");

  Function::const_arg_iterator AI = F->arg_begin();
  unsigned ArgIdx = 0;
  for (; &*AI != this; ++AI)
    ++ArgIdx;

  return ArgIdx;
}

/// hasByValAttr - Return true if this argument has the byval attribute on it
/// in its containing function.
bool Argument::hasByValAttr() const {
  if (!isa<PointerType>(getType())) return false;
  return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::ByVal);
}

/// hasNoAliasAttr - Return true if this argument has the noalias attribute on
/// it in its containing function.
bool Argument::hasNoAliasAttr() const {
  if (!isa<PointerType>(getType())) return false;
  return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::NoAlias);
}

/// hasSRetAttr - Return true if this argument has the sret attribute on
/// it in its containing function.
bool Argument::hasStructRetAttr() const {
  if (!isa<PointerType>(getType())) return false;
  return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::StructRet);
}

//===----------------------------------------------------------------------===//
// Helper Methods in Function
//===----------------------------------------------------------------------===//

const FunctionType *Function::getFunctionType() const {
  return cast<FunctionType>(getType()->getElementType());
}

bool Function::isVarArg() const {
  return getFunctionType()->isVarArg();
}

const Type *Function::getReturnType() const {
  return getFunctionType()->getReturnType();
}

void Function::removeFromParent() {
  getParent()->getFunctionList().remove(this);
}

void Function::eraseFromParent() {
  getParent()->getFunctionList().erase(this);
}

/// @brief Determine whether the function has the given attribute.
bool Function::paramHasAttr(uint16_t i, unsigned attr) const {
  return ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr);
}

/// @brief Determine if the function cannot return.
bool Function::doesNotReturn() const {
  return paramHasAttr(0, ParamAttr::NoReturn);
}

/// @brief Determine if the function cannot unwind.
bool Function::doesNotThrow() const {
  return paramHasAttr(0, ParamAttr::NoUnwind);
}

/// @brief Determine if the function does not access memory.
bool Function::doesNotAccessMemory() const {
  return paramHasAttr(0, ParamAttr::ReadNone);
}

/// @brief Determine if the function does not access or only reads memory.
bool Function::onlyReadsMemory() const {
  return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
}

/// @brief Determine if the function returns a structure.
bool Function::isStructReturn() const {
  return paramHasAttr(1, ParamAttr::StructRet);
}

//===----------------------------------------------------------------------===//
// Function Implementation
//===----------------------------------------------------------------------===//

Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
                   const std::string &name, Module *ParentModule)
  : GlobalValue(PointerType::getUnqual(Ty),
                Value::FunctionVal, 0, 0, Linkage, name),
    ParamAttrs(0) {
  SymTab = new ValueSymbolTable();

  assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
         && "LLVM functions cannot return aggregate values!");

  // If the function has arguments, mark them as lazily built.
  if (Ty->getNumParams())
    SubclassData = 1;   // Set the "has lazy arguments" bit.

  // Make sure that we get added to a function
  LeakDetector::addGarbageObject(this);

  if (ParentModule)
    ParentModule->getFunctionList().push_back(this);
}

Function::~Function() {
  dropAllReferences();    // After this it is safe to delete instructions.

  // Delete all of the method arguments and unlink from symbol table...
  ArgumentList.clear();
  delete SymTab;

  // Drop our reference to the parameter attributes, if any.
  if (ParamAttrs)
    ParamAttrs->dropRef();

  // Remove the function from the on-the-side collector table.
  clearCollector();
}

void Function::BuildLazyArguments() const {
  // Create the arguments vector, all arguments start out unnamed.
  const FunctionType *FT = getFunctionType();
  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
    assert(FT->getParamType(i) != Type::VoidTy &&
           "Cannot have void typed arguments!");
    ArgumentList.push_back(new Argument(FT->getParamType(i)));
  }

  // Clear the lazy arguments bit.
  const_cast<Function*>(this)->SubclassData &= ~1;
}

size_t Function::arg_size() const {
  return getFunctionType()->getNumParams();
}
bool Function::arg_empty() const {
  return getFunctionType()->getNumParams() == 0;
}

void Function::setParent(Module *parent) {
  if (getParent())
    LeakDetector::addGarbageObject(this);
  Parent = parent;
  if (getParent())
    LeakDetector::removeGarbageObject(this);
}

void Function::setParamAttrs(const ParamAttrsList *attrs) {
  // Avoid deleting the ParamAttrsList if they are setting the
  // attributes to the same list.
  if (ParamAttrs == attrs)
    return;

  // Drop reference on the old ParamAttrsList
  if (ParamAttrs)
    ParamAttrs->dropRef();

  // Add reference to the new ParamAttrsList
  if (attrs)
    attrs->addRef();

  // Set the new ParamAttrsList.
  ParamAttrs = attrs;
}

// dropAllReferences() - This function causes all the subinstructions to "let
// go" of all references that they are maintaining.  This allows one to
// 'delete' a whole class at a time, even though there may be circular
// references... first all references are dropped, and all use counts go to
// zero.  Then everything is deleted for real.  Note that no operations are
// valid on an object that has "dropped all references", except operator
// delete.
//
void Function::dropAllReferences() {
  for (iterator I = begin(), E = end(); I != E; ++I)
    I->dropAllReferences();
  BasicBlocks.clear();    // Delete all basic blocks...
}

// Maintain the collector name for each function in an on-the-side table. This
// saves allocating an additional word in Function for programs which do not use
// GC (i.e., most programs) at the cost of increased overhead for clients which
// do use GC.
static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
static StringPool *CollectorNamePool;

bool Function::hasCollector() const {
  return CollectorNames && CollectorNames->count(this);
}

const char *Function::getCollector() const {
  assert(hasCollector() && "Function has no collector");
  return *(*CollectorNames)[this];
}

void Function::setCollector(const char *Str) {
  if (!CollectorNamePool)
    CollectorNamePool = new StringPool();
  if (!CollectorNames)
    CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
  (*CollectorNames)[this] = CollectorNamePool->intern(Str);
}

void Function::clearCollector() {
  if (CollectorNames) {
    CollectorNames->erase(this);
    if (CollectorNames->empty()) {
      delete CollectorNames;
      CollectorNames = 0;
      if (CollectorNamePool->empty()) {
        delete CollectorNamePool;
        CollectorNamePool = 0;
      }
    }
  }
}

/// getIntrinsicID - This method returns the ID number of the specified
/// function, or Intrinsic::not_intrinsic if the function is not an
/// intrinsic, or if the pointer is null.  This value is always defined to be
/// zero to allow easy checking for whether a function is intrinsic or not.  The
/// particular intrinsic functions which correspond to this value are defined in
/// llvm/Intrinsics.h.
///
unsigned Function::getIntrinsicID(bool noAssert) const {
  const ValueName *ValName = this->getValueName();
  if (!ValName)
    return 0;
  unsigned Len = ValName->getKeyLength();
  const char *Name = ValName->getKeyData();

  if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
      || Name[2] != 'v' || Name[3] != 'm')
    return 0;  // All intrinsics start with 'llvm.'

  assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");

#define GET_FUNCTION_RECOGNIZER
#include "llvm/Intrinsics.gen"
#undef GET_FUNCTION_RECOGNIZER
  assert(noAssert && "Invalid LLVM intrinsic name");
  return 0;
}

std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
  assert(id < num_intrinsics && "Invalid intrinsic ID!");
  const char * const Table[] = {
    "not_intrinsic",
#define GET_INTRINSIC_NAME_TABLE
#include "llvm/Intrinsics.gen"
#undef GET_INTRINSIC_NAME_TABLE
  };
  if (numTys == 0)
    return Table[id];
  std::string Result(Table[id]);
  for (unsigned i = 0; i < numTys; ++i)
    if (Tys[i])
      Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
  return Result;
}

const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
                                       unsigned numTys) {
  const Type *ResultTy = NULL;
  std::vector<const Type*> ArgTys;
  bool IsVarArg = false;

#define GET_INTRINSIC_GENERATOR
#include "llvm/Intrinsics.gen"
#undef GET_INTRINSIC_GENERATOR

  return FunctionType::get(ResultTy, ArgTys, IsVarArg);
}

const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
  ParamAttrsVector Attrs;
  uint16_t Attr = ParamAttr::None;

#define GET_INTRINSIC_ATTRIBUTES
#include "llvm/Intrinsics.gen"
#undef GET_INTRINSIC_ATTRIBUTES

  // Intrinsics cannot throw exceptions.
  Attr |= ParamAttr::NoUnwind;

  Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
  return ParamAttrsList::get(Attrs);
}

Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
                                    unsigned numTys) {
  // There can never be multiple globals with the same name of different types,
  // because intrinsics must be a specific type.
  Function *F =
    cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
                                          getType(id, Tys, numTys)));
  F->setParamAttrs(getParamAttrs(id));
  return F;
}

Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
    if (CE->getOpcode() == Instruction::BitCast) {
      if (isa<PointerType>(CE->getOperand(0)->getType()))
        return StripPointerCasts(CE->getOperand(0));
    } else if (CE->getOpcode() == Instruction::GetElementPtr) {
      for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
        if (!CE->getOperand(i)->isNullValue())
          return Ptr;
      return StripPointerCasts(CE->getOperand(0));
    }
    return Ptr;
  }

  if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
    if (isa<PointerType>(CI->getOperand(0)->getType()))
      return StripPointerCasts(CI->getOperand(0));
  } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
    if (GEP->hasAllZeroIndices())
      return StripPointerCasts(GEP->getOperand(0));
  }
  return Ptr;
}

// vim: sw=2 ai
<commit_msg>Duncan pointed out that we can fast fail here, because the sret parameter of a function must be the first parameter.<commit_after>//===-- Function.cpp - Implement the Global object classes ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Function class for the VMCore library.
//
//===----------------------------------------------------------------------===//

#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/ParameterAttributes.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/Support/LeakDetector.h"
#include "llvm/Support/StringPool.h"
#include "SymbolTableListTraitsImpl.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;

BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
  BasicBlock *Ret = new BasicBlock();
  // This should not be garbage monitored.
  LeakDetector::removeGarbageObject(Ret);
  return Ret;
}

iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
  return F->getBasicBlockList();
}

Argument *ilist_traits<Argument>::createSentinel() {
  Argument *Ret = new Argument(Type::Int32Ty);
  // This should not be garbage monitored.
  LeakDetector::removeGarbageObject(Ret);
  return Ret;
}

iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
  return F->getArgumentList();
}

// Explicit instantiations of SymbolTableListTraits since some of the methods
// are not in the public header file...
template class SymbolTableListTraits<Argument, Function>;
template class SymbolTableListTraits<BasicBlock, Function>;

//===----------------------------------------------------------------------===//
// Argument Implementation
//===----------------------------------------------------------------------===//

Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
  : Value(Ty, Value::ArgumentVal) {
  Parent = 0;

  // Make sure that we get added to a function
  LeakDetector::addGarbageObject(this);

  if (Par)
    Par->getArgumentList().push_back(this);
  setName(Name);
}

void Argument::setParent(Function *parent) {
  if (getParent())
    LeakDetector::addGarbageObject(this);
  Parent = parent;
  if (getParent())
    LeakDetector::removeGarbageObject(this);
}

/// getArgNo - Return the index of this formal argument in its containing
/// function.  For example in "void foo(int a, float b)" a is 0 and b is 1.
unsigned Argument::getArgNo() const {
  const Function *F = getParent();
  assert(F && "Argument is not in a function");

  Function::const_arg_iterator AI = F->arg_begin();
  unsigned ArgIdx = 0;
  for (; &*AI != this; ++AI)
    ++ArgIdx;

  return ArgIdx;
}

/// hasByValAttr - Return true if this argument has the byval attribute on it
/// in its containing function.
bool Argument::hasByValAttr() const {
  if (!isa<PointerType>(getType())) return false;
  return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::ByVal);
}

/// hasNoAliasAttr - Return true if this argument has the noalias attribute on
/// it in its containing function.
bool Argument::hasNoAliasAttr() const {
  if (!isa<PointerType>(getType())) return false;
  return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::NoAlias);
}

/// hasSRetAttr - Return true if this argument has the sret attribute on
/// it in its containing function.
bool Argument::hasStructRetAttr() const {
  if (!isa<PointerType>(getType())) return false;
  if (getArgNo()) return false; // StructRet param must be first param
  return getParent()->paramHasAttr(1, ParamAttr::StructRet);
}

//===----------------------------------------------------------------------===//
// Helper Methods in Function
//===----------------------------------------------------------------------===//

const FunctionType *Function::getFunctionType() const {
  return cast<FunctionType>(getType()->getElementType());
}

bool Function::isVarArg() const {
  return getFunctionType()->isVarArg();
}

const Type *Function::getReturnType() const {
  return getFunctionType()->getReturnType();
}

void Function::removeFromParent() {
  getParent()->getFunctionList().remove(this);
}

void Function::eraseFromParent() {
  getParent()->getFunctionList().erase(this);
}

/// @brief Determine whether the function has the given attribute.
bool Function::paramHasAttr(uint16_t i, unsigned attr) const {
  return ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr);
}

/// @brief Determine if the function cannot return.
bool Function::doesNotReturn() const {
  return paramHasAttr(0, ParamAttr::NoReturn);
}

/// @brief Determine if the function cannot unwind.
bool Function::doesNotThrow() const {
  return paramHasAttr(0, ParamAttr::NoUnwind);
}

/// @brief Determine if the function does not access memory.
bool Function::doesNotAccessMemory() const {
  return paramHasAttr(0, ParamAttr::ReadNone);
}

/// @brief Determine if the function does not access or only reads memory.
bool Function::onlyReadsMemory() const {
  return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
}

/// @brief Determine if the function returns a structure.
bool Function::isStructReturn() const {
  return paramHasAttr(1, ParamAttr::StructRet);
}

//===----------------------------------------------------------------------===//
// Function Implementation
//===----------------------------------------------------------------------===//

Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
                   const std::string &name, Module *ParentModule)
  : GlobalValue(PointerType::getUnqual(Ty),
                Value::FunctionVal, 0, 0, Linkage, name),
    ParamAttrs(0) {
  SymTab = new ValueSymbolTable();

  assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
         && "LLVM functions cannot return aggregate values!");

  // If the function has arguments, mark them as lazily built.
  if (Ty->getNumParams())
    SubclassData = 1;   // Set the "has lazy arguments" bit.

  // Make sure that we get added to a function
  LeakDetector::addGarbageObject(this);

  if (ParentModule)
    ParentModule->getFunctionList().push_back(this);
}

Function::~Function() {
  dropAllReferences();    // After this it is safe to delete instructions.

  // Delete all of the method arguments and unlink from symbol table...
  ArgumentList.clear();
  delete SymTab;

  // Drop our reference to the parameter attributes, if any.
  if (ParamAttrs)
    ParamAttrs->dropRef();

  // Remove the function from the on-the-side collector table.
  clearCollector();
}

void Function::BuildLazyArguments() const {
  // Create the arguments vector, all arguments start out unnamed.
  const FunctionType *FT = getFunctionType();
  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
    assert(FT->getParamType(i) != Type::VoidTy &&
           "Cannot have void typed arguments!");
    ArgumentList.push_back(new Argument(FT->getParamType(i)));
  }

  // Clear the lazy arguments bit.
  const_cast<Function*>(this)->SubclassData &= ~1;
}

size_t Function::arg_size() const {
  return getFunctionType()->getNumParams();
}
bool Function::arg_empty() const {
  return getFunctionType()->getNumParams() == 0;
}

void Function::setParent(Module *parent) {
  if (getParent())
    LeakDetector::addGarbageObject(this);
  Parent = parent;
  if (getParent())
    LeakDetector::removeGarbageObject(this);
}

void Function::setParamAttrs(const ParamAttrsList *attrs) {
  // Avoid deleting the ParamAttrsList if they are setting the
  // attributes to the same list.
  if (ParamAttrs == attrs)
    return;

  // Drop reference on the old ParamAttrsList
  if (ParamAttrs)
    ParamAttrs->dropRef();

  // Add reference to the new ParamAttrsList
  if (attrs)
    attrs->addRef();

  // Set the new ParamAttrsList.
  ParamAttrs = attrs;
}

// dropAllReferences() - This function causes all the subinstructions to "let
// go" of all references that they are maintaining.  This allows one to
// 'delete' a whole class at a time, even though there may be circular
// references... first all references are dropped, and all use counts go to
// zero.  Then everything is deleted for real.  Note that no operations are
// valid on an object that has "dropped all references", except operator
// delete.
//
void Function::dropAllReferences() {
  for (iterator I = begin(), E = end(); I != E; ++I)
    I->dropAllReferences();
  BasicBlocks.clear();    // Delete all basic blocks...
}

// Maintain the collector name for each function in an on-the-side table. This
// saves allocating an additional word in Function for programs which do not use
// GC (i.e., most programs) at the cost of increased overhead for clients which
// do use GC.
static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
static StringPool *CollectorNamePool;

bool Function::hasCollector() const {
  return CollectorNames && CollectorNames->count(this);
}

const char *Function::getCollector() const {
  assert(hasCollector() && "Function has no collector");
  return *(*CollectorNames)[this];
}

void Function::setCollector(const char *Str) {
  if (!CollectorNamePool)
    CollectorNamePool = new StringPool();
  if (!CollectorNames)
    CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
  (*CollectorNames)[this] = CollectorNamePool->intern(Str);
}

void Function::clearCollector() {
  if (CollectorNames) {
    CollectorNames->erase(this);
    if (CollectorNames->empty()) {
      delete CollectorNames;
      CollectorNames = 0;
      if (CollectorNamePool->empty()) {
        delete CollectorNamePool;
        CollectorNamePool = 0;
      }
    }
  }
}

/// getIntrinsicID - This method returns the ID number of the specified
/// function, or Intrinsic::not_intrinsic if the function is not an
/// intrinsic, or if the pointer is null.  This value is always defined to be
/// zero to allow easy checking for whether a function is intrinsic or not.  The
/// particular intrinsic functions which correspond to this value are defined in
/// llvm/Intrinsics.h.
///
unsigned Function::getIntrinsicID(bool noAssert) const {
  const ValueName *ValName = this->getValueName();
  if (!ValName)
    return 0;
  unsigned Len = ValName->getKeyLength();
  const char *Name = ValName->getKeyData();

  if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
      || Name[2] != 'v' || Name[3] != 'm')
    return 0;  // All intrinsics start with 'llvm.'

  assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");

#define GET_FUNCTION_RECOGNIZER
#include "llvm/Intrinsics.gen"
#undef GET_FUNCTION_RECOGNIZER
  assert(noAssert && "Invalid LLVM intrinsic name");
  return 0;
}

std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
  assert(id < num_intrinsics && "Invalid intrinsic ID!");
  const char * const Table[] = {
    "not_intrinsic",
#define GET_INTRINSIC_NAME_TABLE
#include "llvm/Intrinsics.gen"
#undef GET_INTRINSIC_NAME_TABLE
  };
  if (numTys == 0)
    return Table[id];
  std::string Result(Table[id]);
  for (unsigned i = 0; i < numTys; ++i)
    if (Tys[i])
      Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
  return Result;
}

const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
                                       unsigned numTys) {
  const Type *ResultTy = NULL;
  std::vector<const Type*> ArgTys;
  bool IsVarArg = false;

#define GET_INTRINSIC_GENERATOR
#include "llvm/Intrinsics.gen"
#undef GET_INTRINSIC_GENERATOR

  return FunctionType::get(ResultTy, ArgTys, IsVarArg);
}

const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
  ParamAttrsVector Attrs;
  uint16_t Attr = ParamAttr::None;

#define GET_INTRINSIC_ATTRIBUTES
#include "llvm/Intrinsics.gen"
#undef GET_INTRINSIC_ATTRIBUTES

  // Intrinsics cannot throw exceptions.
  Attr |= ParamAttr::NoUnwind;

  Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
  return ParamAttrsList::get(Attrs);
}

Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
                                    unsigned numTys) {
  // There can never be multiple globals with the same name of different types,
  // because intrinsics must be a specific type.
  Function *F =
    cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
                                          getType(id, Tys, numTys)));
  F->setParamAttrs(getParamAttrs(id));
  return F;
}

Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
    if (CE->getOpcode() == Instruction::BitCast) {
      if (isa<PointerType>(CE->getOperand(0)->getType()))
        return StripPointerCasts(CE->getOperand(0));
    } else if (CE->getOpcode() == Instruction::GetElementPtr) {
      for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
        if (!CE->getOperand(i)->isNullValue())
          return Ptr;
      return StripPointerCasts(CE->getOperand(0));
    }
    return Ptr;
  }

  if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
    if (isa<PointerType>(CI->getOperand(0)->getType()))
      return StripPointerCasts(CI->getOperand(0));
  } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
    if (GEP->hasAllZeroIndices())
      return StripPointerCasts(GEP->getOperand(0));
  }
  return Ptr;
}

// vim: sw=2 ai
<|endoftext|>


<commit_before>//===-- Metadata.cpp - Implement Metadata classes -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Metadata classes.
//
//===----------------------------------------------------------------------===//

#include "LLVMContextImpl.h"
#include "llvm/Metadata.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Instruction.h"
#include "SymbolTableListTraitsImpl.h"
using namespace llvm;

//===----------------------------------------------------------------------===//
//MetadataBase implementation
//

/// resizeOperands - Metadata keeps track of other metadata uses using
/// OperandList. Resize this list to hold anticipated number of metadata
/// operands.
void MetadataBase::resizeOperands(unsigned NumOps) {
  unsigned e = getNumOperands();
  if (NumOps == 0) {
    NumOps = e*2;
    if (NumOps < 2) NumOps = 2;
  } else if (NumOps > NumOperands) {
    // No resize needed.
    if (ReservedSpace >= NumOps) return;
  } else if (NumOps == NumOperands) {
    if (ReservedSpace == NumOps) return;
  } else {
    return;
  }

  ReservedSpace = NumOps;
  Use *OldOps = OperandList;
  Use *NewOps = allocHungoffUses(NumOps);
  std::copy(OldOps, OldOps + e, NewOps);
  OperandList = NewOps;
  if (OldOps) Use::zap(OldOps, OldOps + e, true);
}
//===----------------------------------------------------------------------===//
//MDString implementation
//
MDString *MDString::get(LLVMContext &Context, const StringRef &Str) {
  LLVMContextImpl *pImpl = Context.pImpl;
  sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
  StringMapEntry<MDString *> &Entry =
    pImpl->MDStringCache.GetOrCreateValue(Str);
  MDString *&S = Entry.getValue();
  if (!S) S = new MDString(Context, Entry.getKeyData(),
                           Entry.getKeyLength());

  return S;
}

//===----------------------------------------------------------------------===//
//MDNode implementation
//
MDNode::MDNode(LLVMContext &C, Value*const* Vals, unsigned NumVals)
  : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
  NumOperands = 0;
  resizeOperands(NumVals);
  for (unsigned i = 0; i != NumVals; ++i) {
    // Only record metadata uses.
    if (MetadataBase *MB = dyn_cast_or_null<MetadataBase>(Vals[i]))
      OperandList[NumOperands++] = MB;
    else if(Vals[i] &&
            Vals[i]->getType()->getTypeID() == Type::MetadataTyID)
      OperandList[NumOperands++] = Vals[i];
    Node.push_back(ElementVH(Vals[i], this));
  }
}

void MDNode::Profile(FoldingSetNodeID &ID) const {
  for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
    ID.AddPointer(*I);
}

MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
  LLVMContextImpl *pImpl = Context.pImpl;
  FoldingSetNodeID ID;
  for (unsigned i = 0; i != NumVals; ++i)
    ID.AddPointer(Vals[i]);

  pImpl->ConstantsLock.reader_acquire();
  void *InsertPoint;
  MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
  pImpl->ConstantsLock.reader_release();

  if (!N) {
    sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
    N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
    if (!N) {
      // InsertPoint will have been set by the FindNodeOrInsertPos call.
      N = new MDNode(Context, Vals, NumVals);
      pImpl->MDNodeSet.InsertNode(N, InsertPoint);
    }
  }

  return N;
}

/// dropAllReferences - Remove all uses and clear node vector.
void MDNode::dropAllReferences() {
  User::dropAllReferences();
  Node.clear();
}

MDNode::~MDNode() {
  {
    LLVMContextImpl *pImpl = getType()->getContext().pImpl;
    sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
    pImpl->MDNodeSet.RemoveNode(this);
  }
  dropAllReferences();
}

// Replace value from this node's element list.
void MDNode::replaceElement(Value *From, Value *To) {
  if (From == To || !getType())
    return;
  LLVMContext &Context = getType()->getContext();
  LLVMContextImpl *pImpl = Context.pImpl;

  // Find value. This is a linear search, do something if it consumes
  // lot of time. It is possible that to have multiple instances of
  // From in this MDNode's element list.
  SmallVector<unsigned, 4> Indexes;
  unsigned Index = 0;
  for (SmallVector<ElementVH, 4>::iterator I = Node.begin(),
         E = Node.end(); I != E; ++I, ++Index) {
    Value *V = *I;
    if (V && V == From)
      Indexes.push_back(Index);
  }

  if (Indexes.empty())
    return;

  // Remove "this" from the context map.
  {
    sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
    pImpl->MDNodeSet.RemoveNode(this);
  }

  // MDNode only lists metadata elements in operand list, because MDNode
  // used by MDNode is considered a valid use. However on the side, MDNode
  // using a non-metadata value is not considered a "use" of non-metadata
  // value.
  SmallVector<unsigned, 4> OpIndexes;
  unsigned OpIndex = 0;
  for (User::op_iterator OI = op_begin(), OE = op_end();
       OI != OE; ++OI, OpIndex++) {
    if (*OI == From)
      OpIndexes.push_back(OpIndex);
  }
  if (MetadataBase *MDTo = dyn_cast_or_null<MetadataBase>(To)) {
    for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
           OE = OpIndexes.end(); OI != OE; ++OI)
      setOperand(*OI, MDTo);
  } else {
    for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
           OE = OpIndexes.end(); OI != OE; ++OI)
      setOperand(*OI, 0);
  }

  // Replace From element(s) in place.
  for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end();
       I != E; ++I) {
    unsigned Index = *I;
    Node[Index] = ElementVH(To, this);
  }

  // Insert updated "this" into the context's folding node set.
  // If a node with same element list already exist then before inserting
  // updated "this" into the folding node set, replace all uses of existing
  // node with updated "this" node.
  FoldingSetNodeID ID;
  Profile(ID);
  pImpl->ConstantsLock.reader_acquire();
  void *InsertPoint;
  MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
  pImpl->ConstantsLock.reader_release();

  if (N) {
    N->replaceAllUsesWith(this);
    delete N;
    N = 0;
  }

  {
    sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
    N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
    if (!N) {
      // InsertPoint will have been set by the FindNodeOrInsertPos call.
      N = this;
      pImpl->MDNodeSet.InsertNode(N, InsertPoint);
    }
  }
}

//===----------------------------------------------------------------------===//
//NamedMDNode implementation
//
NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
                         MetadataBase*const* MDs,
                         unsigned NumMDs, Module *ParentModule)
  : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
  setName(N);
  NumOperands = 0;
  resizeOperands(NumMDs);

  for (unsigned i = 0; i != NumMDs; ++i) {
    if (MDs[i])
      OperandList[NumOperands++] = MDs[i];
    Node.push_back(WeakMetadataVH(MDs[i]));
  }
  if (ParentModule)
    ParentModule->getNamedMDList().push_back(this);
}

NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
  assert (NMD && "Invalid source NamedMDNode!");
  SmallVector<MetadataBase *, 4> Elems;
  for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
    Elems.push_back(NMD->getElement(i));
  return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
                         Elems.data(), Elems.size(), M);
}

/// eraseFromParent - Drop all references and remove the node from parent
/// module.
void NamedMDNode::eraseFromParent() {
  getParent()->getNamedMDList().erase(this);
}

/// dropAllReferences - Remove all uses and clear node vector.
void NamedMDNode::dropAllReferences() {
  User::dropAllReferences();
  Node.clear();
}

NamedMDNode::~NamedMDNode() {
  dropAllReferences();
}

//===----------------------------------------------------------------------===//
//Metadata implementation
//

/// RegisterMDKind - Register a new metadata kind and return its ID.
/// A metadata kind can be registered only once.
unsigned MetadataContext::RegisterMDKind(const char *Name) {
  assert (validName(Name) && "Invalid custome metadata name!");
  unsigned Count = MDHandlerNames.size();
  StringMap<unsigned>::iterator I = MDHandlerNames.find(Name);
  assert(I == MDHandlerNames.end() && "Already registered MDKind!");
  MDHandlerNames[Name] = Count + 1;
  return Count + 1;
}

/// validName - Return true if Name is a valid custom metadata handler name.
bool MetadataContext::validName(const char *Name) {
  if (!Name)
    return false;

  if (!isalpha(*Name))
    return false;

  unsigned Length = strlen(Name);
  unsigned Count = 1;
  ++Name;
  while (Name &&
         (isalnum(*Name) || *Name == '_' || *Name == '-' || *Name == '.')) {
    ++Name;
    ++Count;
  }
  if (Length != Count)
    return false;
  return true;
}

/// getMDKind - Return metadata kind. If the requested metadata kind
/// is not registered then return 0.
unsigned MetadataContext::getMDKind(const char *Name) {
  assert (validName(Name) && "Invalid custome metadata name!");
  StringMap<unsigned>::iterator I = MDHandlerNames.find(Name);
  if (I == MDHandlerNames.end())
    return 0;

  return I->getValue();
}

/// addMD - Attach the metadata of given kind with an Instruction.
void MetadataContext::addMD(unsigned MDKind, MDNode *Node, Instruction *Inst) {
  assert (Node && "Unable to add custome metadata");
  Inst->HasMetadata = true;
  MDStoreTy::iterator I = MetadataStore.find(Inst);
  if (I == MetadataStore.end()) {
    MDMapTy Info;
    Info.push_back(std::make_pair(MDKind, Node));
    MetadataStore.insert(std::make_pair(Inst, Info));
    return;
  }

  MDMapTy &Info = I->second;
  // If there is an entry for this MDKind then replace it.
  for (unsigned i = 0, e = Info.size(); i != e; ++i) {
    MDPairTy &P = Info[i];
    if (P.first == MDKind) {
      Info[i] = std::make_pair(MDKind, Node);
      return;
    }
  }

  // Otherwise add a new entry.
  Info.push_back(std::make_pair(MDKind, Node));
  return;
}

/// removeMD - Remove metadata of given kind attached with an instuction.
void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
  MDStoreTy::iterator I = MetadataStore.find(Inst);
  if (I == MetadataStore.end())
    return;

  MDMapTy &Info = I->second;
  for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
    MDPairTy &P = *MI;
    if (P.first == Kind) {
      Info.erase(MI);
      return;
    }
  }

  return;
}

/// removeMDs - Remove all metadata attached with an instruction.
void MetadataContext::removeMDs(const Instruction *Inst) {
  // Find Metadata handles for this instruction.
  MDStoreTy::iterator I = MetadataStore.find(Inst);
  assert (I != MetadataStore.end() && "Invalid custom metadata info!");
  MDMapTy &Info = I->second;

  // FIXME : Give all metadata handlers a chance to adjust.

  // Remove the entries for this instruction.
  Info.clear();
  MetadataStore.erase(I);
}

/// getMD - Get the metadata of given kind attached with an Instruction.
/// If the metadata is not found then return 0.
MDNode *MetadataContext::getMD(unsigned MDKind, const Instruction *Inst) {
  MDStoreTy::iterator I = MetadataStore.find(Inst);
  if (I == MetadataStore.end())
    return NULL;

  MDMapTy &Info = I->second;
  for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
    if (I->first == MDKind)
      return dyn_cast_or_null<MDNode>(I->second);
  return NULL;
}

/// getMDs - Get the metadata attached with an Instruction.
const MetadataContext::MDMapTy *MetadataContext::getMDs(const Instruction *Inst) {
  MDStoreTy::iterator I = MetadataStore.find(Inst);
  if (I == MetadataStore.end())
    return NULL;

  return &(I->second);
}

/// getHandlerNames - Get handler names. This is used by bitcode
/// writer.
const StringMap<unsigned> *MetadataContext::getHandlerNames() {
  return &MDHandlerNames;
}

/// ValueIsCloned - This handler is used to update metadata store
/// when In1 is cloned to create In2.
void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
  // Find Metadata handles for In1.
  MDStoreTy::iterator I = MetadataStore.find(In1);
  assert (I != MetadataStore.end() && "Invalid custom metadata info!");

  // FIXME : Give all metadata handlers a chance to adjust.

  MDMapTy &In1Info = I->second;
  MDMapTy In2Info;
  for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
    if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
      addMD(I->first, MD, In2);
}
<commit_msg><commit_after>//===-- Metadata.cpp - Implement Metadata classes -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Metadata classes.
//
//===----------------------------------------------------------------------===//

#include "LLVMContextImpl.h"
#include "llvm/Metadata.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Instruction.h"
#include "SymbolTableListTraitsImpl.h"
using namespace llvm;

//===----------------------------------------------------------------------===//
//MetadataBase implementation
//

/// resizeOperands - Metadata keeps track of other metadata uses using
/// OperandList. Resize this list to hold anticipated number of metadata
/// operands.
void MetadataBase::resizeOperands(unsigned NumOps) {
  unsigned e = getNumOperands();
  if (NumOps == 0) {
    NumOps = e*2;
    if (NumOps < 2) NumOps = 2;
  } else if (NumOps > NumOperands) {
    // No resize needed.
    if (ReservedSpace >= NumOps) return;
  } else if (NumOps == NumOperands) {
    if (ReservedSpace == NumOps) return;
  } else {
    return;
  }

  ReservedSpace = NumOps;
  Use *OldOps = OperandList;
  Use *NewOps = allocHungoffUses(NumOps);
  std::copy(OldOps, OldOps + e, NewOps);
  OperandList = NewOps;
  if (OldOps) Use::zap(OldOps, OldOps + e, true);
}
//===----------------------------------------------------------------------===//
//MDString implementation
//
MDString *MDString::get(LLVMContext &Context, const StringRef &Str) {
  LLVMContextImpl *pImpl = Context.pImpl;
  sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
  StringMapEntry<MDString *> &Entry =
    pImpl->MDStringCache.GetOrCreateValue(Str);
  MDString *&S = Entry.getValue();
  if (!S) S = new MDString(Context, Entry.getKeyData(),
                           Entry.getKeyLength());

  return S;
}

//===----------------------------------------------------------------------===//
//MDNode implementation
//
MDNode::MDNode(LLVMContext &C, Value*const* Vals, unsigned NumVals)
  : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
  NumOperands = 0;
  resizeOperands(NumVals);
  for (unsigned i = 0; i != NumVals; ++i) {
    // Only record metadata uses.
    if (MetadataBase *MB = dyn_cast_or_null<MetadataBase>(Vals[i]))
      OperandList[NumOperands++] = MB;
    else if(Vals[i] &&
            Vals[i]->getType()->getTypeID() == Type::MetadataTyID)
      OperandList[NumOperands++] = Vals[i];
    Node.push_back(ElementVH(Vals[i], this));
  }
}

void MDNode::Profile(FoldingSetNodeID &ID) const {
  for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
    ID.AddPointer(*I);
}

MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
  LLVMContextImpl *pImpl = Context.pImpl;
  FoldingSetNodeID ID;
  for (unsigned i = 0; i != NumVals; ++i)
    ID.AddPointer(Vals[i]);

  pImpl->ConstantsLock.reader_acquire();
  void *InsertPoint;
  MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
  pImpl->ConstantsLock.reader_release();

  if (!N) {
    sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
    N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
    if (!N) {
      // InsertPoint will have been set by the FindNodeOrInsertPos call.
      N = new MDNode(Context, Vals, NumVals);
      pImpl->MDNodeSet.InsertNode(N, InsertPoint);
    }
  }

  return N;
}

/// dropAllReferences - Remove all uses and clear node vector.
void MDNode::dropAllReferences() {
  User::dropAllReferences();
  Node.clear();
}

MDNode::~MDNode() {
  {
    LLVMContextImpl *pImpl = getType()->getContext().pImpl;
    sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
    pImpl->MDNodeSet.RemoveNode(this);
  }
  dropAllReferences();
}

// Replace value from this node's element list.
void MDNode::replaceElement(Value *From, Value *To) {
  if (From == To || !getType())
    return;
  LLVMContext &Context = getType()->getContext();
  LLVMContextImpl *pImpl = Context.pImpl;

  // Find value. This is a linear search, do something if it consumes
  // lot of time. It is possible that to have multiple instances of
  // From in this MDNode's element list.
  SmallVector<unsigned, 4> Indexes;
  unsigned Index = 0;
  for (SmallVector<ElementVH, 4>::iterator I = Node.begin(),
         E = Node.end(); I != E; ++I, ++Index) {
    Value *V = *I;
    if (V && V == From)
      Indexes.push_back(Index);
  }

  if (Indexes.empty())
    return;

  // Remove "this" from the context map.
  {
    sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
    pImpl->MDNodeSet.RemoveNode(this);
  }

  // MDNode only lists metadata elements in operand list, because MDNode
  // used by MDNode is considered a valid use. However on the side, MDNode
  // using a non-metadata value is not considered a "use" of non-metadata
  // value.
  SmallVector<unsigned, 4> OpIndexes;
  unsigned OpIndex = 0;
  for (User::op_iterator OI = op_begin(), OE = op_end();
       OI != OE; ++OI, OpIndex++) {
    if (*OI == From)
      OpIndexes.push_back(OpIndex);
  }
  if (MetadataBase *MDTo = dyn_cast_or_null<MetadataBase>(To)) {
    for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
           OE = OpIndexes.end(); OI != OE; ++OI)
      setOperand(*OI, MDTo);
  } else {
    for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
           OE = OpIndexes.end(); OI != OE; ++OI)
      setOperand(*OI, 0);
  }

  // Replace From element(s) in place.
  for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end();
       I != E; ++I) {
    unsigned Index = *I;
    Node[Index] = ElementVH(To, this);
  }

  // Insert updated "this" into the context's folding node set.
  // If a node with same element list already exist then before inserting
  // updated "this" into the folding node set, replace all uses of existing
  // node with updated "this" node.
  FoldingSetNodeID ID;
  Profile(ID);
  pImpl->ConstantsLock.reader_acquire();
  void *InsertPoint;
  MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
  pImpl->ConstantsLock.reader_release();

  if (N) {
    N->replaceAllUsesWith(this);
    delete N;
    N = 0;
  }

  {
    sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
    N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
    if (!N) {
      // InsertPoint will have been set by the FindNodeOrInsertPos call.
      N = this;
      pImpl->MDNodeSet.InsertNode(N, InsertPoint);
    }
  }
}

//===----------------------------------------------------------------------===//
//NamedMDNode implementation
//
NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
                         MetadataBase*const* MDs,
                         unsigned NumMDs, Module *ParentModule)
  : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
  setName(N);
  NumOperands = 0;
  resizeOperands(NumMDs);

  for (unsigned i = 0; i != NumMDs; ++i) {
    if (MDs[i])
      OperandList[NumOperands++] = MDs[i];
    Node.push_back(WeakMetadataVH(MDs[i]));
  }
  if (ParentModule)
    ParentModule->getNamedMDList().push_back(this);
}

NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
  assert (NMD && "Invalid source NamedMDNode!");
  SmallVector<MetadataBase *, 4> Elems;
  for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
    Elems.push_back(NMD->getElement(i));
  return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
                         Elems.data(), Elems.size(), M);
}

/// eraseFromParent - Drop all references and remove the node from parent
/// module.
void NamedMDNode::eraseFromParent() {
  getParent()->getNamedMDList().erase(this);
}

/// dropAllReferences - Remove all uses and clear node vector.
void NamedMDNode::dropAllReferences() {
  User::dropAllReferences();
  Node.clear();
}

NamedMDNode::~NamedMDNode() {
  dropAllReferences();
}

//===----------------------------------------------------------------------===//
//Metadata implementation
//

/// RegisterMDKind - Register a new metadata kind and return its ID.
/// A metadata kind can be registered only once.
unsigned MetadataContext::RegisterMDKind(const char *Name) {
  assert (validName(Name) && "Invalid custome metadata name!");
  unsigned Count = MDHandlerNames.size();
  assert(MDHandlerNames.find(Name) == MDHandlerNames.end()
         && "Already registered MDKind!");
  MDHandlerNames[Name] = Count + 1;
  return Count + 1;
}

/// validName - Return true if Name is a valid custom metadata handler name.
bool MetadataContext::validName(const char *Name) {
  if (!Name)
    return false;

  if (!isalpha(*Name))
    return false;

  unsigned Length = strlen(Name);
  unsigned Count = 1;
  ++Name;
  while (Name &&
         (isalnum(*Name) || *Name == '_' || *Name == '-' || *Name == '.')) {
    ++Name;
    ++Count;
  }
  if (Length != Count)
    return false;
  return true;
}

/// getMDKind - Return metadata kind. If the requested metadata kind
/// is not registered then return 0.
unsigned MetadataContext::getMDKind(const char *Name) {
  assert (validName(Name) && "Invalid custome metadata name!");
  StringMap<unsigned>::iterator I = MDHandlerNames.find(Name);
  if (I == MDHandlerNames.end())
    return 0;

  return I->getValue();
}

/// addMD - Attach the metadata of given kind with an Instruction.
void MetadataContext::addMD(unsigned MDKind, MDNode *Node, Instruction *Inst) {
  assert (Node && "Unable to add custome metadata");
  Inst->HasMetadata = true;
  MDStoreTy::iterator I = MetadataStore.find(Inst);
  if (I == MetadataStore.end()) {
    MDMapTy Info;
    Info.push_back(std::make_pair(MDKind, Node));
    MetadataStore.insert(std::make_pair(Inst, Info));
    return;
  }

  MDMapTy &Info = I->second;
  // If there is an entry for this MDKind then replace it.
  for (unsigned i = 0, e = Info.size(); i != e; ++i) {
    MDPairTy &P = Info[i];
    if (P.first == MDKind) {
      Info[i] = std::make_pair(MDKind, Node);
      return;
    }
  }

  // Otherwise add a new entry.
  Info.push_back(std::make_pair(MDKind, Node));
  return;
}

/// removeMD - Remove metadata of given kind attached with an instuction.
void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
  MDStoreTy::iterator I = MetadataStore.find(Inst);
  if (I == MetadataStore.end())
    return;

  MDMapTy &Info = I->second;
  for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
    MDPairTy &P = *MI;
    if (P.first == Kind) {
      Info.erase(MI);
      return;
    }
  }

  return;
}

/// removeMDs - Remove all metadata attached with an instruction.
void MetadataContext::removeMDs(const Instruction *Inst) {
  // Find Metadata handles for this instruction.
  MDStoreTy::iterator I = MetadataStore.find(Inst);
  assert (I != MetadataStore.end() && "Invalid custom metadata info!");
  MDMapTy &Info = I->second;

  // FIXME : Give all metadata handlers a chance to adjust.

  // Remove the entries for this instruction.
  Info.clear();
  MetadataStore.erase(I);
}

/// getMD - Get the metadata of given kind attached with an Instruction.
/// If the metadata is not found then return 0.
MDNode *MetadataContext::getMD(unsigned MDKind, const Instruction *Inst) {
  MDStoreTy::iterator I = MetadataStore.find(Inst);
  if (I == MetadataStore.end())
    return NULL;

  MDMapTy &Info = I->second;
  for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
    if (I->first == MDKind)
      return dyn_cast_or_null<MDNode>(I->second);
  return NULL;
}

/// getMDs - Get the metadata attached with an Instruction.
const MetadataContext::MDMapTy *MetadataContext::getMDs(const Instruction *Inst) {
  MDStoreTy::iterator I = MetadataStore.find(Inst);
  if (I == MetadataStore.end())
    return NULL;

  return &(I->second);
}

/// getHandlerNames - Get handler names. This is used by bitcode
/// writer.
const StringMap<unsigned> *MetadataContext::getHandlerNames() {
  return &MDHandlerNames;
}

/// ValueIsCloned - This handler is used to update metadata store
/// when In1 is cloned to create In2.
void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
  // Find Metadata handles for In1.
  MDStoreTy::iterator I = MetadataStore.find(In1);
  assert (I != MetadataStore.end() && "Invalid custom metadata info!");

  // FIXME : Give all metadata handlers a chance to adjust.

  MDMapTy &In1Info = I->second;
  MDMapTy In2Info;
  for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
    if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
      addMD(I->first, MD, In2);
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 - 2014 Leap Motion. All rights reserved. Proprietary and confidential.
#include "stdafx.h"
#include "AutoNetServer.h"
#include "Autowiring/at_exit.h"
#include <iostream>

AutoNetServer::AutoNetServer():
  CoreThread("AutoNetServer"),
  m_Server(std::make_shared<websocketpp::server>(websocketpp::server::handler::ptr(new AutoNetServer::Handler(*this)))),
  m_Port(8000)
{
  m_Server->alog().unset_level(websocketpp::log::alevel::ALL);
  m_Server->elog().unset_level(websocketpp::log::elevel::ALL);

  for (auto type = g_pFirstEntry; type; type = type->pFlink) {
    if (type->IsEventReceiver())
      m_EventTypes.insert(type->NewTypeIdentifier());

    if (type->CanInject()){
      m_AllTypes[type->ti.name()] = [type]{
        std::cout
        << "Injecting "
        << type->ti.name()
        << " into "
        << AutoCurrentContext()->GetSigilType().name()
        << std::endl;
        type->Inject();
      };
    }
  }
}

AutoNetServer::~AutoNetServer(){}

//Core Thread methods
void AutoNetServer::Run(void){
  std::cout << "Starting Autonet server..." << std::endl;

  m_Server->start_listen(m_Port);

  auto teardown = MakeAtExit([this] {
    m_Server->close_all();
    m_Server->stop_listen(true);
  });

  PollThreadUtilization(std::chrono::milliseconds(1000));

  CoreThread::Run();
}

void AutoNetServer::OnStop(void){
  for (auto sub : m_Subscribers){
    SendMessage(sub, "Closing");
  }
  m_Server->stop();
}

void AutoNetServer::Breakpoint(std::string name){
  std::unique_lock<std::mutex> lk(m_mutex);

  m_breakpoints.insert(name);

  *this += [this, name]{
    BroadcastMessage("breakpoint", name);
  };

  m_breakpoint_cv.wait(lk, [this, name]{
    return !m_breakpoints.count(name);
  });
}

// Update Functions
void AutoNetServer::NewContext(CoreContext& newCtxt){
  auto ctxt = newCtxt.shared_from_this();

  *this += [this, ctxt] {
    Jzon::Object context;
    context.Add("name", ctxt->GetSigilType().name());

    if (ctxt->GetParentContext()){
      context.Add("parent", ResolveContextID(ctxt->GetParentContext().get()));
    }

    BroadcastMessage("newContext", ResolveContextID(ctxt.get()), context);
  };
}

void AutoNetServer::ExpiredContext(CoreContext& oldCtxt){
  int id = ResolveContextID(&oldCtxt);
  *this += [this, id] {
    BroadcastMessage("expiredContext", id);
  };
}

void AutoNetServer::NewObject(CoreContext& ctxt, const AnySharedPointer& object){
  int contextID = ResolveContextID(&ctxt);

  *this += [this, object, contextID]{
    Jzon::Object objData;
    Jzon::Object types;
    std::shared_ptr<Object> objectPtr = *object;

    // Add object data
    objData.Add("name", typeid(*objectPtr).name());
    {
      Jzon::Array slots;
      for (auto slot = object->GetSlotInformation().pHead; slot; slot = slot->pFlink) {
        Jzon::Object slotData;
        slotData.Add("name", slot->type.name());
        slotData.Add("autoRequired", slot->autoRequired);
        slotData.Add("offset", int(slot->slotOffset));
        slots.Add(slotData);
      }
      objData.Add("slots", slots);
    }

    // Add type information
    auto member = leap::fast_pointer_cast<ContextMember>(objectPtr);
    if (member) {
      types.Add("contextMember", true);
    }

    auto runnable = leap::fast_pointer_cast<CoreRunnable>(objectPtr);
    if (runnable) {
      types.Add("coreRunnable", true);
    }

    auto thread = leap::fast_pointer_cast<BasicThread>(objectPtr);
    if(thread) {
      m_Threads[thread->GetSelf<BasicThread>()];

      Jzon::Object utilization;
      utilization.Add("kernel", 0.0);
      utilization.Add("user", 0.0);
      types.Add("thread", utilization);
    }

    auto eventRcvr = leap::fast_pointer_cast<EventReceiver>(objectPtr);
    if (eventRcvr) {
      Jzon::Array listenerTypes;
      for (auto event : m_EventTypes) {
        if (event->Is(objectPtr.get()))
          listenerTypes.Add(event->Type().name());
      }

      types.Add("eventReceiver", listenerTypes);
    }

    auto filter = leap::fast_pointer_cast<ExceptionFilter>(objectPtr);
    if (filter) {
      types.Add("exceptionFilter", true);
    }

    auto bolt = leap::fast_pointer_cast<BoltBase>(objectPtr);
    if (bolt) {
      Jzon::Array sigils;
      for(auto cur = bolt->GetContextSigils(); *cur; cur++){
        sigils.Add((*cur)->name());
      }
      types.Add("bolt", sigils);
    }

    BroadcastMessage("newObject", contextID, types, objData);
  };

}

void AutoNetServer::EventFired(CoreContext& context, const std::type_info& info){
  int contextID = ResolveContextID(&context);
  std::string name = info.name();

  *this += [this, contextID, name] {
    Jzon::Object eventHash;
    eventHash.Add("name", name);

    BroadcastMessage("eventFired", contextID, eventHash);
  };
}

void AutoNetServer::HandleTerminateContext(int contextID) {
  ResolveContextID(contextID)->SignalShutdown();
}

void AutoNetServer::HandleInjectContextMember(int contextID, std::string typeName) {
  std::shared_ptr<CoreContext> ctxt = ResolveContextID(contextID)->shared_from_this();

  if (m_AllTypes.find(typeName) != m_AllTypes.end()) {
    CurrentContextPusher pshr(ctxt);
    m_AllTypes[typeName]();
  } else {
    // Type doesn't exist
    assert(false);
  }
}

void AutoNetServer::HandleResumeFromBreakpoint(std::string name){
  std::unique_lock<std::mutex> lk(m_mutex);

  m_breakpoints.erase(name);
  m_breakpoint_cv.notify_all();
}

//helper functions
int AutoNetServer::ResolveContextID(CoreContext* ctxt) {
  static int counter = 0;

  if ( m_ContextIDs.find(ctxt) == m_ContextIDs.end() ){
    m_ContextIDs[ctxt] = counter;
    m_ContextPtrs[counter] = ctxt;
    return counter++;
  } else {
    return m_ContextIDs[ctxt];
  }
}

CoreContext* AutoNetServer::ResolveContextID(int id) {
  return m_ContextPtrs.at(id);
}

void AutoNetServer::PollThreadUtilization(std::chrono::milliseconds period){

  *this += period, [this, period] {

    for(auto q = m_Threads.begin(); q != m_Threads.end();) {
      std::shared_ptr<BasicThread> thread = q->first.lock();
      if(!thread) {
        m_Threads.erase(q++);
        continue;
      }

      std::chrono::milliseconds runtimeKM, runtimeUM;
      thread->GetThreadTimes(runtimeKM, runtimeUM);

      // Determine the amount of time this thread has run since the last time we
      // asked it for its runtime.
      std::chrono::duration<double> deltaRuntimeKM = runtimeKM - q->second.m_lastRuntimeKM;
      std::chrono::duration<double> deltaRuntimeUM = runtimeUM - q->second.m_lastRuntimeUM;

      // Update timing values:
      q->second.m_lastRuntimeKM = runtimeKM;
      q->second.m_lastRuntimeUM = runtimeUM;

      // Broadcast current thread utilization
      int contextID = ResolveContextID(thread->GetContext().get());
      std::string name = typeid(*thread.get()).name();

      double kmPercent = 100 * (deltaRuntimeKM / period);
      double umPercent = 100 * (deltaRuntimeUM / period);

      // Make sure user + kernel percent < 100.0
      umPercent = std::min(umPercent, 99.9 - kmPercent);

      if (kmPercent >= 0.0 && umPercent >= 0.0) {
        BroadcastMessage("threadUtilization", contextID, name, kmPercent, umPercent);
      }

      // Next!
      q++;
    }

    // Poll again after "period" milliseconds
    PollThreadUtilization(period);
  };
}
<commit_msg>Fixing Windows build error<commit_after>// Copyright (c) 2010 - 2014 Leap Motion. All rights reserved. Proprietary and confidential.
#include "stdafx.h"
#include "AutoNetServer.h"
#include "Autowiring/at_exit.h"
#include <iostream>

AutoNetServer::AutoNetServer():
  CoreThread("AutoNetServer"),
  m_Server(std::make_shared<websocketpp::server>(websocketpp::server::handler::ptr(new AutoNetServer::Handler(*this)))),
  m_Port(8000)
{
  m_Server->alog().unset_level(websocketpp::log::alevel::ALL);
  m_Server->elog().unset_level(websocketpp::log::elevel::ALL);

  for (auto type = g_pFirstEntry; type; type = type->pFlink) {
    if (type->IsEventReceiver())
      m_EventTypes.insert(type->NewTypeIdentifier());

    if (type->CanInject()){
      m_AllTypes[type->ti.name()] = [type]{
        std::cout
        << "Injecting "
        << type->ti.name()
        << " into "
        << AutoCurrentContext()->GetSigilType().name()
        << std::endl;
        type->Inject();
      };
    }
  }
}

AutoNetServer::~AutoNetServer(){}

//Core Thread methods
void AutoNetServer::Run(void){
  std::cout << "Starting Autonet server..." << std::endl;

  m_Server->start_listen(m_Port);

  auto teardown = MakeAtExit([this] {
    m_Server->close_all();
    m_Server->stop_listen(true);
  });

  PollThreadUtilization(std::chrono::milliseconds(1000));

  CoreThread::Run();
}

void AutoNetServer::OnStop(void){
  for (auto sub : m_Subscribers){
    SendMessage(sub, "Closing");
  }
  m_Server->stop();
}

void AutoNetServer::Breakpoint(std::string name){
  std::unique_lock<std::mutex> lk(m_mutex);

  m_breakpoints.insert(name);

  *this += [this, name]{
    BroadcastMessage("breakpoint", name);
  };

  m_breakpoint_cv.wait(lk, [this, name]{
    return !m_breakpoints.count(name);
  });
}

// Update Functions
void AutoNetServer::NewContext(CoreContext& newCtxt){
  auto ctxt = newCtxt.shared_from_this();

  *this += [this, ctxt] {
    Jzon::Object context;
    context.Add("name", ctxt->GetSigilType().name());

    if (ctxt->GetParentContext()){
      context.Add("parent", ResolveContextID(ctxt->GetParentContext().get()));
    }

    BroadcastMessage("newContext", ResolveContextID(ctxt.get()), context);
  };
}

void AutoNetServer::ExpiredContext(CoreContext& oldCtxt){
  int id = ResolveContextID(&oldCtxt);
  *this += [this, id] {
    BroadcastMessage("expiredContext", id);
  };
}

void AutoNetServer::NewObject(CoreContext& ctxt, const AnySharedPointer& object){
  int contextID = ResolveContextID(&ctxt);

  *this += [this, object, contextID]{
    Jzon::Object objData;
    Jzon::Object types;
    std::shared_ptr<Object> objectPtr = *object;

    // Add object data
    objData.Add("name", typeid(*objectPtr).name());
    {
      Jzon::Array slots;
      for (auto slot = object->GetSlotInformation().pHead; slot; slot = slot->pFlink) {
        Jzon::Object slotData;
        slotData.Add("name", slot->type.name());
        slotData.Add("autoRequired", slot->autoRequired);
        slotData.Add("offset", int(slot->slotOffset));
        slots.Add(slotData);
      }
      objData.Add("slots", slots);
    }

    // Add type information
    auto member = leap::fast_pointer_cast<ContextMember>(objectPtr);
    if (member) {
      types.Add("contextMember", true);
    }

    auto runnable = leap::fast_pointer_cast<CoreRunnable>(objectPtr);
    if (runnable) {
      types.Add("coreRunnable", true);
    }

    auto thread = leap::fast_pointer_cast<BasicThread>(objectPtr);
    if(thread) {
      m_Threads[thread->GetSelf<BasicThread>()];

      Jzon::Object utilization;
      utilization.Add("kernel", 0.0);
      utilization.Add("user", 0.0);
      types.Add("thread", utilization);
    }

    auto eventRcvr = leap::fast_pointer_cast<EventReceiver>(objectPtr);
    if (eventRcvr) {
      Jzon::Array listenerTypes;
      for (auto event : m_EventTypes) {
        if (event->Is(objectPtr.get()))
          listenerTypes.Add(event->Type().name());
      }

      types.Add("eventReceiver", listenerTypes);
    }

    auto filter = leap::fast_pointer_cast<ExceptionFilter>(objectPtr);
    if (filter) {
      types.Add("exceptionFilter", true);
    }

    auto bolt = leap::fast_pointer_cast<BoltBase>(objectPtr);
    if (bolt) {
      Jzon::Array sigils;
      for(auto cur = bolt->GetContextSigils(); *cur; cur++){
        sigils.Add((*cur)->name());
      }
      types.Add("bolt", sigils);
    }

    BroadcastMessage("newObject", contextID, types, objData);
  };

}

void AutoNetServer::EventFired(CoreContext& context, const std::type_info& info){
  int contextID = ResolveContextID(&context);
  std::string name = info.name();

  *this += [this, contextID, name] {
    Jzon::Object eventHash;
    eventHash.Add("name", name);

    BroadcastMessage("eventFired", contextID, eventHash);
  };
}

void AutoNetServer::HandleTerminateContext(int contextID) {
  ResolveContextID(contextID)->SignalShutdown();
}

void AutoNetServer::HandleInjectContextMember(int contextID, std::string typeName) {
  std::shared_ptr<CoreContext> ctxt = ResolveContextID(contextID)->shared_from_this();

  if (m_AllTypes.find(typeName) != m_AllTypes.end()) {
    CurrentContextPusher pshr(ctxt);
    m_AllTypes[typeName]();
  } else {
    // Type doesn't exist
    assert(false);
  }
}

void AutoNetServer::HandleResumeFromBreakpoint(std::string name){
  std::unique_lock<std::mutex> lk(m_mutex);

  m_breakpoints.erase(name);
  m_breakpoint_cv.notify_all();
}

//helper functions
int AutoNetServer::ResolveContextID(CoreContext* ctxt) {
  static int counter = 0;

  if ( m_ContextIDs.find(ctxt) == m_ContextIDs.end() ){
    m_ContextIDs[ctxt] = counter;
    m_ContextPtrs[counter] = ctxt;
    return counter++;
  } else {
    return m_ContextIDs[ctxt];
  }
}

CoreContext* AutoNetServer::ResolveContextID(int id) {
  return m_ContextPtrs.at(id);
}

void AutoNetServer::PollThreadUtilization(std::chrono::milliseconds period){

  *this += period, [this, period] {

    for(auto q = m_Threads.begin(); q != m_Threads.end();) {
      std::shared_ptr<BasicThread> thread = q->first.lock();
      if(!thread) {
        m_Threads.erase(q++);
        continue;
      }

      std::chrono::milliseconds runtimeKM, runtimeUM;
      thread->GetThreadTimes(runtimeKM, runtimeUM);

      // Determine the amount of time this thread has run since the last time we
      // asked it for its runtime.
      std::chrono::duration<double> deltaRuntimeKM = runtimeKM - q->second.m_lastRuntimeKM;
      std::chrono::duration<double> deltaRuntimeUM = runtimeUM - q->second.m_lastRuntimeUM;

      // Update timing values:
      q->second.m_lastRuntimeKM = runtimeKM;
      q->second.m_lastRuntimeUM = runtimeUM;

      // Broadcast current thread utilization
      int contextID = ResolveContextID(thread->GetContext().get());
      std::string name = typeid(*thread.get()).name();

      std::chrono::duration<double> periodDbl = period;
      double kmPercent = 100.0 * (deltaRuntimeKM.count() / periodDbl.count());
      double umPercent = 100.0 * (deltaRuntimeUM.count() / periodDbl.count());

      // Make sure user + kernel percent < 100.0
      umPercent = std::min(umPercent, 99.9 - kmPercent);

      if (kmPercent >= 0.0 && umPercent >= 0.0) {
        BroadcastMessage("threadUtilization", contextID, name, kmPercent, umPercent);
      }

      // Next!
      q++;
    }

    // Poll again after "period" milliseconds
    PollThreadUtilization(period);
  };
}
<|endoftext|>