Showing posts with label cpp_rvo. Show all posts
Showing posts with label cpp_rvo. Show all posts

Jan 1, 2019

[C++][C] The case of forgotten return bug

read: https://yurichev.com/blog/no_return/

Scenarios:
  • Even without return variable from a function signature which returns, %rax is filled with
    something due to compiler will use as less registers as possible.
    Since %rax is filled with something which is not the returning value, this issues a bug
    (in debug/none-optimized mode).
  • While in optimization mode, optimize prevails, thus a function with signature which returns but inside the function body has no return statement, compiler opts out with returning 0, which again, issues a bug.


Take away:
  • Always turns on -Wall during the programming(I'm using Vim) and compiling.
  • In C++17, consider using attribute: [[nodiscard]] a good practice.
    For side-effect only, take Discarded-value expressions into consideration.


#include <stdio.h>
#include <stdlib.h>

struct color
{
        int R;
        int G;
        int B;
};

struct color* create_color (int R, int G, int B)
{
        struct color* rt=(struct color*)malloc(sizeof(struct color));
        rt->R=R;
        rt->G=G;
        rt->B=B;
        // must be "return rt;" here
};

int main()
{
        struct color* a=create_color(1,2,3);
        printf ("%d %d %d\n", a->R, a->G, a->B);
};

https://godbolt.org/z/o8bgyD
create_color(int, int, int):
pushq %rbp
movq %rsp, %rbp
subq $32, %rsp
movl %edi, -20(%rbp)
movl %esi, -24(%rbp)
movl %edx, -28(%rbp)
movl $12, %edi
call malloc
movq %rax, -8(%rbp)
movq -8(%rbp), %rax
movl -20(%rbp), %edx
movl %edx, (%rax)
movq -8(%rbp), %rax
movl -24(%rbp), %edx
movl %edx, 4(%rax)
movq -8(%rbp), %rax
movl -28(%rbp), %edx
movl %edx, 8(%rax)
nop
leave
ret
.LC0:
.string "%d %d %d\n"
main:
pushq %rbp
movq %rsp, %rbp
subq $16, %rsp
movl $3, %edx
movl $2, %esi
movl $1, %edi
call create_color(int, int, int)
movq %rax, -8(%rbp)
movq -8(%rbp), %rax
movl 8(%rax), %ecx
movq -8(%rbp), %rax
movl 4(%rax), %edx
movq -8(%rbp), %rax
movl (%rax), %eax
movl %eax, %esi
movl $.LC0, %edi
movl $0, %eax
call printf
movl $0, %eax
leave
ret

Nov 4, 2018

[cppcon 2018] Return Value Optimization: Harder Than It Looks - Arthur O'Dwyer

With this talk, Arthur tried to focus on not only RVO but what if RVO doesn't work, what mechanisms kick in and how it effects our design.


'return slot' definition
iff the function returning type's size is larger than %eax, the compiler will pass in extra parameter to the callee function which stores the pointer to the caller's pre-allocated address which is large enough to store the callee's returning type's value.
Caller owns the return slot address.


Copy elision rules in C++
  • C++03/14
  • C++17
    • Mandatory in many circumstances
  • Cases RVO not possible


RVO Limitation (which can't do RVO)
  • callee has branches
  • returning callee's argument
  • returning a global/namespace level varaible
  • returning a derived type of returning type
Even though above cases can't be RVOed, the compiler
will try hard to do you an implicit move.
But, if it just can NOT being moved, copy instead.

Digress a bit here:


Beware:
Overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. If the first overload resolution fails or was not performed, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object's type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue. (Thus do a copy through copy constructor)

RVO/Move works on constructor, not on conversion operators.

Why RVO works on constructor that takes rvalue reference (move) / const reference (copy constructor, C++98)?
Because we have unique_ptr
Why RVO doesn't work on conversion operators?
Auh, KISS.
// Works due to unique_ptr has template move constructor, which allows RVO.
// Since unique_ptr does not allow being copied.
unique_ptr<base> Call()
{
    unique_ptr<derived> de{new Derived{}};
    return de;                              
}


Types that have move constructor which enables RVO in the standard:
(i.e the return type isn't same as function return signature type)


While the callee's parameter is reference, always do a copy, never move.
(Since you don't know what it refers to)

Base Call(Base&& b){
    return b;
}


Base Call(Base& b){
    return b;
}


Base Call(Base& b){
    Base&& x = std::move(b);
    return x;
}

What about this one:
// Compiler will either do a Move or a Copy.
Base Call(Base b){
    b += 1;
    return b;
}


Other Take aways:
  • When returning lambda, consider designing the lambda which can be RVOed.
  • Don't do std::move by yourself,
    i.e DO NOT DO
    return std::move(x);
    which will disable RVO/implicit move.
  • When dealing with legacy C code, use C++ as a wrapper, which gives as value semantics(RAII style).
  • In clang, use -Wall to enable -Wreturn-std-move

Nov 2, 2018

[CppCon 2018] The Nightmare of Initialization in C++ - Nicolai Josuttis


Interestingly RVO (Return Value Optimization) has become a hot topic in C++17, not only Nicolai talks about it, Arthur O'Dwyer also has a talk in CppCon2018 talking about RVO.

Years back when I first read of RVO is, again, from the classic book written by Stanley B. Lippman, Inside the C++ Object Model. RVO used to be an option for compiler, but now is mandated in C++17.


Initialization in C++
Well, you could see this mocking video about C++'s initialization on the web :-)


RVO works for constructor
// RVO works for constructor.
auto a = std::atomic<int>{9};
auto r = std::array{};



C++17's prvalue:
prvalue can temporary materialization conversion' to
xvalue.


Does compiler always warns while doing a narrow type
conversion?
Not really for template:
[C++11/14] constant expression value can convert to smaller size data structure


C++17 relaxed Enumeration Initialization
Initialize enumerations with integral values:

enum class Test { a, b};
Test te1{0}; // ok in C++17

enum Int : unsigned long long{};
Int ie1{42}; // ok in C++17

enum Flag {b1=1, b2=2};
Flag f3{0}; // error!

std::byte b{0b111'111}; // ok in C++17

Rule of thumb:
Make sure either both default constructor and one argument/initialization list constructor explicit or both non-explicit.
If not:
vector<int> v1 = {1 , 2}; // ok
vector<int> v2 = {1}; // ok
vector<int> v2 = {}; // error! in C++11, fixed in C++14


Aggregates:
  • C
    • Structs or arrays (types for multiple members, not union)
  • C++98/03: class or array with:
    • no user-declared constructors
    • no private or protected non-static data members
    • no base classes
    • no virtual functions
  • C++11/14: class or array with:
    • no user-provided constructors
    • no private or protected non-static data members
    • no base classes
    • no virtual functions
  • C++17: class or array with:
    • no user-provided, explicit, or inherited constructors
    • no private or protected non-static data members
    • no virtual, private, or protected base classes
    • no virtual functions
  • std::array<> is an aggregate,
    i.e without initialize value is an UB.
Reference:
[golang][c++] padding


assert:
Beware about comma, since assert is a macro.
This is mentioned in Davide Di Gennaro's
Advanced Metaprogramming in Classic C++
assert( c == std::complex(0,0)); // ok
assert( c == std::complex{0,0}); // error
assert(( c == std::complex{0,0})); // ok



Reference:

Oct 14, 2018

[C++] C++17 RVO is the standard.

With side-project on Envoy, found something interesting thus jot down for future reference.

  • Idiom:
    Functions take values as arguments and std::move to final destination. (Less constructor/destructor calls involved)

    Or use template trick to limit the universal constructor having higher priority then non-template ones.
  • C++17 has RVO into the language. Thus,
    -fno-elide-constructors
    will not turn off RVO in any how.
  • is_convertible, used as the guard for universal constructor to allow copy constructor takes itself type's instance or derived one.
    However, is_convertible isn't using the 'cast' as implementation, which is in run-time, it simply uses a form like:
    To test() { return std::declval<From>(); } // ODR use of declval here, which static_assert fails. It's just an example.
    That is to say, any type with conversion operator would meet the is_convertible requirement, not only the derived ones.
  • explicit is your friend. Single parameter constructor, including template ones, use explicit prevent automatic type conversion by accident.

As usual, one example explains what mentioned above.
#include <boost/type_index.hpp>
#include <iostream>
#include <string_view>
#include <utility>

using namespace std;


struct Base {
    // -- 1
    // Guarded , using enable_if_t, is_convertible_v for C++17
    template <typename T, typename = typename enable_if<
                              !is_convertible<T, Base>::value>::type>
    explicit Base(T &&t)
    {
    }

    Base(const Base &) {}  // on purpose, compiler generates by default -- 2

    Base(Base &&) {}  // on purpose, compiler generates by default. -- 3
};

struct Derived : Base {
    using Base::Base;
};

struct Mutation {
    explicit operator Base()
    {
        return Base{42}; // Hits (1)
    }
};

int main()
{
    auto _ = "Pikachu"sv;

    Mutation m;
    // static_cast<Base>(m);  // Can't call this way due to Base's universal
    // constructor installed.
    Base b1{
        m.operator Base()}; // -fno-elide-constructors has no effect for C++17
    // By default Move constructor will never be hit in C++17
    // Prior then C++17, Move constructor will be hit if no -fno-elide-constructors
    Base b2{D{42}}; // Hits (3), no RVO, RVO only happens on _same_ type.
}

Sep 23, 2018

[C++] std::move(R-VALUE) undefined behavior? No.

Callee's RVO r-value is allocated on caller's stack, thus
std::move a returned r-value and reference to it isn't UB.
https://godbolt.org/z/-CllrO
#include <utility>
using namespace std;

struct T {
    int A[1000];
    T()
    {
        for (int i = 0; i < 1000; i++) {
            A[i] = 42;
        }
    }
};


T layer1()
{
    return T{};
}


T layer2()
{
    return layer1();
}

T layer3()
{
    return layer2();
}


int main()
{
    T const &ref{std::move(layer3())};
    T &&ref2{std::move(layer3())};
    int const &ref3{layer3().A[99]};
    int const &ref4{layer3().A[999]};
}

A NRVO will be allocated on caller's stack as well.
https://godbolt.org/z/iqbhCI
#include <utility>
using namespace std;

struct T {
    int A[1000];
    T()
    {
        for (int i = 0; i < 1000; i++) {
            A[i] = 42;
        }
    }
};


T layer1()
{
    T t{};
    return t;
}


int main()
{

    int const &ref4{layer1().A[999]};
}

However, if we try to out smart the compiler using std::move for NRVO, compiler has no idea what's inside the std::move thus
create the large object on callee's stack and then do a
memcpy back to caller's stack.
https://godbolt.org/z/ql7B9i
#include <utility>
using namespace std;

struct T {
    int A[1000];
    T()
    {
        for (int i = 0; i < 1000; i++) {
            A[i] = 42;
        }
    }
};


T layer1()
{
    T t{};
    return std::move(t);
}


int main()
{

    int const &ref4{layer1().A[999]};
}


Some UB examples here https://github.com/jeaye/value-category-cheatsheet
is not correct.

Further reading:
https://abseil.io/tips/11

Feb 16, 2016

[RVO] Details

Conditions for RVO:
iff: 
(1) the type of the local object is the same as that returned by the function and 
(2) the local object  (i.e not rvalue, but l-value local object ) is what's being returned.



If the conditions for the RVO are met,
but compilers choose not to perform copy elision, 
the object being returned must be treated as an rvalue.

The situation is similar for by-value function parameters.
They’re not eligible for copy elision with respect to their function’s return value,
but compilers must treat them as rvalues if they’re returned.


clang/g++ command to avoid RVO:

#  -fno-elide-constructors

reference:
http://stackoverflow.com/questions/13099603/c11-move-constructor-not-called-default-constructor-preferred/13099664#13099664

Aug 8, 2015

[C++14] copy this ptr and RVO

Either capture this or copy *this


template <typename R, typename... Args>
auto memoize(R(*fn)(Args...))
{
    std::map<std::tuple<Args...>, R> table;
    return [fn, table](Args... args) mutable -> R {
        auto argt = std::make_tuple(args...);
        auto memoized = table.find(argt);
        if(memoized == table.end())
        {
            auto result = fn(args...);
            table[argt] = result;
            return result;
        }
        else
        {
            return memoized->second;
        }
    };
}
g++ -fno-elide-constructors

Apr 26, 2014

[C++11] RVO


#include <iostream>

// print out 1 3 1

struct X {
X(const char *) { std::cout << 1; }
X(const X &) { std::cout << 2; }
X(X &&) { std::cout << 3; }
};

X f(X a) {
   return a; // no RVO due to 'a' is argument which construct inplace with parameter "hello"
             // always needs a copy constructor to copy 'a' to the extra tmp returned argument 'X'
}


X g(const char * b) {
   X c(b); //NRVO
   return c;
}

int main() {
   f("hello");
   g("hello");
}

Mar 15, 2014

[C++][C++11] Compiler generated implicit default copy constructor/move constructor assign/move assign op deprecated.

clang++ -std=c++11 test.cpp -Wdeprecated

if any of copy/move constructor defined:
default constructor must be defined if needed(as before)

If user defined copy constructor:
Move constructor is =delete

If user defined assign operator:
Move assign operator is =delete

If user defined move constructor:
Copy constructor is =delete
assign operator is =delete

If user defined move assign operator:
Copy constructor is =delete
assign operator is =delete

If user defined destructor:
None of the implicit copy/move constructor, assign/move assign operator is defined.
Generate warning of deprecated

Also beware of RVO(copy elision):
copy elision
Want Speed? Pass by Value.

------------------------

§12.8.32 of the C++11 standard:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects.
In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later (即target) of the times when the two objects would have been destroyed without the optimization. 
This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which maybe combined to eliminate multiple copies):
  • in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value (return type要與function return type宣告的一致, 且無CV qualify) 
  • in a throw-expression, when the operand is the name of a non-volatile automatic object whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one), the copy/move operation from the operand to the exception object (15.1) can be omitted by constructing the automatic object directly into the exception object 
  • when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move(傳入copy/move constructor若為temporary object, 且無CV qualify,則可omit) 
  • when the exception-declaration of an exception handler (Clause 15) declares an object of the same type (except for cv-qualification) as the exception object (15.1), the copy/move operation can be omitted by treating the exception-declaration as an alias for the exception object if the meaning of the program will be unchanged except for the execution of constructors and destructors for the object declared by the exception-declaration.
Reference:
Everything You Ever Wanted to Know About Move Semantics