<commit_before>#include <list>
#include "vmmethod.hpp"

namespace rubinius {
namespace jit {
  class CFGBlock {
  public:
    typedef std::list<CFGBlock*> List;

  private:
    int start_ip_;
    int end_ip_;
    List children_;
    bool loop_;
    bool detached_;
    CFGBlock* exception_handler_;
    int exception_type_;

  public:
    CFGBlock(int start, bool loop=false)
      : start_ip_(start)
      , end_ip_(0)
      , loop_(loop)
      , detached_(true)
      , exception_handler_(0)
      , exception_type_(-1)
    {}

    int start_ip() {
      return start_ip_;
    }

    void set_end_ip(int ip) {
      end_ip_ = ip;
    }

    void add_child(CFGBlock* block) {
      if(block->detached_p()) {
        block->attached();
        children_.push_back(block);
      }
    }

    void attached() {
      detached_ = false;
    }

    bool detached_p() {
      return detached_;
    }

    bool loop_p() {
      return loop_;
    }

    CFGBlock* exception_handler() {
      return exception_handler_;
    }

    void set_exception_handler(CFGBlock* blk) {
      exception_handler_ = blk;
    }

    int exception_type() {
      return exception_type_;
    }

    void set_exception_type(int type) {
      exception_type_ = type;
    }
  };

  class CFGCalculator {
  public:
    typedef std::map<opcode, CFGBlock*> Blocks;

  private:
    Blocks blocks_;
    CFGBlock* root_;
    CFGBlock* current_;
    opcode* stream_;
    size_t stream_size_;

  public:
    CFGCalculator(opcode* stream, size_t size)
      : root_(0)
      , current_(0)
      , stream_(stream)
      , stream_size_(size)
    {}

    CFGCalculator(VMMethod* vmm)
      : root_(0)
      , current_(0)
      , stream_(vmm->opcodes)
      , stream_size_(vmm->total)
    {}

    ~CFGCalculator() {
      for(Blocks::iterator i = blocks_.begin();
          i != blocks_.end();
          i++) {
        delete i->second;
      }
    }

    CFGBlock* root() {
      return root_;
    }

    CFGBlock* find_block(int ip) {
      Blocks::iterator i = blocks_.find(ip);
      if(i == blocks_.end()) return 0;
      return i->second;
    }

    void set_block(int ip, CFGBlock* blk) {
      assert(!blocks_[ip]);
      blocks_[ip] = blk;
    }

    CFGBlock* add_block(int ip, bool loop=false) {
      CFGBlock* blk = find_block(ip);
      if(blk) {
        // If we hit a block that is the start of a loop header,
        // be sure to set it's exception handler. These blocks are created
        // during the first pass.
        if(blk->loop_p()) {
          // Inherit the current exception handler
          blk->set_exception_handler(current_->exception_handler());
        }
        return blk;
      }

      blk = new CFGBlock(ip, loop);

      // Inherit the current exception handler
      blk->set_exception_handler(current_->exception_handler());

      set_block(ip, blk);
      return blk;
    }

    void find_backward_gotos() {
      VMMethod::Iterator iter(stream_, stream_size_);

      while(!iter.end()) {
        switch(iter.op()) {
        case InstructionSequence::insn_goto:
        case InstructionSequence::insn_goto_if_true:
        case InstructionSequence::insn_goto_if_false:
          if(iter.operand1() < iter.position()) {
            if(!find_block(iter.operand1())) {
              CFGBlock* blk = new CFGBlock(iter.operand1(), true);
              set_block(iter.operand1(), blk);
            }
          }
          break;
        }

        iter.inc();
      }
    }

    void close_current(VMMethod::Iterator& iter, CFGBlock* next) {
      current_->set_end_ip(iter.position());
      current_->add_child(next);
      current_ = next;
    }

    CFGBlock* start_new_block(VMMethod::Iterator& iter) {
      if(!iter.last_instruction()) {
        CFGBlock* blk = add_block(iter.next_position());
        close_current(iter, blk);
        return blk;
      }

      return 0;
    }

    void build() {
      find_backward_gotos();

      // Construct the root block specially.
      if(blocks_[0]) {
        root_ = blocks_[0];
      } else {
        root_ = new CFGBlock(0);
        blocks_[0] = root_;
      }

      current_ = root_;

      VMMethod::Iterator iter(stream_, stream_size_);
      for(;;) {
        if(CFGBlock* next_block = find_block(iter.position())) {
          if(next_block->loop_p() && current_ != next_block) {
            // The handler wasn't setup originally, so we have to set it now.
            next_block->set_exception_handler(current_->exception_handler());

            close_current(iter, next_block);
          } else {
            current_ = next_block;
          }
        }

        switch(iter.op()) {
        case InstructionSequence::insn_goto:
        case InstructionSequence::insn_goto_if_true:
        case InstructionSequence::insn_goto_if_false:
          if(iter.operand1() > iter.position()) {
            current_->add_child(add_block(iter.operand1()));
            start_new_block(iter);
          } else {
#ifndef NDEBUG
            CFGBlock* loop_header = find_block(iter.operand1());
            assert(loop_header);
            assert(loop_header->exception_handler() == current_->exception_handler());
#endif
          }
          break;

        case InstructionSequence::insn_setup_unwind: {
          assert(iter.operand1() > iter.position());
          CFGBlock* handler = add_block(iter.operand1());
          handler->set_exception_type(iter.operand2());

          current_->add_child(handler);

          CFGBlock* body = start_new_block(iter);
          assert(body); // make sure it's not at the end.

          body->set_exception_handler(handler);
          break;
        }
        case InstructionSequence::insn_pop_unwind: {
          assert(current_->exception_handler());
          CFGBlock* cont = start_new_block(iter);
          CFGBlock* current_handler = cont->exception_handler();
          assert(current_handler);

          // Effectively pop the current handler by setting the
          // blocks handler (and thus all blocks after it) to the current
          // handlers handler.
          cont->set_exception_handler(current_handler->exception_handler());
          break;
        }

        case InstructionSequence::insn_ensure_return:
        case InstructionSequence::insn_raise_exc:
        case InstructionSequence::insn_raise_return:
        case InstructionSequence::insn_raise_break:
        case InstructionSequence::insn_reraise:
        case InstructionSequence::insn_ret:
          start_new_block(iter);
          break;
        }

        if(!iter.advance()) break;
      }

      current_->set_end_ip(iter.position());
    }
  };
}}
<commit_msg>Fix CFG block calculation bug<commit_after>#include <list>
#include "vmmethod.hpp"

namespace rubinius {
namespace jit {
  class CFGBlock {
  public:
    typedef std::list<CFGBlock*> List;

  private:
    int start_ip_;
    int end_ip_;
    List children_;
    bool loop_;
    bool detached_;
    CFGBlock* exception_handler_;
    int exception_type_;

  public:
    CFGBlock(int start, bool loop=false)
      : start_ip_(start)
      , end_ip_(0)
      , loop_(loop)
      , detached_(true)
      , exception_handler_(0)
      , exception_type_(-1)
    {}

    int start_ip() {
      return start_ip_;
    }

    void set_end_ip(int ip) {
      end_ip_ = ip;
    }

    void add_child(CFGBlock* block) {
      if(block->detached_p()) {
        block->attached();
        children_.push_back(block);
      }
    }

    void attached() {
      detached_ = false;
    }

    bool detached_p() {
      return detached_;
    }

    bool loop_p() {
      return loop_;
    }

    CFGBlock* exception_handler() {
      return exception_handler_;
    }

    void set_exception_handler(CFGBlock* blk) {
      exception_handler_ = blk;
    }

    int exception_type() {
      return exception_type_;
    }

    void set_exception_type(int type) {
      exception_type_ = type;
    }
  };

  class CFGCalculator {
  public:
    typedef std::map<opcode, CFGBlock*> Blocks;

  private:
    Blocks blocks_;
    CFGBlock* root_;
    CFGBlock* current_;
    opcode* stream_;
    size_t stream_size_;

  public:
    CFGCalculator(opcode* stream, size_t size)
      : root_(0)
      , current_(0)
      , stream_(stream)
      , stream_size_(size)
    {}

    CFGCalculator(VMMethod* vmm)
      : root_(0)
      , current_(0)
      , stream_(vmm->opcodes)
      , stream_size_(vmm->total)
    {}

    ~CFGCalculator() {
      for(Blocks::iterator i = blocks_.begin();
          i != blocks_.end();
          i++) {
        delete i->second;
      }
    }

    CFGBlock* root() {
      return root_;
    }

    CFGBlock* find_block(int ip) {
      Blocks::iterator i = blocks_.find(ip);
      if(i == blocks_.end()) return 0;
      return i->second;
    }

    void set_block(int ip, CFGBlock* blk) {
      assert(!blocks_[ip]);
      blocks_[ip] = blk;
    }

    CFGBlock* add_block(int ip, bool loop=false) {
      CFGBlock* blk = find_block(ip);
      if(blk) {
        // If we hit a block that is the start of a loop header,
        // be sure to set it's exception handler. These blocks are created
        // during the first pass.
        if(blk->loop_p()) {
          // Inherit the current exception handler
          blk->set_exception_handler(current_->exception_handler());
        }
        return blk;
      }

      blk = new CFGBlock(ip, loop);

      // Inherit the current exception handler
      blk->set_exception_handler(current_->exception_handler());

      set_block(ip, blk);
      return blk;
    }

    void find_backward_gotos() {
      VMMethod::Iterator iter(stream_, stream_size_);

      while(!iter.end()) {
        switch(iter.op()) {
        case InstructionSequence::insn_goto:
        case InstructionSequence::insn_goto_if_true:
        case InstructionSequence::insn_goto_if_false:
          if(iter.operand1() < iter.position()) {
            if(!find_block(iter.operand1())) {
              CFGBlock* blk = new CFGBlock(iter.operand1(), true);
              set_block(iter.operand1(), blk);
            }
          }
          break;
        }

        iter.inc();
      }
    }

    void close_current(VMMethod::Iterator& iter, CFGBlock* next) {
      current_->set_end_ip(iter.position());
      current_->add_child(next);
      current_ = next;
    }

    CFGBlock* start_new_block(VMMethod::Iterator& iter) {
      if(!iter.last_instruction()) {
        CFGBlock* blk = add_block(iter.next_position());
        close_current(iter, blk);
        return blk;
      }

      return 0;
    }

    void build() {
      find_backward_gotos();

      // Construct the root block specially.
      if(blocks_[0]) {
        root_ = blocks_[0];
      } else {
        root_ = new CFGBlock(0);
        blocks_[0] = root_;
      }

      current_ = root_;

      VMMethod::Iterator iter(stream_, stream_size_);
      for(;;) {
        if(CFGBlock* next_block = find_block(iter.position())) {
          if(next_block->loop_p() && current_ != next_block) {
            // The handler wasn't setup originally, so we have to set it now.
            next_block->set_exception_handler(current_->exception_handler());

            close_current(iter, next_block);
          } else {
            current_ = next_block;
          }
        }

        switch(iter.op()) {
        case InstructionSequence::insn_goto:
        case InstructionSequence::insn_goto_if_true:
        case InstructionSequence::insn_goto_if_false:
          if(iter.operand1() > iter.position()) {
            current_->add_child(add_block(iter.operand1()));
          } else {
#ifndef NDEBUG
            CFGBlock* loop_header = find_block(iter.operand1());
            assert(loop_header);
            assert(loop_header->exception_handler() == current_->exception_handler());
#endif
          }
          start_new_block(iter);
          break;

        case InstructionSequence::insn_setup_unwind: {
          assert(iter.operand1() > iter.position());
          CFGBlock* handler = add_block(iter.operand1());
          handler->set_exception_type(iter.operand2());

          current_->add_child(handler);

          CFGBlock* body = start_new_block(iter);
          assert(body); // make sure it's not at the end.

          body->set_exception_handler(handler);
          break;
        }
        case InstructionSequence::insn_pop_unwind: {
          assert(current_->exception_handler());
          CFGBlock* cont = start_new_block(iter);
          CFGBlock* current_handler = cont->exception_handler();
          assert(current_handler);

          // Effectively pop the current handler by setting the
          // blocks handler (and thus all blocks after it) to the current
          // handlers handler.
          cont->set_exception_handler(current_handler->exception_handler());
          break;
        }

        case InstructionSequence::insn_ensure_return:
        case InstructionSequence::insn_raise_exc:
        case InstructionSequence::insn_raise_return:
        case InstructionSequence::insn_raise_break:
        case InstructionSequence::insn_reraise:
        case InstructionSequence::insn_ret:
          start_new_block(iter);
          break;
        }

        if(!iter.advance()) break;
      }

      current_->set_end_ip(iter.position());
    }
  };
}}
<|endoftext|>


<commit_before>#include "atlas/gl/ErrorCheck.hpp"
#include "atlas/gl/GL.hpp"
#include "atlas/core/Log.hpp"

namespace atlas
{
    namespace gl
    {
        class DebugCallbackSettings
        {
            DebugCallbackSettings() :
                errorSources(ATLAS_GL_ERROR_SOURCE_ALL),
                errorTypes(ATLAS_GL_ERROR_TYPE_ALL),
                errorSeverity(ATLAS_GL_ERROR_SEVERITY_ALL)
            { }

            ~DebugCallbackSettings()
            { }

            DebugCallbackSettings(DebugCallbackSettings&) = delete;
            void operator=(DebugCallbackSettings&) = delete;

        public:
            static DebugCallbackSettings& getInstance()
            {
                static DebugCallbackSettings instance;
                return instance;
            }

            GLuint errorSources;
            GLuint errorTypes;
            GLuint errorSeverity;
        };

        void initializeGLError()
        {
#ifdef ATLAS_DEBUG
            if (glDebugMessageCallback)
            {
                INFO_LOG("OpenGL debug callback available.");
                glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
                glDebugMessageCallback(openGLErrorCallback, nullptr);
                GLuint unusedIds = 0;
                glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE,
                    GL_DONT_CARE, 0, &unusedIds, true);
            }
            else
            {
                INFO_LOG("OpenGL debug callback is not available.");
            }
#else
            INFO_LOG("OpenGL debug callback only available in debug builds.");
#endif
            DebugCallbackSettings::getInstance();
        }

        void setGLErrorSources(GLuint sources)
        {
            DebugCallbackSettings::getInstance().errorSources = sources;
        }

        void setGLErrorTypes(GLuint types)
        {
            DebugCallbackSettings::getInstance().errorTypes = types;
        }

        void setGLErrorSeverity(GLuint severity)
        {

            DebugCallbackSettings::getInstance().errorSeverity = severity;
        }

        void APIENTRY openGLErrorCallback(GLenum source, GLenum type, GLuint id,
            GLenum severity, GLsizei length, const GLchar* message,
            const void* userParam)
        {
            UNUSED(userParam);
            UNUSED(length);

            DebugCallbackSettings& settings =
                DebugCallbackSettings::getInstance();

            std::string errorOrigin;
            switch (source)
            {
            case GL_DEBUG_SOURCE_API:
                if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_API)
                {
                    errorOrigin = "OpenGL API";
                    break;
                }

                return;

            case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
                if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_WINDOW_SYSTEM)
                {
                    errorOrigin = "window system";
                    break;
                }

                return;

            case GL_DEBUG_SOURCE_SHADER_COMPILER:
                if (settings.errorSources &
                    ATLAS_GL_ERROR_SOURCE_SHADER_COMPILER)
                {
                    errorOrigin = "shader compiler";
                    break;
                }

                return;

            case GL_DEBUG_SOURCE_THIRD_PARTY:
                if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_THIRD_PARTY)
                {
                    errorOrigin = "third party";
                    break;
                }

                return;

            case GL_DEBUG_SOURCE_APPLICATION:
                if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_APPLICATION)
                {
                    errorOrigin = "user of application";
                    break;
                }

                return;

            case GL_DEBUG_SOURCE_OTHER:
                if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_OTHER)
                {
                    errorOrigin = "other";
                    break;
                }

                return;
            }

            std::string errorType;
            switch (type)
            {
            case GL_DEBUG_TYPE_ERROR:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_ERROR)
                {
                    errorType = "error";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
                if (settings.errorTypes &
                    ATLAS_GL_ERROR_TYPE_DEPRECATED_BEHAVIOUR)
                {
                    errorType = "deprecated behaviour";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
                if (settings.errorTypes &
                    ATLAS_GL_ERROR_TYPE_UNDEFINED_BEHAVIOUR)
                {
                    errorType = "undefined behaviour";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_PORTABILITY:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PORTABILITY)
                {
                    errorType = "portability";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_PERFORMANCE:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PERFORMANCE)
                {
                    errorType = "performance";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_MARKER:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_MARKER)
                {
                    errorType = "marker";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_PUSH_GROUP:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PUSH_GROUP)
                {
                    errorType = "push group";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_POP_GROUP:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_POP_GROUP)
                {
                    errorType = "pop group";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_OTHER:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_OTHER)
                {
                    errorType = "other";
                    break;
                }

                return;
            }

            std::string errorMessage = "[" + errorType + "] : [" +
                errorOrigin + "] : (" + std::to_string(id) + "): " + message;

            switch (severity)
            {
            case GL_DEBUG_SEVERITY_NOTIFICATION:
                if (settings.errorSeverity &
                    ATLAS_GL_ERROR_SEVERITY_NOTIFICATION)
                {
                    INFO_LOG("OpenGL notification: " + errorMessage);
                }

                break;

            case GL_DEBUG_SEVERITY_LOW:
                if (settings.errorSeverity &
                    ATLAS_GL_ERROR_SEVERITY_LOW)
                {
                    WARN_LOG("OpenGL warning: " + errorMessage);
                }

                break;

            case GL_DEBUG_SEVERITY_MEDIUM:
                if (settings.errorSeverity & ATLAS_GL_ERROR_SEVERITY_MEDIUM)
                {
                    ERROR_LOG("OpenGL error: " + errorMessage);
                }

                break;

            case GL_DEBUG_SEVERITY_HIGH:
                if (settings.errorSeverity & ATLAS_GL_ERROR_SEVERITY_HIGH)
                {
                    CRITICAL_LOG("OpenGL critical error: " + errorMessage);
                }

                break;
            }
        }
    }
}<commit_msg>[brief] Adds a breakpoint on critical OpenGL errors.<commit_after>#include "atlas/gl/ErrorCheck.hpp"
#include "atlas/gl/GL.hpp"
#include "atlas/core/Log.hpp"
#include "atlas/core/Platform.hpp"

#if defined(ATLAS_PLATFORM_WINDOWS) && defined(ATLAS_DEBUG)
#include <intrin.h>
#endif

namespace atlas
{
    namespace gl
    {
        class DebugCallbackSettings
        {
            DebugCallbackSettings() :
                errorSources(ATLAS_GL_ERROR_SOURCE_ALL),
                errorTypes(ATLAS_GL_ERROR_TYPE_ALL),
                errorSeverity(ATLAS_GL_ERROR_SEVERITY_ALL)
            { }

            ~DebugCallbackSettings()
            { }

            DebugCallbackSettings(DebugCallbackSettings&) = delete;
            void operator=(DebugCallbackSettings&) = delete;

        public:
            static DebugCallbackSettings& getInstance()
            {
                static DebugCallbackSettings instance;
                return instance;
            }

            GLuint errorSources;
            GLuint errorTypes;
            GLuint errorSeverity;
        };

        void initializeGLError()
        {
#ifdef ATLAS_DEBUG
            if (glDebugMessageCallback)
            {
                INFO_LOG("OpenGL debug callback available.");
                glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
                glDebugMessageCallback(openGLErrorCallback, nullptr);
                GLuint unusedIds = 0;
                glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE,
                    GL_DONT_CARE, 0, &unusedIds, true);
            }
            else
            {
                INFO_LOG("OpenGL debug callback is not available.");
            }
#else
            INFO_LOG("OpenGL debug callback only available in debug builds.");
#endif
            DebugCallbackSettings::getInstance();
        }

        void setGLErrorSources(GLuint sources)
        {
            DebugCallbackSettings::getInstance().errorSources = sources;
        }

        void setGLErrorTypes(GLuint types)
        {
            DebugCallbackSettings::getInstance().errorTypes = types;
        }

        void setGLErrorSeverity(GLuint severity)
        {

            DebugCallbackSettings::getInstance().errorSeverity = severity;
        }

        void APIENTRY openGLErrorCallback(GLenum source, GLenum type, GLuint id,
            GLenum severity, GLsizei length, const GLchar* message,
            const void* userParam)
        {
            UNUSED(userParam);
            UNUSED(length);

            DebugCallbackSettings& settings =
                DebugCallbackSettings::getInstance();

            std::string errorOrigin;
            switch (source)
            {
            case GL_DEBUG_SOURCE_API:
                if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_API)
                {
                    errorOrigin = "OpenGL API";
                    break;
                }

                return;

            case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
                if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_WINDOW_SYSTEM)
                {
                    errorOrigin = "window system";
                    break;
                }

                return;

            case GL_DEBUG_SOURCE_SHADER_COMPILER:
                if (settings.errorSources &
                    ATLAS_GL_ERROR_SOURCE_SHADER_COMPILER)
                {
                    errorOrigin = "shader compiler";
                    break;
                }

                return;

            case GL_DEBUG_SOURCE_THIRD_PARTY:
                if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_THIRD_PARTY)
                {
                    errorOrigin = "third party";
                    break;
                }

                return;

            case GL_DEBUG_SOURCE_APPLICATION:
                if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_APPLICATION)
                {
                    errorOrigin = "user of application";
                    break;
                }

                return;

            case GL_DEBUG_SOURCE_OTHER:
                if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_OTHER)
                {
                    errorOrigin = "other";
                    break;
                }

                return;
            }

            std::string errorType;
            switch (type)
            {
            case GL_DEBUG_TYPE_ERROR:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_ERROR)
                {
                    errorType = "error";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
                if (settings.errorTypes &
                    ATLAS_GL_ERROR_TYPE_DEPRECATED_BEHAVIOUR)
                {
                    errorType = "deprecated behaviour";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
                if (settings.errorTypes &
                    ATLAS_GL_ERROR_TYPE_UNDEFINED_BEHAVIOUR)
                {
                    errorType = "undefined behaviour";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_PORTABILITY:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PORTABILITY)
                {
                    errorType = "portability";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_PERFORMANCE:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PERFORMANCE)
                {
                    errorType = "performance";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_MARKER:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_MARKER)
                {
                    errorType = "marker";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_PUSH_GROUP:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PUSH_GROUP)
                {
                    errorType = "push group";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_POP_GROUP:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_POP_GROUP)
                {
                    errorType = "pop group";
                    break;
                }

                return;

            case GL_DEBUG_TYPE_OTHER:
                if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_OTHER)
                {
                    errorType = "other";
                    break;
                }

                return;
            }

            std::string errorMessage = "[" + errorType + "] : [" +
                errorOrigin + "] : (" + std::to_string(id) + "): " + message;

            switch (severity)
            {
            case GL_DEBUG_SEVERITY_NOTIFICATION:
                if (settings.errorSeverity &
                    ATLAS_GL_ERROR_SEVERITY_NOTIFICATION)
                {
                    INFO_LOG("OpenGL notification: " + errorMessage);
                }

                break;

            case GL_DEBUG_SEVERITY_LOW:
                if (settings.errorSeverity &
                    ATLAS_GL_ERROR_SEVERITY_LOW)
                {
                    WARN_LOG("OpenGL warning: " + errorMessage);
                }

                break;

            case GL_DEBUG_SEVERITY_MEDIUM:
                if (settings.errorSeverity & ATLAS_GL_ERROR_SEVERITY_MEDIUM)
                {
                    ERROR_LOG("OpenGL error: " + errorMessage);
                }

                break;

            case GL_DEBUG_SEVERITY_HIGH:
                if (settings.errorSeverity & ATLAS_GL_ERROR_SEVERITY_HIGH)
                {
                    CRITICAL_LOG("OpenGL critical error: " + errorMessage);
                }
#if defined(ATLAS_DEBUG) && defined(ATLAS_PLATFORM_WINDOWS)
                __debugbreak();
#endif

                break;
            }
        }
    }
}<|endoftext|>


<commit_before>// Copyright (c) 2014-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chainparams.h>
#include <net.h>
#include <signet.h>
#include <validation.h>

#include <test/util/setup_common.h>

#include <boost/signals2/signal.hpp>
#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(validation_tests, TestingSetup)

static void TestBlockSubsidyHalvings(const CChainParams& chainParams)
{
    const Consensus::Params& consensusParams = chainParams.GetConsensus();
    int maxHalvings = 64;
    CAmount nInitialSubsidy = 50 * COIN;

    CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0
    BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2);
    for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) {
        int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval;
        CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams);
        BOOST_CHECK(nSubsidy <= nInitialSubsidy);
        BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2);
        nPreviousSubsidy = nSubsidy;
    }
    BOOST_CHECK_EQUAL(GetBlockSubsidy(maxHalvings * consensusParams.nSubsidyHalvingInterval, chainParams), 0);
}

static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval)
{
    Consensus::Params consensusParams;
    consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval;
    TestBlockSubsidyHalvings(consensusParams);
}

BOOST_AUTO_TEST_CASE(block_subsidy_test)
{
    const auto chainParams = CreateChainParams(*m_node.args, CBaseChainParams::MAIN);
    TestBlockSubsidyHalvings(chainParams->GetConsensus()); // As in main
    TestBlockSubsidyHalvings(150); // As in regtest
    TestBlockSubsidyHalvings(1000); // Just another interval
}

BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
    const auto chainParams = CreateChainParams(*m_node.args, CBaseChainParams::MAIN);
    CAmount nSum = 0;
    for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) {
        CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams);
        BOOST_CHECK(nSubsidy <= 50 * COIN);
        nSum += nSubsidy * 1000;
        BOOST_CHECK(MoneyRange(nSum));
    }
    BOOST_CHECK_EQUAL(nSum, CAmount{2099999997690000});
}

BOOST_AUTO_TEST_CASE(signet_parse_tests)
{
    ArgsManager signet_argsman;
    signet_argsman.ForceSetArg("-signetchallenge", "51"); // set challenge to OP_TRUE
    const auto signet_params = CreateChainParams(signet_argsman, CBaseChainParams::SIGNET);
    CBlock block;
    BOOST_CHECK(signet_params->GetConsensus().signet_challenge == std::vector<uint8_t>{{OP_TRUE}});
    CScript challenge{OP_TRUE};

    // empty block is invalid
    BOOST_CHECK(!SignetTxs::Create(block, challenge));
    BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // no witness commitment
    CMutableTransaction cb;
    cb.vout.emplace_back(0, CScript{});
    block.vtx.push_back(MakeTransactionRef(cb));
    block.vtx.push_back(MakeTransactionRef(cb)); // Add dummy tx to excercise merkle root code
    BOOST_CHECK(!SignetTxs::Create(block, challenge));
    BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // no header is treated valid
    std::vector<uint8_t> witness_commitment_section_141{0xaa, 0x21, 0xa9, 0xed};
    for (int i = 0; i < 32; ++i) {
        witness_commitment_section_141.push_back(0xff);
    }
    cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141;
    block.vtx.at(0) = MakeTransactionRef(cb);
    BOOST_CHECK(SignetTxs::Create(block, challenge));
    BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // no data after header, valid
    std::vector<uint8_t> witness_commitment_section_325{0xec, 0xc7, 0xda, 0xa2};
    cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
    block.vtx.at(0) = MakeTransactionRef(cb);
    BOOST_CHECK(SignetTxs::Create(block, challenge));
    BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // Premature end of data, invalid
    witness_commitment_section_325.push_back(0x01);
    witness_commitment_section_325.push_back(0x51);
    cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
    block.vtx.at(0) = MakeTransactionRef(cb);
    BOOST_CHECK(!SignetTxs::Create(block, challenge));
    BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // has data, valid
    witness_commitment_section_325.push_back(0x00);
    cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
    block.vtx.at(0) = MakeTransactionRef(cb);
    BOOST_CHECK(SignetTxs::Create(block, challenge));
    BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // Extraneous data, invalid
    witness_commitment_section_325.push_back(0x00);
    cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
    block.vtx.at(0) = MakeTransactionRef(cb);
    BOOST_CHECK(!SignetTxs::Create(block, challenge));
    BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));
}

static bool ReturnFalse() { return false; }
static bool ReturnTrue() { return true; }

BOOST_AUTO_TEST_CASE(test_combiner_all)
{
    boost::signals2::signal<bool (), CombinerAll> Test;
    BOOST_CHECK(Test());
    Test.connect(&ReturnFalse);
    BOOST_CHECK(!Test());
    Test.connect(&ReturnTrue);
    BOOST_CHECK(!Test());
    Test.disconnect(&ReturnFalse);
    BOOST_CHECK(Test());
    Test.disconnect(&ReturnTrue);
    BOOST_CHECK(Test());
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>refactor: fix -Wbraced-scalar-init warning in validation tests<commit_after>// Copyright (c) 2014-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chainparams.h>
#include <net.h>
#include <signet.h>
#include <validation.h>

#include <test/util/setup_common.h>

#include <boost/signals2/signal.hpp>
#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(validation_tests, TestingSetup)

static void TestBlockSubsidyHalvings(const CChainParams& chainParams)
{
    const Consensus::Params& consensusParams = chainParams.GetConsensus();
    int maxHalvings = 64;
    CAmount nInitialSubsidy = 50 * COIN;

    CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0
    BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2);
    for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) {
        int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval;
        CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams);
        BOOST_CHECK(nSubsidy <= nInitialSubsidy);
        BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2);
        nPreviousSubsidy = nSubsidy;
    }
    BOOST_CHECK_EQUAL(GetBlockSubsidy(maxHalvings * consensusParams.nSubsidyHalvingInterval, chainParams), 0);
}

static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval)
{
    Consensus::Params consensusParams;
    consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval;
    TestBlockSubsidyHalvings(consensusParams);
}

BOOST_AUTO_TEST_CASE(block_subsidy_test)
{
    const auto chainParams = CreateChainParams(*m_node.args, CBaseChainParams::MAIN);
    TestBlockSubsidyHalvings(chainParams->GetConsensus()); // As in main
    TestBlockSubsidyHalvings(150); // As in regtest
    TestBlockSubsidyHalvings(1000); // Just another interval
}

BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
    const auto chainParams = CreateChainParams(*m_node.args, CBaseChainParams::MAIN);
    CAmount nSum = 0;
    for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) {
        CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams);
        BOOST_CHECK(nSubsidy <= 50 * COIN);
        nSum += nSubsidy * 1000;
        BOOST_CHECK(MoneyRange(nSum));
    }
    BOOST_CHECK_EQUAL(nSum, CAmount{2099999997690000});
}

BOOST_AUTO_TEST_CASE(signet_parse_tests)
{
    ArgsManager signet_argsman;
    signet_argsman.ForceSetArg("-signetchallenge", "51"); // set challenge to OP_TRUE
    const auto signet_params = CreateChainParams(signet_argsman, CBaseChainParams::SIGNET);
    CBlock block;
    BOOST_CHECK(signet_params->GetConsensus().signet_challenge == std::vector<uint8_t>{OP_TRUE});
    CScript challenge{OP_TRUE};

    // empty block is invalid
    BOOST_CHECK(!SignetTxs::Create(block, challenge));
    BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // no witness commitment
    CMutableTransaction cb;
    cb.vout.emplace_back(0, CScript{});
    block.vtx.push_back(MakeTransactionRef(cb));
    block.vtx.push_back(MakeTransactionRef(cb)); // Add dummy tx to excercise merkle root code
    BOOST_CHECK(!SignetTxs::Create(block, challenge));
    BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // no header is treated valid
    std::vector<uint8_t> witness_commitment_section_141{0xaa, 0x21, 0xa9, 0xed};
    for (int i = 0; i < 32; ++i) {
        witness_commitment_section_141.push_back(0xff);
    }
    cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141;
    block.vtx.at(0) = MakeTransactionRef(cb);
    BOOST_CHECK(SignetTxs::Create(block, challenge));
    BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // no data after header, valid
    std::vector<uint8_t> witness_commitment_section_325{0xec, 0xc7, 0xda, 0xa2};
    cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
    block.vtx.at(0) = MakeTransactionRef(cb);
    BOOST_CHECK(SignetTxs::Create(block, challenge));
    BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // Premature end of data, invalid
    witness_commitment_section_325.push_back(0x01);
    witness_commitment_section_325.push_back(0x51);
    cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
    block.vtx.at(0) = MakeTransactionRef(cb);
    BOOST_CHECK(!SignetTxs::Create(block, challenge));
    BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // has data, valid
    witness_commitment_section_325.push_back(0x00);
    cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
    block.vtx.at(0) = MakeTransactionRef(cb);
    BOOST_CHECK(SignetTxs::Create(block, challenge));
    BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));

    // Extraneous data, invalid
    witness_commitment_section_325.push_back(0x00);
    cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
    block.vtx.at(0) = MakeTransactionRef(cb);
    BOOST_CHECK(!SignetTxs::Create(block, challenge));
    BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));
}

static bool ReturnFalse() { return false; }
static bool ReturnTrue() { return true; }

BOOST_AUTO_TEST_CASE(test_combiner_all)
{
    boost::signals2::signal<bool (), CombinerAll> Test;
    BOOST_CHECK(Test());
    Test.connect(&ReturnFalse);
    BOOST_CHECK(!Test());
    Test.connect(&ReturnTrue);
    BOOST_CHECK(!Test());
    Test.disconnect(&ReturnFalse);
    BOOST_CHECK(Test());
    Test.disconnect(&ReturnTrue);
    BOOST_CHECK(Test());
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/**
 * @file persistence_dat.cpp
 *
 * @brief Purpose: Contains methods to save the game
 *
 * MIT License
 * Copyright (c) 2017 MindScape
 *
 * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
 *
 */
#include "persistence_dat.hpp"
#include "../engine/include/log.hpp"
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stack>

using namespace engine;

PersistenceDat *PersistenceDat::instance = 0;

/**
 * @brief Get Instance
 *
 * Method responsible for get instance
 *
 * @return void
 */
PersistenceDat *PersistenceDat::get_instance(){
	if (!instance) {
		instance = nullptr;
	}
	else {
		/*Do nothing*/
	}

	instance = new PersistenceDat();

	return instance;
}

/**
 * @brief Dump Method
 *
 * Method responsible for dump
 *
 * @param path path to save the open game in a file
 * @param data saved game
 * @return void
 */
bool PersistenceDat::dump(std::string path, PersistenceMap * data){
	std::ofstream save_file;
	save_file.open(path);

	/* Opens the file to be written */
	if (save_file.is_open()) {
		for (auto it = data->begin(); it < data->end(); it++) {

			/* Writes persistence datas in opened file */
			for (auto each_data : *it) {
				save_file << each_data.first << " " << each_data.second << " ";
			}

			save_file << std::endl;
		}
	}
	else {
		INFO("Unable to open file");

		return false;
	}

	save_file.close();

	return true;
}

/**
 * @brief Load Method
 *
 * Method responsible for load the saved game
 *
 * @param p_path path to saved game
 * @return game loaded
 */
PersistenceMap * PersistenceDat::load(std::string p_path){
	PersistenceMap *data = nullptr;
	data = new PersistenceMap();

	std::stack<std::string> paths;
	paths.push(p_path);
	std::string line = "";

	/* Reads the complete file */
	while(!paths.empty()){
		std::string path = paths.top();
		paths.pop();
		std::ifstream save_file;
		save_file.open(path, std::ifstream::in);

		/* Opens the file to be written */
		if (save_file.is_open()){

			/* Writes the opened file with game datas*/
			while (std::getline(save_file,line)){
				bool is_include = false;
				std::istringstream iss(line);
				std::string key = "";
				std::string value = "";
				std::unordered_map<std::string, std::string> object_data;

				/* If the line are empty or the line initialize with comment tag */
				if (line != "" && line[0] != '#'){
					while(iss >> key && iss >> value){

						/* Writes persistence values in opened file */
						if ((is_include = (key == "include"))) {
							paths.push(value);
						}
						else {
							/* Do nothing */
						}

						object_data[key] = value;
					}

					if (!is_include) {
						data->insert_object(object_data);
					}
					else {
				        /* Do nothing */
				    }
				}
				else {
		        	INFO("The file was opened incorrectly");
			    }
			}
		}
		else {
			INFO("Unable to open file");
			return NULL;
		}
	}

	return data;
}
<commit_msg>[DECOMPOSITION] Applies technique in persistence_dat<commit_after>/**
 * @file persistence_dat.cpp
 *
 * @brief Purpose: Contains methods to save the game
 *
 * MIT License
 * Copyright (c) 2017 MindScape
 *
 * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
 *
 */
#include "persistence_dat.hpp"
#include "../engine/include/log.hpp"
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stack>

using namespace engine;

PersistenceDat *PersistenceDat::instance = 0; /**< Instance. Instance of the game */

void write_file(std::stack<std::string> paths, PersistenceMap *data, std::string line);

/**
 * @brief Get Instance
 *
 * Method responsible for get instance
 *
 * @return void
 */
PersistenceDat *PersistenceDat::get_instance(){
	if (!instance) {
		instance = nullptr;
	}
	else {
		/*Do nothing*/
	}

	instance = new PersistenceDat();

	return instance;
}

/**
 * @brief Dump Method
 *
 * Method responsible for dump
 *
 * @param path path to save the open game in a file
 * @param data saved game
 * @return void
 */
bool PersistenceDat::dump(std::string path, PersistenceMap * data){
	std::ofstream save_file; /**< ofstream. Output stream class to operate on file */
	save_file.open(path);

	/* Opens the file to be written */
	if (save_file.is_open()) {
		for (auto it = data->begin(); it < data->end(); it++) {

			/* Writes persistence datas in opened file */
			for (auto each_data : *it) {
				save_file << each_data.first << " " << each_data.second << " ";
			}

			save_file << std::endl;
		}
	}
	else {
		INFO("Unable to open file");

		return false;
	}

	save_file.close();

	return true;
}

/**
 * @brief Load Method
 *
 * Method responsible for load the saved game
 *
 * @param p_path path to saved game
 * @return game loaded
 */
PersistenceMap * PersistenceDat::load(std::string p_path){
	PersistenceMap *data = nullptr; /**< PersistenceMap. Map states */
	data = new PersistenceMap();

	std::stack<std::string> paths; /**< string. path name */

	paths.push(p_path);
	std::string line = "";

	/* Reads the complete file */
	while(!paths.empty()){
		std::string path = paths.top(); /**< string. path name */
		std::ifstream save_file; /**< ifstream. Input stream class to operate on files */

		paths.pop();
		save_file.open(path, std::ifstream::in);

		/* Opens the file to be written */
		if (save_file.is_open()){

			/* Writes the opened file with game datas*/
			while (std::getline(save_file, line)){
				/* If the line isn't empty or the line doesn't initialize with comment tag */
				if (line != "" && line[0] != '#'){
					write_file(paths, data, line);
				}
				else {
		        	INFO("The file was opened incorrectly");
			    }
			}
		}
		else {
			INFO("Unable to open file");
			return NULL;
		}
	}

	return data;
}

/**
 * @brief Writes in file
 *
 * This function allows writes the data in the files
 *
 * @param paths. Name of the path will be write.
 * @param data. Map states.
 * @param line. line that will be written in the file.
 * @return void.
 */
void write_file(std::stack<std::string> paths,
	 PersistenceMap *data, std::string line){

	bool is_include = false;
	std::string key = ""; /**< string. Access key */
	std::string value = ""; /**< string. Data values */

	std::istringstream iss(line); /**< istringstream. Input stream class to operate on strings. */
	std::unordered_map<std::string, std::string> object_data; /**< object of the dada */

	while(iss >> key && iss >> value){
		/* Writes persistence values in opened file */
		if (is_include = (key == "include")) {
			/* If it's to write in the file */

			paths.push(value);
		}
		else {
			/* Do nothing */
		}

		object_data[key] = value;
	}

	if (!is_include) {
		/* If it isn't to write in the file and save the object datas */

		data->insert_object(object_data);
	}
	else {
		/* Do nothing */
	}
}
<|endoftext|>


<commit_before>/*
 ***********************************************************************************************************************
 *
 *  Copyright (c) 2020 Advanced Micro Devices, Inc. All Rights Reserved.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 *
 **********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file  llpcGfxRegHandler.cpp
* @brief LLPC source file: Implementation of LLPC utility class GfxRegHandler
***********************************************************************************************************************
*/
#include "llpcGfxRegHandler.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"

using namespace lgc;
using namespace llvm;

// =====================================================================================================================
GfxRegHandler::GfxRegHandler(
    Builder* pBuilder,  // [in] The builder handle
    Value*   pRegister) // [in] The registered target vec <n x i32>
    :
    GfxRegHandlerBase(pBuilder, pRegister)
{
    m_pOne = pBuilder->getInt32(1);
}

// =====================================================================================================================
// Common function for getting the current value for the hardware register
Value* GfxRegHandler::GetRegCommon(
    uint32_t regId) // The register ID, which is the index of BitsInfo and BitsState
{
    // Under two condition, we need to fetch the range of bits
    //  - The register has not being initialized
    //  - The register is being modified
    if ((m_pBitsState[regId].pValue == nullptr) ||
        (m_pBitsState[regId].isModified))
    {
        // Fetch bits according to BitsInfo
        m_pBitsState[regId].pValue = GetBits(m_pBitsInfo[regId]);
    }

    // Since the specified range of bits is cached, set it unmodified
    m_pBitsState[regId].isModified = 0;

    // Return the cached value
    return m_pBitsState[regId].pValue;
}

// =====================================================================================================================
// Get combined data from two seperate DWORDs
// Note: The return type is one DWORD, it doesn't support two DWORDs for now.
// TODO: Expand to support 2-DWORDs combination result.
Value* GfxRegHandler::GetRegCombine(
    uint32_t regIdLo, // The ID of low part register
    uint32_t regIdHi) // Reg ID of high part register
{
    Value* pRegValueLo = GetRegCommon(regIdLo);
    Value* pRegValueHi = GetRegCommon(regIdHi);
    return m_pBuilder->CreateOr(m_pBuilder->CreateShl(pRegValueHi, m_pBitsInfo[regIdLo].offset), pRegValueLo);
}

// =====================================================================================================================
// Set register value into two seperate DWORDs
// Note: The input pRegValue only supports one DWORD
void GfxRegHandler::SetRegCombine(
    uint32_t regIdLo,   // The ID of low part register
    uint32_t regIdHi,   // Reg ID of high part register
    Value*   pRegValue) // [in] Data used for setting
{
    Value* pRegValueLo = m_pBuilder->CreateIntrinsic(Intrinsic::amdgcn_ubfe,
                                                     m_pBuilder->getInt32Ty(),
                                                     { pRegValue,
                                                       m_pBuilder->getInt32(0),
                                                       m_pBuilder->getInt32(m_pBitsInfo[regIdLo].offset) });

    Value* pRegValueHi = m_pBuilder->CreateLShr(pRegValue, m_pBuilder->getInt32(m_pBitsInfo[regIdLo].offset));

    SetRegCommon(regIdLo, pRegValueLo);
    SetRegCommon(regIdHi, pRegValueHi);
}

// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx9-10)
// Refer to imported/chip/gfx9/gfx9_plus_merged_registers.h : SQ_IMG_SAMP_WORD
static constexpr BitsInfo SqImgSampRegBitsGfx9[static_cast<uint32_t>(SqSampRegs::Count)] =
{
    { 0, 30, 2 }, // FilterMode
    { 2, 20, 2 }, // XyMagFilter
    { 2, 22, 2 }, // XyMinFilter
};

// =====================================================================================================================
// Helper class for handling Registers defined in SQ_IMG_SAMP_WORD
SqImgSampRegHandler::SqImgSampRegHandler(
    Builder*      pBuilder,      // [in] Bound builder context
    Value*        pRegister,     // [in] Bound register vec <n x i32>
    GfxIpVersion* pGfxIpVersion) // [in] Target GFX IP version
    :
    GfxRegHandler(pBuilder, pRegister)
{
    m_pGfxIpVersion = pGfxIpVersion;

    switch (pGfxIpVersion->major)
    {
    case 9:
    case 10:
        m_pBitsInfo = SqImgSampRegBitsGfx9;
        break;
    default:
        llvm_unreachable("GFX IP is not supported!");
        break;
    }
    SetBitsState(m_pBitsState);
}

// =====================================================================================================================
// Get the current value for the hardware register
Value* SqImgSampRegHandler::GetReg(
    SqSampRegs regId) // Register ID
{
    switch (regId)
    {
    case SqSampRegs::FilterMode:
    case SqSampRegs::xyMagFilter:
    case SqSampRegs::xyMinFilter:
        return GetRegCommon(static_cast<uint32_t>(regId));
    default:
        // TODO: More will be implemented.
        llvm_unreachable("Not implemented!");
        break;
    }
    return nullptr;
}

// =====================================================================================================================
// Set the current value for the hardware register
void SqImgSampRegHandler::SetReg(
    SqSampRegs regId,      // Register ID
    Value*     pRegValue ) // [in] Value to set to this register
{
    switch (regId)
    {
    case SqSampRegs::FilterMode:
    case SqSampRegs::xyMagFilter:
    case SqSampRegs::xyMinFilter:
        SetRegCommon(static_cast<uint32_t>(regId), pRegValue);
        break;
    default:
        llvm_unreachable("Set \"IsTileOpt\" is not allowed!");
        break;
    }
}

// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx9)
// Refer to imported/chip/gfx9/gfx9_plus_merged_registers.h : SQ_IMG_RSRC_WORD
static constexpr BitsInfo SqImgRsrcRegBitsGfx9[static_cast<uint32_t>(SqRsrcRegs::Count)] =
{
    { 0,  0, 32 }, // BaseAddress
    { 1,  0,  8 }, // BaseAddressHi
    { 1, 20,  9 }, // Format
    { 2,  0, 14 }, // Width
    { 2, 14, 14 }, // Height
    { 3,  0, 12 }, // DstSelXYZW
    { 3, 20,  5 }, // IsTileOpt
    { 4,  0, 13 }, // Depth
    { 4, 13, 12 }, // Pitch
    { 4, 29,  3 }, // BcSwizzle
    {},            // WidthLo
    {},            // WidthHi
};

// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx10)
// TODO: update comment when the registers file is available
static constexpr BitsInfo SqImgRsrcRegBitsGfx10[static_cast<uint32_t>(SqRsrcRegs::Count)] =
{
    { 0,  0, 32 }, // BaseAddress
    { 1,  0,  8 }, // BaseAddressHi
    { 1, 20,  9 }, // Format
    {},            // Width
    { 2, 14, 16 }, // Height
    { 3,  0, 12 }, // DstSelXYZW
    { 3, 20,  5 }, // IsTileOpt
    { 4,  0, 16 }, // Depth
    {},            // Pitch
    { 3, 25,  3 }, // BcSwizzle
    { 1, 30,  2 }, // WidthLo
    { 2,  0, 14 }, // WidthHi
};

// =====================================================================================================================
// Helper class for handling Registers defined in SQ_IMG_RSRC_WORD
SqImgRsrcRegHandler::SqImgRsrcRegHandler(
    Builder*      pBuilder,      // [in] Bound builder context
    Value*        pRegister,     // [in] Bound register vec <n x i32>
    GfxIpVersion* pGfxIpVersion) // [in] Current GFX IP version
    :
    GfxRegHandler(pBuilder, pRegister)
{
    m_pGfxIpVersion = pGfxIpVersion;

    switch (pGfxIpVersion->major)
    {
    case 9:
        m_pBitsInfo = SqImgRsrcRegBitsGfx9;
        break;
    case 10:
        m_pBitsInfo = SqImgRsrcRegBitsGfx10;
        break;
    default:
        llvm_unreachable("GFX IP is not supported!");
        break;
    }
    SetBitsState(m_pBitsState);
}

// =====================================================================================================================
// Get the current value for the hardware register
Value* SqImgRsrcRegHandler::GetReg(
    SqRsrcRegs regId) // Register ID
{
    switch (regId)
    {
    case SqRsrcRegs::BaseAddress:
    case SqRsrcRegs::Format:
    case SqRsrcRegs::DstSelXYZW:
    case SqRsrcRegs::Depth:
    case SqRsrcRegs::BcSwizzle:
        return GetRegCommon(static_cast<uint32_t>(regId));
    case SqRsrcRegs::Height:
    case SqRsrcRegs::Pitch:
        return m_pBuilder->CreateAdd(GetRegCommon(static_cast<uint32_t>(regId)), m_pOne);
    case SqRsrcRegs::Width:
        switch (m_pGfxIpVersion->major)
        {
        case 9:
            return m_pBuilder->CreateAdd(GetRegCommon(static_cast<uint32_t>(regId)), m_pOne);
        case 10:
            return m_pBuilder->CreateAdd(GetRegCombine(static_cast<uint32_t>(SqRsrcRegs::WidthLo),
                                                       static_cast<uint32_t>(SqRsrcRegs::WidthHi)),
                                                       m_pOne);
        default:
            llvm_unreachable("GFX IP is not supported!");
            break;
        }
    case SqRsrcRegs::IsTileOpt:
        return m_pBuilder->CreateICmpNE(GetRegCommon(static_cast<uint32_t>(regId)), m_pBuilder->getInt32(0));
    default:
        // TODO: More will be implemented.
        llvm_unreachable("Not implemented!");
    }
    return nullptr;
}

// =====================================================================================================================
// Set the current value for the hardware register
void SqImgRsrcRegHandler::SetReg(
    SqRsrcRegs regId,      // Register ID
    Value*     pRegValue)  // [in] Value to set to this register
{
    switch (regId)
    {
    case SqRsrcRegs::BaseAddress:
    case SqRsrcRegs::BaseAddressHi:
    case SqRsrcRegs::Format:
    case SqRsrcRegs::DstSelXYZW:
    case SqRsrcRegs::Depth:
    case SqRsrcRegs::BcSwizzle:
        SetRegCommon(static_cast<uint32_t>(regId), pRegValue);
        break;
    case SqRsrcRegs::Height:
    case SqRsrcRegs::Pitch:
        SetRegCommon(static_cast<uint32_t>(regId), m_pBuilder->CreateSub(pRegValue, m_pOne));
        break;
    case SqRsrcRegs::Width:
        switch (m_pGfxIpVersion->major)
        {
        case 9:
            SetRegCommon(static_cast<uint32_t>(regId), m_pBuilder->CreateSub(pRegValue, m_pOne));
            break;
        case 10:
            SetRegCombine(static_cast<uint32_t>(SqRsrcRegs::WidthLo),
                          static_cast<uint32_t>(SqRsrcRegs::WidthHi),
                          m_pBuilder->CreateSub(pRegValue, m_pOne));
            break;
        default:
            llvm_unreachable("GFX IP is not supported!");
            break;
        }
        break;
    case SqRsrcRegs::IsTileOpt:
        llvm_unreachable("Set \"IsTileOpt\" is not allowed!");
        break;
    }
}
<commit_msg>Fixed GfxRegHandler clang compile error<commit_after>/*
 ***********************************************************************************************************************
 *
 *  Copyright (c) 2020 Advanced Micro Devices, Inc. All Rights Reserved.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 *
 **********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file  llpcGfxRegHandler.cpp
* @brief LLPC source file: Implementation of LLPC utility class GfxRegHandler
***********************************************************************************************************************
*/
#include "llpcGfxRegHandler.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"

using namespace lgc;
using namespace llvm;

// =====================================================================================================================
GfxRegHandler::GfxRegHandler(
    Builder* pBuilder,  // [in] The builder handle
    Value*   pRegister) // [in] The registered target vec <n x i32>
    :
    GfxRegHandlerBase(pBuilder, pRegister)
{
    m_pOne = pBuilder->getInt32(1);
}

// =====================================================================================================================
// Common function for getting the current value for the hardware register
Value* GfxRegHandler::GetRegCommon(
    uint32_t regId) // The register ID, which is the index of BitsInfo and BitsState
{
    // Under two condition, we need to fetch the range of bits
    //  - The register has not being initialized
    //  - The register is being modified
    if ((m_pBitsState[regId].pValue == nullptr) ||
        (m_pBitsState[regId].isModified))
    {
        // Fetch bits according to BitsInfo
        m_pBitsState[regId].pValue = GetBits(m_pBitsInfo[regId]);
    }

    // Since the specified range of bits is cached, set it unmodified
    m_pBitsState[regId].isModified = 0;

    // Return the cached value
    return m_pBitsState[regId].pValue;
}

// =====================================================================================================================
// Get combined data from two seperate DWORDs
// Note: The return type is one DWORD, it doesn't support two DWORDs for now.
// TODO: Expand to support 2-DWORDs combination result.
Value* GfxRegHandler::GetRegCombine(
    uint32_t regIdLo, // The ID of low part register
    uint32_t regIdHi) // Reg ID of high part register
{
    Value* pRegValueLo = GetRegCommon(regIdLo);
    Value* pRegValueHi = GetRegCommon(regIdHi);
    return m_pBuilder->CreateOr(m_pBuilder->CreateShl(pRegValueHi, m_pBitsInfo[regIdLo].offset), pRegValueLo);
}

// =====================================================================================================================
// Set register value into two seperate DWORDs
// Note: The input pRegValue only supports one DWORD
void GfxRegHandler::SetRegCombine(
    uint32_t regIdLo,   // The ID of low part register
    uint32_t regIdHi,   // Reg ID of high part register
    Value*   pRegValue) // [in] Data used for setting
{
    Value* pRegValueLo = m_pBuilder->CreateIntrinsic(Intrinsic::amdgcn_ubfe,
                                                     m_pBuilder->getInt32Ty(),
                                                     { pRegValue,
                                                       m_pBuilder->getInt32(0),
                                                       m_pBuilder->getInt32(m_pBitsInfo[regIdLo].offset) });

    Value* pRegValueHi = m_pBuilder->CreateLShr(pRegValue, m_pBuilder->getInt32(m_pBitsInfo[regIdLo].offset));

    SetRegCommon(regIdLo, pRegValueLo);
    SetRegCommon(regIdHi, pRegValueHi);
}

// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx9-10)
// Refer to imported/chip/gfx9/gfx9_plus_merged_registers.h : SQ_IMG_SAMP_WORD
static constexpr BitsInfo SqImgSampRegBitsGfx9[static_cast<uint32_t>(SqSampRegs::Count)] =
{
    { 0, 30, 2 }, // FilterMode
    { 2, 20, 2 }, // XyMagFilter
    { 2, 22, 2 }, // XyMinFilter
};

// =====================================================================================================================
// Helper class for handling Registers defined in SQ_IMG_SAMP_WORD
SqImgSampRegHandler::SqImgSampRegHandler(
    Builder*      pBuilder,      // [in] Bound builder context
    Value*        pRegister,     // [in] Bound register vec <n x i32>
    GfxIpVersion* pGfxIpVersion) // [in] Target GFX IP version
    :
    GfxRegHandler(pBuilder, pRegister)
{
    m_pGfxIpVersion = pGfxIpVersion;

    switch (pGfxIpVersion->major)
    {
    case 9:
    case 10:
        m_pBitsInfo = SqImgSampRegBitsGfx9;
        break;
    default:
        llvm_unreachable("GFX IP is not supported!");
        break;
    }
    SetBitsState(m_pBitsState);
}

// =====================================================================================================================
// Get the current value for the hardware register
Value* SqImgSampRegHandler::GetReg(
    SqSampRegs regId) // Register ID
{
    switch (regId)
    {
    case SqSampRegs::FilterMode:
    case SqSampRegs::xyMagFilter:
    case SqSampRegs::xyMinFilter:
        return GetRegCommon(static_cast<uint32_t>(regId));
    default:
        // TODO: More will be implemented.
        llvm_unreachable("Not implemented!");
        break;
    }
    return nullptr;
}

// =====================================================================================================================
// Set the current value for the hardware register
void SqImgSampRegHandler::SetReg(
    SqSampRegs regId,      // Register ID
    Value*     pRegValue ) // [in] Value to set to this register
{
    switch (regId)
    {
    case SqSampRegs::FilterMode:
    case SqSampRegs::xyMagFilter:
    case SqSampRegs::xyMinFilter:
        SetRegCommon(static_cast<uint32_t>(regId), pRegValue);
        break;
    default:
        llvm_unreachable("Set \"IsTileOpt\" is not allowed!");
        break;
    }
}

// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx9)
// Refer to imported/chip/gfx9/gfx9_plus_merged_registers.h : SQ_IMG_RSRC_WORD
static constexpr BitsInfo SqImgRsrcRegBitsGfx9[static_cast<uint32_t>(SqRsrcRegs::Count)] =
{
    { 0,  0, 32 }, // BaseAddress
    { 1,  0,  8 }, // BaseAddressHi
    { 1, 20,  9 }, // Format
    { 2,  0, 14 }, // Width
    { 2, 14, 14 }, // Height
    { 3,  0, 12 }, // DstSelXYZW
    { 3, 20,  5 }, // IsTileOpt
    { 4,  0, 13 }, // Depth
    { 4, 13, 12 }, // Pitch
    { 4, 29,  3 }, // BcSwizzle
    {},            // WidthLo
    {},            // WidthHi
};

// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx10)
// TODO: update comment when the registers file is available
static constexpr BitsInfo SqImgRsrcRegBitsGfx10[static_cast<uint32_t>(SqRsrcRegs::Count)] =
{
    { 0,  0, 32 }, // BaseAddress
    { 1,  0,  8 }, // BaseAddressHi
    { 1, 20,  9 }, // Format
    {},            // Width
    { 2, 14, 16 }, // Height
    { 3,  0, 12 }, // DstSelXYZW
    { 3, 20,  5 }, // IsTileOpt
    { 4,  0, 16 }, // Depth
    {},            // Pitch
    { 3, 25,  3 }, // BcSwizzle
    { 1, 30,  2 }, // WidthLo
    { 2,  0, 14 }, // WidthHi
};

// =====================================================================================================================
// Helper class for handling Registers defined in SQ_IMG_RSRC_WORD
SqImgRsrcRegHandler::SqImgRsrcRegHandler(
    Builder*      pBuilder,      // [in] Bound builder context
    Value*        pRegister,     // [in] Bound register vec <n x i32>
    GfxIpVersion* pGfxIpVersion) // [in] Current GFX IP version
    :
    GfxRegHandler(pBuilder, pRegister)
{
    m_pGfxIpVersion = pGfxIpVersion;

    switch (pGfxIpVersion->major)
    {
    case 9:
        m_pBitsInfo = SqImgRsrcRegBitsGfx9;
        break;
    case 10:
        m_pBitsInfo = SqImgRsrcRegBitsGfx10;
        break;
    default:
        llvm_unreachable("GFX IP is not supported!");
        break;
    }
    SetBitsState(m_pBitsState);
}

// =====================================================================================================================
// Get the current value for the hardware register
Value* SqImgRsrcRegHandler::GetReg(
    SqRsrcRegs regId) // Register ID
{
    switch (regId)
    {
    case SqRsrcRegs::BaseAddress:
    case SqRsrcRegs::Format:
    case SqRsrcRegs::DstSelXYZW:
    case SqRsrcRegs::Depth:
    case SqRsrcRegs::BcSwizzle:
        return GetRegCommon(static_cast<uint32_t>(regId));
    case SqRsrcRegs::Height:
    case SqRsrcRegs::Pitch:
        return m_pBuilder->CreateAdd(GetRegCommon(static_cast<uint32_t>(regId)), m_pOne);
    case SqRsrcRegs::Width:
        switch (m_pGfxIpVersion->major)
        {
        case 9:
            return m_pBuilder->CreateAdd(GetRegCommon(static_cast<uint32_t>(regId)), m_pOne);
        case 10:
            return m_pBuilder->CreateAdd(GetRegCombine(static_cast<uint32_t>(SqRsrcRegs::WidthLo),
                                                       static_cast<uint32_t>(SqRsrcRegs::WidthHi)),
                                                       m_pOne);
        default:
            llvm_unreachable("GFX IP is not supported!");
            break;
        }
    case SqRsrcRegs::IsTileOpt:
        return m_pBuilder->CreateICmpNE(GetRegCommon(static_cast<uint32_t>(regId)), m_pBuilder->getInt32(0));
    default:
        // TODO: More will be implemented.
        llvm_unreachable("Not implemented!");
    }
    return nullptr;
}

// =====================================================================================================================
// Set the current value for the hardware register
void SqImgRsrcRegHandler::SetReg(
    SqRsrcRegs regId,      // Register ID
    Value*     pRegValue)  // [in] Value to set to this register
{
    switch (regId)
    {
    case SqRsrcRegs::BaseAddress:
    case SqRsrcRegs::BaseAddressHi:
    case SqRsrcRegs::Format:
    case SqRsrcRegs::DstSelXYZW:
    case SqRsrcRegs::Depth:
    case SqRsrcRegs::BcSwizzle:
        SetRegCommon(static_cast<uint32_t>(regId), pRegValue);
        break;
    case SqRsrcRegs::Height:
    case SqRsrcRegs::Pitch:
        SetRegCommon(static_cast<uint32_t>(regId), m_pBuilder->CreateSub(pRegValue, m_pOne));
        break;
    case SqRsrcRegs::Width:
        switch (m_pGfxIpVersion->major)
        {
        case 9:
            SetRegCommon(static_cast<uint32_t>(regId), m_pBuilder->CreateSub(pRegValue, m_pOne));
            break;
        case 10:
            SetRegCombine(static_cast<uint32_t>(SqRsrcRegs::WidthLo),
                          static_cast<uint32_t>(SqRsrcRegs::WidthHi),
                          m_pBuilder->CreateSub(pRegValue, m_pOne));
            break;
        default:
            llvm_unreachable("GFX IP is not supported!");
            break;
        }
        break;
    case SqRsrcRegs::IsTileOpt:
    case SqRsrcRegs::WidthLo:
    case SqRsrcRegs::WidthHi:
    case SqRsrcRegs::Count:
        llvm_unreachable("Bad SqImgRsrcRegHandler::SetReg!");
        break;
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix: fix filling of event/track cuts values histogram<commit_after><|endoftext|>


<commit_before>AliAnalysisVertexingHF* ConfigVertexingHF() {

  printf("Call to AliAnalysisVertexingHF parameters setting :\n");
  vHF = new AliAnalysisVertexingHF();

  //--- switch-off candidates finding (default: all on)
  //vHF->SetD0toKpiOff();
  //vHF->SetJPSItoEleOff();
  //vHF->Set3ProngOff();
  //vHF->SetLikeSignOn();
  vHF->Set4ProngOff();
  //vHF->SetDstarOff();
  //--- secondary vertex with KF?
  //vHF->SetSecVtxWithKF();
  //--- set cuts for single-track selection

  AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCuts->SetRequireITSRefit(kTRUE);
  esdTrackCuts->SetMinNClustersITS(5);
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kBoth);
  esdTrackCuts->SetMinDCAToVertexXY(0.);
  esdTrackCuts->SetPtRange(0.3,1.e10);
  AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
  trkFilter->AddCuts(esdTrackCuts);
  vHF->SetTrackFilter(trkFilter);
  AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
  AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
  trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
  vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
  //--- set cuts for candidates selection
  vHF->SetD0toKpiCuts(0.7,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
  vHF->SetBtoJPSICuts(0.350);
  vHF->SetDplusCuts(0.2,0.,0.,0.,0.,0.01,0.06,0.,0.,0.8);
  vHF->SetDsCuts(0.2,0.,0.,0.,0.,0.005,0.06,0.,0.,0.8,0.,0.1,0.1);
  vHF->SetLcCuts(0.2,0.,0.,0.,0.,0.01,0.06,0.,0.,0.8);
  vHF->SetDstarCuts(999999., 999999., 0.1, 1.0, 0.5);
  vHF->SetD0fromDstarCuts(0.7,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
  //--- set this if you want to reconstruct primary vertex candidate by
  //    candidate using other tracks in the event (for pp, broad
  //    interaction region)
  //vHF->SetRecoPrimVtxSkippingTrks();
  //--- OR set this if you want to remove the candidate daughters from
  //    the primary vertex, without recostructing it from scratch
  //vHF->SetRmTrksFromPrimVtx();

  //--- check the settings
  vHF->PrintStatus();
  //--- verbose
  //AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);

  return vHF;
}

<commit_msg>Added possibility to use the event primary vertex as the decay vertex of the D* (no secondary vertex tried between D0 and pi_s)<commit_after>AliAnalysisVertexingHF* ConfigVertexingHF() {

  printf("Call to AliAnalysisVertexingHF parameters setting :\n");
  vHF = new AliAnalysisVertexingHF();

  //--- switch-off candidates finding (default: all on)
  //vHF->SetD0toKpiOff();
  //vHF->SetJPSItoEleOff();
  //vHF->Set3ProngOff();
  //vHF->SetLikeSignOn();
  vHF->Set4ProngOff();
  //vHF->SetDstarOff();
  vHF->SetFindVertexForDstar(kTRUE);
  //--- secondary vertex with KF?
  //vHF->SetSecVtxWithKF();
  //--- set cuts for single-track selection

  AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCuts->SetRequireITSRefit(kTRUE);
  esdTrackCuts->SetMinNClustersITS(5);
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kBoth);
  esdTrackCuts->SetMinDCAToVertexXY(0.);
  esdTrackCuts->SetPtRange(0.3,1.e10);
  AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
  trkFilter->AddCuts(esdTrackCuts);
  vHF->SetTrackFilter(trkFilter);
  AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCutsSoftPi->SetRequireITSRefit(kTRUE);
  AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
  trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
  vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
  //--- set cuts for candidates selection
  vHF->SetD0toKpiCuts(0.7,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
  vHF->SetBtoJPSICuts(0.350);
  vHF->SetDplusCuts(0.2,0.,0.,0.,0.,0.01,0.06,0.,0.,0.8);
  vHF->SetDsCuts(0.2,0.,0.,0.,0.,0.005,0.06,0.,0.,0.8,0.,0.1,0.1);
  vHF->SetLcCuts(0.2,0.,0.,0.,0.,0.01,0.06,0.,0.,0.8);
  vHF->SetDstarCuts(999999., 999999., 0.1, 1.0, 0.5);
  vHF->SetD0fromDstarCuts(0.7,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
  //--- set this if you want to reconstruct primary vertex candidate by
  //    candidate using other tracks in the event (for pp, broad
  //    interaction region)
  //vHF->SetRecoPrimVtxSkippingTrks();
  //--- OR set this if you want to remove the candidate daughters from
  //    the primary vertex, without recostructing it from scratch
  //vHF->SetRmTrksFromPrimVtx();

  //--- check the settings
  vHF->PrintStatus();
  //--- verbose
  //AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);

  return vHF;
}

<|endoftext|>


<commit_before>//===- lib/Driver/GnuLdInputGraph.cpp -------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Driver/GnuLdInputGraph.h"
#include "lld/ReaderWriter/LinkerScript.h"

#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"

using namespace lld;

/// \brief Parse the input file to lld::File.
error_code ELFFileNode::parse(const LinkingContext &ctx,
                              raw_ostream &diagnostics) {
  ErrorOr<StringRef> filePath = getPath(ctx);
  if (error_code ec = filePath.getError())
    return ec;

  if (error_code ec = getBuffer(*filePath))
    return ec;

  if (ctx.logInputFiles())
    diagnostics << *filePath << "\n";

  if (_attributes._isWholeArchive) {
    std::vector<std::unique_ptr<File>> parsedFiles;
    error_code ec = ctx.registry().parseFile(_buffer, parsedFiles);
    if (ec)
      return ec;
    assert(parsedFiles.size() == 1);
    std::unique_ptr<File> f(parsedFiles[0].release());
    if (auto archive = reinterpret_cast<const ArchiveLibraryFile *>(f.get())) {
      // Have this node own the FileArchive object.
      _archiveFile.reset(archive);
      f.release();
      // Add all members to _files vector
      return archive->parseAllMembers(_files);
    }
    // if --whole-archive is around non-archive, just use it as normal.
    _files.push_back(std::move(f));
    return error_code::success();
  }
  return ctx.registry().parseFile(_buffer, _files);
}

/// \brief Parse the GnuLD Script
error_code GNULdScript::parse(const LinkingContext &ctx,
                              raw_ostream &diagnostics) {
  ErrorOr<StringRef> filePath = getPath(ctx);
  if (error_code ec = filePath.getError())
    return ec;

  if (error_code ec = getBuffer(*filePath))
    return ec;

  if (ctx.logInputFiles())
    diagnostics << *filePath << "\n";

  _lexer.reset(new script::Lexer(std::move(_buffer)));
  _parser.reset(new script::Parser(*_lexer.get()));

  _linkerScript = _parser->parse();

  if (!_linkerScript)
    return LinkerScriptReaderError::parse_error;

  return error_code::success();
}

static bool isPathUnderSysroot(StringRef sysroot, StringRef path) {
  // TODO: Handle the case when 'sysroot' and/or 'path' are symlinks.
  if (sysroot.empty() || sysroot.size() >= path.size())
    return false;
  if (llvm::sys::path::is_separator(sysroot.back()))
    sysroot = sysroot.substr(0, sysroot.size() - 1);
  if (!llvm::sys::path::is_separator(path[sysroot.size()]))
    return false;

  return llvm::sys::fs::equivalent(sysroot, path.substr(0, sysroot.size()));
}

/// \brief Handle GnuLD script for ELF.
error_code ELFGNULdScript::parse(const LinkingContext &ctx,
                                 raw_ostream &diagnostics) {
  ELFFileNode::Attributes attributes;
  if (error_code ec = GNULdScript::parse(ctx, diagnostics))
    return ec;
  StringRef sysRoot = _elfLinkingContext.getSysroot();
  if (!sysRoot.empty() && isPathUnderSysroot(sysRoot, *getPath(ctx)))
    attributes.setSysRooted(true);
  for (const script::Command *c : _linkerScript->_commands) {
    auto *group = dyn_cast<script::Group>(c);
    if (!group)
      continue;
    std::unique_ptr<Group> groupStart(new Group());
    for (const script::Path &path : group->getPaths()) {
      // TODO : Propagate Set WholeArchive/dashlPrefix
      attributes.setAsNeeded(path._asNeeded);
      auto inputNode = new ELFFileNode(
          _elfLinkingContext, _elfLinkingContext.allocateString(path._path),
          attributes);
      std::unique_ptr<InputElement> inputFile(inputNode);
      groupStart.get()->addFile(std::move(inputFile));
    }
    _expandElements.push_back(std::move(groupStart));
  }
  return error_code::success();
}
<commit_msg>Trivial simplification<commit_after>//===- lib/Driver/GnuLdInputGraph.cpp -------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Driver/GnuLdInputGraph.h"
#include "lld/ReaderWriter/LinkerScript.h"

#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"

using namespace lld;

/// \brief Parse the input file to lld::File.
error_code ELFFileNode::parse(const LinkingContext &ctx,
                              raw_ostream &diagnostics) {
  ErrorOr<StringRef> filePath = getPath(ctx);
  if (error_code ec = filePath.getError())
    return ec;
  if (error_code ec = getBuffer(*filePath))
    return ec;
  if (ctx.logInputFiles())
    diagnostics << *filePath << "\n";

  if (_attributes._isWholeArchive) {
    std::vector<std::unique_ptr<File>> parsedFiles;
    if (error_code ec = ctx.registry().parseFile(_buffer, parsedFiles))
      return ec;
    assert(parsedFiles.size() == 1);
    std::unique_ptr<File> f(parsedFiles[0].release());
    if (auto archive = reinterpret_cast<const ArchiveLibraryFile *>(f.get())) {
      // Have this node own the FileArchive object.
      _archiveFile.reset(archive);
      f.release();
      // Add all members to _files vector
      return archive->parseAllMembers(_files);
    }
    // if --whole-archive is around non-archive, just use it as normal.
    _files.push_back(std::move(f));
    return error_code::success();
  }
  return ctx.registry().parseFile(_buffer, _files);
}

/// \brief Parse the GnuLD Script
error_code GNULdScript::parse(const LinkingContext &ctx,
                              raw_ostream &diagnostics) {
  ErrorOr<StringRef> filePath = getPath(ctx);
  if (error_code ec = filePath.getError())
    return ec;
  if (error_code ec = getBuffer(*filePath))
    return ec;

  if (ctx.logInputFiles())
    diagnostics << *filePath << "\n";

  _lexer.reset(new script::Lexer(std::move(_buffer)));
  _parser.reset(new script::Parser(*_lexer.get()));

  _linkerScript = _parser->parse();

  if (!_linkerScript)
    return LinkerScriptReaderError::parse_error;

  return error_code::success();
}

static bool isPathUnderSysroot(StringRef sysroot, StringRef path) {
  // TODO: Handle the case when 'sysroot' and/or 'path' are symlinks.
  if (sysroot.empty() || sysroot.size() >= path.size())
    return false;
  if (llvm::sys::path::is_separator(sysroot.back()))
    sysroot = sysroot.substr(0, sysroot.size() - 1);
  if (!llvm::sys::path::is_separator(path[sysroot.size()]))
    return false;

  return llvm::sys::fs::equivalent(sysroot, path.substr(0, sysroot.size()));
}

/// \brief Handle GnuLD script for ELF.
error_code ELFGNULdScript::parse(const LinkingContext &ctx,
                                 raw_ostream &diagnostics) {
  ELFFileNode::Attributes attributes;
  if (error_code ec = GNULdScript::parse(ctx, diagnostics))
    return ec;
  StringRef sysRoot = _elfLinkingContext.getSysroot();
  if (!sysRoot.empty() && isPathUnderSysroot(sysRoot, *getPath(ctx)))
    attributes.setSysRooted(true);
  for (const script::Command *c : _linkerScript->_commands) {
    auto *group = dyn_cast<script::Group>(c);
    if (!group)
      continue;
    std::unique_ptr<Group> groupStart(new Group());
    for (const script::Path &path : group->getPaths()) {
      // TODO : Propagate Set WholeArchive/dashlPrefix
      attributes.setAsNeeded(path._asNeeded);
      auto inputNode = new ELFFileNode(
          _elfLinkingContext, _elfLinkingContext.allocateString(path._path),
          attributes);
      std::unique_ptr<InputElement> inputFile(inputNode);
      groupStart.get()->addFile(std::move(inputFile));
    }
    _expandElements.push_back(std::move(groupStart));
  }
  return error_code::success();
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vvasilev@cern.ch>
//------------------------------------------------------------------------------

#include "MetaSema.h"

#include "Display.h"

#include "cling/Interpreter/Interpreter.h"
#include "cling/MetaProcessor/MetaProcessor.h"

#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"

#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h" // for llvm::outs() FIXME

#include <cstdlib>

namespace cling {

  void MetaSema::actOnLCommand(llvm::sys::Path file) const {
    m_Interpreter.loadFile(file.str());
    // TODO: extra checks. Eg if the path is readable, if the file exists...
  }

  void MetaSema::actOnComment(llvm::StringRef comment) const {
    // Some of the comments are meaningful for the cling::Interpreter
    m_Interpreter.declare(comment);
  }

  void MetaSema::actOnxCommand(llvm::sys::Path file, llvm::StringRef args)
  {
    // Fall back to the meta processor for now.
    m_LastResultedValue = StoredValueRef::invalidValue();
    m_MetaProcessor.executeFile(file.str(), args.str(), &m_LastResultedValue);
    //m_Interpreter.loadFile(path.str());
    // TODO: extra checks. Eg if the path is readable, if the file exists...
  }

  void MetaSema::actOnqCommand() {
    m_IsQuitRequested = true;
  }

  void MetaSema::actOnUCommand() const {
     m_Interpreter.unload();
  }

  void MetaSema::actOnICommand(llvm::sys::Path path) const {
    if (path.isEmpty())
      m_Interpreter.DumpIncludePath();
    else
      m_Interpreter.AddIncludePath(path.str());
  }

  void MetaSema::actOnrawInputCommand(SwitchMode mode/* = kToggle*/) const {
    if (mode == kToggle) {
      bool flag = !m_Interpreter.isRawInputEnabled();
      m_Interpreter.enableRawInput(flag);
      // FIXME:
      llvm::outs() << (flag ? "U" :"Not u") << "sing raw input\n";
    }
    else
      m_Interpreter.enableRawInput(mode);
  }

  void MetaSema::actOnprintASTCommand(SwitchMode mode/* = kToggle*/) const {
    if (mode == kToggle) {
      bool flag = !m_Interpreter.isPrintingAST();
      m_Interpreter.enablePrintAST(flag);
      // FIXME:
      llvm::outs() << (flag ? "P" : "Not p") << "rinting AST\n";
    }
    else
      m_Interpreter.enablePrintAST(mode);
  }

  void MetaSema::actOndynamicExtensionsCommand(SwitchMode mode/* = kToggle*/)
    const {
    if (mode == kToggle) {
      bool flag = !m_Interpreter.isDynamicLookupEnabled();
      m_Interpreter.enableDynamicLookup(flag);
      // FIXME:
      llvm::outs() << (flag ? "U" : "Not u") << "sing dynamic extensions\n";
    }
    else
      m_Interpreter.enableDynamicLookup(mode);
  }

  void MetaSema::actOnhelpCommand() const {
    std::string& metaString = m_Interpreter.getOptions().MetaString;
    llvm::outs() << "Cling meta commands usage\n";
    llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
    llvm::outs() << "\n";
    llvm::outs() << metaString << "q\t\t\t\t- Exit the program\n";
    llvm::outs() << metaString << "L <filename>\t\t\t - Load file or library\n";
    llvm::outs() << metaString << "(x|X) <filename>[args]\t\t- Same as .L and runs a ";
    llvm::outs() << "function with signature ";
    llvm::outs() << "\t\t\t\tret_type filename(args)\n";
    llvm::outs() << metaString << "I [path]\t\t\t- Shows the include path. If a path is ";
    llvm::outs() << "given - \n\t\t\t\tadds the path to the include paths\n";
    llvm::outs() << metaString << "@ \t\t\t\t- Cancels and ignores the multiline input\n";
    llvm::outs() << metaString << "rawInput [0|1]\t\t\t- Toggle wrapping and printing ";
    llvm::outs() << "the execution\n\t\t\t\tresults of the input\n";
    llvm::outs() << metaString << "dynamicExtensions [0|1]\t- Toggles the use of the ";
    llvm::outs() << "dynamic scopes and the \t\t\t\tlate binding\n";
    llvm::outs() << metaString << "printAST [0|1]\t\t\t- Toggles the printing of input's ";
    llvm::outs() << "corresponding \t\t\t\tAST nodes\n";
    llvm::outs() << metaString << "help\t\t\t\t- Shows this information\n";
  }

  void MetaSema::actOnfileExCommand() const {
    const clang::SourceManager& SM = m_Interpreter.getCI()->getSourceManager();
    SM.getFileManager().PrintStats();

    llvm::outs() << "\n***\n\n";

    for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
           E = SM.fileinfo_end(); I != E; ++I) {
      llvm::outs() << (*I).first->getName();
      llvm::outs() << "\n";
    }

  }

  void MetaSema::actOnfilesCommand() const {
    typedef llvm::SmallVectorImpl<Interpreter::LoadedFileInfo*> LoadedFiles_t;
    const LoadedFiles_t& LoadedFiles = m_Interpreter.getLoadedFiles();
    for (LoadedFiles_t::const_iterator I = LoadedFiles.begin(),
           E = LoadedFiles.end(); I != E; ++I) {
      char cType[] = { 'S', 'D', 'B' };
      llvm::outs() << '[' << cType[(*I)->getType()] << "] "
                   << (*I)->getName() << '\n';
    }
  }

  void MetaSema::actOnclassCommand(llvm::StringRef className) const {
    if (!className.empty())
      DisplayClass(llvm::outs(), &m_Interpreter, className.str().c_str(), true);
    else
      DisplayClasses(llvm::outs(), &m_Interpreter, false);
  }

  void MetaSema::actOnClassCommand() const {
    DisplayClasses(llvm::outs(), &m_Interpreter, true);
  }

  void MetaSema::actOngCommand(llvm::StringRef varName) const {
    if (varName.empty())
      DisplayGlobals(llvm::outs(), &m_Interpreter);
    else
      DisplayGlobal(llvm::outs(), &m_Interpreter, varName.str().c_str());
  }

  void MetaSema::actOnTypedefCommand(llvm::StringRef typedefName) const {
    if (typedefName.empty())
      DisplayTypedefs(llvm::outs(), &m_Interpreter);
    else
      DisplayTypedef(llvm::outs(), &m_Interpreter, typedefName.str().c_str());
  }

  void MetaSema::actOnShellCommand(llvm::StringRef commandLine) const {
    llvm::StringRef trimmed(commandLine.trim(" \t\n\v\f\r "));
    if (!trimmed.empty()) {
       int ret = std::system(trimmed.str().c_str());
       (void) ret; // Silence warning unused return result of system.
    }
  }

} // end namespace cling
<commit_msg>Also print headers from modules - once we update clang as it doesn't exist yet in our revision...<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vvasilev@cern.ch>
//------------------------------------------------------------------------------

#include "MetaSema.h"

#include "Display.h"

#include "cling/Interpreter/Interpreter.h"
#include "cling/MetaProcessor/MetaProcessor.h"

#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Serialization/ASTReader.h"

#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h" // for llvm::outs() FIXME

#include <cstdlib>

namespace cling {

  void MetaSema::actOnLCommand(llvm::sys::Path file) const {
    m_Interpreter.loadFile(file.str());
    // TODO: extra checks. Eg if the path is readable, if the file exists...
  }

  void MetaSema::actOnComment(llvm::StringRef comment) const {
    // Some of the comments are meaningful for the cling::Interpreter
    m_Interpreter.declare(comment);
  }

  void MetaSema::actOnxCommand(llvm::sys::Path file, llvm::StringRef args)
  {
    // Fall back to the meta processor for now.
    m_LastResultedValue = StoredValueRef::invalidValue();
    m_MetaProcessor.executeFile(file.str(), args.str(), &m_LastResultedValue);
    //m_Interpreter.loadFile(path.str());
    // TODO: extra checks. Eg if the path is readable, if the file exists...
  }

  void MetaSema::actOnqCommand() {
    m_IsQuitRequested = true;
  }

  void MetaSema::actOnUCommand() const {
     m_Interpreter.unload();
  }

  void MetaSema::actOnICommand(llvm::sys::Path path) const {
    if (path.isEmpty())
      m_Interpreter.DumpIncludePath();
    else
      m_Interpreter.AddIncludePath(path.str());
  }

  void MetaSema::actOnrawInputCommand(SwitchMode mode/* = kToggle*/) const {
    if (mode == kToggle) {
      bool flag = !m_Interpreter.isRawInputEnabled();
      m_Interpreter.enableRawInput(flag);
      // FIXME:
      llvm::outs() << (flag ? "U" :"Not u") << "sing raw input\n";
    }
    else
      m_Interpreter.enableRawInput(mode);
  }

  void MetaSema::actOnprintASTCommand(SwitchMode mode/* = kToggle*/) const {
    if (mode == kToggle) {
      bool flag = !m_Interpreter.isPrintingAST();
      m_Interpreter.enablePrintAST(flag);
      // FIXME:
      llvm::outs() << (flag ? "P" : "Not p") << "rinting AST\n";
    }
    else
      m_Interpreter.enablePrintAST(mode);
  }

  void MetaSema::actOndynamicExtensionsCommand(SwitchMode mode/* = kToggle*/)
    const {
    if (mode == kToggle) {
      bool flag = !m_Interpreter.isDynamicLookupEnabled();
      m_Interpreter.enableDynamicLookup(flag);
      // FIXME:
      llvm::outs() << (flag ? "U" : "Not u") << "sing dynamic extensions\n";
    }
    else
      m_Interpreter.enableDynamicLookup(mode);
  }

  void MetaSema::actOnhelpCommand() const {
    std::string& metaString = m_Interpreter.getOptions().MetaString;
    llvm::outs() << "Cling meta commands usage\n";
    llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
    llvm::outs() << "\n";
    llvm::outs() << metaString << "q\t\t\t\t- Exit the program\n";
    llvm::outs() << metaString << "L <filename>\t\t\t - Load file or library\n";
    llvm::outs() << metaString << "(x|X) <filename>[args]\t\t- Same as .L and runs a ";
    llvm::outs() << "function with signature ";
    llvm::outs() << "\t\t\t\tret_type filename(args)\n";
    llvm::outs() << metaString << "I [path]\t\t\t- Shows the include path. If a path is ";
    llvm::outs() << "given - \n\t\t\t\tadds the path to the include paths\n";
    llvm::outs() << metaString << "@ \t\t\t\t- Cancels and ignores the multiline input\n";
    llvm::outs() << metaString << "rawInput [0|1]\t\t\t- Toggle wrapping and printing ";
    llvm::outs() << "the execution\n\t\t\t\tresults of the input\n";
    llvm::outs() << metaString << "dynamicExtensions [0|1]\t- Toggles the use of the ";
    llvm::outs() << "dynamic scopes and the \t\t\t\tlate binding\n";
    llvm::outs() << metaString << "printAST [0|1]\t\t\t- Toggles the printing of input's ";
    llvm::outs() << "corresponding \t\t\t\tAST nodes\n";
    llvm::outs() << metaString << "help\t\t\t\t- Shows this information\n";
  }

  void MetaSema::actOnfileExCommand() const {
    const clang::SourceManager& SM = m_Interpreter.getCI()->getSourceManager();
    SM.getFileManager().PrintStats();

    llvm::outs() << "\n***\n\n";

    for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
           E = SM.fileinfo_end(); I != E; ++I) {
      llvm::outs() << (*I).first->getName();
      llvm::outs() << "\n";
    }
    /* Only available in clang's trunk:
    clang::ASTReader* Reader = m_Interpreter.getCI()->getModuleManager();
    const clang::serialization::ModuleManager& ModMan
      = Reader->getModuleManager();
    for (clang::serialization::ModuleManager::ModuleConstIterator I
           = ModMan.begin(), E = ModMan.end(); I != E; ++I) {
      typedef
        std::vector<llvm::PointerIntPair<const clang::FileEntry*, 1, bool> >
        InputFiles_t;
      const InputFiles_t& InputFiles = (*I)->InputFilesLoaded;
      for (InputFiles_t::const_iterator IFI = InputFiles.begin(),
             IFE = InputFiles.end(); IFI != IFE; ++IFI) {
        llvm::outs() << IFI->getPointer()->getName();
        llvm::outs() << "\n";
      }
    }
    */
  }

  void MetaSema::actOnfilesCommand() const {
    typedef llvm::SmallVectorImpl<Interpreter::LoadedFileInfo*> LoadedFiles_t;
    const LoadedFiles_t& LoadedFiles = m_Interpreter.getLoadedFiles();
    for (LoadedFiles_t::const_iterator I = LoadedFiles.begin(),
           E = LoadedFiles.end(); I != E; ++I) {
      char cType[] = { 'S', 'D', 'B' };
      llvm::outs() << '[' << cType[(*I)->getType()] << "] "
                   << (*I)->getName() << '\n';
    }
  }

  void MetaSema::actOnclassCommand(llvm::StringRef className) const {
    if (!className.empty())
      DisplayClass(llvm::outs(), &m_Interpreter, className.str().c_str(), true);
    else
      DisplayClasses(llvm::outs(), &m_Interpreter, false);
  }

  void MetaSema::actOnClassCommand() const {
    DisplayClasses(llvm::outs(), &m_Interpreter, true);
  }

  void MetaSema::actOngCommand(llvm::StringRef varName) const {
    if (varName.empty())
      DisplayGlobals(llvm::outs(), &m_Interpreter);
    else
      DisplayGlobal(llvm::outs(), &m_Interpreter, varName.str().c_str());
  }

  void MetaSema::actOnTypedefCommand(llvm::StringRef typedefName) const {
    if (typedefName.empty())
      DisplayTypedefs(llvm::outs(), &m_Interpreter);
    else
      DisplayTypedef(llvm::outs(), &m_Interpreter, typedefName.str().c_str());
  }

  void MetaSema::actOnShellCommand(llvm::StringRef commandLine) const {
    llvm::StringRef trimmed(commandLine.trim(" \t\n\v\f\r "));
    if (!trimmed.empty()) {
       int ret = std::system(trimmed.str().c_str());
       (void) ret; // Silence warning unused return result of system.
    }
  }

} // end namespace cling
<|endoftext|>