blob: 4a3ae4db2eed5089774a02192345e72710d0b4c5 [file] [log] [blame]
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +01001///
Adnan AlSinanabc093b2022-02-08 16:57:06 +00002/// Copyright (c) 2019-2022 Arm Limited.
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +01003///
4/// SPDX-License-Identifier: MIT
5///
6/// Permission is hereby granted, free of charge, to any person obtaining a copy
7/// of this software and associated documentation files (the "Software"), to
8/// deal in the Software without restriction, including without limitation the
9/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10/// sell copies of the Software, and to permit persons to whom the Software is
11/// furnished to do so, subject to the following conditions:
12///
13/// The above copyright notice and this permission notice shall be included in all
14/// copies or substantial portions of the Software.
15///
16/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22/// SOFTWARE.
23///
24namespace arm_compute
25{
26/**
Sheri Zhangd813bab2021-04-30 16:53:41 +010027@page contribution_guidelines Contribution Guidelines
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +010028
29@tableofcontents
30
31If you want to contribute to Arm Compute Library, be sure to review the following guidelines.
32
33The development is structured in the following way:
34- Release repository: https://github.com/arm-software/ComputeLibrary
35- Development repository: https://review.mlplatform.org/#/admin/projects/ml/ComputeLibrary
36- Please report issues here: https://github.com/ARM-software/ComputeLibrary/issues
37
Adnan AlSinanabc093b2022-02-08 16:57:06 +000038@section S5_0_inc_lang Inclusive language guideline
39As part of the initiative to use inclusive language, there are certain phrases and words that were removed or replaced by more inclusive ones. Examples include but not limited to:
40\includedoc non_inclusive_language_examples.dox
41
42Please also follow this guideline when committing changes to Compute Library.
ramelg01b4cd2dc2022-03-30 18:42:23 +010043It is worth mentioning that the term "master" is still used in some comments but only in reference to external code links that Arm has no governance on.
Adnan AlSinanabc093b2022-02-08 16:57:06 +000044
Ramy Elgammalfa8ff8e2022-08-12 16:57:10 +010045Futhermore, starting from release (22.05), 'master' branch is no longer being used, it has been replaced by 'main'. Please update your clone jobs accordingly.
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +010046@section S5_1_coding_standards Coding standards and guidelines
47
48Best practices (as suggested by clang-tidy):
49
50- No uninitialised values
51
52Helps to prevent undefined behaviour and allows to declare variables const if they are not changed after initialisation. See http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-pro-type-member-init.html
53
54@code{.cpp}
55const float32x4_t foo = vdupq_n_f32(0.f);
56const float32x4_t bar = foo;
57
58const int32x4x2_t i_foo = {{
59 vconvq_s32_f32(foo),
60 vconvq_s32_f32(foo)
61}};
62const int32x4x2_t i_bar = i_foo;
63@endcode
64
65- No C-style casts (in C++ source code)
66
67Only use static_cast, dynamic_cast, and (if required) reinterpret_cast and const_cast. See http://en.cppreference.com/w/cpp/language/explicit_cast for more information when to use which type of cast. C-style casts do not differentiate between the different cast types and thus make it easy to violate type safety. Also, due to the prefix notation it is less clear which part of an expression is going to be casted. See http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-pro-type-cstyle-cast.html
68
69- No implicit casts to bool
70
71Helps to increase readability and might help to catch bugs during refactoring. See http://clang.llvm.org/extra/clang-tidy/checks/readability-implicit-bool-cast.html
72
73@code{.cpp}
74extern int *ptr;
75if(ptr){} // Bad
76if(ptr != nullptr) {} // Good
77
78extern int foo;
79if(foo) {} // Bad
80if(foo != 0) {} // Good
81@endcode
82
83- Use nullptr instead of NULL or 0
84
85The nullptr literal is type-checked and is therefore safer to use. See http://clang.llvm.org/extra/clang-tidy/checks/modernize-use-nullptr.html
86
87- No need to explicitly initialise std::string with an empty string
88
89The default constructor of std::string creates an empty string. In general it is therefore not necessary to specify it explicitly. See http://clang.llvm.org/extra/clang-tidy/checks/readability-redundant-string-init.html
90
91@code{.cpp}
92// Instead of
93std::string foo("");
94std::string bar = "";
95
96// The following has the same effect
97std::string foo;
98std::string bar;
99@endcode
100
101- Braces for all control blocks and loops (which have a body)
102
103To increase readability and protect against refactoring errors the body of control block and loops must be wrapped in braces. See http://clang.llvm.org/extra/clang-tidy/checks/readability-braces-around-statements.html
104
105For now loops for which the body is empty do not have to add empty braces. This exception might be revoked in the future. Anyway, situations in which this exception applies should be rare.
106
107@code{.cpp}
108Iterator it;
109while(it.next()); // No need for braces here
110
111// Make more use of it
112@endcode
113
114- Only one declaration per line
115
116Increase readability and thus prevent errors.
117
118@code{.cpp}
119int a, b; // BAD
120int c, *d; // EVEN WORSE
121
122int e = 0; // GOOD
123int *p = nullptr; // GOOD
124@endcode
125
126- Pass primitive types (and those that are cheap to copy or move) by value
127
128For primitive types it is more efficient to pass them by value instead of by const reference because:
129
130 - the data type might be smaller than the "reference type"
131 - pass by value avoids aliasing and thus allows for better optimisations
132 - pass by value is likely to avoid one level of indirection (references are often implemented as auto dereferenced pointers)
133
134This advice also applies to non-primitive types that have cheap copy or move operations and the function needs a local copy of the argument anyway.
135
136More information:
137
138 - http://stackoverflow.com/a/14013189
139 - http://stackoverflow.com/a/270435
140 - http://web.archive.org/web/20140113221447/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
141
142@code{.cpp}
143void foo(int i, long l, float32x4_t f); // Pass-by-value for builtin types
144void bar(const float32x4x4_t &f); // As this is a struct pass-by-const-reference is probably better
145void foobar(const MyLargeCustomTypeClass &m); // Definitely better as const-reference except if a copy has to be made anyway.
146@endcode
147
148- Don't use unions
149
Jakub Sujakee301b32021-06-04 09:46:08 +0100150Unions cannot be used to convert values between different types because (in C++) it is undefined behaviour to read from a member other than the last one that has been assigned to. This limits the use of unions to a few corner cases and therefore the general advice is not to use unions. See http://releases.llvm.org/3.8.0/tools/clang/tools/extra/docs/clang-tidy/checks/cppcoreguidelines-pro-type-union-access.html
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100151
152- Use pre-increment/pre-decrement whenever possible
153
Jakub Sujakee301b32021-06-04 09:46:08 +0100154In contrast to the pre-increment the post-increment has to make a copy of the incremented object. This might not be a problem for primitive types like int but for class like objects that overload the operators, like iterators, it can have a huge impact on the performance. See http://stackoverflow.com/a/9205011
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100155
156To be consistent across the different cases the general advice is to use the pre-increment operator unless post-increment is explicitly required. The same rules apply for the decrement operator.
157
158@code{.cpp}
159for(size_t i = 0; i < 9; i++); // BAD
160for(size_t i = 0; i < 9; ++i); // GOOD
161@endcode
162
163- Don't use uint in C/C++
164
165The C and C++ standards don't define a uint type. Though some compilers seem to support it by default it would require to include the header sys/types.h. Instead we use the slightly more verbose unsigned int type.
166
167- Don't use unsigned int in function's signature
168
169Unsigned integers are good for representing bitfields and modular arithmetic. The fact that unsigned arithmetic doesn't model the behavior of a simple integer, but is instead defined by the standard to model modular arithmetic (wrapping around on overflow/underflow), means that a significant class of bugs cannot be diagnosed by the compiler. Mixing signedness of integer types is responsible for an equally large class of problems.
170
171- No "Yoda-style" comparisons
172
173As compilers are now able to warn about accidental assignments if it is likely that the intention has been to compare values it is no longer required to place literals on the left-hand side of the comparison operator. Sticking to the natural order increases the readability and thus prevents logical errors (which cannot be spotted by the compiler). In the rare case that the desired result is to assign a value and check it the expression has to be surrounded by parentheses.
174
175@code{.cpp}
176if(nullptr == ptr || false == cond) // BAD
177{
178 //...
179}
180
181if(ptr == nullptr || cond == false) // GOOD
182{
183 //...
184}
185
186if(ptr = nullptr || cond = false) // Most likely a mistake. Will cause a compiler warning
187{
188 //...
189}
190
191if((ptr = nullptr) || (cond = false)) // Trust me, I know what I'm doing. No warning.
192{
193 //...
194}
195@endcode
196
197@subsection S5_1_1_rules Rules
198
199 - Use spaces for indentation and alignment. No tabs! Indentation should be done with 4 spaces.
200 - Unix line returns in all the files.
201 - Pointers and reference symbols attached to the variable name, not the type (i.e. char \&foo;, and not char& foo).
202 - No trailing spaces or tabs at the end of lines.
203 - No spaces or tabs on empty lines.
204 - Put { and } on a new line and increase the indentation level for code inside the scope (except for namespaces).
205 - Single space before and after comparison operators ==, <, >, !=.
206 - No space around parenthesis.
207 - No space before, one space after ; (unless it is at the end of a line).
208
209@code{.cpp}
210for(int i = 0; i < width * height; ++i)
211{
212 void *d = foo(ptr, i, &addr);
213 static_cast<uint8_t *>(data)[i] = static_cast<uint8_t *>(d)[0];
214}
215@endcode
216
217 - Put a comment after \#else, \#endif, and namespace closing brace indicating the related name
218
219@code{.cpp}
220namespace mali
221{
222#ifdef MALI_DEBUG
223 ...
224#else // MALI_DEBUG
225 ...
226#endif // MALI_DEBUG
227} // namespace mali
228@endcode
229
230- CamelCase for class names only and lower case words separated with _ (snake_case) for all the functions / methods / variables / arguments / attributes.
231
232@code{.cpp}
233class ClassName
234{
235 public:
236 void my_function();
237 int my_attribute() const; // Accessor = attribute name minus '_', const if it's a simple type
238 private:
239 int _my_attribute; // '_' in front of name
240};
241@endcode
242
243- Use quotes instead of angular brackets to include local headers. Use angular brackets for system headers.
244- Also include the module header first, then local headers, and lastly system headers. All groups should be separated by a blank line and sorted lexicographically within each group.
245- Where applicable the C++ version of system headers has to be included, e.g. cstddef instead of stddef.h.
246- See http://llvm.org/docs/CodingStandards.html#include-style
247
248@code{.cpp}
249#include "MyClass.h"
250
251#include "arm_cv/core/Helpers.h"
252#include "arm_cv/core/Types.h"
253
254#include <cstddef>
255#include <numeric>
256@endcode
257
258- Only use "auto" when the type can be explicitly deduced from the assignment.
259
260@code{.cpp}
261auto a = static_cast<float*>(bar); // OK: there is an explicit cast
262auto b = std::make_unique<Image>(foo); // OK: we can see it's going to be an std::unique_ptr<Image>
263auto c = img.ptr(); // NO: Can't tell what the type is without knowing the API.
264auto d = vdup_n_u8(0); // NO: It's not obvious what type this function returns.
265@endcode
266
267- OpenCL:
268 - Use __ in front of the memory types qualifiers and kernel: __kernel, __constant, __private, __global, __local.
269 - Indicate how the global workgroup size / offset / local workgroup size are being calculated.
270
271 - Doxygen:
272
273 - No '*' in front of argument names
274 - [in], [out] or [in,out] *in front* of arguments
Viet-Hoa Doaa794052022-05-23 16:47:42 +0100275 - Skip a line between the description and params and between params and \@return (If there is a return)
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100276 - Align params names and params descriptions (Using spaces), and with a single space between the widest column and the next one.
277 - Use an upper case at the beginning of the description
278
279@snippet arm_compute/runtime/NEON/functions/NEActivationLayer.h NEActivationLayer snippet
280
281@subsection S5_1_2_how_to_check_the_rules How to check the rules
282
283astyle (http://astyle.sourceforge.net/) and clang-format (https://clang.llvm.org/docs/ClangFormat.html) can check and help you apply some of these rules.
284
285@subsection S5_1_3_library_size_guidelines Library size: best practices and guidelines
286
287@subsubsection S5_1_3_1_template_suggestions Template suggestions
288
289When writing a new patch we should also have in mind the effect it will have in the final library size. We can try some of the following things:
290
291 - Place non-dependent template code in a different non-templated class/method
292
293@code{.cpp}
294template<typename T>
295class Foo
296{
297public:
298 enum { v1, v2 };
299 // ...
300};
301@endcode
302
303 can be converted to:
304
305@code{.cpp}
306struct Foo_base
307{
308 enum { v1, v2 };
309 // ...
310};
311
312template<typename T>
313class Foo : public Foo_base
314{
315public:
316 // ...
317};
318@endcode
319
320 - In some cases it's preferable to use runtime switches instead of template parameters
321
322 - Sometimes we can rewrite the code without templates and without any (significant) performance loss. Let's say that we've written a function where the only use of the templated argument is used for casting:
323
324@code{.cpp}
325template <typename T>
326void NETemplatedKernel::run(const Window &window)
327{
328...
329 *(reinterpret_cast<T *>(out.ptr())) = *(reinterpret_cast<const T *>(in.ptr()));
330...
331}
332@endcode
333
334The above snippet can be transformed to:
335
336@code{.cpp}
337void NENonTemplatedKernel::run(const Window &window)
338{
339...
340std::memcpy(out.ptr(), in.ptr(), element_size);
341...
342}
343@endcode
344
345@subsection S5_1_4_secure_coding_practices Secure coding practices
346
347@subsubsection S5_1_4_1_general_coding_practices General Coding Practices
348
349- **Use tested and approved managed code** rather than creating new unmanaged code for common tasks.
350- **Utilize locking to prevent multiple simultaneous requests** or use a synchronization mechanism to prevent race conditions.
351- **Protect shared variables and resources** from inappropriate concurrent access.
352- **Explicitly initialize all your variables and other data stores**, either during declaration or just before the first usage.
353- **In cases where the application must run with elevated privileges, raise privileges as late as possible, and drop them as soon as possible**.
354- **Avoid calculation errors** by understanding your programming language's underlying representation and how it interacts with numeric calculation. Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how your language handles numbers that are too large or too small for its underlying representation.
355- **Restrict users from generating new code** or altering existing code.
356
357
358@subsubsection S5_1_4_2_secure_coding_best_practices Secure Coding Best Practices
359
360- **Validate input**. Validate input from all untrusted data sources. Proper input validation can eliminate the vast majority of software vulnerabilities. Be suspicious of most external data sources, including command line arguments, network interfaces, environmental variables, and user controlled files.
361- **Heed compiler warnings**. Compile code using the default compiler flags that exist in the SConstruct file.
362- Use **static analysis tools** to detect and eliminate additional security flaws.
363- **Keep it simple**. Keep the design as simple and small as possible. Complex designs increase the likelihood that errors will be made in their implementation, configuration, and use. Additionally, the effort required to achieve an appropriate level of assurance increases dramatically as security mechanisms become more complex.
364- **Default deny**. Base access decisions on permission rather than exclusion. This means that, by default, access is denied and the protection scheme identifies conditions under which access is permitted
365- **Adhere to the principle of least privilege**. Every process should execute with the least set of privileges necessary to complete the job. Any elevated permission should only be accessed for the least amount of time required to complete the privileged task. This approach reduces the opportunities an attacker has to execute arbitrary code with elevated privileges.
366- **Sanitize data sent to other systems**. Sanitize all data passed to complex subsystems such as command shells, relational databases, and commercial off-the-shelf (COTS) components. Attackers may be able to invoke unused functionality in these components through the use of various injection attacks. This is not necessarily an input validation problem because the complex subsystem being invoked does not understand the context in which the call is made. Because the calling process understands the context, it is responsible for sanitizing the data before invoking the subsystem.
367- **Practice defense in depth**. Manage risk with multiple defensive strategies, so that if one layer of defense turns out to be inadequate, another layer of defense can prevent a security flaw from becoming an exploitable vulnerability and/or limit the consequences of a successful exploit. For example, combining secure programming techniques with secure runtime environments should reduce the likelihood that vulnerabilities remaining in the code at deployment time can be exploited in the operational environment.
368
Sang-Hoon Park776c2352020-10-21 10:30:20 +0100369@subsection S5_1_5_guidelines_for_stable_api_abi Guidelines for stable API/ABI
370
371The Application Programming Interface (API) and Application Binary Interface (ABI) are the interfaces exposed
372to users so their programs can interact with the library efficiently and effectively. Even though changing API/ABI
373in a way that does not give backward compatibility is not necessarily bad if it can improve other users' experience and the library,
374contributions should be made with the awareness of API/ABI stability. If you'd like to make changes that affects
375the library's API/ABI, please review and follow the guidelines shown in this section. Also, please note that
376these guidelines are not exhaustive list but discussing things that might be easily overlooked.
377
378@subsubsection S5_1_5_1_guidelines_for_api Guidelines for API
379
380- When adding new arguments, consider grouping arguments (including the old ones) into a struct rather than adding arguments with default values.
381Introducing a new struct might break the API/ABI once, but it will be helpful to keep the stability.
382- When new member variables are added, please make sure they are initialized.
383- Avoid adding enum elements in the middle.
384- When removing arguments, follow the deprecation process described in the following section.
385- When changing behavior affecting API contracts, follow the deprecation process described in the following section.
386
387@subsubsection S5_1_5_2_guidelines_for_abi Guidelines for ABI
388
389We recommend to read through <a href="https://community.kde.org/Policies/Binary_Compatibility_Issues_With_C%2B%2B">this page</a>
390and double check your contributions to see if they include the changes listed.
391
392Also, for classes that requires strong ABI stability, consider using <a href="https://en.cppreference.com/w/cpp/language/pimpl">pImpl idiom</a>.
393
394@subsubsection S5_1_5_3_api_deprecation_process API deprecation process
395
396In order to deprecate an existing API, these rules should be followed.
397
398- Removal of a deprecated API should wait at least for one official release.
399- Deprecation of runtime APIs should strictly follow the aforementioned period, whereas core APIs can have more flexibility as they are mostly used internally rather than user-facing.
400- Any API changes (update, addition and deprecation) in all components should be well documented by the contribution itself.
401
Georgios Pinitas40f51a62020-11-21 03:04:18 +0000402Also, it is recommended to use the following utility macros which is designed to work with both clang and gcc using C++14 and later.
Sang-Hoon Park776c2352020-10-21 10:30:20 +0100403
404- ARM_COMPUTE_DEPRECATED: Just deprecate the wrapped function
405- ARM_COMPUTE_DEPRECATED_REL: Deprecate the wrapped function and also capture the release that was deprecated
406- ARM_COMPUTE_DEPRECATED_REL_REPLACE: Deprecate the wrapped function and also capture the release that was deprecated along with a possible replacement candidate
407
408@code{.cpp}
409ARM_COMPUTE_DEPRECATED_REL_REPLACE(20.08, DoNewThing)
410void DoOldThing();
411
412void DoNewThing();
413@endcode
414
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100415@section S5_2_how_to_submit_a_patch How to submit a patch
416
417To be able to submit a patch to our development repository you need to have a GitHub account. With that, you will be able to sign in to Gerrit where your patch will be reviewed.
418
419Next step is to clone the Compute Library repository:
420
421 git clone "ssh://<your-github-id>@review.mlplatform.org:29418/ml/ComputeLibrary"
422
423If you have cloned from GitHub or through HTTP, make sure you add a new git remote using SSH:
424
425 git remote add acl-gerrit "ssh://<your-github-id>@review.mlplatform.org:29418/ml/ComputeLibrary"
426
427After that, you will need to upload an SSH key to https://review.mlplatform.org/#/settings/ssh-keys
428
429Then, make sure to install the commit-msg Git hook in order to add a change-ID to the commit message of your patch:
430
431 cd "ComputeLibrary" && mkdir -p .git/hooks && curl -Lo `git rev-parse --git-dir`/hooks/commit-msg https://review.mlplatform.org/tools/hooks/commit-msg; chmod +x `git rev-parse --git-dir`/hooks/commit-msg)
432
433When your patch is ready, remember to sign off your contribution by adding a line with your name and e-mail address to every git commit message:
434
435 Signed-off-by: John Doe <john.doe@example.org>
436
437You must use your real name, no pseudonyms or anonymous contributions are accepted.
438
439You can add this to your patch with:
440
441 git commit -s --amend
442
443You are now ready to submit your patch for review:
444
ramelg0136a1c112022-03-29 19:09:56 +0100445 git push acl-gerrit HEAD:refs/for/main
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100446
447@section S5_3_code_review Patch acceptance and code review
448
Jakub Sujakee301b32021-06-04 09:46:08 +0100449Once a patch is uploaded for review, there is a pre-commit test that runs on a Jenkins server for continuous integration tests. In order to be merged a patch needs to:
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100450
451- get a "+1 Verified" from the pre-commit job
452- get a "+1 Comments-Addressed", in case of comments from reviewers the committer has to address them all. A comment is considered addressed when the first line of the reply contains the word "Done"
453- get a "+2" from a reviewer, that means the patch has the final approval
454
ramelg01b2eba7f2021-12-23 08:32:08 +0000455At the moment, the Jenkins server is not publicly accessible and for security reasons patches submitted by non-allowlisted committers do not trigger the pre-commit tests. For this reason, one of the maintainers has to manually trigger the job.
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100456
457If the pre-commit test fails, the Jenkins job will post a comment on Gerrit with the details about the failure so that the committer will be able to reproduce the error and fix the issue, if any (sometimes there can be infrastructure issues, a test platform disconnecting for example, where the job needs to be retriggered).
458
459*/
460} // namespace arm_compute