For various implementation reasons, I've defined the following enum:
typedef enum HBSnakeMovementDirection
{
HBSnakeMovementDirectionUp = 1,
HBSnakeMovementDirectionDown = -1,
HBSnakeMovementDirectionRight = 2,
HBSnakeMovementDirectionLeft = -2
}
HBSnakeMovementDirection;
However, if I try to use HBSnakeMovementDirectionRight, I get the following warning:
Implicit conversion changes signedness: 'int' to 'HBSnakeMovementDirection'
It has no problem with any of the other enum values. What's the problem here? I thought it might have to do with mixing negative and positive enum values, but I can't find out anything definitive about this.
(I was able to come up with all positive enum values that allow me to work around this issue, but it still stumped me, so I thought I'd ask about it.)
I should state that, as with all my projects, I enable almost every warning—hence, -Wconversion's complaints—and treat them as errors. (I like to be as strict as possible at compile time.) I'm using LLVM 1.6.
UPDATE 1: Literally any use of HBSnakeMovementDirectionRight results in the preceding warning:
HBSnakeMovementDirection movementDirectionRight = HBSnakeMovementDirectionRight;
I have to cast HBSnakeMovementDirectionRight to HBSnakeMovementDirection to silence the warning.
UPDATE 2: As requested, here is the entire build command that's being issued on my machine:
http://pastie.org/1580957
UPDATE 3: Here is the exact project I'm working on hosted on GitHub:
https://github.com/LucasTizma/Hebi
Specifically, the following tree:
https://github.com/LucasTizma/Hebi/tree/89262e2e53881584daf029e3dd5f1e99dfbd6f96
As Darren said, it does look like a compiler bug, and Dave said it doesn’t happen with Clang 2.0.
I’ve found that the following type definition makes the OP code compile with Clang 1.6:
typedef enum HBSnakeMovementDirection
{
HBSnakeMovementDirectionUp = 1, // Default movement direction upon initialization via -init
HBSnakeMovementDirectionDown = -1,
HBSnakeMovementDirectionLeft = -2,
HBSnakeMovementDirectionRight = 2,
NBSnakeMovementDirectionNone = -3
}
HBSnakeMovementDirection;
(note the additional NBSnakeMovementDirectionNone)
This could be related to LLVM bug 1884, which has been fixed.
I can reproduce this. It certainly looks like a compiler bug to me. The presence of negative values in the enum causes the compiler to mistakenly think that the value of "2" is outside of the range of the enum, hence the warning.
The behavior is the same whether you specify "2" or "HBSnakeMovementDirectionRight": It accepts 1 and rejects 2.
Edit: I tested this in an existing iPhone project, setting the compiler LLVM 1.6 and setting the -Wconversion flag.
typedef enum HBSnakeMovementDirection
{
neg1 = -1,
pos1 = 1,
pos2 = 2,
} HBSnakeMovementDirection;
HBSnakeMovementDirection d = -3; // Warning: Can't convert int to HBSnakeMovementDirection
HBSnakeMovementDirection d = -2; // OK
HBSnakeMovementDirection d = -1; // OK
HBSnakeMovementDirection d = 0; // OK
HBSnakeMovementDirection d = 1; // OK
HBSnakeMovementDirection d = 2; // Warning: Can't convert int to HBSnakeMovementDirection
HBSnakeMovementDirection d = pos2; // Warning: Can't convert int to HBSnakeMovementDirection
Definitely looks like a compiler bug. I opened the project in Xcode 3 and compiled, and got the error. When I opened the project in Xcode 4 and used the clang2.0 compiler, I got no warnings.
Related
I was running my code through Clippy and it suggested changing the following:
const SPECIAL_VALUE: u8 = 0; // May change eventually.
pub fn version1(value: u8) -> bool {
(value >= 1 && value <= 9) || value == SPECIAL_VALUE
}
Into
pub fn version2(value: u8) -> bool {
(1..=9).contains(&value) || value == SPECIAL_VALUE
}
Since it is more readable. Unfortunately the resulting assembly output is twice as long, even with optimization level 3. Manually inlining it (2-nestings down), gives almost the same code as version1 and is as efficient.
pub fn manually_inlined(value: u8) -> bool {
(1 <= value && value <= 9) || value == SPECIAL_VALUE
}
If I remove the || value == SPECIAL_VALUE they all resolve with the same (though with 1 more instruction added to decrement the parameter value before a compare). Also if I change SPECIAL_VALUE to something not adjacent to the range they all resolve to same assembly code as version2, which is the reason why I kept it 0 unless I eventually have to change it.
I have a link to Godbolt with the code here: https://rust.godbolt.org/z/bMYzfcYob
Why is the compiler failing to properly inline/optimize version2? Is it an "optimization bug"? Or am I misunderstanding some semantics of Rust, maybe something with the borrowing prevents the optimization, but can't the compiler assume no mutation of value due to the aliasing and referencing rules?
Trying to do the same in C++ suggest, yields the worse option in both cases (https://godbolt.org/z/zahfz65W3)
Edit: Changing the compiler for my C++ version to GCC makes it optimized in both cases.
This was indeed a missed optimization opportunity that has now been corrected in LLVM. https://github.com/rust-lang/rust/issues/90609#issuecomment-1046037263 .
I am getting into Vulkan and stumbled on my first problem. When trying to create a debug report callback (validation layers and debug extensions are available on my intel hd vulkan driver, at least it says so), it fails telling me vkCreateDebugReportCallbackEXT is an unresolved symbol. When trying to get the function pointer it fails telling me vkCreateDebugReportCallbackEXT is already defined.
Which it is, in the Vulkan header. I could set VK_NO_PROTOTYPES but then I would have to load everything by hand. Is there a way around this? Just using a different name for the function pointer won't work, since I am using Vulkan-Hpp and it uses vkCreateDebugReportCallbackEXT as it is.
Is this a driver bug, telling me debug extensions are available, but there are not?
Btw, I am using VS2015.
Thanks for any help
That's normal. vulkan.h defines them as a global functions. But the loader commands obviously return function pointer.
Normally you would just use a different name you like. But I like to have the canonical names too...
I solve it by defining the function myself (using the declaration from vulkan.h) which in turn calls the loaded pointer:
VKAPI_ATTR VkResult VKAPI_CALL vkCommandEXT( /*...*/ ){
return fpCommandEXT( /*...*/ );
}
(Shameless self-promotion) Like so:
https://github.com/krOoze/Hello_Triangle/blob/8227220/ErrorHandling.h#L181
I make the command to self-load on its first use — if you don't like that, in older commit I had more conventional loader:
https://github.com/krOoze/Hello_Triangle/blob/699ab57/HelloTriangle.cpp#L731
PS:
Khronos themselves just added loader code that illustrates that nicely:
https://github.com/KhronosGroup/Vulkan-Docs/blob/1.0/src/ext_loader/vulkan_ext.c
If you handle multiple VkInstances or VkDevices the loaded functions have to be dispatched to the correct instance or device. For example, I do that (likely inefficiently) here:
https://github.com/krOoze/Hello_Triangle/blob/a691de5/ExtensionLoader.h
I had same issue, couldn't find solution so i solved it this way
(might be wrong, but i just want to share in case it will help somebody):
struct DebugDispatch {
//KHRONOS
PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT = 0;
PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT = 0;
//LUNARG
PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT = 0;
PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT = 0;
}
VKAPI_ATTR vk::Bool32 VKAPI_CALL debugReportCallback(...){...}
VKAPI_ATTR vk::Bool32 VKAPI_CALL debugUtilsMessengerCallback(...){...}
enum class ValidationFlagsBits : unsigned int {
NONE = 0,
KHRONOS = 1,
LUNARG = 1 << 1
};
typedef vk::Flags<ValidationFlagsBits> ValidationFlags;
void Example(){
...
vk::Instance instance;
instance = vk::createInstance(...);
DebugDispatch debug_dispatch;
vk::DebugReportCallbackEXT debug_report_callback;
vk::DebugUtilsMessengerEXT debug_utils_messenger;
if(validation_flags & ValidationFlagsBits::KHRONOS){
debug_dispatch.vkCreateDebugReportCallbackEXT =
(PFN_vkCreateDebugReportCallbackEXT)instance.getProcAddr("vkCreateDebugReportCallbackEXT");
debug_dispatch.vkDestroyDebugReportCallbackEXT =
(PFN_vkDestroyDebugReportCallbackEXT)instance.getProcAddr("vkDestroyDebugReportCallbackEXT");
vk::DebugUtilsMessengerCreateInfoEXT create_info{};
create_info.messageSeverity = ...;
create_info.messageType = ...;
create_info.pfnUserCallback = reinterpret_cast<PFN_vkDebugUtilsMessengerCallbackEXT>(&debugUtilsMessengerCallback);
debug_utils_messenger = instance.createDebugUtilsMessengerEXT(create_info, nullptr, debug_dispatch);
}
if(validation_flags & ValidationFlagsBits::LUNARG){
debug_dispatch.vkCreateDebugUtilsMessengerEXT =
(PFN_vkCreateDebugUtilsMessengerEXT)instance.getProcAddr("vkCreateDebugUtilsMessengerEXT");
debug_dispatch.vkDestroyDebugUtilsMessengerEXT =
(PFN_vkDestroyDebugUtilsMessengerEXT)instance.getProcAddr("vkDestroyDebugUtilsMessengerEXT");
vk::DebugReportCallbackCreateInfoEXT create_info{};
create_info.flags = ...;
create_info.pfnCallback = reinterpret_cast<PFN_vkDebugReportCallbackEXT>(&debugReportCallback);
debug_report_callback = instance.createDebugReportCallbackEXT(create_info, nullptr, debug_dispatch);
}
...
if(validation_flags & ValidationFlagsBits::KHRONOS){
instance.destroyDebugUtilsMessengerEXT(debug_utils_messenger, nullptr, debug_dispatch);
}
if(validation_flags & ValidationFlagsBits::LUNARG){
instance.destroyDebugReportCallbackEXT(debug_report_callback, nullptr, debug_dispatch);
}
instance.destroy();
}
I was trying out lambda functions and making a jump table to execute them, but I found g++ didn't recognize the type of the lambda function such that I could assign them to an array or tuple container.
One such attempt was this:
auto x = [](){};
decltype(x) fn = [](){};
decltype(x) jmpTable[] = { [](){}, [](){} };
On compilation I get these errors:
tst.cpp:53:27: error: conversion from ‘main()::<lambda()>’ to non-scalar type ‘main()::<lambda()>’ requested
tst.cpp:54:39: error: conversion from ‘main()::<lambda()>’ to non-scalar type ‘main()::<lambda()>’ requested
Hmmmm, can't convert from type A to non-scalar type A? What's that mean? o.O
I can use std::function to get this to work, but a problem with that is it doesn't seem to work with tuple:
function<void()> jmpTable[] = [](){}; // works
struct { int i; function<void()>> fn; } myTuple = {1, [](){}}; // works
tuple<int, function<void()>> stdTuple1 = {1, [](){}}; // fails
tuple<int, function<void()>> stdTuple2 = make_tuple(1, [](){}); // works
tst.cpp:43:58: error: converting to ‘std::tuple<int, std::function<void()> >’ from initializer list would use explicit constructor ‘std::tuple<_T1, _T2>::tuple(_U1&&, _U2&&) [with _U1 = int, _U2 = main()::<lambda()>, _T1 = int, _T2 = std::function<void()>]’
Constructor marked explicit? Why?
So my question is if I am doing something invalid or is this version just not quite up to the task?
Hmmmm, can't convert from type A to non-scalar type A? What's that mean? o.O
No, that's not a conversion to the same type. Despite having identical bodies, the different lambdas have different types. Newer versions of GCC make this clearer, and give the error message:
error: conversion from '__lambda1' to non-scalar type '__lambda0' requested
clang does even better:
error: no viable conversion from '<lambda at test.cc:2:18>' to 'decltype(x)' (aka '<lambda at test.cc:1:10>')
I can use std::function to get this to work, but a problem with that is it doesn't seem to work with tuple:
It does (with 4.5.4, at least, I don't have 4.5.3 to test), but your initialisation isn't quite right.
tuple<int, function<void()>> stdTuple1 {1, [](){}}; // lose the = to initialise stdTuple1 directly
I'm not sure about the state of n3043 in 4.5.3, but you should be able to use function pointer conversion. If I'm not misunderstanding your usage intentions, this may work for you;
void (*x)();
decltype(x) fn = [](){};
decltype(x) jmpTable[] = { [](){}, [](){} };
I'm a newbie to this site, so if I mess up any question-asking etiquette here I apologize in advance... Thanks!
This is extremely simplified example code, but I think it shows what I'm talking about: I have a C++ method that makes a call into another method to test a value...
char m_array[MAX]; // class member, MAX is a #define
foo(unsigned int n)
{
if (validNumber(n)) //test n
{
// do stuff
m_array[n-1] = 0;
}
}
where: validNumber(unsigned int val) { return ((val > 0) && (val <= MAX)); }
The irritation I'm having is that PC Lint's Value Tracking seems to ignore the validNumber() call and gives a warning 661 possible access of out-of-bounds pointer (1 beyond end of data) by operator '['
However if I do it like this, Lint is happy:
if ((n > 0) && (n <= MAX)) //test n
...
So, does Lint's Value Tracking just not work if the test is a method call?
Thanks again,
HF
I'd guess that validNumber is defined after foo, but in any case, PC Lint normally makes one pass over the code, and in such cases it doesn't see validNumber as a check for the boundaries for n.
You could try the option -passes(2) or even 3, and see what Lint makes out of it. I think (but didn't try) that Lint would then correctly note that the value for n is within the correct bounds.
I have seen that GCC is not able to detect pure mathematical functions and it needs you to provide the attribute "const" to indicate that.
What compilers can detect pure mathematical functions and optimize them (without telling you so)?
To do so is inherently risky in languages that have pointers and lack global compilation & analysis. So, if a an operation is declared non-const, the compiler must assume it could have side-effects.
Example:
//getx.cpp
int GetX(int input)
{
int* pData = (int*) input;
*pData = 50;
return 0;
}
// gety.cpp
int GetY(int input)
{
return GetX(input + 4);
}
// main.cpp
int main()
{
int arg[] { 0, 4 };
return GetY((int)arg);
}
The compiler while compiling GetY can't tell that GetX treats its argument as a pointer and dereferences and modifies data in a non-functional, side-effect-prone manner. That information is only available during linking so you'd have to re-invent the concept of linking to include a lot of code generation and analysis to support such a feature.
It's not really (afaik) the compiler that does this, but when writing C# in Visual Studio when using the plugin ReSharper, you can get compile time hints that indicate that it is possible to declare something as const. On the other hand, that doesn't go under the category "without telling you so", so it might not be what you're looking for...
It seems that gcc now does: doing "gcc -O2 -S" on the following code, and reading the assembly, the call to foo() from within test() is identified as pure and moved outside of the loop:
#include <stdio.h>
double __attribute__((noinline)) foo(double x)
{
x = x + 1;
x = x * x;
if (x > 20)
x -= 1;
x -= x * x;
return x;
}
void test(int iters, double x)
{
int i;
for (i = 0; i < iters; ++i) {
printf("%g\n", foo(x));
}
}
This is Fedora 22, gcc 5.1.1, x86_64. I haven't tried, but with -flto, I would expect this to work across compilation units.
Also, it is worth noting that today gcc has the command line options -Wsuggest-attribute=pure and -Wsuggest-attribute=const.