<commit_before>/* Copyright (c) 2015-2016 The Khronos Group Inc.
 * Copyright (c) 2015-2016 Valve Corporation
 * Copyright (c) 2015-2016 LunarG, Inc.
 * Copyright (c) 2015-2016 Google, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: Tobin Ehlis <tobin@lunarg.com>
 */
#include <assert.h>
#include <unordered_map>
#include "vk_dispatch_table_helper.h"
#include "vulkan/vk_layer.h"
#include "vk_layer_table.h"
static device_table_map tableMap;
static instance_table_map tableInstanceMap;

#define DISPATCH_MAP_DEBUG 0

// Map lookup must be thread safe
VkLayerDispatchTable *device_dispatch_table(void *object) {
    dispatch_key key = get_dispatch_key(object);
    device_table_map::const_iterator it = tableMap.find((void *)key);
    assert(it != tableMap.end() && "Not able to find device dispatch entry");
    return it->second;
}

VkLayerInstanceDispatchTable *instance_dispatch_table(void *object) {
    dispatch_key key = get_dispatch_key(object);
    instance_table_map::const_iterator it = tableInstanceMap.find((void *)key);
#if DISPATCH_MAP_DEBUG
    if (it != tableInstanceMap.end()) {
        fprintf(stderr, "instance_dispatch_table: map:  0x%p, object:  0x%p, key:  0x%p, table:  0x%p\n", &tableInstanceMap, object,
                key, it->second);
    } else {
        fprintf(stderr, "instance_dispatch_table: map:  0x%p, object:  0x%p, key:  0x%p, table: UNKNOWN\n", &tableInstanceMap,
                object, key);
    }
#endif
    assert(it != tableInstanceMap.end() && "Not able to find instance dispatch entry");
    return it->second;
}

void destroy_dispatch_table(device_table_map &map, dispatch_key key) {
    device_table_map::const_iterator it = map.find((void *)key);
#if DISPATCH_MAP_DEBUG
    if (it != map.end()) {
        fprintf(stderr, "destroy device dispatch_table: map:  0x%p, key:  0x%p, table:  0x%p\n", &map, key, it->second);
    } else {
        fprintf(stderr, "destroy device dispatch table: map:  0x%p, key:  0x%p, table: UNKNOWN\n", &map, key);
        assert(it != map.end());
    }
#endif
    if (it != map.end()) {
        delete it->second;
        map.erase(it);
    }
}

void destroy_dispatch_table(instance_table_map &map, dispatch_key key) {
    instance_table_map::const_iterator it = map.find((void *)key);
#if DISPATCH_MAP_DEBUG
    if (it != map.end()) {
        fprintf(stderr, "destroy instance dispatch_table: map:  0x%p, key:  0x%p, table:  0x%p\n", &map, key, it->second);
    } else {
        fprintf(stderr, "destroy instance dispatch table: map:  0x%p, key:  0x%p, table: UNKNOWN\n", &map, key);
        assert(it != map.end());
    }
#endif
    if (it != map.end()) {
        delete it->second;
        map.erase(it);
    }
}

void destroy_device_dispatch_table(dispatch_key key) { destroy_dispatch_table(tableMap, key); }

void destroy_instance_dispatch_table(dispatch_key key) { destroy_dispatch_table(tableInstanceMap, key); }

VkLayerDispatchTable *get_dispatch_table(device_table_map &map, void *object) {
    dispatch_key key = get_dispatch_key(object);
    device_table_map::const_iterator it = map.find((void *)key);
#if DISPATCH_MAP_DEBUG
    if (it != map.end()) {
        fprintf(stderr, "device_dispatch_table: map:  0x%p, object:  0x%p, key:  0x%p, table:  0x%p\n", &tableInstanceMap, object,
                key, it->second);
    } else {
        fprintf(stderr, "device_dispatch_table: map:  0x%p, object:  0x%p, key:  0x%p, table: UNKNOWN\n", &tableInstanceMap, object,
                key);
    }
#endif
    assert(it != map.end() && "Not able to find device dispatch entry");
    return it->second;
}

VkLayerInstanceDispatchTable *get_dispatch_table(instance_table_map &map, void *object) {
    dispatch_key key = get_dispatch_key(object);
    instance_table_map::const_iterator it = map.find((void *)key);
#if DISPATCH_MAP_DEBUG
    if (it != map.end()) {
        fprintf(stderr, "instance_dispatch_table: map:  0x%p, object:  0x%p, key:  0x%p, table:  0x%p\n", &tableInstanceMap, object,
                key, it->second);
    } else {
        fprintf(stderr, "instance_dispatch_table: map:  0x%p, object:  0x%p, key:  0x%p, table: UNKNOWN\n", &tableInstanceMap,
                object, key);
    }
#endif
    assert(it != map.end() && "Not able to find instance dispatch entry");
    return it->second;
}

VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func) {
    VkLayerInstanceCreateInfo *chain_info = (VkLayerInstanceCreateInfo *)pCreateInfo->pNext;
    while (chain_info && !(chain_info->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && chain_info->function == func)) {
        chain_info = (VkLayerInstanceCreateInfo *)chain_info->pNext;
    }
    assert(chain_info != NULL);
    return chain_info;
}

VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, VkLayerFunction func) {
    VkLayerDeviceCreateInfo *chain_info = (VkLayerDeviceCreateInfo *)pCreateInfo->pNext;
    while (chain_info && !(chain_info->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && chain_info->function == func)) {
        chain_info = (VkLayerDeviceCreateInfo *)chain_info->pNext;
    }
    assert(chain_info != NULL);
    return chain_info;
}

/* Various dispatchable objects will use the same underlying dispatch table if they
 * are created from that "parent" object. Thus use pointer to dispatch table
 * as the key to these table maps.
 *    Instance -> PhysicalDevice
 *    Device -> CommandBuffer or Queue
 * If use the object themselves as key to map then implies Create entrypoints have to be intercepted
 * and a new key inserted into map */
VkLayerInstanceDispatchTable *initInstanceTable(VkInstance instance, const PFN_vkGetInstanceProcAddr gpa, instance_table_map &map) {
    VkLayerInstanceDispatchTable *pTable;
    dispatch_key key = get_dispatch_key(instance);
    instance_table_map::const_iterator it = map.find((void *)key);

    if (it == map.end()) {
        pTable = new VkLayerInstanceDispatchTable;
        map[(void *)key] = pTable;
#if DISPATCH_MAP_DEBUG
        fprintf(stderr, "New, Instance: map:  0x%p, key:  0x%p, table:  0x%p\n", &map, key, pTable);
#endif
    } else {
#if DISPATCH_MAP_DEBUG
        fprintf(stderr, "Instance: map:  0x%p, key:  0x%p, table:  0x%p\n", &map, key, it->second);
#endif
        return it->second;
    }

    layer_init_instance_dispatch_table(instance, pTable, gpa);

    // Setup func pointers that are required but not externally exposed.  These won't be added to the instance dispatch table by
    // default.
    pTable->GetPhysicalDeviceProcAddr = (PFN_GetPhysicalDeviceProcAddr)gpa(instance, "vk_layerGetPhysicalDeviceProcAddr");

    return pTable;
}

VkLayerInstanceDispatchTable *initInstanceTable(VkInstance instance, const PFN_vkGetInstanceProcAddr gpa) {
    return initInstanceTable(instance, gpa, tableInstanceMap);
}

VkLayerDispatchTable *initDeviceTable(VkDevice device, const PFN_vkGetDeviceProcAddr gpa, device_table_map &map) {
    VkLayerDispatchTable *pTable;
    dispatch_key key = get_dispatch_key(device);
    device_table_map::const_iterator it = map.find((void *)key);

    if (it == map.end()) {
        pTable = new VkLayerDispatchTable;
        map[(void *)key] = pTable;
#if DISPATCH_MAP_DEBUG
        fprintf(stderr, "New, Device: map:  0x%p, key:  0x%p, table:  0x%p\n", &map, key, pTable);
#endif
    } else {
#if DISPATCH_MAP_DEBUG
        fprintf(stderr, "Device: map:  0x%p, key:  0x%p, table:  0x%p\n", &map, key, it->second);
#endif
        return it->second;
    }

    layer_init_device_dispatch_table(device, pTable, gpa);

    return pTable;
}

VkLayerDispatchTable *initDeviceTable(VkDevice device, const PFN_vkGetDeviceProcAddr gpa) {
    return initDeviceTable(device, gpa, tableMap);
}
<commit_msg>layers: Remove debug code from vk_layer_table.cpp<commit_after>/* Copyright (c) 2015-2016 The Khronos Group Inc.
 * Copyright (c) 2015-2016 Valve Corporation
 * Copyright (c) 2015-2016 LunarG, Inc.
 * Copyright (c) 2015-2016 Google, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: Tobin Ehlis <tobin@lunarg.com>
 */
#include <assert.h>
#include <unordered_map>
#include "vk_dispatch_table_helper.h"
#include "vulkan/vk_layer.h"
#include "vk_layer_table.h"
static device_table_map tableMap;
static instance_table_map tableInstanceMap;

// Map lookup must be thread safe
VkLayerDispatchTable *device_dispatch_table(void *object) {
    dispatch_key key = get_dispatch_key(object);
    device_table_map::const_iterator it = tableMap.find((void *)key);
    assert(it != tableMap.end() && "Not able to find device dispatch entry");
    return it->second;
}

VkLayerInstanceDispatchTable *instance_dispatch_table(void *object) {
    dispatch_key key = get_dispatch_key(object);
    instance_table_map::const_iterator it = tableInstanceMap.find((void *)key);
    assert(it != tableInstanceMap.end() && "Not able to find instance dispatch entry");
    return it->second;
}

void destroy_dispatch_table(device_table_map &map, dispatch_key key) {
    device_table_map::const_iterator it = map.find((void *)key);
    if (it != map.end()) {
        delete it->second;
        map.erase(it);
    }
}

void destroy_dispatch_table(instance_table_map &map, dispatch_key key) {
    instance_table_map::const_iterator it = map.find((void *)key);
    if (it != map.end()) {
        delete it->second;
        map.erase(it);
    }
}

void destroy_device_dispatch_table(dispatch_key key) { destroy_dispatch_table(tableMap, key); }

void destroy_instance_dispatch_table(dispatch_key key) { destroy_dispatch_table(tableInstanceMap, key); }

VkLayerDispatchTable *get_dispatch_table(device_table_map &map, void *object) {
    dispatch_key key = get_dispatch_key(object);
    device_table_map::const_iterator it = map.find((void *)key);
    assert(it != map.end() && "Not able to find device dispatch entry");
    return it->second;
}

VkLayerInstanceDispatchTable *get_dispatch_table(instance_table_map &map, void *object) {
    dispatch_key key = get_dispatch_key(object);
    instance_table_map::const_iterator it = map.find((void *)key);
    assert(it != map.end() && "Not able to find instance dispatch entry");
    return it->second;
}

VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func) {
    VkLayerInstanceCreateInfo *chain_info = (VkLayerInstanceCreateInfo *)pCreateInfo->pNext;
    while (chain_info && !(chain_info->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && chain_info->function == func)) {
        chain_info = (VkLayerInstanceCreateInfo *)chain_info->pNext;
    }
    assert(chain_info != NULL);
    return chain_info;
}

VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, VkLayerFunction func) {
    VkLayerDeviceCreateInfo *chain_info = (VkLayerDeviceCreateInfo *)pCreateInfo->pNext;
    while (chain_info && !(chain_info->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && chain_info->function == func)) {
        chain_info = (VkLayerDeviceCreateInfo *)chain_info->pNext;
    }
    assert(chain_info != NULL);
    return chain_info;
}

/* Various dispatchable objects will use the same underlying dispatch table if they
 * are created from that "parent" object. Thus use pointer to dispatch table
 * as the key to these table maps.
 *    Instance -> PhysicalDevice
 *    Device -> CommandBuffer or Queue
 * If use the object themselves as key to map then implies Create entrypoints have to be intercepted
 * and a new key inserted into map */
VkLayerInstanceDispatchTable *initInstanceTable(VkInstance instance, const PFN_vkGetInstanceProcAddr gpa, instance_table_map &map) {
    VkLayerInstanceDispatchTable *pTable;
    dispatch_key key = get_dispatch_key(instance);
    instance_table_map::const_iterator it = map.find((void *)key);

    if (it == map.end()) {
        pTable = new VkLayerInstanceDispatchTable;
        map[(void *)key] = pTable;
    } else {
        return it->second;
    }

    layer_init_instance_dispatch_table(instance, pTable, gpa);

    // Setup func pointers that are required but not externally exposed.  These won't be added to the instance dispatch table by
    // default.
    pTable->GetPhysicalDeviceProcAddr = (PFN_GetPhysicalDeviceProcAddr)gpa(instance, "vk_layerGetPhysicalDeviceProcAddr");

    return pTable;
}

VkLayerInstanceDispatchTable *initInstanceTable(VkInstance instance, const PFN_vkGetInstanceProcAddr gpa) {
    return initInstanceTable(instance, gpa, tableInstanceMap);
}

VkLayerDispatchTable *initDeviceTable(VkDevice device, const PFN_vkGetDeviceProcAddr gpa, device_table_map &map) {
    VkLayerDispatchTable *pTable;
    dispatch_key key = get_dispatch_key(device);
    device_table_map::const_iterator it = map.find((void *)key);

    if (it == map.end()) {
        pTable = new VkLayerDispatchTable;
        map[(void *)key] = pTable;
    } else {
        return it->second;
    }

    layer_init_device_dispatch_table(device, pTable, gpa);

    return pTable;
}

VkLayerDispatchTable *initDeviceTable(VkDevice device, const PFN_vkGetDeviceProcAddr gpa) {
    return initDeviceTable(device, gpa, tableMap);
}
<|endoftext|>


<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/xla/layout.h"

#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "tensorflow/compiler/xla/layout_util.h"

namespace xla {

TileProto Tile::ToProto() const {
  TileProto tile_proto;
  for (int64_t i : dimensions()) {
    tile_proto.add_dimensions(i);
  }
  return tile_proto;
}

string Tile::ToString() const {
  std::vector<string> elements;
  auto dims = dimensions();
  elements.reserve(dims.size());
  for (auto dim : dims) {
    if (dim >= 0) {
      elements.push_back(std::to_string(dim));
    } else {
      if (dim == kCombineDimension) {
        elements.push_back("*");
      } else {
        elements.push_back(absl::StrCat("Invalid value ", dim));
      }
    }
  }
  return absl::StrCat("(", absl::StrJoin(elements, ","), ")");
}

/* static */ Layout Layout::CreateFromProto(const LayoutProto& proto) {
  Layout layout;
  layout.set_format(proto.format());
  layout.minor_to_major_.reserve(proto.minor_to_major_size());
  for (const int64_t dimension : proto.minor_to_major()) {
    layout.add_minor_to_major(dimension);
  }
  for (const TileProto& tile_proto : proto.tiles()) {
    *layout.add_tiles() = Tile::CreateFromProto(tile_proto);
  }
  layout.set_element_size_in_bits(proto.element_size_in_bits());
  layout.set_memory_space(proto.memory_space());
  return layout;
}

LayoutProto Layout::ToProto() const {
  LayoutProto proto;
  proto.set_format(format_);
  proto.mutable_minor_to_major()->Reserve(minor_to_major_size());
  for (const int64_t dimension : minor_to_major()) {
    proto.add_minor_to_major(dimension);
  }
  for (const Tile& tile : tiles()) {
    *proto.add_tiles() = tile.ToProto();
  }
  proto.set_element_size_in_bits(element_size_in_bits());
  proto.set_memory_space(memory_space_);
  return proto;
}

string Layout::ToString() const {
  if (format() == DENSE) {
    string colon_string = tiles().empty() ? "" : "T";
    for (const Tile& tile : tiles()) {
      absl::StrAppend(&colon_string, tile.ToString());
    }
    if (element_size_in_bits() != 0) {
      absl::StrAppend(&colon_string, "E(", element_size_in_bits(), ")");
    }
    if (memory_space() != 0) {
      absl::StrAppend(&colon_string, "S(", memory_space(), ")");
    }
    return absl::StrCat("{", absl::StrJoin(minor_to_major(), ","),
                        colon_string.empty() ? "" : ":", colon_string, "}");
  } else {
    CHECK_EQ(format(), INVALID_FORMAT);
    return "invalid{}";
  }
}

bool Layout::Equal::operator()(const Layout& lhs, const Layout& rhs) {
  if (lhs.format() != rhs.format()) {
    return false;
  }
  if (lhs.format() == DENSE && lhs.minor_to_major() != rhs.minor_to_major()) {
    return false;
  }
  if (!ignore_tiles_ && lhs.tiles() != rhs.tiles()) {
    return false;
  }
  if (!ignore_element_size_ &&
      lhs.element_size_in_bits() != rhs.element_size_in_bits()) {
    return false;
  }
  if (!ignore_memory_space_ && lhs.memory_space() != rhs.memory_space()) {
    return false;
  }
  return true;
}

bool Layout::operator==(const Layout& other) const {
  return Equal()(*this, other);
}

std::ostream& operator<<(std::ostream& out, const Tile& tile) {
  out << tile.ToString();
  return out;
}

std::ostream& operator<<(std::ostream& out, const Layout& layout) {
  out << layout.ToString();
  return out;
}

}  // namespace xla
<commit_msg>[tensorflow/compiler/xla/layout.cc] Use `const auto&` instead of `auto`<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/xla/layout.h"

#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "tensorflow/compiler/xla/layout_util.h"

namespace xla {

TileProto Tile::ToProto() const {
  TileProto tile_proto;
  for (int64_t i : dimensions()) {
    tile_proto.add_dimensions(i);
  }
  return tile_proto;
}

string Tile::ToString() const {
  std::vector<string> elements;
  const auto& dims = dimensions();
  elements.reserve(dims.size());
  for (auto dim : dims) {
    if (dim >= 0) {
      elements.push_back(std::to_string(dim));
    } else {
      if (dim == kCombineDimension) {
        elements.push_back("*");
      } else {
        elements.push_back(absl::StrCat("Invalid value ", dim));
      }
    }
  }
  return absl::StrCat("(", absl::StrJoin(elements, ","), ")");
}

/* static */ Layout Layout::CreateFromProto(const LayoutProto& proto) {
  Layout layout;
  layout.set_format(proto.format());
  layout.minor_to_major_.reserve(proto.minor_to_major_size());
  for (const int64_t dimension : proto.minor_to_major()) {
    layout.add_minor_to_major(dimension);
  }
  for (const TileProto& tile_proto : proto.tiles()) {
    *layout.add_tiles() = Tile::CreateFromProto(tile_proto);
  }
  layout.set_element_size_in_bits(proto.element_size_in_bits());
  layout.set_memory_space(proto.memory_space());
  return layout;
}

LayoutProto Layout::ToProto() const {
  LayoutProto proto;
  proto.set_format(format_);
  proto.mutable_minor_to_major()->Reserve(minor_to_major_size());
  for (const int64_t dimension : minor_to_major()) {
    proto.add_minor_to_major(dimension);
  }
  for (const Tile& tile : tiles()) {
    *proto.add_tiles() = tile.ToProto();
  }
  proto.set_element_size_in_bits(element_size_in_bits());
  proto.set_memory_space(memory_space_);
  return proto;
}

string Layout::ToString() const {
  if (format() == DENSE) {
    string colon_string = tiles().empty() ? "" : "T";
    for (const Tile& tile : tiles()) {
      absl::StrAppend(&colon_string, tile.ToString());
    }
    if (element_size_in_bits() != 0) {
      absl::StrAppend(&colon_string, "E(", element_size_in_bits(), ")");
    }
    if (memory_space() != 0) {
      absl::StrAppend(&colon_string, "S(", memory_space(), ")");
    }
    return absl::StrCat("{", absl::StrJoin(minor_to_major(), ","),
                        colon_string.empty() ? "" : ":", colon_string, "}");
  } else {
    CHECK_EQ(format(), INVALID_FORMAT);
    return "invalid{}";
  }
}

bool Layout::Equal::operator()(const Layout& lhs, const Layout& rhs) {
  if (lhs.format() != rhs.format()) {
    return false;
  }
  if (lhs.format() == DENSE && lhs.minor_to_major() != rhs.minor_to_major()) {
    return false;
  }
  if (!ignore_tiles_ && lhs.tiles() != rhs.tiles()) {
    return false;
  }
  if (!ignore_element_size_ &&
      lhs.element_size_in_bits() != rhs.element_size_in_bits()) {
    return false;
  }
  if (!ignore_memory_space_ && lhs.memory_space() != rhs.memory_space()) {
    return false;
  }
  return true;
}

bool Layout::operator==(const Layout& other) const {
  return Equal()(*this, other);
}

std::ostream& operator<<(std::ostream& out, const Tile& tile) {
  out << tile.ToString();
  return out;
}

std::ostream& operator<<(std::ostream& out, const Layout& layout) {
  out << layout.ToString();
  return out;
}

}  // namespace xla
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Real Logic Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <util/MemoryMappedFile.h>
#include <concurrent/errors/ErrorLogReader.h>
#include <util/CommandOptionParser.h>

#include <iostream>
#include <atomic>
#include <thread>
#include <signal.h>
#include <Context.h>
#include <cstdio>

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <iomanip>

using namespace aeron;
using namespace aeron::util;
using namespace aeron::concurrent;
using namespace aeron::concurrent::errors;
using namespace std::chrono;

static const char optHelp   = 'h';
static const char optPath   = 'p';

struct Settings
{
    std::string basePath = Context::defaultAeronPath();
};

Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv)
{
    cp.parse(argc, argv);
    if (cp.getOption(optHelp).isPresent())
    {
        cp.displayOptionsHelp(std::cout);
        exit(0);
    }

    Settings s;

    s.basePath = cp.getOption(optPath).getParam(0, s.basePath);

    return s;
}

std::string formatDate(std::int64_t millisecondsSinceEpoch)
{
    // yyyy-MM-dd HH:mm:ss.SSSZ
    milliseconds msSinceEpoch(millisecondsSinceEpoch);
    milliseconds msAfterSec(millisecondsSinceEpoch % 1000);
    system_clock::time_point tp(msSinceEpoch);

    std::time_t tm = system_clock::to_time_t(tp);

    std::ostringstream result;

    result << std::put_time(std::localtime(&tm), "%Y-%m-%d %H:%M:%S.");
    result.fill('0');
    result << std::setw(3) << msAfterSec.count() << std::put_time(std::localtime(&tm), "%z");

    return result.str();
}

int main (int argc, char** argv)
{
    CommandOptionParser cp;
    cp.addOption(CommandOption (optHelp,   0, 0, "                Displays help information."));
    cp.addOption(CommandOption (optPath,   1, 1, "basePath        Base Path to shared memory. Default: " + Context::defaultAeronPath()));

    try
    {
        Settings settings = parseCmdLine(cp, argc, argv);

        MemoryMappedFile::ptr_t cncFile =
            MemoryMappedFile::mapExisting((settings.basePath + "/" + CncFileDescriptor::CNC_FILE).c_str());

        const std::int32_t cncVersion = CncFileDescriptor::cncVersion(cncFile);

        if (cncVersion != CncFileDescriptor::CNC_VERSION)
        {
            std::cerr << "CNC version not supported: file version=" << cncVersion << std::endl;
            return -1;
        }

        AtomicBuffer errorBuffer = CncFileDescriptor::createErrorLogBuffer(cncFile);

        const int distinctErrorCount = ErrorLogReader::read(
            errorBuffer,
            [](
                std::int32_t observationCount,
                std::int64_t firstObservationTimestamp,
                std::int64_t lastObservationTimestamp,
                const std::string &encodedException)
                {
                    std::printf(
                        "***\n%d observations from %s to %s for:\n %s\n",
                        observationCount,
                        formatDate(firstObservationTimestamp).c_str(),
                        formatDate(lastObservationTimestamp).c_str(),
                        encodedException.c_str());
                },
            0);

        std::printf("\n%d distinct errors observed.\n", distinctErrorCount);
    }
    catch (CommandOptionException& e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        cp.displayOptionsHelp(std::cerr);
        return -1;
    }
    catch (SourcedException& e)
    {
        std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
        return -1;
    }
    catch (std::exception& e)
    {
        std::cerr << "FAILED: " << e.what() << " : " << std::endl;
        return -1;
    }

    return 0;
}
<commit_msg>[C++]: avoid using put_time as gcc 4 doesn't support it.<commit_after>/*
 * Copyright 2016 Real Logic Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <util/MemoryMappedFile.h>
#include <concurrent/errors/ErrorLogReader.h>
#include <util/CommandOptionParser.h>

#include <iostream>
#include <atomic>
#include <thread>
#include <signal.h>
#include <Context.h>
#include <cstdio>

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <iomanip>

using namespace aeron;
using namespace aeron::util;
using namespace aeron::concurrent;
using namespace aeron::concurrent::errors;
using namespace std::chrono;

static const char optHelp   = 'h';
static const char optPath   = 'p';

struct Settings
{
    std::string basePath = Context::defaultAeronPath();
};

Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv)
{
    cp.parse(argc, argv);
    if (cp.getOption(optHelp).isPresent())
    {
        cp.displayOptionsHelp(std::cout);
        exit(0);
    }

    Settings s;

    s.basePath = cp.getOption(optPath).getParam(0, s.basePath);

    return s;
}

std::string formatDate(std::int64_t millisecondsSinceEpoch)
{
    // yyyy-MM-dd HH:mm:ss.SSSZ
    milliseconds msSinceEpoch(millisecondsSinceEpoch);
    milliseconds msAfterSec(millisecondsSinceEpoch % 1000);
    system_clock::time_point tp(msSinceEpoch);

    std::time_t tm = system_clock::to_time_t(tp);

    char timeBuffer[80];
    char msecBuffer[8];
    char tzBuffer[8];

    std::strftime(timeBuffer, sizeof(timeBuffer) - 1, "%Y-%m-%d %H:%M:%S.", std::localtime(&tm));
    std::snprintf(msecBuffer, sizeof(msecBuffer) - 1, "%03" PRId64, msAfterSec.count());
    std::strftime(tzBuffer, sizeof(tzBuffer) - 1, "%z", std::localtime(&tm));

    return std::string(timeBuffer) + std::string(msecBuffer) + std::string(tzBuffer);
}

int main (int argc, char** argv)
{
    CommandOptionParser cp;
    cp.addOption(CommandOption (optHelp,   0, 0, "                Displays help information."));
    cp.addOption(CommandOption (optPath,   1, 1, "basePath        Base Path to shared memory. Default: " + Context::defaultAeronPath()));

    try
    {
        Settings settings = parseCmdLine(cp, argc, argv);

        MemoryMappedFile::ptr_t cncFile =
            MemoryMappedFile::mapExisting((settings.basePath + "/" + CncFileDescriptor::CNC_FILE).c_str());

        const std::int32_t cncVersion = CncFileDescriptor::cncVersion(cncFile);

        if (cncVersion != CncFileDescriptor::CNC_VERSION)
        {
            std::cerr << "CNC version not supported: file version=" << cncVersion << std::endl;
            return -1;
        }

        AtomicBuffer errorBuffer = CncFileDescriptor::createErrorLogBuffer(cncFile);

        const int distinctErrorCount = ErrorLogReader::read(
            errorBuffer,
            [](
                std::int32_t observationCount,
                std::int64_t firstObservationTimestamp,
                std::int64_t lastObservationTimestamp,
                const std::string &encodedException)
                {
                    std::printf(
                        "***\n%d observations from %s to %s for:\n %s\n",
                        observationCount,
                        formatDate(firstObservationTimestamp).c_str(),
                        formatDate(lastObservationTimestamp).c_str(),
                        encodedException.c_str());
                },
            0);

        std::printf("\n%d distinct errors observed.\n", distinctErrorCount);
    }
    catch (CommandOptionException& e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        cp.displayOptionsHelp(std::cerr);
        return -1;
    }
    catch (SourcedException& e)
    {
        std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
        return -1;
    }
    catch (std::exception& e)
    {
        std::cerr << "FAILED: " << e.what() << " : " << std::endl;
        return -1;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <aidu_vision/laserscancombination.h>
#include <geometry_msgs/Twist.h>
#include <math.h>
#include <vector>

using namespace aidu;

LaserScanCombination::LaserScanCombination(): core::Node::Node(){

  //subscribing and pubishing
  scanmsg = nh->subscribe("/scan", 1, &LaserScanCombination::LaserScanCallback, this);
  distmsg= nh->subscribe("/sensors", 1, &LaserScanCombination::DistCallback, this);
  laserscanpublisher= nh->advertise<sensor_msgs::LaserScan>("/scan2",1);
}

  void LaserScanCombination::DistCallback(const aidu_vision::DistanceSensors::ConstPtr& distmsg){
    distLeft=distmsg->Left/1000.0;
    distRight=distmsg->Right/1000.0;
  }

  void LaserScanCombination::LaserScanCallback(const sensor_msgs::LaserScan::ConstPtr& scanmsg){
    // Distance sensor position
    const double xSensor=0.23; 	// x distance from kinect
    const double ySensor=0.38;	// y distance from kinect
    const double rMin=sqrt(pow(xSensor,2)+pow(ySensor,2));
    const double thetaMax=asin(ySensor/rMin)+1.5705;
    ROS_INFO("thetamax:%f",thetaMax);
    //getting lasercan data
    sensor_msgs::LaserScan scanmsg2;
    double angle_min=scanmsg->angle_min;
    double angle_max=scanmsg->angle_max;
    double angle_increment=scanmsg->angle_increment;
    int size =(scanmsg->angle_max-scanmsg->angle_min)/(scanmsg->angle_increment);
    ROS_INFO("size:%d", size);

    //adding left and right sensor data to laserscan
    int negaddionalPoints=floor((thetaMax+angle_min)/angle_increment);
    int posaddionalPoints=ceil((thetaMax-angle_max)/angle_increment);
    int totalsize=negaddionalPoints+size+posaddionalPoints;
    ROS_INFO("totalsize:%d",totalsize);
    //Copying laser scan data to new array filled with NaNs
    float* ranges = new float[totalsize];

    for (int i=0;i<negaddionalPoints;i++){
      ranges[i]=std::numeric_limits<double>::quiet_NaN();
    }
    for (int i=negaddionalPoints;i<(negaddionalPoints+size);i++){
      ranges[i]=scanmsg->ranges[i-negaddionalPoints];
    }
    for (int i=(negaddionalPoints+size);i<(totalsize);i++){
      ranges[i]=std::numeric_limits<double>::quiet_NaN();
    }

    //transforming coordinate frame of the ultrasonic sensor data to lasercan frame
    double rLeft=sqrt(pow((xSensor+distLeft),2)+pow(ySensor,2));
    double rRight=sqrt(pow((xSensor+distRight),2)+pow(ySensor,2));
    double thetaLeft=asin(ySensor/rLeft)+1.5705;
    double thetaRight=asin(ySensor/rRight)+1.5705;
    ROS_INFO("thetaleft:%f    thetaright:%f",thetaLeft,thetaRight);

    // Adding ultrasonic sensor data in the laserscan array
    int posLeft=totalsize-ceil((thetaMax-thetaLeft)/angle_increment);
    int posRight=floor((thetaMax-thetaRight)/angle_increment);
    ROS_INFO("posleft=%d    posright:%d",posLeft,posRight);
    ranges[posLeft]=distLeft;
    ranges[posRight]=distRight;

    ROS_INFO("sizeof:%d", sizeof(ranges));
    std::vector<float> ranges2 (ranges, ranges + totalsize);

    //setting new laserscan msg
    scanmsg2.angle_min=-thetaMax;
    scanmsg2.angle_max=-thetaMax+totalsize*angle_increment;
    scanmsg2.ranges=ranges2;
    scanmsg2.angle_increment=scanmsg->angle_increment;
    scanmsg2.range_max=scanmsg->range_max;
    scanmsg2.range_min=scanmsg->range_min;
    scanmsg2.scan_time=scanmsg->scan_time;
    scanmsg2.time_increment=scanmsg->time_increment;
    scanmsg2.header.frame_id=scanmsg->header.frame_id;
    scanmsg2.header.stamp=scanmsg2.header.stamp;
    scanmsg2.intensities=scanmsg->intensities;
    laserscanpublisher.publish(scanmsg2);

    delete[] ranges;
  }

  int main(int argc, char** argv) {
  ros::init(argc, argv, "laserscancombination");
  LaserScanCombination laserscancombination;
  laserscancombination.spin();
  return 0;
}<commit_msg>removed some errorso<commit_after>#include <aidu_vision/laserscancombination.h>
#include <geometry_msgs/Twist.h>
#include <math.h>
#include <vector>

using namespace aidu;

LaserScanCombination::LaserScanCombination(): core::Node::Node(){

  //subscribing and pubishing
  scanmsg = nh->subscribe("/scan", 1, &LaserScanCombination::LaserScanCallback, this);
  distmsg= nh->subscribe("/sensors", 1, &LaserScanCombination::DistCallback, this);
  laserscanpublisher= nh->advertise<sensor_msgs::LaserScan>("/scan2",1);
}

  void LaserScanCombination::DistCallback(const aidu_vision::DistanceSensors::ConstPtr& distmsg){
    distLeft=distmsg->Left/1000.0;
    distRight=distmsg->Right/1000.0;
  }

  void LaserScanCombination::LaserScanCallback(const sensor_msgs::LaserScan::ConstPtr& scanmsg){
    // Distance sensor position
    const double xSensor=0.23; 	// x distance from kinect
    const double ySensor=0.38;	// y distance from kinect
    const double rMin=sqrt(pow(xSensor,2)+pow(ySensor,2));
    const double thetaMax=asin(ySensor/rMin)+1.5705;
    ROS_INFO("thetamax:%f",thetaMax);

    //getting lasercan data
    sensor_msgs::LaserScan scanmsg2;
    double angle_min=scanmsg->angle_min;
    double angle_max=scanmsg->angle_max;
    double angle_increment=scanmsg->angle_increment;
    int size =(scanmsg->angle_max-scanmsg->angle_min)/(scanmsg->angle_increment);
    ROS_INFO("size:%d", size);

    //adding left and right sensor data to laserscan
    int negaddionalPoints=floor((thetaMax+angle_min)/angle_increment);
    int posaddionalPoints=ceil((thetaMax-angle_max)/angle_increment);
    int totalsize=negaddionalPoints+size+posaddionalPoints;
    ROS_INFO("totalsize:%d",totalsize);
    //Copying laser scan data to new array filled with NaNs
    float* ranges = new float[totalsize];

    for (int i=0;i<negaddionalPoints;i++){
      ranges[i]=std::numeric_limits<double>::quiet_NaN();
    }
    for (int i=negaddionalPoints;i<(negaddionalPoints+size);i++){
      ranges[i]=scanmsg->ranges[i-negaddionalPoints];
    }
    for (int i=(negaddionalPoints+size);i<(totalsize);i++){
      ranges[i]=std::numeric_limits<double>::quiet_NaN();
    }

    //transforming coordinate frame of the ultrasonic sensor data to lasercan frame
    double rLeft=sqrt(pow((xSensor+distLeft),2)+pow(ySensor,2));
    double rRight=sqrt(pow((xSensor+distRight),2)+pow(ySensor,2));
    double thetaLeft=asin(ySensor/rLeft)+1.5705;
    double thetaRight=asin(ySensor/rRight)+1.5705;
    ROS_INFO("thetaleft:%f    thetaright:%f",thetaLeft,thetaRight);

    // Adding ultrasonic sensor data in the laserscan array
    int posLeft=totalsize-ceil((thetaMax-thetaLeft)/angle_increment);
    int posRight=floor((thetaMax-thetaRight)/angle_increment);
    ROS_INFO("posleft=%d    posright:%d",posLeft,posRight);
    ranges[posLeft]=rLeft;
    ranges[posRight]=rRight;

    ROS_INFO("sizeof:%d", sizeof(ranges));
    std::vector<float> ranges2 (ranges, ranges + totalsize);

    //setting new laserscan msg
    scanmsg2.angle_min=-thetaMax;
    scanmsg2.angle_max=-thetaMax+totalsize*angle_increment;
    scanmsg2.ranges=ranges2;
    scanmsg2.angle_increment=scanmsg->angle_increment;
    scanmsg2.range_max=scanmsg->range_max;
    scanmsg2.range_min=scanmsg->range_min;
    scanmsg2.scan_time=scanmsg->scan_time;
    scanmsg2.time_increment=scanmsg->time_increment;
    scanmsg2.header.frame_id=scanmsg->header.frame_id;
    scanmsg2.header.stamp=scanmsg2.header.stamp;
    scanmsg2.intensities=scanmsg->intensities;
    laserscanpublisher.publish(scanmsg2);

    delete[] ranges;
  }

  int main(int argc, char** argv) {
  ros::init(argc, argv, "laserscancombination");
  LaserScanCombination laserscancombination;
  laserscancombination.spin();
  return 0;
}<|endoftext|>


<commit_before>//===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the BasicBlock class for the VMCore library.
//
//===----------------------------------------------------------------------===//

#include "llvm/BasicBlock.h"
#include "llvm/Constant.h"
#include "llvm/Instructions.h"
#include "llvm/Type.h"
#include "llvm/Support/CFG.h"
#include "llvm/SymbolTable.h"
#include "llvm/Support/LeakDetector.h"
#include "SymbolTableListTraitsImpl.h"
#include <algorithm>
using namespace llvm;

namespace {
  /// DummyInst - An instance of this class is used to mark the end of the
  /// instruction list.  This is not a real instruction.
  struct DummyInst : public Instruction {
    DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
      // This should not be garbage monitored.
      LeakDetector::removeGarbageObject(this);
    }

    virtual Instruction *clone() const {
      assert(0 && "Cannot clone EOL");abort();
      return 0;
    }
    virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }

    // Methods for support type inquiry through isa, cast, and dyn_cast...
    static inline bool classof(const DummyInst *) { return true; }
    static inline bool classof(const Instruction *I) {
      return I->getOpcode() == OtherOpsEnd;
    }
    static inline bool classof(const Value *V) {
      return isa<Instruction>(V) && classof(cast<Instruction>(V));
    }
  };
}

Instruction *ilist_traits<Instruction>::createSentinel() {
  return new DummyInst();
}
iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
  return BB->getInstList();
}

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

BasicBlock::BasicBlock(const std::string &Name, Function *Parent,
                       BasicBlock *InsertBefore)
  : Value(Type::LabelTy, Value::BasicBlockVal, Name) {
  // Initialize the instlist...
  InstList.setItemParent(this);

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

  if (InsertBefore) {
    assert(Parent &&
           "Cannot insert block before another block with no function!");
    Parent->getBasicBlockList().insert(InsertBefore, this);
  } else if (Parent) {
    Parent->getBasicBlockList().push_back(this);
  }
}

BasicBlock::~BasicBlock() {
  assert(getParent() == 0 && "BasicBlock still linked into the program!");
  dropAllReferences();
  InstList.clear();
}

void BasicBlock::setParent(Function *parent) {
  if (getParent())
    LeakDetector::addGarbageObject(this);

  InstList.setParent(parent);

  if (getParent())
    LeakDetector::removeGarbageObject(this);
}

// Specialize setName to take care of symbol table majik
void BasicBlock::setName(const std::string &name, SymbolTable *ST) {
  Function *P;
  assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) &&
	 "Invalid symtab argument!");
  if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this);
  Value::setName(name);
  if (P && hasName()) P->getSymbolTable().insert(this);
}

void BasicBlock::removeFromParent() {
  getParent()->getBasicBlockList().remove(this);
}

void BasicBlock::eraseFromParent() {
  getParent()->getBasicBlockList().erase(this);
}

TerminatorInst *BasicBlock::getTerminator() {
  if (InstList.empty()) return 0;
  return dyn_cast<TerminatorInst>(&InstList.back());
}

const TerminatorInst *const BasicBlock::getTerminator() const {
  if (InstList.empty()) return 0;
  return dyn_cast<TerminatorInst>(&InstList.back());
}

void BasicBlock::dropAllReferences() {
  for(iterator I = begin(), E = end(); I != E; ++I)
    I->dropAllReferences();
}

// removePredecessor - This method is used to notify a BasicBlock that the
// specified Predecessor of the block is no longer able to reach it.  This is
// actually not used to update the Predecessor list, but is actually used to
// update the PHI nodes that reside in the block.  Note that this should be
// called while the predecessor still refers to this block.
//
void BasicBlock::removePredecessor(BasicBlock *Pred) {
  assert(find(pred_begin(this), pred_end(this), Pred) != pred_end(this) &&
	 "removePredecessor: BB is not a predecessor!");
  if (InstList.empty()) return;
  PHINode *APN = dyn_cast<PHINode>(&front());
  if (!APN) return;   // Quick exit.

  // If there are exactly two predecessors, then we want to nuke the PHI nodes
  // altogether.  However, we cannot do this, if this in this case:
  //
  //  Loop:
  //    %x = phi [X, Loop]
  //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
  //    br Loop                 ;; %x2 does not dominate all uses
  //
  // This is because the PHI node input is actually taken from the predecessor
  // basic block.  The only case this can happen is with a self loop, so we
  // check for this case explicitly now.
  //
  unsigned max_idx = APN->getNumIncomingValues();
  assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
  if (max_idx == 2) {
    BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);

    // Disable PHI elimination!
    if (this == Other) max_idx = 3;
  }

  if (max_idx <= 2) {                // <= Two predecessors BEFORE I remove one?
    // Yup, loop through and nuke the PHI nodes
    while (PHINode *PN = dyn_cast<PHINode>(&front())) {
      PN->removeIncomingValue(Pred); // Remove the predecessor first...

      // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
      if (max_idx == 2) {
        if (PN->getOperand(0) != PN)
          PN->replaceAllUsesWith(PN->getOperand(0));
        else
          // We are left with an infinite loop with no entries: kill the PHI.
          PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
        getInstList().pop_front();    // Remove the PHI node
      }

      // If the PHI node already only had one entry, it got deleted by
      // removeIncomingValue.
    }
  } else {
    // Okay, now we know that we need to remove predecessor #pred_idx from all
    // PHI nodes.  Iterate over each PHI node fixing them up
    PHINode *PN;
    for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ++II)
      PN->removeIncomingValue(Pred);
  }
}

// splitBasicBlock - This splits a basic block into two at the specified
// instruction.  Note that all instructions BEFORE the specified iterator stay
// as part of the original basic block, an unconditional branch is added to
// the new BB, and the rest of the instructions in the BB are moved to the new
// BB, including the old terminator.  This invalidates the iterator.
//
// Note that this only works on well formed basic blocks (must have a
// terminator), and 'I' must not be the end of instruction list (which would
// cause a degenerate basic block to be formed, having a terminator inside of
// the basic block).
//
BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
  assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
  assert(I != InstList.end() &&
	 "Trying to get me to create degenerate basic block!");

  BasicBlock *New = new BasicBlock(BBName, getParent(), getNext());

  // Move all of the specified instructions from the original basic block into
  // the new basic block.
  New->getInstList().splice(New->end(), this->getInstList(), I, end());

  // Add a branch instruction to the newly formed basic block.
  new BranchInst(New, this);

  // Now we must loop through all of the successors of the New block (which
  // _were_ the successors of the 'this' block), and update any PHI nodes in
  // successors.  If there were PHI nodes in the successors, then they need to
  // know that incoming branches will be from New, not from Old.
  //
  for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
    // Loop over any phi nodes in the basic block, updating the BB field of
    // incoming values...
    BasicBlock *Successor = *I;
    PHINode *PN;
    for (BasicBlock::iterator II = Successor->begin();
         (PN = dyn_cast<PHINode>(II)); ++II) {
      int IDX = PN->getBasicBlockIndex(this);
      while (IDX != -1) {
        PN->setIncomingBlock((unsigned)IDX, New);
        IDX = PN->getBasicBlockIndex(this);
      }
    }
  }
  return New;
}
<commit_msg>Reduce the amount of searching this assertion does.  On a testcase of mine, this reduces the time for -simplifycfg in a debug build from 106s to 14.82s<commit_after>//===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the BasicBlock class for the VMCore library.
//
//===----------------------------------------------------------------------===//

#include "llvm/BasicBlock.h"
#include "llvm/Constant.h"
#include "llvm/Instructions.h"
#include "llvm/Type.h"
#include "llvm/Support/CFG.h"
#include "llvm/SymbolTable.h"
#include "llvm/Support/LeakDetector.h"
#include "SymbolTableListTraitsImpl.h"
#include <algorithm>
using namespace llvm;

namespace {
  /// DummyInst - An instance of this class is used to mark the end of the
  /// instruction list.  This is not a real instruction.
  struct DummyInst : public Instruction {
    DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
      // This should not be garbage monitored.
      LeakDetector::removeGarbageObject(this);
    }

    virtual Instruction *clone() const {
      assert(0 && "Cannot clone EOL");abort();
      return 0;
    }
    virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }

    // Methods for support type inquiry through isa, cast, and dyn_cast...
    static inline bool classof(const DummyInst *) { return true; }
    static inline bool classof(const Instruction *I) {
      return I->getOpcode() == OtherOpsEnd;
    }
    static inline bool classof(const Value *V) {
      return isa<Instruction>(V) && classof(cast<Instruction>(V));
    }
  };
}

Instruction *ilist_traits<Instruction>::createSentinel() {
  return new DummyInst();
}
iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
  return BB->getInstList();
}

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

BasicBlock::BasicBlock(const std::string &Name, Function *Parent,
                       BasicBlock *InsertBefore)
  : Value(Type::LabelTy, Value::BasicBlockVal, Name) {
  // Initialize the instlist...
  InstList.setItemParent(this);

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

  if (InsertBefore) {
    assert(Parent &&
           "Cannot insert block before another block with no function!");
    Parent->getBasicBlockList().insert(InsertBefore, this);
  } else if (Parent) {
    Parent->getBasicBlockList().push_back(this);
  }
}

BasicBlock::~BasicBlock() {
  assert(getParent() == 0 && "BasicBlock still linked into the program!");
  dropAllReferences();
  InstList.clear();
}

void BasicBlock::setParent(Function *parent) {
  if (getParent())
    LeakDetector::addGarbageObject(this);

  InstList.setParent(parent);

  if (getParent())
    LeakDetector::removeGarbageObject(this);
}

// Specialize setName to take care of symbol table majik
void BasicBlock::setName(const std::string &name, SymbolTable *ST) {
  Function *P;
  assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) &&
	 "Invalid symtab argument!");
  if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this);
  Value::setName(name);
  if (P && hasName()) P->getSymbolTable().insert(this);
}

void BasicBlock::removeFromParent() {
  getParent()->getBasicBlockList().remove(this);
}

void BasicBlock::eraseFromParent() {
  getParent()->getBasicBlockList().erase(this);
}

TerminatorInst *BasicBlock::getTerminator() {
  if (InstList.empty()) return 0;
  return dyn_cast<TerminatorInst>(&InstList.back());
}

const TerminatorInst *const BasicBlock::getTerminator() const {
  if (InstList.empty()) return 0;
  return dyn_cast<TerminatorInst>(&InstList.back());
}

void BasicBlock::dropAllReferences() {
  for(iterator I = begin(), E = end(); I != E; ++I)
    I->dropAllReferences();
}

// removePredecessor - This method is used to notify a BasicBlock that the
// specified Predecessor of the block is no longer able to reach it.  This is
// actually not used to update the Predecessor list, but is actually used to
// update the PHI nodes that reside in the block.  Note that this should be
// called while the predecessor still refers to this block.
//
void BasicBlock::removePredecessor(BasicBlock *Pred) {
  assert((getNumUses() > 16 ||// Reduce cost of this assertion for complex CFGs.
          find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
	 "removePredecessor: BB is not a predecessor!");

  if (InstList.empty()) return;
  PHINode *APN = dyn_cast<PHINode>(&front());
  if (!APN) return;   // Quick exit.

  // If there are exactly two predecessors, then we want to nuke the PHI nodes
  // altogether.  However, we cannot do this, if this in this case:
  //
  //  Loop:
  //    %x = phi [X, Loop]
  //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
  //    br Loop                 ;; %x2 does not dominate all uses
  //
  // This is because the PHI node input is actually taken from the predecessor
  // basic block.  The only case this can happen is with a self loop, so we
  // check for this case explicitly now.
  //
  unsigned max_idx = APN->getNumIncomingValues();
  assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
  if (max_idx == 2) {
    BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);

    // Disable PHI elimination!
    if (this == Other) max_idx = 3;
  }

  if (max_idx <= 2) {                // <= Two predecessors BEFORE I remove one?
    // Yup, loop through and nuke the PHI nodes
    while (PHINode *PN = dyn_cast<PHINode>(&front())) {
      PN->removeIncomingValue(Pred); // Remove the predecessor first...

      // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
      if (max_idx == 2) {
        if (PN->getOperand(0) != PN)
          PN->replaceAllUsesWith(PN->getOperand(0));
        else
          // We are left with an infinite loop with no entries: kill the PHI.
          PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
        getInstList().pop_front();    // Remove the PHI node
      }

      // If the PHI node already only had one entry, it got deleted by
      // removeIncomingValue.
    }
  } else {
    // Okay, now we know that we need to remove predecessor #pred_idx from all
    // PHI nodes.  Iterate over each PHI node fixing them up
    PHINode *PN;
    for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ++II)
      PN->removeIncomingValue(Pred);
  }
}

// splitBasicBlock - This splits a basic block into two at the specified
// instruction.  Note that all instructions BEFORE the specified iterator stay
// as part of the original basic block, an unconditional branch is added to
// the new BB, and the rest of the instructions in the BB are moved to the new
// BB, including the old terminator.  This invalidates the iterator.
//
// Note that this only works on well formed basic blocks (must have a
// terminator), and 'I' must not be the end of instruction list (which would
// cause a degenerate basic block to be formed, having a terminator inside of
// the basic block).
//
BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
  assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
  assert(I != InstList.end() &&
	 "Trying to get me to create degenerate basic block!");

  BasicBlock *New = new BasicBlock(BBName, getParent(), getNext());

  // Move all of the specified instructions from the original basic block into
  // the new basic block.
  New->getInstList().splice(New->end(), this->getInstList(), I, end());

  // Add a branch instruction to the newly formed basic block.
  new BranchInst(New, this);

  // Now we must loop through all of the successors of the New block (which
  // _were_ the successors of the 'this' block), and update any PHI nodes in
  // successors.  If there were PHI nodes in the successors, then they need to
  // know that incoming branches will be from New, not from Old.
  //
  for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
    // Loop over any phi nodes in the basic block, updating the BB field of
    // incoming values...
    BasicBlock *Successor = *I;
    PHINode *PN;
    for (BasicBlock::iterator II = Successor->begin();
         (PN = dyn_cast<PHINode>(II)); ++II) {
      int IDX = PN->getBasicBlockIndex(this);
      while (IDX != -1) {
        PN->setIncomingBlock((unsigned)IDX, New);
        IDX = PN->getBasicBlockIndex(this);
      }
    }
  }
  return New;
}
<|endoftext|>


<commit_before>/*=========================================================================

 Program:   BlueBerry Platform
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) German Cancer Research Center, Division of Medical and
 Biological Informatics. All rights reserved.
 See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/

#include "QmitkDiffusionImagingAppIntroPart.h"

#include "mitkNodePredicateDataType.h"
#include <berryIWorkbenchWindow.h>
#include <berryIWorkbench.h>
#include <berryIWorkbenchPage.h>
#include <berryIPerspectiveRegistry.h>
#include <berryWorkbenchPreferenceConstants.h>
#include <berryIPreferences.h>
#include <berryIEditorReference.h>

#include <mitkLogMacros.h>

#include <QLabel>
#include <QMessageBox>
#include <QtCore/qconfig.h>
#ifdef QT_WEBKIT
#include <QWebView>
#include <QWebPage>
#endif
#include <QString>
#include <QStringList>
#include <QRegExp>
#include <QChar>
#include <QByteArray>
#include <QDesktopServices>

#include "QmitkStdMultiWidget.h"
#include "QmitkStdMultiWidgetEditor.h"
#include "mitkPluginActivator.h"
#include "mitkDataStorageEditorInput.h"

#include "mitkBaseDataIOFactory.h"
#include "mitkSceneIO.h"
#include "mitkProgressBar.h"
#include "mitkDataNodeFactory.h"
#include "mitkNodePredicateNot.h"
#include "mitkNodePredicateProperty.h"

QmitkDiffusionImagingAppIntroPart::QmitkDiffusionImagingAppIntroPart()
  : m_Controls(NULL)
{
  berry::IPreferences::Pointer workbenchPrefs = mitkPluginActivator::GetDefault()->GetPreferencesService()->GetSystemPreferences();
  workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true);
  workbenchPrefs->Flush();
}

QmitkDiffusionImagingAppIntroPart::~QmitkDiffusionImagingAppIntroPart()
{
  // if the workbench is not closing (that means, welcome screen was closed explicitly), set "Show_intro" false
  if (!this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing())
  {
    berry::IPreferences::Pointer workbenchPrefs = mitkPluginActivator::GetDefault()->GetPreferencesService()->GetSystemPreferences();
    workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, false);
    workbenchPrefs->Flush();
  }
  else
  {
    berry::IPreferences::Pointer workbenchPrefs = mitkPluginActivator::GetDefault()->GetPreferencesService()->GetSystemPreferences();
    workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true);
    workbenchPrefs->Flush();
  }

  // if workbench is not closing (Just welcome screen closing), open last used perspective
  if (this->GetIntroSite()->GetPage()->GetPerspective()->GetId()
    == "org.mitk.diffusionimagingapp.perspectives.welcome" && !this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing())
    {
    berry::IPerspectiveDescriptor::Pointer perspective = this->GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->GetPerspectiveRegistry()->FindPerspectiveWithId("org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp");
    if (perspective)
    {
      this->GetIntroSite()->GetPage()->SetPerspective(perspective);
    }
  }

}

void QmitkDiffusionImagingAppIntroPart::CreateQtPartControl(QWidget* parent)
{
  if (!m_Controls)
  {
    // create GUI widgets
    m_Controls = new Ui::QmitkWelcomeScreenViewControls;
    m_Controls->setupUi(parent);
#ifdef QT_WEBKIT

    // create a QWebView as well as a QWebPage and QWebFrame within the QWebview
    m_view = new QWebView(parent);
    m_view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);

    QUrl urlQtResource(QString("qrc:/org.mitk.gui.qt.welcomescreen/mitkdiffusionimagingappwelcomeview.html"),  QUrl::TolerantMode );
    m_view->load( urlQtResource );

    // adds the webview as a widget
    parent->layout()->addWidget(m_view);
    this->CreateConnections();
#else
    parent->layout()->addWidget(new QLabel("
Please install Qt with the WebKit option to see cool pictures!
"));
#endif
  }
}

#ifdef QT_WEBKIT
void QmitkDiffusionImagingAppIntroPart::CreateConnections()
{
  if ( m_Controls )
  {
    connect( (QObject*)(m_view->page()), SIGNAL(linkClicked(const QUrl& )), this, SLOT(DelegateMeTo(const QUrl& )) );
  }
}

void QmitkDiffusionImagingAppIntroPart::DelegateMeTo(const QUrl& showMeNext)
{
  QString scheme          = showMeNext.scheme();
  QByteArray urlHostname  = showMeNext.encodedHost();
  QByteArray urlPath      = showMeNext.encodedPath();
  QByteArray dataset      = showMeNext.encodedQueryItemValue("dataset");
  QByteArray clear        = showMeNext.encodedQueryItemValue("clear");

  if (scheme.isEmpty()) MITK_INFO << " empty scheme of the to be delegated link" ;

  // if the scheme is set to mitk, it is to be tested which action should be applied
  if (scheme.contains(QString("mitk")) )
  {
    if(urlPath.isEmpty() ) MITK_INFO << " mitk path is empty " ;

    // searching for the perspective keyword within the host name
    if(urlHostname.contains(QByteArray("perspectives")) )
    {
      // the simplified method removes every whitespace
      // ( whitespace means any character for which the standard C++ isspace() method returns true)
      urlPath = urlPath.simplified();
      QString tmpPerspectiveId(urlPath.data());
      tmpPerspectiveId.replace(QString("/"), QString("") );
      std::string perspectiveId  = tmpPerspectiveId.toStdString();

      // is working fine as long as the perspective id is valid, if not the application crashes
      GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() );

      mitk::DataStorageEditorInput::Pointer editorInput;
      editorInput = new mitk::DataStorageEditorInput();
      berry::IEditorPart::Pointer editor = GetIntroSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID);

      QmitkStdMultiWidgetEditor::Pointer multiWidgetEditor;
      mitk::DataStorage::Pointer dataStorage;

      if (editor.Cast<QmitkStdMultiWidgetEditor>().IsNull())
      {
        editorInput = new mitk::DataStorageEditorInput();
        dataStorage = editorInput->GetDataStorageReference()->GetDataStorage();
      }
      else
      {
        multiWidgetEditor = editor.Cast<QmitkStdMultiWidgetEditor>();
        multiWidgetEditor->GetStdMultiWidget()->RequestUpdate();
        dataStorage = multiWidgetEditor->GetEditorInput().Cast<mitk::DataStorageEditorInput>()->GetDataStorageReference()->GetDataStorage();
      }

      bool dsmodified = false;
     if(dataStorage.IsNotNull() && dsmodified)
      {
        // get all nodes that have not set "includeInBoundingBox" to false
        mitk::NodePredicateNot::Pointer pred
            = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox"
                                                                           , mitk::BoolProperty::New(false)));

        mitk::DataStorage::SetOfObjects::ConstPointer rs = dataStorage->GetSubset(pred);

        if(rs->Size() > 0)
        {
          // calculate bounding geometry of these nodes
          mitk::TimeSlicedGeometry::Pointer bounds = dataStorage->ComputeBoundingGeometry3D(rs);
          // initialize the views to the bounding geometry
          mitk::RenderingManager::GetInstance()->InitializeViews(bounds);
        }
      }

    }
    // searching for the load
    if(urlHostname.contains(QByteArray("perspectives")) )
    {
      // the simplified method removes every whitespace
      // ( whitespace means any character for which the standard C++ isspace() method returns true)
      urlPath = urlPath.simplified();
      QString tmpPerspectiveId(urlPath.data());
      tmpPerspectiveId.replace(QString("/"), QString("") );
      std::string perspectiveId  = tmpPerspectiveId.toStdString();

      // is working fine as long as the perspective id is valid, if not the application crashes
      GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() );

      mitk::DataStorageEditorInput::Pointer editorInput;
      editorInput = new mitk::DataStorageEditorInput();
      GetIntroSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID);
    }
    else
    {
      MITK_INFO << "Unkown mitk action keyword (see documentation for mitk links)" ;
    }
  }
  // if the scheme is set to http, by default no action is performed, if an external webpage needs to be
  // shown it should be implemented below
  else if (scheme.contains(QString("http")) )
  {
    QDesktopServices::openUrl(showMeNext);
//    m_view->load( ) ;
  }
  else if(scheme.contains("qrc"))
  {
    m_view->load(showMeNext);
  }

}

#endif

void QmitkDiffusionImagingAppIntroPart::StandbyStateChanged(bool standby)
{

}

void QmitkDiffusionImagingAppIntroPart::SetFocus()
{

}
<commit_msg>Code cleanup<commit_after>/*=========================================================================

 Program:   BlueBerry Platform
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) German Cancer Research Center, Division of Medical and
 Biological Informatics. All rights reserved.
 See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/

#include "QmitkDiffusionImagingAppIntroPart.h"

#include "mitkNodePredicateDataType.h"
#include <berryIWorkbenchWindow.h>
#include <berryIWorkbench.h>
#include <berryIWorkbenchPage.h>
#include <berryIPerspectiveRegistry.h>
#include <berryWorkbenchPreferenceConstants.h>
#include <berryIPreferences.h>
#include <berryIEditorReference.h>

#include <mitkLogMacros.h>

#include <QLabel>
#include <QMessageBox>
#include <QtCore/qconfig.h>
#ifdef QT_WEBKIT
#include <QWebView>
#include <QWebPage>
#endif
#include <QString>
#include <QStringList>
#include <QRegExp>
#include <QChar>
#include <QByteArray>
#include <QDesktopServices>

#include "QmitkStdMultiWidget.h"
#include "QmitkStdMultiWidgetEditor.h"
#include "mitkPluginActivator.h"
#include "mitkDataStorageEditorInput.h"

#include "mitkBaseDataIOFactory.h"
#include "mitkSceneIO.h"
#include "mitkProgressBar.h"
#include "mitkDataNodeFactory.h"
#include "mitkNodePredicateNot.h"
#include "mitkNodePredicateProperty.h"

QmitkDiffusionImagingAppIntroPart::QmitkDiffusionImagingAppIntroPart()
  : m_Controls(NULL)
{
  berry::IPreferences::Pointer workbenchPrefs = mitkPluginActivator::GetDefault()->GetPreferencesService()->GetSystemPreferences();
  workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true);
  workbenchPrefs->Flush();
}

QmitkDiffusionImagingAppIntroPart::~QmitkDiffusionImagingAppIntroPart()
{
  // if the workbench is not closing (that means, welcome screen was closed explicitly), set "Show_intro" false
  if (!this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing())
  {
    berry::IPreferences::Pointer workbenchPrefs = mitkPluginActivator::GetDefault()->GetPreferencesService()->GetSystemPreferences();
    workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, false);
    workbenchPrefs->Flush();
  }
  else
  {
    berry::IPreferences::Pointer workbenchPrefs = mitkPluginActivator::GetDefault()->GetPreferencesService()->GetSystemPreferences();
    workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true);
    workbenchPrefs->Flush();
  }

  // if workbench is not closing (Just welcome screen closing), open last used perspective
  if (this->GetIntroSite()->GetPage()->GetPerspective()->GetId()
    == "org.mitk.diffusionimagingapp.perspectives.welcome" && !this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing())
    {
    berry::IPerspectiveDescriptor::Pointer perspective = this->GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->GetPerspectiveRegistry()->FindPerspectiveWithId("org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp");
    if (perspective)
    {
      this->GetIntroSite()->GetPage()->SetPerspective(perspective);
    }
  }

}

void QmitkDiffusionImagingAppIntroPart::CreateQtPartControl(QWidget* parent)
{
  if (!m_Controls)
  {
    // create GUI widgets
    m_Controls = new Ui::QmitkWelcomeScreenViewControls;
    m_Controls->setupUi(parent);
#ifdef QT_WEBKIT

    // create a QWebView as well as a QWebPage and QWebFrame within the QWebview
    m_view = new QWebView(parent);
    m_view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);

    QUrl urlQtResource(QString("qrc:/org.mitk.gui.qt.welcomescreen/mitkdiffusionimagingappwelcomeview.html"),  QUrl::TolerantMode );
    m_view->load( urlQtResource );

    // adds the webview as a widget
    parent->layout()->addWidget(m_view);
    this->CreateConnections();
#else
    parent->layout()->addWidget(new QLabel("
Please install Qt with the WebKit option to see cool pictures!
"));
#endif
  }
}

#ifdef QT_WEBKIT
void QmitkDiffusionImagingAppIntroPart::CreateConnections()
{
  if ( m_Controls )
  {
    connect( (QObject*)(m_view->page()), SIGNAL(linkClicked(const QUrl& )), this, SLOT(DelegateMeTo(const QUrl& )) );
  }
}

void QmitkDiffusionImagingAppIntroPart::DelegateMeTo(const QUrl& showMeNext)
{
  QString scheme          = showMeNext.scheme();
  QByteArray urlHostname  = showMeNext.encodedHost();
  QByteArray urlPath      = showMeNext.encodedPath();
  QByteArray dataset      = showMeNext.encodedQueryItemValue("dataset");
  QByteArray clear        = showMeNext.encodedQueryItemValue("clear");

  if (scheme.isEmpty()) MITK_INFO << " empty scheme of the to be delegated link" ;

  // if the scheme is set to mitk, it is to be tested which action should be applied
  if (scheme.contains(QString("mitk")) )
  {
    if(urlPath.isEmpty() ) MITK_INFO << " mitk path is empty " ;

    // searching for the perspective keyword within the host name
    if(urlHostname.contains(QByteArray("perspectives")) )
    {
      // the simplified method removes every whitespace
      // ( whitespace means any character for which the standard C++ isspace() method returns true)
      urlPath = urlPath.simplified();
      QString tmpPerspectiveId(urlPath.data());
      tmpPerspectiveId.replace(QString("/"), QString("") );
      std::string perspectiveId  = tmpPerspectiveId.toStdString();

      // is working fine as long as the perspective id is valid, if not the application crashes
      GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() );
    }
  }
  // if the scheme is set to http, by default no action is performed, if an external webpage needs to be
  // shown it should be implemented below
  else if (scheme.contains(QString("http")) )
  {
    QDesktopServices::openUrl(showMeNext);
//    m_view->load( ) ;
  }
  else if(scheme.contains("qrc"))
  {
    m_view->load(showMeNext);
  }

}

#endif

void QmitkDiffusionImagingAppIntroPart::StandbyStateChanged(bool standby)
{

}

void QmitkDiffusionImagingAppIntroPart::SetFocus()
{

}
<|endoftext|>


<commit_before>#include <stdio.h>
#include "Halide.h"

using namespace Halide;

// This test exercises the ability to override halide_get_library_symbol (etc)
// when using JIT code; to do so, it compiles & calls a simple pipeline
// using an OpenCL schedule, since that is known to use these calls
// in a (reasonably) well-defined way and is unlikely to change a great deal
// in the near future; additionally, it doesn't require a particular
// feature in LLVM (unlike, say, Hexagon).

namespace {

void my_error_handler(void* u, const char *msg) {
    if (!strstr(msg, "OpenCL API not found")) {
        fprintf(stderr, "Saw unexpected error: %s\n", msg);
        exit(-1);
    }
    printf("Saw expected error: %s\n", msg);
    printf("Success!\n");
    exit(0);
}

void *my_get_symbol_impl(const char *name) {
    fprintf(stderr, "Saw unexpected call: get_symbol(%s)\n", name);
    exit(-1);
}

void *my_load_library_impl(const char *name) {
    if (!strstr(name, "OpenCL") && !strstr(name, "opencl")) {
        fprintf(stderr, "Saw unexpected call: load_library(%s)\n", name);
        exit(-1);
    }
    printf("Saw load_library: %s\n", name);
    return nullptr;
}

void *my_get_library_symbol_impl(void *lib, const char *name) {
    if (lib != nullptr || strcmp(name, "clGetPlatformIDs") != 0) {
        fprintf(stderr, "Saw unexpected call: get_library_symbol(%p, %s)\n", lib, name);
        exit(-1);
    }
    printf("Saw get_library_symbol: %s\n", name);
    return nullptr;
}

}

int main(int argc, char **argv) {
    // These calls are only available for AOT-compiled code:
    //
    //   halide_set_custom_get_symbol(my_get_symbol_impl);
    //   halide_set_custom_load_library(my_load_library_impl);
    //   halide_set_custom_get_library_symbol(my_get_library_symbol_impl);
    //
    // For JIT code, we must use JITSharedRuntime::set_default_handlers().

    Internal::JITHandlers handlers;
    handlers.custom_get_symbol = my_get_symbol_impl;
    handlers.custom_load_library = my_load_library_impl;
    handlers.custom_get_library_symbol = my_get_library_symbol_impl;
    Internal::JITSharedRuntime::set_default_handlers(handlers);

    Var x, y;
    Func f;
    f(x, y) = cast<int32_t>(x + y);
    Target target = get_jit_target_from_environment().with_feature(Target::OpenCL);
    f.gpu_tile(x, y, 8, 8, TailStrategy::Auto, DeviceAPI::OpenCL);
    f.set_error_handler(my_error_handler);

    Buffer<int32_t> out = f.realize(64, 64, target);

    fprintf(stderr, "Should not get here.\n");
    return -1;
}
<commit_msg>Ensure overrides are called<commit_after>#include <stdio.h>
#include "Halide.h"

using namespace Halide;

// This test exercises the ability to override halide_get_library_symbol (etc)
// when using JIT code; to do so, it compiles & calls a simple pipeline
// using an OpenCL schedule, since that is known to use these calls
// in a (reasonably) well-defined way and is unlikely to change a great deal
// in the near future; additionally, it doesn't require a particular
// feature in LLVM (unlike, say, Hexagon).

namespace {

int load_library_calls = 0;
int get_library_symbol_calls = 0;

void my_error_handler(void* u, const char *msg) {
    if (!strstr(msg, "OpenCL API not found")) {
        fprintf(stderr, "Saw unexpected error: %s\n", msg);
        exit(-1);
    }
    printf("Saw expected error: %s\n", msg);
    if (load_library_calls == 0 || get_library_symbol_calls == 0) {
        fprintf(stderr, "Should have seen load_library and get_library_symbol calls!\n");
        exit(-1);
    }
    printf("Success!\n");
    exit(0);
}

void *my_get_symbol_impl(const char *name) {
    fprintf(stderr, "Saw unexpected call: get_symbol(%s)\n", name);
    exit(-1);
}

void *my_load_library_impl(const char *name) {
    load_library_calls++;
    if (!strstr(name, "OpenCL") && !strstr(name, "opencl")) {
        fprintf(stderr, "Saw unexpected call: load_library(%s)\n", name);
        exit(-1);
    }
    printf("Saw load_library: %s\n", name);
    return nullptr;
}

void *my_get_library_symbol_impl(void *lib, const char *name) {
    get_library_symbol_calls++;
    if (lib != nullptr || strcmp(name, "clGetPlatformIDs") != 0) {
        fprintf(stderr, "Saw unexpected call: get_library_symbol(%p, %s)\n", lib, name);
        exit(-1);
    }
    printf("Saw get_library_symbol: %s\n", name);
    return nullptr;
}

}

int main(int argc, char **argv) {
    // These calls are only available for AOT-compiled code:
    //
    //   halide_set_custom_get_symbol(my_get_symbol_impl);
    //   halide_set_custom_load_library(my_load_library_impl);
    //   halide_set_custom_get_library_symbol(my_get_library_symbol_impl);
    //
    // For JIT code, we must use JITSharedRuntime::set_default_handlers().

    Internal::JITHandlers handlers;
    handlers.custom_get_symbol = my_get_symbol_impl;
    handlers.custom_load_library = my_load_library_impl;
    handlers.custom_get_library_symbol = my_get_library_symbol_impl;
    Internal::JITSharedRuntime::set_default_handlers(handlers);

    Var x, y;
    Func f;
    f(x, y) = cast<int32_t>(x + y);
    Target target = get_jit_target_from_environment().with_feature(Target::OpenCL);
    f.gpu_tile(x, y, 8, 8, TailStrategy::Auto, DeviceAPI::OpenCL);
    f.set_error_handler(my_error_handler);

    Buffer<int32_t> out = f.realize(64, 64, target);

    fprintf(stderr, "Should not get here.\n");
    return -1;
}
<|endoftext|>


<commit_before>#include <UnitTest++.h>
#include <tightdb/column.hpp>
#include "../testsettings.hpp"
#include "../util/number_names.hpp"
#include "verified_string.hpp"

#if TEST_DURATION > 0

using namespace tightdb;

std::string randstring(void);

namespace {

// Support functions for monkey test
uint64_t rand2(int bitwidth = 64)
{
    uint64_t i = (int64_t)rand() * (int64_t)rand() * (int64_t)rand() * (int64_t)rand() * (int64_t)rand();
    if (bitwidth < 64) {
        const uint64_t mask = ((1ULL << bitwidth) - 1ULL);
        i &= mask;
    }
    return i;
}

}

std::string randstring(void)
{
    // If there are in the order of TIGHTDB_MAX_LIST_SIZE different strings, then we'll get a good
    // distribution btw. arrays with no matches and arrays with multiple matches, when
    // testing Find/FindAll
    int64_t t = (rand() % 100) * 100;
    size_t len = (rand() % 10) * 100 + 1;
    std::string s;
    while (s.length() < len)
        s += number_name(t);

    s = s.substr(0, len);
    return s;
}

TEST(ColumnString_monkeytest2)
{
    const uint64_t ITER = 16 * 5000 * TEST_DURATION * TEST_DURATION * TEST_DURATION;
    const uint64_t SEED = 123;

    VerifiedString a;
    Array res;

    srand(SEED);
    unsigned int trend = 5;

    for (size_t iter = 0; iter < ITER; iter++) {

//          if (rand() % 10 == 0) printf("Input bitwidth around ~%d, , a.Size()=%d\n", (int)current_bitwidth, (int)a.Size());

        if (!(rand2() % (ITER / 100))) {
            trend = (unsigned int)rand2() % 10;

            a.find_first(randstring().c_str());
            a.find_all(res, randstring().c_str());
        }

        if (rand2() % 10 > trend && a.Size() < ITER / 100) {
            if (rand2() % 2 == 0) {
                // Insert
                const size_t pos = rand2() % (a.Size() + 1);
                a.Insert(pos, randstring().c_str());
            }
            else {
                // Add
                a.add(randstring().c_str());
            }
        }
        else if (a.Size() > 0) {
            // Delete
            const size_t i = rand2() % a.Size();
            a.Delete(i);
        }
    }

    // Cleanup
    a.Destroy();
    res.Destroy();
}

#endif
<commit_msg>Fix for: New convenience library for test utilities<commit_after>#include <UnitTest++.h>
#include <tightdb/column.hpp>
#include "../testsettings.hpp"
#include "../util/number_names.hpp"
#include "verified_string.hpp"

#if TEST_DURATION > 0

using namespace tightdb;

std::string randstring(void);

namespace {

// Support functions for monkey test
uint64_t rand2(int bitwidth = 64)
{
    uint64_t i = (int64_t)rand() * (int64_t)rand() * (int64_t)rand() * (int64_t)rand() * (int64_t)rand();
    if (bitwidth < 64) {
        const uint64_t mask = ((1ULL << bitwidth) - 1ULL);
        i &= mask;
    }
    return i;
}

}

std::string randstring(void)
{
    // If there are in the order of TIGHTDB_MAX_LIST_SIZE different strings, then we'll get a good
    // distribution btw. arrays with no matches and arrays with multiple matches, when
    // testing Find/FindAll
    int64_t t = (rand() % 100) * 100;
    size_t len = (rand() % 10) * 100 + 1;
    std::string s;
    while (s.length() < len)
        s += test_util::number_name(t);

    s = s.substr(0, len);
    return s;
}

TEST(ColumnString_monkeytest2)
{
    const uint64_t ITER = 16 * 5000 * TEST_DURATION * TEST_DURATION * TEST_DURATION;
    const uint64_t SEED = 123;

    VerifiedString a;
    Array res;

    srand(SEED);
    unsigned int trend = 5;

    for (size_t iter = 0; iter < ITER; iter++) {

//          if (rand() % 10 == 0) printf("Input bitwidth around ~%d, , a.Size()=%d\n", (int)current_bitwidth, (int)a.Size());

        if (!(rand2() % (ITER / 100))) {
            trend = (unsigned int)rand2() % 10;

            a.find_first(randstring().c_str());
            a.find_all(res, randstring().c_str());
        }

        if (rand2() % 10 > trend && a.Size() < ITER / 100) {
            if (rand2() % 2 == 0) {
                // Insert
                const size_t pos = rand2() % (a.Size() + 1);
                a.Insert(pos, randstring().c_str());
            }
            else {
                // Add
                a.add(randstring().c_str());
            }
        }
        else if (a.Size() > 0) {
            // Delete
            const size_t i = rand2() % a.Size();
            a.Delete(i);
        }
    }

    // Cleanup
    a.Destroy();
    res.Destroy();
}

#endif
<|endoftext|>


<commit_before>#include <BidiagonalFactorization.h>
#include <Matrix.h>
#include <SparseMatrix.h>
#include <Vector.h>
#include <gtest/gtest.h>

TEST(BidiagonalFactorization, Factorize4x4Matrix)
{
    /* matrix to be factorized */
    freeaml::Matrix<double> A = {{3.11, 4.20, 4.25, 1.73},
                                 {2.73, 1.23, 3.89, 2.11},
                                 {4.63, 0.00, 1.51, 2.67},
                                 {3.70, 0.00, 0.31, 3.84}};

    freeaml::Matrix<double> U, V;
    freeaml::SparseMatrix<double> Z;

    /* compute the bidiagonal factorization A = UZV^t */
    bool status = freeaml::BidiagonalFactorization::factorize(A, U, Z, V);

    EXPECT_TRUE(status);

    /* compute UZV^t */
    freeaml::Matrix<double> UZVt = U * Z * V.transpose();

    /* compute U^t*U and V^t*V */
    freeaml::Matrix<double> UtU = U.transpose() * U;
    freeaml::Matrix<double> VtV = V.transpose() * V;

    /* I is the 4×4 identity matrix */
    freeaml::Matrix<double> I = freeaml::identity_matrix<double>(4);

    EXPECT_LE((A - UZVt).max_norm(), 1.e-10);
    EXPECT_LE((UtU - I).max_norm(), 1.e-10);
    EXPECT_LE((VtV - I).max_norm(), 1.e-10);
}

TEST(BidiagonalFactorization, Factorize6x4Matrix)
{
    /* matrix to be factorized */
    freeaml::Matrix<double> A = {{3.11, 4.20, 4.25, 1.73},
                                 {2.73, 1.23, 3.89, 2.11},
                                 {4.63, 0.00, 1.51, 2.67},
                                 {3.70, 0.00, 0.31, 3.84},
                                 {2.35, 0.67, 1.48, 4.82},
                                 {1.94, 0.48, 0.00, 1.44}};

    freeaml::Matrix<double> U, V;
    freeaml::SparseMatrix<double> Z;

    /* compute the bidiagonal factorization A = UZV^t */
    bool status = freeaml::BidiagonalFactorization::factorize(A, U, Z, V);

    EXPECT_TRUE(status);

    /* compute UZV^t */
    freeaml::Matrix<double> UZVt = U * Z * V.transpose();

    /* compute U^t*U and V^t*V */
    freeaml::Matrix<double> UtU = U.transpose() * U;
    freeaml::Matrix<double> VtV = V.transpose() * V;

    /* I4 and I6 are the 4×4 and 6×6 identity matrices respectively */
    freeaml::Matrix<double> I4 = freeaml::identity_matrix<double>(4);
    freeaml::Matrix<double> I6 = freeaml::identity_matrix<double>(6);

    EXPECT_LE((A - UZVt).max_norm(), 1.e-10);
    EXPECT_LE((UtU - I6).max_norm(), 1.e-10);
    EXPECT_LE((VtV - I4).max_norm(), 1.e-10);
}

TEST(BidiagonalFactorization, Factorize4x6Matrix)
{
    /* matrix to be factorized */
    freeaml::Matrix<double> A = {{2.02, 0.07, 3.56, 0.96, 3.09, 2.93},
                                 {0.23, 1.13, 1.04, 4.56, 0.77, 2.89},
                                 {0.51, 1.93, 2.06, 4.80, 0.68, 2.28},
                                 {0.28, 0.83, 4.07, 2.25, 3.83, 0.13}};

    freeaml::Matrix<double> U, V;
    freeaml::SparseMatrix<double> Z;

    /* compute the bidiagonal factorization A = UZV^t */
    bool status = freeaml::BidiagonalFactorization::factorize(A, U, Z, V);

    EXPECT_TRUE(status);

    /* compute UZV^t */
    freeaml::Matrix<double> UZVt = U * Z * V.transpose();

    /* compute U^t*U and V^t*V */
    freeaml::Matrix<double> UtU = U.transpose() * U;
    freeaml::Matrix<double> VtV = V.transpose() * V;

    /* I4 and I6 are the 4×4 and 6×6 identity matrices respectively */
    freeaml::Matrix<double> I4 = freeaml::identity_matrix<double>(4);
    freeaml::Matrix<double> I6 = freeaml::identity_matrix<double>(6);

    EXPECT_LE((A - UZVt).max_norm(), 1.e-10);
    EXPECT_LE((UtU - I4).max_norm(), 1.e-10);
    EXPECT_LE((VtV - I6).max_norm(), 1.e-10);
}
<commit_msg>fixes test names<commit_after>#include <BidiagonalFactorization.h>
#include <Matrix.h>
#include <SparseMatrix.h>
#include <Vector.h>
#include <gtest/gtest.h>

TEST(BidiagonalFactorizationTest, Factorize4x4Matrix)
{
    /* matrix to be factorized */
    freeaml::Matrix<double> A = {{3.11, 4.20, 4.25, 1.73},
                                 {2.73, 1.23, 3.89, 2.11},
                                 {4.63, 0.00, 1.51, 2.67},
                                 {3.70, 0.00, 0.31, 3.84}};

    freeaml::Matrix<double> U, V;
    freeaml::SparseMatrix<double> Z;

    /* compute the bidiagonal factorization A = UZV^t */
    bool status = freeaml::BidiagonalFactorization::factorize(A, U, Z, V);

    EXPECT_TRUE(status);

    /* compute UZV^t */
    freeaml::Matrix<double> UZVt = U * Z * V.transpose();

    /* compute U^t*U and V^t*V */
    freeaml::Matrix<double> UtU = U.transpose() * U;
    freeaml::Matrix<double> VtV = V.transpose() * V;

    /* I is the 4×4 identity matrix */
    freeaml::Matrix<double> I = freeaml::identity_matrix<double>(4);

    EXPECT_LE((A - UZVt).max_norm(), 1.e-10);
    EXPECT_LE((UtU - I).max_norm(), 1.e-10);
    EXPECT_LE((VtV - I).max_norm(), 1.e-10);
}

TEST(BidiagonalFactorizationTest, Factorize6x4Matrix)
{
    /* matrix to be factorized */
    freeaml::Matrix<double> A = {{3.11, 4.20, 4.25, 1.73},
                                 {2.73, 1.23, 3.89, 2.11},
                                 {4.63, 0.00, 1.51, 2.67},
                                 {3.70, 0.00, 0.31, 3.84},
                                 {2.35, 0.67, 1.48, 4.82},
                                 {1.94, 0.48, 0.00, 1.44}};

    freeaml::Matrix<double> U, V;
    freeaml::SparseMatrix<double> Z;

    /* compute the bidiagonal factorization A = UZV^t */
    bool status = freeaml::BidiagonalFactorization::factorize(A, U, Z, V);

    EXPECT_TRUE(status);

    /* compute UZV^t */
    freeaml::Matrix<double> UZVt = U * Z * V.transpose();

    /* compute U^t*U and V^t*V */
    freeaml::Matrix<double> UtU = U.transpose() * U;
    freeaml::Matrix<double> VtV = V.transpose() * V;

    /* I4 and I6 are the 4×4 and 6×6 identity matrices respectively */
    freeaml::Matrix<double> I4 = freeaml::identity_matrix<double>(4);
    freeaml::Matrix<double> I6 = freeaml::identity_matrix<double>(6);

    EXPECT_LE((A - UZVt).max_norm(), 1.e-10);
    EXPECT_LE((UtU - I6).max_norm(), 1.e-10);
    EXPECT_LE((VtV - I4).max_norm(), 1.e-10);
}

TEST(BidiagonalFactorizationTest, Factorize4x6Matrix)
{
    /* matrix to be factorized */
    freeaml::Matrix<double> A = {{2.02, 0.07, 3.56, 0.96, 3.09, 2.93},
                                 {0.23, 1.13, 1.04, 4.56, 0.77, 2.89},
                                 {0.51, 1.93, 2.06, 4.80, 0.68, 2.28},
                                 {0.28, 0.83, 4.07, 2.25, 3.83, 0.13}};

    freeaml::Matrix<double> U, V;
    freeaml::SparseMatrix<double> Z;

    /* compute the bidiagonal factorization A = UZV^t */
    bool status = freeaml::BidiagonalFactorization::factorize(A, U, Z, V);

    EXPECT_TRUE(status);

    /* compute UZV^t */
    freeaml::Matrix<double> UZVt = U * Z * V.transpose();

    /* compute U^t*U and V^t*V */
    freeaml::Matrix<double> UtU = U.transpose() * U;
    freeaml::Matrix<double> VtV = V.transpose() * V;

    /* I4 and I6 are the 4×4 and 6×6 identity matrices respectively */
    freeaml::Matrix<double> I4 = freeaml::identity_matrix<double>(4);
    freeaml::Matrix<double> I6 = freeaml::identity_matrix<double>(6);

    EXPECT_LE((A - UZVt).max_norm(), 1.e-10);
    EXPECT_LE((UtU - I4).max_norm(), 1.e-10);
    EXPECT_LE((VtV - I6).max_norm(), 1.e-10);
}
<|endoftext|>