diff --git a/.gitignore b/.gitignore index 9118753a0a..f332b57b56 100644 --- a/.gitignore +++ b/.gitignore @@ -11,4 +11,8 @@ GPATH docs/details/examples.dox /TAGS external/ +extern/ compile_commands.json +venv +test/gtest +src/backend/cuda/cub diff --git a/include/af/features.h b/include/af/features.h index e387782ae6..aa5e049a91 100644 --- a/include/af/features.h +++ b/include/af/features.h @@ -38,7 +38,7 @@ namespace af ~features(); /// Copy assignment operator - features& operator= (const features& f); + features& operator= (const features& other); /// Returns the number of features represented by this object size_t getNumFeatures() const; diff --git a/include/af/graphics.h b/include/af/graphics.h index df06c4b395..d6ffa208fb 100644 --- a/include/af/graphics.h +++ b/include/af/graphics.h @@ -83,12 +83,13 @@ class AFAPI Window { Creates a window object with default width and height with title set to "ArrayFire" - \param[in] wnd is an \ref af_window handle which can be retrieved by + \param[in] window is an \ref af_window handle which can be retrieved + by doing a get call on any \ref Window object \ingroup gfx_func_window */ - Window(const af_window wnd); + Window(const af_window window); /** Destroys the window handle diff --git a/include/af/random.h b/include/af/random.h index 347cdf84ed..bf81e9218e 100644 --- a/include/af/random.h +++ b/include/af/random.h @@ -53,9 +53,9 @@ namespace af /** Copy constructor for \ref af::randomEngine. - \param[in] in The input random engine object + \param[in] other The input random engine object */ - randomEngine(const randomEngine &in); + randomEngine(const randomEngine &other); /** Creates a copy of the random engine object from a \ref @@ -73,11 +73,11 @@ namespace af /** \brief Assigns the internal state of randome engine - \param[in] in The object to be assigned to the random engine + \param[in] other The object to be assigned to the random engine \returns the reference to this */ - randomEngine &operator=(const randomEngine &in); + randomEngine &operator=(const randomEngine &other); /** \brief Sets the random type of the random engine diff --git a/include/af/seq.h b/include/af/seq.h index 9f1600f005..5a19921b1f 100644 --- a/include/af/seq.h +++ b/include/af/seq.h @@ -111,10 +111,10 @@ class AFAPI seq Creates a copy seq from another sequence. - \param[in] afs seqence to be copies + \param[in] other seqence to be copies \param[in] is_gfor is the gfor flag */ - seq(seq afs, bool is_gfor); + seq(seq other, bool is_gfor); /** \brief Create a seq object from an \ref af_seq struct diff --git a/src/.clang-tidy b/src/.clang-tidy new file mode 100644 index 0000000000..c6a2c6577d --- /dev/null +++ b/src/.clang-tidy @@ -0,0 +1,391 @@ +--- +Checks: 'clang-diagnostic-*,clang-analyzer-*,*,-fuchsia-*,-cppcoreguidelines-*,-misc-misplaced-const,-hicpp-no-array-decay,-readability-implicit-bool-conversion,bugprone-*,performance-*,modernize-*,-llvm-header-guard,-hicpp-use-auto,-modernize-use-trailing-return-type,-hicpp-uppercase-literal-suffix,-hicpp-use-nullptr,-modernize-use-nullptr,-google-runtime-int,-llvm-include-order,-google-runtime-references,-readability-magic-numbers,-readability-isolate-declaration,-hicpp-vararg,-google-readability-todo,-bugprone-macro-parentheses,-misc-unused-using-decls,-readability-else-after-return,-hicpp-avoid-c-arrays,-modernize-avoid-c-arrays' +WarningsAsErrors: '' +HeaderFilterRegex: '' +AnalyzeTemporaryDtors: true +FormatStyle: file +User: arrayfire +CheckOptions: + - key: abseil-string-find-startswith.AbseilStringsMatchHeader + value: 'absl/strings/match.h' + - key: abseil-string-find-startswith.IncludeStyle + value: llvm + - key: abseil-string-find-startswith.StringLikeClasses + value: '::std::basic_string' + - key: bugprone-argument-comment.CommentBoolLiterals + value: '0' + - key: bugprone-argument-comment.CommentCharacterLiterals + value: '0' + - key: bugprone-argument-comment.CommentFloatLiterals + value: '0' + - key: bugprone-argument-comment.CommentIntegerLiterals + value: '0' + - key: bugprone-argument-comment.CommentNullPtrs + value: '0' + - key: bugprone-argument-comment.CommentStringLiterals + value: '0' + - key: bugprone-argument-comment.CommentUserDefinedLiterals + value: '0' + - key: bugprone-argument-comment.StrictMode + value: '0' + - key: bugprone-assert-side-effect.AssertMacros + value: assert + - key: bugprone-assert-side-effect.CheckFunctionCalls + value: '0' + - key: bugprone-dangling-handle.HandleClasses + value: 'std::basic_string_view;std::experimental::basic_string_view' + - key: bugprone-exception-escape.FunctionsThatShouldNotThrow + value: '' + - key: bugprone-exception-escape.IgnoredExceptions + value: '' + - key: bugprone-misplaced-widening-cast.CheckImplicitCasts + value: '0' + - key: bugprone-sizeof-expression.WarnOnSizeOfCompareToConstant + value: '1' + - key: bugprone-sizeof-expression.WarnOnSizeOfConstant + value: '1' + - key: bugprone-sizeof-expression.WarnOnSizeOfIntegerExpression + value: '0' + - key: bugprone-sizeof-expression.WarnOnSizeOfThis + value: '1' + - key: bugprone-string-constructor.LargeLengthThreshold + value: '8388608' + - key: bugprone-string-constructor.WarnOnLargeLength + value: '1' + - key: bugprone-suspicious-enum-usage.StrictMode + value: '0' + - key: bugprone-suspicious-missing-comma.MaxConcatenatedTokens + value: '5' + - key: bugprone-suspicious-missing-comma.RatioThreshold + value: '0.200000' + - key: bugprone-suspicious-missing-comma.SizeThreshold + value: '5' + - key: bugprone-suspicious-string-compare.StringCompareLikeFunctions + value: '' + - key: bugprone-suspicious-string-compare.WarnOnImplicitComparison + value: '1' + - key: bugprone-suspicious-string-compare.WarnOnLogicalNotComparison + value: '0' + - key: bugprone-too-small-loop-variable.MagnitudeBitsUpperLimit + value: '16' + - key: bugprone-unhandled-self-assignment.WarnOnlyIfThisHasSuspiciousField + value: '1' + - key: bugprone-unused-return-value.CheckedFunctions + value: '::std::async;::std::launder;::std::remove;::std::remove_if;::std::unique;::std::unique_ptr::release;::std::basic_string::empty;::std::vector::empty' + - key: cert-dcl16-c.IgnoreMacros + value: '1' + - key: cert-dcl16-c.NewSuffixes + value: 'L;LL;LU;LLU' + - key: cert-dcl59-cpp.HeaderFileExtensions + value: ',h,hh,hpp,hxx' + - key: cert-err09-cpp.CheckThrowTemporaries + value: '1' + - key: cert-err61-cpp.CheckThrowTemporaries + value: '1' + - key: cert-msc32-c.DisallowedSeedTypes + value: 'time_t,std::time_t' + - key: cert-msc51-cpp.DisallowedSeedTypes + value: 'time_t,std::time_t' + - key: cert-oop11-cpp.IncludeStyle + value: llvm + - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField + value: '0' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: cppcoreguidelines-explicit-virtual-functions.FinalSpelling + value: final + - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors + value: '1' + - key: cppcoreguidelines-explicit-virtual-functions.OverrideSpelling + value: override + - key: cppcoreguidelines-macro-usage.AllowedRegexp + value: '^DEBUG_*' + - key: cppcoreguidelines-macro-usage.CheckCapsOnly + value: '0' + - key: cppcoreguidelines-macro-usage.IgnoreCommandLineMacros + value: '1' + - key: cppcoreguidelines-no-malloc.Allocations + value: '::malloc;::calloc' + - key: cppcoreguidelines-no-malloc.Deallocations + value: '::free' + - key: cppcoreguidelines-no-malloc.Reallocations + value: '::realloc' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: '1' + - key: cppcoreguidelines-owning-memory.LegacyResourceConsumers + value: '::free;::realloc;::freopen;::fclose' + - key: cppcoreguidelines-owning-memory.LegacyResourceProducers + value: '::malloc;::aligned_alloc;::realloc;::calloc;::fopen;::freopen;::tmpfile' + - key: cppcoreguidelines-pro-bounds-constant-array-index.GslHeader + value: '' + - key: cppcoreguidelines-pro-bounds-constant-array-index.IncludeStyle + value: '0' + - key: cppcoreguidelines-pro-type-member-init.IgnoreArrays + value: '0' + - key: cppcoreguidelines-pro-type-member-init.UseAssignment + value: '0' + - key: cppcoreguidelines-special-member-functions.AllowMissingMoveFunctions + value: '0' + - key: cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor + value: '0' + - key: fuchsia-header-anon-namespaces.HeaderFileExtensions + value: ',h,hh,hpp,hxx' + - key: fuchsia-restrict-system-includes.Includes + value: '*' + - key: google-build-namespaces.HeaderFileExtensions + value: ',h,hh,hpp,hxx' + - key: google-global-names-in-headers.HeaderFileExtensions + value: ',h,hh,hpp,hxx' + - key: google-readability-braces-around-statements.ShortStatementLines + value: '1' + - key: google-readability-function-size.BranchThreshold + value: '4294967295' + - key: google-readability-function-size.LineThreshold + value: '4294967295' + - key: google-readability-function-size.NestingThreshold + value: '4294967295' + - key: google-readability-function-size.ParameterThreshold + value: '4294967295' + - key: google-readability-function-size.StatementThreshold + value: '800' + - key: google-readability-function-size.VariableThreshold + value: '4294967295' + - key: google-readability-namespace-comments.ShortNamespaceLines + value: '10' + - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' + - key: google-runtime-int.SignedTypePrefix + value: int + - key: google-runtime-int.TypeSuffix + value: '' + - key: google-runtime-int.UnsignedTypePrefix + value: uint + - key: google-runtime-references.WhiteListTypes + value: '' + - key: hicpp-braces-around-statements.ShortStatementLines + value: '0' + - key: hicpp-function-size.BranchThreshold + value: '4294967295' + - key: hicpp-function-size.LineThreshold + value: '4294967295' + - key: hicpp-function-size.NestingThreshold + value: '4294967295' + - key: hicpp-function-size.ParameterThreshold + value: '4294967295' + - key: hicpp-function-size.StatementThreshold + value: '800' + - key: hicpp-function-size.VariableThreshold + value: '4294967295' + - key: hicpp-member-init.IgnoreArrays + value: '0' + - key: hicpp-member-init.UseAssignment + value: '0' + - key: hicpp-move-const-arg.CheckTriviallyCopyableMove + value: '1' + - key: hicpp-multiway-paths-covered.WarnOnMissingElse + value: '0' + - key: hicpp-named-parameter.IgnoreFailedSplit + value: '0' + - key: hicpp-no-malloc.Allocations + value: '::malloc;::calloc' + - key: hicpp-no-malloc.Deallocations + value: '::free' + - key: hicpp-no-malloc.Reallocations + value: '::realloc' + - key: hicpp-signed-bitwise.IgnorePositiveIntegerLiterals + value: 'true' + - key: hicpp-special-member-functions.AllowMissingMoveFunctions + value: '0' + - key: hicpp-special-member-functions.AllowSoleDefaultDtor + value: '0' + - key: hicpp-uppercase-literal-suffix.IgnoreMacros + value: '1' + - key: hicpp-uppercase-literal-suffix.NewSuffixes + value: '' + - key: hicpp-use-auto.MinTypeNameLength + value: '5' + - key: hicpp-use-auto.RemoveStars + value: '0' + - key: hicpp-use-emplace.ContainersWithPushBack + value: '::std::vector;::std::list;::std::deque' + - key: hicpp-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' + - key: hicpp-use-emplace.TupleMakeFunctions + value: '::std::make_pair;::std::make_tuple' + - key: hicpp-use-emplace.TupleTypes + value: '::std::pair;::std::tuple' + - key: hicpp-use-equals-default.IgnoreMacros + value: '1' + - key: hicpp-use-equals-delete.IgnoreMacros + value: '1' + - key: hicpp-use-noexcept.ReplacementString + value: '' + - key: hicpp-use-noexcept.UseNoexceptFalse + value: '1' + - key: hicpp-use-nullptr.NullMacros + value: '' + - key: hicpp-use-override.FinalSpelling + value: final + - key: hicpp-use-override.IgnoreDestructors + value: '0' + - key: hicpp-use-override.OverrideSpelling + value: override + - key: llvm-namespace-comment.ShortNamespaceLines + value: '1' + - key: llvm-namespace-comment.SpacesBeforeComments + value: '1' + - key: misc-definitions-in-headers.HeaderFileExtensions + value: ',h,hh,hpp,hxx' + - key: misc-definitions-in-headers.UseHeaderFileExtension + value: '1' + - key: misc-throw-by-value-catch-by-reference.CheckThrowTemporaries + value: '1' + - key: misc-unused-parameters.StrictMode + value: '0' + - key: modernize-loop-convert.MaxCopySize + value: '16' + - key: modernize-loop-convert.MinConfidence + value: reasonable + - key: modernize-loop-convert.NamingStyle + value: CamelCase + - key: modernize-make-shared.IgnoreMacros + value: '1' + - key: modernize-make-shared.IncludeStyle + value: '0' + - key: modernize-make-shared.MakeSmartPtrFunction + value: 'std::make_shared' + - key: modernize-make-shared.MakeSmartPtrFunctionHeader + value: memory + - key: modernize-make-unique.IgnoreMacros + value: '1' + - key: modernize-make-unique.IncludeStyle + value: '0' + - key: modernize-make-unique.MakeSmartPtrFunction + value: 'std::make_unique' + - key: modernize-make-unique.MakeSmartPtrFunctionHeader + value: memory + - key: modernize-pass-by-value.IncludeStyle + value: llvm + - key: modernize-pass-by-value.ValuesOnly + value: '0' + - key: modernize-raw-string-literal.ReplaceShorterLiterals + value: '0' + - key: modernize-replace-auto-ptr.IncludeStyle + value: llvm + - key: modernize-replace-random-shuffle.IncludeStyle + value: llvm + - key: modernize-use-auto.MinTypeNameLength + value: '5' + - key: modernize-use-auto.RemoveStars + value: '0' + - key: modernize-use-default-member-init.IgnoreMacros + value: '1' + - key: modernize-use-default-member-init.UseAssignment + value: '0' + - key: modernize-use-emplace.ContainersWithPushBack + value: '::std::vector;::std::list;::std::deque' + - key: modernize-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' + - key: modernize-use-emplace.TupleMakeFunctions + value: '::std::make_pair;::std::make_tuple' + - key: modernize-use-emplace.TupleTypes + value: '::std::pair;::std::tuple' + - key: modernize-use-equals-default.IgnoreMacros + value: '1' + - key: modernize-use-equals-delete.IgnoreMacros + value: '1' + - key: modernize-use-nodiscard.ReplacementString + value: '[[nodiscard]]' + - key: modernize-use-noexcept.ReplacementString + value: '' + - key: modernize-use-noexcept.UseNoexceptFalse + value: '1' + - key: modernize-use-nullptr.NullMacros + value: 'NULL' + - key: modernize-use-override.FinalSpelling + value: final + - key: modernize-use-override.IgnoreDestructors + value: '0' + - key: modernize-use-override.OverrideSpelling + value: override + - key: modernize-use-transparent-functors.SafeMode + value: '0' + - key: modernize-use-using.IgnoreMacros + value: '1' + - key: objc-forbidden-subclassing.ForbiddenSuperClassNames + value: 'ABNewPersonViewController;ABPeoplePickerNavigationController;ABPersonViewController;ABUnknownPersonViewController;NSHashTable;NSMapTable;NSPointerArray;NSPointerFunctions;NSTimer;UIActionSheet;UIAlertView;UIImagePickerController;UITextInputMode;UIWebView' + - key: openmp-exception-escape.IgnoredExceptions + value: '' + - key: performance-faster-string-find.StringLikeClasses + value: 'std::basic_string' + - key: performance-for-range-copy.AllowedTypes + value: '' + - key: performance-for-range-copy.WarnOnAllAutoCopies + value: '0' + - key: performance-inefficient-string-concatenation.StrictMode + value: '0' + - key: performance-inefficient-vector-operation.VectorLikeClasses + value: '::std::vector' + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: '1' + - key: performance-move-constructor-init.IncludeStyle + value: llvm + - key: performance-type-promotion-in-math-fn.IncludeStyle + value: llvm + - key: performance-unnecessary-copy-initialization.AllowedTypes + value: 'Array$;SparseArray*' + - key: performance-unnecessary-value-param.AllowedTypes + value: 'CParam' + - key: performance-unnecessary-value-param.IncludeStyle + value: llvm + - key: portability-simd-intrinsics.Std + value: '' + - key: portability-simd-intrinsics.Suggest + value: '0' + - key: readability-braces-around-statements.ShortStatementLines + value: '0' + - key: readability-function-size.BranchThreshold + value: '4294967295' + - key: readability-function-size.LineThreshold + value: '4294967295' + - key: readability-function-size.NestingThreshold + value: '4294967295' + - key: readability-function-size.ParameterThreshold + value: '4294967295' + - key: readability-function-size.StatementThreshold + value: '800' + - key: readability-function-size.VariableThreshold + value: '4294967295' + - key: readability-identifier-naming.IgnoreFailedSplit + value: '0' + - key: readability-implicit-bool-conversion.AllowIntegerConditions + value: '0' + - key: readability-implicit-bool-conversion.AllowPointerConditions + value: '0' + - key: readability-inconsistent-declaration-parameter-name.IgnoreMacros + value: '1' + - key: readability-inconsistent-declaration-parameter-name.Strict + value: '0' + - key: readability-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: readability-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: readability-redundant-smartptr-get.IgnoreMacros + value: '1' + - key: readability-simplify-boolean-expr.ChainedConditionalAssignment + value: '0' + - key: readability-simplify-boolean-expr.ChainedConditionalReturn + value: '0' + - key: readability-simplify-subscript-expr.Types + value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array' + - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold + value: '3' + - key: readability-uppercase-literal-suffix.IgnoreMacros + value: '1' + - key: readability-uppercase-literal-suffix.NewSuffixes + value: 'f,U,L,UL,LL,ULL' + - key: zircon-temporary-objects.Names + value: '' +... diff --git a/src/api/c/anisotropic_diffusion.cpp b/src/api/c/anisotropic_diffusion.cpp index 9b560d28c0..6608ad10ab 100644 --- a/src/api/c/anisotropic_diffusion.cpp +++ b/src/api/c/anisotropic_diffusion.cpp @@ -17,23 +17,24 @@ #include #include #include + #include #include #include using af::dim4; -using namespace detail; template -af_array diffusion(const Array in, const float dt, const float K, +af_array diffusion(const Array& in, const float dt, const float K, const unsigned iterations, const af_flux_function fftype, const af::diffusionEq eq) { - auto out = copyArray(in); - auto dims = out.dims(); - auto g0 = createEmptyArray(dims); - auto g1 = createEmptyArray(dims); - float cnst = -2.0f * K * K / dims.elements(); + auto out = copyArray(in); + auto dims = out.dims(); + auto g0 = createEmptyArray(dims); + auto g1 = createEmptyArray(dims); + float cnst = + -2.0f * K * K / dims.elements(); // NOLINT(readability-magic-numbers) for (unsigned i = 0; i < iterations; ++i) { gradient(g0, g1, out); @@ -71,7 +72,7 @@ af_err af_anisotropic_diffusion(af_array* out, const af_array in, auto input = castArray(in); - af_array output = 0; + af_array output = nullptr; switch (inputType) { case f64: output = diffusion(input, dt, K, iterations, F, eq); diff --git a/src/api/c/approx.cpp b/src/api/c/approx.cpp index c13093b46e..5d5f6acb00 100644 --- a/src/api/c/approx.cpp +++ b/src/api/c/approx.cpp @@ -19,7 +19,10 @@ #include using af::dim4; -using namespace detail; +using detail::approx1; +using detail::approx2; +using detail::cdouble; +using detail::cfloat; namespace { template @@ -53,10 +56,10 @@ void af_approx1_common(af_array *yo, const af_array yi, const af_array xo, const ArrayInfo &yi_info = getInfo(yi); const ArrayInfo &xo_info = getInfo(xo); - const dim4 yi_dims = yi_info.dims(); - const dim4 xo_dims = xo_info.dims(); - dim4 yo_dims = yi_dims; - yo_dims[xdim] = xo_dims[xdim]; + const dim4 &yi_dims = yi_info.dims(); + const dim4 &xo_dims = xo_info.dims(); + dim4 yo_dims = yi_dims; + yo_dims[xdim] = xo_dims[xdim]; ARG_ASSERT(1, yi_info.isFloating()); // Only floating and complex types ARG_ASSERT(2, xo_info.isRealFloating()); // Only floating types @@ -70,7 +73,7 @@ void af_approx1_common(af_array *yo, const af_array yi, const af_array xo, // yi_dims[3]) if (xo_dims[xdim] != xo_dims.elements()) { for (int i = 0; i < 4; i++) { - if (xdim != i) DIM_ASSERT(2, xo_dims[i] == yi_dims[i]); + if (xdim != i) { DIM_ASSERT(2, xo_dims[i] == yi_dims[i]); } } } @@ -196,7 +199,9 @@ void af_approx2_common(af_array *zo, const af_array zi, const af_array xo, // POS should either be (x, y, 1, 1) or (x, y, zi_dims[2], zi_dims[3]) if (xo_dims[xdim] * xo_dims[ydim] != xo_dims.elements()) { for (int i = 0; i < 4; i++) { - if (xdim != i && ydim != i) DIM_ASSERT(2, xo_dims[i] == zi_dims[i]); + if (xdim != i && ydim != i) { + DIM_ASSERT(2, xo_dims[i] == zi_dims[i]); + } } } diff --git a/src/api/c/array.cpp b/src/api/c/array.cpp index f0b58e6633..d2bca69180 100644 --- a/src/api/c/array.cpp +++ b/src/api/c/array.cpp @@ -16,14 +16,18 @@ #include #include -using namespace detail; - +using af::dim4; using common::half; using common::SparseArrayBase; - -af_array createHandle(const af::dim4 &d, af_dtype dtype) { - using namespace detail; - +using detail::cdouble; +using detail::cfloat; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; + +af_array createHandle(const dim4 &d, af_dtype dtype) { // clang-format off switch (dtype) { case f32: return createHandle(d); @@ -44,9 +48,7 @@ af_array createHandle(const af::dim4 &d, af_dtype dtype) { // clang-format on } -af_array createHandleFromValue(const af::dim4 &d, double val, af_dtype dtype) { - using namespace detail; - +af_array createHandleFromValue(const dim4 &d, double val, af_dtype dtype) { // clang-format off switch (dtype) { case f32: return createHandleFromValue(d, val); @@ -161,7 +163,7 @@ af_err af_create_handle(af_array *result, const unsigned ndims, try { AF_CHECK(af_init()); - if (ndims > 0) ARG_ASSERT(2, ndims > 0 && dims != NULL); + if (ndims > 0) { ARG_ASSERT(2, ndims > 0 && dims != NULL); } dim4 d(0); for (unsigned i = 0; i < ndims; i++) { d[i] = dims[i]; } @@ -181,40 +183,39 @@ af_err af_copy_array(af_array *out, const af_array in) { af_array res = 0; if (info.isSparse()) { - SparseArrayBase sbase = getSparseArrayBase(in); + const SparseArrayBase sbase = getSparseArrayBase(in); if (info.ndims() == 0) { return af_create_sparse_array_from_ptr( out, info.dims()[0], info.dims()[1], 0, nullptr, nullptr, nullptr, type, sbase.getStorage(), afDevice); - } else { - switch (type) { - case f32: res = copySparseArray(in); break; - case f64: res = copySparseArray(in); break; - case c32: res = copySparseArray(in); break; - case c64: res = copySparseArray(in); break; - default: TYPE_ERROR(0, type); - } } + switch (type) { + case f32: res = copySparseArray(in); break; + case f64: res = copySparseArray(in); break; + case c32: res = copySparseArray(in); break; + case c64: res = copySparseArray(in); break; + default: TYPE_ERROR(0, type); + } + } else { if (info.ndims() == 0) { return af_create_handle(out, 0, nullptr, type); - } else { - switch (type) { - case f32: res = copyArray(in); break; - case c32: res = copyArray(in); break; - case f64: res = copyArray(in); break; - case c64: res = copyArray(in); break; - case b8: res = copyArray(in); break; - case s32: res = copyArray(in); break; - case u32: res = copyArray(in); break; - case u8: res = copyArray(in); break; - case s64: res = copyArray(in); break; - case u64: res = copyArray(in); break; - case s16: res = copyArray(in); break; - case u16: res = copyArray(in); break; - case f16: res = copyArray(in); break; - default: TYPE_ERROR(1, type); - } + } + switch (type) { + case f32: res = copyArray(in); break; + case c32: res = copyArray(in); break; + case f64: res = copyArray(in); break; + case c64: res = copyArray(in); break; + case b8: res = copyArray(in); break; + case s32: res = copyArray(in); break; + case u32: res = copyArray(in); break; + case u8: res = copyArray(in); break; + case s64: res = copyArray(in); break; + case u64: res = copyArray(in); break; + case s16: res = copyArray(in); break; + case u16: res = copyArray(in); break; + case f16: res = copyArray(in); break; + default: TYPE_ERROR(1, type); } } std::swap(*out, res); @@ -254,7 +255,7 @@ af_err af_get_data_ref_count(int *use_count, const af_array in) { af_err af_release_array(af_array arr) { try { - if (arr == 0) return AF_SUCCESS; + if (arr == 0) { return AF_SUCCESS; } const ArrayInfo &info = getInfo(arr, false, false); af_dtype type = info.getType(); @@ -338,7 +339,6 @@ void write_array(af_array arr, const T *const data, const size_t bytes, } else { writeDeviceDataArray(getArray(arr), data, bytes); } - return; } af_err af_write_array(af_array arr, const void *data, const size_t bytes, diff --git a/src/api/c/assign.cpp b/src/api/c/assign.cpp index 7782170936..ede1041ca1 100644 --- a/src/api/c/assign.cpp +++ b/src/api/c/assign.cpp @@ -24,18 +24,25 @@ #include #include -using namespace detail; - -using std::enable_if; using std::signbit; using std::swap; using std::vector; +using af::dim4; using common::convert2Canonical; using common::createSpanIndex; using common::half; using common::if_complex; using common::if_real; +using detail::Array; +using detail::cdouble; +using detail::cfloat; +using detail::createSubArray; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; template static void assign(Array& out, const vector seqs, @@ -44,23 +51,23 @@ static void assign(Array& out, const vector seqs, const dim4& outDs = out.dims(); const dim4& iDims = in.dims(); - if (iDims.elements() == 0) return; + if (iDims.elements() == 0) { return; } out.eval(); dim4 oDims = toDims(seqs, outDs); bool isVec = true; - for (int i = 0; isVec && i < (int)oDims.ndims() - 1; i++) { + for (int i = 0; isVec && i < static_cast(oDims.ndims()) - 1; i++) { isVec &= oDims[i] == 1; } isVec &= in.isVector() || in.isScalar(); - for (dim_t i = ndims; i < (int)in.ndims(); i++) { oDims[i] = 1; } + for (dim_t i = ndims; i < in.ndims(); i++) { oDims[i] = 1; } if (isVec) { - if (oDims.elements() != (dim_t)in.elements() && in.elements() != 1) { + if (oDims.elements() != in.elements() && in.elements() != 1) { AF_ERROR("Size mismatch between input and output", AF_ERR_SIZE); } @@ -73,8 +80,9 @@ static void assign(Array& out, const vector seqs, copyArray(dst, in_); } else { for (int i = 0; i < AF_MAX_DIMS; i++) { - if (oDims[i] != iDims[i]) + if (oDims[i] != iDims[i]) { AF_ERROR("Size mismatch between input and output", AF_ERR_SIZE); + } } Array dst = createSubArray(out, seqs, false); @@ -126,7 +134,8 @@ af_err af_assign_seq(af_array* out, const af_array lhs, const unsigned ndims, const ArrayInfo& lInfo = getInfo(lhs); if (ndims == 1 && ndims != lInfo.ndims()) { - af_array tmp_in, tmp_out; + af_array tmp_in; + af_array tmp_out; AF_CHECK(af_flat(&tmp_in, lhs)); AF_CHECK(af_assign_seq(&tmp_out, tmp_in, ndims, index, rhs)); AF_CHECK( @@ -135,7 +144,7 @@ af_err af_assign_seq(af_array* out, const af_array lhs, const unsigned ndims, // This can run into a double free issue if tmp_in == tmp_out // The condition ensures release only if both are different // Issue found on Tegra X1 - if (tmp_in != tmp_out) AF_CHECK(af_release_array(tmp_out)); + if (tmp_in != tmp_out) { AF_CHECK(af_release_array(tmp_out)); } return AF_SUCCESS; } @@ -144,10 +153,11 @@ af_err af_assign_seq(af_array* out, const af_array lhs, const unsigned ndims, if (*out != lhs) { int count = 0; AF_CHECK(af_get_data_ref_count(&count, lhs)); - if (count > 1) + if (count > 1) { AF_CHECK(af_copy_array(&res, lhs)); - else + } else { res = retain(lhs); + } } else { res = lhs; } @@ -223,7 +233,7 @@ af_err af_assign_gen(af_array* out, const af_array lhs, const dim_t ndims, } af_array rhs = rhs_; - if (track == (int)ndims) { + if (track == static_cast(ndims)) { // all indexs are sequences, redirecting to af_assign return af_assign_seq(out, lhs, ndims, seqs.data(), rhs); } @@ -238,15 +248,17 @@ af_err af_assign_gen(af_array* out, const af_array lhs, const dim_t ndims, af_dtype lhsType = lInfo.getType(); af_dtype rhsType = rInfo.getType(); - if (rhsDims.ndims() == 0) return af_retain_array(out, lhs); + if (rhsDims.ndims() == 0) { return af_retain_array(out, lhs); } - if (lhsDims.ndims() == 0) + if (lhsDims.ndims() == 0) { return af_create_handle(out, 0, nullptr, lhsType); + } ARG_ASSERT(2, (ndims == 1) || (ndims == (dim_t)lInfo.ndims())); - if (ndims == 1 && ndims != (dim_t)lInfo.ndims()) { - af_array tmp_in = 0, tmp_out = 0; + if (ndims == 1 && ndims != static_cast(lInfo.ndims())) { + af_array tmp_in = 0; + af_array tmp_out = 0; AF_CHECK(af_flat(&tmp_in, lhs)); AF_CHECK(af_assign_gen(&tmp_out, tmp_in, ndims, indexs, rhs_)); AF_CHECK( @@ -255,7 +267,7 @@ af_err af_assign_gen(af_array* out, const af_array lhs, const dim_t ndims, // This can run into a double free issue if tmp_in == tmp_out // The condition ensures release only if both are different // Issue found on Tegra X1 - if (tmp_in != tmp_out) AF_CHECK(af_release_array(tmp_out)); + if (tmp_in != tmp_out) { AF_CHECK(af_release_array(tmp_out)); } return AF_SUCCESS; } @@ -269,8 +281,9 @@ af_err af_assign_gen(af_array* out, const af_array lhs, const dim_t ndims, AF_CHECK(af_get_data_ref_count(&count, lhs)); if (count > 1) { AF_CHECK(af_copy_array(&output, lhs)); - } else + } else { output = retain(lhs); + } } else { output = lhs; } @@ -280,21 +293,24 @@ af_err af_assign_gen(af_array* out, const af_array lhs, const dim_t ndims, // particular dimension, set the length of // that dimension accordingly before any checks for (dim_t i = 0; i < ndims; i++) { - if (!indexs[i].isSeq) + if (!indexs[i].isSeq) { oDims[i] = getInfo(indexs[i].idx.arr).elements(); + } } - for (dim_t i = ndims; i < (dim_t)lInfo.ndims(); i++) oDims[i] = 1; + for (dim_t i = ndims; i < static_cast(lInfo.ndims()); i++) { + oDims[i] = 1; + } bool isVec = true; for (int i = 0; isVec && i < oDims.ndims() - 1; i++) { isVec &= oDims[i] == 1; } - // TODO: Move logic out of this + // TODO(umar): Move logic out of this isVec &= rInfo.isVector() || rInfo.isScalar(); if (isVec) { - if (oDims.elements() != (dim_t)rInfo.elements() && + if (oDims.elements() != static_cast(rInfo.elements()) && rInfo.elements() != 1) { AF_ERROR("Size mismatch between input and output", AF_ERR_SIZE); } @@ -308,13 +324,14 @@ af_err af_assign_gen(af_array* out, const af_array lhs, const dim_t ndims, } } else { for (int i = 0; i < AF_MAX_DIMS; i++) { - if (oDims[i] != rhsDims[i]) + if (oDims[i] != rhsDims[i]) { AF_ERROR("Size mismatch between input and output", AF_ERR_SIZE); + } } } - std::array idxrs; + std::array idxrs{}; for (dim_t i = 0; i < AF_MAX_DIMS; ++i) { if (i < ndims) { bool isSeq = indexs[i].isSeq; @@ -370,11 +387,11 @@ af_err af_assign_gen(af_array* out, const af_array lhs, const dim_t ndims, } catch (...) { if (*out != lhs) { AF_CHECK(af_release_array(output)); - if (isVec) AF_CHECK(af_release_array(rhs)); + if (isVec) { AF_CHECK(af_release_array(rhs)); } } throw; } - if (isVec) AF_CHECK(af_release_array(rhs)); + if (isVec) { AF_CHECK(af_release_array(rhs)); } swap(*out, output); } CATCHALL; diff --git a/src/api/c/bilateral.cpp b/src/api/c/bilateral.cpp index bb3beccb43..7d3427ee74 100644 --- a/src/api/c/bilateral.cpp +++ b/src/api/c/bilateral.cpp @@ -16,7 +16,10 @@ #include using af::dim4; -using namespace detail; +using detail::bilateral; +using detail::uchar; +using detail::uint; +using detail::ushort; template static inline af_array bilateral(const af_array &in, const float &sp_sig, @@ -74,8 +77,11 @@ static af_err bilateral(af_array *out, const af_array &in, const float &s_sigma, af_err af_bilateral(af_array *out, const af_array in, const float spatial_sigma, const float chromatic_sigma, const bool isColor) { - if (isColor) - return bilateral(out, in, spatial_sigma, chromatic_sigma); - else - return bilateral(out, in, spatial_sigma, chromatic_sigma); + af_err err = AF_ERR_UNKNOWN; + if (isColor) { + err = bilateral(out, in, spatial_sigma, chromatic_sigma); + } else { + err = bilateral(out, in, spatial_sigma, chromatic_sigma); + } + return err; } diff --git a/src/api/c/binary.cpp b/src/api/c/binary.cpp index d4ddf3a211..1a2890f85b 100644 --- a/src/api/c/binary.cpp +++ b/src/api/c/binary.cpp @@ -26,9 +26,17 @@ #include -using namespace detail; using af::dim4; using common::half; +using detail::arithOp; +using detail::arithOpD; +using detail::cdouble; +using detail::cfloat; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; template static inline af_array arithOp(const af_array lhs, const af_array rhs, @@ -48,12 +56,14 @@ template static inline af_array arithSparseDenseOp(const af_array lhs, const af_array rhs, const bool reverse) { - if (op == af_add_t || op == af_sub_t) + if (op == af_add_t || op == af_sub_t) { return getHandle( arithOpD(castSparse(lhs), castArray(rhs), reverse)); - else if (op == af_mul_t || op == af_div_t) + } + if (op == af_mul_t || op == af_div_t) { return getHandle( arithOp(castSparse(lhs), castArray(rhs), reverse)); + } } template @@ -115,7 +125,6 @@ static af_err af_arith_real(af_array *out, const af_array lhs, case f16: res = arithOp(lhs, rhs, odims); break; default: TYPE_ERROR(0, otype); } - std::swap(*out, res); } CATCHALL; @@ -126,8 +135,8 @@ template static af_err af_arith_sparse(af_array *out, const af_array lhs, const af_array rhs) { try { - common::SparseArrayBase linfo = getSparseArrayBase(lhs); - common::SparseArrayBase rinfo = getSparseArrayBase(rhs); + const common::SparseArrayBase linfo = getSparseArrayBase(lhs); + const common::SparseArrayBase rinfo = getSparseArrayBase(rhs); ARG_ASSERT(1, (linfo.getStorage() == rinfo.getStorage())); ARG_ASSERT(1, (linfo.dims() == rinfo.dims())); @@ -153,10 +162,9 @@ template static af_err af_arith_sparse_dense(af_array *out, const af_array lhs, const af_array rhs, const bool reverse = false) { - using namespace common; try { - common::SparseArrayBase linfo = getSparseArrayBase(lhs); - ArrayInfo rinfo = getInfo(rhs); + const common::SparseArrayBase linfo = getSparseArrayBase(lhs); + const ArrayInfo &rinfo = getInfo(rhs); const af_dtype otype = implicit(linfo.getType(), rinfo.getType()); af_array res; @@ -185,82 +193,86 @@ static af_err af_arith_sparse_dense(af_array *out, const af_array lhs, af_err af_add(af_array *out, const af_array lhs, const af_array rhs, const bool batchMode) { // Check if inputs are sparse - ArrayInfo linfo = getInfo(lhs, false, true); - ArrayInfo rinfo = getInfo(rhs, false, true); + const ArrayInfo &linfo = getInfo(lhs, false, true); + const ArrayInfo &rinfo = getInfo(rhs, false, true); if (linfo.isSparse() && rinfo.isSparse()) { return af_arith_sparse(out, lhs, rhs); - } else if (linfo.isSparse() && !rinfo.isSparse()) { + } + if (linfo.isSparse() && !rinfo.isSparse()) { return af_arith_sparse_dense(out, lhs, rhs); - } else if (!linfo.isSparse() && rinfo.isSparse()) { + } + if (!linfo.isSparse() && rinfo.isSparse()) { // second operand(Array) of af_arith call should be dense return af_arith_sparse_dense(out, rhs, lhs, true); - } else { - return af_arith(out, lhs, rhs, batchMode); } + return af_arith(out, lhs, rhs, batchMode); } af_err af_mul(af_array *out, const af_array lhs, const af_array rhs, const bool batchMode) { // Check if inputs are sparse - ArrayInfo linfo = getInfo(lhs, false, true); - ArrayInfo rinfo = getInfo(rhs, false, true); + const ArrayInfo &linfo = getInfo(lhs, false, true); + const ArrayInfo &rinfo = getInfo(rhs, false, true); if (linfo.isSparse() && rinfo.isSparse()) { // return af_arith_sparse(out, lhs, rhs); // MKL doesn't have mul or div support yet, hence // this is commented out although alternative cpu code exists return AF_ERR_NOT_SUPPORTED; - } else if (linfo.isSparse() && !rinfo.isSparse()) { + } + if (linfo.isSparse() && !rinfo.isSparse()) { return af_arith_sparse_dense(out, lhs, rhs); - } else if (!linfo.isSparse() && rinfo.isSparse()) { + } + if (!linfo.isSparse() && rinfo.isSparse()) { return af_arith_sparse_dense(out, rhs, lhs, true); // dense should be rhs - } else { - return af_arith(out, lhs, rhs, batchMode); } + return af_arith(out, lhs, rhs, batchMode); } af_err af_sub(af_array *out, const af_array lhs, const af_array rhs, const bool batchMode) { // Check if inputs are sparse - ArrayInfo linfo = getInfo(lhs, false, true); - ArrayInfo rinfo = getInfo(rhs, false, true); + const ArrayInfo &linfo = getInfo(lhs, false, true); + const ArrayInfo &rinfo = getInfo(rhs, false, true); if (linfo.isSparse() && rinfo.isSparse()) { return af_arith_sparse(out, lhs, rhs); - } else if (linfo.isSparse() && !rinfo.isSparse()) { + } + if (linfo.isSparse() && !rinfo.isSparse()) { return af_arith_sparse_dense(out, lhs, rhs); - } else if (!linfo.isSparse() && rinfo.isSparse()) { + } + if (!linfo.isSparse() && rinfo.isSparse()) { return af_arith_sparse_dense(out, rhs, lhs, true); // dense should be rhs - } else { - return af_arith(out, lhs, rhs, batchMode); } + return af_arith(out, lhs, rhs, batchMode); } af_err af_div(af_array *out, const af_array lhs, const af_array rhs, const bool batchMode) { // Check if inputs are sparse - ArrayInfo linfo = getInfo(lhs, false, true); - ArrayInfo rinfo = getInfo(rhs, false, true); + const ArrayInfo &linfo = getInfo(lhs, false, true); + const ArrayInfo &rinfo = getInfo(rhs, false, true); if (linfo.isSparse() && rinfo.isSparse()) { // return af_arith_sparse(out, lhs, rhs); // MKL doesn't have mul or div support yet, hence // this is commented out although alternative cpu code exists return AF_ERR_NOT_SUPPORTED; - } else if (linfo.isSparse() && !rinfo.isSparse()) { + } + if (linfo.isSparse() && !rinfo.isSparse()) { return af_arith_sparse_dense(out, lhs, rhs); - } else if (!linfo.isSparse() && rinfo.isSparse()) { + } + if (!linfo.isSparse() && rinfo.isSparse()) { // Division by sparse is currently not allowed - for convinence of // dealing with division by 0 // return af_arith_sparse_dense(out, rhs, lhs, true); // dense // should be rhs return AF_ERR_NOT_SUPPORTED; - } else { - return af_arith(out, lhs, rhs, batchMode); } + return af_arith(out, lhs, rhs, batchMode); } af_err af_maxof(af_array *out, const af_array lhs, const af_array rhs, @@ -298,7 +310,8 @@ af_err af_pow(af_array *out, const af_array lhs, const af_array rhs, AF_CHECK(af_release_array(log_res)); std::swap(*out, res); return AF_SUCCESS; - } else if (linfo.isComplex()) { + } + if (linfo.isComplex()) { af_array mag, angle; af_array mag_res, angle_res; af_array real_res, imag_res, cplx_res; diff --git a/src/api/c/blas.cpp b/src/api/c/blas.cpp index fe54e2f72d..d34d55fd4a 100644 --- a/src/api/c/blas.cpp +++ b/src/api/c/blas.cpp @@ -26,36 +26,39 @@ #include using common::half; +using common::SparseArrayBase; +using detail::cdouble; +using detail::cfloat; +using detail::gemm; +using detail::matmul; template static inline af_array sparseMatmul(const af_array lhs, const af_array rhs, af_mat_prop optLhs, af_mat_prop optRhs) { - return getHandle(detail::matmul(getSparseArray(lhs), getArray(rhs), - optLhs, optRhs)); + return getHandle( + matmul(getSparseArray(lhs), getArray(rhs), optLhs, optRhs)); } template static inline void gemm(af_array *out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, const af_array lhs, const af_array rhs, const T *betas) { - detail::gemm(getArray(*out), optLhs, optRhs, alpha, getArray(lhs), - getArray(rhs), betas); + gemm(getArray(*out), optLhs, optRhs, alpha, getArray(lhs), + getArray(rhs), betas); } template static inline af_array dot(const af_array lhs, const af_array rhs, af_mat_prop optLhs, af_mat_prop optRhs) { return getHandle( - detail::dot(getArray(lhs), getArray(rhs), optLhs, optRhs)); + dot(getArray(lhs), getArray(rhs), optLhs, optRhs)); } af_err af_sparse_matmul(af_array *out, const af_array lhs, const af_array rhs, const af_mat_prop optLhs, const af_mat_prop optRhs) { - using namespace detail; - try { - common::SparseArrayBase lhsBase = getSparseArrayBase(lhs); - const ArrayInfo &rhsInfo = getInfo(rhs); + const SparseArrayBase lhsBase = getSparseArrayBase(lhs); + const ArrayInfo &rhsInfo = getInfo(rhs); ARG_ASSERT(2, lhsBase.isSparse() == true && rhsInfo.isSparse() == false); @@ -117,8 +120,6 @@ af_err af_sparse_matmul(af_array *out, const af_array lhs, const af_array rhs, af_err af_gemm(af_array *out, const af_mat_prop optLhs, const af_mat_prop optRhs, const void *alpha, const af_array lhs, const af_array rhs, const void *beta) { - using namespace detail; // needed for cfloat and cdouble - try { const ArrayInfo &lhsInfo = getInfo(lhs, false, true); const ArrayInfo &rhsInfo = getInfo(rhs, true, true); @@ -212,27 +213,25 @@ af_err af_gemm(af_array *out, const af_mat_prop optLhs, af_err af_matmul(af_array *out, const af_array lhs, const af_array rhs, const af_mat_prop optLhs, const af_mat_prop optRhs) { - using namespace detail; // needed for cfloat and cdouble - try { const ArrayInfo &lhsInfo = getInfo(lhs, false, true); const ArrayInfo &rhsInfo = getInfo(rhs, true, true); - if (lhsInfo.isSparse()) + if (lhsInfo.isSparse()) { return af_sparse_matmul(out, lhs, rhs, optLhs, optRhs); + } const int aRowDim = (optLhs == AF_MAT_NONE) ? 0 : 1; const int bColDim = (optRhs == AF_MAT_NONE) ? 1 : 0; - const af::dim4 lDims = lhsInfo.dims(); - const af::dim4 rDims = rhsInfo.dims(); - const int M = lDims[aRowDim]; - const int N = rDims[bColDim]; + const af::dim4 &lDims = lhsInfo.dims(); + const af::dim4 &rDims = rhsInfo.dims(); + const int M = lDims[aRowDim]; + const int N = rDims[bColDim]; const dim_t d2 = std::max(lDims[2], rDims[2]); const dim_t d3 = std::max(lDims[3], rDims[3]); const af::dim4 oDims = af::dim4(M, N, d2, d3); - const int num_batch = oDims[2] * oDims[3]; af_array gemm_out = 0; AF_CHECK(af_create_handle(&gemm_out, oDims.ndims(), oDims.get(), @@ -287,8 +286,6 @@ af_err af_matmul(af_array *out, const af_array lhs, const af_array rhs, af_err af_dot(af_array *out, const af_array lhs, const af_array rhs, const af_mat_prop optLhs, const af_mat_prop optRhs) { - using namespace detail; - try { const ArrayInfo &lhsInfo = getInfo(lhs); const ArrayInfo &rhsInfo = getInfo(rhs); @@ -332,7 +329,7 @@ af_err af_dot(af_array *out, const af_array lhs, const af_array rhs, template static inline T dotAll(af_array out) { - T res; + T res{}; AF_CHECK(af_eval(out)); AF_CHECK(af_get_data_ptr((void *)&res, out)); return res; @@ -341,17 +338,18 @@ static inline T dotAll(af_array out) { af_err af_dot_all(double *rval, double *ival, const af_array lhs, const af_array rhs, const af_mat_prop optLhs, const af_mat_prop optRhs) { - using namespace detail; + using namespace detail; // NOLINT needed for imag and real functions + // name resolution try { *rval = 0; - if (ival) *ival = 0; + if (ival) { *ival = 0; } af_array out = 0; AF_CHECK(af_dot(&out, lhs, rhs, optLhs, optRhs)); - ArrayInfo lhsInfo = getInfo(lhs); - af_dtype lhs_type = lhsInfo.getType(); + const ArrayInfo &lhsInfo = getInfo(lhs); + af_dtype lhs_type = lhsInfo.getType(); switch (lhs_type) { case f16: *rval = static_cast(dotAll(out)); break; @@ -360,17 +358,17 @@ af_err af_dot_all(double *rval, double *ival, const af_array lhs, case c32: { cfloat temp = dotAll(out); *rval = real(temp); - if (ival) *ival = imag(temp); + if (ival) { *ival = imag(temp); } } break; case c64: { cdouble temp = dotAll(out); *rval = real(temp); - if (ival) *ival = imag(temp); + if (ival) { *ival = imag(temp); } } break; default: TYPE_ERROR(1, lhs_type); } - if (out != 0) AF_CHECK(af_release_array(out)); + if (out != 0) { AF_CHECK(af_release_array(out)); } } CATCHALL return AF_SUCCESS; diff --git a/src/api/c/canny.cpp b/src/api/c/canny.cpp index 6c1341ff61..524c63f556 100644 --- a/src/api/c/canny.cpp +++ b/src/api/c/canny.cpp @@ -34,7 +34,6 @@ using af::dim4; using std::vector; -using namespace detail; Array gradientMagnitude(const Array& gx, const Array& gy, const bool& isf) { @@ -56,7 +55,7 @@ Array otsuThreshold(const Array& supEdges, Array hist = detail::histogram(supEdges, NUM_BINS, 0, maxVal); - const af::dim4 hDims = hist.dims(); + const af::dim4& hDims = hist.dims(); // reduce along histogram dimension i.e. 0th dimension auto totals = reduce(hist, 0); @@ -71,16 +70,16 @@ Array otsuThreshold(const Array& supEdges, std::vector seqBegin(4, af_span); std::vector seqRest(4, af_span); - seqBegin[0] = af_make_seq(0, hDims[0] - 1, 1); - seqRest[0] = af_make_seq(0, hDims[0] - 1, 1); + seqBegin[0] = af_make_seq(0, static_cast(hDims[0] - 1), 1); + seqRest[0] = af_make_seq(0, static_cast(hDims[0] - 1), 1); const af::dim4& iDims = supEdges.dims(); Array sigmas = detail::createEmptyArray(hDims); for (unsigned b = 0; b < (NUM_BINS - 1); ++b) { - seqBegin[0].end = (double)b; - seqRest[0].begin = (double)(b + 1); + seqBegin[0].end = static_cast(b); + seqRest[0].begin = static_cast(b + 1); auto frontPartition = createSubArray(probability, seqBegin, false); auto endPartition = createSubArray(probability, seqRest, false); @@ -139,12 +138,12 @@ Array normalize(const Array& supEdges, const float minVal, std::pair, Array> computeCandidates( const Array& supEdges, const float t1, const af_canny_threshold ct, const float t2) { - float maxVal = detail::reduce_all(supEdges); - const unsigned NUM_BINS = static_cast(maxVal); + float maxVal = detail::reduce_all(supEdges); + auto NUM_BINS = static_cast(maxVal); auto lowRatio = createValueArray(supEdges.dims(), t1); - switch (ct) { + switch (ct) { // NOLINT(hicpp-multiway-paths-covered) case AF_CANNY_THRESHOLD_AUTO_OTSU: { auto T2 = otsuThreshold(supEdges, NUM_BINS, maxVal); auto T1 = arithOp(T2, lowRatio, T2.dims()); diff --git a/src/api/c/cast.cpp b/src/api/c/cast.cpp index 32ecf959f5..43ee4e9dad 100644 --- a/src/api/c/cast.cpp +++ b/src/api/c/cast.cpp @@ -7,22 +7,29 @@ * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ +#include +#include #include +#include +#include +#include #include #include #include #include #include #include +#include -#include -#include -#include -#include -#include - -using namespace detail; +using af::dim4; using common::half; +using detail::cdouble; +using detail::cfloat; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; static af_array cast(const af_array in, const af_dtype type) { const ArrayInfo& info = getInfo(in, false, true); diff --git a/src/api/c/cholesky.cpp b/src/api/c/cholesky.cpp index b83369d4dc..4dd8fdc20f 100644 --- a/src/api/c/cholesky.cpp +++ b/src/api/c/cholesky.cpp @@ -7,8 +7,9 @@ * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ -#include #include + +#include #include #include #include @@ -16,8 +17,8 @@ #include #include -using af::dim4; -using namespace detail; +using detail::cdouble; +using detail::cfloat; template static inline af_array cholesky(int *info, const af_array in, diff --git a/src/api/c/clamp.cpp b/src/api/c/clamp.cpp index df9629bc93..f0da3323eb 100644 --- a/src/api/c/clamp.cpp +++ b/src/api/c/clamp.cpp @@ -7,24 +7,31 @@ * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ +#include #include #include #include #include #include #include +#include #include #include #include #include #include -#include -#include - -using namespace detail; using af::dim4; using common::half; +using detail::arithOp; +using detail::Array; +using detail::cdouble; +using detail::cfloat; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; template static inline af_array clampOp(const af_array in, const af_array lo, diff --git a/src/api/c/complex.cpp b/src/api/c/complex.cpp index a14a6b16eb..1732aaf4bc 100644 --- a/src/api/c/complex.cpp +++ b/src/api/c/complex.cpp @@ -21,9 +21,13 @@ #include -using namespace detail; using af::dim4; using common::half; +using detail::cdouble; +using detail::cfloat; +using detail::conj; +using detail::imag; +using detail::real; template static inline af_array cplx(const af_array lhs, const af_array rhs, @@ -42,7 +46,7 @@ af_err af_cplx2(af_array *out, const af_array lhs, const af_array rhs, AF_ERROR("Inputs to cplx2 can not be of complex type", AF_ERR_ARG); } - if (type != f64) type = f32; + if (type != f64) { type = f32; } dim4 odims = getOutDims(getInfo(lhs).dims(), getInfo(rhs).dims(), batchMode); @@ -176,21 +180,13 @@ af_err af_abs(af_array *out, const af_array in) { if (in_type == f16) { type = f16; } switch (type) { - case f32: - res = getHandle(abs(castArray(in))); - break; - case f64: - res = getHandle(abs(castArray(in))); - break; - case c32: - res = getHandle(abs(castArray(in))); - break; - case c64: - res = getHandle(abs(castArray(in))); - break; - case f16: - res = getHandle(abs(getArray(in))); - break; + // clang-format off + case f32: res = getHandle(detail::abs(castArray(in))); break; + case f64: res = getHandle(detail::abs(castArray(in))); break; + case c32: res = getHandle(detail::abs(castArray(in))); break; + case c64: res = getHandle(detail::abs(castArray(in))); break; + case f16: res = getHandle(detail::abs(getArray(in))); break; + // clang-format on default: TYPE_ERROR(1, in_type); break; } diff --git a/src/api/c/confidence_connected.cpp b/src/api/c/confidence_connected.cpp index 5a2910329f..acf9e3bbd9 100644 --- a/src/api/c/confidence_connected.cpp +++ b/src/api/c/confidence_connected.cpp @@ -24,18 +24,22 @@ #include using af::dim4; -using namespace detail; +using std::array; +using std::conditional; +using std::is_same; +using std::sqrt; +using std::swap; /// Index corner points of given seed points template Array pointList(const Array& in, const Array& x, const Array& y) { - af_array xcoords = getHandle(x); - af_array ycoords = getHandle(y); - std::array idxrs = {{{xcoords, false, false}, - {ycoords, false, false}, - common::createSpanIndex(), - common::createSpanIndex()}}; + af_array xcoords = getHandle(x); + af_array ycoords = getHandle(y); + array idxrs = {{{xcoords, false, false}, + {ycoords, false, false}, + common::createSpanIndex(), + common::createSpanIndex()}}; Array retVal = detail::index(in, idxrs.data()); @@ -80,8 +84,8 @@ af_array ccHelper(const Array& img, const Array& seedx, const Array& seedy, const unsigned radius, const unsigned mult, const unsigned iterations, const double segmentedValue) { - using CT = typename std::conditional::value, double, - float>::type; + using CT = + typename conditional::value, double, float>::type; constexpr CT epsilon = 1.0e-6; auto calcVar = [](CT s2, CT s1, CT n) -> CT { @@ -90,8 +94,8 @@ af_array ccHelper(const Array& img, const Array& seedx, return retVal; }; - const dim4 inDims = img.dims(); - const dim4 seedDims = seedx.dims(); + const dim4& inDims = img.dims(); + const dim4& seedDims = seedx.dims(); const size_t numSeeds = seedx.elements(); const unsigned nhoodLen = 2 * radius + 1; const unsigned nhoodSize = nhoodLen * nhoodLen; @@ -118,11 +122,11 @@ af_array ccHelper(const Array& img, const Array& seedx, CT totSum = reduce_all(S1); CT totSumSq = reduce_all(S2); CT totalNum = numSeeds * nhoodSize; - CT mean = totSum / totalNum; - CT var = calcVar(totSumSq, totSum, totalNum); - CT stddev = std::sqrt(var); - CT lower = mean - mult * stddev; - CT upper = mean + mult * stddev; + CT s1mean = totSum / totalNum; + CT s1var = calcVar(totSumSq, totSum, totalNum); + CT s1stddev = sqrt(s1var); + CT lower = s1mean - mult * s1stddev; + CT upper = s1mean + mult * s1stddev; Array seedIntensities = pointList(in, seedx, seedy); CT maxSeedIntensity = reduce_all(seedIntensities); @@ -133,7 +137,7 @@ af_array ccHelper(const Array& img, const Array& seedx, Array segmented = floodFill(in, seedx, seedy, CT(1), lower, upper); - if (std::abs(var) < epsilon) { + if (std::abs(s1var) < epsilon) { // If variance is close to zero, stop after initial segmentation return getHandle(labelSegmented(segmented)); } @@ -151,18 +155,18 @@ af_array ccHelper(const Array& img, const Array& seedx, Array valids = arithOp(segmented, in, inDims); Array vsqrd = arithOp(valids, valids, inDims); - CT sum = reduce_all(valids, true); - CT sumOfSqs = reduce_all(vsqrd, true); - CT mean = sum / sampleCount; - CT var = calcVar(sumOfSqs, sum, CT(sampleCount)); - CT stddev = std::sqrt(var); - CT newLow = mean - mult * stddev; - CT newHigh = mean + mult * stddev; + CT validsSum = reduce_all(valids, true); + CT sumOfSqs = reduce_all(vsqrd, true); + CT validsMean = validsSum / sampleCount; + CT validsVar = calcVar(sumOfSqs, validsSum, CT(sampleCount)); + CT stddev = sqrt(validsVar); + CT newLow = validsMean - mult * stddev; + CT newHigh = validsMean + mult * stddev; if (newLow > minSeedIntensity) { newLow = minSeedIntensity; } if (newHigh < maxSeedIntensity) { newHigh = maxSeedIntensity; } - if (std::abs(var) < epsilon) { + if (std::abs(validsVar) < epsilon) { // If variance is close to zero, discontinue iterating. continueLoop = false; } @@ -184,11 +188,11 @@ af_err af_confidence_cc(af_array* out, const af_array in, const af_array seedx, AF_ERR_NOT_SUPPORTED); #endif try { - const ArrayInfo inInfo = getInfo(in); - const ArrayInfo seedxInfo = getInfo(seedx); - const ArrayInfo seedyInfo = getInfo(seedy); - const af::dim4 inputDimensions = inInfo.dims(); - const af::dtype inputArrayType = inInfo.getType(); + const ArrayInfo& inInfo = getInfo(in); + const ArrayInfo& seedxInfo = getInfo(seedx); + const ArrayInfo& seedyInfo = getInfo(seedy); + const af::dim4& inputDimensions = inInfo.dims(); + const af::dtype inputArrayType = inInfo.getType(); // TODO(pradeep) handle case where seeds are towards border // and indexing may result in throwing exception @@ -224,7 +228,7 @@ af_err af_confidence_cc(af_array* out, const af_array in, const af_array seedx, break; default: TYPE_ERROR(0, inputArrayType); } - std::swap(*out, output); + swap(*out, output); } CATCHALL; return AF_SUCCESS; diff --git a/src/api/c/convolve.cpp b/src/api/c/convolve.cpp index e2f95fdd09..938808a648 100644 --- a/src/api/c/convolve.cpp +++ b/src/api/c/convolve.cpp @@ -6,16 +6,16 @@ * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ +#include + #include #include #include #include #include -#include #include #include #include - #include #include #include @@ -26,7 +26,17 @@ using af::dim4; using common::half; -using namespace detail; +using detail::arithOp; +using detail::Array; +using detail::cast; +using detail::cdouble; +using detail::cfloat; +using detail::convolve; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; template inline static af_array convolve(const af_array &s, const af_array &f, @@ -65,14 +75,15 @@ AF_BATCH_KIND identifyBatchKind(const dim4 &sDims, const dim4 &fDims) { dim_t sn = sDims.ndims(); dim_t fn = fDims.ndims(); - if (sn == baseDim && fn == baseDim) - return AF_BATCH_NONE; - else if (sn == baseDim && (fn > baseDim && fn <= AF_MAX_DIMS)) + if (sn == baseDim && fn == baseDim) { return AF_BATCH_NONE; } + if (sn == baseDim && (fn > baseDim && fn <= AF_MAX_DIMS)) { return AF_BATCH_RHS; - else if ((sn > baseDim && sn <= AF_MAX_DIMS) && fn == baseDim) + } + if ((sn > baseDim && sn <= AF_MAX_DIMS) && fn == baseDim) { return AF_BATCH_LHS; - else if ((sn > baseDim && sn <= AF_MAX_DIMS) && - (fn > baseDim && fn <= AF_MAX_DIMS)) { + } + if ((sn > baseDim && sn <= AF_MAX_DIMS) && + (fn > baseDim && fn <= AF_MAX_DIMS)) { bool doesDimensionsMatch = true; bool isInterleaved = true; for (dim_t i = baseDim; i < AF_MAX_DIMS; i++) { @@ -80,10 +91,10 @@ AF_BATCH_KIND identifyBatchKind(const dim4 &sDims, const dim4 &fDims) { isInterleaved &= (sDims[i] == 1 || fDims[i] == 1 || sDims[i] == fDims[i]); } - if (doesDimensionsMatch) return AF_BATCH_SAME; + if (doesDimensionsMatch) { return AF_BATCH_SAME; } return (isInterleaved ? AF_BATCH_DIFF : AF_BATCH_UNSUPPORTED); - } else - return AF_BATCH_UNSUPPORTED; + } + return AF_BATCH_UNSUPPORTED; } template @@ -240,36 +251,38 @@ af_err convolve2_sep(af_array *out, af_array col_filter, af_array row_filter, template bool isFreqDomain(const af_array &signal, const af_array filter, af_conv_domain domain) { - if (domain == AF_CONV_FREQ) return true; - if (domain != AF_CONV_AUTO) return false; + if (domain == AF_CONV_FREQ) { return true; } + if (domain != AF_CONV_AUTO) { return false; } const ArrayInfo &sInfo = getInfo(signal); const ArrayInfo &fInfo = getInfo(filter); - dim4 sdims = sInfo.dims(); - dim4 fdims = fInfo.dims(); + const dim4 &sdims = sInfo.dims(); + dim4 fdims = fInfo.dims(); - if (identifyBatchKind(sdims, fdims) == AF_BATCH_DIFF) return true; + if (identifyBatchKind(sdims, fdims) == AF_BATCH_DIFF) { + return true; + } int kbatch = 1; for (int i = 3; i >= baseDim; i--) { kbatch *= fdims[i]; } - if (kbatch >= 10) return true; + if (kbatch >= 10) { return true; } if (baseDim == 1) { - if (fdims[0] > 128) return true; + if (fdims[0] > 128) { return true; } } if (baseDim == 2) { // maximum supported size in 2D domain - if (fdims[0] > 17 || fdims[1] > 17) return true; + if (fdims[0] > 17 || fdims[1] > 17) { return true; } // Maximum supported non square size - if (fdims[0] != fdims[1] && fdims[0] > 5) return true; + if (fdims[0] != fdims[1] && fdims[0] > 5) { return true; } } if (baseDim == 3) { - if (fdims[0] > 5 || fdims[1] > 5 || fdims[2] > 5) return true; + if (fdims[0] > 5 || fdims[1] > 5 || fdims[2] > 5) { return true; } } return false; @@ -278,13 +291,14 @@ bool isFreqDomain(const af_array &signal, const af_array filter, af_err af_convolve1(af_array *out, const af_array signal, const af_array filter, const af_conv_mode mode, af_conv_domain domain) { try { - if (isFreqDomain<1>(signal, filter, domain)) + if (isFreqDomain<1>(signal, filter, domain)) { return af_fft_convolve1(out, signal, filter, mode); + } - if (mode == AF_CONV_EXPAND) + if (mode == AF_CONV_EXPAND) { return convolve<1, true>(out, signal, filter); - else - return convolve<1, false>(out, signal, filter); + } + { return convolve<1, false>(out, signal, filter); } } CATCHALL; } @@ -297,13 +311,15 @@ af_err af_convolve2(af_array *out, const af_array signal, const af_array filter, return af_convolve1(out, signal, filter, mode, domain); } - if (isFreqDomain<2>(signal, filter, domain)) + if (isFreqDomain<2>(signal, filter, domain)) { return af_fft_convolve2(out, signal, filter, mode); + } - if (mode == AF_CONV_EXPAND) + if (mode == AF_CONV_EXPAND) { return convolve<2, true>(out, signal, filter); - else + } else { return convolve<2, false>(out, signal, filter); + } } CATCHALL; } @@ -371,13 +387,15 @@ af_err af_convolve3(af_array *out, const af_array signal, const af_array filter, return af_convolve2(out, signal, filter, mode, domain); } - if (isFreqDomain<3>(signal, filter, domain)) + if (isFreqDomain<3>(signal, filter, domain)) { return af_fft_convolve3(out, signal, filter, mode); + } - if (mode == AF_CONV_EXPAND) + if (mode == AF_CONV_EXPAND) { return convolve<3, true>(out, signal, filter); - else + } else { return convolve<3, false>(out, signal, filter); + } } CATCHALL; } @@ -386,10 +404,11 @@ af_err af_convolve2_sep(af_array *out, const af_array signal, const af_array col_filter, const af_array row_filter, const af_conv_mode mode) { try { - if (mode == AF_CONV_EXPAND) + if (mode == AF_CONV_EXPAND) { return convolve2_sep(out, signal, col_filter, row_filter); - else + } else { return convolve2_sep(out, signal, col_filter, row_filter); + } } CATCHALL; } @@ -398,8 +417,8 @@ template af_array conv2GradCall(const af_array incoming_gradient, const af_array original_signal, const af_array original_filter, - const af_array convolved_output, af::dim4 stride, - af::dim4 padding, af::dim4 dilation, + const af_array convolved_output, const dim4 &stride, + const dim4 &padding, const dim4 &dilation, af_conv_gradient_type grad_type) { if (grad_type == AF_CONV_GRADIENT_FILTER) { return getHandle(detail::conv2FilterGradient( @@ -423,7 +442,7 @@ af_err af_convolve2_gradient_nn( af_conv_gradient_type grad_type) { try { const ArrayInfo &iinfo = getInfo(incoming_gradient); - af::dim4 iDims = iinfo.dims(); + const af::dim4 &iDims = iinfo.dims(); const ArrayInfo &sinfo = getInfo(original_signal); af::dim4 sDims = sinfo.dims(); diff --git a/src/api/c/corrcoef.cpp b/src/api/c/corrcoef.cpp index cb47e1d1df..00b67ab015 100644 --- a/src/api/c/corrcoef.cpp +++ b/src/api/c/corrcoef.cpp @@ -32,8 +32,8 @@ static To corrcoef(const af_array& X, const af_array& Y) { Array xIn = cast(getArray(X)); Array yIn = cast(getArray(Y)); - dim4 dims = xIn.dims(); - dim_t n = xIn.elements(); + const dim4& dims = xIn.dims(); + dim_t n = xIn.elements(); To xSum = detail::reduce_all(xIn); To ySum = detail::reduce_all(yIn); @@ -46,15 +46,17 @@ static To corrcoef(const af_array& X, const af_array& Y) { To ySqSum = detail::reduce_all(ySq); To xySum = detail::reduce_all(xy); - To result = (n * xySum - xSum * ySum) / (sqrt(n * xSqSum - xSum * xSum) * - sqrt(n * ySqSum - ySum * ySum)); + To result = + (n * xySum - xSum * ySum) / (std::sqrt(n * xSqSum - xSum * xSum) * + std::sqrt(n * ySqSum - ySum * ySum)); return result; } +// NOLINTNEXTLINE af_err af_corrcoef(double* realVal, double* imagVal, const af_array X, const af_array Y) { - UNUSED(imagVal); // TODO: implement for complex types + UNUSED(imagVal); // TODO(umar): implement for complex types try { const ArrayInfo& xInfo = getInfo(X); const ArrayInfo& yInfo = getInfo(Y); @@ -66,8 +68,9 @@ af_err af_corrcoef(double* realVal, double* imagVal, const af_array X, ARG_ASSERT(2, (xType == yType)); ARG_ASSERT(2, (xDims.ndims() == yDims.ndims())); - for (dim_t i = 0; i < xDims.ndims(); ++i) + for (dim_t i = 0; i < xDims.ndims(); ++i) { ARG_ASSERT(2, (xDims[i] == yDims[i])); + } switch (xType) { case f64: *realVal = corrcoef(X, Y); break; diff --git a/src/api/c/covariance.cpp b/src/api/c/covariance.cpp index b250743ad1..df9c13e5ff 100644 --- a/src/api/c/covariance.cpp +++ b/src/api/c/covariance.cpp @@ -23,13 +23,13 @@ #include "stats.h" using af::dim4; -using namespace detail; +using detail::Array; template -static af_array cov(const af_array& X, const af_array& Y, const bool isbiased) { - typedef typename baseOutType::type weightType; - Array _x = getArray(X); - Array _y = getArray(Y); +static af_array cov(const af_array& X, const af_array& Y, bool isbiased) { + using weightType = typename baseOutType::type; + const Array _x = getArray(X); + const Array _y = getArray(Y); Array xArr = cast(_x); Array yArr = cast(_y); diff --git a/src/api/c/data.cpp b/src/api/c/data.cpp index b0d76e3fe7..79a604173b 100644 --- a/src/api/c/data.cpp +++ b/src/api/c/data.cpp @@ -27,7 +27,18 @@ using af::dim4; using common::half; -using namespace detail; +using detail::cdouble; +using detail::cfloat; +using detail::createValueArray; +using detail::intl; +using detail::iota; +using detail::padArrayBorders; +using detail::range; +using detail::scalar; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; dim4 verifyDims(const unsigned ndims, const dim_t *const dims) { DIM_ASSERT(1, ndims >= 1); @@ -49,12 +60,8 @@ af_err af_constant(af_array *result, const double value, const unsigned ndims, af_array out; AF_CHECK(af_init()); - dim4 d(1, 1, 1, 1); - if (ndims <= 0) { - return af_create_handle(result, 0, nullptr, type); - } else { - d = verifyDims(ndims, dims); - } + if (ndims <= 0) { return af_create_handle(result, 0, nullptr, type); } + dim4 d = verifyDims(ndims, dims); switch (type) { case f32: out = createHandleFromValue(d, value); break; @@ -92,12 +99,8 @@ af_err af_constant_complex(af_array *result, const double real, af_array out; AF_CHECK(af_init()); - dim4 d(1, 1, 1, 1); - if (ndims <= 0) { - return af_create_handle(result, 0, nullptr, type); - } else { - d = verifyDims(ndims, dims); - } + if (ndims <= 0) { return af_create_handle(result, 0, nullptr, type); } + dim4 d = verifyDims(ndims, dims); switch (type) { case c32: out = createCplx(d, real, imag); break; @@ -117,12 +120,8 @@ af_err af_constant_long(af_array *result, const intl val, const unsigned ndims, af_array out; AF_CHECK(af_init()); - dim4 d(1, 1, 1, 1); - if (ndims <= 0) { - return af_create_handle(result, 0, nullptr, s64); - } else { - d = verifyDims(ndims, dims); - } + if (ndims <= 0) { return af_create_handle(result, 0, nullptr, s64); } + dim4 d = verifyDims(ndims, dims); out = getHandle(createValueArray(d, val)); @@ -139,12 +138,9 @@ af_err af_constant_ulong(af_array *result, const uintl val, af_array out; AF_CHECK(af_init()); - dim4 d(1, 1, 1, 1); - if (ndims <= 0) { - return af_create_handle(result, 0, nullptr, u64); - } else { - d = verifyDims(ndims, dims); - } + if (ndims <= 0) { return af_create_handle(result, 0, nullptr, u64); } + dim4 d = verifyDims(ndims, dims); + out = getHandle(createValueArray(d, val)); std::swap(*result, out); @@ -207,12 +203,8 @@ af_err af_range(af_array *result, const unsigned ndims, const dim_t *const dims, af_array out; AF_CHECK(af_init()); - dim4 d(0); - if (ndims <= 0) { - return af_create_handle(result, 0, nullptr, type); - } else { - d = verifyDims(ndims, dims); - } + if (ndims <= 0) { return af_create_handle(result, 0, nullptr, type); } + dim4 d = verifyDims(ndims, dims); switch (type) { case f32: out = range_(d, seq_dim); break; @@ -364,10 +356,11 @@ af_err af_diag_extract(af_array *out, const af_array in, const int num) { template af_array triangle(const af_array in, bool is_unit_diag) { - if (is_unit_diag) + if (is_unit_diag) { return getHandle(triangle(getArray(in))); - else + } else { return getHandle(triangle(getArray(in))); + } } af_err af_lower(af_array *out, const af_array in, bool is_unit_diag) { diff --git a/src/api/c/deconvolution.cpp b/src/api/c/deconvolution.cpp index 174843c03c..b86c9dca72 100644 --- a/src/api/c/deconvolution.cpp +++ b/src/api/c/deconvolution.cpp @@ -26,12 +26,16 @@ #include #include +#include #include #include #include using af::dim4; -using namespace detail; +using detail::Array; +using detail::shift; +using std::array; +using std::vector; const int BASE_DIM = 2; @@ -58,13 +62,13 @@ Array complexNorm(const Array& input) { std::vector calcPadInfo(dim4& inLPad, dim4& psfLPad, dim4& inUPad, dim4& psfUPad, dim4& odims, dim_t nElems, const dim4& idims, const dim4& fdims) { - std::vector index(4); + vector index(4); for (int d = 0; d < 4; ++d) { if (d < BASE_DIM) { dim_t pad = idims[d] + fdims[d]; - while (greatestPrimeFactor(pad) > GREATEST_PRIME_FACTOR) pad++; + while (greatestPrimeFactor(pad) > GREATEST_PRIME_FACTOR) { pad++; } dim_t diffLen = pad - idims[d]; inLPad[d] = diffLen / 2; @@ -137,7 +141,7 @@ void landweber(Array& currentEstimate, const Array& in, template af_array iterDeconv(const af_array in, const af_array ker, const uint iters, const float rfactor, const af_iterative_deconv_algo algo) { - typedef RealType T; + using T = RealType; using CT = typename std::conditional::value, cdouble, cfloat>::type; auto input = castArray(in); @@ -154,24 +158,25 @@ af_array iterDeconv(const af_array in, const af_array ker, const uint iters, padArrayBorders(input, inLPad, inUPad, AF_PAD_CLAMP_TO_EDGE); auto paddedPsf = padArrayBorders(psf, psfLPad, psfUPad, AF_PAD_ZERO); - const int shiftDims[4] = {-int(fdims[0] / 2), -int(fdims[1] / 2), 0, 0}; - auto shiftedPsf = shift(paddedPsf, shiftDims); + const std::array shiftDims = {-int(fdims[0] / 2), + -int(fdims[1] / 2), 0, 0}; + auto shiftedPsf = shift(paddedPsf, shiftDims.data()); auto P = fft_r2c(shiftedPsf); auto Pc = conj(P); Array currentEstimate = paddedIn; - const double normFactor = 1 / (double)nElems; + const double normFactor = 1 / static_cast(nElems); switch (algo) { case AF_ITERATIVE_DECONV_RICHARDSONLUCY: richardsonLucy(currentEstimate, paddedIn, P, Pc, iters, normFactor, odims); break; + case AF_ITERATIVE_DECONV_LANDWEBER: default: landweber(currentEstimate, paddedIn, P, Pc, iters, rfactor, normFactor, odims); - break; } return getHandle(createSubArray(currentEstimate, index)); } @@ -220,7 +225,7 @@ af_err af_iterative_deconv(af_array* out, const af_array in, const af_array ker, template Array denominator(const Array& I, const Array& P, const float gamma, const af_inverse_deconv_algo algo) { - typedef typename af::dtype_traits::base_type T; + using T = typename af::dtype_traits::base_type; auto RCNST = createValueArray(I.dims(), scalar(gamma)); @@ -245,7 +250,7 @@ Array denominator(const Array& I, const Array& P, const float gamma, template af_array invDeconv(const af_array in, const af_array ker, const float gamma, const af_inverse_deconv_algo algo) { - typedef RealType T; + using T = RealType; using CT = typename std::conditional::value, cdouble, cfloat>::type; auto input = castArray(in); @@ -261,9 +266,10 @@ af_array invDeconv(const af_array in, const af_array ker, const float gamma, auto paddedIn = padArrayBorders(input, inLPad, inUPad, AF_PAD_CLAMP_TO_EDGE); auto paddedPsf = padArrayBorders(psf, psfLPad, psfUPad, AF_PAD_ZERO); - const int shiftDims[4] = {-int(fdims[0] / 2), -int(fdims[1] / 2), 0, 0}; + const array shiftDims = {-int(fdims[0] / 2), -int(fdims[1] / 2), 0, + 0}; - auto shiftedPsf = shift(paddedPsf, shiftDims); + auto shiftedPsf = shift(paddedPsf, shiftDims.data()); auto I = fft_r2c(paddedIn); auto P = fft_r2c(shiftedPsf); @@ -277,7 +283,8 @@ af_array invDeconv(const af_array in, const af_array ker, const float gamma, select_scalar(val, cond, val, 0); - auto ival = fft_c2r(val, 1 / (double)nElems, odims); + auto ival = + fft_c2r(val, 1 / static_cast(nElems), odims); return getHandle(createSubArray(ival, index)); } diff --git a/src/api/c/det.cpp b/src/api/c/det.cpp index 1cd6e76ac1..a5cc7154e8 100644 --- a/src/api/c/det.cpp +++ b/src/api/c/det.cpp @@ -20,7 +20,11 @@ #include using af::dim4; -using namespace detail; +using detail::Array; +using detail::cdouble; +using detail::cfloat; +using detail::createEmptyArray; +using detail::scalar; template T det(const af_array a) { @@ -57,7 +61,7 @@ T det(const af_array a) { is_neg ^= (hP[i] != (i + 1)); } - if (is_neg) res = res * scalar(-1); + if (is_neg) { res = res * scalar(-1); } return res; } @@ -72,9 +76,10 @@ af_err af_det(double *real_val, double *imag_val, const af_array in) { af_dtype type = i_info.getType(); - if (i_info.dims()[0]) + if (i_info.dims()[0]) { DIM_ASSERT(1, i_info.dims()[0] == i_info.dims()[1]); // Only square matrices + } ARG_ASSERT(1, i_info.isFloating()); // Only floating and complex types *real_val = 0; diff --git a/src/api/c/device.cpp b/src/api/c/device.cpp index 99d6983f17..9ea55f8dcb 100644 --- a/src/api/c/device.cpp +++ b/src/api/c/device.cpp @@ -14,7 +14,6 @@ #include #include #include - #include #include #include @@ -23,8 +22,26 @@ #include #include -using namespace detail; +using af::dim4; using common::half; +using detail::Array; +using detail::cdouble; +using detail::cfloat; +using detail::createEmptyArray; +using detail::devprop; +using detail::evalFlag; +using detail::getActiveDeviceId; +using detail::getBackend; +using detail::getDeviceCount; +using detail::getDeviceInfo; +using detail::intl; +using detail::isDoubleSupported; +using detail::isHalfSupported; +using detail::setDevice; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; af_err af_set_backend(const af_backend bknd) { try { @@ -67,7 +84,7 @@ af_err af_get_device_id(int* device, const af_array in) { try { if (in) { const ArrayInfo& info = getInfo(in, false, false); - *device = info.getDevId(); + *device = static_cast(info.getDevId()); } else { return AF_ERR_ARG; } @@ -77,7 +94,7 @@ af_err af_get_device_id(int* device, const af_array in) { } af_err af_get_active_backend(af_backend* result) { - *result = (af_backend)getBackend(); + *result = static_cast(getBackend()); return AF_SUCCESS; } @@ -92,7 +109,7 @@ af_err af_init() { af_err af_info() { try { - printf("%s", getDeviceInfo().c_str()); + printf("%s", getDeviceInfo().c_str()); // NOLINT } CATCHALL; return AF_SUCCESS; @@ -102,7 +119,8 @@ af_err af_info_string(char** str, const bool verbose) { UNUSED(verbose); // TODO(umar): Add something useful try { std::string infoStr = getDeviceInfo(); - af_alloc_host((void**)str, sizeof(char) * (infoStr.size() + 1)); + af_alloc_host(reinterpret_cast(str), + sizeof(char) * (infoStr.size() + 1)); // Need to do a deep copy // str.c_str wont cut it @@ -172,7 +190,7 @@ af_err af_set_device(const int device) { char err_msg[] = "The device index of %d is out of range. Use a value " "between 0 and %d."; - snprintf(buf, 512, err_msg, device, ndevices - 1); + snprintf(buf, 512, err_msg, device, ndevices - 1); // NOLINT AF_ERROR(buf, AF_ERR_ARG); } } @@ -194,13 +212,11 @@ af_err af_sync(const int device) { template static inline void eval(af_array arr) { getArray(arr).eval(); - return; } template static inline void sparseEval(af_array arr) { getSparseArray(arr).eval(); - return; } af_err af_eval(af_array arr) { @@ -250,14 +266,13 @@ static inline void evalMultiple(int num, af_array* arrayPtrs) { } evalMultiple(arrays); - return; } af_err af_eval_multiple(int num, af_array* arrays) { try { const ArrayInfo& info = getInfo(arrays[0]); af_dtype type = info.getType(); - dim4 dims = info.dims(); + const dim4& dims = info.dims(); for (int i = 1; i < num; i++) { const ArrayInfo& currInfo = getInfo(arrays[i]); diff --git a/src/api/c/diff.cpp b/src/api/c/diff.cpp index 1e2c024afe..3fb1cee150 100644 --- a/src/api/c/diff.cpp +++ b/src/api/c/diff.cpp @@ -16,7 +16,13 @@ #include using af::dim4; -using namespace detail; +using detail::cdouble; +using detail::cfloat; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; template static inline af_array diff1(const af_array in, const int dim) { diff --git a/src/api/c/dog.cpp b/src/api/c/dog.cpp index 7b932817a7..633f901409 100644 --- a/src/api/c/dog.cpp +++ b/src/api/c/dog.cpp @@ -7,6 +7,7 @@ * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ +#include #include #include #include @@ -18,7 +19,12 @@ #include using af::dim4; -using namespace detail; +using detail::arithOp; +using detail::Array; +using detail::convolve; +using detail::uchar; +using detail::uint; +using detail::ushort; template static af_array dog(const af_array& in, const int radius1, const int radius2) { diff --git a/src/api/c/error.cpp b/src/api/c/error.cpp index 3404161c36..c818414eaa 100644 --- a/src/api/c/error.cpp +++ b/src/api/c/error.cpp @@ -10,12 +10,14 @@ #include #include #include + #include #include void af_get_last_error(char **str, dim_t *len) { std::string &global_error_string = get_global_error_string(); - dim_t slen = std::min(MAX_ERR_SIZE, (int)global_error_string.size()); + dim_t slen = + std::min(MAX_ERR_SIZE, static_cast(global_error_string.size())); if (len && slen == 0) { *len = 0; @@ -23,13 +25,13 @@ void af_get_last_error(char **str, dim_t *len) { return; } - af_alloc_host((void **)str, sizeof(char) * (slen + 1)); + af_alloc_host(reinterpret_cast(str), sizeof(char) * (slen + 1)); global_error_string.copy(*str, slen); (*str)[slen] = '\0'; global_error_string = std::string(""); - if (len) *len = slen; + if (len) { *len = slen; } } af_err af_set_enable_stacktrace(int is_enabled) { diff --git a/src/api/c/events.cpp b/src/api/c/events.cpp index 24aeed4421..c3d7d5a773 100644 --- a/src/api/c/events.cpp +++ b/src/api/c/events.cpp @@ -14,7 +14,11 @@ #include #include -using namespace detail; +using detail::block; +using detail::createEvent; +using detail::enqueueWaitOnActiveQueue; +using detail::Event; +using detail::markEventOnActiveQueue; Event &getEvent(af_event &handle) { Event &event = *static_cast(handle); diff --git a/src/api/c/fast.cpp b/src/api/c/fast.cpp index 742d68e21f..dbdd50c6a7 100644 --- a/src/api/c/fast.cpp +++ b/src/api/c/fast.cpp @@ -7,6 +7,7 @@ * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ +#include #include #include #include @@ -18,7 +19,12 @@ #include using af::dim4; -using namespace detail; +using detail::Array; +using detail::createEmptyArray; +using detail::createValueArray; +using detail::uchar; +using detail::uint; +using detail::ushort; template static af_features fast(af_array const &in, const float thr, diff --git a/src/api/c/features.cpp b/src/api/c/features.cpp index 0c933aaa1c..06b048e830 100644 --- a/src/api/c/features.cpp +++ b/src/api/c/features.cpp @@ -14,26 +14,27 @@ af_err af_release_features(af_features featHandle) { try { - af_features_t feat = *(af_features_t *)featHandle; + af_features_t feat = *static_cast(featHandle); if (feat.n > 0) { - if (feat.x != 0) AF_CHECK(af_release_array(feat.x)); - if (feat.y != 0) AF_CHECK(af_release_array(feat.y)); - if (feat.score != 0) AF_CHECK(af_release_array(feat.score)); - if (feat.orientation != 0) + if (feat.x != 0) { AF_CHECK(af_release_array(feat.x)); } + if (feat.y != 0) { AF_CHECK(af_release_array(feat.y)); } + if (feat.score != 0) { AF_CHECK(af_release_array(feat.score)); } + if (feat.orientation != 0) { AF_CHECK(af_release_array(feat.orientation)); - if (feat.size != 0) AF_CHECK(af_release_array(feat.size)); + } + if (feat.size != 0) { AF_CHECK(af_release_array(feat.size)); } feat.n = 0; } - delete (af_features_t *)featHandle; + delete static_cast(featHandle); } CATCHALL; return AF_SUCCESS; } af_features getFeaturesHandle(const af_features_t feat) { - af_features_t *featHandle = new af_features_t; - *featHandle = feat; - return (af_features)featHandle; + auto *featHandle = new af_features_t; + *featHandle = feat; + return static_cast(featHandle); } af_err af_create_features(af_features *featHandle, dim_t num) { @@ -58,7 +59,7 @@ af_err af_create_features(af_features *featHandle, dim_t num) { } af_features_t getFeatures(const af_features featHandle) { - return *(af_features_t *)featHandle; + return *static_cast(featHandle); } af_err af_retain_features(af_features *outHandle, diff --git a/src/api/c/fft.cpp b/src/api/c/fft.cpp index 7a8283571d..e68a4a4722 100644 --- a/src/api/c/fft.cpp +++ b/src/api/c/fft.cpp @@ -15,12 +15,15 @@ #include using af::dim4; -using namespace detail; +using detail::Array; +using detail::cdouble; +using detail::cfloat; +using detail::multiply_inplace; void computePaddedDims(dim4 &pdims, const dim4 &idims, const dim_t npad, dim_t const *const pad) { for (int i = 0; i < 4; i++) { - pdims[i] = (i < (int)npad) ? pad[i] : idims[i]; + pdims[i] = (i < static_cast(npad)) ? pad[i] : idims[i]; } } @@ -37,7 +40,7 @@ static af_err fft(af_array *out, const af_array in, const double norm_factor, try { const ArrayInfo &info = getInfo(in); af_dtype type = info.getType(); - af::dim4 dims = info.dims(); + const dim4 &dims = info.dims(); if (dims.ndims() == 0) { return af_retain_array(out, in); } diff --git a/src/api/c/fft_common.hpp b/src/api/c/fft_common.hpp index 76e4dc777e..a8bf7d06a3 100644 --- a/src/api/c/fft_common.hpp +++ b/src/api/c/fft_common.hpp @@ -10,38 +10,38 @@ #include #include -using namespace detail; - -void computePaddedDims(dim4 &pdims, const dim4 &idims, const dim_t npad, +void computePaddedDims(af::dim4 &pdims, const af::dim4 &idims, const dim_t npad, dim_t const *const pad); template -Array fft(const Array input, const double norm_factor, - const dim_t npad, const dim_t *const pad) { - dim4 pdims(1); +detail::Array fft(const detail::Array input, + const double norm_factor, const dim_t npad, + const dim_t *const pad) { + af::dim4 pdims(1); computePaddedDims(pdims, input.dims(), npad, pad); - auto res = padArray(input, pdims, scalar(0)); + auto res = padArray(input, pdims, detail::scalar(0)); - fft_inplace(res); + detail::fft_inplace(res); if (norm_factor != 1.0) multiply_inplace(res, norm_factor); return res; } template -Array fft_r2c(const Array input, const double norm_factor, - const dim_t npad, const dim_t *const pad) { - dim4 idims = input.dims(); +detail::Array fft_r2c(const detail::Array input, + const double norm_factor, const dim_t npad, + const dim_t *const pad) { + af::dim4 idims = input.dims(); bool is_pad = false; for (int i = 0; i < npad; i++) { is_pad |= (pad[i] != idims[i]); } - Array tmp = input; + detail::Array tmp = input; if (is_pad) { - dim4 pdims(1); + af::dim4 pdims(1); computePaddedDims(pdims, input.dims(), npad, pad); - tmp = padArray(input, pdims, scalar(0)); + tmp = padArray(input, pdims, detail::scalar(0)); } auto res = fft_r2c(tmp); @@ -51,9 +51,11 @@ Array fft_r2c(const Array input, const double norm_factor, } template -Array fft_c2r(const Array input, const double norm_factor, - const dim4 &odims) { - Array output = fft_c2r(input, odims); +detail::Array fft_c2r(const detail::Array input, + const double norm_factor, + const af::dim4 &odims) { + detail::Array output = + fft_c2r(input, odims); if (norm_factor != 1) { // Normalize input because tmp was not normalized diff --git a/src/api/c/fftconvolve.cpp b/src/api/c/fftconvolve.cpp index 32694b11e7..87dae06c5c 100644 --- a/src/api/c/fftconvolve.cpp +++ b/src/api/c/fftconvolve.cpp @@ -19,7 +19,22 @@ #include using af::dim4; -using namespace detail; +using detail::arithOp; +using detail::Array; +using detail::cast; +using detail::cdouble; +using detail::cfloat; +using detail::createSubArray; +using detail::fftconvolve; +using detail::intl; +using detail::real; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; +using std::max; +using std::swap; +using std::vector; template static inline af_array fftconvolve_fallback(const af_array signal, @@ -27,13 +42,13 @@ static inline af_array fftconvolve_fallback(const af_array signal, bool expand) { const Array S = castArray(signal); const Array F = castArray(filter); - const dim4 sdims = S.dims(); - const dim4 fdims = F.dims(); + const dim4 &sdims = S.dims(); + const dim4 &fdims = F.dims(); dim4 odims(1, 1, 1, 1); dim4 psdims(1, 1, 1, 1); dim4 pfdims(1, 1, 1, 1); - std::vector index(AF_MAX_DIMS); + vector index(AF_MAX_DIMS); int count = 1; for (int i = 0; i < baseDim; i++) { @@ -49,17 +64,17 @@ static inline af_array fftconvolve_fallback(const af_array signal, // Get the indexing params for output if (expand) { - index[i].begin = 0; - index[i].end = tdim_i - 1; + index[i].begin = 0.; + index[i].end = static_cast(tdim_i) - 1.; } else { - index[i].begin = fdims[i] / 2; - index[i].end = index[i].begin + sdims[i] - 1; + index[i].begin = static_cast(fdims[i]) / 2.0; + index[i].end = static_cast(index[i].begin + sdims[i]) - 1.; } - index[i].step = 1; + index[i].step = 1.; } for (int i = baseDim; i < AF_MAX_DIMS; i++) { - odims[i] = std::max(sdims[i], fdims[i]); + odims[i] = max(sdims[i], fdims[i]); psdims[i] = sdims[i]; pfdims[i] = fdims[i]; index[i] = af_span; @@ -75,8 +90,8 @@ static inline af_array fftconvolve_fallback(const af_array signal, T1 = arithOp(T1, T2, odims); // ifft(ffit(signal) * fft(filter)) - T1 = fft(T1, 1.0 / (double)count, baseDim, - odims.get()); + T1 = fft(T1, 1.0 / static_cast(count), + baseDim, odims.get()); // Index to proper offsets T1 = createSubArray(T1, index); @@ -92,11 +107,12 @@ template inline static af_array fftconvolve(const af_array &s, const af_array &f, const bool expand, AF_BATCH_KIND kind) { - if (kind == AF_BATCH_DIFF) + if (kind == AF_BATCH_DIFF) { return fftconvolve_fallback(s, f, expand); - else + } else { return getHandle(fftconvolve( getArray(s), castArray(f), expand, kind)); + } } template @@ -104,14 +120,14 @@ AF_BATCH_KIND identifyBatchKind(const dim4 &sDims, const dim4 &fDims) { dim_t sn = sDims.ndims(); dim_t fn = fDims.ndims(); - if (sn == baseDim && fn == baseDim) - return AF_BATCH_NONE; - else if (sn == baseDim && (fn > baseDim && fn <= AF_MAX_DIMS)) + if (sn == baseDim && fn == baseDim) { return AF_BATCH_NONE; } + if (sn == baseDim && (fn > baseDim && fn <= AF_MAX_DIMS)) { return AF_BATCH_RHS; - else if ((sn > baseDim && sn <= AF_MAX_DIMS) && fn == baseDim) + } + if ((sn > baseDim && sn <= AF_MAX_DIMS) && fn == baseDim) { return AF_BATCH_LHS; - else if ((sn > baseDim && sn <= AF_MAX_DIMS) && - (fn > baseDim && fn <= AF_MAX_DIMS)) { + } else if ((sn > baseDim && sn <= AF_MAX_DIMS) && + (fn > baseDim && fn <= AF_MAX_DIMS)) { bool doesDimensionsMatch = true; bool isInterleaved = true; for (dim_t i = baseDim; i < AF_MAX_DIMS; i++) { @@ -119,10 +135,11 @@ AF_BATCH_KIND identifyBatchKind(const dim4 &sDims, const dim4 &fDims) { isInterleaved &= (sDims[i] == 1 || fDims[i] == 1 || sDims[i] == fDims[i]); } - if (doesDimensionsMatch) return AF_BATCH_SAME; + if (doesDimensionsMatch) { return AF_BATCH_SAME; } return (isInterleaved ? AF_BATCH_DIFF : AF_BATCH_UNSUPPORTED); - } else + } else { return AF_BATCH_UNSUPPORTED; + } } template @@ -134,8 +151,8 @@ af_err fft_convolve(af_array *out, const af_array signal, const af_array filter, af_dtype stype = sInfo.getType(); - dim4 sdims = sInfo.dims(); - dim4 fdims = fInfo.dims(); + const dim4 &sdims = sInfo.dims(); + const dim4 &fdims = fInfo.dims(); AF_BATCH_KIND convBT = identifyBatchKind(sdims, fdims); @@ -200,7 +217,7 @@ af_err fft_convolve(af_array *out, const af_array signal, const af_array filter, break; default: TYPE_ERROR(1, stype); } - std::swap(*out, output); + swap(*out, output); } CATCHALL; @@ -217,9 +234,8 @@ af_err af_fft_convolve2(af_array *out, const af_array signal, if (getInfo(signal).dims().ndims() < 2 && getInfo(filter).dims().ndims() < 2) { return fft_convolve<1>(out, signal, filter, mode == AF_CONV_EXPAND); - } else { - return fft_convolve<2>(out, signal, filter, mode == AF_CONV_EXPAND); } + return fft_convolve<2>(out, signal, filter, mode == AF_CONV_EXPAND); } af_err af_fft_convolve3(af_array *out, const af_array signal, @@ -227,7 +243,6 @@ af_err af_fft_convolve3(af_array *out, const af_array signal, if (getInfo(signal).dims().ndims() < 3 && getInfo(filter).dims().ndims() < 3) { return fft_convolve<2>(out, signal, filter, mode == AF_CONV_EXPAND); - } else { - return fft_convolve<3>(out, signal, filter, mode == AF_CONV_EXPAND); } + return fft_convolve<3>(out, signal, filter, mode == AF_CONV_EXPAND); } diff --git a/src/api/c/filters.cpp b/src/api/c/filters.cpp index 4ad1834904..c129c01710 100644 --- a/src/api/c/filters.cpp +++ b/src/api/c/filters.cpp @@ -18,7 +18,9 @@ #include using af::dim4; -using namespace detail; +using detail::uchar; +using detail::uint; +using detail::ushort; af_err af_medfilt(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad) { diff --git a/src/api/c/flip.cpp b/src/api/c/flip.cpp index e8c51d1db1..d1a5159ea8 100644 --- a/src/api/c/flip.cpp +++ b/src/api/c/flip.cpp @@ -25,21 +25,28 @@ #include #include -using namespace detail; +using af::dim4; using common::half; +using detail::Array; +using detail::cdouble; +using detail::cfloat; +using detail::intl; +using detail::uchar; +using detail::uintl; +using detail::ushort; using std::swap; using std::vector; template static af_array flipArray(const af_array in, const unsigned dim) { - const Array &input = getArray(in); + const Array input = getArray(in); vector index(4); for (int i = 0; i < 4; i++) { index[i] = af_span; } // Reverse "dim" dim4 in_dims = input.dims(); - af_seq s = {(double)(in_dims[dim] - 1), 0, -1}; + af_seq s = {static_cast(in_dims[dim] - 1), 0, -1}; index[dim] = s; diff --git a/src/api/c/gaussian_kernel.cpp b/src/api/c/gaussian_kernel.cpp index 0fb1bfefb6..b956dc8a69 100644 --- a/src/api/c/gaussian_kernel.cpp +++ b/src/api/c/gaussian_kernel.cpp @@ -20,7 +20,9 @@ #include #include -using namespace detail; +using detail::arithOp; +using detail::Array; +using detail::createValueArray; template Array gaussianKernel(const int rows, const int cols, const double sigma_r, @@ -36,8 +38,8 @@ Array gaussianKernel(const int rows, const int cols, const double sigma_r, Array wt = range(dim4(cols, rows), 0); Array w = transpose(wt, false); - Array c = - createValueArray(odims, scalar((double)(cols - 1) / 2.0)); + Array c = createValueArray( + odims, scalar(static_cast(cols - 1) / 2.0)); w = arithOp(w, c, odims); sigma = sigma_c > 0 ? sigma_c : 0.25 * cols; @@ -51,8 +53,8 @@ Array gaussianKernel(const int rows, const int cols, const double sigma_r, if (rows > 1) { Array w = range(dim4(rows, cols), 0); - Array r = - createValueArray(odims, scalar((double)(rows - 1) / 2.0)); + Array r = createValueArray( + odims, scalar(static_cast(rows - 1) / 2.0)); w = arithOp(w, r, odims); sigma = sigma_r > 0 ? sigma_r : 0.25 * rows; diff --git a/src/api/c/gradient.cpp b/src/api/c/gradient.cpp index 857ad2f2b3..419039ad11 100644 --- a/src/api/c/gradient.cpp +++ b/src/api/c/gradient.cpp @@ -16,7 +16,8 @@ #include using af::dim4; -using namespace detail; +using detail::cdouble; +using detail::cfloat; template static inline void gradient(af_array *grad0, af_array *grad1, diff --git a/src/api/c/harris.cpp b/src/api/c/harris.cpp index ea2f00934f..c55beb3fc5 100644 --- a/src/api/c/harris.cpp +++ b/src/api/c/harris.cpp @@ -17,8 +17,13 @@ #include #include +#include + using af::dim4; -using namespace detail; +using detail::Array; +using detail::createEmptyArray; +using detail::createValueArray; +using std::floor; template static af_features harris(af_array const &in, const unsigned max_corners, @@ -50,12 +55,13 @@ af_err af_harris(af_features *out, const af_array in, const float k_thr) { try { const ArrayInfo &info = getInfo(in); - af::dim4 dims = info.dims(); + dim4 dims = info.dims(); dim_t in_ndims = dims.ndims(); - unsigned filter_len = - (block_size == 0) ? floor(6.f * sigma) : block_size; - if (block_size == 0 && filter_len % 2 == 0) filter_len--; + unsigned filter_len = (block_size == 0) + ? static_cast(floor(6.f * sigma)) + : block_size; + if (block_size == 0 && filter_len % 2 == 0) { filter_len--; } const unsigned edge = (block_size > 0) ? block_size / 2 : filter_len / 2; diff --git a/src/api/c/hist.cpp b/src/api/c/hist.cpp index 10d61963a0..756dd6b80e 100644 --- a/src/api/c/hist.cpp +++ b/src/api/c/hist.cpp @@ -17,9 +17,8 @@ #include #include -using af::dim4; -using namespace detail; -using namespace graphics; +using detail::Array; +using graphics::ForgeManager; template fg_chart setup_histogram(fg_window const window, const af_array in, @@ -27,18 +26,19 @@ fg_chart setup_histogram(fg_window const window, const af_array in, const af_cell* const props) { ForgeModule& _ = graphics::forgePlugin(); - Array histogramInput = getArray(in); - dim_t nBins = histogramInput.elements(); + const Array histogramInput = getArray(in); + dim_t nBins = histogramInput.elements(); // Retrieve Forge Histogram with nBins and array type ForgeManager& fgMngr = forgeManager(); // Get the chart for the current grid position (if any) fg_chart chart = NULL; - if (props->col > -1 && props->row > -1) + if (props->col > -1 && props->row > -1) { chart = fgMngr.getChart(window, props->row, props->col, FG_CHART_2D); - else + } else { chart = fgMngr.getChart(window, 0, 0, FG_CHART_2D); + } // Create a histogram for the chart fg_histogram hist = fgMngr.getHistogram(chart, nBins, getGLType()); @@ -56,15 +56,21 @@ fg_chart setup_histogram(fg_window const window, const af_array in, if (xMin == 0 && xMax == 0 && yMin == 0 && yMax == 0) { // No previous limits. Set without checking - xMin = step_round(minval, false); - xMax = step_round(maxval, true); - yMax = step_round(freqMax, true); + xMin = static_cast(step_round(minval, false)); + xMax = static_cast(step_round(maxval, true)); + yMax = static_cast(step_round(freqMax, true)); // For histogram, always set yMin to 0. yMin = 0; } else { - if (xMin > minval) xMin = step_round(minval, false); - if (xMax < maxval) xMax = step_round(maxval, true); - if (yMax < freqMax) yMax = step_round(freqMax, true); + if (xMin > minval) { + xMin = static_cast(step_round(minval, false)); + } + if (xMax < maxval) { + xMax = static_cast(step_round(maxval, true)); + } + if (yMax < freqMax) { + yMax = static_cast(step_round(freqMax, true)); + } // For histogram, always set yMin to 0. yMin = 0; } diff --git a/src/api/c/histeq.cpp b/src/api/c/histeq.cpp index a4447ac82e..050dd21fe7 100644 --- a/src/api/c/histeq.cpp +++ b/src/api/c/histeq.cpp @@ -20,7 +20,7 @@ #include #include -using namespace detail; +using detail::Array; template static af_array hist_equal(const af_array& in, const af_array& hist) { @@ -31,14 +31,14 @@ static af_array hist_equal(const af_array& in, const af_array& hist) { Array fHist = cast(getArray(hist)); - dim4 hDims = fHist.dims(); - dim_t grayLevels = fHist.elements(); + const dim4& hDims = fHist.dims(); + dim_t grayLevels = fHist.elements(); Array cdf = scan(fHist, 0); float minCdf = reduce_all(cdf); float maxCdf = reduce_all(cdf); - float factor = (float)(grayLevels - 1) / (maxCdf - minCdf); + float factor = static_cast(grayLevels - 1) / (maxCdf - minCdf); // constant array of min value from cdf Array minCnst = createValueArray(hDims, minCdf); diff --git a/src/api/c/histogram.cpp b/src/api/c/histogram.cpp index ad18aa63c7..f5c5c6497b 100644 --- a/src/api/c/histogram.cpp +++ b/src/api/c/histogram.cpp @@ -14,19 +14,25 @@ #include #include -using af::dim4; -using namespace detail; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; template static inline af_array histogram(const af_array in, const unsigned &nbins, const double &minval, const double &maxval, const bool islinear) { - if (islinear) - return getHandle(histogram( + af_array out = nullptr; + if (islinear) { + out = getHandle(histogram( getArray(in), nbins, minval, maxval)); - else - return getHandle(histogram( + } else { + out = getHandle(histogram( getArray(in), nbins, minval, maxval)); + } + return out; } af_err af_histogram(af_array *out, const af_array in, const unsigned nbins, diff --git a/src/api/c/homography.cpp b/src/api/c/homography.cpp index f888b4f92c..e929f1bd66 100644 --- a/src/api/c/homography.cpp +++ b/src/api/c/homography.cpp @@ -17,8 +17,12 @@ #include #include +#include + using af::dim4; -using namespace detail; +using detail::Array; +using detail::createEmptyArray; +using std::swap; template static inline void homography(af_array& H, int& inliers, const af_array x_src, @@ -89,8 +93,8 @@ af_err af_homography(af_array* H, int* inliers, const af_array x_src, break; default: TYPE_ERROR(1, otype); } - std::swap(*H, outH); - std::swap(*inliers, outInl); + swap(*H, outH); + swap(*inliers, outInl); } CATCHALL; diff --git a/src/api/c/hsv_rgb.cpp b/src/api/c/hsv_rgb.cpp index e321125bc9..4661a255cc 100644 --- a/src/api/c/hsv_rgb.cpp +++ b/src/api/c/hsv_rgb.cpp @@ -16,7 +16,9 @@ #include using af::dim4; -using namespace detail; +using detail::Array; +using detail::hsv2rgb; +using detail::rgb2hsv; template static af_array convert(const af_array& in) { diff --git a/src/api/c/iir.cpp b/src/api/c/iir.cpp index 96dfc2b187..2c56011cc2 100644 --- a/src/api/c/iir.cpp +++ b/src/api/c/iir.cpp @@ -19,7 +19,8 @@ #include using af::dim4; -using namespace detail; +using detail::cdouble; +using detail::cfloat; af_err af_fir(af_array* y, const af_array b, const af_array x) { try { @@ -28,9 +29,9 @@ af_err af_fir(af_array* y, const af_array b, const af_array x) { dim4 xdims = getInfo(x).dims(); af_seq seqs[] = {af_span, af_span, af_span, af_span}; - seqs[0].begin = 0; - seqs[0].end = xdims[0] - 1; - seqs[0].step = 1; + seqs[0].begin = 0.; + seqs[0].end = static_cast(xdims[0]) - 1.; + seqs[0].step = 1.; af_array res; AF_CHECK(af_index(&res, out, 4, seqs)); AF_CHECK(af_release_array(out)); diff --git a/src/api/c/image.cpp b/src/api/c/image.cpp index 17505279b7..8f172a6762 100644 --- a/src/api/c/image.cpp +++ b/src/api/c/image.cpp @@ -27,8 +27,16 @@ #include using af::dim4; -using namespace detail; -using namespace graphics; +using detail::arithOp; +using detail::Array; +using detail::cast; +using detail::copy_image; +using detail::createValueArray; +using detail::forgeManager; +using detail::uchar; +using detail::uint; +using detail::ushort; +using graphics::ForgeManager; template Array normalizePerType(const Array& in) { @@ -58,10 +66,10 @@ static fg_image convert_and_copy_image(const af_array in) { ForgeManager& fgMngr = forgeManager(); // The inDims[2] * 100 is a hack to convert to fg_channel_format - // TODO Write a proper conversion function - fg_image ret_val = - fgMngr.getImage(inDims[1], inDims[0], - (fg_channel_format)(inDims[2] * 100), getGLType()); + // TODO(pradeep): Write a proper conversion function + fg_image ret_val = fgMngr.getImage( + inDims[1], inDims[0], static_cast(inDims[2] * 100), + getGLType()); copy_image(normalizePerType(imgData), ret_val); return ret_val; diff --git a/src/api/c/imageio.cpp b/src/api/c/imageio.cpp index c44da9d0f8..ba0a024d9e 100644 --- a/src/api/c/imageio.cpp +++ b/src/api/c/imageio.cpp @@ -35,17 +35,20 @@ #include using af::dim4; -using namespace detail; +using detail::pinnedAlloc; +using detail::pinnedFree; +using detail::uchar; +using detail::uint; +using detail::ushort; using std::string; using std::swap; -using std::unique_ptr; template static af_err readImage(af_array* rImage, const uchar* pSrcLine, const int nSrcPitch, const uint fi_w, const uint fi_h) { // create an array to receive the loaded image data. AF_CHECK(af_init()); - float* pDst = pinnedAlloc(fi_w * fi_h * 4); // 4 channels is max + auto* pDst = pinnedAlloc(fi_w * fi_h * 4); // 4 channels is max float* pDst0 = pDst; float* pDst1 = pDst + (fi_w * fi_h * 1); float* pDst2 = pDst + (fi_w * fi_h * 2); @@ -56,32 +59,37 @@ static af_err readImage(af_array* rImage, const uchar* pSrcLine, for (uint x = 0; x < fi_w; ++x) { for (uint y = 0; y < fi_h; ++y) { - const T* src = (T*)(pSrcLine - y * nSrcPitch); + const T* src = reinterpret_cast(pSrcLine - y * nSrcPitch); if (fo_color == 1) { - pDst0[indx] = (T) * (src + (x * step)); + pDst0[indx] = static_cast(*(src + (x * step))); } else if (fo_color >= 3) { - if ((af_dtype)af::dtype_traits::af_type == u8) { - pDst0[indx] = (float)*(src + (x * step + FI_RGBA_RED)); - pDst1[indx] = (float)*(src + (x * step + FI_RGBA_GREEN)); - pDst2[indx] = (float)*(src + (x * step + FI_RGBA_BLUE)); - if (fo_color == 4) - pDst3[indx] = - (float)*(src + (x * step + FI_RGBA_ALPHA)); + if (static_cast(af::dtype_traits::af_type) == u8) { + pDst0[indx] = + static_cast(*(src + (x * step + FI_RGBA_RED))); + pDst1[indx] = + static_cast(*(src + (x * step + FI_RGBA_GREEN))); + pDst2[indx] = + static_cast(*(src + (x * step + FI_RGBA_BLUE))); + if (fo_color == 4) { + pDst3[indx] = static_cast( + *(src + (x * step + FI_RGBA_ALPHA))); + } } else { // Non 8-bit types do not use ordering // See Pixel Access Functions Chapter in FreeImage Doc - pDst0[indx] = (float)*(src + (x * step + 0)); - pDst1[indx] = (float)*(src + (x * step + 1)); - pDst2[indx] = (float)*(src + (x * step + 2)); - if (fo_color == 4) - pDst3[indx] = (float)*(src + (x * step + 3)); + pDst0[indx] = static_cast(*(src + (x * step + 0))); + pDst1[indx] = static_cast(*(src + (x * step + 1))); + pDst2[indx] = static_cast(*(src + (x * step + 2))); + if (fo_color == 4) { + pDst3[indx] = + static_cast(*(src + (x * step + 3))); + } } } indx++; } } - // TODO af::dim4 dims(fi_h, fi_w, fo_color, 1); af_err err = af_create_array(rImage, pDst, dims.ndims(), dims.get(), (af_dtype)af::dtype_traits::af_type); @@ -104,7 +112,8 @@ FreeImage_Module::FreeImage_Module() : module(nullptr, nullptr) { FreeImage_Module::FreeImage_Module() : module("freeimage", nullptr) { if (!module.isLoaded()) { string error_message = - "Error loading FreeImage: " + module.getErrorMessage() + + "Error loading FreeImage: " + + common::DependencyModule::getErrorMessage() + "\nFreeImage or one of it's dependencies failed to " "load. Try installing FreeImage or check if FreeImage is in the " "search path."; @@ -139,7 +148,8 @@ FreeImage_Module::FreeImage_Module() : module("freeimage", nullptr) { #ifndef FREEIMAGE_STATIC if (!module.symbolsLoaded()) { string error_message = - "Error loading FreeImage: " + module.getErrorMessage() + + "Error loading FreeImage: " + + common::DependencyModule::getErrorMessage() + "\nThe installed version of FreeImage is not compatible with " "ArrayFire. Please create an issue on which this error message"; AF_ERROR(error_message.c_str(), AF_ERR_LOAD_LIB); @@ -147,14 +157,15 @@ FreeImage_Module::FreeImage_Module() : module("freeimage", nullptr) { #endif } -FreeImage_Module::~FreeImage_Module() { +FreeImage_Module::~FreeImage_Module() { // NOLINT(hicpp-use-equals-default, + // modernize-use-equals-default) #ifdef FREEIMAGE_STATIC getFreeImagePlugin().FreeImage_DeInitialise(); #endif } FreeImage_Module& getFreeImagePlugin() { - static FreeImage_Module* plugin = new FreeImage_Module(); + static auto* plugin = new FreeImage_Module(); return *plugin; } @@ -167,27 +178,27 @@ static af_err readImage(af_array* rImage, const uchar* pSrcLine, const int nSrcPitch, const uint fi_w, const uint fi_h) { // create an array to receive the loaded image data. AF_CHECK(af_init()); - float* pDst = pinnedAlloc(fi_w * fi_h); + auto* pDst = pinnedAlloc(fi_w * fi_h); uint indx = 0; uint step = nSrcPitch / (fi_w * sizeof(T)); T r, g, b; for (uint x = 0; x < fi_w; ++x) { for (uint y = 0; y < fi_h; ++y) { - const T* src = (T*)(pSrcLine - y * nSrcPitch); + const T* src = reinterpret_cast(pSrcLine - y * nSrcPitch); if (fo_color == 1) { - pDst[indx] = (T) * (src + (x * step)); + pDst[indx] = static_cast(*(src + (x * step))); } else if (fo_color >= 3) { - if ((af_dtype)af::dtype_traits::af_type == u8) { - r = (T) * (src + (x * step + FI_RGBA_RED)); - g = (T) * (src + (x * step + FI_RGBA_GREEN)); - b = (T) * (src + (x * step + FI_RGBA_BLUE)); + if (static_cast(af::dtype_traits::af_type) == u8) { + r = *(src + (x * step + FI_RGBA_RED)); + g = *(src + (x * step + FI_RGBA_GREEN)); + b = *(src + (x * step + FI_RGBA_BLUE)); } else { // Non 8-bit types do not use ordering // See Pixel Access Functions Chapter in FreeImage Doc - r = (T) * (src + (x * step + 0)); - g = (T) * (src + (x * step + 1)); - b = (T) * (src + (x * step + 2)); + r = *(src + (x * step + 0)); + g = *(src + (x * step + 1)); + b = *(src + (x * step + 2)); } pDst[indx] = r * 0.2989f + g * 0.5870f + b * 0.1140f; } @@ -226,16 +237,21 @@ af_err af_load_image(af_array* out, const char* filename, const bool isColor) { AF_ERR_NOT_SUPPORTED); } - int flags = 0; - if (fif == FIF_JPEG) flags = flags | JPEG_ACCURATE; + unsigned flags = 0; + if (fif == FIF_JPEG) { + flags = flags | static_cast(JPEG_ACCURATE); + } #ifdef JPEG_GREYSCALE - if (fif == FIF_JPEG && !isColor) flags = flags | JPEG_GREYSCALE; + if (fif == FIF_JPEG && !isColor) { + flags = flags | static_cast(JPEG_GREYSCALE); + } #endif // check that the plugin has reading capabilities ... bitmap_ptr pBitmap = make_bitmap_ptr(NULL); if (_.FreeImage_FIFSupportsReading(fif)) { - pBitmap.reset(_.FreeImage_Load(fif, filename, flags)); + pBitmap.reset( + _.FreeImage_Load(fif, filename, static_cast(flags))); } if (pBitmap == NULL) { @@ -248,7 +264,7 @@ af_err af_load_image(af_array* out, const char* filename, const bool isColor) { uint color_type = _.FreeImage_GetColorType(pBitmap.get()); const uint fi_bpp = _.FreeImage_GetBPP(pBitmap.get()); // int fi_color = (int)((fi_bpp / 8.0) + 0.5); //ceil - int fi_color; + uint fi_color; switch (color_type) { case 0: // FIC_MINISBLACK case 1: // FIC_MINISWHITE @@ -267,7 +283,7 @@ af_err af_load_image(af_array* out, const char* filename, const bool isColor) { break; } - const int fi_bpc = fi_bpp / fi_color; + const uint fi_bpc = fi_bpp / fi_color; if (fi_bpc != 8 && fi_bpc != 16 && fi_bpc != 32) { AF_ERROR("FreeImage Error: Bits per channel not supported", AF_ERR_NOT_SUPPORTED); @@ -289,19 +305,19 @@ af_err af_load_image(af_array* out, const char* filename, const bool isColor) { af_array rImage; if (isColor) { if (fi_color == 4) { // 4 channel image - if (fi_bpc == 8) + if (fi_bpc == 8) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK( (readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { switch (image_type) { case FIT_UINT32: AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { switch (image_type) { case FIT_UINT32: AF_CHECK(( @@ -370,19 +387,20 @@ af_err af_load_image(af_array* out, const char* filename, const bool isColor) { AF_ERR_NOT_SUPPORTED); break; } + } } else { // 3 channel image - if (fi_bpc == 8) + if (fi_bpc == 8) { AF_CHECK(( readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { switch (image_type) { case FIT_UINT32: AF_CHECK( @@ -413,18 +431,19 @@ af_err af_load_image(af_array* out, const char* filename, const bool isColor) { AF_ERR_NOT_SUPPORTED); break; } + } } } else { // output gray irrespective if (fi_color == 1) { // 4 channel image - if (fi_bpc == 8) + if (fi_bpc == 8) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { switch (image_type) { case FIT_UINT32: AF_CHECK((readImage)(&rImage, @@ -449,16 +468,17 @@ af_err af_load_image(af_array* out, const char* filename, const bool isColor) { AF_ERR_NOT_SUPPORTED); break; } + } } else if (fi_color == 3 || fi_color == 4) { - if (fi_bpc == 8) + if (fi_bpc == 8) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { switch (image_type) { case FIT_UINT32: AF_CHECK((readImage)(&rImage, @@ -483,6 +503,7 @@ af_err af_load_image(af_array* out, const char* filename, const bool isColor) { AF_ERR_NOT_SUPPORTED); break; } + } } } @@ -519,15 +540,15 @@ af_err af_save_image(const char* filename, const af_array in_) { DIM_ASSERT(1, channels <= 4); DIM_ASSERT(1, channels != 2); - int fi_bpp = channels * 8; + uint fi_bpp = channels * 8; // sizes uint fi_w = info.dims()[1]; uint fi_h = info.dims()[0]; // create the result image storage using FreeImage - bitmap_ptr pResultBitmap = - make_bitmap_ptr(_.FreeImage_Allocate(fi_w, fi_h, fi_bpp, 0, 0, 0)); + bitmap_ptr pResultBitmap = make_bitmap_ptr(_.FreeImage_Allocate( + fi_w, fi_h, static_cast(fi_bpp), 0, 0, 0)); if (pResultBitmap == NULL) { AF_ERROR("FreeImage Error: Error creating image or file", AF_ERR_RUNTIME); @@ -546,7 +567,7 @@ af_err af_save_image(const char* filename, const af_array in_) { AF_CHECK(af_mul(&in, in_, c255, false)); AF_CHECK(af_release_array(c255)); free_in = true; - } else if (max_real < 256) { + } else if (max_real < 256) { // NOLINT(bugprone-branch-clone) in = in_; } else if (max_real < 65536) { af_array c255 = 0; @@ -556,7 +577,7 @@ af_err af_save_image(const char* filename, const af_array in_) { AF_CHECK(af_release_array(c255)); free_in = true; } else { - in = in_; + in = (in_); } // FI = row major | AF = column major @@ -578,10 +599,11 @@ af_err af_save_image(const char* filename, const af_array in_) { AF_CHECK(af_transpose(&aaT, aa, false)); const ArrayInfo& cinfo = getInfo(rrT); - float* pSrc0 = pinnedAlloc(cinfo.elements()); - float* pSrc1 = pinnedAlloc(cinfo.elements()); - float* pSrc2 = pinnedAlloc(cinfo.elements()); - float* pSrc3 = pinnedAlloc(cinfo.elements()); + + auto* pSrc0 = pinnedAlloc(cinfo.elements()); + auto* pSrc1 = pinnedAlloc(cinfo.elements()); + auto* pSrc2 = pinnedAlloc(cinfo.elements()); + auto* pSrc3 = pinnedAlloc(cinfo.elements()); AF_CHECK(af_get_data_ptr((void*)pSrc0, rrT)); AF_CHECK(af_get_data_ptr((void*)pSrc1, ggT)); @@ -592,13 +614,13 @@ af_err af_save_image(const char* filename, const af_array in_) { for (uint y = 0; y < fi_h; ++y) { for (uint x = 0; x < fi_w; ++x) { *(pDstLine + x * step + FI_RGBA_RED) = - (uchar)pSrc0[indx]; // r + static_cast(pSrc0[indx]); // r *(pDstLine + x * step + FI_RGBA_GREEN) = - (uchar)pSrc1[indx]; // g + static_cast(pSrc1[indx]); // g *(pDstLine + x * step + FI_RGBA_BLUE) = - (uchar)pSrc2[indx]; // b + static_cast(pSrc2[indx]); // b *(pDstLine + x * step + FI_RGBA_ALPHA) = - (uchar)pSrc3[indx]; // a + static_cast(pSrc3[indx]); // a ++indx; } pDstLine -= nDstPitch; @@ -613,9 +635,10 @@ af_err af_save_image(const char* filename, const af_array in_) { AF_CHECK(af_transpose(&bbT, bb, false)); const ArrayInfo& cinfo = getInfo(rrT); - float* pSrc0 = pinnedAlloc(cinfo.elements()); - float* pSrc1 = pinnedAlloc(cinfo.elements()); - float* pSrc2 = pinnedAlloc(cinfo.elements()); + + auto* pSrc0 = pinnedAlloc(cinfo.elements()); + auto* pSrc1 = pinnedAlloc(cinfo.elements()); + auto* pSrc2 = pinnedAlloc(cinfo.elements()); AF_CHECK(af_get_data_ptr((void*)pSrc0, rrT)); AF_CHECK(af_get_data_ptr((void*)pSrc1, ggT)); @@ -625,11 +648,11 @@ af_err af_save_image(const char* filename, const af_array in_) { for (uint y = 0; y < fi_h; ++y) { for (uint x = 0; x < fi_w; ++x) { *(pDstLine + x * step + FI_RGBA_RED) = - (uchar)pSrc0[indx]; // r + static_cast(pSrc0[indx]); // r *(pDstLine + x * step + FI_RGBA_GREEN) = - (uchar)pSrc1[indx]; // g + static_cast(pSrc1[indx]); // g *(pDstLine + x * step + FI_RGBA_BLUE) = - (uchar)pSrc2[indx]; // b + static_cast(pSrc2[indx]); // b ++indx; } pDstLine -= nDstPitch; @@ -640,12 +663,12 @@ af_err af_save_image(const char* filename, const af_array in_) { } else { AF_CHECK(af_transpose(&rrT, rr, false)); const ArrayInfo& cinfo = getInfo(rrT); - float* pSrc0 = pinnedAlloc(cinfo.elements()); + auto* pSrc0 = pinnedAlloc(cinfo.elements()); AF_CHECK(af_get_data_ptr((void*)pSrc0, rrT)); for (uint y = 0; y < fi_h; ++y) { for (uint x = 0; x < fi_w; ++x) { - *(pDstLine + x * step) = (uchar)pSrc0[indx]; + *(pDstLine + x * step) = static_cast(pSrc0[indx]); ++indx; } pDstLine -= nDstPitch; @@ -653,26 +676,28 @@ af_err af_save_image(const char* filename, const af_array in_) { pinnedFree(pSrc0); } - int flags = 0; - if (fif == FIF_JPEG) flags = flags | JPEG_QUALITYSUPERB; + unsigned flags = 0; + if (fif == FIF_JPEG) { + flags = flags | static_cast(JPEG_QUALITYSUPERB); + } // now save the result image - if (!(_.FreeImage_Save(fif, pResultBitmap.get(), filename, flags) == - TRUE)) { + if (_.FreeImage_Save(fif, pResultBitmap.get(), filename, + static_cast(flags)) == FALSE) { AF_ERROR("FreeImage Error: Failed to save image", AF_ERR_RUNTIME); } - if (free_in) AF_CHECK(af_release_array(in)); - if (rr != 0) AF_CHECK(af_release_array(rr)); - if (gg != 0) AF_CHECK(af_release_array(gg)); - if (bb != 0) AF_CHECK(af_release_array(bb)); - if (aa != 0) AF_CHECK(af_release_array(aa)); - if (rrT != 0) AF_CHECK(af_release_array(rrT)); - if (ggT != 0) AF_CHECK(af_release_array(ggT)); - if (bbT != 0) AF_CHECK(af_release_array(bbT)); - if (aaT != 0) AF_CHECK(af_release_array(aaT)); + if (free_in) { AF_CHECK(af_release_array(in)); } + if (rr != 0) { AF_CHECK(af_release_array(rr)); } + if (gg != 0) { AF_CHECK(af_release_array(gg)); } + if (bb != 0) { AF_CHECK(af_release_array(bb)); } + if (aa != 0) { AF_CHECK(af_release_array(aa)); } + if (rrT != 0) { AF_CHECK(af_release_array(rrT)); } + if (ggT != 0) { AF_CHECK(af_release_array(ggT)); } + if (bbT != 0) { AF_CHECK(af_release_array(bbT)); } + if (aaT != 0) { AF_CHECK(af_release_array(aaT)); } } - CATCHALL + CATCHALL; return AF_SUCCESS; } @@ -690,7 +715,7 @@ af_err af_load_image_memory(af_array* out, const void* ptr) { // set your own FreeImage error handler _.FreeImage_SetOutputMessage(FreeImageErrorHandler); - FIMEMORY* stream = (FIMEMORY*)ptr; + auto* stream = static_cast(const_cast(ptr)); _.FreeImage_SeekMemory(stream, 0L, SEEK_SET); // try to guess the file format from the file extension @@ -704,13 +729,16 @@ af_err af_load_image_memory(af_array* out, const void* ptr) { AF_ERR_NOT_SUPPORTED); } - int flags = 0; - if (fif == FIF_JPEG) flags = flags | JPEG_ACCURATE; + unsigned flags = 0; + if (fif == FIF_JPEG) { + flags = flags | static_cast(JPEG_ACCURATE); + } // check that the plugin has reading capabilities ... bitmap_ptr pBitmap = make_bitmap_ptr(NULL); if (_.FreeImage_FIFSupportsReading(fif)) { - pBitmap.reset(_.FreeImage_LoadFromMemory(fif, stream, flags)); + pBitmap.reset(_.FreeImage_LoadFromMemory(fif, stream, + static_cast(flags))); } if (pBitmap == NULL) { @@ -741,7 +769,7 @@ af_err af_load_image_memory(af_array* out, const void* ptr) { fi_color = 3; break; } - const int fi_bpc = fi_bpp / fi_color; + const uint fi_bpc = fi_bpp / fi_color; if (fi_bpc != 8 && fi_bpc != 16 && fi_bpc != 32) { AF_ERROR("FreeImage Error: Bits per channel not supported", AF_ERR_NOT_SUPPORTED); @@ -759,47 +787,50 @@ af_err af_load_image_memory(af_array* out, const void* ptr) { // result image af_array rImage; if (fi_color == 4) { // 4 channel image - if (fi_bpc == 8) + if (fi_bpc == 8) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); + } } else if (fi_color == 1) { // 1 channel image - if (fi_bpc == 8) + if (fi_bpc == 8) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); + } } else { // 3 channel image - if (fi_bpc == 8) + if (fi_bpc == 8) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { AF_CHECK((readImage)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); + } } swap(*out, rImage); @@ -819,7 +850,7 @@ af_err af_save_image_memory(void** ptr, const af_array in_, _.FreeImage_SetOutputMessage(FreeImageErrorHandler); // try to guess the file format from the file extension - FREE_IMAGE_FORMAT fif = (FREE_IMAGE_FORMAT)format; + auto fif = static_cast(format); if (fif == FIF_UNKNOWN || fif > 34) { // FreeImage FREE_IMAGE_FORMAT // has upto 34 enums as of 3.17 @@ -832,15 +863,15 @@ af_err af_save_image_memory(void** ptr, const af_array in_, DIM_ASSERT(1, channels <= 4); DIM_ASSERT(1, channels != 2); - int fi_bpp = channels * 8; + uint fi_bpp = channels * 8; // sizes uint fi_w = info.dims()[1]; uint fi_h = info.dims()[0]; // create the result image storage using FreeImage - bitmap_ptr pResultBitmap = - make_bitmap_ptr(_.FreeImage_Allocate(fi_w, fi_h, fi_bpp, 0, 0, 0)); + bitmap_ptr pResultBitmap = make_bitmap_ptr(_.FreeImage_Allocate( + fi_w, fi_h, static_cast(fi_bpp), 0, 0, 0)); if (pResultBitmap == NULL) { AF_ERROR("FreeImage Error: Error creating image or file", AF_ERR_RUNTIME); @@ -882,10 +913,10 @@ af_err af_save_image_memory(void** ptr, const af_array in_, AF_CHECK(af_transpose(&aaT, aa, false)); const ArrayInfo& cinfo = getInfo(rrT); - float* pSrc0 = pinnedAlloc(cinfo.elements()); - float* pSrc1 = pinnedAlloc(cinfo.elements()); - float* pSrc2 = pinnedAlloc(cinfo.elements()); - float* pSrc3 = pinnedAlloc(cinfo.elements()); + auto* pSrc0 = pinnedAlloc(cinfo.elements()); + auto* pSrc1 = pinnedAlloc(cinfo.elements()); + auto* pSrc2 = pinnedAlloc(cinfo.elements()); + auto* pSrc3 = pinnedAlloc(cinfo.elements()); AF_CHECK(af_get_data_ptr((void*)pSrc0, rrT)); AF_CHECK(af_get_data_ptr((void*)pSrc1, ggT)); @@ -896,13 +927,13 @@ af_err af_save_image_memory(void** ptr, const af_array in_, for (uint y = 0; y < fi_h; ++y) { for (uint x = 0; x < fi_w; ++x) { *(pDstLine + x * step + FI_RGBA_RED) = - (uchar)pSrc0[indx]; // r + static_cast(pSrc0[indx]); // r *(pDstLine + x * step + FI_RGBA_GREEN) = - (uchar)pSrc1[indx]; // g + static_cast(pSrc1[indx]); // g *(pDstLine + x * step + FI_RGBA_BLUE) = - (uchar)pSrc2[indx]; // b + static_cast(pSrc2[indx]); // b *(pDstLine + x * step + FI_RGBA_ALPHA) = - (uchar)pSrc3[indx]; // a + static_cast(pSrc3[indx]); // a ++indx; } pDstLine -= nDstPitch; @@ -917,9 +948,9 @@ af_err af_save_image_memory(void** ptr, const af_array in_, AF_CHECK(af_transpose(&bbT, bb, false)); const ArrayInfo& cinfo = getInfo(rrT); - float* pSrc0 = pinnedAlloc(cinfo.elements()); - float* pSrc1 = pinnedAlloc(cinfo.elements()); - float* pSrc2 = pinnedAlloc(cinfo.elements()); + auto* pSrc0 = pinnedAlloc(cinfo.elements()); + auto* pSrc1 = pinnedAlloc(cinfo.elements()); + auto* pSrc2 = pinnedAlloc(cinfo.elements()); AF_CHECK(af_get_data_ptr((void*)pSrc0, rrT)); AF_CHECK(af_get_data_ptr((void*)pSrc1, ggT)); @@ -929,11 +960,11 @@ af_err af_save_image_memory(void** ptr, const af_array in_, for (uint y = 0; y < fi_h; ++y) { for (uint x = 0; x < fi_w; ++x) { *(pDstLine + x * step + FI_RGBA_RED) = - (uchar)pSrc0[indx]; // r + static_cast(pSrc0[indx]); // r *(pDstLine + x * step + FI_RGBA_GREEN) = - (uchar)pSrc1[indx]; // g + static_cast(pSrc1[indx]); // g *(pDstLine + x * step + FI_RGBA_BLUE) = - (uchar)pSrc2[indx]; // b + static_cast(pSrc2[indx]); // b ++indx; } pDstLine -= nDstPitch; @@ -944,12 +975,12 @@ af_err af_save_image_memory(void** ptr, const af_array in_, } else { AF_CHECK(af_transpose(&rrT, rr, false)); const ArrayInfo& cinfo = getInfo(rrT); - float* pSrc0 = pinnedAlloc(cinfo.elements()); + auto* pSrc0 = pinnedAlloc(cinfo.elements()); AF_CHECK(af_get_data_ptr((void*)pSrc0, rrT)); for (uint y = 0; y < fi_h; ++y) { for (uint x = 0; x < fi_w; ++x) { - *(pDstLine + x * step) = (uchar)pSrc0[indx]; + *(pDstLine + x * step) = static_cast(pSrc0[indx]); ++indx; } pDstLine -= nDstPitch; @@ -961,28 +992,30 @@ af_err af_save_image_memory(void** ptr, const af_array in_, uint32_t size_in_bytes = 0; FIMEMORY* stream = _.FreeImage_OpenMemory(data, size_in_bytes); - int flags = 0; - if (fif == FIF_JPEG) flags = flags | JPEG_QUALITYSUPERB; + unsigned flags = 0; + if (fif == FIF_JPEG) { + flags = flags | static_cast(JPEG_QUALITYSUPERB); + } // now save the result image - if (!(_.FreeImage_SaveToMemory(fif, pResultBitmap.get(), stream, - flags) == TRUE)) { + if (_.FreeImage_SaveToMemory(fif, pResultBitmap.get(), stream, + static_cast(flags)) == FALSE) { AF_ERROR("FreeImage Error: Failed to save image", AF_ERR_RUNTIME); } *ptr = stream; - if (free_in) AF_CHECK(af_release_array(in)); - if (rr != 0) AF_CHECK(af_release_array(rr)); - if (gg != 0) AF_CHECK(af_release_array(gg)); - if (bb != 0) AF_CHECK(af_release_array(bb)); - if (aa != 0) AF_CHECK(af_release_array(aa)); - if (rrT != 0) AF_CHECK(af_release_array(rrT)); - if (ggT != 0) AF_CHECK(af_release_array(ggT)); - if (bbT != 0) AF_CHECK(af_release_array(bbT)); - if (aaT != 0) AF_CHECK(af_release_array(aaT)); + if (free_in) { AF_CHECK(af_release_array(in)); } + if (rr != 0) { AF_CHECK(af_release_array(rr)); } + if (gg != 0) { AF_CHECK(af_release_array(gg)); } + if (bb != 0) { AF_CHECK(af_release_array(bb)); } + if (aa != 0) { AF_CHECK(af_release_array(aa)); } + if (rrT != 0) { AF_CHECK(af_release_array(rrT)); } + if (ggT != 0) { AF_CHECK(af_release_array(ggT)); } + if (bbT != 0) { AF_CHECK(af_release_array(bbT)); } + if (aaT != 0) { AF_CHECK(af_release_array(aaT)); } } - CATCHALL + CATCHALL; return AF_SUCCESS; } @@ -996,19 +1029,19 @@ af_err af_delete_image_memory(void* ptr) { // set your own FreeImage error handler _.FreeImage_SetOutputMessage(FreeImageErrorHandler); - FIMEMORY* stream = (FIMEMORY*)ptr; + auto* stream = static_cast(ptr); _.FreeImage_SeekMemory(stream, 0L, SEEK_SET); // Ensure data is freeimage compatible FREE_IMAGE_FORMAT fif = - _.FreeImage_GetFileTypeFromMemory((FIMEMORY*)ptr, 0); + _.FreeImage_GetFileTypeFromMemory(static_cast(ptr), 0); if (fif == FIF_UNKNOWN) { AF_ERROR("FreeImage Error: Unknown Filetype", AF_ERR_NOT_SUPPORTED); } - _.FreeImage_CloseMemory((FIMEMORY*)ptr); + _.FreeImage_CloseMemory(static_cast(ptr)); } - CATCHALL + CATCHALL; return AF_SUCCESS; } diff --git a/src/api/c/imageio2.cpp b/src/api/c/imageio2.cpp index 13b7d0a3b7..f1edab6d7e 100644 --- a/src/api/c/imageio2.cpp +++ b/src/api/c/imageio2.cpp @@ -32,7 +32,11 @@ #include using af::dim4; -using namespace detail; +using detail::pinnedAlloc; +using detail::pinnedFree; +using detail::uchar; +using detail::uint; +using detail::ushort; template static af_err readImage_t(af_array* rImage, const uchar* pSrcLine, @@ -51,60 +55,63 @@ static af_err readImage_t(af_array* rImage, const uchar* pSrcLine, for (uint x = 0; x < fi_w; ++x) { for (uint y = 0; y < fi_h; ++y) { - const T* src = (T*)((uchar*)pSrcLine - y * nSrcPitch); + const T* src = reinterpret_cast(const_cast(pSrcLine) - + y * nSrcPitch); if (fi_color == 1) { - pDst0[indx] = (T) * (src + (x * step)); + pDst0[indx] = *(src + (x * step)); } else if (fi_color >= 3) { - if ((af_dtype)af::dtype_traits::af_type == u8) { - pDst0[indx] = (T) * (src + (x * step + FI_RGBA_RED)); - pDst1[indx] = (T) * (src + (x * step + FI_RGBA_GREEN)); - pDst2[indx] = (T) * (src + (x * step + FI_RGBA_BLUE)); - if (fi_color == 4) - pDst3[indx] = (T) * (src + (x * step + FI_RGBA_ALPHA)); + if (static_cast(af::dtype_traits::af_type) == u8) { + pDst0[indx] = *(src + (x * step + FI_RGBA_RED)); + pDst1[indx] = *(src + (x * step + FI_RGBA_GREEN)); + pDst2[indx] = *(src + (x * step + FI_RGBA_BLUE)); + if (fi_color == 4) { + pDst3[indx] = *(src + (x * step + FI_RGBA_ALPHA)); + } } else { // Non 8-bit types do not use ordering // See Pixel Access Functions Chapter in FreeImage Doc - pDst0[indx] = (T) * (src + (x * step + 0)); - pDst1[indx] = (T) * (src + (x * step + 1)); - pDst2[indx] = (T) * (src + (x * step + 2)); - if (fi_color == 4) - pDst3[indx] = (T) * (src + (x * step + 3)); + pDst0[indx] = *(src + (x * step + 0)); + pDst1[indx] = *(src + (x * step + 1)); + pDst2[indx] = *(src + (x * step + 2)); + if (fi_color == 4) { + pDst3[indx] = *(src + (x * step + 3)); + } } } indx++; } } - // TODO af::dim4 dims(fi_h, fi_w, fi_color, 1); - af_err err = af_create_array(rImage, pDst, dims.ndims(), dims.get(), - (af_dtype)af::dtype_traits::af_type); + af_err err = + af_create_array(rImage, pDst, dims.ndims(), dims.get(), + static_cast(af::dtype_traits::af_type)); pinnedFree(pDst); return err; } FREE_IMAGE_TYPE getFIT(FI_CHANNELS channels, af_dtype type) { if (channels == AFFI_GRAY) { - if (type == u8) - return FIT_BITMAP; - else if (type == u16) + if (type == u8) { return FIT_BITMAP; } + if (type == u16) { return FIT_UINT16; - else if (type == f32) + } else if (type == f32) { return FIT_FLOAT; + } } else if (channels == AFFI_RGB) { - if (type == u8) - return FIT_BITMAP; - else if (type == u16) + if (type == u8) { return FIT_BITMAP; } + if (type == u16) { return FIT_RGB16; - else if (type == f32) + } else if (type == f32) { return FIT_RGBF; + } } else if (channels == AFFI_RGBA) { - if (type == u8) - return FIT_BITMAP; - else if (type == u16) + if (type == u8) { return FIT_BITMAP; } + if (type == u16) { return FIT_RGBA16; - else if (type == f32) + } else if (type == f32) { return FIT_RGBAF; + } } return FIT_BITMAP; } @@ -133,13 +140,16 @@ af_err af_load_image_native(af_array* out, const char* filename) { AF_ERR_NOT_SUPPORTED); } - int flags = 0; - if (fif == FIF_JPEG) flags = flags | JPEG_ACCURATE; + unsigned flags = 0; + if (fif == FIF_JPEG) { + flags = flags | static_cast(JPEG_ACCURATE); + } // check that the plugin has reading capabilities ... bitmap_ptr pBitmap = make_bitmap_ptr(nullptr); if (_.FreeImage_FIFSupportsReading(fif)) { - pBitmap.reset(_.FreeImage_Load(fif, filename, flags)); + pBitmap.reset( + _.FreeImage_Load(fif, filename, static_cast(flags))); } if (pBitmap == NULL) { @@ -152,7 +162,7 @@ af_err af_load_image_native(af_array* out, const char* filename) { uint color_type = _.FreeImage_GetColorType(pBitmap.get()); const uint fi_bpp = _.FreeImage_GetBPP(pBitmap.get()); // int fi_color = (int)((fi_bpp / 8.0) + 0.5); //ceil - int fi_color; + uint fi_color; switch (color_type) { case 0: // FIC_MINISBLACK case 1: // FIC_MINISWHITE @@ -171,7 +181,7 @@ af_err af_load_image_native(af_array* out, const char* filename) { break; } - const int fi_bpc = fi_bpp / fi_color; + const uint fi_bpc = fi_bpp / fi_color; if (fi_bpc != 8 && fi_bpc != 16 && fi_bpc != 32) { AF_ERROR("FreeImage Error: Bits per channel not supported", AF_ERR_NOT_SUPPORTED); @@ -192,15 +202,15 @@ af_err af_load_image_native(af_array* out, const char* filename) { // result image af_array rImage; if (fi_color == 4) { // 4 channel image - if (fi_bpc == 8) + if (fi_bpc == 8) { AF_CHECK((readImage_t)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK((readImage_t)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { switch (image_type) { case FIT_UINT32: AF_CHECK((readImage_t)(&rImage, @@ -225,16 +235,17 @@ af_err af_load_image_native(af_array* out, const char* filename) { AF_ERR_NOT_SUPPORTED); break; } + } } else if (fi_color == 1) { - if (fi_bpc == 8) + if (fi_bpc == 8) { AF_CHECK((readImage_t)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK((readImage_t)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { switch (image_type) { case FIT_UINT32: AF_CHECK((readImage_t)(&rImage, @@ -259,15 +270,16 @@ af_err af_load_image_native(af_array* out, const char* filename) { AF_ERR_NOT_SUPPORTED); break; } + } } else { // 3 channel imag - if (fi_bpc == 8) + if (fi_bpc == 8) { AF_CHECK((readImage_t)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 16) + } else if (fi_bpc == 16) { AF_CHECK((readImage_t)(&rImage, pSrcLine, nSrcPitch, fi_w, fi_h)); - else if (fi_bpc == 32) + } else if (fi_bpc == 32) { switch (image_type) { case FIT_UINT32: AF_CHECK((readImage_t)(&rImage, @@ -291,6 +303,7 @@ af_err af_load_image_native(af_array* out, const char* filename) { AF_ERR_NOT_SUPPORTED); break; } + } } std::swap(*out, rImage); @@ -301,7 +314,7 @@ af_err af_load_image_native(af_array* out, const char* filename) { } template -static void save_t(T* pDstLine, const af_array in, const dim4 dims, +static void save_t(T* pDstLine, const af_array in, const dim4& dims, uint nDstPitch) { af_array rr = 0, gg = 0, bb = 0, aa = 0; AF_CHECK(channel_split(in, dims, &rr, &gg, &bb, @@ -314,20 +327,20 @@ static void save_t(T* pDstLine, const af_array in, const dim4 dims, uint indx = 0; AF_CHECK(af_transpose(&rrT, rr, false)); - if (channels >= 3) AF_CHECK(af_transpose(&ggT, gg, false)); - if (channels >= 3) AF_CHECK(af_transpose(&bbT, bb, false)); - if (channels >= 4) AF_CHECK(af_transpose(&aaT, aa, false)); + if (channels >= 3) { AF_CHECK(af_transpose(&ggT, gg, false)); } + if (channels >= 3) { AF_CHECK(af_transpose(&bbT, bb, false)); } + if (channels >= 4) { AF_CHECK(af_transpose(&aaT, aa, false)); } const ArrayInfo& cinfo = getInfo(rrT); pSrc0 = pinnedAlloc(cinfo.elements()); - if (channels >= 3) pSrc1 = pinnedAlloc(cinfo.elements()); - if (channels >= 3) pSrc2 = pinnedAlloc(cinfo.elements()); - if (channels >= 4) pSrc3 = pinnedAlloc(cinfo.elements()); + if (channels >= 3) { pSrc1 = pinnedAlloc(cinfo.elements()); } + if (channels >= 3) { pSrc2 = pinnedAlloc(cinfo.elements()); } + if (channels >= 4) { pSrc3 = pinnedAlloc(cinfo.elements()); } AF_CHECK(af_get_data_ptr((void*)pSrc0, rrT)); - if (channels >= 3) AF_CHECK(af_get_data_ptr((void*)pSrc1, ggT)); - if (channels >= 3) AF_CHECK(af_get_data_ptr((void*)pSrc2, bbT)); - if (channels >= 4) AF_CHECK(af_get_data_ptr((void*)pSrc3, aaT)); + if (channels >= 3) { AF_CHECK(af_get_data_ptr((void*)pSrc1, ggT)); } + if (channels >= 3) { AF_CHECK(af_get_data_ptr((void*)pSrc2, bbT)); } + if (channels >= 4) { AF_CHECK(af_get_data_ptr((void*)pSrc3, aaT)); } const uint fi_w = dims[1]; const uint fi_h = dims[0]; @@ -336,45 +349,48 @@ static void save_t(T* pDstLine, const af_array in, const dim4 dims, for (uint y = 0; y < fi_h; ++y) { for (uint x = 0; x < fi_w; ++x) { if (channels == 1) { - *(pDstLine + x * step) = (T)pSrc0[indx]; // r -> 0 + *(pDstLine + x * step) = pSrc0[indx]; // r -> 0 } else if (channels >= 3) { - if ((af_dtype)af::dtype_traits::af_type == u8) { + if (static_cast(af::dtype_traits::af_type) == u8) { *(pDstLine + x * step + FI_RGBA_RED) = - (T)pSrc0[indx]; // r -> 0 + pSrc0[indx]; // r -> 0 *(pDstLine + x * step + FI_RGBA_GREEN) = - (T)pSrc1[indx]; // g -> 1 + pSrc1[indx]; // g -> 1 *(pDstLine + x * step + FI_RGBA_BLUE) = - (T)pSrc2[indx]; // b -> 2 - if (channels >= 4) + pSrc2[indx]; // b -> 2 + if (channels >= 4) { *(pDstLine + x * step + FI_RGBA_ALPHA) = - (T)pSrc3[indx]; // a + pSrc3[indx]; // a + } } else { // Non 8-bit types do not use ordering // See Pixel Access Functions Chapter in FreeImage Doc - *(pDstLine + x * step + 0) = (T)pSrc0[indx]; // r -> 0 - *(pDstLine + x * step + 1) = (T)pSrc1[indx]; // g -> 1 - *(pDstLine + x * step + 2) = (T)pSrc2[indx]; // b -> 2 - if (channels >= 4) - *(pDstLine + x * step + 3) = (T)pSrc3[indx]; // a + *(pDstLine + x * step + 0) = pSrc0[indx]; // r -> 0 + *(pDstLine + x * step + 1) = pSrc1[indx]; // g -> 1 + *(pDstLine + x * step + 2) = pSrc2[indx]; // b -> 2 + if (channels >= 4) { + *(pDstLine + x * step + 3) = pSrc3[indx]; // a + } } } ++indx; } - pDstLine = (T*)(((uchar*)pDstLine) - nDstPitch); + pDstLine = reinterpret_cast(reinterpret_cast(pDstLine) - + nDstPitch); } pinnedFree(pSrc0); - if (channels >= 3) pinnedFree(pSrc1); - if (channels >= 3) pinnedFree(pSrc2); - if (channels >= 4) pinnedFree(pSrc3); - - if (rr != 0) AF_CHECK(af_release_array(rr)); - if (gg != 0) AF_CHECK(af_release_array(gg)); - if (bb != 0) AF_CHECK(af_release_array(bb)); - if (aa != 0) AF_CHECK(af_release_array(aa)); - if (rrT != 0) AF_CHECK(af_release_array(rrT)); - if (ggT != 0) AF_CHECK(af_release_array(ggT)); - if (bbT != 0) AF_CHECK(af_release_array(bbT)); - if (aaT != 0) AF_CHECK(af_release_array(aaT)); + if (channels >= 3) { pinnedFree(pSrc1); } + if (channels >= 3) { pinnedFree(pSrc2); } + if (channels >= 4) { pinnedFree(pSrc3); } + + if (rr != 0) { AF_CHECK(af_release_array(rr)); } + if (gg != 0) { AF_CHECK(af_release_array(gg)); } + if (bb != 0) { AF_CHECK(af_release_array(bb)); } + if (aa != 0) { AF_CHECK(af_release_array(aa)); } + if (rrT != 0) { AF_CHECK(af_release_array(rrT)); } + if (ggT != 0) { AF_CHECK(af_release_array(ggT)); } + if (bbT != 0) { AF_CHECK(af_release_array(bbT)); } + if (aaT != 0) { AF_CHECK(af_release_array(aaT)); } } // Save an image to disk. @@ -399,7 +415,7 @@ af_err af_save_image_native(const char* filename, const af_array in) { const ArrayInfo& info = getInfo(in); // check image color type - FI_CHANNELS channels = (FI_CHANNELS)info.dims()[2]; + auto channels = static_cast(info.dims()[2]); DIM_ASSERT(1, channels <= 4); DIM_ASSERT(1, channels != 2); @@ -426,13 +442,7 @@ af_err af_save_image_native(const char* filename, const af_array in) { bitmap_ptr pResultBitmap = make_bitmap_ptr(nullptr); switch (type) { case u8: - pResultBitmap.reset(_.FreeImage_AllocateT(fit_type, fi_w, fi_h, - fi_bpp, 0, 0, 0)); - break; case u16: - pResultBitmap.reset(_.FreeImage_AllocateT(fit_type, fi_w, fi_h, - fi_bpp, 0, 0, 0)); - break; case f32: pResultBitmap.reset(_.FreeImage_AllocateT(fit_type, fi_w, fi_h, fi_bpp, 0, 0, 0)); @@ -453,63 +463,65 @@ af_err af_save_image_native(const char* filename, const af_array in) { if (channels == AFFI_GRAY) { switch (type) { case u8: - save_t((uchar*)pDstLine, in, info.dims(), - nDstPitch); + save_t(static_cast(pDstLine), in, + info.dims(), nDstPitch); break; case u16: - save_t((ushort*)pDstLine, in, - info.dims(), nDstPitch); + save_t(static_cast(pDstLine), + in, info.dims(), nDstPitch); break; case f32: - save_t((float*)pDstLine, in, info.dims(), - nDstPitch); + save_t(static_cast(pDstLine), in, + info.dims(), nDstPitch); break; default: TYPE_ERROR(1, type); } } else if (channels == AFFI_RGB) { switch (type) { case u8: - save_t((uchar*)pDstLine, in, info.dims(), - nDstPitch); + save_t(static_cast(pDstLine), in, + info.dims(), nDstPitch); break; case u16: - save_t((ushort*)pDstLine, in, info.dims(), - nDstPitch); + save_t(static_cast(pDstLine), in, + info.dims(), nDstPitch); break; case f32: - save_t((float*)pDstLine, in, info.dims(), - nDstPitch); + save_t(static_cast(pDstLine), in, + info.dims(), nDstPitch); break; default: TYPE_ERROR(1, type); } } else { switch (type) { case u8: - save_t((uchar*)pDstLine, in, info.dims(), - nDstPitch); + save_t(static_cast(pDstLine), in, + info.dims(), nDstPitch); break; case u16: - save_t((ushort*)pDstLine, in, - info.dims(), nDstPitch); + save_t(static_cast(pDstLine), + in, info.dims(), nDstPitch); break; case f32: - save_t((float*)pDstLine, in, info.dims(), - nDstPitch); + save_t(static_cast(pDstLine), in, + info.dims(), nDstPitch); break; default: TYPE_ERROR(1, type); } } - int flags = 0; - if (fif == FIF_JPEG) flags = flags | JPEG_QUALITYSUPERB; + unsigned flags = 0; + if (fif == FIF_JPEG) { + flags = flags | static_cast(JPEG_QUALITYSUPERB); + } // now save the result image - if (!(_.FreeImage_Save(fif, pResultBitmap.get(), filename, flags) == - TRUE)) { + if (!(_.FreeImage_Save(fif, pResultBitmap.get(), filename, + static_cast(flags)) == TRUE)) { AF_ERROR("FreeImage Error: Failed to save image", AF_ERR_RUNTIME); } } - CATCHALL + CATCHALL; return AF_SUCCESS; } diff --git a/src/api/c/implicit.cpp b/src/api/c/implicit.cpp index fbb6ba3262..f30afda7eb 100644 --- a/src/api/c/implicit.cpp +++ b/src/api/c/implicit.cpp @@ -23,22 +23,22 @@ af_dtype implicit(const af_dtype lty, const af_dtype rty) { if (lty == c64 || rty == c64) { return c64; } if (lty == c32 || rty == c32) { - if (lty == f64 || rty == f64) return c64; + if (lty == f64 || rty == f64) { return c64; } return c32; } - if (lty == f64 || rty == f64) return f64; - if (lty == f32 || rty == f32) return f32; - if ((lty == f16) || (rty == f16)) return f16; - - if ((lty == u64) || (rty == u64)) return u64; - if ((lty == s64) || (rty == s64)) return s64; - if ((lty == u32) || (rty == u32)) return u32; - if ((lty == s32) || (rty == s32)) return s32; - if ((lty == u16) || (rty == u16)) return u16; - if ((lty == s16) || (rty == s16)) return s16; - if ((lty == u8) || (rty == u8)) return u8; - if ((lty == b8) && (rty == b8)) return b8; + if (lty == f64 || rty == f64) { return f64; } + if (lty == f32 || rty == f32) { return f32; } + if ((lty == f16) || (rty == f16)) { return f16; } + + if ((lty == u64) || (rty == u64)) { return u64; } + if ((lty == s64) || (rty == s64)) { return s64; } + if ((lty == u32) || (rty == u32)) { return u32; } + if ((lty == s32) || (rty == s32)) { return s32; } + if ((lty == u16) || (rty == u16)) { return u16; } + if ((lty == s16) || (rty == s16)) { return s16; } + if ((lty == u8) || (rty == u8)) { return u8; } + if ((lty == b8) && (rty == b8)) { return b8; } return f32; } diff --git a/src/api/c/implicit.hpp b/src/api/c/implicit.hpp index d0bb51d62e..704e90a4f5 100644 --- a/src/api/c/implicit.hpp +++ b/src/api/c/implicit.hpp @@ -17,7 +17,5 @@ #include #include -using namespace detail; - af_dtype implicit(const af_array lhs, const af_array rhs); af_dtype implicit(const af_dtype lty, const af_dtype rty); diff --git a/src/api/c/index.cpp b/src/api/c/index.cpp index 3ecdb64874..fcaca34f06 100644 --- a/src/api/c/index.cpp +++ b/src/api/c/index.cpp @@ -58,13 +58,14 @@ af_seq convert2Canonical(const af_seq s, const dim_t len) { template static af_array indexBySeqs(const af_array& src, const vector indicesV) { - size_t ndims = indicesV.size(); - auto input = getArray(src); + size_t ndims = indicesV.size(); + const auto& input = getArray(src); - if (ndims == 1 && ndims != input.ndims()) + if (ndims == 1 && ndims != input.ndims()) { return getHandle(createSubArray(::flat(input), indicesV)); - else + } else { return getHandle(createSubArray(input, indicesV)); + } } af_err af_index(af_array* result, const af_array in, const unsigned ndims, @@ -203,7 +204,7 @@ af_err af_index_gen(af_array* out, const af_array in, const dim_t ndims, return AF_SUCCESS; } - if (ndims == 1 && ndims != (dim_t)iInfo.ndims()) { + if (ndims == 1 && ndims != static_cast(iInfo.ndims())) { af_array in_ = 0; AF_CHECK(af_flat(&in_, in)); AF_CHECK(af_index_gen(out, in_, ndims, indexs)); @@ -212,7 +213,7 @@ af_err af_index_gen(af_array* out, const af_array in, const dim_t ndims, } int track = 0; - std::array seqs; + std::array seqs{}; seqs.fill(af_span); for (dim_t i = 0; i < ndims; i++) { if (indexs[i].isSeq) { @@ -221,9 +222,11 @@ af_err af_index_gen(af_array* out, const af_array in, const dim_t ndims, } } - if (track == (int)ndims) return af_index(out, in, ndims, seqs.data()); + if (track == static_cast(ndims)) { + return af_index(out, in, ndims, seqs.data()); + } - std::array idxrs; + std::array idxrs{}; for (dim_t i = 0; i < AF_MAX_DIMS; ++i) { if (i < ndims) { @@ -289,7 +292,7 @@ af_seq af_make_seq(double begin, double end, double step) { af_err af_create_indexers(af_index_t** indexers) { try { - af_index_t* out = new af_index_t[AF_MAX_DIMS]; + auto* out = new af_index_t[AF_MAX_DIMS]; for (int i = 0; i < AF_MAX_DIMS; ++i) { out[i].idx.seq = af_span; out[i].isSeq = true; diff --git a/src/api/c/internal.cpp b/src/api/c/internal.cpp index 82ab7f7a8b..219942cc1e 100644 --- a/src/api/c/internal.cpp +++ b/src/api/c/internal.cpp @@ -42,12 +42,14 @@ af_err af_create_strided_array(af_array *arr, const void *data, ARG_ASSERT(5, strides_ != NULL); ARG_ASSERT(5, strides_[0] == 1); - for (int i = 1; i < (int)ndims; i++) { ARG_ASSERT(5, strides_[i] > 0); } + for (int i = 1; i < static_cast(ndims); i++) { + ARG_ASSERT(5, strides_[i] > 0); + } dim4 dims(ndims, dims_); dim4 strides(ndims, strides_); - for (int i = ndims; i < 4; i++) { + for (int i = static_cast(ndims); i < 4; i++) { strides[i] = strides[i - 1] * dims[i - 1]; } @@ -56,58 +58,72 @@ af_err af_create_strided_array(af_array *arr, const void *data, af_array res; AF_CHECK(af_init()); + void *in_data = const_cast( + data); // const cast because the api cannot change switch (ty) { case f32: res = getHandle(createStridedArray( - dims, strides, offset, (float *)data, isdev)); + dims, strides, offset, static_cast(in_data), + isdev)); break; case f64: res = getHandle(createStridedArray( - dims, strides, offset, (double *)data, isdev)); + dims, strides, offset, static_cast(in_data), + isdev)); break; case c32: res = getHandle(createStridedArray( - dims, strides, offset, (cfloat *)data, isdev)); + dims, strides, offset, static_cast(in_data), + isdev)); break; case c64: res = getHandle(createStridedArray( - dims, strides, offset, (cdouble *)data, isdev)); + dims, strides, offset, static_cast(in_data), + isdev)); break; case u32: - res = getHandle(createStridedArray(dims, strides, offset, - (uint *)data, isdev)); + res = getHandle(createStridedArray( + dims, strides, offset, static_cast(in_data), + isdev)); break; case s32: - res = getHandle(createStridedArray(dims, strides, offset, - (int *)data, isdev)); + res = getHandle(createStridedArray( + dims, strides, offset, static_cast(in_data), isdev)); break; case u64: res = getHandle(createStridedArray( - dims, strides, offset, (uintl *)data, isdev)); + dims, strides, offset, static_cast(in_data), + isdev)); break; case s64: - res = getHandle(createStridedArray(dims, strides, offset, - (intl *)data, isdev)); + res = getHandle(createStridedArray( + dims, strides, offset, static_cast(in_data), + isdev)); break; case u16: res = getHandle(createStridedArray( - dims, strides, offset, (ushort *)data, isdev)); + dims, strides, offset, static_cast(in_data), + isdev)); break; case s16: res = getHandle(createStridedArray( - dims, strides, offset, (short *)data, isdev)); + dims, strides, offset, static_cast(in_data), + isdev)); break; case b8: - res = getHandle(createStridedArray(dims, strides, offset, - (char *)data, isdev)); + res = getHandle(createStridedArray( + dims, strides, offset, static_cast(in_data), + isdev)); break; case u8: res = getHandle(createStridedArray( - dims, strides, offset, (uchar *)data, isdev)); + dims, strides, offset, static_cast(in_data), + isdev)); break; case f16: - res = getHandle(createStridedArray(dims, strides, offset, - (half *)data, isdev)); + res = getHandle(createStridedArray( + dims, strides, offset, static_cast(in_data), + isdev)); break; default: TYPE_ERROR(6, ty); } @@ -147,19 +163,19 @@ af_err af_get_raw_ptr(void **ptr, const af_array arr) { af_dtype ty = getInfo(arr).getType(); switch (ty) { - case f32: res = (void *)getRawPtr(getArray(arr)); break; - case f64: res = (void *)getRawPtr(getArray(arr)); break; - case c32: res = (void *)getRawPtr(getArray(arr)); break; - case c64: res = (void *)getRawPtr(getArray(arr)); break; - case u32: res = (void *)getRawPtr(getArray(arr)); break; - case s32: res = (void *)getRawPtr(getArray(arr)); break; - case u64: res = (void *)getRawPtr(getArray(arr)); break; - case s64: res = (void *)getRawPtr(getArray(arr)); break; - case u16: res = (void *)getRawPtr(getArray(arr)); break; - case s16: res = (void *)getRawPtr(getArray(arr)); break; - case b8: res = (void *)getRawPtr(getArray(arr)); break; - case u8: res = (void *)getRawPtr(getArray(arr)); break; - case f16: res = (void *)getRawPtr(getArray(arr)); break; + case f32: res = getRawPtr(getArray(arr)); break; + case f64: res = getRawPtr(getArray(arr)); break; + case c32: res = getRawPtr(getArray(arr)); break; + case c64: res = getRawPtr(getArray(arr)); break; + case u32: res = getRawPtr(getArray(arr)); break; + case s32: res = getRawPtr(getArray(arr)); break; + case u64: res = getRawPtr(getArray(arr)); break; + case s64: res = getRawPtr(getArray(arr)); break; + case u16: res = getRawPtr(getArray(arr)); break; + case s16: res = getRawPtr(getArray(arr)); break; + case b8: res = getRawPtr(getArray(arr)); break; + case u8: res = getRawPtr(getArray(arr)); break; + case f16: res = getRawPtr(getArray(arr)); break; default: TYPE_ERROR(6, ty); } @@ -184,19 +200,19 @@ af_err af_is_owner(bool *result, const af_array arr) { af_dtype ty = getInfo(arr).getType(); switch (ty) { - case f32: res = (void *)getArray(arr).isOwner(); break; - case f64: res = (void *)getArray(arr).isOwner(); break; - case c32: res = (void *)getArray(arr).isOwner(); break; - case c64: res = (void *)getArray(arr).isOwner(); break; - case u32: res = (void *)getArray(arr).isOwner(); break; - case s32: res = (void *)getArray(arr).isOwner(); break; - case u64: res = (void *)getArray(arr).isOwner(); break; - case s64: res = (void *)getArray(arr).isOwner(); break; - case u16: res = (void *)getArray(arr).isOwner(); break; - case s16: res = (void *)getArray(arr).isOwner(); break; - case b8: res = (void *)getArray(arr).isOwner(); break; - case u8: res = (void *)getArray(arr).isOwner(); break; - case f16: res = (void *)getArray(arr).isOwner(); break; + case f32: res = getArray(arr).isOwner(); break; + case f64: res = getArray(arr).isOwner(); break; + case c32: res = getArray(arr).isOwner(); break; + case c64: res = getArray(arr).isOwner(); break; + case u32: res = getArray(arr).isOwner(); break; + case s32: res = getArray(arr).isOwner(); break; + case u64: res = getArray(arr).isOwner(); break; + case s64: res = getArray(arr).isOwner(); break; + case u16: res = getArray(arr).isOwner(); break; + case s16: res = getArray(arr).isOwner(); break; + case b8: res = getArray(arr).isOwner(); break; + case u8: res = getArray(arr).isOwner(); break; + case f16: res = getArray(arr).isOwner(); break; default: TYPE_ERROR(6, ty); } diff --git a/src/api/c/inverse.cpp b/src/api/c/inverse.cpp index 1eee6eeb12..fe6625d5c1 100644 --- a/src/api/c/inverse.cpp +++ b/src/api/c/inverse.cpp @@ -16,7 +16,6 @@ #include #include -using af::dim4; using namespace detail; template diff --git a/src/api/c/join.cpp b/src/api/c/join.cpp index 34d6f7a12d..3fdfeb7036 100644 --- a/src/api/c/join.cpp +++ b/src/api/c/join.cpp @@ -33,7 +33,7 @@ static inline af_array join_many(const int dim, const unsigned n_arrays, std::vector> inputs_; inputs_.reserve(n_arrays); - for (int i = 0; i < (int)n_arrays; i++) { + for (unsigned i = 0; i < n_arrays; i++) { inputs_.push_back(getArray(inputs[i])); } return getHandle(join(dim, inputs_)); @@ -59,7 +59,7 @@ af_err af_join(af_array *out, const int dim, const af_array first, // All dimensions except join dimension must be equal // Compute output dims for (int i = 0; i < 4; i++) { - if (i != dim) DIM_ASSERT(2, fdims[i] == sdims[i]); + if (i != dim) { DIM_ASSERT(2, fdims[i] == sdims[i]); } } af_array output; @@ -97,14 +97,14 @@ af_err af_join_many(af_array *out, const int dim, const unsigned n_arrays, std::vector info; info.reserve(n_arrays); std::vector dims(n_arrays); - for (int i = 0; i < (int)n_arrays; i++) { + for (unsigned i = 0; i < n_arrays; i++) { info.push_back(getInfo(inputs[i])); dims[i] = info[i].dims(); } ARG_ASSERT(1, dim >= 0 && dim < 4); - for (int i = 1; i < (int)n_arrays; i++) { + for (unsigned i = 1; i < n_arrays; i++) { ARG_ASSERT(3, info[0].getType() == info[i].getType()); DIM_ASSERT(3, info[i].elements() > 0); } @@ -113,7 +113,7 @@ af_err af_join_many(af_array *out, const int dim, const unsigned n_arrays, // Compute output dims for (int i = 0; i < 4; i++) { if (i != dim) { - for (int j = 1; j < (int)n_arrays; j++) { + for (unsigned j = 1; j < n_arrays; j++) { DIM_ASSERT(3, dims[0][i] == dims[j][i]); } } diff --git a/src/api/c/match_template.cpp b/src/api/c/match_template.cpp index e5fbef6f4a..7e984b0c86 100644 --- a/src/api/c/match_template.cpp +++ b/src/api/c/match_template.cpp @@ -15,7 +15,11 @@ #include using af::dim4; -using namespace detail; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; template static af_array match_template(const af_array& sImg, const af_array tImg, @@ -63,8 +67,8 @@ af_err af_match_template(af_array* out, const af_array search_img, const ArrayInfo& sInfo = getInfo(search_img); const ArrayInfo& tInfo = getInfo(template_img); - dim4 const sDims = sInfo.dims(); - dim4 const tDims = tInfo.dims(); + dim4 const& sDims = sInfo.dims(); + dim4 const& tDims = tInfo.dims(); dim_t sNumDims = sDims.ndims(); dim_t tNumDims = tDims.ndims(); diff --git a/src/api/c/mean.cpp b/src/api/c/mean.cpp index 04a8523bf6..9cef0f8cb1 100644 --- a/src/api/c/mean.cpp +++ b/src/api/c/mean.cpp @@ -23,31 +23,33 @@ #include "stats.h" using common::half; - -using namespace detail; +using detail::Array; +using detail::cdouble; +using detail::cfloat; +using detail::mean; template static To mean(const af_array &in) { - typedef typename baseOutType::type Tw; + using Tw = typename baseOutType::type; return mean(getArray(in)); } template static T mean(const af_array &in, const af_array &weights) { - typedef typename baseOutType::type Tw; + using Tw = typename baseOutType::type; return mean(castArray(in), castArray(weights)); } template static af_array mean(const af_array &in, const dim_t dim) { - typedef typename baseOutType::type Tw; + using Tw = typename baseOutType::type; return getHandle(mean(getArray(in), dim)); } template static af_array mean(const af_array &in, const af_array &weights, const dim_t dim) { - typedef typename baseOutType::type Tw; + using Tw = typename baseOutType::type; return getHandle( mean(castArray(in), castArray(weights), dim)); } @@ -113,16 +115,16 @@ af_err af_mean_weighted(af_array *out, const af_array in, } switch (iType) { - case f64: output = mean(in, w, dim); break; - case f32: output = mean(in, w, dim); break; - case s32: output = mean(in, w, dim); break; - case u32: output = mean(in, w, dim); break; - case s64: output = mean(in, w, dim); break; - case u64: output = mean(in, w, dim); break; - case s16: output = mean(in, w, dim); break; - case u16: output = mean(in, w, dim); break; - case u8: output = mean(in, w, dim); break; + case f32: + case s32: + case u32: + case s16: + case u16: + case u8: case b8: output = mean(in, w, dim); break; + case f64: + case s64: + case u64: output = mean(in, w, dim); break; case c32: output = mean(in, w, dim); break; case c64: output = mean(in, w, dim); break; case f16: output = mean(in, w, dim); break; @@ -184,17 +186,17 @@ af_err af_mean_all_weighted(double *realVal, double *imagVal, const af_array in, f64)); /* verify that weights are non-complex real numbers */ switch (iType) { - case f64: *realVal = mean(in, weights); break; - case f32: *realVal = mean(in, weights); break; - case s32: *realVal = mean(in, weights); break; - case u32: *realVal = mean(in, weights); break; - case s64: *realVal = mean(in, weights); break; - case u64: *realVal = mean(in, weights); break; - case s16: *realVal = mean(in, weights); break; - case u16: *realVal = mean(in, weights); break; - case u8: *realVal = mean(in, weights); break; - case b8: *realVal = mean(in, weights); break; + case f32: + case s32: + case u32: + case s16: + case u16: + case u8: + case b8: case f16: *realVal = mean(in, weights); break; + case f64: + case s64: + case u64: *realVal = mean(in, weights); break; case c32: { cfloat tmp = mean(in, weights); *realVal = real(tmp); diff --git a/src/api/c/meanshift.cpp b/src/api/c/meanshift.cpp index a6725f96d6..d69f11033d 100644 --- a/src/api/c/meanshift.cpp +++ b/src/api/c/meanshift.cpp @@ -39,7 +39,7 @@ af_err af_mean_shift(af_array *out, const af_array in, af::dim4 dims = info.dims(); DIM_ASSERT(1, (dims.ndims() >= 2)); - if (is_color) DIM_ASSERT(1, (dims[2] == 3)); + if (is_color) { DIM_ASSERT(1, (dims[2] == 3)); } af_array output; switch (type) { diff --git a/src/api/c/median.cpp b/src/api/c/median.cpp index fee958f06a..07652b121c 100644 --- a/src/api/c/median.cpp +++ b/src/api/c/median.cpp @@ -20,8 +20,13 @@ #include #include -using namespace detail; using af::dim4; +using detail::Array; +using detail::division; +using detail::uchar; +using detail::uint; +using detail::ushort; +using std::sort; template static double median(const af_array& in) { @@ -38,7 +43,8 @@ static double median(const af_array& in) { T result; AF_CHECK(af_get_data_ptr((void*)&result, in)); return result; - } else if (nElems == 2) { + } + if (nElems == 2) { T result[2]; AF_CHECK(af_get_data_ptr((void*)&result, in)); return division( @@ -96,6 +102,7 @@ static af_array median(const af_array& in, const dim_t dim) { af_array sortedIn_handle = getHandle(sortedIn); AF_CHECK(af_index(&left, sortedIn_handle, input.ndims(), slices)); + af_array out = nullptr; if (dimLength % 2 == 1) { // mid-1 is our guy if (input.isFloating()) { @@ -119,7 +126,6 @@ static af_array median(const af_array& in, const dim_t dim) { af_array sumarr = 0; af_array carr = 0; - af_array result = 0; dim4 cdims = dims; cdims[dim] = 1; @@ -137,18 +143,19 @@ static af_array median(const af_array& in, const dim_t dim) { } AF_CHECK(af_add(&sumarr, left, right, false)); - AF_CHECK(af_mul(&result, sumarr, carr, false)); + AF_CHECK(af_mul(&out, sumarr, carr, false)); AF_CHECK(af_release_array(left)); AF_CHECK(af_release_array(right)); AF_CHECK(af_release_array(sumarr)); AF_CHECK(af_release_array(carr)); AF_CHECK(af_release_array(sortedIn_handle)); - return result; } + return out; } -af_err af_median_all(double* realVal, double* imagVal, const af_array in) { +af_err af_median_all(double* realVal, double* imagVal, // NOLINT + const af_array in) { UNUSED(imagVal); try { const ArrayInfo& info = getInfo(in); diff --git a/src/api/c/memory.cpp b/src/api/c/memory.cpp index 1bffe37a05..818c2a96ae 100644 --- a/src/api/c/memory.cpp +++ b/src/api/c/memory.cpp @@ -25,10 +25,30 @@ #include -using namespace detail; - +using af::dim4; using common::half; +using detail::cdouble; +using detail::cfloat; +using detail::createDeviceDataArray; +using detail::deviceMemoryInfo; +using detail::getActiveDeviceId; +using detail::getDeviceCount; +using detail::intl; +using detail::isLocked; +using detail::memAllocUser; +using detail::memFreeUser; +using detail::memLock; +using detail::memUnlock; +using detail::pinnedAlloc; +using detail::pinnedFree; +using detail::printMemInfo; +using detail::signalMemoryCleanup; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; using std::move; +using std::swap; af_err af_device_array(af_array *arr, void *data, const unsigned ndims, const dim_t *const dims, const af_dtype type) { @@ -87,7 +107,7 @@ af_err af_device_array(af_array *arr, void *data, const unsigned ndims, default: TYPE_ERROR(4, type); } - std::swap(*arr, res); + swap(*arr, res); } CATCHALL; @@ -127,7 +147,7 @@ inline void lockArray(const af_array arr) { // Ideally we need to use .get(false), i.e. get ptr without offset // This is however not supported in opencl // Use getData().get() as alternative - memLock((void *)getArray(arr).getData().get()); + memLock(static_cast(getArray(arr).getData().get())); } af_err af_lock_device_ptr(const af_array arr) { return af_lock_array(arr); } @@ -163,7 +183,7 @@ inline bool checkUserLock(const af_array arr) { // Ideally we need to use .get(false), i.e. get ptr without offset // This is however not supported in opencl // Use getData().get() as alternative - return isLocked((void *)getArray(arr).getData().get()); + return isLocked(static_cast(getArray(arr).getData().get())); } af_err af_is_locked_array(bool *res, const af_array arr) { @@ -197,7 +217,7 @@ inline void unlockArray(const af_array arr) { // Ideally we need to use .get(false), i.e. get ptr without offset // This is however not supported in opencl // Use getData().get() as alternative - memUnlock((void *)getArray(arr).getData().get()); + memUnlock(static_cast(getArray(arr).getData().get())); } af_err af_unlock_device_ptr(const af_array arr) { return af_unlock_array(arr); } @@ -240,7 +260,7 @@ af_err af_alloc_device(void **ptr, const dim_t bytes) { af_err af_alloc_pinned(void **ptr, const dim_t bytes) { try { AF_CHECK(af_init()); - *ptr = (void *)pinnedAlloc(bytes); + *ptr = static_cast(pinnedAlloc(bytes)); } CATCHALL; return AF_SUCCESS; @@ -256,19 +276,21 @@ af_err af_free_device(void *ptr) { af_err af_free_pinned(void *ptr) { try { - pinnedFree((char *)ptr); + pinnedFree(static_cast(ptr)); } CATCHALL; return AF_SUCCESS; } af_err af_alloc_host(void **ptr, const dim_t bytes) { - if ((*ptr = malloc(bytes))) { return AF_SUCCESS; } + if ((*ptr = malloc(bytes))) { // NOLINT(hicpp-no-malloc) + return AF_SUCCESS; + } return AF_ERR_NO_MEM; } af_err af_free_host(void *ptr) { - free(ptr); + free(ptr); // NOLINT(hicpp-no-malloc) return AF_SUCCESS; } @@ -277,8 +299,9 @@ af_err af_print_mem_info(const char *msg, const int device_id) { int device = device_id; if (device == -1) { device = getActiveDeviceId(); } - if (msg != NULL) + if (msg != nullptr) { ARG_ASSERT(0, strlen(msg) < 256); // 256 character limit on msg + } ARG_ASSERT(1, device >= 0 && device < getDeviceCount()); printMemInfo(msg ? msg : "", device); @@ -325,21 +348,20 @@ af_err af_get_mem_step_size(size_t *step_bytes) { //////////////////////////////////////////////////////////////////////////////// MemoryManager &getMemoryManager(const af_memory_manager handle) { - return *(MemoryManager *)handle; + return *static_cast(handle); } af_memory_manager getHandle(MemoryManager &manager) { MemoryManager *handle; handle = &manager; - return (af_memory_manager)handle; + return static_cast(handle); } af_err af_create_memory_manager(af_memory_manager *manager) { try { AF_CHECK(af_init()); std::unique_ptr m(new MemoryManager()); - *manager = getHandle(*m); - m.release(); + *manager = getHandle(*m.release()); } CATCHALL; @@ -351,7 +373,7 @@ af_err af_release_memory_manager(af_memory_manager handle) { // NB: does NOT reset the internal memory manager to be the default: // af_unset_memory_manager_pinned must be used to fully-reset with a new // AF default memory manager - delete (MemoryManager *)handle; + delete static_cast(handle); } CATCHALL; @@ -721,13 +743,13 @@ bool MemoryManagerFunctionWrapper::isUserLocked(const void *ptr) { int out; AF_CHECK(getMemoryManager(handle_).is_user_locked_fn( handle_, &out, const_cast(ptr))); - return (bool)out; + return static_cast(out); } -void MemoryManagerFunctionWrapper::usageInfo(size_t *alloc_bytes, - size_t *alloc_buffers, - size_t *lock_bytes, - size_t *lock_buffers) { +void MemoryManagerFunctionWrapper::usageInfo(size_t * /*alloc_bytes*/, + size_t * /*alloc_buffers*/, + size_t * /*lock_bytes*/, + size_t * /*lock_buffers*/) { // Not implemented in the public memory manager API, but for backward // compatibility reasons, needs to be in the common memory manager interface // so that it can be used with the default memory manager. Called from @@ -748,7 +770,7 @@ bool MemoryManagerFunctionWrapper::jitTreeExceedsMemoryPressure(size_t bytes) { int out; AF_CHECK(getMemoryManager(handle_).jit_tree_exceeds_memory_pressure_fn( handle_, &out, bytes)); - return (bool)out; + return static_cast(out); } size_t MemoryManagerFunctionWrapper::getMemStepSize() { @@ -764,6 +786,7 @@ void MemoryManagerFunctionWrapper::setMemStepSize(size_t new_step_size) { // Not implemented in the public memory manager API, but for backward // compatibility reasons, needs to be in the common memory manager interface // so that it can be used with the default memory manager. + UNUSED(new_step_size); AF_ERROR("Memory step size API not implemented for custom memory manager ", AF_ERR_NOT_SUPPORTED); } diff --git a/src/api/c/memoryapi.hpp b/src/api/c/memoryapi.hpp index ab942e721d..945b0fb287 100644 --- a/src/api/c/memoryapi.hpp +++ b/src/api/c/memoryapi.hpp @@ -76,6 +76,6 @@ struct MemoryManager { MemoryManagerFunctionWrapper *wrapper; }; -MemoryManager &getMemoryManager(const af_memory_manager manager); +MemoryManager &getMemoryManager(const af_memory_manager handle); af_memory_manager getHandle(MemoryManager &manager); diff --git a/src/api/c/moddims.cpp b/src/api/c/moddims.cpp index d368fc2e5b..07471692ca 100644 --- a/src/api/c/moddims.cpp +++ b/src/api/c/moddims.cpp @@ -18,7 +18,13 @@ using af::dim4; using common::half; -using namespace detail; +using detail::cdouble; +using detail::cfloat; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; namespace { template diff --git a/src/api/c/moments.cpp b/src/api/c/moments.cpp index 379dd90edd..2584cf1123 100644 --- a/src/api/c/moments.cpp +++ b/src/api/c/moments.cpp @@ -62,7 +62,7 @@ af_err af_moments(af_array* out, const af_array in, template static inline void moment_copy(double* out, const af_array moments) { - auto info = getInfo(moments); + const auto& info = getInfo(moments); vector h_moments(info.elements()); copyData(h_moments.data(), moments); diff --git a/src/api/c/morph.cpp b/src/api/c/morph.cpp index bec787d978..f318ed6486 100644 --- a/src/api/c/morph.cpp +++ b/src/api/c/morph.cpp @@ -16,11 +16,17 @@ #include using af::dim4; -using namespace detail; +using detail::Array; +using detail::cdouble; +using detail::cfloat; +using detail::createEmptyArray; +using detail::uchar; +using detail::uint; +using detail::ushort; template static inline af_array morph(const af_array &in, const af_array &mask) { - const Array &input = getArray(in); + const Array input = getArray(in); const Array &filter = castArray(mask); Array out = morph(input, filter); return getHandle(out); @@ -28,7 +34,7 @@ static inline af_array morph(const af_array &in, const af_array &mask) { template static inline af_array morph3d(const af_array &in, const af_array &mask) { - const Array &input = getArray(in); + const Array input = getArray(in); const Array &filter = castArray(mask); Array out = morph3d(input, filter); return getHandle(out); diff --git a/src/api/c/nearest_neighbour.cpp b/src/api/c/nearest_neighbour.cpp index 6c88b1357e..abc2a7b65b 100644 --- a/src/api/c/nearest_neighbour.cpp +++ b/src/api/c/nearest_neighbour.cpp @@ -16,7 +16,15 @@ #include using af::dim4; -using namespace detail; +using detail::Array; +using detail::cdouble; +using detail::cfloat; +using detail::createEmptyArray; +using detail::intl; +using detail::uchar; +using detail::uint; +using detail::uintl; +using detail::ushort; template static void nearest_neighbour(af_array* idx, af_array* dist, diff --git a/src/api/c/norm.cpp b/src/api/c/norm.cpp index 42eccd23b6..06ea1b3a66 100644 --- a/src/api/c/norm.cpp +++ b/src/api/c/norm.cpp @@ -30,7 +30,8 @@ double matrixNorm(const Array &A, double p) { if (p == 1) { Array colSum = reduce(A, 0); return reduce_all(colSum); - } else if (p == af::Inf) { + } + if (p == af::Inf) { Array rowSum = reduce(A, 1); return reduce_all(rowSum); } @@ -41,9 +42,8 @@ double matrixNorm(const Array &A, double p) { template double vectorNorm(const Array &A, double p) { - if (p == 1) { - return reduce_all(A); - } else if (p == af::Inf) { + if (p == 1) { return reduce_all(A); } + if (p == af::Inf) { return reduce_all(A); } else if (p == 2) { Array A_sq = arithOp(A, A, A.dims()); @@ -81,7 +81,7 @@ double LPQNorm(const Array &A, double p, double q) { template double norm(const af_array a, const af_norm_type type, const double p, const double q) { - typedef typename af::dtype_traits::base_type BT; + using BT = typename af::dtype_traits::base_type; const Array A = abs(getArray(a)); diff --git a/src/api/c/pinverse.cpp b/src/api/c/pinverse.cpp index 6361d809f9..2c6ea88f0a 100644 --- a/src/api/c/pinverse.cpp +++ b/src/api/c/pinverse.cpp @@ -59,7 +59,7 @@ Array pinverseSvd(const Array &in, const double tol) { dim_t Q = in.dims()[3]; // Compute SVD - typedef typename dtype_traits::base_type Tr; + using Tr = typename dtype_traits::base_type; // Ideally, these initializations should use createEmptyArray(), but for // some reason, linux-opencl-k80 will produce wrong results for large arrays Array u = createValueArray(dim4(M, M, P, Q), scalar(0)); diff --git a/src/api/c/plot.cpp b/src/api/c/plot.cpp index 6d30820338..ddff3aa2bc 100644 --- a/src/api/c/plot.cpp +++ b/src/api/c/plot.cpp @@ -51,10 +51,11 @@ fg_chart setup_plot(fg_window window, const af_array in_, fg_chart chart = NULL; fg_chart_type ctype = order == 2 ? FG_CHART_2D : FG_CHART_3D; - if (props->col > -1 && props->row > -1) + if (props->col > -1 && props->row > -1) { chart = fgMngr.getChart(window, props->row, props->col, ctype); - else + } else { chart = fgMngr.getChart(window, 0, 0, ctype); + } fg_plot plot = fgMngr.getPlot(chart, tdims[1], getGLType(), ptype, mtype); @@ -79,16 +80,16 @@ fg_chart setup_plot(fg_window window, const af_array in_, cmax[0] = step_round(dmax[0], true); cmin[1] = step_round(dmin[1], false); cmax[1] = step_round(dmax[1], true); - if (order == 3) cmin[2] = step_round(dmin[2], false); - if (order == 3) cmax[2] = step_round(dmax[2], true); + if (order == 3) { cmin[2] = step_round(dmin[2], false); } + if (order == 3) { cmax[2] = step_round(dmax[2], true); } } else { - if (cmin[0] > dmin[0]) cmin[0] = step_round(dmin[0], false); - if (cmax[0] < dmax[0]) cmax[0] = step_round(dmax[0], true); - if (cmin[1] > dmin[1]) cmin[1] = step_round(dmin[1], false); - if (cmax[1] < dmax[1]) cmax[1] = step_round(dmax[1], true); + if (cmin[0] > dmin[0]) { cmin[0] = step_round(dmin[0], false); } + if (cmax[0] < dmax[0]) { cmax[0] = step_round(dmax[0], true); } + if (cmin[1] > dmin[1]) { cmin[1] = step_round(dmin[1], false); } + if (cmax[1] < dmax[1]) { cmax[1] = step_round(dmax[1], true); } if (order == 3) { - if (cmin[2] > dmin[2]) cmin[2] = step_round(dmin[2], false); - if (cmax[2] < dmax[2]) cmax[2] = step_round(dmax[2], true); + if (cmin[2] > dmin[2]) { cmin[2] = step_round(dmin[2], false); } + if (cmax[2] < dmax[2]) { cmax[2] = step_round(dmax[2], true); } } } FG_CHECK(_.fg_set_chart_axes_limits(chart, cmin[0], cmax[0], cmin[1], @@ -103,10 +104,12 @@ template fg_chart setup_plot(fg_window window, const af_array in_, const int order, const af_cell* const props, fg_plot_type ptype, fg_marker_type mtype) { - if (order == 2) + if (order == 2) { return setup_plot(window, in_, props, ptype, mtype); - else if (order == 3) + } + if (order == 3) { return setup_plot(window, in_, props, ptype, mtype); + } // Dummy to avoid warnings return NULL; } @@ -181,15 +184,15 @@ af_err plotWrapper(const af_window window, const af_array X, const af_array Y, if (window == 0) { AF_ERROR("Not a valid window", AF_ERR_INTERNAL); } const ArrayInfo& xInfo = getInfo(X); - af::dim4 xDims = xInfo.dims(); + const af::dim4& xDims = xInfo.dims(); af_dtype xType = xInfo.getType(); const ArrayInfo& yInfo = getInfo(Y); - af::dim4 yDims = yInfo.dims(); + const af::dim4& yDims = yInfo.dims(); af_dtype yType = yInfo.getType(); const ArrayInfo& zInfo = getInfo(Z); - af::dim4 zDims = zInfo.dims(); + const af::dim4& zDims = zInfo.dims(); af_dtype zType = zInfo.getType(); DIM_ASSERT(0, xDims == yDims); @@ -255,11 +258,11 @@ af_err plotWrapper(const af_window window, const af_array X, const af_array Y, if (window == 0) { AF_ERROR("Not a valid window", AF_ERR_INTERNAL); } const ArrayInfo& xInfo = getInfo(X); - af::dim4 xDims = xInfo.dims(); + const af::dim4& xDims = xInfo.dims(); af_dtype xType = xInfo.getType(); const ArrayInfo& yInfo = getInfo(Y); - af::dim4 yDims = yInfo.dims(); + const af::dim4& yDims = yInfo.dims(); af_dtype yType = yInfo.getType(); DIM_ASSERT(0, xDims == yDims); @@ -344,7 +347,8 @@ af_err af_draw_plot3(const af_window wind, const af_array P, if (dims.ndims() == 2 && dims[1] == 3) { return plotWrapper(wind, P, 1, props); - } else if (dims.ndims() == 2 && dims[0] == 3) { + } + if (dims.ndims() == 2 && dims[0] == 3) { return plotWrapper(wind, P, 0, props); } else if (dims.ndims() == 1 && dims[0] % 3 == 0) { dim4 rdims(dims.elements() / 3, 3, 1, 1); @@ -405,7 +409,8 @@ af_err af_draw_scatter3(const af_window wind, const af_array P, if (dims.ndims() == 2 && dims[1] == 3) { return plotWrapper(wind, P, 1, props, FG_PLOT_SCATTER, fg_marker); - } else if (dims.ndims() == 2 && dims[0] == 3) { + } + if (dims.ndims() == 2 && dims[0] == 3) { return plotWrapper(wind, P, 0, props, FG_PLOT_SCATTER, fg_marker); } else if (dims.ndims() == 1 && dims[0] % 3 == 0) { dim4 rdims(dims.elements() / 3, 3, 1, 1); diff --git a/src/api/c/print.cpp b/src/api/c/print.cpp index 8b9ddb4007..4a533b77c0 100644 --- a/src/api/c/print.cpp +++ b/src/api/c/print.cpp @@ -273,7 +273,8 @@ af_err af_array_to_string(char **output, const char *exp, const af_array arr, } } std::string str = ss.str(); - af_alloc_host((void **)output, sizeof(char) * (str.size() + 1)); + af_alloc_host(reinterpret_cast(output), + sizeof(char) * (str.size() + 1)); str.copy(*output, str.size()); (*output)[str.size()] = '\0'; // don't forget the terminating 0 } diff --git a/src/api/c/random.cpp b/src/api/c/random.cpp index 49a7eb13db..744588680f 100644 --- a/src/api/c/random.cpp +++ b/src/api/c/random.cpp @@ -30,33 +30,33 @@ using af::dim4; Array emptyArray() { return createEmptyArray(af::dim4(0)); } struct RandomEngine { - af_random_engine_type type; - std::shared_ptr seed; - std::shared_ptr counter; - Array pos; - Array sh1; - Array sh2; - uint mask; - Array recursion_table; - Array temper_table; - Array state; - - RandomEngine(void) - : type(AF_RANDOM_ENGINE_DEFAULT) - , seed(new uintl()) + // clang-format off + af_random_engine_type type{AF_RANDOM_ENGINE_DEFAULT}; // NOLINT(misc-non-private-member-variables-in-classes) + std::shared_ptr seed; // NOLINT(misc-non-private-member-variables-in-classes) + std::shared_ptr counter; // NOLINT(misc-non-private-member-variables-in-classes) + Array pos; // NOLINT(misc-non-private-member-variables-in-classes) + Array sh1; // NOLINT(misc-non-private-member-variables-in-classes) + Array sh2; // NOLINT(misc-non-private-member-variables-in-classes) + uint mask{0}; // NOLINT(misc-non-private-member-variables-in-classes) + Array recursion_table; // NOLINT(misc-non-private-member-variables-in-classes) + Array temper_table; // NOLINT(misc-non-private-member-variables-in-classes) + Array state; // NOLINT(misc-non-private-member-variables-in-classes) + // clang-format on + + RandomEngine() + : seed(new uintl()) , counter(new uintl()) , pos(emptyArray()) , sh1(emptyArray()) , sh2(emptyArray()) - , mask(0) , recursion_table(emptyArray()) , temper_table(emptyArray()) , state(emptyArray()) {} }; -af_random_engine getRandomEngineHandle(const RandomEngine engine) { - RandomEngine *engineHandle = new RandomEngine; - *engineHandle = engine; +af_random_engine getRandomEngineHandle(const RandomEngine &engine) { + auto *engineHandle = new RandomEngine; + *engineHandle = engine; return static_cast(engineHandle); } @@ -64,7 +64,7 @@ RandomEngine *getRandomEngine(const af_random_engine engineHandle) { if (engineHandle == 0) { AF_ERROR("Uninitialized random engine", AF_ERR_ARG); } - return (RandomEngine *)engineHandle; + return static_cast(engineHandle); } namespace { @@ -109,8 +109,8 @@ af_err af_get_default_random_engine(af_random_engine *r) { try { AF_CHECK(af_init()); - thread_local RandomEngine *re = new RandomEngine; - *r = static_cast(re); + thread_local auto *re = new RandomEngine; + *r = static_cast(re); return AF_SUCCESS; } CATCHALL; diff --git a/src/api/c/rank.cpp b/src/api/c/rank.cpp index 22b6b720c0..6f0860a800 100644 --- a/src/api/c/rank.cpp +++ b/src/api/c/rank.cpp @@ -24,8 +24,8 @@ using namespace detail; template static inline uint rank(const af_array in, double tol) { - typedef typename af::dtype_traits::base_type BT; - Array In = getArray(in); + using BT = typename af::dtype_traits::base_type; + const Array In = getArray(in); Array R = createEmptyArray(dim4()); diff --git a/src/api/c/reduce.cpp b/src/api/c/reduce.cpp index 1c5ef4c821..e5088b8e5b 100644 --- a/src/api/c/reduce.cpp +++ b/src/api/c/reduce.cpp @@ -75,7 +75,7 @@ static af_err reduce_type(af_array *out, const af_array in, const int dim) { const ArrayInfo &in_info = getInfo(in); - if (dim >= (int)in_info.ndims()) { + if (dim >= static_cast(in_info.ndims())) { *out = retain(in); return AF_SUCCESS; } @@ -179,7 +179,9 @@ static af_err reduce_common(af_array *out, const af_array in, const int dim) { const ArrayInfo &in_info = getInfo(in); - if (dim >= (int)in_info.ndims()) { return af_retain_array(out, in); } + if (dim >= static_cast(in_info.ndims())) { + return af_retain_array(out, in); + } af_dtype type = in_info.getType(); af_array res; @@ -287,7 +289,7 @@ static af_err reduce_promote(af_array *out, const af_array in, const int dim, const ArrayInfo &in_info = getInfo(in); - if (dim >= (int)in_info.ndims()) { + if (dim >= static_cast(in_info.ndims())) { *out = retain(in); return AF_SUCCESS; } @@ -522,10 +524,11 @@ af_err af_any_true_by_key(af_array *keys_out, af_array *vals_out, dim); } -template -static inline To reduce_all(const af_array in, bool change_nan = false, - double nanval = 0) { - return reduce_all(getArray(in), change_nan, nanval); +template +static inline Tret reduce_all(const af_array in, bool change_nan = false, + double nanval = 0) { + return static_cast( + reduce_all(getArray(in), change_nan, nanval)); } template @@ -534,24 +537,26 @@ static af_err reduce_all_type(double *real, double *imag, const af_array in) { const ArrayInfo &in_info = getInfo(in); af_dtype type = in_info.getType(); - ARG_ASSERT(0, real != NULL); + ARG_ASSERT(0, real != nullptr); *real = 0; - if (imag) *imag = 0; + if (imag) { *imag = 0; } switch (type) { - case f32: *real = (double)reduce_all(in); break; - case f64: *real = (double)reduce_all(in); break; - case c32: *real = (double)reduce_all(in); break; - case c64: *real = (double)reduce_all(in); break; - case u32: *real = (double)reduce_all(in); break; - case s32: *real = (double)reduce_all(in); break; - case u64: *real = (double)reduce_all(in); break; - case s64: *real = (double)reduce_all(in); break; - case u16: *real = (double)reduce_all(in); break; - case s16: *real = (double)reduce_all(in); break; - case b8: *real = (double)reduce_all(in); break; - case u8: *real = (double)reduce_all(in); break; - case f16: *real = (double)reduce_all(in); break; + // clang-format off + case f32: *real = reduce_all(in); break; + case f64: *real = reduce_all(in); break; + case c32: *real = reduce_all(in); break; + case c64: *real = reduce_all(in); break; + case u32: *real = reduce_all(in); break; + case s32: *real = reduce_all(in); break; + case u64: *real = reduce_all(in); break; + case s64: *real = reduce_all(in); break; + case u16: *real = reduce_all(in); break; + case s16: *real = reduce_all(in); break; + case b8: *real = reduce_all(in); break; + case u8: *real = reduce_all(in); break; + case f16: *real = reduce_all(in); break; + // clang-format on default: TYPE_ERROR(1, type); } } @@ -568,48 +573,37 @@ static af_err reduce_all_common(double *real_val, double *imag_val, af_dtype type = in_info.getType(); ARG_ASSERT(2, in_info.ndims() > 0); - ARG_ASSERT(0, real_val != NULL); + ARG_ASSERT(0, real_val != nullptr); *real_val = 0; - if (imag_val != NULL) *imag_val = 0; + if (imag_val != nullptr) { *imag_val = 0; } cfloat cfval; cdouble cdval; switch (type) { - case f32: - *real_val = (double)reduce_all(in); - break; - case f64: - *real_val = (double)reduce_all(in); - break; - case u32: *real_val = (double)reduce_all(in); break; - case s32: *real_val = (double)reduce_all(in); break; - case u64: - *real_val = (double)reduce_all(in); - break; - case s64: *real_val = (double)reduce_all(in); break; - case u16: - *real_val = (double)reduce_all(in); - break; - case s16: - *real_val = (double)reduce_all(in); - break; - case b8: *real_val = (double)reduce_all(in); break; - case u8: - *real_val = (double)reduce_all(in); - break; - case f16: *real_val = (double)reduce_all(in); break; - + // clang-format off + case f32: *real_val = reduce_all(in); break; + case f64: *real_val = reduce_all(in); break; + case u32: *real_val = reduce_all(in); break; + case s32: *real_val = reduce_all(in); break; + case u64: *real_val = reduce_all(in); break; + case s64: *real_val = reduce_all(in); break; + case u16: *real_val = reduce_all(in); break; + case s16: *real_val = reduce_all(in); break; + case b8: *real_val = reduce_all(in); break; + case u8: *real_val = reduce_all(in); break; + case f16: *real_val = reduce_all(in); break; + // clang-format on case c32: - cfval = reduce_all(in); - ARG_ASSERT(1, imag_val != NULL); + cfval = reduce_all(in); + ARG_ASSERT(1, imag_val != nullptr); *real_val = real(cfval); *imag_val = imag(cfval); break; case c64: - cdval = reduce_all(in); - ARG_ASSERT(1, imag_val != NULL); + cdval = reduce_all(in); + ARG_ASSERT(1, imag_val != nullptr); *real_val = real(cdval); *imag_val = imag(cdval); break; @@ -630,75 +624,49 @@ static af_err reduce_all_promote(double *real_val, double *imag_val, const ArrayInfo &in_info = getInfo(in); af_dtype type = in_info.getType(); - ARG_ASSERT(0, real_val != NULL); + ARG_ASSERT(0, real_val != nullptr); *real_val = 0; - if (imag_val) *imag_val = 0; + if (imag_val) { *imag_val = 0; } cfloat cfval; cdouble cdval; switch (type) { - case f32: - *real_val = (double)reduce_all(in, change_nan, - nanval); - break; - case f64: - *real_val = (double)reduce_all( - in, change_nan, nanval); - break; - case u32: - *real_val = - (double)reduce_all(in, change_nan, nanval); - break; - case s32: - *real_val = - (double)reduce_all(in, change_nan, nanval); - break; - case u64: - *real_val = (double)reduce_all(in, change_nan, - nanval); - break; - case s64: - *real_val = - (double)reduce_all(in, change_nan, nanval); - break; - case u16: - *real_val = (double)reduce_all(in, change_nan, - nanval); - break; - case s16: - *real_val = - (double)reduce_all(in, change_nan, nanval); - break; - case u8: - *real_val = - (double)reduce_all(in, change_nan, nanval); - break; + // clang-format off + case f32: *real_val = reduce_all(in, change_nan, nanval); break; + case f64: *real_val = reduce_all(in, change_nan, nanval); break; + case u32: *real_val = reduce_all(in, change_nan, nanval); break; + case s32: *real_val = reduce_all(in, change_nan, nanval); break; + case u64: *real_val = reduce_all(in, change_nan, nanval); break; + case s64: *real_val = reduce_all(in, change_nan, nanval); break; + case u16: *real_val = reduce_all(in, change_nan, nanval); break; + case s16: *real_val = reduce_all(in, change_nan, nanval); break; + case u8: *real_val = reduce_all(in, change_nan, nanval); break; + // clang-format on case b8: { if (op == af_mul_t) { - *real_val = (double)reduce_all( - in, change_nan, nanval); + *real_val = reduce_all(in, change_nan, + nanval); } else { - *real_val = (double)reduce_all( + *real_val = reduce_all( in, change_nan, nanval); } } break; case c32: - cfval = reduce_all(in); - ARG_ASSERT(1, imag_val != NULL); + cfval = reduce_all(in); + ARG_ASSERT(1, imag_val != nullptr); *real_val = real(cfval); *imag_val = imag(cfval); break; case c64: - cdval = reduce_all(in); - ARG_ASSERT(1, imag_val != NULL); + cdval = reduce_all(in); + ARG_ASSERT(1, imag_val != nullptr); *real_val = real(cdval); *imag_val = imag(cdval); break; case f16: - *real_val = - (double)reduce_all(in, change_nan, nanval); + *real_val = reduce_all(in, change_nan, nanval); break; default: TYPE_ERROR(1, type); @@ -778,7 +746,7 @@ static af_err ireduce_common(af_array *val, af_array *idx, const af_array in, const ArrayInfo &in_info = getInfo(in); ARG_ASSERT(2, in_info.ndims() > 0); - if (dim >= (int)in_info.ndims()) { + if (dim >= static_cast(in_info.ndims())) { *val = retain(in); *idx = createHandleFromValue(in_info.dims(), 0); return AF_SUCCESS; @@ -830,13 +798,13 @@ static af_err rreduce_common(af_array *val, af_array *idx, const af_array in, const ArrayInfo &in_info = getInfo(in); ARG_ASSERT(2, in_info.ndims() > 0); - if (dim >= (int)in_info.ndims()) { + if (dim >= static_cast(in_info.ndims())) { *val = retain(in); *idx = createHandleFromValue(in_info.dims(), 0); return AF_SUCCESS; } - // TODO: make sure ragged_len.dims == in.dims(), except on reduced dim + // Make sure ragged_len.dims == in.dims(), except on reduced dim const ArrayInfo &ragged_info = getInfo(ragged_len); dim4 test_dim = in_info.dims(); test_dim[dim] = 1; @@ -892,9 +860,9 @@ af_err af_max_ragged(af_array *val, af_array *idx, const af_array in, return rreduce_common(val, idx, in, ragged_len, dim); } -template -static inline T ireduce_all(unsigned *loc, const af_array in) { - return ireduce_all(loc, getArray(in)); +template +static inline Tret ireduce_all(unsigned *loc, const af_array in) { + return static_cast(ireduce_all(loc, getArray(in))); } template @@ -905,45 +873,45 @@ static af_err ireduce_all_common(double *real_val, double *imag_val, af_dtype type = in_info.getType(); ARG_ASSERT(3, in_info.ndims() > 0); - ARG_ASSERT(0, real_val != NULL); + ARG_ASSERT(0, real_val != nullptr); *real_val = 0; - if (imag_val) *imag_val = 0; + if (imag_val) { *imag_val = 0; } cfloat cfval; cdouble cdval; switch (type) { case f32: - *real_val = (double)ireduce_all(loc, in); + *real_val = ireduce_all(loc, in); break; case f64: - *real_val = (double)ireduce_all(loc, in); + *real_val = ireduce_all(loc, in); break; - case u32: *real_val = (double)ireduce_all(loc, in); break; - case s32: *real_val = (double)ireduce_all(loc, in); break; + case u32: *real_val = ireduce_all(loc, in); break; + case s32: *real_val = ireduce_all(loc, in); break; case u64: - *real_val = (double)ireduce_all(loc, in); + *real_val = ireduce_all(loc, in); break; - case s64: *real_val = (double)ireduce_all(loc, in); break; + case s64: *real_val = ireduce_all(loc, in); break; case u16: - *real_val = (double)ireduce_all(loc, in); + *real_val = ireduce_all(loc, in); break; case s16: - *real_val = (double)ireduce_all(loc, in); + *real_val = ireduce_all(loc, in); break; - case b8: *real_val = (double)ireduce_all(loc, in); break; - case u8: *real_val = (double)ireduce_all(loc, in); break; + case b8: *real_val = ireduce_all(loc, in); break; + case u8: *real_val = ireduce_all(loc, in); break; case c32: cfval = ireduce_all(loc, in); - ARG_ASSERT(1, imag_val != NULL); + ARG_ASSERT(1, imag_val != nullptr); *real_val = real(cfval); *imag_val = imag(cfval); break; case c64: cdval = ireduce_all(loc, in); - ARG_ASSERT(1, imag_val != NULL); + ARG_ASSERT(1, imag_val != nullptr); *real_val = real(cdval); *imag_val = imag(cdval); break; diff --git a/src/api/c/reorder.cpp b/src/api/c/reorder.cpp index 418d1180cf..bbd4431a5c 100644 --- a/src/api/c/reorder.cpp +++ b/src/api/c/reorder.cpp @@ -40,8 +40,8 @@ static inline af_array reorder(const af_array in, const af::dim4 &rdims0) { af_array out; if (rdims[0] == 0 && rdims[1] == 1 && rdims[2] == 2 && rdims[3] == 3) { - Array Out = In; - out = getHandle(Out); + const Array &Out = In; + out = getHandle(Out); } else if (rdims[0] == 0) { dim4 odims = dim4(1, 1, 1, 1); dim4 ostrides = dim4(1, 1, 1, 1); diff --git a/src/api/c/resize.cpp b/src/api/c/resize.cpp index 9e912d6caf..6c783e0374 100644 --- a/src/api/c/resize.cpp +++ b/src/api/c/resize.cpp @@ -16,7 +16,6 @@ #include #include -using af::dim4; using namespace detail; template diff --git a/src/api/c/rgb_gray.cpp b/src/api/c/rgb_gray.cpp index 0f308be153..ce4c2f6f57 100644 --- a/src/api/c/rgb_gray.cpp +++ b/src/api/c/rgb_gray.cpp @@ -117,10 +117,11 @@ af_err convert(af_array* out, const af_array in, const float r, const float g, // If RGB is input, then assert 3 channels // else 1 channel - if (isRGB2GRAY) + if (isRGB2GRAY) { ARG_ASSERT(1, (inputDims[2] == 3)); - else + } else { ARG_ASSERT(1, (inputDims[2] == 1)); + } af_array output = 0; switch (iType) { diff --git a/src/api/c/rotate.cpp b/src/api/c/rotate.cpp index fd2a9252e3..45b03c6796 100644 --- a/src/api/c/rotate.cpp +++ b/src/api/c/rotate.cpp @@ -13,8 +13,12 @@ #include #include #include +#include using af::dim4; +using std::cos; +using std::fabs; +using std::sin; using namespace detail; template @@ -27,16 +31,14 @@ static inline af_array rotate(const af_array in, const float theta, af_err af_rotate(af_array *out, const af_array in, const float theta, const bool crop, const af_interp_type method) { try { - unsigned odims0 = 0, odims1 = 0; + dim_t odims0 = 0, odims1 = 0; const ArrayInfo &info = getInfo(in); af::dim4 idims = info.dims(); if (!crop) { - odims0 = idims[0] * fabs(std::cos(theta)) + - idims[1] * fabs(std::sin(theta)); - odims1 = idims[1] * fabs(std::cos(theta)) + - idims[0] * fabs(std::sin(theta)); + odims0 = idims[0] * fabs(cos(theta)) + idims[1] * fabs(sin(theta)); + odims1 = idims[1] * fabs(cos(theta)) + idims[0] * fabs(sin(theta)); } else { odims0 = idims[0]; odims1 = idims[1]; @@ -68,7 +70,7 @@ af_err af_rotate(af_array *out, const af_array in, const float theta, case u64: output = rotate(in, theta, odims, method); break; case s16: output = rotate(in, theta, odims, method); break; case u16: output = rotate(in, theta, odims, method); break; - case u8: output = rotate(in, theta, odims, method); break; + case u8: case b8: output = rotate(in, theta, odims, method); break; default: TYPE_ERROR(1, itype); } diff --git a/src/api/c/sat.cpp b/src/api/c/sat.cpp index d63e2aa75d..9b6231e0e6 100644 --- a/src/api/c/sat.cpp +++ b/src/api/c/sat.cpp @@ -24,7 +24,7 @@ inline af_array sat(const af_array& in) { af_err af_sat(af_array* out, const af_array in) { try { const ArrayInfo& info = getInfo(in); - const dim4 dims = info.dims(); + const dim4& dims = info.dims(); ARG_ASSERT(1, (dims.ndims() >= 2)); diff --git a/src/api/c/scan.cpp b/src/api/c/scan.cpp index 05811bae09..053ac0111a 100644 --- a/src/api/c/scan.cpp +++ b/src/api/c/scan.cpp @@ -18,7 +18,6 @@ #include #include -using af::dim4; using namespace detail; template @@ -116,7 +115,7 @@ af_err af_accum(af_array* out, const af_array in, const int dim) { const ArrayInfo& in_info = getInfo(in); - if (dim >= (int)in_info.ndims()) { + if (dim >= static_cast(in_info.ndims())) { *out = retain(in); return AF_SUCCESS; } @@ -157,7 +156,7 @@ af_err af_scan(af_array* out, const af_array in, const int dim, af_binary_op op, const ArrayInfo& in_info = getInfo(in); - if (dim >= (int)in_info.ndims()) { + if (dim >= static_cast(in_info.ndims())) { *out = retain(in); return AF_SUCCESS; } @@ -221,7 +220,7 @@ af_err af_scan_by_key(af_array* out, const af_array key, const af_array in, const ArrayInfo& in_info = getInfo(in); const ArrayInfo& key_info = getInfo(key); - if (dim >= (int)in_info.ndims()) { + if (dim >= static_cast(in_info.ndims())) { *out = retain(in); return AF_SUCCESS; } @@ -245,9 +244,7 @@ af_err af_scan_by_key(af_array* out, const af_array key, const af_array in, res = scan_op(key, in, dim, op, inclusive_scan); break; - case u32: - res = scan_op(key, in, dim, op, inclusive_scan); - break; + case s16: case s32: res = scan_op(key, in, dim, op, inclusive_scan); break; @@ -258,14 +255,8 @@ af_err af_scan_by_key(af_array* out, const af_array key, const af_array in, res = scan_op(key, in, dim, op, inclusive_scan); break; case u16: - res = scan_op(key, in, dim, op, inclusive_scan); - break; - case s16: - res = scan_op(key, in, dim, op, inclusive_scan); - break; + case u32: case u8: - res = scan_op(key, in, dim, op, inclusive_scan); - break; case b8: res = scan_op(key, in, dim, op, inclusive_scan); break; diff --git a/src/api/c/set.cpp b/src/api/c/set.cpp index df128f44ec..8bf9f8c4c4 100644 --- a/src/api/c/set.cpp +++ b/src/api/c/set.cpp @@ -15,7 +15,6 @@ #include #include -using af::dim4; using namespace detail; template @@ -117,7 +116,7 @@ af_err af_set_intersect(af_array* out, const af_array first, const ArrayInfo& first_info = getInfo(first); const ArrayInfo& second_info = getInfo(second); - // TODO: fix for set intersect from union + // TODO(umar): fix for set intersect from union if (first_info.isEmpty()) { return af_retain_array(out, first); } if (second_info.isEmpty()) { return af_retain_array(out, second); } diff --git a/src/api/c/shift.cpp b/src/api/c/shift.cpp index 44da4d8b57..9b0a0f0170 100644 --- a/src/api/c/shift.cpp +++ b/src/api/c/shift.cpp @@ -14,7 +14,6 @@ #include #include -using af::dim4; using namespace detail; template diff --git a/src/api/c/sobel.cpp b/src/api/c/sobel.cpp index 7e7c35b2ea..9e70f3f257 100644 --- a/src/api/c/sobel.cpp +++ b/src/api/c/sobel.cpp @@ -19,11 +19,11 @@ using af::dim4; using namespace detail; -typedef std::pair ArrayPair; +using ArrayPair = std::pair; template ArrayPair sobelDerivatives(const af_array &in, const unsigned &ker_size) { - typedef std::pair, Array> BAPair; - BAPair out = sobelDerivatives(getArray(in), ker_size); + using BAPair = std::pair, Array>; + BAPair out = sobelDerivatives(getArray(in), ker_size); return std::make_pair(getHandle(out.first), getHandle(out.second)); } diff --git a/src/api/c/sort.cpp b/src/api/c/sort.cpp index ffefbb580c..62b2a37e2f 100644 --- a/src/api/c/sort.cpp +++ b/src/api/c/sort.cpp @@ -185,8 +185,6 @@ void sort_by_key_tmplt(af_array *okey, af_array *oval, const af_array ikey, break; default: TYPE_ERROR(1, vtype); } - - return; } af_err af_sort_by_key(af_array *out_keys, af_array *out_values, diff --git a/src/api/c/sparse.cpp b/src/api/c/sparse.cpp index c093504db5..03331e472d 100644 --- a/src/api/c/sparse.cpp +++ b/src/api/c/sparse.cpp @@ -133,19 +133,22 @@ af_array createSparseArrayFromPtr(const af::dim4 &dims, const dim_t nNZ, const int *const colIdx, const af::storage stype, const af::source source) { - SparseArray sparse = createEmptySparseArray(dims, nNZ, stype); - if (nNZ) { - if (source == afHost) - sparse = common::createHostDataSparseArray(dims, nNZ, values, - rowIdx, colIdx, stype); - else if (source == afDevice) - sparse = common::createDeviceDataSparseArray( - dims, nNZ, const_cast(values), const_cast(rowIdx), - const_cast(colIdx), stype); + switch (source) { + case afHost: + return getHandle(common::createHostDataSparseArray( + dims, nNZ, values, rowIdx, colIdx, stype)); + break; + case afDevice: + return getHandle(common::createDeviceDataSparseArray( + dims, nNZ, const_cast(values), + const_cast(rowIdx), const_cast(colIdx), + stype)); + break; + } } - return getHandle(sparse); + return getHandle(createEmptySparseArray(dims, nNZ, stype)); } af_err af_create_sparse_array_from_ptr( @@ -400,10 +403,10 @@ af_array getSparseValues(const af_array in) { af_err af_sparse_get_info(af_array *values, af_array *rows, af_array *cols, af_storage *stype, const af_array in) { try { - if (values != NULL) AF_CHECK(af_sparse_get_values(values, in)); - if (rows != NULL) AF_CHECK(af_sparse_get_row_idx(rows, in)); - if (cols != NULL) AF_CHECK(af_sparse_get_col_idx(cols, in)); - if (stype != NULL) AF_CHECK(af_sparse_get_storage(stype, in)); + if (values != NULL) { AF_CHECK(af_sparse_get_values(values, in)); } + if (rows != NULL) { AF_CHECK(af_sparse_get_row_idx(rows, in)); } + if (cols != NULL) { AF_CHECK(af_sparse_get_col_idx(cols, in)); } + if (stype != NULL) { AF_CHECK(af_sparse_get_storage(stype, in)); } } CATCHALL; diff --git a/src/api/c/sparse_handle.hpp b/src/api/c/sparse_handle.hpp index c7afce5306..e3925b61d2 100644 --- a/src/api/c/sparse_handle.hpp +++ b/src/api/c/sparse_handle.hpp @@ -20,7 +20,7 @@ #include -const common::SparseArrayBase &getSparseArrayBase(const af_array arr, +const common::SparseArrayBase &getSparseArrayBase(const af_array in, bool device_check = true); template diff --git a/src/api/c/stdev.cpp b/src/api/c/stdev.cpp index b67c3c3dc4..11da858ca3 100644 --- a/src/api/c/stdev.cpp +++ b/src/api/c/stdev.cpp @@ -28,8 +28,8 @@ using namespace detail; template static outType stdev(const af_array& in) { - typedef typename baseOutType::type weightType; - Array _in = getArray(in); + using weightType = typename baseOutType::type; + const Array _in = getArray(in); Array input = cast(_in); Array meanCnst = createValueArray( input.dims(), mean(_in)); @@ -45,10 +45,10 @@ static outType stdev(const af_array& in) { template static af_array stdev(const af_array& in, int dim) { - typedef typename baseOutType::type weightType; - Array _in = getArray(in); - Array input = cast(_in); - dim4 iDims = input.dims(); + using weightType = typename baseOutType::type; + const Array _in = getArray(in); + Array input = cast(_in); + dim4 iDims = input.dims(); Array meanArr = mean(_in, dim); @@ -63,7 +63,7 @@ static af_array stdev(const af_array& in, int dim) { Array diffSq = detail::arithOp(diff, diff, diff.dims()); Array redDiff = reduce(diffSq, dim); - dim4 oDims = redDiff.dims(); + const dim4& oDims = redDiff.dims(); Array divArr = createValueArray(oDims, scalar(iDims[dim])); @@ -74,6 +74,7 @@ static af_array stdev(const af_array& in, int dim) { return getHandle(result); } +// NOLINTNEXTLINE(readability-non-const-parameter) af_err af_stdev_all(double* realVal, double* imagVal, const af_array in) { UNUSED(imagVal); // TODO implement for complex values try { @@ -90,8 +91,8 @@ af_err af_stdev_all(double* realVal, double* imagVal, const af_array in) { case u64: *realVal = stdev(in); break; case u8: *realVal = stdev(in); break; case b8: *realVal = stdev(in); break; - // TODO: FIXME: sqrt(complex) is not present in cuda/opencl backend - // case c32: { + // TODO(umar): FIXME: sqrt(complex) is not present in cuda/opencl + // backend case c32: { // cfloat tmp = stdev(in); // *realVal = real(tmp); // *imagVal = imag(tmp); @@ -126,9 +127,9 @@ af_err af_stdev(af_array* out, const af_array in, const dim_t dim) { case u64: output = stdev(in, dim); break; case u8: output = stdev(in, dim); break; case b8: output = stdev(in, dim); break; - // TODO: FIXME: sqrt(complex) is not present in cuda/opencl backend - // case c32: output = stdev(in, dim); break; - // case c64: output = stdev(in, dim); break; + // TODO(umar): FIXME: sqrt(complex) is not present in cuda/opencl + // backend case c32: output = stdev(in, dim); + // break; case c64: output = stdev(in, dim); break; default: TYPE_ERROR(1, type); } std::swap(*out, output); diff --git a/src/api/c/stream.cpp b/src/api/c/stream.cpp index 1392df6db9..1be207c66d 100644 --- a/src/api/c/stream.cpp +++ b/src/api/c/stream.cpp @@ -80,7 +80,7 @@ static int save(const char *key, const af_array arr, const char *filename, } // Throw exception if file is not open - if (!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG); + if (!fs.is_open()) { AF_ERROR("File failed to open", AF_ERR_ARG); } // Assert Version if (fs.peek() == std::fstream::traits_type::eof()) { @@ -94,14 +94,14 @@ static int save(const char *key, const af_array arr, const char *filename, prev_version == sfv_char, "ArrayFire data format has changed. Can't append to file"); - fs.read((char *)&n_arrays, sizeof(int)); + fs.read(reinterpret_cast(&n_arrays), sizeof(int)); } } else { fs.open(filename, std::fstream::out | std::fstream::binary | std::fstream::trunc); // Throw exception if file is not open - if (!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG); + if (!fs.is_open()) { AF_ERROR("File failed to open", AF_ERR_ARG); } } n_arrays++; @@ -109,16 +109,16 @@ static int save(const char *key, const af_array arr, const char *filename, // Write version and n_arrays to top of file fs.seekp(0); fs.write(&sfv_char, 1); - fs.write((char *)&n_arrays, sizeof(int)); + fs.write(reinterpret_cast(&n_arrays), sizeof(int)); // Write array to end of file. Irrespective of new or append fs.seekp(0, std::ios_base::end); - fs.write((char *)&klen, sizeof(int)); + fs.write(reinterpret_cast(&klen), sizeof(int)); fs.write(k.c_str(), klen); - fs.write((char *)&offset, sizeof(intl)); + fs.write(reinterpret_cast(&offset), sizeof(intl)); fs.write(&type, sizeof(char)); - fs.write((char *)&odims, sizeof(intl) * 4); - fs.write((char *)&data.front(), sizeof(T) * data.size()); + fs.write(reinterpret_cast(&odims), sizeof(intl) * 4); + fs.write(reinterpret_cast(&data.front()), sizeof(T) * data.size()); fs.close(); return n_arrays - 1; @@ -157,7 +157,7 @@ af_err af_save_array(int *index, const char *key, const af_array arr, template static af_array readDataToArray(std::fstream &fs) { intl dims[4]; - fs.read((char *)&dims, 4 * sizeof(intl)); + fs.read(reinterpret_cast(&dims), 4 * sizeof(intl)); dim4 d; for (int i = 0; i < 4; i++) { d[i] = dims[i]; } @@ -165,7 +165,7 @@ static af_array readDataToArray(std::fstream &fs) { intl size = d.elements(); std::vector data(size); - fs.read((char *)&data.front(), size * sizeof(T)); + fs.read(reinterpret_cast(&data.front()), size * sizeof(T)); return getHandle(createHostDataArray(d, &data.front())); } @@ -177,18 +177,18 @@ static af_array readArrayV1(const char *filename, const unsigned index) { std::fstream fs(filename, std::fstream::in | std::fstream::binary); // Throw exception if file is not open - if (!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG); + if (!fs.is_open()) { AF_ERROR("File failed to open", AF_ERR_ARG); } if (fs.peek() == std::fstream::traits_type::eof()) { AF_ERROR("File is empty", AF_ERR_ARG); } fs.read(&version, sizeof(char)); - fs.read((char *)&n_arrays, sizeof(int)); + fs.read(reinterpret_cast(&n_arrays), sizeof(int)); AF_ASSERT((int)index < n_arrays, "Index out of bounds"); - for (int i = 0; i < (int)index; i++) { + for (unsigned i = 0; i < index; i++) { // (int ) Length of the key // (cstring) Key // (intl ) Offset bytes to next array (type + dims + data) @@ -196,7 +196,7 @@ static af_array readArrayV1(const char *filename, const unsigned index) { // (intl ) dim4 (x 4) // (T ) data (x elements) int klen = -1; - fs.read((char *)&klen, sizeof(int)); + fs.read(reinterpret_cast(&klen), sizeof(int)); // char* key = new char[klen]; // fs.read((char*)&key, klen * sizeof(char)); @@ -206,14 +206,14 @@ static af_array readArrayV1(const char *filename, const unsigned index) { // Read data offset intl offset = -1; - fs.read((char *)&offset, sizeof(intl)); + fs.read(reinterpret_cast(&offset), sizeof(intl)); // Skip data fs.seekg(offset, std::ios_base::cur); } int klen = -1; - fs.read((char *)&klen, sizeof(int)); + fs.read(reinterpret_cast(&klen), sizeof(int)); // char* key = new char[klen]; // fs.read((char*)&key, klen * sizeof(char)); @@ -223,13 +223,13 @@ static af_array readArrayV1(const char *filename, const unsigned index) { // Read data offset intl offset = -1; - fs.read((char *)&offset, sizeof(intl)); + fs.read(reinterpret_cast(&offset), sizeof(intl)); // Read type and dims char type_ = -1; fs.read(&type_, sizeof(char)); - af_dtype type = (af_dtype)type_; + auto type = static_cast(type_); af_array out; switch (type) { @@ -272,7 +272,7 @@ static af_array checkVersionAndRead(const char *filename, } fs.close(); - switch (version) { + switch (version) { // NOLINT(hicpp-multiway-paths-covered) case 1: return readArrayV1(filename, index); default: AF_ERROR("Invalid version", AF_ERR_ARG); } @@ -300,10 +300,10 @@ int checkVersionAndFindIndex(const char *filename, const char *k) { int index = -1; if (version == 1) { int n_arrays = -1; - fs.read((char *)&n_arrays, sizeof(int)); + fs.read(reinterpret_cast(&n_arrays), sizeof(int)); for (int i = 0; i < n_arrays; i++) { int klen = -1; - fs.read((char *)&klen, sizeof(int)); + fs.read(reinterpret_cast(&klen), sizeof(int)); string readKey; readKey.resize(klen); fs.read(&readKey.front(), klen); @@ -312,12 +312,11 @@ int checkVersionAndFindIndex(const char *filename, const char *k) { // Ket matches, break index = i; break; - } else { - // Key doesn't match. Skip the data - intl offset = -1; - fs.read((char *)&offset, sizeof(intl)); - fs.seekg(offset, std::ios_base::cur); } + // Key doesn't match. Skip the data + intl offset = -1; + fs.read(reinterpret_cast(&offset), sizeof(intl)); + fs.seekg(offset, std::ios_base::cur); } } else { AF_ERROR("Invalid version", AF_ERR_ARG); @@ -350,7 +349,7 @@ af_err af_read_array_key(af_array *out, const char *filename, const char *key) { // Find index of key. Then call read by index int index = checkVersionAndFindIndex(filename, key); - if (index == -1) AF_ERROR("Key not found", AF_ERR_INVALID_ARRAY); + if (index == -1) { AF_ERROR("Key not found", AF_ERR_INVALID_ARRAY); } af_array output = checkVersionAndRead(filename, index); std::swap(*out, output); diff --git a/src/api/c/surface.cpp b/src/api/c/surface.cpp index 8f325acb8e..6ca2c6d1a2 100644 --- a/src/api/c/surface.cpp +++ b/src/api/c/surface.cpp @@ -70,10 +70,11 @@ fg_chart setup_surface(fg_window window, const af_array xVals, // Get the chart for the current grid position (if any) fg_chart chart = NULL; - if (props->col > -1 && props->row > -1) + if (props->col > -1 && props->row > -1) { chart = fgMngr.getChart(window, props->row, props->col, FG_CHART_3D); - else + } else { chart = fgMngr.getChart(window, 0, 0, FG_CHART_3D); + } fg_surface surface = fgMngr.getSurface(chart, Z_dims[0], Z_dims[1], getGLType()); @@ -104,12 +105,12 @@ fg_chart setup_surface(fg_window window, const af_array xVals, cmin[2] = step_round(dmin[2], false); cmax[2] = step_round(dmax[2], true); } else { - if (cmin[0] > dmin[0]) cmin[0] = step_round(dmin[0], false); - if (cmax[0] < dmax[0]) cmax[0] = step_round(dmax[0], true); - if (cmin[1] > dmin[1]) cmin[1] = step_round(dmin[1], false); - if (cmax[1] < dmax[1]) cmax[1] = step_round(dmax[1], true); - if (cmin[2] > dmin[2]) cmin[2] = step_round(dmin[2], false); - if (cmax[2] < dmax[2]) cmax[2] = step_round(dmax[2], true); + if (cmin[0] > dmin[0]) { cmin[0] = step_round(dmin[0], false); } + if (cmax[0] < dmax[0]) { cmax[0] = step_round(dmax[0], true); } + if (cmin[1] > dmin[1]) { cmin[1] = step_round(dmin[1], false); } + if (cmax[1] < dmax[1]) { cmax[1] = step_round(dmax[1], true); } + if (cmin[2] > dmin[2]) { cmin[2] = step_round(dmin[2], false); } + if (cmax[2] < dmax[2]) { cmax[2] = step_round(dmax[2], true); } } FG_CHECK(_.fg_set_chart_axes_limits(chart, cmin[0], cmax[0], cmin[1], @@ -135,7 +136,7 @@ af_err af_draw_surface(const af_window window, const af_array xVals, af_dtype Ytype = Yinfo.getType(); const ArrayInfo& Sinfo = getInfo(S); - af::dim4 S_dims = Sinfo.dims(); + const af::dim4& S_dims = Sinfo.dims(); af_dtype Stype = Sinfo.getType(); TYPE_ASSERT(Xtype == Ytype); diff --git a/src/api/c/svd.cpp b/src/api/c/svd.cpp index cb208192fb..c1552a1e37 100644 --- a/src/api/c/svd.cpp +++ b/src/api/c/svd.cpp @@ -28,7 +28,7 @@ static inline void svd(af_array *s, af_array *u, af_array *vt, int M = dims[0]; int N = dims[1]; - typedef typename af::dtype_traits::base_type Tr; + using Tr = typename af::dtype_traits::base_type; // Allocate output arrays Array sA = createEmptyArray(af::dim4(min(M, N))); @@ -50,7 +50,7 @@ static inline void svdInPlace(af_array *s, af_array *u, af_array *vt, int M = dims[0]; int N = dims[1]; - typedef typename af::dtype_traits::base_type Tr; + using Tr = typename af::dtype_traits::base_type; // Allocate output arrays Array sA = createEmptyArray(af::dim4(min(M, N))); diff --git a/src/api/c/tile.cpp b/src/api/c/tile.cpp index e59592c541..14d87559ba 100644 --- a/src/api/c/tile.cpp +++ b/src/api/c/tile.cpp @@ -26,7 +26,7 @@ using namespace detail; template static inline af_array tile(const af_array in, const af::dim4 &tileDims) { const Array inArray = getArray(in); - const dim4 inDims = inArray.dims(); + const dim4 &inDims = inArray.dims(); // FIXME: Always use JIT instead of checking for the condition. // The current limitation exists for performance reasons. it should change @@ -42,11 +42,13 @@ static inline af_array tile(const af_array in, const af::dim4 &tileDims) { outDims[i] = inDims[i] * tileDims[i]; } + af_array out = nullptr; if (take_jit_path) { - return getHandle(unaryOp(inArray, outDims)); + out = getHandle(unaryOp(inArray, outDims)); } else { - return getHandle(tile(inArray, tileDims)); + out = getHandle(tile(inArray, tileDims)); } + return out; } af_err af_tile(af_array *out, const af_array in, const af::dim4 &tileDims) { diff --git a/src/api/c/topk.cpp b/src/api/c/topk.cpp index 4d848eef9a..0972f3b46e 100644 --- a/src/api/c/topk.cpp +++ b/src/api/c/topk.cpp @@ -41,7 +41,7 @@ af_err af_topk(af_array *values, af_array *indices, const af_array in, try { af::topkFunction ord = (order == AF_TOPK_DEFAULT ? AF_TOPK_MAX : order); - ArrayInfo inInfo = getInfo(in); + const ArrayInfo &inInfo = getInfo(in); ARG_ASSERT(2, (inInfo.ndims() > 0)); @@ -67,9 +67,10 @@ af_err af_topk(af_array *values, af_array *indices, const af_array in, ARG_ASSERT(2, (inInfo.dims()[rdim] >= k)); ARG_ASSERT(4, (k <= 256)); // TODO(umar): Remove this limitation - if (rdim != 0) + if (rdim != 0) { AF_ERROR("topk is supported along dimenion 0 only.", AF_ERR_NOT_SUPPORTED); + } af_dtype type = inInfo.getType(); diff --git a/src/api/c/transform.cpp b/src/api/c/transform.cpp index bcd5563296..ff379f0b88 100644 --- a/src/api/c/transform.cpp +++ b/src/api/c/transform.cpp @@ -20,10 +20,9 @@ using namespace detail; template static inline void transform(af_array *out, const af_array in, - const af_array tf, const dim4 &odims, - const af_interp_type method, const bool inverse, - const bool perspective) { - transform(getArray(*out), getArray(in), getArray(tf), odims, + const af_array tf, const af_interp_type method, + const bool inverse, const bool perspective) { + transform(getArray(*out), getArray(in), getArray(tf), method, inverse, perspective); } @@ -33,13 +32,12 @@ AF_BATCH_KIND getTransformBatchKind(const dim4 &iDims, const dim4 &tDims) { dim_t iNd = iDims.ndims(); dim_t tNd = tDims.ndims(); - if (iNd == baseDim && tNd == baseDim) - return AF_BATCH_NONE; - else if (iNd == baseDim && tNd <= 4) + if (iNd == baseDim && tNd == baseDim) { return AF_BATCH_NONE; } + if (iNd == baseDim && tNd <= 4) { return AF_BATCH_RHS; - else if (iNd <= 4 && tNd == baseDim) + } else if (iNd <= 4 && tNd == baseDim) { return AF_BATCH_LHS; - else if (iNd <= 4 && tNd <= 4) { + } else if (iNd <= 4 && tNd <= 4) { bool dimsMatch = true; bool isInterleaved = true; for (dim_t i = baseDim; i < 4; i++) { @@ -47,10 +45,11 @@ AF_BATCH_KIND getTransformBatchKind(const dim4 &iDims, const dim4 &tDims) { isInterleaved &= (iDims[i] == 1 || tDims[i] == 1 || iDims[i] == tDims[i]); } - if (dimsMatch) return AF_BATCH_SAME; + if (dimsMatch) { return AF_BATCH_SAME; } return (isInterleaved ? AF_BATCH_DIFF : AF_BATCH_UNSUPPORTED); - } else + } else { return AF_BATCH_UNSUPPORTED; + } } void af_transform_common(af_array *out, const af_array in, const af_array tf, @@ -64,8 +63,8 @@ void af_transform_common(af_array *out, const af_array in, const af_array tf, const ArrayInfo &t_info = getInfo(tf); const ArrayInfo &i_info = getInfo(in); - const dim4 idims = i_info.dims(); - const dim4 tdims = t_info.dims(); + const dim4 &idims = i_info.dims(); + const dim4 &tdims = t_info.dims(); const af_dtype itype = i_info.getType(); // Assert type and interpolation @@ -93,17 +92,19 @@ void af_transform_common(af_array *out, const af_array in, const af_array tf, // If idims[2] > 1 and tdims[2] > 1, then both must be equal // else at least one of them must be 1 - if (tdims[2] != 1 && idims[2] != 1) + if (tdims[2] != 1 && idims[2] != 1) { DIM_ASSERT(2, idims[2] == tdims[2]); - else + } else { DIM_ASSERT(2, idims[2] == 1 || tdims[2] == 1); + } // If idims[3] > 1 and tdims[3] > 1, then both must be equal // else at least one of them must be 1 - if (tdims[3] != 1 && idims[3] != 1) + if (tdims[3] != 1 && idims[3] != 1) { DIM_ASSERT(2, idims[3] == tdims[3]); - else + } else { DIM_ASSERT(2, idims[3] == 1 || tdims[3] == 1); + } const bool perspective = (tdims[1] == 3); dim_t o0 = odim0, o1 = odim1, o2 = 0, o3 = 0; @@ -141,18 +142,18 @@ void af_transform_common(af_array *out, const af_array in, const af_array tf, // clang-format off switch(itype) { - case f32: transform(out, in, tf, odims, method, inverse, perspective); break; - case f64: transform(out, in, tf, odims, method, inverse, perspective); break; - case c32: transform(out, in, tf, odims, method, inverse, perspective); break; - case c64: transform(out, in, tf, odims, method, inverse, perspective); break; - case s32: transform(out, in, tf, odims, method, inverse, perspective); break; - case u32: transform(out, in, tf, odims, method, inverse, perspective); break; - case s64: transform(out, in, tf, odims, method, inverse, perspective); break; - case u64: transform(out, in, tf, odims, method, inverse, perspective); break; - case s16: transform(out, in, tf, odims, method, inverse, perspective); break; - case u16: transform(out, in, tf, odims, method, inverse, perspective); break; - case u8: transform(out, in, tf, odims, method, inverse, perspective); break; - case b8: transform(out, in, tf, odims, method, inverse, perspective); break; + case f32: transform(out, in, tf, method, inverse, perspective); break; + case f64: transform(out, in, tf, method, inverse, perspective); break; + case c32: transform(out, in, tf, method, inverse, perspective); break; + case c64: transform(out, in, tf, method, inverse, perspective); break; + case s32: transform(out, in, tf, method, inverse, perspective); break; + case u32: transform(out, in, tf, method, inverse, perspective); break; + case s64: transform(out, in, tf, method, inverse, perspective); break; + case u64: transform(out, in, tf, method, inverse, perspective); break; + case s16: transform(out, in, tf, method, inverse, perspective); break; + case u16: transform(out, in, tf, method, inverse, perspective); break; + case u8: transform(out, in, tf, method, inverse, perspective); break; + case b8: transform(out, in, tf, method, inverse, perspective); break; default: TYPE_ERROR(1, itype); } // clang-format on @@ -225,8 +226,8 @@ af_err af_scale(af_array *out, const af_array in, const float scale0, DIM_ASSERT(4, odim0 != 0); DIM_ASSERT(5, odim1 != 0); - sx = idims[0] / (float)_odim0; - sy = idims[1] / (float)_odim1; + sx = idims[0] / static_cast(_odim0); + sy = idims[1] / static_cast(_odim1); } else { sx = 1.f / scale0, sy = 1.f / scale1; diff --git a/src/api/c/transform_coordinates.cpp b/src/api/c/transform_coordinates.cpp index 979fa8da01..4f27ac048d 100644 --- a/src/api/c/transform_coordinates.cpp +++ b/src/api/c/transform_coordinates.cpp @@ -38,8 +38,15 @@ template static af_array transform_coordinates(const af_array &tf_, const float d0_, const float d1_) { af::dim4 h_dims(4, 3); - T h_in[4 * 3] = {(T)0, (T)0, (T)d1_, (T)d1_, (T)0, (T)d0_, - (T)d0_, (T)0, (T)1, (T)1, (T)1, (T)1}; + T zero = 0; + T one = 1; + T d0 = static_cast(d0_); + T d1 = static_cast(d1_); + // clang-format off + T h_in[4 * 3] = {zero, zero, d1, d1, + zero, d0, d0, zero, + one, one, one, one}; + // clang-format on const Array tf = getArray(tf_); Array in = createHostDataArray(h_dims, h_in); diff --git a/src/api/c/transpose.cpp b/src/api/c/transpose.cpp index 33140b9978..17553f191f 100644 --- a/src/api/c/transpose.cpp +++ b/src/api/c/transpose.cpp @@ -90,7 +90,7 @@ af_err af_transpose_inplace(af_array in, const bool conjugate) { DIM_ASSERT(0, dims[0] == dims[1]); // If singleton element - if (dims[0] == 1) return AF_SUCCESS; + if (dims[0] == 1) { return AF_SUCCESS; } switch (type) { case f32: transpose_inplace(in, conjugate); break; diff --git a/src/api/c/unary.cpp b/src/api/c/unary.cpp index d5435d1883..c42cd4d4ff 100644 --- a/src/api/c/unary.cpp +++ b/src/api/c/unary.cpp @@ -201,7 +201,7 @@ struct unaryOpCplxFun { // log(r) Array a_out = unaryOp(r); // phi - Array b_out = phi; + const Array &b_out = phi; // log(r) + i * phi return cplx(a_out, b_out, a_out.dims()); @@ -631,14 +631,16 @@ static inline af_array checkOp(const af_array in) { template struct cplxLogicOp { - af_array operator()(Array resR, Array resI, dim4 dims) { + af_array operator()(const Array &resR, const Array &resI, + const dim4 &dims) { return getHandle(logicOp(resR, resI, dims)); } }; template<> struct cplxLogicOp { - af_array operator()(Array resR, Array resI, dim4 dims) { + af_array operator()(const Array &resR, const Array &resI, + const dim4 &dims) { return getHandle(logicOp(resR, resI, dims)); } }; @@ -652,7 +654,7 @@ static inline af_array checkOpCplx(const af_array in) { Array resI = checkOp(I); const ArrayInfo &in_info = getInfo(in); - dim4 dims = in_info.dims(); + const dim4 &dims = in_info.dims(); cplxLogicOp cplxLogic; af_array res = cplxLogic(resR, resI, dims); @@ -669,7 +671,7 @@ static af_err af_check(af_array *out, const af_array in) { // Convert all inputs to floats / doubles / complex af_dtype type = implicit(in_type, f32); - if (in_type == f16) type = f16; + if (in_type == f16) { type = f16; } switch (type) { case f32: res = checkOp(in); break; diff --git a/src/api/c/var.cpp b/src/api/c/var.cpp index 1a8d2010f2..8ad68943d9 100644 --- a/src/api/c/var.cpp +++ b/src/api/c/var.cpp @@ -35,9 +35,9 @@ using std::tuple; template static outType varAll(const af_array& in, const bool isbiased) { - typedef typename baseOutType::type weightType; - Array inArr = getArray(in); - Array input = cast(inArr); + using weightType = typename baseOutType::type; + const Array inArr = getArray(in); + Array input = cast(inArr); Array meanCnst = createValueArray( input.dims(), mean(inArr)); @@ -56,13 +56,13 @@ static outType varAll(const af_array& in, const bool isbiased) { template static outType varAll(const af_array& in, const af_array weights) { - typedef typename baseOutType::type bType; + using bType = typename baseOutType::type; Array input = cast(getArray(in)); Array wts = cast(getArray(weights)); bType wtsSum = reduce_all(getArray(weights)); - outType wtdMean = mean(input, getArray(weights)); + auto wtdMean = mean(input, getArray(weights)); Array meanArr = createValueArray(input.dims(), wtdMean); Array diff = @@ -83,7 +83,7 @@ static tuple, Array> meanvar( const Array& in, const Array::type>& weights, const af_var_bias bias, const dim_t dim) { - typedef typename baseOutType::type weightType; + using weightType = typename baseOutType::type; Array input = cast(in); dim4 iDims = input.dims(); @@ -129,7 +129,7 @@ static tuple meanvar(const af_array& in, const af_array& weights, const af_var_bias bias, const dim_t dim) { - typedef typename baseOutType::type weightType; + using weightType = typename baseOutType::type; Array mean = createEmptyArray({0}), var = createEmptyArray({0}); @@ -162,10 +162,9 @@ static af_array var_(const af_array& in, const af_array& weights, Array empty = createEmptyArray({0}); return getHandle( var(getArray(in), empty, bias, dim)); - } else { - return getHandle(var( - getArray(in), getArray(weights), bias, dim)); } + return getHandle(var(getArray(in), + getArray(weights), bias, dim)); } af_err af_var(af_array* out, const af_array in, const bool isbiased, diff --git a/src/api/c/vector_field.cpp b/src/api/c/vector_field.cpp index bb6fdc1d3f..6dcd6d083d 100644 --- a/src/api/c/vector_field.cpp +++ b/src/api/c/vector_field.cpp @@ -57,17 +57,19 @@ fg_chart setup_vector_field(fg_window window, const vector& points, fg_chart chart = NULL; if (pIn.dims()[0] == 2) { - if (props->col > -1 && props->row > -1) + if (props->col > -1 && props->row > -1) { chart = fgMngr.getChart(window, props->row, props->col, FG_CHART_2D); - else + } else { chart = fgMngr.getChart(window, 0, 0, FG_CHART_2D); + } } else { - if (props->col > -1 && props->row > -1) + if (props->col > -1 && props->row > -1) { chart = fgMngr.getChart(window, props->row, props->col, FG_CHART_3D); - else + } else { chart = fgMngr.getChart(window, 0, 0, FG_CHART_3D); + } } fg_vector_field vfield = @@ -93,16 +95,16 @@ fg_chart setup_vector_field(fg_window window, const vector& points, cmax[0] = step_round(dmax[0], true); cmin[1] = step_round(dmin[1], false); cmax[1] = step_round(dmax[1], true); - if (pIn.dims()[0] == 3) cmin[2] = step_round(dmin[2], false); - if (pIn.dims()[0] == 3) cmax[2] = step_round(dmax[2], true); + if (pIn.dims()[0] == 3) { cmin[2] = step_round(dmin[2], false); } + if (pIn.dims()[0] == 3) { cmax[2] = step_round(dmax[2], true); } } else { - if (cmin[0] > dmin[0]) cmin[0] = step_round(dmin[0], false); - if (cmax[0] < dmax[0]) cmax[0] = step_round(dmax[0], true); - if (cmin[1] > dmin[1]) cmin[1] = step_round(dmin[1], false); - if (cmax[1] < dmax[1]) cmax[1] = step_round(dmax[1], true); + if (cmin[0] > dmin[0]) { cmin[0] = step_round(dmin[0], false); } + if (cmax[0] < dmax[0]) { cmax[0] = step_round(dmax[0], true); } + if (cmin[1] > dmin[1]) { cmin[1] = step_round(dmin[1], false); } + if (cmax[1] < dmax[1]) { cmax[1] = step_round(dmax[1], true); } if (pIn.dims()[0] == 3) { - if (cmin[2] > dmin[2]) cmin[2] = step_round(dmin[2], false); - if (cmax[2] < dmax[2]) cmax[2] = step_round(dmax[2], true); + if (cmin[2] > dmin[2]) { cmin[2] = step_round(dmin[2], false); } + if (cmax[2] < dmax[2]) { cmax[2] = step_round(dmax[2], true); } } } FG_CHECK(_.fg_set_chart_axes_limits(chart, cmin[0], cmax[0], cmin[1], @@ -124,7 +126,7 @@ af_err vectorFieldWrapper(const af_window window, const af_array points, af_dtype pType = pInfo.getType(); const ArrayInfo& dInfo = getInfo(directions); - af::dim4 dDims = dInfo.dims(); + const af::dim4& dDims = dInfo.dims(); af_dtype dType = dInfo.getType(); DIM_ASSERT(0, pDims == dDims); @@ -193,9 +195,9 @@ af_err vectorFieldWrapper(const af_window window, const af_array xPoints, const ArrayInfo& ypInfo = getInfo(yPoints); const ArrayInfo& zpInfo = getInfo(zPoints); - af::dim4 xpDims = xpInfo.dims(); - af::dim4 ypDims = ypInfo.dims(); - af::dim4 zpDims = zpInfo.dims(); + af::dim4 xpDims = xpInfo.dims(); + const af::dim4& ypDims = ypInfo.dims(); + const af::dim4& zpDims = zpInfo.dims(); af_dtype xpType = xpInfo.getType(); af_dtype ypType = ypInfo.getType(); @@ -205,9 +207,9 @@ af_err vectorFieldWrapper(const af_window window, const af_array xPoints, const ArrayInfo& ydInfo = getInfo(yDirs); const ArrayInfo& zdInfo = getInfo(zDirs); - af::dim4 xdDims = xdInfo.dims(); - af::dim4 ydDims = ydInfo.dims(); - af::dim4 zdDims = zdInfo.dims(); + const af::dim4& xdDims = xdInfo.dims(); + const af::dim4& ydDims = ydInfo.dims(); + const af::dim4& zdDims = zdInfo.dims(); af_dtype xdType = xdInfo.getType(); af_dtype ydType = ydInfo.getType(); @@ -298,8 +300,8 @@ af_err vectorFieldWrapper(const af_window window, const af_array xPoints, const ArrayInfo& xpInfo = getInfo(xPoints); const ArrayInfo& ypInfo = getInfo(yPoints); - af::dim4 xpDims = xpInfo.dims(); - af::dim4 ypDims = ypInfo.dims(); + af::dim4 xpDims = xpInfo.dims(); + const af::dim4& ypDims = ypInfo.dims(); af_dtype xpType = xpInfo.getType(); af_dtype ypType = ypInfo.getType(); @@ -307,8 +309,8 @@ af_err vectorFieldWrapper(const af_window window, const af_array xPoints, const ArrayInfo& xdInfo = getInfo(xDirs); const ArrayInfo& ydInfo = getInfo(yDirs); - af::dim4 xdDims = xdInfo.dims(); - af::dim4 ydDims = ydInfo.dims(); + const af::dim4& xdDims = xdInfo.dims(); + const af::dim4& ydDims = ydInfo.dims(); af_dtype xdType = xdInfo.getType(); af_dtype ydType = ydInfo.getType(); diff --git a/src/api/c/where.cpp b/src/api/c/where.cpp index 8f2bf468fa..69b121323f 100644 --- a/src/api/c/where.cpp +++ b/src/api/c/where.cpp @@ -16,7 +16,6 @@ #include #include -using af::dim4; using namespace detail; template diff --git a/src/api/c/window.cpp b/src/api/c/window.cpp index 92da1b35fe..bcde57658d 100644 --- a/src/api/c/window.cpp +++ b/src/api/c/window.cpp @@ -15,7 +15,6 @@ #include #include -using af::dim4; using namespace detail; using namespace graphics; @@ -75,26 +74,27 @@ af_err af_set_axes_limits_compute(const af_window window, const af_array x, ForgeManager& fgMngr = forgeManager(); - fg_chart chart = NULL; + fg_chart chart = nullptr; fg_chart_type ctype = (z ? FG_CHART_3D : FG_CHART_2D); - if (props->col > -1 && props->row > -1) + if (props->col > -1 && props->row > -1) { chart = fgMngr.getChart(window, props->row, props->col, ctype); - else + } else { chart = fgMngr.getChart(window, 0, 0, ctype); + } - double xmin = -1, xmax = 1; - double ymin = -1, ymax = 1; - double zmin = -1, zmax = 1; - AF_CHECK(af_min_all(&xmin, NULL, x)); - AF_CHECK(af_max_all(&xmax, NULL, x)); - AF_CHECK(af_min_all(&ymin, NULL, y)); - AF_CHECK(af_max_all(&ymax, NULL, y)); + double xmin = -1., xmax = 1.; + double ymin = -1., ymax = 1.; + double zmin = -1., zmax = 1.; + AF_CHECK(af_min_all(&xmin, nullptr, x)); + AF_CHECK(af_max_all(&xmax, nullptr, x)); + AF_CHECK(af_min_all(&ymin, nullptr, y)); + AF_CHECK(af_max_all(&ymax, nullptr, y)); if (ctype == FG_CHART_3D) { - AF_CHECK(af_min_all(&zmin, NULL, z)); - AF_CHECK(af_max_all(&zmax, NULL, z)); + AF_CHECK(af_min_all(&zmin, nullptr, z)); + AF_CHECK(af_max_all(&zmax, nullptr, z)); } if (!exact) { @@ -123,21 +123,22 @@ af_err af_set_axes_limits_2d(const af_window window, const float xmin, ForgeManager& fgMngr = forgeManager(); - fg_chart chart = NULL; + fg_chart chart = nullptr; // The ctype here below doesn't really matter as it is only fetching // the chart. It will not set it. // If this is actually being done, then it is extremely bad. fg_chart_type ctype = FG_CHART_2D; - if (props->col > -1 && props->row > -1) + if (props->col > -1 && props->row > -1) { chart = fgMngr.getChart(window, props->row, props->col, ctype); - else + } else { chart = fgMngr.getChart(window, 0, 0, ctype); + } - float _xmin = xmin; - float _xmax = xmax; - float _ymin = ymin; - float _ymax = ymax; + double _xmin = xmin; + double _xmax = xmax; + double _ymin = ymin; + double _ymax = ymax; if (!exact) { _xmin = step_round(_xmin, false); _xmax = step_round(_xmax, true); @@ -163,23 +164,24 @@ af_err af_set_axes_limits_3d(const af_window window, const float xmin, ForgeManager& fgMngr = forgeManager(); - fg_chart chart = NULL; + fg_chart chart = nullptr; // The ctype here below doesn't really matter as it is only fetching // the chart. It will not set it. // If this is actually being done, then it is extremely bad. fg_chart_type ctype = FG_CHART_3D; - if (props->col > -1 && props->row > -1) + if (props->col > -1 && props->row > -1) { chart = fgMngr.getChart(window, props->row, props->col, ctype); - else + } else { chart = fgMngr.getChart(window, 0, 0, ctype); + } - float _xmin = xmin; - float _xmax = xmax; - float _ymin = ymin; - float _ymax = ymax; - float _zmin = zmin; - float _zmax = zmax; + double _xmin = xmin; + double _xmax = xmax; + double _ymin = ymin; + double _ymax = ymax; + double _zmin = zmin; + double _zmax = zmax; if (!exact) { _xmin = step_round(_xmin, false); _xmax = step_round(_xmax, true); @@ -205,14 +207,15 @@ af_err af_set_axes_titles(const af_window window, const char* const xtitle, ForgeManager& fgMngr = forgeManager(); - fg_chart chart = NULL; + fg_chart chart = nullptr; fg_chart_type ctype = (ztitle ? FG_CHART_3D : FG_CHART_2D); - if (props->col > -1 && props->row > -1) + if (props->col > -1 && props->row > -1) { chart = fgMngr.getChart(window, props->row, props->col, ctype); - else + } else { chart = fgMngr.getChart(window, 0, 0, ctype); + } FG_CHECK(forgePlugin().fg_set_chart_axes_titles(chart, xtitle, ytitle, ztitle)); @@ -238,10 +241,11 @@ af_err af_set_axes_label_format(const af_window window, fg_chart_type ctype = (zformat ? FG_CHART_3D : FG_CHART_2D); - if (props->col > -1 && props->row > -1) + if (props->col > -1 && props->row > -1) { chart = fgMngr.getChart(window, props->row, props->col, ctype); - else + } else { chart = fgMngr.getChart(window, 0, 0, ctype); + } if (ctype == FG_CHART_2D) { FG_CHECK(forgePlugin().fg_set_chart_label_format(chart, xformat, diff --git a/src/api/c/wrap.cpp b/src/api/c/wrap.cpp index 4736f14399..011c86ca88 100644 --- a/src/api/c/wrap.cpp +++ b/src/api/c/wrap.cpp @@ -19,11 +19,10 @@ using af::dim4; using namespace detail; template -static inline void wrap(af_array* out, const af_array in, const dim_t ox, - const dim_t oy, const dim_t wx, const dim_t wy, - const dim_t sx, const dim_t sy, const dim_t px, - const dim_t py, const bool is_column) { - wrap(getArray(*out), getArray(in), ox, oy, wx, wy, sx, sy, px, py, +static inline void wrap(af_array* out, const af_array in, const dim_t wx, + const dim_t wy, const dim_t sx, const dim_t sy, + const dim_t px, const dim_t py, const bool is_column) { + wrap(getArray(*out), getArray(in), wx, wy, sx, sy, px, py, is_column); } @@ -36,7 +35,7 @@ void af_wrap_common(af_array* out, const af_array in, const dim_t ox, const ArrayInfo& info = getInfo(in); const af_dtype in_type = info.getType(); - const dim4 in_dims = info.dims(); + const dim4& in_dims = info.dims(); const dim4 out_dims(ox, oy, in_dims[2], in_dims[3]); ARG_ASSERT(4, wx > 0); @@ -60,18 +59,18 @@ void af_wrap_common(af_array* out, const af_array in, const dim_t ox, // clang-format off switch(in_type) { - case f32: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case f64: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case c32: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case c64: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case s32: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case u32: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case s64: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case u64: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case s16: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case u16: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case u8: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; - case b8: wrap(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column); break; + case f32: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case f64: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case c32: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case c64: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case s32: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case u32: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case s64: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case u64: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case s16: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case u16: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case u8: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; + case b8: wrap(out, in, wx, wy, sx, sy, px, py, is_column); break; default: TYPE_ERROR(1, in_type); } // clang-format on diff --git a/src/api/c/ycbcr_rgb.cpp b/src/api/c/ycbcr_rgb.cpp index 1ee1065085..40ea20c8fd 100644 --- a/src/api/c/ycbcr_rgb.cpp +++ b/src/api/c/ycbcr_rgb.cpp @@ -23,7 +23,7 @@ using namespace detail; template static Array mix(const Array& X, const Array& Y, double xf, double yf) { - dim4 dims = X.dims(); + const dim4& dims = X.dims(); Array xf_cnst = createValueArray(dims, xf); Array yf_cnst = createValueArray(dims, yf); @@ -36,7 +36,7 @@ static Array mix(const Array& X, const Array& Y, double xf, template static Array mix(const Array& X, const Array& Y, const Array& Z, double xf, double yf, double zf) { - dim4 dims = X.dims(); + const dim4& dims = X.dims(); Array xf_cnst = createValueArray(dims, xf); Array yf_cnst = createValueArray(dims, yf); Array zf_cnst = createValueArray(dims, zf); @@ -52,10 +52,10 @@ static Array mix(const Array& X, const Array& Y, const Array& Z, template static Array digitize(const Array ch, const double scale, const double offset) { - dim4 dims = ch.dims(); - Array base = createValueArray(dims, scalar(offset)); - Array cnst = createValueArray(dims, scalar(scale)); - Array scl = arithOp(ch, cnst, dims); + const dim4& dims = ch.dims(); + Array base = createValueArray(dims, scalar(offset)); + Array cnst = createValueArray(dims, scalar(scale)); + Array scl = arithOp(ch, cnst, dims); return arithOp(scl, base, dims); } @@ -79,7 +79,7 @@ static af_array convert(const af_array& in, const af_ycc_std standard) { // extract three channels as three slices // prepare sequence objects // get Array objects for corresponding channel views - const Array& input = getArray(in); + const Array input = getArray(in); std::vector indices(4, af_span); indices[2] = {0, 0, 1}; @@ -92,13 +92,13 @@ static af_array convert(const af_array& in, const af_ycc_std standard) { Array Z = createSubArray(input, indices, false); if (isYCbCr2RGB) { - dim4 dims = X.dims(); - Array yc = createValueArray(dims, 16); - Array cc = createValueArray(dims, 128); - Array Y_ = arithOp(X, yc, dims); - Array Cb_ = arithOp(Y, cc, dims); - Array Cr_ = arithOp(Z, cc, dims); - Array R = mix(Y_, Cr_, INV_219, INV_112 * (1 - kr)); + const dim4& dims = X.dims(); + Array yc = createValueArray(dims, 16); + Array cc = createValueArray(dims, 128); + Array Y_ = arithOp(X, yc, dims); + Array Cb_ = arithOp(Y, cc, dims); + Array Cr_ = arithOp(Z, cc, dims); + Array R = mix(Y_, Cr_, INV_219, INV_112 * (1 - kr)); Array G = mix(Y_, Cr_, Cb_, INV_219, INV_112 * (kr - 1) * kr * invKl, INV_112 * (kb - 1) * kb * invKl); @@ -106,19 +106,18 @@ static af_array convert(const af_array& in, const af_ycc_std standard) { // join channels Array RG = join(2, R, G); return getHandle(join(2, RG, B)); - } else { - Array Ey = mix(X, Y, Z, kr, kl, kb); - Array Ecr = - mix(X, Y, Z, 0.5, 0.5 * kl / (kr - 1), 0.5 * kb / (kr - 1)); - Array Ecb = - mix(X, Y, Z, 0.5 * kr / (kb - 1), 0.5 * kl / (kb - 1), 0.5); - Array Y = digitize(Ey, 219.0, 16.0); - Array Cr = digitize(Ecr, 224.0, 128.0); - Array Cb = digitize(Ecb, 224.0, 128.0); - // join channels - Array YCb = join(2, Y, Cb); - return getHandle(join(2, YCb, Cr)); } + Array Ey = mix(X, Y, Z, kr, kl, kb); + Array Ecr = + mix(X, Y, Z, 0.5, 0.5 * kl / (kr - 1), 0.5 * kb / (kr - 1)); + Array Ecb = + mix(X, Y, Z, 0.5 * kr / (kb - 1), 0.5 * kl / (kb - 1), 0.5); + Array Y_ = digitize(Ey, 219.0, 16.0); + Array Cr = digitize(Ecr, 224.0, 128.0); + Array Cb = digitize(Ecb, 224.0, 128.0); + // join channels + Array YCb = join(2, Y_, Cb); + return getHandle(join(2, YCb, Cr)); } template diff --git a/src/api/cpp/array.cpp b/src/api/cpp/array.cpp index 2e75293867..eff157bfd5 100644 --- a/src/api/cpp/array.cpp +++ b/src/api/cpp/array.cpp @@ -89,7 +89,7 @@ af::dim4 seqToDims(af_index_t *indices, af::dim4 parentDims, } } return odims; - } catch (logic_error &err) { AF_THROW_ERR(err.what(), AF_ERR_SIZE); } + } catch (const logic_error &err) { AF_THROW_ERR(err.what(), AF_ERR_SIZE); } } unsigned numDims(const af_array arr) { @@ -137,12 +137,16 @@ af_array initDataArray(const void *ptr, int ty, af::source src, dim_t d0, namespace af { struct array::array_proxy::array_proxy_impl { - array *parent_; //< The original array + // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) + array *parent_; //< The original array + // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) af_index_t indices_[4]; //< Indexing array or seq objects + // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) bool is_linear_; // if true the parent_ object will be deleted on distruction. This is // necessary only when calling indexing functions in array_proxy objects. + // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) bool delete_on_destruction_; array_proxy_impl(array &parent, af_index_t *idx, bool linear) : parent_(&parent) @@ -194,7 +198,7 @@ array::array(dim_t dim0, dim_t dim1, dim_t dim2, dim_t dim3, af::dtype ty) template<> struct dtype_traits { enum { af_type = f16, ctype = f16 }; - typedef half base_type; + using base_type = half; static const char *getName() { return "half"; } }; @@ -292,7 +296,7 @@ array::~array() { } #else // THOU SHALL NOT THROW IN DESTRUCTORS - if (af_array arr = get()) af_release_array(arr); + if (af_array arr = get()) { af_release_array(arr); } #endif } @@ -386,6 +390,7 @@ array::array_proxy array::operator()(const index &s0, const index &s1, return const_cast(this)->operator()(s0, s1, s2, s3); } +// NOLINTNEXTLINE(readability-const-return-type) const array::array_proxy array::operator()(const index &s0) const { index z = index(0); if (isvector()) { @@ -401,12 +406,14 @@ const array::array_proxy array::operator()(const index &s0) const { } } +// NOLINTNEXTLINE(readability-const-return-type) const array::array_proxy array::operator()(const index &s0, const index &s1, const index &s2, const index &s3) const { return gen_indexing(*this, s0, s1, s2, s3); } +// NOLINTNEXTLINE(readability-const-return-type) const array::array_proxy array::row(int index) const { return this->operator()(index, span, span, span); } @@ -415,6 +422,7 @@ array::array_proxy array::row(int index) { return const_cast(this)->row(index); } +// NOLINTNEXTLINE(readability-const-return-type) const array::array_proxy array::col(int index) const { return this->operator()(span, index, span, span); } @@ -423,6 +431,7 @@ array::array_proxy array::col(int index) { return const_cast(this)->col(index); } +// NOLINTNEXTLINE(readability-const-return-type) const array::array_proxy array::slice(int index) const { return this->operator()(span, span, index, span); } @@ -431,6 +440,7 @@ array::array_proxy array::slice(int index) { return const_cast(this)->slice(index); } +// NOLINTNEXTLINE(readability-const-return-type) const array::array_proxy array::rows(int first, int last) const { seq idx(first, last, 1); return this->operator()(idx, span, span, span); @@ -440,6 +450,7 @@ array::array_proxy array::rows(int first, int last) { return const_cast(this)->rows(first, last); } +// NOLINTNEXTLINE(readability-const-return-type) const array::array_proxy array::cols(int first, int last) const { seq idx(first, last, 1); return this->operator()(span, idx, span, span); @@ -449,6 +460,7 @@ array::array_proxy array::cols(int first, int last) { return const_cast(this)->cols(first, last); } +// NOLINTNEXTLINE(readability-const-return-type) const array::array_proxy array::slices(int first, int last) const { seq idx(first, last, 1); return this->operator()(span, span, idx, span); @@ -458,6 +470,7 @@ array::array_proxy array::slices(int first, int last) { return const_cast(this)->slices(first, last); } +// NOLINTNEXTLINE(readability-const-return-type) const array array::as(af::dtype type) const { af_array out; AF_THROW(af_cast(&out, this->get(), type)); @@ -576,6 +589,7 @@ array::array_proxy &af::array::array_proxy::operator=(const array &other) { array::array_proxy &af::array::array_proxy::operator=( const array::array_proxy &other) { + if (this == &other) { return *this; } array out = other; *this = out; return *this; @@ -588,6 +602,7 @@ af::array::array_proxy::array_proxy(const array_proxy &other) : impl(new array_proxy_impl(*other.impl->parent_, other.impl->indices_, other.impl->is_linear_)) {} +// NOLINTNEXTLINE(hicpp-noexcept-move) too late to change public API af::array::array_proxy::array_proxy(array_proxy &&other) { impl = other.impl; other.impl = nullptr; @@ -758,12 +773,17 @@ array::array_proxy::operator array() { proxy.impl->delete_on_destruction(true); \ return proxy; \ } - +// NOLINTNEXTLINE(readability-const-return-type) MEM_INDEX(row(int index), row(index)); +// NOLINTNEXTLINE(readability-const-return-type) MEM_INDEX(rows(int first, int last), rows(first, last)); +// NOLINTNEXTLINE(readability-const-return-type) MEM_INDEX(col(int index), col(index)); +// NOLINTNEXTLINE(readability-const-return-type) MEM_INDEX(cols(int first, int last), cols(first, last)); +// NOLINTNEXTLINE(readability-const-return-type) MEM_INDEX(slice(int index), slice(index)); +// NOLINTNEXTLINE(readability-const-return-type) MEM_INDEX(slices(int first, int last), slices(first, last)); #undef MEM_INDEX @@ -772,7 +792,7 @@ MEM_INDEX(slices(int first, int last), slices(first, last)); // Operator = /////////////////////////////////////////////////////////////////////////// array &array::operator=(const array &other) { - if (this->get() == other.get()) { return *this; } + if (this == &other || this->get() == other.get()) { return *this; } // TODO(umar): Unsafe. loses data if af_weak_copy fails if (this->arr != nullptr) { AF_THROW(af_release_array(this->arr)); } @@ -1067,6 +1087,8 @@ INSTANTIATE(half_float::half) // FIXME: These functions need to be implemented properly at a later point void array::array_proxy::unlock() const {} void array::array_proxy::lock() const {} + +// NOLINTNEXTLINE(readability-convert-member-functions-to-static) bool array::array_proxy::isLocked() const { return false; } int array::nonzeros() const { return count(*this); } diff --git a/src/api/cpp/blas.cpp b/src/api/cpp/blas.cpp index b985dd863b..fbff177818 100644 --- a/src/api/cpp/blas.cpp +++ b/src/api/cpp/blas.cpp @@ -38,8 +38,8 @@ array matmulTT(const array &lhs, const array &rhs) { } array matmul(const array &a, const array &b, const array &c) { - int tmp1 = a.dims(0) * b.dims(1); - int tmp2 = b.dims(0) * c.dims(1); + dim_t tmp1 = a.dims(0) * b.dims(1); + dim_t tmp2 = b.dims(0) * c.dims(1); if (tmp1 < tmp2) { return matmul(matmul(a, b), c); @@ -49,8 +49,8 @@ array matmul(const array &a, const array &b, const array &c) { } array matmul(const array &a, const array &b, const array &c, const array &d) { - int tmp1 = a.dims(0) * c.dims(1); - int tmp2 = b.dims(0) * d.dims(1); + dim_t tmp1 = a.dims(0) * c.dims(1); + dim_t tmp2 = b.dims(0) * d.dims(1); if (tmp1 < tmp2) { return matmul(matmul(a, b, c), d); diff --git a/src/api/cpp/convolve.cpp b/src/api/cpp/convolve.cpp index a74710d1d1..a69d26b9b4 100644 --- a/src/api/cpp/convolve.cpp +++ b/src/api/cpp/convolve.cpp @@ -25,8 +25,8 @@ array convolve(const array &signal, const array &filter, const convMode mode, switch (std::min(sN, fN)) { case 1: return convolve1(signal, filter, mode, domain); case 2: return convolve2(signal, filter, mode, domain); + default: case 3: return convolve3(signal, filter, mode, domain); - default: return convolve3(signal, filter, mode, domain); } } @@ -52,20 +52,24 @@ array convolve2(const array &signal, const array &filter, const convMode mode, return array(out); } -array convolve2NN(const array &signal, const array &filter, const dim4 stride, - const dim4 padding, const dim4 dilation) { +array convolve2NN( + const array &signal, const array &filter, + const dim4 stride, // NOLINT(performance-unnecessary-value-param) + const dim4 padding, // NOLINT(performance-unnecessary-value-param) + const dim4 dilation) { // NOLINT(performance-unnecessary-value-param) af_array out = 0; AF_THROW(af_convolve2_nn(&out, signal.get(), filter.get(), 2, stride.get(), 2, padding.get(), 2, dilation.get())); return array(out); } -array convolve2GradientNN(const array &incoming_gradient, - const array &original_signal, - const array &original_filter, - const array &convolved_output, const dim4 stride, - const dim4 padding, const dim4 dilation, - af_conv_gradient_type gradType) { +array convolve2GradientNN( + const array &incoming_gradient, const array &original_signal, + const array &original_filter, const array &convolved_output, + const dim4 stride, // NOLINT(performance-unnecessary-value-param) + const dim4 padding, // NOLINT(performance-unnecessary-value-param) + const dim4 dilation, // NOLINT(performance-unnecessary-value-param) + af_conv_gradient_type gradType) { af_array out = 0; AF_THROW(af_convolve2_gradient_nn( &out, incoming_gradient.get(), original_signal.get(), diff --git a/src/api/cpp/data.cpp b/src/api/cpp/data.cpp index 3c68386a11..126b10d990 100644 --- a/src/api/cpp/data.cpp +++ b/src/api/cpp/data.cpp @@ -44,14 +44,15 @@ struct is_complex { array constant(af_half val, const dim4 &dims, const dtype type) { af_array res; + UNUSED(val); AF_THROW(af_constant(&res, 0, //(double)val, dims.ndims(), dims.get(), type)); return array(res); } -template::value == false, T>::type> -array constant(T val, const dim4 &dims, const dtype type) { +template(is_complex::value), T>::type> +array constant(T val, const dim4 &dims, dtype type) { af_array res; if (type != s64 && type != u64) { AF_THROW( @@ -67,8 +68,8 @@ array constant(T val, const dim4 &dims, const dtype type) { } template -typename enable_if::value == true, array>::type constant( - T val, const dim4 &dims, const dtype type) { +typename enable_if(is_complex::value), array>::type +constant(T val, const dim4 &dims, const dtype type) { if (type != c32 && type != c64) { return ::constant(real(val), dims, type); } diff --git a/src/api/cpp/device.cpp b/src/api/cpp/device.cpp index 52f783e576..524ebe0bb6 100644 --- a/src/api/cpp/device.cpp +++ b/src/api/cpp/device.cpp @@ -31,7 +31,7 @@ int getAvailableBackends() { } af::Backend getBackendId(const array &in) { - af::Backend result = (af::Backend)0; + auto result = static_cast(0); AF_THROW(af_get_backend_id(&result, in.get())); return result; } @@ -44,7 +44,7 @@ int getDeviceId(const array &in) { } af::Backend getActiveBackend() { - af::Backend result = (af::Backend)0; + auto result = static_cast(0); AF_THROW(af_get_active_backend(&result)); return result; } @@ -54,7 +54,7 @@ void info() { AF_THROW(af_info()); } const char *infoString(const bool verbose) { char *str = NULL; AF_THROW(af_info_string(&str, verbose)); - return (const char *)str; + return str; } void deviceprop(char *d_name, char *d_platform, char *d_toolkit, diff --git a/src/api/cpp/error.hpp b/src/api/cpp/error.hpp index 4e4a464cce..37e03fc0e5 100644 --- a/src/api/cpp/error.hpp +++ b/src/api/cpp/error.hpp @@ -20,7 +20,7 @@ af::exception ex(msg, __PRETTY_FUNCTION__, __AF_FILENAME__, __LINE__, \ __err); \ af_free_host(msg); \ - throw ex; /* NOLINT(misc-throw-by-value-catch-by-reference)*/ \ + throw std::move(ex); \ } while (0) #define AF_THROW_ERR(__msg, __err) \ diff --git a/src/api/cpp/event.cpp b/src/api/cpp/event.cpp index 577700399f..47a70e3491 100644 --- a/src/api/cpp/event.cpp +++ b/src/api/cpp/event.cpp @@ -12,13 +12,13 @@ namespace af { -event::event() { AF_THROW(af_create_event(&e_)); } +event::event() : e_{} { AF_THROW(af_create_event(&e_)); } event::event(af_event e) : e_(e) {} event::~event() { // No dtor throw - if (e_) af_delete_event(e_); + if (e_) { af_delete_event(e_); } } event::event(event&& other) : e_(other.e_) { other.e_ = 0; } diff --git a/src/api/cpp/exception.cpp b/src/api/cpp/exception.cpp index 523da68a84..8a56a48ea2 100644 --- a/src/api/cpp/exception.cpp +++ b/src/api/cpp/exception.cpp @@ -7,10 +7,10 @@ * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ -#include -#include // strncpy #include #include +#include +#include // strncpy #ifdef OS_WIN #define snprintf _snprintf @@ -18,38 +18,40 @@ namespace af { -exception::exception() : m_err(AF_ERR_UNKNOWN) { +exception::exception() : m_msg{}, m_err(AF_ERR_UNKNOWN) { strncpy(m_msg, "unknown exception", sizeof(m_msg)); } -exception::exception(const char *msg) : m_err(AF_ERR_UNKNOWN) { +exception::exception(const char *msg) : m_msg{}, m_err(AF_ERR_UNKNOWN) { strncpy(m_msg, msg, sizeof(m_msg)); m_msg[sizeof(m_msg) - 1] = '\0'; } -exception::exception(const char *file, unsigned line, af_err err) : m_err(err) { +exception::exception(const char *file, unsigned line, af_err err) + : m_msg{}, m_err(err) { snprintf(m_msg, sizeof(m_msg) - 1, "ArrayFire Exception (%s:%d):\nIn %s:%u", - af_err_to_string(err), (int)err, file, line); + af_err_to_string(err), static_cast(err), file, line); m_msg[sizeof(m_msg) - 1] = '\0'; } exception::exception(const char *msg, const char *file, unsigned line, af_err err) - : m_err(err) { + : m_msg{}, m_err(err) { snprintf(m_msg, sizeof(m_msg) - 1, "ArrayFire Exception (%s:%d):\n%s\nIn %s:%u", - af_err_to_string(err), (int)(err), msg, file, line); + af_err_to_string(err), static_cast(err), msg, file, line); m_msg[sizeof(m_msg) - 1] = '\0'; } exception::exception(const char *msg, const char *func, const char *file, unsigned line, af_err err) - : m_err(err) { + : m_msg{}, m_err(err) { snprintf(m_msg, sizeof(m_msg) - 1, "ArrayFire Exception (%s:%d):\n%s\nIn function %s\nIn file %s:%u", - af_err_to_string(err), (int)(err), msg, func, file, line); + af_err_to_string(err), static_cast(err), msg, func, file, + line); m_msg[sizeof(m_msg) - 1] = '\0'; } diff --git a/src/api/cpp/features.cpp b/src/api/cpp/features.cpp index d84e39ff53..96a669b5ab 100644 --- a/src/api/cpp/features.cpp +++ b/src/api/cpp/features.cpp @@ -13,9 +13,9 @@ namespace af { -features::features() { AF_THROW(af_create_features(&feat, 0)); } +features::features() : feat{} { AF_THROW(af_create_features(&feat, 0)); } -features::features(const size_t n) { +features::features(const size_t n) : feat{} { AF_THROW(af_create_features(&feat, (int)n)); } diff --git a/src/api/cpp/fft.cpp b/src/api/cpp/fft.cpp index f72038a2f3..dbce09f488 100644 --- a/src/api/cpp/fft.cpp +++ b/src/api/cpp/fft.cpp @@ -12,6 +12,9 @@ #include #include "error.hpp" +using af::array; +using af::dim4; + namespace af { array fftNorm(const array& in, const double norm_factor, const dim_t odim0) { af_array out = 0; @@ -46,6 +49,7 @@ array fft3(const array& in, const dim_t odim0, const dim_t odim1, return fft3Norm(in, 1.0, odim0, odim1, odim2); } +// NOLINTNEXTLINE(performance-unnecessary-value-param) array dft(const array& in, const double norm_factor, const dim4 outDims) { array temp; switch (in.dims().ndims()) { @@ -60,6 +64,7 @@ array dft(const array& in, const double norm_factor, const dim4 outDims) { return temp; } +// NOLINTNEXTLINE(performance-unnecessary-value-param) array dft(const array& in, const dim4 outDims) { return dft(in, 1.0, outDims); } array dft(const array& in) { return dft(in, 1.0, dim4(0, 0, 0, 0)); } @@ -87,7 +92,7 @@ array ifft3Norm(const array& in, const double norm_factor, const dim_t odim0, array ifft(const array& in, const dim_t odim0) { const dim4 dims = in.dims(); dim_t dim0 = odim0 == 0 ? dims[0] : odim0; - double norm_factor = 1.0 / dim0; + double norm_factor = 1.0 / static_cast(dim0); return ifftNorm(in, norm_factor, odim0); } @@ -95,7 +100,7 @@ array ifft2(const array& in, const dim_t odim0, const dim_t odim1) { const dim4 dims = in.dims(); dim_t dim0 = odim0 == 0 ? dims[0] : odim0; dim_t dim1 = odim1 == 0 ? dims[1] : odim1; - double norm_factor = 1.0 / (dim0 * dim1); + double norm_factor = 1.0 / static_cast(dim0 * dim1); return ifft2Norm(in, norm_factor, odim0, odim1); } @@ -105,10 +110,11 @@ array ifft3(const array& in, const dim_t odim0, const dim_t odim1, dim_t dim0 = odim0 == 0 ? dims[0] : odim0; dim_t dim1 = odim1 == 0 ? dims[1] : odim1; dim_t dim2 = odim2 == 0 ? dims[2] : odim2; - double norm_factor = 1.0 / (dim0 * dim1 * dim2); + double norm_factor = 1.0 / static_cast(dim0 * dim1 * dim2); return ifft3Norm(in, norm_factor, odim0, odim1, odim2); } +// NOLINTNEXTLINE(performance-unnecessary-value-param) array idft(const array& in, const double norm_factor, const dim4 outDims) { array temp; switch (in.dims().ndims()) { @@ -125,6 +131,7 @@ array idft(const array& in, const double norm_factor, const dim4 outDims) { return temp; } +// NOLINTNEXTLINE(performance-unnecessary-value-param) array idft(const array& in, const dim4 outDims) { return idft(in, 1.0, outDims); } @@ -145,19 +152,20 @@ void fft3InPlace(array& in, const double norm_factor) { void ifftInPlace(array& in, const double norm_factor) { const dim4 dims = in.dims(); - double norm = norm_factor * (1.0 / dims[0]); + double norm = norm_factor * (1.0 / static_cast(dims[0])); AF_THROW(af_ifft_inplace(in.get(), norm)); } void ifft2InPlace(array& in, const double norm_factor) { const dim4 dims = in.dims(); - double norm = norm_factor * (1.0 / (dims[0] * dims[1])); + double norm = norm_factor * (1.0 / static_cast(dims[0] * dims[1])); AF_THROW(af_ifft2_inplace(in.get(), norm)); } void ifft3InPlace(array& in, const double norm_factor) { const dim4 dims = in.dims(); - double norm = norm_factor * (1.0 / (dims[0] * dims[1] * dims[2])); + double norm = + norm_factor * (1.0 / static_cast(dims[0] * dims[1] * dims[2])); AF_THROW(af_ifft3_inplace(in.get(), norm)); } @@ -200,7 +208,7 @@ AFAPI array fftC2R<1>(const array& in, const bool is_odd, if (norm == 0) { dim4 idims = in.dims(); dim_t dim0 = getOrigDim(idims[0], is_odd); - norm = 1.0 / dim0; + norm = 1.0 / static_cast(dim0); } af_array res; @@ -217,7 +225,7 @@ AFAPI array fftC2R<2>(const array& in, const bool is_odd, dim4 idims = in.dims(); dim_t dim0 = getOrigDim(idims[0], is_odd); dim_t dim1 = idims[1]; - norm = 1.0 / (dim0 * dim1); + norm = 1.0 / static_cast(dim0 * dim1); } af_array res; @@ -235,7 +243,7 @@ AFAPI array fftC2R<3>(const array& in, const bool is_odd, dim_t dim0 = getOrigDim(idims[0], is_odd); dim_t dim1 = idims[1]; dim_t dim2 = idims[2]; - norm = 1.0 / (dim0 * dim1 * dim2); + norm = 1.0 / static_cast(dim0 * dim1 * dim2); } af_array res; diff --git a/src/api/cpp/fftconvolve.cpp b/src/api/cpp/fftconvolve.cpp index 61fbf9937c..24f68b103b 100644 --- a/src/api/cpp/fftconvolve.cpp +++ b/src/api/cpp/fftconvolve.cpp @@ -22,8 +22,8 @@ array fftConvolve(const array& signal, const array& filter, switch (std::min(sN, fN)) { case 1: return fftConvolve1(signal, filter, mode); case 2: return fftConvolve2(signal, filter, mode); + default: case 3: return fftConvolve3(signal, filter, mode); - default: return fftConvolve3(signal, filter, mode); } } diff --git a/src/api/cpp/gfor.cpp b/src/api/cpp/gfor.cpp index fa37fd9ef1..f97ad1c34f 100644 --- a/src/api/cpp/gfor.cpp +++ b/src/api/cpp/gfor.cpp @@ -29,8 +29,9 @@ bool gforToggle() { } array batchFunc(const array &lhs, const array &rhs, batchFunc_t func) { - if (gforGet()) + if (gforGet()) { AF_THROW_ERR("batchFunc can not be used inside GFOR", AF_ERR_ARG); + } gforSet(true); array res = func(lhs, rhs); gforSet(false); diff --git a/src/api/cpp/index.cpp b/src/api/cpp/index.cpp index bbc22bfdf0..68908c007c 100644 --- a/src/api/cpp/index.cpp +++ b/src/api/cpp/index.cpp @@ -32,31 +32,31 @@ void copy(array &dst, const array &src, const index &idx0, const index &idx1, AF_THROW(af_assign_gen(&lhs, lhs, nd, indices, rhs)); } -index::index() { +index::index() : impl{} { impl.idx.seq = af_span; impl.isSeq = true; impl.isBatch = false; } -index::index(const int idx) { +index::index(const int idx) : impl{} { impl.idx.seq = af_make_seq(idx, idx, 1); impl.isSeq = true; impl.isBatch = false; } -index::index(const af::seq &s0) { +index::index(const af::seq &s0) : impl{} { impl.idx.seq = s0.s; impl.isSeq = true; impl.isBatch = s0.m_gfor; } -index::index(const af_seq &s0) { +index::index(const af_seq &s0) : impl{} { impl.idx.seq = s0; impl.isSeq = true; impl.isBatch = false; } -index::index(const af::array &idx0) { +index::index(const af::array &idx0) : impl{} { array idx = idx0.isbool() ? where(idx0) : idx0; af_array arr = 0; AF_THROW(af_retain_array(&arr, idx.get())); @@ -66,15 +66,20 @@ index::index(const af::array &idx0) { impl.isBatch = false; } -index::index(const af::index &idx0) { *this = idx0; } +index::index(const af::index &idx0) : impl{idx0.impl} {} // NOLINT + +// NOLINTNEXTLINE(hicpp-noexcept-move) +index::index(index &&idx0) : impl{idx0.impl} { idx0.impl.idx.arr = nullptr; } index::~index() { - if (!impl.isSeq && impl.idx.arr) af_release_array(impl.idx.arr); + if (!impl.isSeq && impl.idx.arr) { af_release_array(impl.idx.arr); } } index &index::operator=(const index &idx0) { + if (this == &idx0) { return *this; } + impl = idx0.get(); - if (impl.isSeq == false) { + if (!impl.isSeq) { // increment reference count to avoid double free // when/if idx0 is destroyed AF_THROW(af_retain_array(&impl.idx.arr, impl.idx.arr)); @@ -82,11 +87,7 @@ index &index::operator=(const index &idx0) { return *this; } -index::index(index &&idx0) { - impl = idx0.impl; - idx0.impl.idx.arr = nullptr; -} - +// NOLINTNEXTLINE(hicpp-noexcept-move) index &index::operator=(index &&idx0) { impl = idx0.impl; idx0.impl.idx.arr = nullptr; @@ -97,9 +98,7 @@ static bool operator==(const af_seq &lhs, const af_seq &rhs) { return lhs.begin == rhs.begin && lhs.end == rhs.end && lhs.step == rhs.step; } -bool index::isspan() const { - return impl.isSeq == true && impl.idx.seq == af_span; -} +bool index::isspan() const { return impl.isSeq && impl.idx.seq == af_span; } const af_index_t &index::get() const { return impl; } diff --git a/src/api/cpp/internal.cpp b/src/api/cpp/internal.cpp index b2d14360a2..e6760b7fe7 100644 --- a/src/api/cpp/internal.cpp +++ b/src/api/cpp/internal.cpp @@ -12,9 +12,11 @@ #include "error.hpp" namespace af { -array createStridedArray(const void *data, const dim_t offset, const dim4 dims, - const dim4 strides, const af::dtype ty, - const af::source location) { +array createStridedArray( + const void *data, const dim_t offset, + const dim4 dims, // NOLINT(performance-unnecessary-value-param) + const dim4 strides, // NOLINT(performance-unnecessary-value-param) + const af::dtype ty, const af::source location) { af_array res; AF_THROW(af_create_strided_array(&res, data, offset, dims.ndims(), dims.get(), strides.get(), ty, location)); diff --git a/src/api/cpp/mean.cpp b/src/api/cpp/mean.cpp index 55c0a02335..c03a83fa51 100644 --- a/src/api/cpp/mean.cpp +++ b/src/api/cpp/mean.cpp @@ -52,28 +52,28 @@ template<> AFAPI af_cfloat mean(const array& in) { double real, imag; AF_THROW(af_mean_all(&real, &imag, in.get())); - return af_cfloat((float)real, (float)imag); + return {static_cast(real), static_cast(imag)}; } template<> AFAPI af_cdouble mean(const array& in) { double real, imag; AF_THROW(af_mean_all(&real, &imag, in.get())); - return af_cdouble(real, imag); + return {real, imag}; } template<> AFAPI af_cfloat mean(const array& in, const array& weights) { double real, imag; AF_THROW(af_mean_all_weighted(&real, &imag, in.get(), weights.get())); - return af_cfloat((float)real, (float)imag); + return {static_cast(real), static_cast(imag)}; } template<> AFAPI af_cdouble mean(const array& in, const array& weights) { double real, imag; AF_THROW(af_mean_all_weighted(&real, &imag, in.get(), weights.get())); - return af_cdouble(real, imag); + return {real, imag}; } INSTANTIATE_MEAN(float); diff --git a/src/api/cpp/random.cpp b/src/api/cpp/random.cpp index 57751a2bec..821f5c70fe 100644 --- a/src/api/cpp/random.cpp +++ b/src/api/cpp/random.cpp @@ -25,7 +25,7 @@ randomEngine::randomEngine(const randomEngine &other) : engine(0) { } } -randomEngine::randomEngine(af_random_engine handle) : engine(handle) {} +randomEngine::randomEngine(af_random_engine engine) : engine(engine) {} randomEngine::~randomEngine() { if (engine) { af_release_random_engine(engine); } @@ -39,7 +39,7 @@ randomEngine &randomEngine::operator=(const randomEngine &other) { return *this; } -randomEngineType randomEngine::getType(void) { +randomEngineType randomEngine::getType() { af_random_engine_type type; AF_THROW(af_random_engine_get_type(&type, engine)); return type; @@ -53,13 +53,13 @@ void randomEngine::setSeed(const unsigned long long seed) { AF_THROW(af_random_engine_set_seed(&engine, seed)); } -unsigned long long randomEngine::getSeed(void) const { +unsigned long long randomEngine::getSeed() const { unsigned long long seed; AF_THROW(af_random_engine_get_seed(&seed, engine)); return seed; } -af_random_engine randomEngine::get(void) const { return engine; } +af_random_engine randomEngine::get() const { return engine; } array randu(const dim4 &dims, const dtype ty, randomEngine &r) { af_array out; @@ -121,7 +121,7 @@ void setDefaultRandomEngineType(randomEngineType rtype) { AF_THROW(af_set_default_random_engine_type(rtype)); } -randomEngine getDefaultRandomEngine(void) { +randomEngine getDefaultRandomEngine() { af_random_engine internal_handle = 0; af_random_engine handle = 0; AF_THROW(af_get_default_random_engine(&internal_handle)); diff --git a/src/api/cpp/seq.cpp b/src/api/cpp/seq.cpp index 5f849a5acd..5d56a70f95 100644 --- a/src/api/cpp/seq.cpp +++ b/src/api/cpp/seq.cpp @@ -33,47 +33,51 @@ void seq::init(double begin, double end, double step) { #ifndef signbit // wtf windows?! inline int signbit(double x) { - if (x < 0) return -1; + if (x < 0) { return -1; } return 0; } #endif -seq::~seq() {} +seq::~seq() = default; -seq::seq(double n) : m_gfor(false) { - if (n < 0) { - init(0, n, 1); +seq::seq(double length) : s{}, size{}, m_gfor(false) { + if (length < 0) { + init(0, length, 1); } else { - init(0, n - 1, 1); + init(0, length - 1, 1); } } -seq::seq(const af_seq& s_) : m_gfor(false) { init(s_.begin, s_.end, s_.step); } +seq::seq(const af_seq& s_) : s{}, size{}, m_gfor(false) { + init(s_.begin, s_.end, s_.step); +} seq& seq::operator=(const af_seq& s_) { init(s_.begin, s_.end, s_.step); return *this; } -seq::seq(double begin, double end, double step) : m_gfor(false) { +seq::seq(double begin, double end, double step) : s{}, size{}, m_gfor(false) { if (step == 0) { - if (begin != end) // Span + if (begin != end) { // Span AF_THROW_ERR("Invalid step size", AF_ERR_ARG); + } } if ((signbit(end) == signbit(begin)) && - (signbit(end - begin) != signbit(step))) + (signbit(end - begin) != signbit(step))) { AF_THROW_ERR("Sequence is invalid", AF_ERR_ARG); + } init(begin, end, step); } -seq::seq(seq other, bool is_gfor) +seq::seq(seq other, // NOLINT(performance-unnecessary-value-param) + bool is_gfor) : s(other.s), size(other.size), m_gfor(is_gfor) {} seq::operator array() const { double diff = s.end - s.begin; - dim_t len = - (int)((diff + std::fabs(s.step) * (signbit(diff) == 0 ? 1 : -1)) / - s.step); + dim_t len = static_cast( + (diff + std::fabs(s.step) * (signbit(diff) == 0 ? 1 : -1)) / s.step); array tmp = (m_gfor) ? range(1, 1, 1, len, 3) : range(len); diff --git a/src/api/cpp/sparse.cpp b/src/api/cpp/sparse.cpp index 1f9cabea4f..92486f873a 100644 --- a/src/api/cpp/sparse.cpp +++ b/src/api/cpp/sparse.cpp @@ -12,8 +12,11 @@ #include "error.hpp" namespace af { -array sparse(const dim_t nRows, const dim_t nCols, const array values, - const array rowIdx, const array colIdx, const af::storage stype) { +array sparse(const dim_t nRows, const dim_t nCols, + const array values, // NOLINT(performance-unnecessary-value-param) + const array rowIdx, // NOLINT(performance-unnecessary-value-param) + const array colIdx, // NOLINT(performance-unnecessary-value-param) + const af::storage stype) { af_array out = 0; AF_THROW(af_create_sparse_array(&out, nRows, nCols, values.get(), rowIdx.get(), colIdx.get(), stype)); @@ -21,8 +24,8 @@ array sparse(const dim_t nRows, const dim_t nCols, const array values, } array sparse(const dim_t nRows, const dim_t nCols, const dim_t nNZ, - const void *const values, const int *const rowIdx, - const int *const colIdx, const dtype type, const af::storage stype, + const void* const values, const int* const rowIdx, + const int* const colIdx, const dtype type, const af::storage stype, const af::source src) { af_array out = 0; AF_THROW(af_create_sparse_array_from_ptr(&out, nRows, nCols, nNZ, values, @@ -30,26 +33,30 @@ array sparse(const dim_t nRows, const dim_t nCols, const dim_t nNZ, return array(out); } +// NOLINTNEXTLINE(performance-unnecessary-value-param) array sparse(const array dense, const af::storage stype) { af_array out = 0; AF_THROW(af_create_sparse_array_from_dense(&out, dense.get(), stype)); return array(out); } +// NOLINTNEXTLINE(performance-unnecessary-value-param) array sparseConvertTo(const array in, const af::storage stype) { af_array out = 0; AF_THROW(af_sparse_convert_to(&out, in.get(), stype)); return array(out); } +// NOLINTNEXTLINE(performance-unnecessary-value-param) array dense(const array sparse) { af_array out = 0; AF_THROW(af_sparse_to_dense(&out, sparse.get())); return array(out); } -void sparseGetInfo(array &values, array &rowIdx, array &colIdx, storage &stype, - const array in) { +void sparseGetInfo( + array& values, array& rowIdx, array& colIdx, storage& stype, + const array in) { // NOLINT(performance-unnecessary-value-param) af_array values_ = 0, rowIdx_ = 0, colIdx_ = 0; af_storage stype_ = AF_STORAGE_DENSE; AF_THROW( @@ -58,33 +65,37 @@ void sparseGetInfo(array &values, array &rowIdx, array &colIdx, storage &stype, rowIdx = array(rowIdx_); colIdx = array(colIdx_); stype = stype_; - return; } +// NOLINTNEXTLINE(performance-unnecessary-value-param) array sparseGetValues(const array in) { af_array out = 0; AF_THROW(af_sparse_get_values(&out, in.get())); return array(out); } +// NOLINTNEXTLINE(performance-unnecessary-value-param) array sparseGetRowIdx(const array in) { af_array out = 0; AF_THROW(af_sparse_get_row_idx(&out, in.get())); return array(out); } +// NOLINTNEXTLINE(performance-unnecessary-value-param) array sparseGetColIdx(const array in) { af_array out = 0; AF_THROW(af_sparse_get_col_idx(&out, in.get())); return array(out); } +// NOLINTNEXTLINE(performance-unnecessary-value-param) dim_t sparseGetNNZ(const array in) { dim_t out = 0; AF_THROW(af_sparse_get_nnz(&out, in.get())); return out; } +// NOLINTNEXTLINE(performance-unnecessary-value-param) af::storage sparseGetStorage(const array in) { af::storage out; AF_THROW(af_sparse_get_storage(&out, in.get())); diff --git a/src/api/cpp/stdev.cpp b/src/api/cpp/stdev.cpp index 7c8c116987..4031e53ba9 100644 --- a/src/api/cpp/stdev.cpp +++ b/src/api/cpp/stdev.cpp @@ -27,14 +27,14 @@ template<> AFAPI af_cfloat stdev(const array& in) { double real, imag; AF_THROW(af_stdev_all(&real, &imag, in.get())); - return af_cfloat((float)real, (float)imag); + return {static_cast(real), static_cast(imag)}; } template<> AFAPI af_cdouble stdev(const array& in) { double real, imag; AF_THROW(af_stdev_all(&real, &imag, in.get())); - return af_cdouble(real, imag); + return {real, imag}; } INSTANTIATE_STDEV(float); diff --git a/src/api/cpp/timing.cpp b/src/api/cpp/timing.cpp index c42ad90c87..847c8d7873 100644 --- a/src/api/cpp/timing.cpp +++ b/src/api/cpp/timing.cpp @@ -7,16 +7,16 @@ * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ -#include #include #include #include +#include #include using namespace af; // get current time -static inline timer time_now(void) { +static inline timer time_now() { #if defined(OS_WIN) timer time; QueryPerformanceCounter(&time.val); @@ -53,7 +53,7 @@ static inline double time_seconds(timer start, timer end) { double nano = (double)info.numer / (double)info.denom; return (end.val - start.val) * nano * 1e-9; #elif defined(OS_LNX) - struct timeval elapsed; + struct timeval elapsed {}; timersub(&start.val, &end.val, &elapsed); long sec = elapsed.tv_sec; long usec = elapsed.tv_usec; @@ -98,12 +98,12 @@ double timeit(void (*fn)()) { // then run (min time / (trials * median_time)) batches // else // run 1 batch - int batches = (int)ceilf(min_time / (trials * median_time)); + int batches = static_cast(ceilf(min_time / (trials * median_time))); double run_time = 0; for (int b = 0; b < batches; b++) { timer start = timer::start(); - for (int i = 0; i < trials; ++i) fn(); + for (int i = 0; i < trials; ++i) { fn(); } sync(); run_time += timer::stop(start) / trials; } diff --git a/src/api/cpp/util.cpp b/src/api/cpp/util.cpp index b265fed161..c2bf0c05bf 100644 --- a/src/api/cpp/util.cpp +++ b/src/api/cpp/util.cpp @@ -17,12 +17,10 @@ using namespace std; namespace af { void print(const char *exp, const array &arr) { AF_THROW(af_print_array_gen(exp, arr.get(), 4)); - return; } void print(const char *exp, const array &arr, const int precision) { AF_THROW(af_print_array_gen(exp, arr.get(), precision)); - return; } int saveArray(const char *key, const array &arr, const char *filename, @@ -53,7 +51,6 @@ int readArrayCheck(const char *filename, const char *key) { void toString(char **output, const char *exp, const array &arr, const int precision, const bool transpose) { AF_THROW(af_array_to_string(output, exp, arr.get(), precision, transpose)); - return; } const char *toString(const char *exp, const array &arr, const int precision, diff --git a/src/api/cpp/var.cpp b/src/api/cpp/var.cpp index 534eb07f48..a5c563420a 100644 --- a/src/api/cpp/var.cpp +++ b/src/api/cpp/var.cpp @@ -53,28 +53,28 @@ template<> AFAPI af_cfloat var(const array& in, const bool isbiased) { double real, imag; AF_THROW(af_var_all(&real, &imag, in.get(), isbiased)); - return af_cfloat((float)real, (float)imag); + return {static_cast(real), static_cast(imag)}; } template<> AFAPI af_cdouble var(const array& in, const bool isbiased) { double real, imag; AF_THROW(af_var_all(&real, &imag, in.get(), isbiased)); - return af_cdouble(real, imag); + return {real, imag}; } template<> AFAPI af_cfloat var(const array& in, const array& weights) { double real, imag; AF_THROW(af_var_all_weighted(&real, &imag, in.get(), weights.get())); - return af_cfloat((float)real, (float)imag); + return {static_cast(real), static_cast(imag)}; } template<> AFAPI af_cdouble var(const array& in, const array& weights) { double real, imag; AF_THROW(af_var_all_weighted(&real, &imag, in.get(), weights.get())); - return af_cdouble(real, imag); + return {real, imag}; } INSTANTIATE_VAR(float); diff --git a/src/backend/common/ArrayInfo.cpp b/src/backend/common/ArrayInfo.cpp index d1a09f05fc..0de280b89c 100644 --- a/src/backend/common/ArrayInfo.cpp +++ b/src/backend/common/ArrayInfo.cpp @@ -30,36 +30,36 @@ dim4 calcStrides(const dim4 &parentDim) { return out; } -int ArrayInfo::getDevId() const { +unsigned ArrayInfo::getDevId() const { // The actual device ID is only stored in the first 8 bits of devId // See ArrayInfo.hpp for more - return devId & 0xff; + return devId & 0xffU; } void ArrayInfo::setId(int id) const { // 1 << (backendId + 8) sets the 9th, 10th or 11th bit of devId to 1 // for CPU, CUDA and OpenCL respectively // See ArrayInfo.hpp for more - int backendId = - detail::getBackend() >> 1; // Convert enums 1, 2, 4 to ints 0, 1, 2 - const_cast(this)->setId(id | 1 << (backendId + 8)); + unsigned backendId = + detail::getBackend() >> 1U; // Convert enums 1, 2, 4 to ints 0, 1, 2 + const_cast(this)->setId(id | 1 << (backendId + 8U)); } void ArrayInfo::setId(int id) { // 1 << (backendId + 8) sets the 9th, 10th or 11th bit of devId to 1 // for CPU, CUDA and OpenCL respectively // See ArrayInfo.hpp for more - int backendId = - detail::getBackend() >> 1; // Convert enums 1, 2, 4 to ints 0, 1, 2 - devId = id | 1 << (backendId + 8); + unsigned backendId = + detail::getBackend() >> 1U; // Convert enums 1, 2, 4 to ints 0, 1, 2 + devId = id | 1U << (backendId + 8U); } af_backend ArrayInfo::getBackendId() const { // devId >> 8 converts the backend info to 1, 2, 4 which are enums // for CPU, CUDA and OpenCL respectively // See ArrayInfo.hpp for more - int backendId = devId >> 8; - return (af_backend)backendId; + unsigned backendId = devId >> 8U; + return static_cast(backendId); } void ArrayInfo::modStrides(const dim4 &newStrides) { dim_strides = newStrides; } @@ -120,7 +120,7 @@ bool ArrayInfo::isLinear() const { if (ndims() == 1) { return dim_strides[0] == 1; } dim_t count = 1; - for (int i = 0; i < (int)ndims(); i++) { + for (size_t i = 0; i < ndims(); i++) { if (count != dim_strides[i]) { return false; } count *= dim_size[i]; } @@ -150,8 +150,9 @@ dim4 toDims(const vector &seqs, const dim4 &parentDims) { dim4 outDims(1, 1, 1, 1); for (unsigned i = 0; i < seqs.size(); i++) { outDims[i] = af::calcDim(seqs[i], parentDims[i]); - if (outDims[i] > parentDims[i]) + if (outDims[i] > parentDims[i]) { AF_ERROR("Size mismatch between input and output", AF_ERR_SIZE); + } } return outDims; } @@ -167,8 +168,9 @@ dim4 toOffset(const vector &seqs, const dim4 &parentDims) { outOffsets[i] = 0; } - if (outOffsets[i] >= parentDims[i]) + if (outOffsets[i] >= parentDims[i]) { AF_ERROR("Index out of range", AF_ERR_SIZE); + } } return outOffsets; } diff --git a/src/backend/common/ArrayInfo.hpp b/src/backend/common/ArrayInfo.hpp index 334556d4fa..d878d75fea 100644 --- a/src/backend/common/ArrayInfo.hpp +++ b/src/backend/common/ArrayInfo.hpp @@ -39,7 +39,7 @@ class ArrayInfo { // This can be changed in the future if the need arises for more devices as // this implementation is internal. Make sure to change the bit shift ops // when such a change is being made - int devId; + unsigned devId; af_dtype type; af::dim4 dim_size; dim_t offset; @@ -95,7 +95,7 @@ class ArrayInfo { const af::dim4& dims() const { return dim_size; } size_t total() const { return offset + dim_strides[3] * dim_size[3]; } - int getDevId() const; + unsigned getDevId() const; void setId(int id) const; diff --git a/src/backend/common/DefaultMemoryManager.cpp b/src/backend/common/DefaultMemoryManager.cpp index 35a4dc58a9..030399bcb9 100644 --- a/src/backend/common/DefaultMemoryManager.cpp +++ b/src/backend/common/DefaultMemoryManager.cpp @@ -20,15 +20,12 @@ #include #include -using std::make_unique; using std::max; using std::move; using std::stoi; using std::string; using std::vector; -using spdlog::logger; - namespace common { DefaultMemoryManager::memory_info & @@ -37,7 +34,7 @@ DefaultMemoryManager::getCurrentMemoryInfo() { } void DefaultMemoryManager::cleanDeviceMemoryManager(int device) { - if (this->debug_mode) return; + if (this->debug_mode) { return; } // This vector is used to store the pointers which will be deleted by // the memory manager. We are using this to avoid calling free while @@ -48,7 +45,7 @@ void DefaultMemoryManager::cleanDeviceMemoryManager(int device) { { lock_guard_t lock(this->memory_mutex); // Return if all buffers are locked - if (current.total_buffers == current.lock_buffers) return; + if (current.total_buffers == current.lock_buffers) { return; } free_ptrs.reserve(current.free_map.size()); for (auto &kv : current.free_map) { @@ -81,12 +78,12 @@ DefaultMemoryManager::DefaultMemoryManager(int num_devices, // Debug mode string env_var = getEnvVar("AF_MEM_DEBUG"); - if (!env_var.empty()) this->debug_mode = env_var[0] != '0'; - if (this->debug_mode) mem_step_size = 1; + if (!env_var.empty()) { this->debug_mode = env_var[0] != '0'; } + if (this->debug_mode) { mem_step_size = 1; } // Max Buffer count env_var = getEnvVar("AF_MAX_BUFFERS"); - if (!env_var.empty()) this->max_buffers = max(1, stoi(env_var)); + if (!env_var.empty()) { this->max_buffers = max(1, stoi(env_var)); } } void DefaultMemoryManager::initialize() { this->setMaxMemorySize(); } @@ -96,7 +93,7 @@ void DefaultMemoryManager::shutdown() { signalMemoryCleanup(); } void DefaultMemoryManager::addMemoryManagement(int device) { // If there is a memory manager allocated for this device id, we might // as well use it and the buffers allocated for it - if (static_cast(device) < memory.size()) return; + if (static_cast(device) < memory.size()) { return; } // Assuming, device need not be always the next device Lets resize to // current_size + device + 1 +1 is to account for device being 0-based @@ -105,8 +102,9 @@ void DefaultMemoryManager::addMemoryManagement(int device) { } void DefaultMemoryManager::removeMemoryManagement(int device) { - if ((size_t)device >= memory.size()) + if (static_cast(device) >= memory.size()) { AF_ERROR("No matching device found", AF_ERR_ARG); + } // Do garbage collection for the device and leave the memory::memory_info // struct from the memory vector intact @@ -120,8 +118,9 @@ void DefaultMemoryManager::setMaxMemorySize() { // memsize returned 0, then use 1GB size_t memsize = this->getMaxMemorySize(n); memory[n].max_bytes = - memsize == 0 ? ONE_GB - : max(memsize * 0.75, (double)(memsize - ONE_GB)); + memsize == 0 + ? ONE_GB + : max(memsize * 0.75, static_cast(memsize - ONE_GB)); } } @@ -188,7 +187,7 @@ void *DefaultMemoryManager::alloc(bool user_lock, const unsigned ndims, ptr = this->nativeAlloc(alloc_bytes); } catch (const AfError &ex) { // If out of memory, run garbage collect and try again - if (ex.getError() != AF_ERR_NO_MEM) throw; + if (ex.getError() != AF_ERR_NO_MEM) { throw; } this->signalMemoryCleanup(); ptr = this->nativeAlloc(alloc_bytes); } @@ -206,7 +205,7 @@ void *DefaultMemoryManager::alloc(bool user_lock, const unsigned ndims, } size_t DefaultMemoryManager::allocated(void *ptr) { - if (!ptr) return 0; + if (!ptr) { return 0; } memory_info ¤t = this->getCurrentMemoryInfo(); auto locked_iter = current.locked_map.find(ptr); if (locked_iter == current.locked_map.end()) { return 0; } @@ -281,13 +280,14 @@ void DefaultMemoryManager::printInfo(const char *msg, const int device) { for (auto &kv : current.locked_map) { const char *status_mngr = "Yes"; const char *status_user = "Unknown"; - if (kv.second.user_lock) + if (kv.second.user_lock) { status_user = "Yes"; - else + } else { status_user = " No"; + } const char *unit = "KB"; - double size = (double)(kv.second.bytes) / 1024; + double size = static_cast(kv.second.bytes) / 1024; if (size >= 1024) { size = size / 1024; unit = "MB"; @@ -302,7 +302,7 @@ void DefaultMemoryManager::printInfo(const char *msg, const int device) { const char *status_user = "No"; const char *unit = "KB"; - double size = (double)(kv.first) / 1024; + double size = static_cast(kv.first) / 1024; if (size >= 1024) { size = size / 1024; unit = "MB"; @@ -321,10 +321,10 @@ void DefaultMemoryManager::usageInfo(size_t *alloc_bytes, size_t *alloc_buffers, size_t *lock_bytes, size_t *lock_buffers) { const memory_info ¤t = this->getCurrentMemoryInfo(); lock_guard_t lock(this->memory_mutex); - if (alloc_bytes) *alloc_bytes = current.total_bytes; - if (alloc_buffers) *alloc_buffers = current.total_buffers; - if (lock_bytes) *lock_bytes = current.lock_bytes; - if (lock_buffers) *lock_buffers = current.lock_buffers; + if (alloc_bytes) { *alloc_bytes = current.total_bytes; } + if (alloc_buffers) { *alloc_buffers = current.total_buffers; } + if (lock_bytes) { *lock_bytes = current.lock_bytes; } + if (lock_buffers) { *lock_buffers = current.lock_buffers; } } void DefaultMemoryManager::userLock(const void *ptr) { @@ -338,7 +338,7 @@ void DefaultMemoryManager::userLock(const void *ptr) { } else { locked_info info = {false, true, 100}; // This number is not relevant - current.locked_map[(void *)ptr] = info; + current.locked_map[const_cast(ptr)] = info; } } diff --git a/src/backend/common/DefaultMemoryManager.hpp b/src/backend/common/DefaultMemoryManager.hpp index d014a58fe5..6feda08bf2 100644 --- a/src/backend/common/DefaultMemoryManager.hpp +++ b/src/backend/common/DefaultMemoryManager.hpp @@ -118,9 +118,10 @@ class DefaultMemoryManager final : public common::memory::MemoryManagerBase { float getMemoryPressure() override; bool jitTreeExceedsMemoryPressure(size_t bytes) override; + ~DefaultMemoryManager() = default; + protected: DefaultMemoryManager() = delete; - ~DefaultMemoryManager() = default; DefaultMemoryManager(const DefaultMemoryManager &other) = delete; DefaultMemoryManager(DefaultMemoryManager &&other) = default; DefaultMemoryManager &operator=(const DefaultMemoryManager &other) = delete; diff --git a/src/backend/common/DependencyModule.cpp b/src/backend/common/DependencyModule.cpp index 0176f9a84a..24bc53e4fb 100644 --- a/src/backend/common/DependencyModule.cpp +++ b/src/backend/common/DependencyModule.cpp @@ -38,7 +38,7 @@ using std::vector; namespace { -std::string libName(std::string name) { +std::string libName(const std::string& name) { return libraryPrefix + name + librarySuffix; } } // namespace @@ -62,9 +62,9 @@ DependencyModule::DependencyModule(const char* plugin_file_name, } } -DependencyModule::DependencyModule(const vector plugin_base_file_name, - const vector suffixes, - const vector paths) +DependencyModule::DependencyModule(const vector& plugin_base_file_name, + const vector& suffixes, + const vector& paths) : handle(nullptr), logger(common::loggerFactory("platform")) { for (const string& base_name : plugin_base_file_name) { for (const string& path : paths) { @@ -86,14 +86,16 @@ DependencyModule::~DependencyModule() noexcept { if (handle) { unloadLibrary(handle); } } -bool DependencyModule::isLoaded() const noexcept { return (bool)handle; } +bool DependencyModule::isLoaded() const noexcept { + return static_cast(handle); +} bool DependencyModule::symbolsLoaded() const noexcept { return all_of(begin(functions), end(functions), [](void* ptr) { return ptr != nullptr; }); } -string DependencyModule::getErrorMessage() const noexcept { +string DependencyModule::getErrorMessage() noexcept { return common::getErrorMessage(); } diff --git a/src/backend/common/DependencyModule.hpp b/src/backend/common/DependencyModule.hpp index d9a860a738..9c2b00b53a 100644 --- a/src/backend/common/DependencyModule.hpp +++ b/src/backend/common/DependencyModule.hpp @@ -37,9 +37,9 @@ class DependencyModule { DependencyModule(const char* plugin_file_name, const char** paths = nullptr); - DependencyModule(const std::vector plugin_base_file_name, - const std::vector suffixes, - const std::vector paths); + DependencyModule(const std::vector& plugin_base_file_name, + const std::vector& suffixes, + const std::vector& paths); ~DependencyModule() noexcept; @@ -58,7 +58,7 @@ class DependencyModule { /// Returns the last error message that occurred because of loading the /// library - std::string getErrorMessage() const noexcept; + static std::string getErrorMessage() noexcept; spdlog::logger* getLogger() const noexcept; }; diff --git a/src/backend/common/InteropManager.hpp b/src/backend/common/InteropManager.hpp index b3f95d5d2c..c784ae94aa 100644 --- a/src/backend/common/InteropManager.hpp +++ b/src/backend/common/InteropManager.hpp @@ -31,7 +31,7 @@ class InteropManager { ~InteropManager() { try { destroyResources(); - } catch (AfError &ex) { + } catch (const AfError &ex) { std::string perr = getEnvVar("AF_PRINT_ERRORS"); if (!perr.empty()) { if (perr != "0") fprintf(stderr, "%s\n", ex.what()); diff --git a/src/backend/common/Logger.cpp b/src/backend/common/Logger.cpp index d7c7d05323..ac488cd40b 100644 --- a/src/backend/common/Logger.cpp +++ b/src/backend/common/Logger.cpp @@ -22,10 +22,8 @@ #include using std::array; -using std::make_shared; using std::shared_ptr; using std::string; -using std::to_string; using spdlog::get; using spdlog::logger; @@ -33,7 +31,7 @@ using spdlog::stdout_logger_mt; namespace common { -shared_ptr loggerFactory(string name) { +shared_ptr loggerFactory(const string& name) { shared_ptr logger; if (!(logger = get(name))) { logger = stdout_logger_mt(name); @@ -52,15 +50,15 @@ shared_ptr loggerFactory(string name) { } string bytesToString(size_t bytes) { - constexpr array units{ + constexpr array units{ {"B", "KB", "MB", "GB", "TB", "PB", "EB"}}; size_t count = 0; - double fbytes = static_cast(bytes); + auto fbytes = static_cast(bytes); size_t num_units = units.size(); for (count = 0; count < num_units && fbytes > 1000.0f; count++) { fbytes *= (1.0f / 1024.0f); } - if (count == units.size()) count--; + if (count == units.size()) { count--; } return fmt::format("{:.3g} {}", fbytes, units[count]); } } // namespace common diff --git a/src/backend/common/Logger.hpp b/src/backend/common/Logger.hpp index ac627e81bb..aa56fc4ed0 100644 --- a/src/backend/common/Logger.hpp +++ b/src/backend/common/Logger.hpp @@ -16,7 +16,7 @@ #include namespace common { -std::shared_ptr loggerFactory(std::string name); +std::shared_ptr loggerFactory(const std::string& name); std::string bytesToString(size_t bytes); } // namespace common diff --git a/src/backend/common/SparseArray.cpp b/src/backend/common/SparseArray.cpp index 8a56b4b851..deafcc9f06 100644 --- a/src/backend/common/SparseArray.cpp +++ b/src/backend/common/SparseArray.cpp @@ -71,7 +71,8 @@ SparseArrayBase::SparseArrayBase(af::dim4 _dims, dim_t _nNZ, int *const _rowIdx, } } -SparseArrayBase::SparseArrayBase(af::dim4 _dims, const Array &_rowIdx, +SparseArrayBase::SparseArrayBase(const af::dim4 &_dims, + const Array &_rowIdx, const Array &_colIdx, const af::storage _storage, af_dtype _type, bool _copy) @@ -90,13 +91,13 @@ SparseArrayBase::SparseArrayBase(const SparseArrayBase &base, bool copy) , rowIdx(copy ? copyArray(base.rowIdx) : base.rowIdx) , colIdx(copy ? copyArray(base.colIdx) : base.colIdx) {} -SparseArrayBase::~SparseArrayBase() {} +SparseArrayBase::~SparseArrayBase() = default; dim_t SparseArrayBase::getNNZ() const { - if (stype == AF_STORAGE_COO || stype == AF_STORAGE_CSC) + if (stype == AF_STORAGE_COO || stype == AF_STORAGE_CSC) { return rowIdx.elements(); - else if (stype == AF_STORAGE_CSR) - return colIdx.elements(); + } + if (stype == AF_STORAGE_CSR) { return colIdx.elements(); } // This is to ensure future storages are properly configured return 0; @@ -126,12 +127,11 @@ SparseArray createHostDataSparseArray(const af::dim4 &_dims, const dim_t nNZ, } template -SparseArray createDeviceDataSparseArray(const af::dim4 &_dims, - const dim_t nNZ, T *const _values, - int *const _rowIdx, - int *const _colIdx, - const af::storage _storage, - const bool _copy) { +SparseArray createDeviceDataSparseArray( + const af::dim4 &_dims, const dim_t nNZ, T *const _values, + int *const _rowIdx, // NOLINT(readability-non-const-parameter) + int *const _colIdx, // NOLINT(readability-non-const-parameter) + const af::storage _storage, const bool _copy) { return SparseArray(_dims, nNZ, _values, _rowIdx, _colIdx, _storage, true, _copy); } @@ -162,8 +162,9 @@ void destroySparseArray(SparseArray *sparse) { // Sparse Array Class Implementations //////////////////////////////////////////////////////////////////////////// template -SparseArray::SparseArray(dim4 _dims, dim_t _nNZ, af::storage _storage) - : base(_dims, _nNZ, _storage, (af_dtype)dtype_traits::af_type) +SparseArray::SparseArray(const dim4 &_dims, dim_t _nNZ, af::storage _storage) + : base(_dims, _nNZ, _storage, + static_cast(dtype_traits::af_type)) , values(createValueArray(dim4(_nNZ), scalar(0))) { static_assert(std::is_standard_layout>::value, "SparseArray must be a standard layout type"); @@ -173,12 +174,13 @@ SparseArray::SparseArray(dim4 _dims, dim_t _nNZ, af::storage _storage) } template -SparseArray::SparseArray(af::dim4 _dims, dim_t _nNZ, T *const _values, +SparseArray::SparseArray(const af::dim4 &_dims, dim_t _nNZ, T *const _values, int *const _rowIdx, int *const _colIdx, const af::storage _storage, bool _is_device, bool _copy_device) : base(_dims, _nNZ, _rowIdx, _colIdx, _storage, - (af_dtype)dtype_traits::af_type, _is_device, _copy_device) + static_cast(dtype_traits::af_type), _is_device, + _copy_device) , values(_is_device ? (!_copy_device ? createDeviceDataArray(dim4(_nNZ), _values) : createValueArray(dim4(_nNZ), scalar(0))) @@ -189,12 +191,12 @@ SparseArray::SparseArray(af::dim4 _dims, dim_t _nNZ, T *const _values, } template -SparseArray::SparseArray(af::dim4 _dims, const Array &_values, +SparseArray::SparseArray(const af::dim4 &_dims, const Array &_values, const Array &_rowIdx, const Array &_colIdx, const af::storage _storage, bool _copy) : base(_dims, _rowIdx, _colIdx, _storage, - (af_dtype)dtype_traits::af_type, _copy) + static_cast(dtype_traits::af_type), _copy) , values(_copy ? copyArray(_values) : _values) {} template @@ -202,9 +204,6 @@ SparseArray::SparseArray(const SparseArray &other, bool copy) : base(other.base, copy) , values(copy ? copyArray(other.values) : other.values) {} -template -SparseArray::~SparseArray() {} - #define INSTANTIATE(T) \ template SparseArray createEmptySparseArray( \ const af::dim4 &_dims, dim_t _nNZ, const af::storage _storage); \ @@ -213,7 +212,8 @@ SparseArray::~SparseArray() {} const int *const _rowIdx, const int *const _colIdx, \ const af::storage _storage); \ template SparseArray createDeviceDataSparseArray( \ - const af::dim4 &_dims, const dim_t _nNZ, T *const _values, \ + const af::dim4 &_dims, const dim_t _nNZ, \ + T *const _values, /* NOLINT */ \ int *const _rowIdx, int *const _colIdx, const af::storage _storage, \ const bool _copy); \ template SparseArray createArrayDataSparseArray( \ @@ -224,16 +224,16 @@ SparseArray::~SparseArray() {} template SparseArray copySparseArray(const SparseArray &other); \ template void destroySparseArray(SparseArray * sparse); \ \ - template SparseArray::SparseArray(af::dim4 _dims, dim_t _nNZ, \ + template SparseArray::SparseArray(const af::dim4 &_dims, dim_t _nNZ, \ af::storage _storage); \ template SparseArray::SparseArray( \ - af::dim4 _dims, dim_t _nNZ, T *const _values, int *const _rowIdx, \ - int *const _colIdx, const af::storage _storage, bool _is_device, \ - bool _copy_device); \ + const af::dim4 &_dims, dim_t _nNZ, T *const _values, /* NOLINT */ \ + int *const _rowIdx, int *const _colIdx, const af::storage _storage, \ + bool _is_device, bool _copy_device); \ template SparseArray::SparseArray( \ - af::dim4 _dims, const Array &_values, const Array &_rowIdx, \ - const Array &_colIdx, const af::storage _storage, bool _copy); \ - template SparseArray::~SparseArray(); + const af::dim4 &_dims, const Array &_values, \ + const Array &_rowIdx, const Array &_colIdx, \ + const af::storage _storage, bool _copy) // Instantiate only floating types INSTANTIATE(float); diff --git a/src/backend/common/SparseArray.hpp b/src/backend/common/SparseArray.hpp index 0f02922865..24144a29fe 100644 --- a/src/backend/common/SparseArray.hpp +++ b/src/backend/common/SparseArray.hpp @@ -48,7 +48,7 @@ class SparseArrayBase { af_dtype _type, bool _is_device = false, bool _copy_device = false); - SparseArrayBase(af::dim4 _dims, const Array &_rowIdx, + SparseArrayBase(const af::dim4 &_dims, const Array &_rowIdx, const Array &_colIdx, const af::storage _storage, af_dtype _type, bool _copy = false); @@ -59,7 +59,7 @@ class SparseArrayBase { /// /// \param[in] in The array that will be copied /// \param[in] deep_copy If true a deep copy is performed - SparseArrayBase(const SparseArrayBase &in, bool deep_copy = false); + SparseArrayBase(const SparseArrayBase &base, bool deep_copy = false); ~SparseArrayBase(); @@ -130,14 +130,14 @@ class SparseArray { base; ///< This must be the first element of SparseArray. Array values; ///< Linear array containing actual values - SparseArray(af::dim4 _dims, dim_t _nNZ, af::storage stype); + SparseArray(const af::dim4 &_dims, dim_t _nNZ, af::storage _storage); - explicit SparseArray(af::dim4 _dims, dim_t _nNZ, T *const _values, + explicit SparseArray(const af::dim4 &_dims, dim_t _nNZ, T *const _values, int *const _rowIdx, int *const _colIdx, const af::storage _storage, bool _is_device = false, bool _copy_device = false); - SparseArray(af::dim4 _dims, const Array &_values, + SparseArray(const af::dim4 &_dims, const Array &_values, const Array &_rowIdx, const Array &_colIdx, const af::storage _storage, bool _copy = false); @@ -146,12 +146,12 @@ class SparseArray { /// This constructor copies the \p in SparseArray and creates a new object /// from it. It can also perform a deep copy if the second argument is true. /// - /// \param[in] in The array that will be copied + /// \param[in] other The array that will be copied /// \param[in] deep_copy If true a deep copy is performed - SparseArray(const SparseArray &in, bool deep_copy); + SparseArray(const SparseArray &other, bool deep_copy); public: - ~SparseArray(); + ~SparseArray() noexcept = default; // Functions that call ArrayInfo object's functions #define INSTANTIATE_INFO(return_type, func) \ diff --git a/src/backend/common/dim4.cpp b/src/backend/common/dim4.cpp index a17165451c..a83ed15457 100644 --- a/src/backend/common/dim4.cpp +++ b/src/backend/common/dim4.cpp @@ -23,7 +23,6 @@ static_assert(std::is_standard_layout::value, using std::abs; using std::numeric_limits; -using std::vector; dim4::dim4() : dims{0, 0, 0, 0} {} @@ -33,7 +32,7 @@ dim4::dim4(dim_t first, dim_t second, dim_t third, dim_t fourth) dim4::dim4(const dim4& other) : dims{other.dims[0], other.dims[1], other.dims[2], other.dims[3]} {} -dim4::dim4(const unsigned ndims_, const dim_t* const dims_) { +dim4::dim4(const unsigned ndims_, const dim_t* const dims_) : dims{} { for (unsigned i = 0; i < 4; i++) { dims[i] = ndims_ > i ? dims_[i] : 1; } } @@ -43,12 +42,12 @@ dim_t dim4::elements() { return static_cast(*this).elements(); } dim_t dim4::ndims() const { dim_t num = elements(); - if (num == 0) return 0; - if (num == 1) return 1; + if (num == 0) { return 0; } + if (num == 1) { return 1; } - if (dims[3] != 1) return 4; - if (dims[2] != 1) return 3; - if (dims[1] != 1) return 2; + if (dims[3] != 1) { return 4; } + if (dims[2] != 1) { return 3; } + if (dims[1] != 1) { return 2; } return 1; } @@ -127,8 +126,8 @@ dim_t calcDim(const af_seq& seq, const dim_t& parentDim) { outDim = parentDim; } else if (hasEnd(seq)) { af_seq temp = {seq.begin, seq.end, seq.step}; - if (seq.begin < 0) temp.begin += parentDim; - if (seq.end < 0) temp.end += parentDim; + if (seq.begin < 0) { temp.begin += parentDim; } + if (seq.end < 0) { temp.end += parentDim; } outDim = seqElements(temp); } else { DIM_ASSERT(1, seq.begin >= -DBL_MIN && seq.begin < parentDim); diff --git a/src/backend/common/dispatch.cpp b/src/backend/common/dispatch.cpp index 50d35da9bc..4cf5cbe6b7 100644 --- a/src/backend/common/dispatch.cpp +++ b/src/backend/common/dispatch.cpp @@ -10,11 +10,11 @@ #include "dispatch.hpp" unsigned nextpow2(unsigned x) { - x = x - 1; - x = x | (x >> 1); - x = x | (x >> 2); - x = x | (x >> 4); - x = x | (x >> 8); - x = x | (x >> 16); - return x + 1; + x = x - 1U; + x = x | (x >> 1U); + x = x | (x >> 2U); + x = x | (x >> 4U); + x = x | (x >> 8U); + x = x | (x >> 16U); + return x + 1U; } diff --git a/src/backend/common/err_common.cpp b/src/backend/common/err_common.cpp index 3d0605c286..21e7b7212b 100644 --- a/src/backend/common/err_common.cpp +++ b/src/backend/common/err_common.cpp @@ -19,12 +19,14 @@ #include #include #include +#include #ifdef AF_OPENCL #include #include #endif +using std::move; using std::string; using std::stringstream; @@ -40,24 +42,25 @@ AfError::AfError(const char *const func, const char *const file, const int line, , error(err) , st_(move(st)) {} -AfError::AfError(string func, string file, const int line, string message, - af_err err, boost::stacktrace::stacktrace st) +AfError::AfError(string func, string file, const int line, + const string &message, af_err err, + boost::stacktrace::stacktrace st) : logic_error(message) - , functionName(func) - , fileName(file) + , functionName(move(func)) + , fileName(move(file)) , lineNumber(line) , error(err) , st_(move(st)) {} -const string &AfError::getFunctionName() const { return functionName; } +const string &AfError::getFunctionName() const noexcept { return functionName; } -const string &AfError::getFileName() const { return fileName; } +const string &AfError::getFileName() const noexcept { return fileName; } -int AfError::getLine() const { return lineNumber; } +int AfError::getLine() const noexcept { return lineNumber; } -af_err AfError::getError() const { return error; } +af_err AfError::getError() const noexcept { return error; } -AfError::~AfError() throw() {} +AfError::~AfError() noexcept = default; TypeError::TypeError(const char *const func, const char *const file, const int line, const int index, const af_dtype type, @@ -66,9 +69,9 @@ TypeError::TypeError(const char *const func, const char *const file, , argIndex(index) , errTypeName(getName(type)) {} -const string &TypeError::getTypeName() const { return errTypeName; } +const string &TypeError::getTypeName() const noexcept { return errTypeName; } -int TypeError::getArgIndex() const { return argIndex; } +int TypeError::getArgIndex() const noexcept { return argIndex; } ArgumentError::ArgumentError(const char *const func, const char *const file, const int line, const int index, @@ -78,9 +81,11 @@ ArgumentError::ArgumentError(const char *const func, const char *const file, , argIndex(index) , expected(expectString) {} -const string &ArgumentError::getExpectedCondition() const { return expected; } +const string &ArgumentError::getExpectedCondition() const noexcept { + return expected; +} -int ArgumentError::getArgIndex() const { return argIndex; } +int ArgumentError::getArgIndex() const noexcept { return argIndex; } SupportError::SupportError(const char *const func, const char *const file, const int line, const char *const back, @@ -89,24 +94,26 @@ SupportError::SupportError(const char *const func, const char *const file, move(st)) , backend(back) {} -const string &SupportError::getBackendName() const { return backend; } +const string &SupportError::getBackendName() const noexcept { return backend; } DimensionError::DimensionError(const char *const func, const char *const file, const int line, const int index, const char *const expectString, - const boost::stacktrace::stacktrace st) - : AfError(func, file, line, "Invalid size", AF_ERR_SIZE, move(st)) + const boost::stacktrace::stacktrace &st) + : AfError(func, file, line, "Invalid size", AF_ERR_SIZE, st) , argIndex(index) , expected(expectString) {} -const string &DimensionError::getExpectedCondition() const { return expected; } +const string &DimensionError::getExpectedCondition() const noexcept { + return expected; +} -int DimensionError::getArgIndex() const { return argIndex; } +int DimensionError::getArgIndex() const noexcept { return argIndex; } af_err set_global_error_string(const string &msg, af_err err) { std::string perr = getEnvVar("AF_PRINT_ERRORS"); if (!perr.empty()) { - if (perr != "0") fprintf(stderr, "%s\n", msg.c_str()); + if (perr != "0") { fprintf(stderr, "%s\n", msg.c_str()); } } get_global_error_string() = msg; return err; @@ -123,7 +130,7 @@ af_err processException() { << "In file " << ex.getFileName() << ":" << ex.getLine() << "\n" << "Invalid dimension for argument " << ex.getArgIndex() << "\n" << "Expected: " << ex.getExpectedCondition() << "\n"; - if (is_stacktrace_enabled()) ss << ex.getStacktrace(); + if (is_stacktrace_enabled()) { ss << ex.getStacktrace(); } err = set_global_error_string(ss.str(), AF_ERR_SIZE); } catch (const ArgumentError &ex) { @@ -132,26 +139,26 @@ af_err processException() { << "Invalid argument at index " << ex.getArgIndex() << "\n" << "Expected: " << ex.getExpectedCondition() << "\n"; - if (is_stacktrace_enabled()) ss << ex.getStacktrace(); + if (is_stacktrace_enabled()) { ss << ex.getStacktrace(); } err = set_global_error_string(ss.str(), AF_ERR_ARG); } catch (const SupportError &ex) { ss << ex.getFunctionName() << " not supported for " << ex.getBackendName() << " backend\n"; - if (is_stacktrace_enabled()) ss << ex.getStacktrace(); + if (is_stacktrace_enabled()) { ss << ex.getStacktrace(); } err = set_global_error_string(ss.str(), AF_ERR_NOT_SUPPORTED); } catch (const TypeError &ex) { ss << "In function " << ex.getFunctionName() << "\n" << "In file " << ex.getFileName() << ":" << ex.getLine() << "\n" << "Invalid type for argument " << ex.getArgIndex() << "\n"; - if (is_stacktrace_enabled()) ss << ex.getStacktrace(); + if (is_stacktrace_enabled()) { ss << ex.getStacktrace(); } err = set_global_error_string(ss.str(), AF_ERR_TYPE); } catch (const AfError &ex) { ss << "In function " << ex.getFunctionName() << "\n" << "In file " << ex.getFileName() << ":" << ex.getLine() << "\n" << ex.what() << "\n"; - if (is_stacktrace_enabled()) ss << ex.getStacktrace(); + if (is_stacktrace_enabled()) { ss << ex.getStacktrace(); } err = set_global_error_string(ss.str(), ex.getError()); #ifdef AF_OPENCL @@ -172,8 +179,8 @@ af_err processException() { return err; } -std::string &get_global_error_string() { - thread_local std::string *global_error_string = new std::string(""); +std::string &get_global_error_string() noexcept { + thread_local auto *global_error_string = new std::string(""); return *global_error_string; } @@ -217,7 +224,7 @@ const char *af_err_to_string(const af_err err) { namespace common { -bool &is_stacktrace_enabled() { +bool &is_stacktrace_enabled() noexcept { static bool stacktrace_enabled = true; return stacktrace_enabled; } diff --git a/src/backend/common/err_common.hpp b/src/backend/common/err_common.hpp index 2371c1fc9f..f3d0132f04 100644 --- a/src/backend/common/err_common.hpp +++ b/src/backend/common/err_common.hpp @@ -36,19 +36,25 @@ class AfError : public std::logic_error { boost::stacktrace::stacktrace st); AfError(std::string func, std::string file, const int line, - std::string message, af_err err, boost::stacktrace::stacktrace st); + const std::string& message, af_err err, + boost::stacktrace::stacktrace st); + + AfError(const AfError& other) noexcept = delete; + AfError(AfError&& other) noexcept = default; - const std::string& getFunctionName() const; + const std::string& getFunctionName() const noexcept; - const std::string& getFileName() const; + const std::string& getFileName() const noexcept; - const boost::stacktrace::stacktrace& getStacktrace() const { return st_; }; + const boost::stacktrace::stacktrace& getStacktrace() const noexcept { + return st_; + }; - int getLine() const; + int getLine() const noexcept; - af_err getError() const; + af_err getError() const noexcept; - virtual ~AfError() throw(); + virtual ~AfError() noexcept; }; // TODO: Perhaps add a way to return supported types @@ -62,11 +68,13 @@ class TypeError : public AfError { const int index, const af_dtype type, const boost::stacktrace::stacktrace st); - const std::string& getTypeName() const; + TypeError(TypeError&& other) noexcept = default; + + const std::string& getTypeName() const noexcept; - int getArgIndex() const; + int getArgIndex() const noexcept; - ~TypeError() throw() {} + ~TypeError() noexcept {} }; class ArgumentError : public AfError { @@ -79,12 +87,13 @@ class ArgumentError : public AfError { const int line, const int index, const char* const expectString, const boost::stacktrace::stacktrace st); + ArgumentError(ArgumentError&& other) noexcept = default; - const std::string& getExpectedCondition() const; + const std::string& getExpectedCondition() const noexcept; - int getArgIndex() const; + int getArgIndex() const noexcept; - ~ArgumentError() throw() {} + ~ArgumentError() noexcept {} }; class SupportError : public AfError { @@ -95,10 +104,11 @@ class SupportError : public AfError { SupportError(const char* const func, const char* const file, const int line, const char* const back, const boost::stacktrace::stacktrace st); + SupportError(SupportError&& other) noexcept = default; - ~SupportError() throw() {} + ~SupportError() noexcept {} - const std::string& getBackendName() const; + const std::string& getBackendName() const noexcept; }; class DimensionError : public AfError { @@ -110,13 +120,14 @@ class DimensionError : public AfError { DimensionError(const char* const func, const char* const file, const int line, const int index, const char* const expectString, - const boost::stacktrace::stacktrace st); + const boost::stacktrace::stacktrace& st); + DimensionError(DimensionError&& other) noexcept = default; - const std::string& getExpectedCondition() const; + const std::string& getExpectedCondition() const noexcept; - int getArgIndex() const; + int getArgIndex() const noexcept; - ~DimensionError() throw() {} + ~DimensionError() noexcept {} }; af_err processException(); @@ -187,10 +198,10 @@ af_err set_global_error_string(const std::string& msg, } while (0) static const int MAX_ERR_SIZE = 1024; -std::string& get_global_error_string(); +std::string& get_global_error_string() noexcept; namespace common { -bool& is_stacktrace_enabled(); +bool& is_stacktrace_enabled() noexcept; } // namespace common diff --git a/src/backend/common/graphics_common.cpp b/src/backend/common/graphics_common.cpp index 345e95d15a..e8e24834b9 100644 --- a/src/backend/common/graphics_common.cpp +++ b/src/backend/common/graphics_common.cpp @@ -15,7 +15,8 @@ #include #include -using namespace std; +using std::make_pair; +using std::string; /// Dynamically loads forge function pointer at runtime #define FG_MODULE_FUNCTION_INIT(NAME) \ @@ -138,6 +139,7 @@ INSTANTIATE_GET_FG_TYPE(unsigned char, FG_UINT8); INSTANTIATE_GET_FG_TYPE(unsigned short, FG_UINT16); INSTANTIATE_GET_FG_TYPE(short, FG_INT16); +// NOLINTNEXTLINE(misc-unused-parameters) GLenum glErrorCheck(const char* msg, const char* file, int line) { // Skipped in release mode #ifndef NDEBUG @@ -146,12 +148,15 @@ GLenum glErrorCheck(const char* msg, const char* file, int line) { if (x != GL_NO_ERROR) { char buf[1024]; sprintf(buf, "GL Error at: %s:%d Message: %s Error Code: %d \"%s\"\n", - file, line, msg, (int)x, glGetString(x)); + file, line, msg, static_cast(x), glGetString(x)); AF_ERROR(buf, AF_ERR_INTERNAL); } return x; #else - return (GLenum)0; + UNUSED(msg); + UNUSED(file); + UNUSED(line); + return static_cast(0); #endif } @@ -175,7 +180,7 @@ void makeContextCurrent(fg_window window) { // dir -> true = round up, false = round down double step_round(const double in, const bool dir) { - if (in == 0) return 0; + if (in == 0) { return 0; } static const double __log2 = log10(2); static const double __log4 = log10(4); @@ -192,7 +197,7 @@ double step_round(const double in, const bool dir) { const double dec = std::log10(in / mag); // log of the fraction // This means in is of the for 10^n - if (dec == 0) return in; + if (dec == 0) { return in; } // For negative numbers, -ve round down = +ve round up and vice versa bool op_dir = in > 0 ? dir : !dir; @@ -290,18 +295,18 @@ fg_window ForgeManager::getWindow(const int w, const int h, void ForgeManager::setWindowChartGrid(const fg_window window, const int r, const int c) { - ChartMapIterator iter = mChartMap.find(window); - WindGridMapIterator gIter = mWndGridMap.find(window); + auto chart_iter = mChartMap.find(window); - if (iter != mChartMap.end()) { + if (chart_iter != mChartMap.end()) { // ChartVec found. Clear it. // This has to be cleared as there is no guarantee that existing // chart types(2D/3D) match the future grid requirements - for (const ChartPtr& c : iter->second) { + for (const ChartPtr& c : chart_iter->second) { if (c) { mChartAxesOverrideMap.erase(c->handle); } } - (iter->second).clear(); // Clear ChartList - gIter->second = std::make_pair(1, 1); + (chart_iter->second).clear(); // Clear ChartList + auto gIter = mWndGridMap.find(window); + gIter->second = make_pair(1, 1); } if (r == 0 || c == 0) { @@ -315,26 +320,25 @@ void ForgeManager::setWindowChartGrid(const fg_window window, const int r, ForgeManager::WindowGridDims ForgeManager::getWindowGrid( const fg_window window) { - WindGridMapIterator gIter = mWndGridMap.find(window); - if (gIter == mWndGridMap.end()) { - mWndGridMap[window] = std::make_pair(1, 1); - } + auto gIter = mWndGridMap.find(window); + if (gIter == mWndGridMap.end()) { mWndGridMap[window] = make_pair(1, 1); } return mWndGridMap[window]; } fg_chart ForgeManager::getChart(const fg_window window, const int r, const int c, const fg_chart_type ctype) { - ChartMapIterator iter = mChartMap.find(window); - WindGridMapIterator gIter = mWndGridMap.find(window); + auto gIter = mWndGridMap.find(window); int rows = std::get<0>(gIter->second); int cols = std::get<1>(gIter->second); - if (c >= cols || r >= rows) + if (c >= cols || r >= rows) { AF_ERROR("Window Grid points are out of bounds", AF_ERR_TYPE); + } // upgrade to exclusive access to make changes - ChartPtr& chart = (iter->second)[c * rows + r]; + auto chart_iter = mChartMap.find(window); + ChartPtr& chart = (chart_iter->second)[c * rows + r]; if (!chart) { fg_chart temp = NULL; @@ -356,12 +360,13 @@ fg_chart ForgeManager::getChart(const fg_window window, const int r, return chart->handle; } -long long ForgeManager::genImageKey(int w, int h, fg_channel_format mode, - fg_dtype type) { - assert(w <= 2ll << 16); - assert(h <= 2ll << 16); - long long key = ((w & _16BIT) << 16) | (h & _16BIT); - key = ((((key << 16) | (mode & _16BIT)) << 16) | (type | _16BIT)); +unsigned long long ForgeManager::genImageKey(unsigned w, unsigned h, + fg_channel_format mode, + fg_dtype type) { + assert(w <= 2U << 16U); + assert(h <= 2U << 16U); + unsigned long long key = ((w & _16BIT) << 16U) | (h & _16BIT); + key = ((((key << 16U) | (mode & _16BIT)) << 16U) | (type | _16BIT)); return key; } @@ -369,8 +374,8 @@ fg_image ForgeManager::getImage(int w, int h, fg_channel_format mode, fg_dtype type) { auto key = genImageKey(w, h, mode, type); - ChartKey keypair = std::make_pair(key, nullptr); - ImageMapIterator iter = mImgMap.find(keypair); + ChartKey keypair = std::make_pair(key, nullptr); + auto iter = mImgMap.find(keypair); if (iter == mImgMap.end()) { fg_image img = nullptr; @@ -384,8 +389,8 @@ fg_image ForgeManager::getImage(fg_chart chart, int w, int h, fg_channel_format mode, fg_dtype type) { auto key = genImageKey(w, h, mode, type); - ChartKey keypair = std::make_pair(key, chart); - ImageMapIterator iter = mImgMap.find(keypair); + ChartKey keypair = make_pair(key, chart); + auto iter = mImgMap.find(keypair); if (iter == mImgMap.end()) { fg_chart_type chart_type; @@ -405,11 +410,13 @@ fg_image ForgeManager::getImage(fg_chart chart, int w, int h, fg_plot ForgeManager::getPlot(fg_chart chart, int nPoints, fg_dtype dtype, fg_plot_type ptype, fg_marker_type mtype) { - long long key = (((long long)(nPoints)&_48BIT) << 16); - key |= (((dtype & _4BIT) << 12) | ((ptype & _4BIT) << 8) | (mtype & _8BIT)); + unsigned long long key = + ((static_cast(nPoints) & _48BIT) << 16U); + key |= + (((dtype & _4BIT) << 12U) | ((ptype & _4BIT) << 8U) | (mtype & _8BIT)); - ChartKey keypair = std::make_pair(key, chart); - PlotMapIterator iter = mPltMap.find(keypair); + ChartKey keypair = std::make_pair(key, chart); + auto iter = mPltMap.find(keypair); if (iter == mPltMap.end()) { fg_chart_type chart_type; @@ -427,10 +434,12 @@ fg_plot ForgeManager::getPlot(fg_chart chart, int nPoints, fg_dtype dtype, fg_histogram ForgeManager::getHistogram(fg_chart chart, int nBins, fg_dtype type) { - long long key = (((long long)(nBins)&_48BIT) << 16) | (type & _16BIT); + unsigned long long key = + ((static_cast(nBins) & _48BIT) << 16U) | + (type & _16BIT); - ChartKey keypair = std::make_pair(key, chart); - HistogramMapIterator iter = mHstMap.find(keypair); + ChartKey keypair = make_pair(key, chart); + auto iter = mHstMap.find(keypair); if (iter == mHstMap.end()) { fg_chart_type chart_type; @@ -449,12 +458,12 @@ fg_histogram ForgeManager::getHistogram(fg_chart chart, int nBins, fg_surface ForgeManager::getSurface(fg_chart chart, int nX, int nY, fg_dtype type) { - long long surfaceSize = nX * (long long)(nY); - assert(surfaceSize <= 2ll << 48); - long long key = ((surfaceSize & _48BIT) << 16) | (type & _16BIT); + unsigned long long surfaceSize = nX * static_cast(nY); + assert(surfaceSize <= 2ULL << 48ULL); + unsigned long long key = ((surfaceSize & _48BIT) << 16U) | (type & _16BIT); - ChartKey keypair = std::make_pair(key, chart); - SurfaceMapIterator iter = mSfcMap.find(keypair); + ChartKey keypair = make_pair(key, chart); + auto iter = mSfcMap.find(keypair); if (iter == mSfcMap.end()) { fg_chart_type chart_type; @@ -474,10 +483,12 @@ fg_surface ForgeManager::getSurface(fg_chart chart, int nX, int nY, fg_vector_field ForgeManager::getVectorField(fg_chart chart, int nPoints, fg_dtype type) { - long long key = (((long long)(nPoints)&_48BIT) << 16) | (type & _16BIT); + unsigned long long key = + ((static_cast(nPoints) & _48BIT) << 16U) | + (type & _16BIT); - ChartKey keypair = std::make_pair(key, chart); - VecFieldMapIterator iter = mVcfMap.find(keypair); + ChartKey keypair = make_pair(key, chart); + auto iter = mVcfMap.find(keypair); if (iter == mVcfMap.end()) { fg_chart_type chart_type; @@ -493,7 +504,7 @@ fg_vector_field ForgeManager::getVectorField(fg_chart chart, int nPoints, } bool ForgeManager::getChartAxesOverride(const fg_chart chart) { - AxesOverrideIterator iter = mChartAxesOverrideMap.find(chart); + auto iter = mChartAxesOverrideMap.find(chart); if (iter == mChartAxesOverrideMap.end()) { AF_ERROR("Chart Not Found!", AF_ERR_INTERNAL); } @@ -501,7 +512,7 @@ bool ForgeManager::getChartAxesOverride(const fg_chart chart) { } void ForgeManager::setChartAxesOverride(const fg_chart chart, bool flag) { - AxesOverrideIterator iter = mChartAxesOverrideMap.find(chart); + auto iter = mChartAxesOverrideMap.find(chart); if (iter == mChartAxesOverrideMap.end()) { AF_ERROR("Chart Not Found!", AF_ERR_INTERNAL); } diff --git a/src/backend/common/graphics_common.hpp b/src/backend/common/graphics_common.hpp index 911c1251a9..1f2b9f60b1 100644 --- a/src/backend/common/graphics_common.hpp +++ b/src/backend/common/graphics_common.hpp @@ -244,15 +244,17 @@ class ForgeManager { void setChartAxesOverride(const fg_chart chart, bool flag = true); private: - constexpr static unsigned int WIDTH = 1280; - constexpr static unsigned int HEIGHT = 720; - constexpr static long long _4BIT = 0x000000000000000F; - constexpr static long long _8BIT = 0x00000000000000FF; - constexpr static long long _16BIT = 0x000000000000FFFF; - constexpr static long long _32BIT = 0x00000000FFFFFFFF; - constexpr static long long _48BIT = 0x0000FFFFFFFFFFFF; - - long long genImageKey(int w, int h, fg_channel_format mode, fg_dtype type); + constexpr static unsigned int WIDTH = 1280; + constexpr static unsigned int HEIGHT = 720; + constexpr static unsigned long long _4BIT = 0x000000000000000F; + constexpr static unsigned long long _8BIT = 0x00000000000000FF; + constexpr static unsigned long long _16BIT = 0x000000000000FFFF; + constexpr static unsigned long long _32BIT = 0x00000000FFFFFFFF; + constexpr static unsigned long long _48BIT = 0x0000FFFFFFFFFFFF; + + static unsigned long long genImageKey(unsigned w, unsigned h, + fg_channel_format mode, + fg_dtype type); #define DEFINE_WRAPPER_OBJECT(OBJECT, RELEASE) \ struct OBJECT { \ @@ -281,7 +283,7 @@ class ForgeManager { using HistogramPtr = std::unique_ptr; using VectorFieldPtr = std::unique_ptr; using ChartList = std::vector; - using ChartKey = std::pair; + using ChartKey = std::pair; using ChartMapIterator = std::map::iterator; using WindGridMapIterator = std::map::iterator; diff --git a/src/backend/common/half.hpp b/src/backend/common/half.hpp index 8bb8348ff2..1f29b517a1 100644 --- a/src/backend/common/half.hpp +++ b/src/backend/common/half.hpp @@ -991,6 +991,10 @@ CONSTEXPR_DH static inline bool operator<(common::half lhs, #ifndef __CUDA_ARCH__ std::ostream& operator<<(std::ostream& os, const half& val); +static inline std::string to_string(const half& val) { + return std::to_string(static_cast(val)); +} + static inline std::string to_string(const half&& val) { return std::to_string(static_cast(val)); } diff --git a/src/backend/common/host_memory.cpp b/src/backend/common/host_memory.cpp index a97aa12987..51a01e2164 100644 --- a/src/backend/common/host_memory.cpp +++ b/src/backend/common/host_memory.cpp @@ -80,7 +80,8 @@ size_t getHostMemorySize() { #elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE) /* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- */ - return (size_t)sysconf(_SC_PHYS_PAGES) * (size_t)sysconf(_SC_PAGESIZE); + return static_cast(sysconf(_SC_PHYS_PAGES)) * + static_cast(sysconf(_SC_PAGESIZE)); #elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGE_SIZE) /* Legacy. -------------------------------------------------- */ diff --git a/src/backend/common/jit/Node.cpp b/src/backend/common/jit/Node.cpp index 9fdcfd72d2..bf17e2078e 100644 --- a/src/backend/common/jit/Node.cpp +++ b/src/backend/common/jit/Node.cpp @@ -12,7 +12,8 @@ #include #include -using namespace std; + +using std::vector; namespace common { @@ -20,7 +21,7 @@ int Node::getNodesMap(Node_map_t &node_map, vector &full_nodes, vector &full_ids) const { auto iter = node_map.find(this); if (iter == node_map.end()) { - Node_ids ids; + Node_ids ids{}; for (int i = 0; i < kMaxChildren && m_children[i] != nullptr; i++) { ids.child_ids[i] = diff --git a/src/backend/common/module_loading_unix.cpp b/src/backend/common/module_loading_unix.cpp index 711ec1cfca..81dc4e391c 100644 --- a/src/backend/common/module_loading_unix.cpp +++ b/src/backend/common/module_loading_unix.cpp @@ -28,13 +28,10 @@ void unloadLibrary(LibHandle handle) { dlclose(handle); } string getErrorMessage() { char* errMsg = dlerror(); - if (errMsg) { - return string(errMsg); - } else { - // constructing std::basic_string from NULL/0 address is - // invalid and has undefined behavior - return string("No Error"); - } + if (errMsg) { return string(errMsg); } + // constructing std::basic_string from NULL/0 address is + // invalid and has undefined behavior + return string("No Error"); } } // namespace common diff --git a/src/backend/common/sparse_helpers.hpp b/src/backend/common/sparse_helpers.hpp index 3dda68b16e..2666cec978 100644 --- a/src/backend/common/sparse_helpers.hpp +++ b/src/backend/common/sparse_helpers.hpp @@ -56,9 +56,9 @@ void destroySparseArray(SparseArray *sparse); /// Performs a deep copy of the \p input array. /// -/// \param[in] input The sparse array that is to be copied +/// \param[in] other The sparse array that is to be copied /// \returns A deep copy of the input sparse array template -SparseArray copySparseArray(const SparseArray &input); +SparseArray copySparseArray(const SparseArray &other); } // namespace common diff --git a/src/backend/common/util.cpp b/src/backend/common/util.cpp index a9f2941ca5..ee07d7fa7b 100644 --- a/src/backend/common/util.cpp +++ b/src/backend/common/util.cpp @@ -62,7 +62,7 @@ const char* getName(af_dtype type) { void saveKernel(const std::string& funcName, const std::string& jit_ker, const std::string& ext) { static const char* jitKernelsOutput = getenv(saveJitKernelsEnvVarName); - if (!jitKernelsOutput) return; + if (!jitKernelsOutput) { return; } if (std::strcmp(jitKernelsOutput, "stdout") == 0) { fputs(jit_ker.c_str(), stdout); return; @@ -74,12 +74,13 @@ void saveKernel(const std::string& funcName, const std::string& jit_ker, // Path to a folder const std::string ffp = std::string(jitKernelsOutput) + AF_PATH_SEPARATOR + funcName + ext; - FILE* f = fopen(ffp.c_str(), "w"); + FILE* f = fopen(ffp.c_str(), "we"); if (!f) { fprintf(stderr, "Cannot open file %s\n", ffp.c_str()); return; } - if (fputs(jit_ker.c_str(), f) == EOF) + if (fputs(jit_ker.c_str(), f) == EOF) { fprintf(stderr, "Failed to write kernel to file %s\n", ffp.c_str()); + } fclose(f); } diff --git a/src/backend/cpu/Array.cpp b/src/backend/cpu/Array.cpp index 7c1d3a2de2..92c058b036 100644 --- a/src/backend/cpu/Array.cpp +++ b/src/backend/cpu/Array.cpp @@ -34,6 +34,7 @@ #include #include #include +#include using af::dim4; using common::half; @@ -44,6 +45,7 @@ using cpu::jit::Node_map_t; using cpu::jit::Node_ptr; using std::copy; using std::is_standard_layout; +using std::move; using std::vector; namespace cpu { @@ -56,7 +58,7 @@ Node_ptr bufferNodePtr() { template Array::Array(dim4 dims) : info(getActiveDeviceId(), dims, 0, calcStrides(dims), - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data(memAlloc(dims.elements()).release(), memFree) , data_dims(dims) , node(bufferNodePtr()) @@ -67,8 +69,8 @@ template Array::Array(const dim4 &dims, T *const in_data, bool is_device, bool copy_device) : info(getActiveDeviceId(), dims, 0, calcStrides(dims), - (af_dtype)dtype_traits::af_type) - , data((is_device & !copy_device) ? (T *)in_data + static_cast(dtype_traits::af_type)) + , data((is_device & !copy_device) ? in_data : memAlloc(dims.elements()).release(), memFree) , data_dims(dims) @@ -90,10 +92,10 @@ Array::Array(const dim4 &dims, T *const in_data, bool is_device, template Array::Array(const af::dim4 &dims, Node_ptr n) : info(getActiveDeviceId(), dims, 0, calcStrides(dims), - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data() , data_dims(dims) - , node(n) + , node(move(n)) , ready(false) , owner(true) {} @@ -101,7 +103,7 @@ template Array::Array(const Array &parent, const dim4 &dims, const dim_t &offset_, const dim4 &strides) : info(parent.getDevId(), dims, offset_, strides, - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data(parent.getData()) , data_dims(parent.getDataDims()) , node(bufferNodePtr()) @@ -112,7 +114,7 @@ template Array::Array(const dim4 &dims, const dim4 &strides, dim_t offset_, T *const in_data, bool is_device) : info(getActiveDeviceId(), dims, offset_, strides, - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data(is_device ? in_data : memAlloc(info.total()).release(), memFree) , data_dims(dims) @@ -128,9 +130,10 @@ Array::Array(const dim4 &dims, const dim4 &strides, dim_t offset_, template void Array::eval() { - if (isReady()) return; - if (getQueue().is_worker()) + if (isReady()) { return; } + if (getQueue().is_worker()) { AF_ERROR("Array not evaluated", AF_ERR_INTERNAL); + } this->setId(getActiveDeviceId()); @@ -144,7 +147,7 @@ void Array::eval() { template void Array::eval() const { - if (isReady()) return; + if (isReady()) { return; } const_cast *>(this)->eval(); } @@ -162,8 +165,9 @@ void evalMultiple(vector *> array_ptrs) { vector *> output_arrays; vector nodes; vector> params; - if (getQueue().is_worker()) + if (getQueue().is_worker()) { AF_ERROR("Array not evaluated", AF_ERR_INTERNAL); + } // Check if all the arrays have the same dimension auto it = std::adjacent_find(begin(array_ptrs), end(array_ptrs), @@ -178,7 +182,7 @@ void evalMultiple(vector *> array_ptrs) { } for (Array *array : array_ptrs) { - if (array->ready) continue; + if (array->ready) { continue; } array->setId(getActiveDeviceId()); array->data = @@ -189,21 +193,20 @@ void evalMultiple(vector *> array_ptrs) { nodes.push_back(array->node); } - if (output_arrays.size() > 0) { + if (!output_arrays.empty()) { getQueue().enqueue(kernel::evalMultiple, params, nodes); for (Array *array : output_arrays) { array->ready = true; array->node = bufferNodePtr(); } } - return; } template Node_ptr Array::getNode() const { if (node->isBuffer()) { - BufferNode *bufNode = reinterpret_cast *>(node.get()); - unsigned bytes = this->getDataDims().elements() * sizeof(T); + auto *bufNode = reinterpret_cast *>(node.get()); + unsigned bytes = this->getDataDims().elements() * sizeof(T); bufNode->setData(data, bytes, getOffset(), dims().get(), strides().get(), isLinear()); } @@ -233,8 +236,8 @@ Array createEmptyArray(const dim4 &dims) { template kJITHeuristics passesJitHeuristics(Node *root_node) { - if (!evalFlag()) return kJITHeuristics::Pass; - if (root_node->getHeight() >= (int)getMaxJitSize()) { + if (!evalFlag()) { return kJITHeuristics::Pass; } + if (root_node->getHeight() >= static_cast(getMaxJitSize())) { return kJITHeuristics::TreeHeight; } @@ -277,18 +280,18 @@ Array createSubArray(const Array &parent, const vector &index, return createSubArray(parentCopy, index, copy); } - dim4 pDims = parent.dims(); - dim4 dims = toDims(index, pDims); - dim4 strides = toStride(index, dDims); + const dim4 &pDims = parent.dims(); + dim4 dims = toDims(index, pDims); + dim4 strides = toStride(index, dDims); // Find total offsets after indexing dim4 offsets = toOffset(index, pDims); dim_t offset = parent.getOffset(); - for (int i = 0; i < 4; i++) offset += offsets[i] * parent_strides[i]; + for (int i = 0; i < 4; i++) { offset += offsets[i] * parent_strides[i]; } Array out = Array(parent, dims, offset, strides); - if (!copy) return out; + if (!copy) { return out; } if (strides[0] != 1 || strides[1] < 0 || strides[2] < 0 || strides[3] < 0) { out = copyArray(out); @@ -316,7 +319,7 @@ template void writeDeviceDataArray(Array &arr, const void *const data, const size_t bytes) { if (!arr.isOwner()) { arr = copyArray(arr); } - memcpy(arr.get(), (const T *const)data, bytes); + memcpy(arr.get(), static_cast(data), bytes); } template diff --git a/src/backend/cpu/Array.hpp b/src/backend/cpu/Array.hpp index 86a5af8d9d..c722975e4e 100644 --- a/src/backend/cpu/Array.hpp +++ b/src/backend/cpu/Array.hpp @@ -43,7 +43,7 @@ using af::dim4; using std::shared_ptr; template -void evalMultiple(std::vector *> arrays); +void evalMultiple(std::vector *> array_ptrs); // Creates a new Array object on the heap and returns a reference to it. template diff --git a/src/backend/cpu/Event.cpp b/src/backend/cpu/Event.cpp index 83454529a6..e0c67519d9 100644 --- a/src/backend/cpu/Event.cpp +++ b/src/backend/cpu/Event.cpp @@ -14,9 +14,10 @@ #include #include #include - #include +using std::make_unique; + namespace cpu { /// \brief Creates a new event and marks it in the queue Event makeEvent(cpu::queue& queue) { @@ -26,8 +27,7 @@ Event makeEvent(cpu::queue& queue) { } af_event createEvent() { - std::unique_ptr e; - e.reset(new Event()); + auto e = make_unique(); // Ensure that the default queue is initialized getQueue(); if (e->create() != 0) { diff --git a/src/backend/cpu/anisotropic_diffusion.cpp b/src/backend/cpu/anisotropic_diffusion.cpp index 3a7f518979..97818aea50 100644 --- a/src/backend/cpu/anisotropic_diffusion.cpp +++ b/src/backend/cpu/anisotropic_diffusion.cpp @@ -16,12 +16,13 @@ template void anisotropicDiffusion(Array& inout, const float dt, const float mct, const af::fluxFunction fftype, const af::diffusionEq eq) { - if (eq == AF_DIFFUSION_MCDE) + if (eq == AF_DIFFUSION_MCDE) { getQueue().enqueue(kernel::anisotropicDiffusion, inout, dt, mct, fftype); - else + } else { getQueue().enqueue(kernel::anisotropicDiffusion, inout, dt, mct, fftype); + } } #define INSTANTIATE(T) \ diff --git a/src/backend/cpu/assign.cpp b/src/backend/cpu/assign.cpp index d6f60c72db..0f32fab35d 100644 --- a/src/backend/cpu/assign.cpp +++ b/src/backend/cpu/assign.cpp @@ -26,7 +26,6 @@ #include using af::dim4; -using common::half; using std::vector; namespace cpu { @@ -70,6 +69,6 @@ INSTANTIATE(uchar) INSTANTIATE(char) INSTANTIATE(ushort) INSTANTIATE(short) -INSTANTIATE(half) +INSTANTIATE(common::half) } // namespace cpu diff --git a/src/backend/cpu/bilateral.cpp b/src/backend/cpu/bilateral.cpp index 8198689a62..b70da95376 100644 --- a/src/backend/cpu/bilateral.cpp +++ b/src/backend/cpu/bilateral.cpp @@ -22,7 +22,7 @@ namespace cpu { template Array bilateral(const Array &in, const float &s_sigma, const float &c_sigma) { - const dim4 dims = in.dims(); + const dim4 &dims = in.dims(); Array out = createEmptyArray(dims); getQueue().enqueue(kernel::bilateral, out, in, s_sigma, c_sigma); diff --git a/src/backend/cpu/blas.cpp b/src/backend/cpu/blas.cpp index 3640c95af4..bd516c209e 100644 --- a/src/backend/cpu/blas.cpp +++ b/src/backend/cpu/blas.cpp @@ -36,12 +36,7 @@ using af::dtype_traits; using common::half; using common::is_complex; -using std::add_const; -using std::add_pointer; using std::conditional; -using std::enable_if; -using std::is_floating_point; -using std::remove_const; using std::vector; namespace cpu { @@ -115,14 +110,18 @@ using ptr_type = typename conditional::value, typename blas_base::type *, T *>::type; template -struct scale_type { +class scale_type { const T val; - scale_type(const T *val_ptr) : val(*val_ptr) {} + + public: + explicit scale_type(const T *val_ptr) : val(*val_ptr) {} using api_type = const typename conditional< is_complex::value, const typename blas_base::type *, const typename conditional::type>::type; - api_type getScale() const { return val; } + api_type getScale() const { // NOLINT(readability-const-return-type) + return val; + } }; #define INSTANTIATE_BATCHED(TYPE) \ @@ -132,8 +131,8 @@ struct scale_type { return &val; \ } -INSTANTIATE_BATCHED(float); -INSTANTIATE_BATCHED(double); +INSTANTIATE_BATCHED(float); // NOLINT(readability-const-return-type) +INSTANTIATE_BATCHED(double); // NOLINT(readability-const-return-type) #undef INSTANTIATE_BATCHED #define INSTANTIATE_COMPLEX(TYPE, BATCHED) \ @@ -143,10 +142,10 @@ INSTANTIATE_BATCHED(double); return reinterpret_cast::type *const>(&val); \ } -INSTANTIATE_COMPLEX(cfloat, true); -INSTANTIATE_COMPLEX(cfloat, false); -INSTANTIATE_COMPLEX(cdouble, true); -INSTANTIATE_COMPLEX(cdouble, false); +INSTANTIATE_COMPLEX(cfloat, true); // NOLINT(readability-const-return-type) +INSTANTIATE_COMPLEX(cfloat, false); // NOLINT(readability-const-return-type) +INSTANTIATE_COMPLEX(cdouble, true); // NOLINT(readability-const-return-type) +INSTANTIATE_COMPLEX(cdouble, false); // NOLINT(readability-const-return-type) #undef INSTANTIATE_COMPLEX template @@ -228,12 +227,12 @@ void gemm(Array &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, const int aColDim = (lOpts == CblasNoTrans) ? 1 : 0; const int bColDim = (rOpts == CblasNoTrans) ? 1 : 0; - const dim4 lDims = lhs.dims(); - const dim4 rDims = rhs.dims(); - const int M = lDims[aRowDim]; - const int N = rDims[bColDim]; - const int K = lDims[aColDim]; - const dim4 oDims = out.dims(); + const dim4 &lDims = lhs.dims(); + const dim4 &rDims = rhs.dims(); + const int M = lDims[aRowDim]; + const int N = rDims[bColDim]; + const int K = lDims[aColDim]; + const dim4 oDims = out.dims(); using BT = typename blas_base::type; using CBT = const typename blas_base::type; @@ -267,7 +266,7 @@ void gemm(Array &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, oStrides[1]); } } else { - int batchSize = oDims[2] * oDims[3]; + int batchSize = static_cast(oDims[2] * oDims[3]); const bool is_l_d2_batched = oDims[2] == lDims[2]; const bool is_l_d3_batched = oDims[3] == lDims[3]; @@ -279,13 +278,13 @@ void gemm(Array &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, vector optrs(batchSize); for (int n = 0; n < batchSize; n++) { - int w = n / oDims[2]; - int z = n - w * oDims[2]; + ptrdiff_t w = n / oDims[2]; + ptrdiff_t z = n - w * oDims[2]; - int loff = z * (is_l_d2_batched * lStrides[2]) + - w * (is_l_d3_batched * lStrides[3]); - int roff = z * (is_r_d2_batched * rStrides[2]) + - w * (is_r_d3_batched * rStrides[3]); + ptrdiff_t loff = z * (is_l_d2_batched * lStrides[2]) + + w * (is_l_d3_batched * lStrides[3]); + ptrdiff_t roff = z * (is_r_d2_batched * rStrides[2]) + + w * (is_r_d3_batched * rStrides[3]); lptrs[n] = reinterpret_cast(left.get() + loff); rptrs[n] = reinterpret_cast(right.get() + roff); @@ -330,9 +329,9 @@ template<> void gemm(Array &out, af_mat_prop optLhs, af_mat_prop optRhs, const half *alpha, const Array &lhs, const Array &rhs, const half *beta) { - Array outArr = createValueArray(out.dims(), 0); - const float float_alpha = static_cast(*alpha); - const float float_beta = static_cast(*beta); + Array outArr = createValueArray(out.dims(), 0); + const auto float_alpha = static_cast(*alpha); + const auto float_beta = static_cast(*beta); gemm(outArr, optLhs, optRhs, &float_alpha, cast(lhs), cast(rhs), &float_beta); copyArray(out, outArr); diff --git a/src/backend/cpu/cholesky.cpp b/src/backend/cpu/cholesky.cpp index efe763583a..90519cda3f 100644 --- a/src/backend/cpu/cholesky.cpp +++ b/src/backend/cpu/cholesky.cpp @@ -50,10 +50,11 @@ Array cholesky(int *info, const Array &in, const bool is_upper) { Array out = copyArray(in); *info = cholesky_inplace(out, is_upper); - if (is_upper) + if (is_upper) { triangle(out, out); - else + } else { triangle(out, out); + } return out; } @@ -64,7 +65,7 @@ int cholesky_inplace(Array &in, const bool is_upper) { int N = iDims[0]; char uplo = 'L'; - if (is_upper) uplo = 'U'; + if (is_upper) { uplo = 'U'; } int info = 0; auto func = [&](int *info, Param in) { diff --git a/src/backend/cpu/convolve.cpp b/src/backend/cpu/convolve.cpp index 4011326fc7..efea6e08be 100644 --- a/src/backend/cpu/convolve.cpp +++ b/src/backend/cpu/convolve.cpp @@ -29,7 +29,6 @@ using af::dim4; using common::flip; using common::half; -using std::vector; namespace cpu { @@ -51,7 +50,7 @@ Array convolve(Array const &signal, Array const &filter, } else { oDims = sDims; if (kind == AF_BATCH_RHS) { - for (dim_t i = baseDim; i < 4; ++i) oDims[i] = fDims[i]; + for (dim_t i = baseDim; i < 4; ++i) { oDims[i] = fDims[i]; } } } @@ -66,16 +65,16 @@ Array convolve(Array const &signal, Array const &filter, template Array convolve2(Array const &signal, Array const &c_filter, Array const &r_filter) { - auto sDims = signal.dims(); - dim4 tDims = sDims; - dim4 oDims = sDims; + const auto &sDims = signal.dims(); + dim4 tDims = sDims; + dim4 oDims = sDims; if (expand) { auto cfDims = c_filter.dims(); auto rfDims = r_filter.dims(); - dim_t cflen = (dim_t)cfDims.elements(); - dim_t rflen = (dim_t)rfDims.elements(); + auto cflen = cfDims.elements(); + auto rflen = rfDims.elements(); // separable convolve only does AF_BATCH_NONE and standard // batch(AF_BATCH_LHS) tDims[0] += cflen - 1; @@ -134,8 +133,8 @@ INSTANTIATE(intl, float) template Array convolve2_unwrap(const Array &signal, const Array &filter, - const dim4 stride, const dim4 padding, - const dim4 dilation) { + const dim4 &stride, const dim4 &padding, + const dim4 &dilation) { dim4 sDims = signal.dims(); dim4 fDims = filter.dims(); @@ -190,11 +189,12 @@ template Array conv2DataGradient(const Array &incoming_gradient, const Array &original_signal, const Array &original_filter, - const Array &convolved_output, af::dim4 stride, - af::dim4 padding, af::dim4 dilation) { - const dim4 cDims = incoming_gradient.dims(); - const dim4 sDims = original_signal.dims(); - const dim4 fDims = original_filter.dims(); + const Array & /*convolved_output*/, + af::dim4 stride, af::dim4 padding, + af::dim4 dilation) { + const dim4 &cDims = incoming_gradient.dims(); + const dim4 &sDims = original_signal.dims(); + const dim4 &fDims = original_filter.dims(); Array collapsed_filter = flip(original_filter, {1, 1, 0, 0}); collapsed_filter.modDims(dim4(fDims[0] * fDims[1] * fDims[2], fDims[3])); @@ -221,10 +221,11 @@ template Array conv2FilterGradient(const Array &incoming_gradient, const Array &original_signal, const Array &original_filter, - const Array &convolved_output, af::dim4 stride, - af::dim4 padding, af::dim4 dilation) { - const dim4 cDims = incoming_gradient.dims(); - const dim4 fDims = original_filter.dims(); + const Array & /*convolved_output*/, + af::dim4 stride, af::dim4 padding, + af::dim4 dilation) { + const dim4 &cDims = incoming_gradient.dims(); + const dim4 &fDims = original_filter.dims(); const bool retCols = false; Array unwrapped = diff --git a/src/backend/cpu/copy.cpp b/src/backend/cpu/copy.cpp index f68713790d..359db199cc 100644 --- a/src/backend/cpu/copy.cpp +++ b/src/backend/cpu/copy.cpp @@ -23,7 +23,7 @@ #include #include -using common::half; +using common::half; // NOLINT(misc-unused-using-decls) bug in clang-tidy using common::is_complex; namespace cpu { diff --git a/src/backend/cpu/copy.hpp b/src/backend/cpu/copy.hpp index 5b02711b63..46d7de9a27 100644 --- a/src/backend/cpu/copy.hpp +++ b/src/backend/cpu/copy.hpp @@ -20,7 +20,7 @@ class dim4; namespace cpu { template -void copyData(T *data, const Array &A); +void copyData(T *to, const Array &from); template Array copyArray(const Array &A); diff --git a/src/backend/cpu/device_manager.cpp b/src/backend/cpu/device_manager.cpp index dc00900161..deb5fd0c3b 100644 --- a/src/backend/cpu/device_manager.cpp +++ b/src/backend/cpu/device_manager.cpp @@ -35,13 +35,14 @@ CPUInfo::CPUInfo() CPUID cpuID0(0, 0); uint32_t HFS = cpuID0.EAX(); - mVendorId += string((const char*)&cpuID0.EBX(), 4); - mVendorId += string((const char*)&cpuID0.EDX(), 4); - mVendorId += string((const char*)&cpuID0.ECX(), 4); + mVendorId += string(reinterpret_cast(&cpuID0.EBX()), 4); + mVendorId += string(reinterpret_cast(&cpuID0.EDX()), 4); + mVendorId += string(reinterpret_cast(&cpuID0.ECX()), 4); string upVId = mVendorId; - for_each(upVId.begin(), upVId.end(), [](char& in) { in = ::toupper(in); }); + for_each(upVId.begin(), upVId.end(), + [](char& in) { in = static_cast(::toupper(in)); }); // Get num of cores if (upVId.find("INTEL") != std::string::npos) { @@ -49,7 +50,7 @@ CPUInfo::CPUInfo() if (HFS >= 11) { for (int lvl = 0; lvl < MAX_INTEL_TOP_LVL; ++lvl) { CPUID cpuID4(0x0B, lvl); - uint32_t currLevel = (LVL_TYPE & cpuID4.ECX()) >> 8; + uint32_t currLevel = (LVL_TYPE & cpuID4.ECX()) >> 8U; switch (currLevel) { case 0x01: mNumSMT = LVL_CORES & cpuID4.EBX(); break; case 0x02: mNumLogCpus = LVL_CORES & cpuID4.EBX(); break; @@ -61,15 +62,15 @@ CPUInfo::CPUInfo() mNumCores = mNumLogCpus / (mNumSMT == 0 ? 1 : mNumSMT); } else { if (HFS >= 1) { - mNumLogCpus = (cpuID1.EBX() >> 16) & 0xFF; + mNumLogCpus = (cpuID1.EBX() >> 16U) & 0xFFU; if (HFS >= 4) { - mNumCores = 1 + ((CPUID(4, 0).EAX() >> 26) & 0x3F); + mNumCores = 1 + ((CPUID(4, 0).EAX() >> 26U) & 0x3FU); } } if (mIsHTT) { if (!(mNumCores > 1)) { mNumCores = 1; - mNumLogCpus = (mNumLogCpus >= 2 ? mNumLogCpus : 2); + mNumLogCpus = (mNumLogCpus >= 2 ? mNumLogCpus : 2U); } } else { mNumCores = mNumLogCpus = 1; @@ -78,9 +79,9 @@ CPUInfo::CPUInfo() } else if (upVId.find("AMD") != std::string::npos) { mVendorId = "AMD"; if (HFS >= 1) { - mNumLogCpus = (cpuID1.EBX() >> 16) & 0xFF; - if (CPUID(0x80000000, 0).EAX() >= 8) { - mNumCores = 1 + ((CPUID(0x80000008, 0).ECX() & 0xFF)); + mNumLogCpus = (cpuID1.EBX() >> 16U) & 0xFFU; + if (CPUID(0x80000000, 0).EAX() >= 8U) { + mNumCores = 1 + ((CPUID(0x80000008, 0).ECX() & 0xFFU)); } } if (mIsHTT) { @@ -98,12 +99,12 @@ CPUInfo::CPUInfo() // This seems to be working for both Intel & AMD vendors for (unsigned i = 0x80000002; i < 0x80000005; ++i) { CPUID cpuID(i, 0); - mModelName += string((const char*)&cpuID.EAX(), 4); - mModelName += string((const char*)&cpuID.EBX(), 4); - mModelName += string((const char*)&cpuID.ECX(), 4); - mModelName += string((const char*)&cpuID.EDX(), 4); + mModelName += string(reinterpret_cast(&cpuID.EAX()), 4); + mModelName += string(reinterpret_cast(&cpuID.EBX()), 4); + mModelName += string(reinterpret_cast(&cpuID.ECX()), 4); + mModelName += string(reinterpret_cast(&cpuID.EDX()), 4); } - mModelName = string(mModelName.c_str()); + mModelName.shrink_to_fit(); } #else @@ -133,7 +134,7 @@ DeviceManager::DeviceManager() } DeviceManager& DeviceManager::getInstance() { - static DeviceManager* my_instance = new DeviceManager(); + static auto* my_instance = new DeviceManager(); return *my_instance; } @@ -166,6 +167,8 @@ void DeviceManager::setMemoryManager( void DeviceManager::setMemoryManagerPinned( std::unique_ptr newMgr) { + UNUSED(newMgr); + UNUSED(this); AF_ERROR("Using pinned memory with CPU is not supported", AF_ERR_NOT_SUPPORTED); } diff --git a/src/backend/cpu/device_manager.hpp b/src/backend/cpu/device_manager.hpp index ffd983d048..eeb027ca5e 100644 --- a/src/backend/cpu/device_manager.hpp +++ b/src/backend/cpu/device_manager.hpp @@ -80,9 +80,9 @@ class CPUInfo { // Attributes std::string mVendorId; std::string mModelName; - int mNumSMT; - int mNumCores; - int mNumLogCpus; + unsigned mNumSMT; + unsigned mNumCores; + unsigned mNumLogCpus; bool mIsHTT; }; diff --git a/src/backend/cpu/diagonal.cpp b/src/backend/cpu/diagonal.cpp index e52b0d5c0c..9a8c61fc48 100644 --- a/src/backend/cpu/diagonal.cpp +++ b/src/backend/cpu/diagonal.cpp @@ -19,13 +19,15 @@ #include #include -using common::half; +using common::half; // NOLINT(misc-unused-using-decls) bug in clang-tidy +using std::abs; // NOLINT(misc-unused-using-decls) bug in clang-tidy +using std::min; // NOLINT(misc-unused-using-decls) bug in clang-tidy namespace cpu { template Array diagCreate(const Array &in, const int num) { - int size = in.dims()[0] + std::abs(num); + int size = in.dims()[0] + abs(num); int batch = in.dims()[1]; Array out = createEmptyArray(dim4(size, size, batch)); @@ -36,9 +38,9 @@ Array diagCreate(const Array &in, const int num) { template Array diagExtract(const Array &in, const int num) { - const dim4 idims = in.dims(); - dim_t size = std::min(idims[0], idims[1]) - std::abs(num); - Array out = createEmptyArray(dim4(size, 1, idims[2], idims[3])); + const dim4 &idims = in.dims(); + dim_t size = min(idims[0], idims[1]) - abs(num); + Array out = createEmptyArray(dim4(size, 1, idims[2], idims[3])); getQueue().enqueue(kernel::diagExtract, out, in, num); diff --git a/src/backend/cpu/fast.cpp b/src/backend/cpu/fast.cpp index 91dc6bb19f..057cf96552 100644 --- a/src/backend/cpu/fast.cpp +++ b/src/backend/cpu/fast.cpp @@ -11,15 +11,17 @@ #include #include -#include #include #include #include +#include #include +#include #include using af::dim4; +using std::ceil; namespace cpu { @@ -38,7 +40,7 @@ unsigned fast(Array &x_out, Array &y_out, Array &score_out, Array V = createEmptyArray(dim4()); if (nonmax == 1) { dim4 V_dims(in_dims[0], in_dims[1]); - V = createValueArray(V_dims, (float)0); + V = createValueArray(V_dims, 0.f); V.eval(); } getQueue().sync(); diff --git a/src/backend/cpu/fast.hpp b/src/backend/cpu/fast.hpp index 21c0904c66..d588246916 100644 --- a/src/backend/cpu/fast.hpp +++ b/src/backend/cpu/fast.hpp @@ -14,7 +14,7 @@ class Array; template unsigned fast(Array &x_out, Array &y_out, Array &score_out, const Array &in, const float thr, const unsigned arc_length, - const bool non_max, const float feature_ratio, + const bool nonmax, const float feature_ratio, const unsigned edge); } // namespace cpu diff --git a/src/backend/cpu/fft.cpp b/src/backend/cpu/fft.cpp index 2b7f3158f5..26b1df7c00 100644 --- a/src/backend/cpu/fft.cpp +++ b/src/backend/cpu/fft.cpp @@ -84,7 +84,7 @@ void fft_inplace(Array &in) { const af::dim4 istrides = in.strides(); - typedef typename fftw_transform::ctype_t ctype_t; + using ctype_t = typename fftw_transform::ctype_t; typename fftw_transform::plan_t plan; fftw_transform transform; @@ -93,10 +93,13 @@ void fft_inplace(Array &in) { for (int i = rank; i < 4; i++) { batch *= idims[i]; } plan = transform.create( - rank, t_dims, (int)batch, (ctype_t *)in.get(), in_embed, - (int)istrides[0], (int)istrides[rank], (ctype_t *)in.get(), - in_embed, (int)istrides[0], (int)istrides[rank], - direction ? FFTW_FORWARD : FFTW_BACKWARD, FFTW_ESTIMATE); + rank, t_dims, batch, reinterpret_cast(in.get()), + in_embed, static_cast(istrides[0]), + static_cast(istrides[rank]), + reinterpret_cast(in.get()), in_embed, + static_cast(istrides[0]), static_cast(istrides[rank]), + direction ? FFTW_FORWARD : FFTW_BACKWARD, + FFTW_ESTIMATE); // NOLINT(hicpp-signed-bitwise) transform.execute(plan); transform.destroy(plan); @@ -125,8 +128,9 @@ Array fft_r2c(const Array &in) { const af::dim4 istrides = in.strides(); const af::dim4 ostrides = out.strides(); - typedef typename fftw_real_transform::ctype_t ctype_t; - typename fftw_real_transform::plan_t plan; + using ctype_t = typename fftw_real_transform::ctype_t; + using plan_t = typename fftw_real_transform::plan_t; + plan_t plan; fftw_real_transform transform; @@ -134,9 +138,11 @@ Array fft_r2c(const Array &in) { for (int i = rank; i < 4; i++) { batch *= idims[i]; } plan = transform.create( - rank, t_dims, (int)batch, (Tr *)in.get(), in_embed, - (int)istrides[0], (int)istrides[rank], (ctype_t *)out.get(), - out_embed, (int)ostrides[0], (int)ostrides[rank], FFTW_ESTIMATE); + rank, t_dims, batch, const_cast(in.get()), in_embed, + static_cast(istrides[0]), static_cast(istrides[rank]), + reinterpret_cast(out.get()), out_embed, + static_cast(ostrides[0]), static_cast(ostrides[rank]), + FFTW_ESTIMATE); transform.execute(plan); transform.destroy(plan); @@ -164,8 +170,9 @@ Array fft_c2r(const Array &in, const dim4 &odims) { const af::dim4 istrides = in.strides(); const af::dim4 ostrides = out.strides(); - typedef typename fftw_real_transform::ctype_t ctype_t; - typename fftw_real_transform::plan_t plan; + using ctype_t = typename fftw_real_transform::ctype_t; + using plan_t = typename fftw_real_transform::plan_t; + plan_t plan; fftw_real_transform transform; @@ -178,13 +185,17 @@ Array fft_c2r(const Array &in, const dim4 &odims) { // FFTW_PRESERVE_INPUT also. This flag however only works for 1D // transforms and for higher level transformations, a copy of input // data is passed onto the upstream FFTW calls. - unsigned int flags = FFTW_ESTIMATE; - if (rank == 1) { flags |= FFTW_PRESERVE_INPUT; } + unsigned int flags = FFTW_ESTIMATE; // NOLINT(hicpp-signed-bitwise) + if (rank == 1) { + flags |= FFTW_PRESERVE_INPUT; // NOLINT(hicpp-signed-bitwise) + } - plan = transform.create(rank, t_dims, (int)batch, (ctype_t *)in.get(), - in_embed, (int)istrides[0], (int)istrides[rank], - (Tr *)out.get(), out_embed, (int)ostrides[0], - (int)ostrides[rank], flags); + plan = transform.create( + rank, t_dims, batch, + reinterpret_cast(const_cast(in.get())), in_embed, + static_cast(istrides[0]), static_cast(istrides[rank]), + out.get(), out_embed, static_cast(ostrides[0]), + static_cast(ostrides[rank]), flags); transform.execute(plan); transform.destroy(plan); diff --git a/src/backend/cpu/fftconvolve.cpp b/src/backend/cpu/fftconvolve.cpp index 93cc27227f..28eb5584eb 100644 --- a/src/backend/cpu/fftconvolve.cpp +++ b/src/backend/cpu/fftconvolve.cpp @@ -18,31 +18,34 @@ #include #include +using af::dim4; +using std::ceil; + namespace cpu { template Array fftconvolve(Array const& signal, Array const& filter, const bool expand, AF_BATCH_KIND kind) { - const af::dim4 sd = signal.dims(); - const af::dim4 fd = filter.dims(); + const dim4& sd = signal.dims(); + const dim4& fd = filter.dims(); dim_t fftScale = 1; - af::dim4 packed_dims(1, 1, 1, 1); + dim4 packed_dims(1, 1, 1, 1); int fft_dims[baseDim]; - af::dim4 sig_tmp_dims, sig_tmp_strides; - af::dim4 filter_tmp_dims, filter_tmp_strides; + dim4 sig_tmp_dims, sig_tmp_strides; + dim4 filter_tmp_dims, filter_tmp_strides; // Pack both signal and filter on same memory array, this will ensure // better use of batched FFT capabilities - fft_dims[baseDim - 1] = - nextpow2((unsigned)((int)ceil(sd[0] / 2.f) + fd[0] - 1)); + fft_dims[baseDim - 1] = nextpow2( + static_cast(static_cast(ceil(sd[0] / 2.f)) + fd[0] - 1)); packed_dims[0] = 2 * fft_dims[baseDim - 1]; fftScale *= fft_dims[baseDim - 1]; for (dim_t k = 1; k < baseDim; k++) { - packed_dims[k] = nextpow2((unsigned)(sd[k] + fd[k] - 1)); + packed_dims[k] = nextpow2(static_cast(sd[k] + fd[k] - 1)); fft_dims[baseDim - k - 1] = packed_dims[k]; fftScale *= fft_dims[baseDim - k - 1]; } @@ -87,31 +90,34 @@ Array fftconvolve(Array const& signal, Array const& filter, filter_tmp_strides, filter, offset); dim4 fftDims(1, 1, 1, 1); - for (int i = 0; i < baseDim; ++i) fftDims[i] = fft_dims[i]; + for (int i = 0; i < baseDim; ++i) { fftDims[i] = fft_dims[i]; } + // NOLINTNEXTLINE(performance-unnecessary-value-param) auto upstream_dft = [=](Param packed, const dim4 fftDims) { int fft_dims[baseDim]; - for (int i = 0; i < baseDim; ++i) fft_dims[i] = fftDims[i]; - const dim4 packed_dims = packed.dims(); - const af::dim4 packed_strides = packed.strides(); + for (int i = 0; i < baseDim; ++i) { fft_dims[i] = fftDims[i]; } + const dim4 packed_dims = packed.dims(); + const dim4 packed_strides = packed.strides(); // Compute forward FFT if (isDouble) { fftw_plan plan = fftw_plan_many_dft( baseDim, fft_dims, packed_dims[baseDim], - (fftw_complex*)packed.get(), NULL, packed_strides[0], - packed_strides[baseDim] / 2, (fftw_complex*)packed.get(), NULL, + reinterpret_cast(packed.get()), nullptr, + packed_strides[0], packed_strides[baseDim] / 2, + reinterpret_cast(packed.get()), nullptr, packed_strides[0], packed_strides[baseDim] / 2, FFTW_FORWARD, - FFTW_ESTIMATE); + FFTW_ESTIMATE); // NOLINT(hicpp-signed-bitwise) fftw_execute(plan); fftw_destroy_plan(plan); } else { fftwf_plan plan = fftwf_plan_many_dft( baseDim, fft_dims, packed_dims[baseDim], - (fftwf_complex*)packed.get(), NULL, packed_strides[0], - packed_strides[baseDim] / 2, (fftwf_complex*)packed.get(), NULL, + reinterpret_cast(packed.get()), nullptr, + packed_strides[0], packed_strides[baseDim] / 2, + reinterpret_cast(packed.get()), nullptr, packed_strides[0], packed_strides[baseDim] / 2, FFTW_FORWARD, - FFTW_ESTIMATE); + FFTW_ESTIMATE); // NOLINT(hicpp-signed-bitwise) fftwf_execute(plan); fftwf_destroy_plan(plan); @@ -124,29 +130,32 @@ Array fftconvolve(Array const& signal, Array const& filter, sig_tmp_strides, filter_tmp_dims, filter_tmp_strides, kind, offset); + // NOLINTNEXTLINE(performance-unnecessary-value-param) auto upstream_idft = [=](Param packed, const dim4 fftDims) { int fft_dims[baseDim]; - for (int i = 0; i < baseDim; ++i) fft_dims[i] = fftDims[i]; - const dim4 packed_dims = packed.dims(); - const af::dim4 packed_strides = packed.strides(); + for (int i = 0; i < baseDim; ++i) { fft_dims[i] = fftDims[i]; } + const dim4 packed_dims = packed.dims(); + const dim4 packed_strides = packed.strides(); // Compute inverse FFT if (isDouble) { fftw_plan plan = fftw_plan_many_dft( baseDim, fft_dims, packed_dims[baseDim], - (fftw_complex*)packed.get(), NULL, packed_strides[0], - packed_strides[baseDim] / 2, (fftw_complex*)packed.get(), NULL, + reinterpret_cast(packed.get()), nullptr, + packed_strides[0], packed_strides[baseDim] / 2, + reinterpret_cast(packed.get()), nullptr, packed_strides[0], packed_strides[baseDim] / 2, FFTW_BACKWARD, - FFTW_ESTIMATE); + FFTW_ESTIMATE); // NOLINT(hicpp-signed-bitwise) fftw_execute(plan); fftw_destroy_plan(plan); } else { fftwf_plan plan = fftwf_plan_many_dft( baseDim, fft_dims, packed_dims[baseDim], - (fftwf_complex*)packed.get(), NULL, packed_strides[0], - packed_strides[baseDim] / 2, (fftwf_complex*)packed.get(), NULL, + reinterpret_cast(packed.get()), nullptr, + packed_strides[0], packed_strides[baseDim] / 2, + reinterpret_cast(packed.get()), nullptr, packed_strides[0], packed_strides[baseDim] / 2, FFTW_BACKWARD, - FFTW_ESTIMATE); + FFTW_ESTIMATE); // NOLINT(hicpp-signed-bitwise) fftwf_execute(plan); fftwf_destroy_plan(plan); @@ -167,7 +176,7 @@ Array fftconvolve(Array const& signal, Array const& filter, } else { oDims = sd; if (kind == AF_BATCH_RHS) { - for (dim_t i = baseDim; i < 4; ++i) oDims[i] = fd[i]; + for (dim_t i = baseDim; i < 4; ++i) { oDims[i] = fd[i]; } } } diff --git a/src/backend/cpu/flood_fill.cpp b/src/backend/cpu/flood_fill.cpp index 4b9f6d2de8..7a08663ef3 100644 --- a/src/backend/cpu/flood_fill.cpp +++ b/src/backend/cpu/flood_fill.cpp @@ -13,7 +13,6 @@ #include using af::connectivity; -using af::dim4; namespace cpu { diff --git a/src/backend/cpu/harris.cpp b/src/backend/cpu/harris.cpp index 180a556943..1bc3a674e2 100644 --- a/src/backend/cpu/harris.cpp +++ b/src/backend/cpu/harris.cpp @@ -35,10 +35,12 @@ unsigned harris(Array &x_out, Array &y_out, auto h_filter = memAlloc(filter_len); // Decide between rectangular or circular filter if (sigma < 0.5f) { - for (unsigned i = 0; i < filter_len; i++) - h_filter[i] = (T)1.f / (filter_len); + for (unsigned i = 0; i < filter_len; i++) { + h_filter[i] = static_cast(1) / (filter_len); + } } else { - gaussian1D(h_filter.get(), (int)filter_len, sigma); + gaussian1D(h_filter.get(), static_cast(filter_len), + sigma); } Array filter = createDeviceDataArray(dim4(filter_len), h_filter.release()); @@ -74,7 +76,8 @@ unsigned harris(Array &x_out, Array &y_out, Array yCorners = createEmptyArray(dim4(corner_lim)); Array respCorners = createEmptyArray(dim4(corner_lim)); - const unsigned min_r = (max_corners > 0) ? 0.f : min_response; + const unsigned min_r = + (max_corners > 0) ? 0U : static_cast(min_response); // Performs non-maximal suppression getQueue().sync(); @@ -85,7 +88,7 @@ unsigned harris(Array &x_out, Array &y_out, const unsigned corners_out = min(corners_found, (max_corners > 0) ? max_corners : corner_lim); - if (corners_out == 0) return 0; + if (corners_out == 0) { return 0; } if (max_corners > 0 && corners_found > corners_out) { respCorners.resetDims(dim4(corners_found)); @@ -110,15 +113,16 @@ unsigned harris(Array &x_out, Array &y_out, y_out = createEmptyArray(dim4(corners_out)); resp_out = createEmptyArray(dim4(corners_out)); - auto copyFunc = [=](Param x_out, Param y_out, - Param outResponses, CParam x_crnrs, - CParam y_crnrs, CParam inResponses, - const unsigned corners_out) { - memcpy(x_out.get(), x_crnrs.get(), corners_out * sizeof(float)); - memcpy(y_out.get(), y_crnrs.get(), corners_out * sizeof(float)); - memcpy(outResponses.get(), inResponses.get(), - corners_out * sizeof(float)); - }; + auto copyFunc = + [=](Param x_out, Param y_out, + Param outResponses, const CParam &x_crnrs, + const CParam &y_crnrs, const CParam &inResponses, + const unsigned corners_out) { + memcpy(x_out.get(), x_crnrs.get(), corners_out * sizeof(float)); + memcpy(y_out.get(), y_crnrs.get(), corners_out * sizeof(float)); + memcpy(outResponses.get(), inResponses.get(), + corners_out * sizeof(float)); + }; getQueue().enqueue(copyFunc, x_out, y_out, resp_out, xCorners, yCorners, respCorners, corners_out); } else { diff --git a/src/backend/cpu/histogram.cpp b/src/backend/cpu/histogram.cpp index 4e05216ccd..a6292d951f 100644 --- a/src/backend/cpu/histogram.cpp +++ b/src/backend/cpu/histogram.cpp @@ -21,7 +21,7 @@ namespace cpu { template Array histogram(const Array &in, const unsigned &nbins, const double &minval, const double &maxval) { - const dim4 inDims = in.dims(); + const dim4 &inDims = in.dims(); dim4 outDims = dim4(nbins, 1, inDims[2], inDims[3]); Array out = createValueArray(outDims, outType(0)); diff --git a/src/backend/cpu/homography.cpp b/src/backend/cpu/homography.cpp index ae856431a1..98e93f0f08 100644 --- a/src/backend/cpu/homography.cpp +++ b/src/backend/cpu/homography.cpp @@ -14,13 +14,23 @@ #include #include #include -#include -#include #include +#include +#include +#include +#include using af::dim4; +using std::abs; using std::array; +using std::log; +using std::max; +using std::min; +using std::pow; +using std::round; +using std::sqrt; +using std::vector; namespace cpu { @@ -53,7 +63,7 @@ struct EPS { template void JacobiSVD(T* S, T* V) { const int iterations = 30; - array d; + array d{}; for (int i = 0; i < N; i++) { T sd = 0; @@ -76,21 +86,22 @@ void JacobiSVD(T* S, T* V) { T* Vi = V + i * N; T* Vj = V + j * N; - T p = (T)0; - for (int k = 0; k < M; k++) p += Si[k] * Sj[k]; + T p = static_cast(0); + for (int k = 0; k < M; k++) { p += Si[k] * Sj[k]; } - if (std::abs(p) <= M * EPS::eps() * std::sqrt(d[i] * d[j])) + if (abs(p) <= M * EPS::eps() * sqrt(d[i] * d[j])) { continue; + } T y = d[i] - d[j]; T r = hypot(p * 2, y); T r2 = r * 2; T c, s; if (y >= 0) { - c = std::sqrt((r + y) / r2); + c = sqrt((r + y) / r2); s = p / (r2 * c); } else { - s = std::sqrt((r - y) / r2); + s = sqrt((r - y) / r2); c = p / (r2 * s); } @@ -117,44 +128,53 @@ void JacobiSVD(T* S, T* V) { converged = true; } - if (!converged) break; + if (!converged) { break; } } } } unsigned updateIterations(float inlier_ratio, unsigned iter) { - float w = std::min(std::max(inlier_ratio, 0.0f), 1.0f); + float w = min(max(inlier_ratio, 0.0f), 1.0f); float wn = pow(1 - w, 4.f); float d = 1.f - wn; - if (d < FLT_MIN) return 0; + if (d < FLT_MIN) { return 0; } d = log(d); - float p = std::min(std::max(RANSACConfidence, 0.0f), 1.0f); + float p = min(max(RANSACConfidence, 0.0f), 1.0f); float n = log(1.f - p); - return n <= d * iter ? iter : (unsigned)round(n / d); + return n <= d * static_cast(iter) + ? iter + : static_cast(round(n / d)); } template int computeHomography(T* H_ptr, const float* rnd_ptr, const float* x_src_ptr, const float* y_src_ptr, const float* x_dst_ptr, const float* y_dst_ptr) { - if ((unsigned)rnd_ptr[0] == (unsigned)rnd_ptr[1] || - (unsigned)rnd_ptr[0] == (unsigned)rnd_ptr[2] || - (unsigned)rnd_ptr[0] == (unsigned)rnd_ptr[3] || - (unsigned)rnd_ptr[1] == (unsigned)rnd_ptr[2] || - (unsigned)rnd_ptr[1] == (unsigned)rnd_ptr[3] || - (unsigned)rnd_ptr[2] == (unsigned)rnd_ptr[3]) + if (static_cast(rnd_ptr[0]) == + static_cast(rnd_ptr[1]) || + static_cast(rnd_ptr[0]) == + static_cast(rnd_ptr[2]) || + static_cast(rnd_ptr[0]) == + static_cast(rnd_ptr[3]) || + static_cast(rnd_ptr[1]) == + static_cast(rnd_ptr[2]) || + static_cast(rnd_ptr[1]) == + static_cast(rnd_ptr[3]) || + static_cast(rnd_ptr[2]) == + static_cast(rnd_ptr[3])) { return 1; + } float src_pt_x[4], src_pt_y[4], dst_pt_x[4], dst_pt_y[4]; for (unsigned j = 0; j < 4; j++) { - src_pt_x[j] = x_src_ptr[(unsigned)rnd_ptr[j]]; - src_pt_y[j] = y_src_ptr[(unsigned)rnd_ptr[j]]; - dst_pt_x[j] = x_dst_ptr[(unsigned)rnd_ptr[j]]; - dst_pt_y[j] = y_dst_ptr[(unsigned)rnd_ptr[j]]; + src_pt_x[j] = x_src_ptr[static_cast(rnd_ptr[j])]; + src_pt_y[j] = y_src_ptr[static_cast(rnd_ptr[j])]; + dst_pt_x[j] = x_dst_ptr[static_cast(rnd_ptr[j])]; + dst_pt_y[j] = y_dst_ptr[static_cast(rnd_ptr[j])]; } float x_src_mean = @@ -178,7 +198,7 @@ int computeHomography(T* H_ptr, const float* rnd_ptr, const float* x_src_ptr, float src_scale = sqrt(2.0f) / sqrt(src_var); float dst_scale = sqrt(2.0f) / sqrt(dst_var); - Array A = createValueArray(af::dim4(9, 9), (T)0); + Array A = createValueArray(af::dim4(9, 9), static_cast(0)); af::dim4 Adims = A.dims(); T* A_ptr = A.get(); getQueue().sync(); @@ -204,7 +224,8 @@ int computeHomography(T* H_ptr, const float* rnd_ptr, const float* x_src_ptr, APTR(8, j * 2 + 1) = -dstx; } - Array V = createValueArray(af::dim4(Adims[1], Adims[1]), (T)0); + Array V = + createValueArray(af::dim4(Adims[1], Adims[1]), static_cast(0)); V.eval(); getQueue().sync(); JacobiSVD(A.get(), V.get()); @@ -212,8 +233,8 @@ int computeHomography(T* H_ptr, const float* rnd_ptr, const float* x_src_ptr, dim4 Vdims = V.dims(); T* V_ptr = V.get(); - array vH; - for (unsigned j = 0; j < 9; j++) vH[j] = V_ptr[8 * Vdims[0] + j]; + array vH{}; + for (unsigned j = 0; j < 9; j++) { vH[j] = V_ptr[8 * Vdims[0] + j]; } H_ptr[0] = src_scale * x_dst_mean * vH[6] + src_scale * vH[0] / dst_scale; H_ptr[1] = src_scale * x_dst_mean * vH[7] + src_scale * vH[1] / dst_scale; @@ -252,17 +273,18 @@ int findBestHomography(Array& bestH, const Array& x_src, const float* x_dst_ptr = x_dst.get(); const float* y_dst_ptr = y_dst.get(); - Array H = createValueArray(af::dim4(9, iterations), (T)0); + Array H = + createValueArray(af::dim4(9, iterations), static_cast(0)); H.eval(); getQueue().sync(); - const af::dim4 rdims = rnd.dims(); - const af::dim4 Hdims = H.dims(); + const af::dim4& rdims = rnd.dims(); + const af::dim4& Hdims = H.dims(); - unsigned iter = iterations; - unsigned bestIdx = 0; - unsigned bestInliers = 0; - float minMedian = FLT_MAX; + unsigned iter = iterations; + unsigned bestIdx = 0; + int bestInliers = 0; + float minMedian = FLT_MAX; for (unsigned i = 0; i < iter; i++) { const unsigned Hidx = Hdims[0] * i; @@ -272,11 +294,12 @@ int findBestHomography(Array& bestH, const Array& x_src, const float* rnd_ptr = rnd.get() + ridx; if (computeHomography(H_ptr, rnd_ptr, x_src_ptr, y_src_ptr, - x_dst_ptr, y_dst_ptr)) + x_dst_ptr, y_dst_ptr)) { continue; + } if (htype == AF_HOMOGRAPHY_RANSAC) { - unsigned inliers_count = 0; + int inliers_count = 0; for (unsigned j = 0; j < nsamples; j++) { float z = H_ptr[6] * x_src_ptr[j] + H_ptr[7] * y_src_ptr[j] + H_ptr[8]; @@ -288,16 +311,18 @@ int findBestHomography(Array& bestH, const Array& x_src, z; float dist = sq(x_dst_ptr[j] - x) + sq(y_dst_ptr[j] - y); - if (dist < (inlier_thr * inlier_thr)) inliers_count++; + if (dist < (inlier_thr * inlier_thr)) { inliers_count++; } } - iter = updateIterations( - (nsamples - inliers_count) / (float)nsamples, iter); + iter = + updateIterations(static_cast(nsamples - inliers_count) / + static_cast(nsamples), + iter); if (inliers_count > bestInliers) { bestIdx = i; bestInliers = inliers_count; } } else if (htype == AF_HOMOGRAPHY_LMEDS) { - std::vector err(nsamples); + vector err(nsamples); for (unsigned j = 0; j < nsamples; j++) { float z = H_ptr[6] * x_src_ptr[j] + H_ptr[7] * y_src_ptr[j] + H_ptr[8]; @@ -312,11 +337,12 @@ int findBestHomography(Array& bestH, const Array& x_src, err[j] = sqrt(dist); } - std::stable_sort(err.begin(), err.end()); + stable_sort(err.begin(), err.end()); float median = err[nsamples / 2]; - if (nsamples % 2 == 0) + if (nsamples % 2 == 0) { median = (median + err[nsamples / 2 - 1]) * 0.5f; + } if (median < minMedian && median > FLT_EPSILON) { minMedian = median; @@ -328,9 +354,10 @@ int findBestHomography(Array& bestH, const Array& x_src, memcpy(bestH.get(), H.get() + bestIdx * 9, 9 * sizeof(T)); if (htype == AF_HOMOGRAPHY_LMEDS) { - float sigma = std::max( - 1.4826f * (1 + 5.f / (nsamples - 4)) * (float)sqrt(minMedian), - 1e-6f); + float sigma = + max(1.4826f * (1.f + 5.f / (static_cast(nsamples) - 4.f)) * + static_cast(sqrt(minMedian)), + 1e-6f); float dist_thr = sq(2.5f * sigma); T* bestH_ptr = bestH.get(); @@ -345,7 +372,7 @@ int findBestHomography(Array& bestH, const Array& x_src, z; float dist = sq(x_dst_ptr[j] - x) + sq(y_dst_ptr[j] - y); - if (dist <= dist_thr) bestInliers++; + if (dist <= dist_thr) { bestInliers++; } } } @@ -358,18 +385,20 @@ int homography(Array& bestH, const Array& x_src, const Array& y_dst, const Array& initial, const af_homography_type htype, const float inlier_thr, const unsigned iterations) { - const af::dim4 idims = x_src.dims(); + const dim4& idims = x_src.dims(); const unsigned nsamples = idims[0]; unsigned iter = iterations; - if (htype == AF_HOMOGRAPHY_LMEDS) - iter = std::min( - iter, (unsigned)(log(1.f - LMEDSConfidence) / + if (htype == AF_HOMOGRAPHY_LMEDS) { + iter = min(iter, static_cast( + log(1.f - LMEDSConfidence) / log(1.f - pow(1.f - LMEDSOutlierRatio, 4.f)))); + } af::dim4 rdims(4, iter); - Array fctr = createValueArray(rdims, (float)nsamples); - Array rnd = arithOp(initial, fctr, rdims); + Array fctr = + createValueArray(rdims, static_cast(nsamples)); + Array rnd = arithOp(initial, fctr, rdims); rnd.eval(); getQueue().sync(); diff --git a/src/backend/cpu/hsv_rgb.cpp b/src/backend/cpu/hsv_rgb.cpp index eb37f3a118..da3cf25e54 100644 --- a/src/backend/cpu/hsv_rgb.cpp +++ b/src/backend/cpu/hsv_rgb.cpp @@ -14,8 +14,6 @@ #include #include -using af::dim4; - namespace cpu { template diff --git a/src/backend/cpu/identity.cpp b/src/backend/cpu/identity.cpp index c6a8af4dbb..ded01b348e 100644 --- a/src/backend/cpu/identity.cpp +++ b/src/backend/cpu/identity.cpp @@ -15,7 +15,7 @@ #include #include -using common::half; +using common::half; // NOLINT(misc-unused-using-decls) bug in clang-tidy namespace cpu { diff --git a/src/backend/cpu/image.cpp b/src/backend/cpu/image.cpp index 21b493c696..4b5e3cd486 100644 --- a/src/backend/cpu/image.cpp +++ b/src/backend/cpu/image.cpp @@ -17,8 +17,6 @@ #include #include -using af::dim4; - namespace cpu { template diff --git a/src/backend/cpu/index.cpp b/src/backend/cpu/index.cpp index f9aa108ae6..9a2172569e 100644 --- a/src/backend/cpu/index.cpp +++ b/src/backend/cpu/index.cpp @@ -21,7 +21,7 @@ #include using af::dim4; -using common::half; +using common::half; // NOLINT(misc-unused-using-decls) bug in clang-tidy using std::vector; namespace cpu { diff --git a/src/backend/cpu/iota.cpp b/src/backend/cpu/iota.cpp index cb7b88d83d..38fb1c292b 100644 --- a/src/backend/cpu/iota.cpp +++ b/src/backend/cpu/iota.cpp @@ -15,7 +15,7 @@ #include #include -using common::half; +using common::half; // NOLINT(misc-unused-using-decls) bug in clang-tidy namespace cpu { diff --git a/src/backend/cpu/kernel/random_engine.hpp b/src/backend/cpu/kernel/random_engine.hpp index b47ae0bd92..de70c8fef0 100644 --- a/src/backend/cpu/kernel/random_engine.hpp +++ b/src/backend/cpu/kernel/random_engine.hpp @@ -153,8 +153,9 @@ void philoxUniform(T *out, size_t elements, const uintl seed, uintl counter) { // Recalculate key and ctr to emulate how the CUDA backend // calculates these per thread uint key[2] = {lo, hi}; - uint ctr[4] = {loc + (uint)first_write_idx, - hic + (ctr[0] < loc), (ctr[1] < hic), 0}; + uint ctr[4] = {loc + (uint)first_write_idx, 0, 0, 0}; + ctr[1] = hic + (ctr[0] < loc); + ctr[2] = (ctr[1] < hic); philox(key, ctr); // Use the same ctr array for each of the 4 locations, diff --git a/src/backend/cpu/lookup.cpp b/src/backend/cpu/lookup.cpp index 10eb97b36a..9eda1f9253 100644 --- a/src/backend/cpu/lookup.cpp +++ b/src/backend/cpu/lookup.cpp @@ -20,11 +20,12 @@ namespace cpu { template Array lookup(const Array &input, const Array &indices, const unsigned dim) { - const dim4 iDims = input.dims(); + const dim4 &iDims = input.dims(); dim4 oDims(1); - for (int d = 0; d < 4; ++d) + for (int d = 0; d < 4; ++d) { oDims[d] = (d == int(dim) ? indices.elements() : iDims[d]); + } Array out = createEmptyArray(oDims); getQueue().enqueue(kernel::lookup, out, input, indices, dim); diff --git a/src/backend/cpu/math.cpp b/src/backend/cpu/math.cpp index b061c44b93..8310f12c57 100644 --- a/src/backend/cpu/math.cpp +++ b/src/backend/cpu/math.cpp @@ -16,7 +16,7 @@ uchar abs(uchar val) { return val; } uintl abs(uintl val) { return val; } cfloat scalar(float val) { - cfloat cval = {(float)val, 0}; + cfloat cval = {val, 0}; return cval; } diff --git a/src/backend/cpu/mean.cpp b/src/backend/cpu/mean.cpp index 8d675d460a..6da92b98e2 100644 --- a/src/backend/cpu/mean.cpp +++ b/src/backend/cpu/mean.cpp @@ -72,8 +72,8 @@ T mean(const Array &in, const Array &wt) { const T *inPtr = in.get(); const Tw *wtPtr = wt.get(); - compute_t input = compute_t(inPtr[0]); - compute_t weight = compute_t(wtPtr[0]); + auto input = compute_t(inPtr[0]); + auto weight = compute_t(wtPtr[0]); MeanOpT Op(input, weight); for (dim_t l = 0; l < dims[3]; l++) { diff --git a/src/backend/cpu/meanshift.cpp b/src/backend/cpu/meanshift.cpp index df326dd86c..e8a0f55ba4 100644 --- a/src/backend/cpu/meanshift.cpp +++ b/src/backend/cpu/meanshift.cpp @@ -24,16 +24,17 @@ using std::vector; namespace cpu { template Array meanshift(const Array &in, const float &spatialSigma, - const float &chromaticSigma, const unsigned &numInterations, + const float &chromaticSigma, const unsigned &numIterations, const bool &isColor) { Array out = createEmptyArray(in.dims()); - if (isColor) + if (isColor) { getQueue().enqueue(kernel::meanShift, out, in, spatialSigma, - chromaticSigma, numInterations); - else + chromaticSigma, numIterations); + } else { getQueue().enqueue(kernel::meanShift, out, in, spatialSigma, - chromaticSigma, numInterations); + chromaticSigma, numIterations); + } return out; } diff --git a/src/backend/cpu/memory.cpp b/src/backend/cpu/memory.cpp index 98d9d23e79..e2dc906fd8 100644 --- a/src/backend/cpu/memory.cpp +++ b/src/backend/cpu/memory.cpp @@ -42,7 +42,7 @@ void setMemStepSize(size_t step_bytes) { memoryManager().setMemStepSize(step_bytes); } -size_t getMemStepSize(void) { return memoryManager().getMemStepSize(); } +size_t getMemStepSize() { return memoryManager().getMemStepSize(); } void signalMemoryCleanup() { memoryManager().signalMemoryCleanup(); } @@ -56,8 +56,9 @@ template unique_ptr> memAlloc(const size_t &elements) { // TODO: make memAlloc aware of array shapes dim4 dims(elements); - void *ptr = memoryManager().alloc(false, 1, dims.get(), sizeof(T)); - return unique_ptr>((T *)ptr, memFree); + T *ptr = static_cast( + memoryManager().alloc(false, 1, dims.get(), sizeof(T))); + return unique_ptr>(ptr, memFree); } void *memAllocUser(const size_t &bytes) { @@ -68,18 +69,16 @@ void *memAllocUser(const size_t &bytes) { template void memFree(T *ptr) { - return memoryManager().unlock((void *)ptr, false); + return memoryManager().unlock(static_cast(ptr), false); } void memFreeUser(void *ptr) { memoryManager().unlock(ptr, true); } -void memLock(const void *ptr) { memoryManager().userLock((void *)ptr); } +void memLock(const void *ptr) { memoryManager().userLock(ptr); } -bool isLocked(const void *ptr) { - return memoryManager().isUserLocked((void *)ptr); -} +bool isLocked(const void *ptr) { return memoryManager().isUserLocked(ptr); } -void memUnlock(const void *ptr) { memoryManager().userUnlock((void *)ptr); } +void memUnlock(const void *ptr) { memoryManager().userUnlock(ptr); } void deviceMemoryInfo(size_t *alloc_bytes, size_t *alloc_buffers, size_t *lock_bytes, size_t *lock_buffers) { @@ -92,12 +91,12 @@ T *pinnedAlloc(const size_t &elements) { // TODO: make pinnedAlloc aware of array shapes dim4 dims(elements); void *ptr = memoryManager().alloc(false, 1, dims.get(), sizeof(T)); - return (T *)ptr; + return static_cast(ptr); } template void pinnedFree(T *ptr) { - memoryManager().unlock((void *)ptr, false); + memoryManager().unlock(static_cast(ptr), false); } #define INSTANTIATE(T) \ @@ -128,7 +127,7 @@ void Allocator::shutdown() { try { cpu::setDevice(n); shutdownMemoryManager(); - } catch (AfError err) { + } catch (const AfError &err) { continue; // Do not throw any errors while shutting down } } @@ -141,9 +140,9 @@ size_t Allocator::getMaxMemorySize(int id) { } void *Allocator::nativeAlloc(const size_t bytes) { - void *ptr = malloc(bytes); + void *ptr = malloc(bytes); // NOLINT(hicpp-no-malloc) AF_TRACE("nativeAlloc: {:>7} {}", bytesToString(bytes), ptr); - if (!ptr) AF_ERROR("Unable to allocate memory", AF_ERR_NO_MEM); + if (!ptr) { AF_ERROR("Unable to allocate memory", AF_ERR_NO_MEM); } return ptr; } @@ -152,6 +151,6 @@ void Allocator::nativeFree(void *ptr) { // Make sure this pointer is not being used on the queue before freeing the // memory. getQueue().sync(); - return free((void *)ptr); + free(ptr); // NOLINT(hicpp-no-malloc) } } // namespace cpu diff --git a/src/backend/cpu/moments.cpp b/src/backend/cpu/moments.cpp index a1ddf7d333..aedb9bc214 100644 --- a/src/backend/cpu/moments.cpp +++ b/src/backend/cpu/moments.cpp @@ -16,10 +16,10 @@ namespace cpu { -static inline int bitCount(int v) { - v = v - ((v >> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >> 2) & 0x33333333); - return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; +static inline unsigned bitCount(unsigned v) { + v = v - ((v >> 1U) & 0x55555555U); + v = (v & 0x33333333U) + ((v >> 2U) & 0x33333333U); + return (((v + (v >> 4U)) & 0xF0F0F0FU) * 0x1010101U) >> 24U; } using af::dim4; diff --git a/src/backend/cpu/morph.cpp b/src/backend/cpu/morph.cpp index d109dbf022..c1d391996e 100644 --- a/src/backend/cpu/morph.cpp +++ b/src/backend/cpu/morph.cpp @@ -22,11 +22,11 @@ namespace cpu { template Array morph(const Array &in, const Array &mask) { af::borderType padType = isDilation ? AF_PAD_ZERO : AF_PAD_CLAMP_TO_EDGE; - const af::dim4 idims = in.dims(); - const af::dim4 mdims = mask.dims(); + const af::dim4 &idims = in.dims(); + const af::dim4 &mdims = mask.dims(); const af::dim4 lpad(mdims[0] / 2, mdims[1] / 2, 0, 0); - const af::dim4 upad(lpad); + const af::dim4 &upad(lpad); const af::dim4 odims(lpad[0] + idims[0] + upad[0], lpad[1] + idims[1] + upad[1], idims[2], idims[3]); diff --git a/src/backend/cpu/nearest_neighbour.cpp b/src/backend/cpu/nearest_neighbour.cpp index 4df5cd37f9..916d43d416 100644 --- a/src/backend/cpu/nearest_neighbour.cpp +++ b/src/backend/cpu/nearest_neighbour.cpp @@ -24,9 +24,9 @@ template void nearest_neighbour(Array& idx, Array& dist, const Array& query, const Array& train, const uint dist_dim, const uint n_dist, const af_match_type dist_type) { - uint sample_dim = (dist_dim == 0) ? 1 : 0; - const dim4 qDims = query.dims(); - const dim4 tDims = train.dims(); + uint sample_dim = (dist_dim == 0) ? 1 : 0; + const dim4& qDims = query.dims(); + const dim4& tDims = train.dims(); const dim4 outDims(n_dist, qDims[sample_dim]); const dim4 distDims(tDims[sample_dim], qDims[sample_dim]); diff --git a/src/backend/cpu/orb.cpp b/src/backend/cpu/orb.cpp index 330fc42d7d..54fd77da4b 100644 --- a/src/backend/cpu/orb.cpp +++ b/src/backend/cpu/orb.cpp @@ -17,11 +17,23 @@ #include #include #include + +#include #include +#include +#include +#include +#include using af::dim4; - +using std::ceil; +using std::floor; using std::function; +using std::min; +using std::move; +using std::pow; +using std::round; +using std::sqrt; using std::unique_ptr; using std::vector; @@ -36,21 +48,21 @@ unsigned orb(Array& x, Array& y, Array& score, image.eval(); getQueue().sync(); - unsigned patch_size = REF_PAT_SIZE; + float patch_size = REF_PAT_SIZE; - const af::dim4 idims = image.dims(); - unsigned min_side = std::min(idims[0], idims[1]); - unsigned max_levels = 0; - float scl_sum = 0.f; + const dim4& idims = image.dims(); + float min_side = min(idims[0], idims[1]); + unsigned max_levels = 0; + float scl_sum = 0.f; for (unsigned i = 0; i < levels; i++) { min_side /= scl_fctr; // Minimum image side for a descriptor to be computed - if (min_side < patch_size || max_levels == levels) break; + if (min_side < patch_size || max_levels == levels) { break; } max_levels++; - scl_sum += 1.f / (float)std::pow(scl_fctr, (float)i); + scl_sum += 1.f / pow(scl_fctr, static_cast(i)); } vector>> h_x_pyr(max_levels); @@ -61,31 +73,31 @@ unsigned orb(Array& x, Array& y, Array& score, vector>> h_desc_pyr( max_levels); - std::vector feat_pyr(max_levels); + vector feat_pyr(max_levels); unsigned total_feat = 0; // Compute number of features to keep for each level - std::vector lvl_best(max_levels); + vector lvl_best(max_levels); unsigned feat_sum = 0; for (unsigned i = 0; i < max_levels - 1; i++) { - float lvl_scl = (float)std::pow(scl_fctr, (float)i); - lvl_best[i] = ceil((max_feat / scl_sum) / lvl_scl); + auto lvl_scl = pow(scl_fctr, static_cast(i)); + lvl_best[i] = ceil((static_cast(max_feat) / scl_sum) / lvl_scl); feat_sum += lvl_best[i]; } lvl_best[max_levels - 1] = max_feat - feat_sum; // Maintain a reference to previous level image - Array prev_img = createEmptyArray(af::dim4()); - af::dim4 prev_ldims; + Array prev_img = createEmptyArray(dim4()); + dim4 prev_ldims; - af::dim4 gauss_dims(9); - std::unique_ptr> h_gauss; - Array gauss_filter = createEmptyArray(af::dim4()); + dim4 gauss_dims(9); + unique_ptr> h_gauss; + Array gauss_filter = createEmptyArray(dim4()); for (unsigned i = 0; i < max_levels; i++) { - af::dim4 ldims; - const float lvl_scl = (float)std::pow(scl_fctr, (float)i); - Array lvl_img = createEmptyArray(af::dim4()); + dim4 ldims; + const auto lvl_scl = pow(scl_fctr, static_cast(i)); + Array lvl_img = createEmptyArray(dim4()); if (i == 0) { // First level is used in its original size @@ -114,7 +126,7 @@ unsigned orb(Array& x, Array& y, Array& score, Array score_feat = createEmptyArray(dim4()); // Round feature size to nearest odd integer - float size = 2.f * floor(patch_size / 2.f) + 1.f; + float size = 2.f * floor(static_cast(patch_size) / 2.f) + 1.f; // Avoid keeping features that might be too wide and might not fit on // the image, sqrt(2.f) is the radius when angle is 45 degrees and @@ -153,7 +165,7 @@ unsigned orb(Array& x, Array& y, Array& score, sort_index(harris_sorted, harris_idx, score_harris, 0, false); getQueue().sync(); - usable_feat = std::min(usable_feat, lvl_best[i]); + usable_feat = min(usable_feat, lvl_best[i]); if (usable_feat == 0) { h_score_harris.release(); @@ -201,26 +213,27 @@ unsigned orb(Array& x, Array& y, Array& score, // Compute ORB descriptors auto h_desc_lvl = memAlloc(usable_feat * 8); memset(h_desc_lvl.get(), 0, usable_feat * 8 * sizeof(unsigned)); - if (blur_img) + if (blur_img) { kernel::extract_orb(h_desc_lvl.get(), usable_feat, h_x_lvl.get(), h_y_lvl.get(), h_ori_lvl.get(), h_size_lvl.get(), lvl_filt, lvl_scl, patch_size); - else + } else { kernel::extract_orb(h_desc_lvl.get(), usable_feat, h_x_lvl.get(), h_y_lvl.get(), h_ori_lvl.get(), h_size_lvl.get(), lvl_img, lvl_scl, patch_size); + } // Store results to pyramids total_feat += usable_feat; feat_pyr[i] = usable_feat; - h_x_pyr[i] = std::move(h_x_lvl); - h_y_pyr[i] = std::move(h_y_lvl); - h_score_pyr[i] = std::move(h_score_lvl); - h_ori_pyr[i] = std::move(h_ori_lvl); - h_size_pyr[i] = std::move(h_size_lvl); - h_desc_pyr[i] = std::move(h_desc_lvl); + h_x_pyr[i] = move(h_x_lvl); + h_y_pyr[i] = move(h_y_lvl); + h_score_pyr[i] = move(h_score_lvl); + h_ori_pyr[i] = move(h_ori_lvl); + h_size_pyr[i] = move(h_size_lvl); + h_desc_pyr[i] = move(h_desc_lvl); h_score_harris.release(); h_gauss.release(); } @@ -247,9 +260,9 @@ unsigned orb(Array& x, Array& y, Array& score, unsigned offset = 0; for (unsigned i = 0; i < max_levels; i++) { - if (feat_pyr[i] == 0) continue; + if (feat_pyr[i] == 0) { continue; } - if (i > 0) offset += feat_pyr[i - 1]; + if (i > 0) { offset += feat_pyr[i - 1]; } memcpy(h_x + offset, h_x_pyr[i].get(), feat_pyr[i] * sizeof(float)); memcpy(h_y + offset, h_y_pyr[i].get(), feat_pyr[i] * sizeof(float)); diff --git a/src/backend/cpu/platform.cpp b/src/backend/cpu/platform.cpp index d520d676ff..b10d168e9a 100644 --- a/src/backend/cpu/platform.cpp +++ b/src/backend/cpu/platform.cpp @@ -31,7 +31,7 @@ using std::unique_ptr; namespace cpu { -static const string get_system(void) { +static string get_system() { string arch = (sizeof(void*) == 4) ? "32-bit " : "64-bit "; return arch + @@ -68,10 +68,11 @@ string getDeviceInfo() noexcept { info << string("[0] ") << cinfo.vendor() << ": " << ltrim(model); - if (memMB) + if (memMB) { info << ", " << memMB << " MB, "; - else + } else { info << ", Unknown MB, "; + } info << "Max threads(" << cinfo.threads() << ") "; #ifndef NDEBUG diff --git a/src/backend/cpu/random_engine.cpp b/src/backend/cpu/random_engine.cpp index 81aa060ac8..d6f6e7c792 100644 --- a/src/backend/cpu/random_engine.cpp +++ b/src/backend/cpu/random_engine.cpp @@ -16,7 +16,7 @@ using common::half; namespace cpu { void initMersenneState(Array &state, const uintl seed, - const Array tbl) { + const Array &tbl) { getQueue().enqueue(kernel::initMersenneState, state.get(), tbl.get(), seed); } @@ -157,10 +157,10 @@ INSTANTIATE_NORMAL(float) INSTANTIATE_NORMAL(double) INSTANTIATE_NORMAL(half) -COMPLEX_UNIFORM_DISTRIBUTION(cdouble, double) -COMPLEX_UNIFORM_DISTRIBUTION(cfloat, float) +COMPLEX_UNIFORM_DISTRIBUTION(cdouble, double) // NOLINT +COMPLEX_UNIFORM_DISTRIBUTION(cfloat, float) // NOLINT -COMPLEX_NORMAL_DISTRIBUTION(cdouble, double) -COMPLEX_NORMAL_DISTRIBUTION(cfloat, float) +COMPLEX_NORMAL_DISTRIBUTION(cdouble, double) // NOLINT +COMPLEX_NORMAL_DISTRIBUTION(cfloat, float) // NOLINT } // namespace cpu diff --git a/src/backend/cpu/random_engine.hpp b/src/backend/cpu/random_engine.hpp index bb50388e86..e2e490167d 100644 --- a/src/backend/cpu/random_engine.hpp +++ b/src/backend/cpu/random_engine.hpp @@ -14,10 +14,8 @@ #include namespace cpu { -Array initMersenneState(const uintl seed, Array tbl); - void initMersenneState(Array &state, const uintl seed, - const Array tbl); + const Array &tbl); template Array uniformDistribution(const af::dim4 &dims, diff --git a/src/backend/cpu/reduce.cpp b/src/backend/cpu/reduce.cpp index 8795ce8ff7..1e442714cc 100644 --- a/src/backend/cpu/reduce.cpp +++ b/src/backend/cpu/reduce.cpp @@ -80,7 +80,7 @@ void reduce_by_key(Array &keys_out, Array &vals_out, std::vector index; for (int i = 0; i < keys.ndims(); ++i) { - af_seq s = {0.0, (double)okdims[i] - 1, 1.0}; + af_seq s = {0.0, static_cast(okdims[i]) - 1, 1.0}; index.push_back(s); } Array okeys = createSubArray(fullsz_okeys, index, true); @@ -99,15 +99,15 @@ void reduce_by_key(Array &keys_out, Array &vals_out, vals_out = ovals; } -template -To reduce_all(const Array &in, bool change_nan, double nanval) { +template +Taccumulate reduce_all(const Array &in, bool change_nan, double nanval) { in.eval(); getQueue().sync(); - Transform, op> transform; - Binary, op> reduce; + Transform, op> transform; + Binary, op> reduce; - compute_t out = Binary, op>::init(); + compute_t out = Binary, op>::init(); // Decrement dimension of select dimension af::dim4 dims = in.dims(); @@ -126,15 +126,17 @@ To reduce_all(const Array &in, bool change_nan, double nanval) { for (dim_t i = 0; i < dims[0]; i++) { dim_t idx = i + off1 + off2 + off3; - compute_t in_val = transform(inPtr[idx]); - if (change_nan) in_val = IS_NAN(in_val) ? nanval : in_val; + compute_t in_val = transform(inPtr[idx]); + if (change_nan) { + in_val = IS_NAN(in_val) ? nanval : in_val; + } out = reduce(in_val, out); } } } } - return data_t(out); + return data_t(out); } #define INSTANTIATE(ROp, Ti, To) \ diff --git a/src/backend/cpu/regions.cpp b/src/backend/cpu/regions.cpp index 061358a4ec..0f6612768d 100644 --- a/src/backend/cpu/regions.cpp +++ b/src/backend/cpu/regions.cpp @@ -25,7 +25,7 @@ namespace cpu { template Array regions(const Array &in, af_connectivity connectivity) { - Array out = createValueArray(in.dims(), (T)0); + Array out = createValueArray(in.dims(), static_cast(0)); getQueue().enqueue(kernel::regions, out, in, connectivity); return out; diff --git a/src/backend/cpu/reorder.cpp b/src/backend/cpu/reorder.cpp index 4bc4646e01..83d2038f38 100644 --- a/src/backend/cpu/reorder.cpp +++ b/src/backend/cpu/reorder.cpp @@ -20,9 +20,9 @@ namespace cpu { template Array reorder(const Array &in, const af::dim4 &rdims) { - const af::dim4 iDims = in.dims(); + const af::dim4 &iDims = in.dims(); af::dim4 oDims(0); - for (int i = 0; i < 4; i++) oDims[i] = iDims[rdims[i]]; + for (int i = 0; i < 4; i++) { oDims[i] = iDims[rdims[i]]; } Array out = createEmptyArray(oDims); getQueue().enqueue(kernel::reorder, out, in, oDims, rdims); diff --git a/src/backend/cpu/resize.cpp b/src/backend/cpu/resize.cpp index 6049d0753c..f5850bb106 100644 --- a/src/backend/cpu/resize.cpp +++ b/src/backend/cpu/resize.cpp @@ -22,7 +22,7 @@ Array resize(const Array &in, const dim_t odim0, const dim_t odim1, af::dim4 idims = in.dims(); af::dim4 odims(odim0, odim1, idims[2], idims[3]); // Create output placeholder - Array out = createValueArray(odims, (T)0); + Array out = createValueArray(odims, static_cast(0)); switch (method) { case AF_INTERP_NEAREST: diff --git a/src/backend/cpu/scan.cpp b/src/backend/cpu/scan.cpp index 4522c60799..0adb09b7b0 100644 --- a/src/backend/cpu/scan.cpp +++ b/src/backend/cpu/scan.cpp @@ -22,8 +22,8 @@ namespace cpu { template Array scan(const Array& in, const int dim, bool inclusive_scan) { - dim4 dims = in.dims(); - Array out = createEmptyArray(dims); + const dim4& dims = in.dims(); + Array out = createEmptyArray(dims); if (inclusive_scan) { switch (in.ndims()) { diff --git a/src/backend/cpu/scan_by_key.cpp b/src/backend/cpu/scan_by_key.cpp index d9a0e44bbe..9af16f2b33 100644 --- a/src/backend/cpu/scan_by_key.cpp +++ b/src/backend/cpu/scan_by_key.cpp @@ -22,8 +22,8 @@ namespace cpu { template Array scan(const Array& key, const Array& in, const int dim, bool inclusive_scan) { - dim4 dims = in.dims(); - Array out = createEmptyArray(dims); + const dim4& dims = in.dims(); + Array out = createEmptyArray(dims); kernel::scan_dim_by_key func1(inclusive_scan); kernel::scan_dim_by_key func2(inclusive_scan); kernel::scan_dim_by_key func3(inclusive_scan); diff --git a/src/backend/cpu/set.cpp b/src/backend/cpu/set.cpp index 7a70238f92..d4bb1612e3 100644 --- a/src/backend/cpu/set.cpp +++ b/src/backend/cpu/set.cpp @@ -30,18 +30,19 @@ using std::unique; template Array setUnique(const Array &in, const bool is_sorted) { Array out = createEmptyArray(af::dim4()); - if (is_sorted) + if (is_sorted) { out = copyArray(in); - else + } else { out = sort(in, 0, true); + } // Need to sync old jobs since we need to // operator on pointers directly in std::unique getQueue().sync(); - T *ptr = out.get(); - T *last = unique(ptr, ptr + in.elements()); - dim_t dist = (dim_t)distance(ptr, last); + T *ptr = out.get(); + T *last = unique(ptr, ptr + in.elements()); + auto dist = static_cast(distance(ptr, last)); dim4 dims(dist, 1, 1, 1); out.resetDims(dims); @@ -70,7 +71,7 @@ Array setUnion(const Array &first, const Array &second, T *last = set_union(uFirst.get(), uFirst.get() + first_elements, uSecond.get(), uSecond.get() + second_elements, ptr); - dim_t dist = (dim_t)distance(ptr, last); + auto dist = static_cast(distance(ptr, last)); dim4 dims(dist, 1, 1, 1); out.resetDims(dims); @@ -99,7 +100,7 @@ Array setIntersect(const Array &first, const Array &second, set_intersection(uFirst.get(), uFirst.get() + first_elements, uSecond.get(), uSecond.get() + second_elements, ptr); - dim_t dist = (dim_t)distance(ptr, last); + auto dist = static_cast(distance(ptr, last)); dim4 dims(dist, 1, 1, 1); out.resetDims(dims); diff --git a/src/backend/cpu/sift.cpp b/src/backend/cpu/sift.cpp index 15281c1a53..455f22c608 100644 --- a/src/backend/cpu/sift.cpp +++ b/src/backend/cpu/sift.cpp @@ -54,14 +54,15 @@ unsigned sift(Array& x, Array& y, Array& score, UNUSED(double_input); UNUSED(img_scale); UNUSED(feature_ratio); - if (compute_GLOH) + if (compute_GLOH) { AF_ERROR( "ArrayFire was not built with nonfree support, GLOH disabled\n", AF_ERR_NONFREE); - else + } else { AF_ERROR( "ArrayFire was not built with nonfree support, SIFT disabled\n", AF_ERR_NONFREE); + } #endif } diff --git a/src/backend/cpu/solve.cpp b/src/backend/cpu/solve.cpp index 8a45b4919c..4f80d442e7 100644 --- a/src/backend/cpu/solve.cpp +++ b/src/backend/cpu/solve.cpp @@ -79,6 +79,7 @@ Array solveLU(const Array &A, const Array &pivot, const Array &b, int NRHS = b.dims()[1]; Array B = copyArray(b); + // NOLINTNEXTLINE auto func = [=](CParam A, Param B, CParam pivot, int N, int NRHS) { getrs_func()(AF_LAPACK_COL_MAJOR, 'N', N, NRHS, A.get(), diff --git a/src/backend/cpu/sort.cpp b/src/backend/cpu/sort.cpp index 01c8e266da..50f44dcae9 100644 --- a/src/backend/cpu/sort.cpp +++ b/src/backend/cpu/sort.cpp @@ -52,10 +52,11 @@ template void sort0(Array& val, bool isAscending) { int higherDims = val.elements() / val.dims()[0]; // TODO Make a better heurisitic - if (higherDims > 10) + if (higherDims > 10) { sortBatched(val, isAscending); - else + } else { getQueue().enqueue(kernel::sort0Iterative, val, isAscending); + } } template @@ -74,7 +75,7 @@ Array sort(const Array& in, const unsigned dim, bool isAscending) { af::dim4 reorderDims(0, 1, 2, 3); reorderDims[dim] = 0; preorderDims[0] = out.dims()[dim]; - for (int i = 1; i <= (int)dim; i++) { + for (int i = 1; i <= static_cast(dim); i++) { reorderDims[i - 1] = i; preorderDims[i] = out.dims()[i - 1]; } diff --git a/src/backend/cpu/sort_by_key.cpp b/src/backend/cpu/sort_by_key.cpp index f4a18f6202..e69672e6a4 100644 --- a/src/backend/cpu/sort_by_key.cpp +++ b/src/backend/cpu/sort_by_key.cpp @@ -44,7 +44,7 @@ void sort_by_key(Array &okey, Array &oval, const Array &ikey, af::dim4 reorderDims(0, 1, 2, 3); reorderDims[dim] = 0; preorderDims[0] = okey.dims()[dim]; - for (int i = 1; i <= (int)dim; i++) { + for (int i = 1; i <= static_cast(dim); i++) { reorderDims[i - 1] = i; preorderDims[i] = okey.dims()[i - 1]; } diff --git a/src/backend/cpu/sort_index.cpp b/src/backend/cpu/sort_index.cpp index 4b8e84c2b6..c7ec0b8c05 100644 --- a/src/backend/cpu/sort_index.cpp +++ b/src/backend/cpu/sort_index.cpp @@ -49,7 +49,7 @@ void sort_index(Array &okey, Array &oval, const Array &in, af::dim4 reorderDims(0, 1, 2, 3); reorderDims[dim] = 0; preorderDims[0] = okey.dims()[dim]; - for (int i = 1; i <= (int)dim; i++) { + for (int i = 1; i <= static_cast(dim); i++) { reorderDims[i - 1] = i; preorderDims[i] = okey.dims()[i - 1]; } diff --git a/src/backend/cpu/sort_index.hpp b/src/backend/cpu/sort_index.hpp index 001f152b95..e4a3cbf775 100644 --- a/src/backend/cpu/sort_index.hpp +++ b/src/backend/cpu/sort_index.hpp @@ -11,6 +11,6 @@ namespace cpu { template -void sort_index(Array &val, Array &idx, const Array &in, +void sort_index(Array &okey, Array &oval, const Array &in, const unsigned dim, bool isAscending); } diff --git a/src/backend/cpu/sparse.cpp b/src/backend/cpu/sparse.cpp index 6409c0789b..7e490d0983 100644 --- a/src/backend/cpu/sparse.cpp +++ b/src/backend/cpu/sparse.cpp @@ -83,13 +83,14 @@ Array sparseConvertStorageToDense(const SparseArray &in) { Array rowIdx = in.getRowIdx(); Array colIdx = in.getColIdx(); - if (stype == AF_STORAGE_CSR) + if (stype == AF_STORAGE_CSR) { getQueue().enqueue(kernel::csr2dense, dense, values, rowIdx, colIdx); - else if (stype == AF_STORAGE_COO) + } else if (stype == AF_STORAGE_COO) { getQueue().enqueue(kernel::coo2dense, dense, values, rowIdx, colIdx); - else + } else { AF_ERROR("CPU Backend only supports CSR or COO to Dense", AF_ERR_NOT_SUPPORTED); + } return dense; } @@ -98,8 +99,8 @@ template SparseArray sparseConvertStorageToStorage(const SparseArray &in) { in.eval(); - auto converted = - createEmptySparseArray(in.dims(), (int)in.getNNZ(), dest); + auto converted = createEmptySparseArray( + in.dims(), static_cast(in.getNNZ()), dest); converted.eval(); function, Param, Param, CParam, CParam, diff --git a/src/backend/cpu/sparse_arith.cpp b/src/backend/cpu/sparse_arith.cpp index ec2383b244..f07d9c57c4 100644 --- a/src/backend/cpu/sparse_arith.cpp +++ b/src/backend/cpu/sparse_arith.cpp @@ -27,25 +27,28 @@ #include #include -namespace cpu { +using common::createArrayDataSparseArray; +using common::createEmptySparseArray; +using common::SparseArray; +using std::numeric_limits; -using namespace common; +namespace cpu { template T getInf() { - return scalar(std::numeric_limits::infinity()); + return scalar(numeric_limits::infinity()); } template<> cfloat getInf() { - return scalar(std::numeric_limits::infinity(), - std::numeric_limits::infinity()); + return scalar(numeric_limits::infinity(), + numeric_limits::infinity()); } template<> cdouble getInf() { - return scalar(std::numeric_limits::infinity(), - std::numeric_limits::infinity()); + return scalar(numeric_limits::infinity(), + numeric_limits::infinity()); } template @@ -109,9 +112,9 @@ template SparseArray arithOp(const SparseArray &lhs, const SparseArray &rhs) { af::storage sfmt = lhs.getStorage(); - const dim4 dims = lhs.dims(); - const uint M = dims[0]; - const uint N = dims[1]; + const dim4 &dims = lhs.dims(); + const uint M = dims[0]; + const uint N = dims[1]; auto rowArr = createEmptyArray(dim4(M + 1)); diff --git a/src/backend/cpu/sparse_blas.cpp b/src/backend/cpu/sparse_blas.cpp index edebaa4b1f..bac8bba6ac 100644 --- a/src/backend/cpu/sparse_blas.cpp +++ b/src/backend/cpu/sparse_blas.cpp @@ -69,12 +69,12 @@ using scale_type = const typename blas_base::type, const T>::type; template -To getScaleValue(Ti val) { - return (To)(val); +auto getScaleValue(Ti val) -> std::remove_cv_t { + return static_cast>(val); } template -scale_type getScale() { +scale_type getScale() { // NOLINT(readability-const-return-type) static T val(value); return getScaleValue, T>(val); } @@ -93,7 +93,7 @@ sparse_operation_t toSparseTranspose(af_mat_prop opt) { #ifdef USE_MKL template<> -const sp_cfloat getScaleValue(cfloat val) { +sp_cfloat getScaleValue(cfloat val) { sp_cfloat ret; ret.real = val.real(); ret.imag = val.imag(); @@ -101,7 +101,7 @@ const sp_cfloat getScaleValue(cfloat val) { } template<> -const sp_cdouble getScaleValue(cdouble val) { +sp_cdouble getScaleValue(cdouble val) { sp_cdouble ret; ret.real = val.real(); ret.imag = val.imag(); @@ -240,7 +240,7 @@ Array matmul(const common::SparseArray &lhs, const Array &rhs, pE, const_cast(colIdx.get()), reinterpret_cast>(vptr)); - struct matrix_descr descrLhs; + struct matrix_descr descrLhs {}; descrLhs.type = SPARSE_MATRIX_TYPE_GENERAL; mkl_sparse_optimize(csrLhs); diff --git a/src/backend/cpu/tile.cpp b/src/backend/cpu/tile.cpp index ac9197f11b..9d951badf8 100644 --- a/src/backend/cpu/tile.cpp +++ b/src/backend/cpu/tile.cpp @@ -20,8 +20,8 @@ namespace cpu { template Array tile(const Array &in, const af::dim4 &tileDims) { - const af::dim4 iDims = in.dims(); - af::dim4 oDims = iDims; + const af::dim4 &iDims = in.dims(); + af::dim4 oDims = iDims; oDims *= tileDims; if (iDims.elements() == 0 || oDims.elements() == 0) { diff --git a/src/backend/cpu/topk.cpp b/src/backend/cpu/topk.cpp index 8fd5393e25..553013001b 100644 --- a/src/backend/cpu/topk.cpp +++ b/src/backend/cpu/topk.cpp @@ -34,7 +34,7 @@ void topk(Array& vals, Array& idxs, const Array& in, int ndims = in.dims().ndims(); for (int i = 0; i < ndims; i++) { if (i == dim) { - out_dims[i] = min(k, (int)in.dims()[i]); + out_dims[i] = min(k, static_cast(in.dims()[i])); } else { out_dims[i] = in.dims()[i]; } diff --git a/src/backend/cpu/transform.cpp b/src/backend/cpu/transform.cpp index 7f90f1a50d..f03dd57919 100644 --- a/src/backend/cpu/transform.cpp +++ b/src/backend/cpu/transform.cpp @@ -17,8 +17,8 @@ namespace cpu { template void transform(Array &out, const Array &in, const Array &tf, - const dim4 &odims, const af_interp_type method, - const bool inverse, const bool perspective) { + const af_interp_type method, const bool inverse, + const bool perspective) { out.eval(); in.eval(); tf.eval(); @@ -45,7 +45,7 @@ void transform(Array &out, const Array &in, const Array &tf, #define INSTANTIATE(T) \ template void transform(Array &out, const Array &in, \ - const Array &tf, const dim4 &odims, \ + const Array &tf, \ const af_interp_type method, const bool inverse, \ const bool perspective); diff --git a/src/backend/cpu/transform.hpp b/src/backend/cpu/transform.hpp index 1ddd73d4d6..e00284980a 100644 --- a/src/backend/cpu/transform.hpp +++ b/src/backend/cpu/transform.hpp @@ -12,6 +12,6 @@ namespace cpu { template void transform(Array &out, const Array &in, const Array &tf, - const af::dim4 &odims, const af_interp_type method, - const bool inverse, const bool perspective); + const af_interp_type method, const bool inverse, + const bool perspective); } diff --git a/src/backend/cpu/transpose.cpp b/src/backend/cpu/transpose.cpp index cd5a6b5c8e..4617f19b97 100644 --- a/src/backend/cpu/transpose.cpp +++ b/src/backend/cpu/transpose.cpp @@ -24,7 +24,7 @@ namespace cpu { template Array transpose(const Array &in, const bool conjugate) { - const dim4 inDims = in.dims(); + const dim4 &inDims = in.dims(); const dim4 outDims = dim4(inDims[1], inDims[0], inDims[2], inDims[3]); // create an array with first two dimensions swapped Array out = createEmptyArray(outDims); diff --git a/src/backend/cpu/types.hpp b/src/backend/cpu/types.hpp index 79232a332b..58be372157 100644 --- a/src/backend/cpu/types.hpp +++ b/src/backend/cpu/types.hpp @@ -30,7 +30,7 @@ using data_t = typename common::kernel_type::data; namespace common { template -class kernel_type; +struct kernel_type; class half; diff --git a/src/backend/cpu/vector_field.hpp b/src/backend/cpu/vector_field.hpp index 45f5bb5929..c25a1501e4 100644 --- a/src/backend/cpu/vector_field.hpp +++ b/src/backend/cpu/vector_field.hpp @@ -14,6 +14,5 @@ namespace cpu { template void copy_vector_field(const Array &points, const Array &directions, - fg_vector_field vector_field); - + fg_vector_field vfield); } diff --git a/src/backend/cpu/wrap.cpp b/src/backend/cpu/wrap.cpp index 9010a306ba..6a6c887faa 100644 --- a/src/backend/cpu/wrap.cpp +++ b/src/backend/cpu/wrap.cpp @@ -20,9 +20,9 @@ using common::half; namespace cpu { template -void wrap(Array &out, const Array &in, const dim_t ox, const dim_t oy, - const dim_t wx, const dim_t wy, const dim_t sx, const dim_t sy, - const dim_t px, const dim_t py, const bool is_column) { +void wrap(Array &out, const Array &in, const dim_t wx, const dim_t wy, + const dim_t sx, const dim_t sy, const dim_t px, const dim_t py, + const bool is_column) { evalMultiple(std::vector *>{const_cast *>(&in), &out}); if (is_column) { @@ -35,10 +35,10 @@ void wrap(Array &out, const Array &in, const dim_t ox, const dim_t oy, } #define INSTANTIATE(T) \ - template void wrap(Array & out, const Array &in, const dim_t ox, \ - const dim_t oy, const dim_t wx, const dim_t wy, \ - const dim_t sx, const dim_t sy, const dim_t px, \ - const dim_t py, const bool is_column); + template void wrap(Array & out, const Array &in, const dim_t wx, \ + const dim_t wy, const dim_t sx, const dim_t sy, \ + const dim_t px, const dim_t py, \ + const bool is_column); INSTANTIATE(float) INSTANTIATE(double) diff --git a/src/backend/cpu/wrap.hpp b/src/backend/cpu/wrap.hpp index c37d05c0ef..bcfe18ef5e 100644 --- a/src/backend/cpu/wrap.hpp +++ b/src/backend/cpu/wrap.hpp @@ -12,9 +12,9 @@ namespace cpu { template -void wrap(Array &out, const Array &in, const dim_t ox, const dim_t oy, - const dim_t wx, const dim_t wy, const dim_t sx, const dim_t sy, - const dim_t px, const dim_t py, const bool is_column); +void wrap(Array &out, const Array &in, const dim_t wx, const dim_t wy, + const dim_t sx, const dim_t sy, const dim_t px, const dim_t py, + const bool is_column); template Array wrap_dilated(const Array &in, const dim_t ox, const dim_t oy, diff --git a/src/backend/cuda/Array.cpp b/src/backend/cuda/Array.cpp index b75e809295..6bfb45ff27 100644 --- a/src/backend/cuda/Array.cpp +++ b/src/backend/cuda/Array.cpp @@ -21,6 +21,7 @@ #include #include #include +#include using af::dim4; using common::half; @@ -30,6 +31,7 @@ using common::NodeIterator; using cuda::jit::BufferNode; using std::accumulate; +using std::move; using std::shared_ptr; using std::vector; @@ -52,9 +54,9 @@ Node_ptr bufferNodePtr() { } template -Array::Array(af::dim4 dims) +Array::Array(const af::dim4 &dims) : info(getActiveDeviceId(), dims, 0, calcStrides(dims), - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data((dims.elements() ? memAlloc(dims.elements()).release() : nullptr), memFree) , data_dims(dims) @@ -63,10 +65,10 @@ Array::Array(af::dim4 dims) , owner(true) {} template -Array::Array(af::dim4 dims, const T *const in_data, bool is_device, +Array::Array(const af::dim4 &dims, const T *const in_data, bool is_device, bool copy_device) : info(getActiveDeviceId(), dims, 0, calcStrides(dims), - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data( ((is_device & !copy_device) ? const_cast(in_data) : memAlloc(dims.elements()).release()), @@ -99,7 +101,7 @@ template Array::Array(const Array &parent, const dim4 &dims, const dim_t &offset_, const dim4 &strides) : info(parent.getDevId(), dims, offset_, strides, - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data(parent.getData()) , data_dims(parent.getDataDims()) , node(bufferNodePtr()) @@ -112,30 +114,31 @@ Array::Array(Param &tmp, bool owner_) af::dim4(tmp.dims[0], tmp.dims[1], tmp.dims[2], tmp.dims[3]), 0, af::dim4(tmp.strides[0], tmp.strides[1], tmp.strides[2], tmp.strides[3]), - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data(tmp.ptr, owner_ ? std::function(memFree) - : std::function([](T *) {})) + : std::function([](T * /*unused*/) {})) , data_dims(af::dim4(tmp.dims[0], tmp.dims[1], tmp.dims[2], tmp.dims[3])) , node(bufferNodePtr()) , ready(true) , owner(owner_) {} template -Array::Array(af::dim4 dims, common::Node_ptr n) +Array::Array(const af::dim4 &dims, common::Node_ptr n) : info(getActiveDeviceId(), dims, 0, calcStrides(dims), - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data() , data_dims(dims) - , node(n) + , node(move(n)) , ready(false) , owner(true) {} template -Array::Array(af::dim4 dims, af::dim4 strides, dim_t offset_, +Array::Array(const af::dim4 &dims, const af::dim4 &strides, dim_t offset_, const T *const in_data, bool is_device) : info(getActiveDeviceId(), dims, offset_, strides, - (af_dtype)dtype_traits::af_type) - , data(is_device ? (T *)in_data : memAlloc(info.total()).release(), + static_cast(dtype_traits::af_type)) + , data(is_device ? const_cast(in_data) + : memAlloc(info.total()).release(), memFree) , data_dims(dims) , node(bufferNodePtr()) @@ -152,7 +155,7 @@ Array::Array(af::dim4 dims, af::dim4 strides, dim_t offset_, template void Array::eval() { - if (isReady()) return; + if (isReady()) { return; } this->setId(getActiveDeviceId()); this->data = shared_ptr(memAlloc(elements()).release(), memFree); @@ -174,7 +177,7 @@ T *Array::device() { template void Array::eval() const { - if (isReady()) return; + if (isReady()) { return; } const_cast *>(this)->eval(); } @@ -211,20 +214,18 @@ void evalMultiple(std::vector *> arrays) { evalNodes(outputs, nodes); - for (Array *array : output_arrays) array->node = bufferNodePtr(); - - return; + for (Array *array : output_arrays) { array->node = bufferNodePtr(); } } template -Array::~Array() {} +Array::~Array() = default; template Node_ptr Array::getNode() { if (node->isBuffer()) { - unsigned bytes = this->getDataDims().elements() * sizeof(T); - BufferNode *bufNode = reinterpret_cast *>(node.get()); - Param param = *this; + unsigned bytes = this->getDataDims().elements() * sizeof(T); + auto *bufNode = reinterpret_cast *>(node.get()); + Param param = *this; bufNode->setData(param, data, bytes, isLinear()); } return node; @@ -253,7 +254,7 @@ Node_ptr Array::getNode() const { template kJITHeuristics passesJitHeuristics(Node *root_node) { if (!evalFlag()) { return kJITHeuristics::Pass; } - if (root_node->getHeight() >= (int)getMaxJitSize()) { + if (root_node->getHeight() >= static_cast(getMaxJitSize())) { return kJITHeuristics::TreeHeight; } @@ -361,18 +362,18 @@ Array createSubArray(const Array &parent, return createSubArray(parentCopy, index, copy); } - dim4 pDims = parent.dims(); - dim4 dims = toDims(index, pDims); - dim4 strides = toStride(index, dDims); + const dim4 &pDims = parent.dims(); + dim4 dims = toDims(index, pDims); + dim4 strides = toStride(index, dDims); // Find total offsets after indexing dim4 offsets = toOffset(index, pDims); dim_t offset = parent.getOffset(); - for (int i = 0; i < 4; i++) offset += offsets[i] * parent_strides[i]; + for (int i = 0; i < 4; i++) { offset += offsets[i] * parent_strides[i]; } Array out = Array(parent, dims, offset, strides); - if (!copy) return out; + if (!copy) { return out; } if (strides[0] != 1 || strides[1] < 0 || strides[2] < 0 || strides[3] < 0) { out = copyArray(out); @@ -401,8 +402,6 @@ void writeHostDataArray(Array &arr, const T *const data, CUDA_CHECK(cudaMemcpyAsync(ptr, data, bytes, cudaMemcpyHostToDevice, cuda::getActiveStream())); CUDA_CHECK(cudaStreamSynchronize(cuda::getActiveStream())); - - return; } template @@ -414,8 +413,6 @@ void writeDeviceDataArray(Array &arr, const void *const data, CUDA_CHECK(cudaMemcpyAsync(ptr, data, bytes, cudaMemcpyDeviceToDevice, cuda::getActiveStream())); - - return; } template @@ -437,11 +434,11 @@ void Array::setDataDims(const dim4 &new_dims) { template void destroyArray(Array * A); \ template Array createNodeArray(const dim4 &size, \ common::Node_ptr node); \ - template Array::Array(af::dim4 dims, af::dim4 strides, dim_t offset, \ - const T *const in_data, bool is_device); \ - template Array::Array(af::dim4 dims, const T *const in_data, \ + template Array::Array(const af::dim4 &dims, const af::dim4 &strides, \ + dim_t offset, const T *const in_data, \ + bool is_device); \ + template Array::Array(const af::dim4 &dims, const T *const in_data, \ bool is_device, bool copy_device); \ - template Array::~Array(); \ template Node_ptr Array::getNode() const; \ template void Array::eval(); \ template void Array::eval() const; \ diff --git a/src/backend/cuda/Array.hpp b/src/backend/cuda/Array.hpp index 33b2588672..887bbc4baa 100644 --- a/src/backend/cuda/Array.hpp +++ b/src/backend/cuda/Array.hpp @@ -33,16 +33,17 @@ template void evalNodes(Param out, common::Node *node); template -void evalNodes(std::vector> &out, std::vector nodes); +void evalNodes(std::vector> &out, + const std::vector &nodes); template void evalMultiple(std::vector *> arrays); template -Array createNodeArray(const af::dim4 &size, common::Node_ptr node); +Array createNodeArray(const af::dim4 &dims, common::Node_ptr node); template -Array createValueArray(const af::dim4 &size, const T &value); +Array createValueArray(const af::dim4 &dims, const T &value); // Creates an array and copies from the \p data pointer located in host memory // @@ -52,11 +53,12 @@ template Array createHostDataArray(const af::dim4 &dims, const T *const data); template -Array createDeviceDataArray(const af::dim4 &size, void *data); +Array createDeviceDataArray(const af::dim4 &dims, void *data); template -Array createStridedArray(af::dim4 dims, af::dim4 strides, dim_t offset, - const T *const in_data, bool is_device) { +Array createStridedArray(const af::dim4 &dims, const af::dim4 &strides, + dim_t offset, const T *const in_data, + bool is_device) { return Array(dims, strides, offset, in_data, is_device); } @@ -73,7 +75,7 @@ void writeDeviceDataArray(Array &arr, const void *const data, /// /// \param[in] size The dimension of the output array template -Array createEmptyArray(const af::dim4 &size); +Array createEmptyArray(const af::dim4 &dims); /// Create an Array object from Param object. /// @@ -82,7 +84,7 @@ Array createEmptyArray(const af::dim4 &size); /// If false /// the Array will not delete the object on destruction template -Array createParamArray(Param &in, bool owner); +Array createParamArray(Param &tmp, bool owner); template Array createSubArray(const Array &parent, @@ -124,18 +126,18 @@ class Array { bool ready; bool owner; - Array(af::dim4 dims); + Array(const af::dim4 &dims); - explicit Array(af::dim4 dims, const T *const in_data, + explicit Array(const af::dim4 &dims, const T *const in_data, bool is_device = false, bool copy_device = false); - Array(const Array &parnt, const dim4 &dims, const dim_t &offset, + Array(const Array &parent, const dim4 &dims, const dim_t &offset, const dim4 &stride); Array(Param &tmp, bool owner); - Array(af::dim4 dims, common::Node_ptr n); + Array(const af::dim4 &dims, common::Node_ptr n); public: - Array(af::dim4 dims, af::dim4 strides, dim_t offset, const T *const in_data, - bool is_device = false); + Array(const af::dim4 &dims, const af::dim4 &strides, dim_t offset, + const T *const in_data, bool is_device = false); void resetInfo(const af::dim4 &dims) { info.resetInfo(dims); } void resetDims(const af::dim4 &dims) { info.resetDims(dims); } @@ -238,14 +240,15 @@ class Array { friend void evalMultiple(std::vector *> arrays); friend Array createValueArray(const af::dim4 &size, const T &value); - friend Array createHostDataArray(const af::dim4 &size, + friend Array createHostDataArray(const af::dim4 &dims, const T *const data); - friend Array createDeviceDataArray(const af::dim4 &size, void *data); - friend Array createStridedArray(af::dim4 dims, af::dim4 strides, - dim_t offset, const T *const in_data, + friend Array createDeviceDataArray(const af::dim4 &dims, void *data); + friend Array createStridedArray(const af::dim4 &dims, + const af::dim4 &strides, dim_t offset, + const T *const in_data, bool is_device); - friend Array createEmptyArray(const af::dim4 &size); + friend Array createEmptyArray(const af::dim4 &dims); friend Array createParamArray(Param &tmp, bool owner); friend Array createNodeArray(const af::dim4 &dims, common::Node_ptr node); diff --git a/src/backend/cuda/Event.hpp b/src/backend/cuda/Event.hpp index 4d9cb7e295..b6600934e4 100644 --- a/src/backend/cuda/Event.hpp +++ b/src/backend/cuda/Event.hpp @@ -51,7 +51,7 @@ class CUDARuntimeEventPolicy { using Event = common::EventBase; /// \brief Creates a new event and marks it in the stream -Event makeEvent(cudaStream_t stream); +Event makeEvent(cudaStream_t queue); af_event createEvent(); diff --git a/src/backend/cuda/GraphicsResourceManager.cpp b/src/backend/cuda/GraphicsResourceManager.cpp index c2f45f488e..5778f72658 100644 --- a/src/backend/cuda/GraphicsResourceManager.cpp +++ b/src/backend/cuda/GraphicsResourceManager.cpp @@ -18,7 +18,8 @@ namespace cuda { GraphicsResourceManager::ShrdResVector -GraphicsResourceManager::registerResources(std::vector resources) { +GraphicsResourceManager::registerResources( + const std::vector& resources) { ShrdResVector output; auto deleter = [](cudaGraphicsResource_t* handle) { diff --git a/src/backend/cuda/GraphicsResourceManager.hpp b/src/backend/cuda/GraphicsResourceManager.hpp index ff6a261ba1..ba05c2dbe3 100644 --- a/src/backend/cuda/GraphicsResourceManager.hpp +++ b/src/backend/cuda/GraphicsResourceManager.hpp @@ -23,10 +23,11 @@ class GraphicsResourceManager using ShrdResVector = std::vector>; GraphicsResourceManager() {} - ShrdResVector registerResources(std::vector resources); + static ShrdResVector registerResources( + const std::vector &resources); protected: - GraphicsResourceManager(GraphicsResourceManager const&); - void operator=(GraphicsResourceManager const&); + GraphicsResourceManager(GraphicsResourceManager const &); + void operator=(GraphicsResourceManager const &); }; } // namespace cuda diff --git a/src/backend/cuda/ThrustArrayFirePolicy.cpp b/src/backend/cuda/ThrustArrayFirePolicy.cpp index c67a4ac2e5..6f21b96ed3 100644 --- a/src/backend/cuda/ThrustArrayFirePolicy.cpp +++ b/src/backend/cuda/ThrustArrayFirePolicy.cpp @@ -11,9 +11,11 @@ namespace cuda { -cudaStream_t get_stream(ThrustArrayFirePolicy) { return getActiveStream(); } +cudaStream_t get_stream(ThrustArrayFirePolicy /*unused*/) { + return getActiveStream(); +} -cudaError_t synchronize_stream(ThrustArrayFirePolicy) { +cudaError_t synchronize_stream(ThrustArrayFirePolicy /*unused*/) { return cudaStreamSynchronize(getActiveStream()); } diff --git a/src/backend/cuda/blas.cu b/src/backend/cuda/blas.cu index 188a426118..3f6dec1fa8 100644 --- a/src/backend/cuda/blas.cu +++ b/src/backend/cuda/blas.cu @@ -176,7 +176,6 @@ cudaDataType_t getComputeType() { template<> cudaDataType_t getComputeType() { - auto dev = getDeviceProp(getActiveDeviceId()); cudaDataType_t algo = getType(); // There is probbaly a bug in nvidia cuda docs and/or drivers: According to // https://docs.nvidia.com/cuda/cublas/index.html#cublas-GemmEx computeType @@ -186,6 +185,7 @@ cudaDataType_t getComputeType() { // returns OK. At the moment let's comment out : the drawback is just that // the speed of f16 computation on these GPUs is very slow: // + // auto dev = getDeviceProp(getActiveDeviceId()); // if (dev.major == // 6 && dev.minor == 1) { algo = CUDA_R_32F; } return algo; @@ -193,9 +193,7 @@ cudaDataType_t getComputeType() { template cublasGemmAlgo_t selectGEMMAlgorithm() { - auto dev = getDeviceProp(getActiveDeviceId()); - cublasGemmAlgo_t algo = CUBLAS_GEMM_DEFAULT; - return algo; + return CUBLAS_GEMM_DEFAULT; } template<> diff --git a/src/backend/cuda/cholesky.cpp b/src/backend/cuda/cholesky.cpp index 9d824e1a10..973df87d83 100644 --- a/src/backend/cuda/cholesky.cpp +++ b/src/backend/cuda/cholesky.cpp @@ -41,16 +41,16 @@ namespace cuda { template struct potrf_func_def_t { - typedef cusolverStatus_t (*potrf_func_def)(cusolverDnHandle_t, - cublasFillMode_t, int, T *, int, - T *, int, int *); + using potrf_func_def = cusolverStatus_t (*)(cusolverDnHandle_t, + cublasFillMode_t, int, T *, int, + T *, int, int *); }; template struct potrf_buf_func_def_t { - typedef cusolverStatus_t (*potrf_buf_func_def)(cusolverDnHandle_t, - cublasFillMode_t, int, T *, - int, int *); + using potrf_buf_func_def = cusolverStatus_t (*)(cusolverDnHandle_t, + cublasFillMode_t, int, T *, + int, int *); }; #define CH_FUNC_DEF(FUNC) \ @@ -85,10 +85,11 @@ Array cholesky(int *info, const Array &in, const bool is_upper) { Array out = copyArray(in); *info = cholesky_inplace(out, is_upper); - if (is_upper) + if (is_upper) { triangle(out, out); - else + } else { triangle(out, out); + } return out; } @@ -101,7 +102,7 @@ int cholesky_inplace(Array &in, const bool is_upper) { int lwork = 0; cublasFillMode_t uplo = CUBLAS_FILL_MODE_LOWER; - if (is_upper) uplo = CUBLAS_FILL_MODE_UPPER; + if (is_upper) { uplo = CUBLAS_FILL_MODE_UPPER; } CUSOLVER_CHECK(potrf_buf_func()(solverDnHandle(), uplo, N, in.get(), in.strides()[1], &lwork)); diff --git a/src/backend/cuda/convolve.cpp b/src/backend/cuda/convolve.cpp index 96e2b165a8..90141e2e7a 100644 --- a/src/backend/cuda/convolve.cpp +++ b/src/backend/cuda/convolve.cpp @@ -30,8 +30,8 @@ namespace cuda { template Array convolve(Array const &signal, Array const &filter, AF_BATCH_KIND kind) { - const dim4 sDims = signal.dims(); - const dim4 fDims = filter.dims(); + const dim4 &sDims = signal.dims(); + const dim4 &fDims = filter.dims(); dim4 oDims(1); if (expand) { @@ -45,7 +45,7 @@ Array convolve(Array const &signal, Array const &filter, } else { oDims = sDims; if (kind == AF_BATCH_RHS) { - for (dim_t i = baseDim; i < 4; ++i) oDims[i] = fDims[i]; + for (dim_t i = baseDim; i < 4; ++i) { oDims[i] = fDims[i]; } } } @@ -59,15 +59,15 @@ Array convolve(Array const &signal, Array const &filter, template Array convolve2(Array const &signal, Array const &c_filter, Array const &r_filter) { - const dim4 cfDims = c_filter.dims(); - const dim4 rfDims = r_filter.dims(); + const dim4 &cfDims = c_filter.dims(); + const dim4 &rfDims = r_filter.dims(); const dim_t cfLen = cfDims.elements(); const dim_t rfLen = rfDims.elements(); - const dim4 sDims = signal.dims(); - dim4 tDims = sDims; - dim4 oDims = sDims; + const dim4 &sDims = signal.dims(); + dim4 tDims = sDims; + dim4 oDims = sDims; if (expand) { tDims[0] += cfLen - 1; diff --git a/src/backend/cuda/convolveNN.cpp b/src/backend/cuda/convolveNN.cpp index 9810ac6544..e0db33264b 100644 --- a/src/backend/cuda/convolveNN.cpp +++ b/src/backend/cuda/convolveNN.cpp @@ -41,7 +41,7 @@ namespace cuda { template unique_handle toCudnn(Array arr) { - dim4 dims = arr.dims(); + const dim4 &dims = arr.dims(); auto descriptor = make_handle(); cudnnDataType_t cudnn_dtype = getCudnnDataType(); @@ -55,12 +55,12 @@ using scale_type = template Array convolve2_cudnn(const Array &signal, const Array &filter, - const dim4 stride, const dim4 padding, - const dim4 dilation) { + const dim4 &stride, const dim4 &padding, + const dim4 &dilation) { cudnnHandle_t cudnn = nnHandle(); - dim4 sDims = signal.dims(); - dim4 fDims = filter.dims(); + dim4 sDims = signal.dims(); + const dim4 &fDims = filter.dims(); const int n = sDims[3]; const int c = sDims[2]; @@ -115,8 +115,8 @@ Array convolve2_cudnn(const Array &signal, const Array &filter, auto workspace_buffer = memAlloc(workspace_bytes); // perform convolution - scale_type alpha = scalar>(1.0); - scale_type beta = scalar>(0.0); + auto alpha = scalar>(1.0); + auto beta = scalar>(0.0); CUDNN_CHECK(cuda::cudnnConvolutionForward( cudnn, &alpha, input_descriptor, signal.device(), filter_descriptor, filter.device(), convolution_descriptor, convolution_algorithm, @@ -138,8 +138,8 @@ constexpr void checkTypeSupport() { template Array convolve2_base(const Array &signal, const Array &filter, - const dim4 stride, const dim4 padding, - const dim4 dilation) { + const dim4 &stride, const dim4 &padding, + const dim4 &dilation) { dim4 sDims = signal.dims(); dim4 fDims = filter.dims(); @@ -209,9 +209,10 @@ Array data_gradient_base(const Array &incoming_gradient, const Array &original_filter, const Array &convolved_output, af::dim4 stride, af::dim4 padding, af::dim4 dilation) { - const dim4 cDims = incoming_gradient.dims(); - const dim4 sDims = original_signal.dims(); - const dim4 fDims = original_filter.dims(); + UNUSED(convolved_output); + const dim4 &cDims = incoming_gradient.dims(); + const dim4 &sDims = original_signal.dims(); + const dim4 &fDims = original_filter.dims(); Array collapsed_filter = original_filter; @@ -250,11 +251,12 @@ Array data_gradient_cudnn(const Array &incoming_gradient, const Array &original_filter, const Array &convolved_output, af::dim4 stride, af::dim4 padding, af::dim4 dilation) { + UNUSED(convolved_output); auto cudnn = nnHandle(); - dim4 iDims = incoming_gradient.dims(); - dim4 sDims = original_signal.dims(); - dim4 fDims = original_filter.dims(); + const dim4 &iDims = incoming_gradient.dims(); + dim4 sDims = original_signal.dims(); + dim4 fDims = original_filter.dims(); cudnnDataType_t cudnn_dtype = getCudnnDataType(); @@ -295,8 +297,8 @@ Array data_gradient_cudnn(const Array &incoming_gradient, auto workspace_buffer = memAlloc(workspace_bytes); // perform convolution - scale_type alpha = scalar>(1.0); - scale_type beta = scalar>(0.0); + auto alpha = scalar>(1.0); + auto beta = scalar>(0.0); CUDNN_CHECK(cuda::cudnnConvolutionBackwardData( cudnn, &alpha, w_descriptor, original_filter.get(), dy_descriptor, @@ -333,9 +335,10 @@ Array filter_gradient_base(const Array &incoming_gradient, const Array &original_filter, const Array &convolved_output, af::dim4 stride, af::dim4 padding, af::dim4 dilation) { - const dim4 cDims = incoming_gradient.dims(); - const dim4 sDims = original_signal.dims(); - const dim4 fDims = original_filter.dims(); + UNUSED(convolved_output); + const dim4 &cDims = incoming_gradient.dims(); + const dim4 &sDims = original_signal.dims(); + const dim4 &fDims = original_filter.dims(); const bool retCols = false; Array unwrapped = @@ -372,11 +375,12 @@ Array filter_gradient_cudnn(const Array &incoming_gradient, const Array &convolved_output, af::dim4 stride, af::dim4 padding, af::dim4 dilation) { + UNUSED(convolved_output); auto cudnn = nnHandle(); - dim4 iDims = incoming_gradient.dims(); - dim4 sDims = original_signal.dims(); - dim4 fDims = original_filter.dims(); + const dim4 &iDims = incoming_gradient.dims(); + const dim4 &sDims = original_signal.dims(); + const dim4 &fDims = original_filter.dims(); // create dx descriptor cudnnDataType_t cudnn_dtype = getCudnnDataType(); @@ -410,8 +414,8 @@ Array filter_gradient_cudnn(const Array &incoming_gradient, auto workspace_buffer = memAlloc(workspace_bytes); // perform convolution - scale_type alpha = scalar>(1.0); - scale_type beta = scalar>(0.0); + auto alpha = scalar>(1.0); + auto beta = scalar>(0.0); CUDNN_CHECK(cuda::cudnnConvolutionBackwardFilter( cudnn, &alpha, x_descriptor, original_signal.device(), dy_descriptor, incoming_gradient.device(), convolution_descriptor, diff --git a/src/backend/cuda/copy.cpp b/src/backend/cuda/copy.cpp index a570dab611..6940382b69 100644 --- a/src/backend/cuda/copy.cpp +++ b/src/backend/cuda/copy.cpp @@ -44,7 +44,6 @@ void copyData(T *dst, const Array &src) { CUDA_CHECK(cudaMemcpyAsync(dst, ptr, src.elements() * sizeof(T), cudaMemcpyDeviceToHost, stream)); CUDA_CHECK(cudaStreamSynchronize(stream)); - return; } template @@ -221,7 +220,7 @@ INSTANTIATE_PAD_ARRAY_COMPLEX(cdouble) template T getScalar(const Array &in) { - T retVal; + T retVal{}; CUDA_CHECK(cudaMemcpyAsync(&retVal, in.get(), sizeof(T), cudaMemcpyDeviceToHost, cuda::getActiveStream())); diff --git a/src/backend/cuda/cudnnModule.cpp b/src/backend/cuda/cudnnModule.cpp index 03a14942e3..210a1a6c03 100644 --- a/src/backend/cuda/cudnnModule.cpp +++ b/src/backend/cuda/cudnnModule.cpp @@ -16,6 +16,7 @@ #include #include +using std::make_tuple; using std::string; namespace cuda { @@ -25,10 +26,10 @@ spdlog::logger* cudnnModule::getLogger() const noexcept { } auto cudnnVersionComponents(size_t version) { - int major = version / 1000; - int minor = (version - (major * 1000)) / 100; - int patch = (version - (major * 1000) - (minor * 100)); - return std::tuple(major, minor, patch); + size_t major = version / 1000; + size_t minor = (version - (major * 1000)) / 100; + size_t patch = (version - (major * 1000) - (minor * 100)); + return make_tuple(major, minor, patch); } cudnnModule::cudnnModule() @@ -48,8 +49,8 @@ cudnnModule::cudnnModule() MODULE_FUNCTION_INIT(cudnnGetVersion); int rtmajor, rtminor; - int cudnn_version = this->cudnnGetVersion(); - int cudnn_rtversion = 0; + size_t cudnn_version = this->cudnnGetVersion(); + size_t cudnn_rtversion = 0; std::tie(major, minor, patch) = cudnnVersionComponents(cudnn_version); if (cudnn_version >= 6000) { @@ -135,7 +136,7 @@ cudnnModule::cudnnModule() } cudnnModule& getCudnnPlugin() noexcept { - static cudnnModule* plugin = new cudnnModule(); + static auto* plugin = new cudnnModule(); return *plugin; } diff --git a/src/backend/cuda/cudnnModule.hpp b/src/backend/cuda/cudnnModule.hpp index c850185e40..aa762e25fd 100644 --- a/src/backend/cuda/cudnnModule.hpp +++ b/src/backend/cuda/cudnnModule.hpp @@ -35,7 +35,7 @@ namespace cuda { class cudnnModule { common::DependencyModule module; - int major, minor, patch; + int major{}, minor{}, patch{}; public: cudnnModule(); diff --git a/src/backend/cuda/device_manager.cpp b/src/backend/cuda/device_manager.cpp index 83aa9a0101..d2a23b7f1c 100644 --- a/src/backend/cuda/device_manager.cpp +++ b/src/backend/cuda/device_manager.cpp @@ -94,10 +94,11 @@ bool checkDeviceWithRuntime(int runtime, pair compute) { } if (rt->major >= compute.first) { - if (rt->major == compute.first) + if (rt->major == compute.first) { return rt->minor >= compute.second; - else + } else { return true; + } } else { return false; } @@ -155,7 +156,7 @@ pair getComputeCapability(const int device) { } // pulled from CUTIL from CUDA SDK -static inline int compute2cores(int major, int minor) { +static inline int compute2cores(unsigned major, unsigned minor) { struct { int compute; // 0xMm (hex), M = major version, m = minor version int cores; @@ -167,7 +168,7 @@ static inline int compute2cores(int major, int minor) { }; for (int i = 0; gpus[i].compute != -1; ++i) { - if (gpus[i].compute == (major << 4) + minor) return gpus[i].cores; + if (gpus[i].compute == (major << 4U) + minor) { return gpus[i].cores; } } return 0; } @@ -263,7 +264,7 @@ bool DeviceManager::checkGraphicsInteropCapability() { } DeviceManager &DeviceManager::getInstance() { - static DeviceManager *my_instance = new DeviceManager(); + static auto *my_instance = new DeviceManager(); return *my_instance; } @@ -475,9 +476,8 @@ void DeviceManager::checkCudaVsDriverVersion() { /// are assuming that the initilization is done in the main thread. void initNvrtc() { nvrtcProgram prog; - auto err = nvrtcCreateProgram(&prog, " ", "dummy", 0, nullptr, nullptr); + nvrtcCreateProgram(&prog, " ", "dummy", 0, nullptr, nullptr); nvrtcDestroyProgram(&prog); - return; } DeviceManager::DeviceManager() @@ -501,7 +501,7 @@ DeviceManager::DeviceManager() int cudaMajorVer = cudaRtVer / 1000; for (int i = 0; i < nDevices; i++) { - cudaDevice_t dev; + cudaDevice_t dev{}; CUDA_CHECK(cudaGetDeviceProperties(&dev.prop, i)); if (dev.prop.major < getMinSupportedCompute(cudaMajorVer)) { AF_TRACE("Unsuppored device: {}", dev.prop.name); @@ -540,7 +540,7 @@ DeviceManager::DeviceManager() // Initialize all streams to 0. // Streams will be created in setActiveDevice() for (size_t i = 0; i < MAX_DEVICES; i++) { - streams[i] = (cudaStream_t)0; + streams[i] = static_cast(0); if (i < nDevices) { auto prop = make_pair(cuDevices[i].prop.major, cuDevices[i].prop.minor); @@ -601,11 +601,11 @@ int DeviceManager::setActiveDevice(int device, int nId) { int numDevices = cuDevices.size(); - if (device >= numDevices) return -1; + if (device >= numDevices) { return -1; } int old = getActiveDeviceId(); - if (nId == -1) nId = getDeviceNativeId(device); + if (nId == -1) { nId = getDeviceNativeId(device); } cudaError_t err = cudaSetDevice(nId); @@ -645,7 +645,7 @@ int DeviceManager::setActiveDevice(int device, int nId) { // otherwise fails streamCreate with this error. // All other errors will error out device++; - if (device >= numDevices) break; + if (device >= numDevices) { break; } // Can't call getNativeId here as it will cause an infinite loop with // the constructor diff --git a/src/backend/cuda/device_manager.hpp b/src/backend/cuda/device_manager.hpp index 4594f21d8a..d661244bf4 100644 --- a/src/backend/cuda/device_manager.hpp +++ b/src/backend/cuda/device_manager.hpp @@ -74,7 +74,7 @@ class DeviceManager { friend std::string getPlatformInfo() noexcept; - friend std::string getDriverVersion(); + friend std::string getDriverVersion() noexcept; friend std::string getCUDARuntimeVersion() noexcept; @@ -112,7 +112,7 @@ class DeviceManager { void checkCudaVsDriverVersion(); void sortDevices(sort_mode mode = flops); - int setActiveDevice(int device, int native = -1); + int setActiveDevice(int device, int nId = -1); std::shared_ptr logger; @@ -120,7 +120,7 @@ class DeviceManager { std::vector> devJitComputes; int nDevices; - cudaStream_t streams[MAX_DEVICES]; + cudaStream_t streams[MAX_DEVICES]{}; std::unique_ptr fgMngr; diff --git a/src/backend/cuda/diff.cpp b/src/backend/cuda/diff.cpp index 21482bacec..f67a0eabda 100644 --- a/src/backend/cuda/diff.cpp +++ b/src/backend/cuda/diff.cpp @@ -17,8 +17,8 @@ namespace cuda { template Array diff(const Array &in, const int dim, const bool isDiff2) { - const af::dim4 iDims = in.dims(); - af::dim4 oDims = iDims; + const af::dim4 &iDims = in.dims(); + af::dim4 oDims = iDims; oDims[dim] -= (isDiff2 + 1); if (iDims.elements() == 0 || oDims.elements() == 0) { diff --git a/src/backend/cuda/driver.cpp b/src/backend/cuda/driver.cpp index 088f2f04de..4edcbf664f 100644 --- a/src/backend/cuda/driver.cpp +++ b/src/backend/cuda/driver.cpp @@ -8,8 +8,8 @@ ********************************************************/ #include -#include -#include +#include +#include #ifdef OS_WIN #include @@ -59,34 +59,39 @@ int nvDriverVersion(char *result, int len) { char buffer[1024]; FILE *f = NULL; - if (NULL == (f = fopen("/proc/driver/nvidia/version", "r"))) { return 0; } + if (NULL == (f = fopen("/proc/driver/nvidia/version", "re"))) { return 0; } if (fgets(buffer, 1024, f) == NULL) { - if (f) fclose(f); + if (f) { fclose(f); } return 0; } // just close it now since we've already read what we need - if (f) fclose(f); + if (f) { fclose(f); } for (i = 1; i < 8; i++) { - while (buffer[pos] != ' ' && buffer[pos] != '\t') - if (pos >= 1024 || buffer[pos] == '\0' || buffer[pos] == '\n') + while (buffer[pos] != ' ' && buffer[pos] != '\t') { + if (pos >= 1024 || buffer[pos] == '\0' || buffer[pos] == '\n') { return 0; - else + } else { pos++; - while (buffer[pos] == ' ' || buffer[pos] == '\t') - if (pos >= 1024 || buffer[pos] == '\0' || buffer[pos] == '\n') + } + } + while (buffer[pos] == ' ' || buffer[pos] == '\t') { + if (pos >= 1024 || buffer[pos] == '\0' || buffer[pos] == '\n') { return 0; - else + } else { pos++; + } + } } epos = pos; while (buffer[epos] != ' ' && buffer[epos] != '\t') { - if (epos >= 1024 || buffer[epos] == '\0' || buffer[epos] == '\n') + if (epos >= 1024 || buffer[epos] == '\0' || buffer[epos] == '\n') { return 0; - else + } else { epos++; + } } buffer[epos] = '\0'; diff --git a/src/backend/cuda/driver.h b/src/backend/cuda/driver.h index 835c3fef17..fa828301f9 100644 --- a/src/backend/cuda/driver.h +++ b/src/backend/cuda/driver.h @@ -13,7 +13,7 @@ extern "C" { #endif -int nvDriverVersion(char *buffer, int len); +int nvDriverVersion(char *result, int len); #ifdef __cplusplus } diff --git a/src/backend/cuda/fast_pyramid.cpp b/src/backend/cuda/fast_pyramid.cpp index 6bd2055097..8d14cf752c 100644 --- a/src/backend/cuda/fast_pyramid.cpp +++ b/src/backend/cuda/fast_pyramid.cpp @@ -36,10 +36,10 @@ void fast_pyramid(vector &feat_pyr, vector> &x_pyr, min_side /= scl_fctr; // Minimum image side for a descriptor to be computed - if (min_side < patch_size || max_levels == levels) break; + if (min_side < patch_size || max_levels == levels) { break; } max_levels++; - scl_sum += 1.f / (float)std::pow(scl_fctr, (float)i); + scl_sum += 1.f / std::pow(scl_fctr, static_cast(i)); } // Compute number of features to keep for each level @@ -47,13 +47,14 @@ void fast_pyramid(vector &feat_pyr, vector> &x_pyr, lvl_scl.resize(max_levels); unsigned feat_sum = 0; for (unsigned i = 0; i < max_levels - 1; i++) { - float scl = (float)std::pow(scl_fctr, (float)i); + auto scl = std::pow(scl_fctr, static_cast(i)); lvl_scl[i] = scl; lvl_best[i] = ceil((max_feat / scl_sum) / lvl_scl[i]); feat_sum += lvl_best[i]; } - lvl_scl[max_levels - 1] = (float)std::pow(scl_fctr, (float)max_levels - 1); + lvl_scl[max_levels - 1] = + std::pow(scl_fctr, static_cast(max_levels) - 1); lvl_best[max_levels - 1] = max_feat - feat_sum; // Hold multi-scale image pyramids diff --git a/src/backend/cuda/fast_pyramid.hpp b/src/backend/cuda/fast_pyramid.hpp index 762b61c011..ceac076d95 100644 --- a/src/backend/cuda/fast_pyramid.hpp +++ b/src/backend/cuda/fast_pyramid.hpp @@ -19,7 +19,7 @@ void fast_pyramid(std::vector &feat_pyr, std::vector> &d_x_pyr, std::vector> &d_y_pyr, std::vector &lvl_best, std::vector &lvl_scl, - std::vector> &img_pyr, const Array &image, + std::vector> &img_pyr, const Array &in, const float fast_thr, const unsigned max_feat, const float scl_fctr, const unsigned levels, const unsigned patch_size); diff --git a/src/backend/cuda/fftconvolve.cpp b/src/backend/cuda/fftconvolve.cpp index 33105b7a53..3b6d38ce8a 100644 --- a/src/backend/cuda/fftconvolve.cpp +++ b/src/backend/cuda/fftconvolve.cpp @@ -20,20 +20,21 @@ using af::dim4; namespace cuda { template -const dim4 calcPackedSize(Array const& i1, Array const& i2, - const dim_t baseDim) { - const dim4 i1d = i1.dims(); - const dim4 i2d = i2.dims(); +dim4 calcPackedSize(Array const& i1, Array const& i2, + const dim_t baseDim) { + const dim4& i1d = i1.dims(); + const dim4& i2d = i2.dims(); dim_t pd[4] = {1, 1, 1, 1}; dim_t max_d0 = (i1d[0] > i2d[0]) ? i1d[0] : i2d[0]; dim_t min_d0 = (i1d[0] < i2d[0]) ? i1d[0] : i2d[0]; - pd[0] = nextpow2((unsigned)((int)ceil(max_d0 / 2.f) + min_d0 - 1)); + pd[0] = nextpow2(static_cast( + static_cast(ceil(max_d0 / 2.f)) + min_d0 - 1)); for (dim_t k = 1; k < 4; k++) { if (k < baseDim) { - pd[k] = nextpow2((unsigned)(i1d[k] + i2d[k] - 1)); + pd[k] = nextpow2(static_cast(i1d[k] + i2d[k] - 1)); } else { pd[k] = i1d[k]; } @@ -46,8 +47,8 @@ template Array fftconvolve(Array const& signal, Array const& filter, const bool expand, AF_BATCH_KIND kind) { - const dim4 sDims = signal.dims(); - const dim4 fDims = filter.dims(); + const dim4& sDims = signal.dims(); + const dim4& fDims = filter.dims(); dim4 oDims(1); if (expand) { @@ -61,7 +62,7 @@ Array fftconvolve(Array const& signal, Array const& filter, } else { oDims = sDims; if (kind == AF_BATCH_RHS) { - for (dim_t i = baseDim; i < 4; ++i) oDims[i] = fDims[i]; + for (dim_t i = baseDim; i < 4; ++i) { oDims[i] = fDims[i]; } } } @@ -81,20 +82,22 @@ Array fftconvolve(Array const& signal, Array const& filter, if (kind == AF_BATCH_RHS) { fft_inplace(filter_packed); - if (expand) + if (expand) { kernel::reorderOutputHelper( out, filter_packed, signal, filter); - else + } else { kernel::reorderOutputHelper( out, filter_packed, signal, filter); + } } else { fft_inplace(signal_packed); - if (expand) + if (expand) { kernel::reorderOutputHelper( out, signal_packed, signal, filter); - else + } else { kernel::reorderOutputHelper( out, signal_packed, signal, filter); + } } return out; diff --git a/src/backend/cuda/hist_graphics.cpp b/src/backend/cuda/hist_graphics.cpp index 88feeed330..d415a12aad 100644 --- a/src/backend/cuda/hist_graphics.cpp +++ b/src/backend/cuda/hist_graphics.cpp @@ -43,7 +43,8 @@ void copy_histogram(const Array &data, fg_histogram hist) { CheckGL("Begin CUDA fallback-resource copy"); glBindBuffer(GL_ARRAY_BUFFER, buffer); - GLubyte *ptr = (GLubyte *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + auto *ptr = + static_cast(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); if (ptr) { CUDA_CHECK(cudaMemcpyAsync(ptr, data.get(), bytes, cudaMemcpyDeviceToHost, stream)); diff --git a/src/backend/cuda/histogram.cpp b/src/backend/cuda/histogram.cpp index 8e2b879d7a..5b3359e49a 100644 --- a/src/backend/cuda/histogram.cpp +++ b/src/backend/cuda/histogram.cpp @@ -22,7 +22,7 @@ namespace cuda { template Array histogram(const Array &in, const unsigned &nbins, const double &minval, const double &maxval) { - const dim4 dims = in.dims(); + const dim4 &dims = in.dims(); dim4 outDims = dim4(nbins, 1, dims[2], dims[3]); Array out = createValueArray(outDims, outType(0)); diff --git a/src/backend/cuda/iir.cpp b/src/backend/cuda/iir.cpp index d03653cb71..9951f4e2da 100644 --- a/src/backend/cuda/iir.cpp +++ b/src/backend/cuda/iir.cpp @@ -34,7 +34,7 @@ Array iir(const Array &b, const Array &a, const Array &x) { int num_a = a.dims()[0]; - if (num_a == 1) return c; + if (num_a == 1) { return c; } dim4 ydims = c.dims(); Array y = createEmptyArray(ydims); diff --git a/src/backend/cuda/image.cpp b/src/backend/cuda/image.cpp index 996606888c..d247322201 100644 --- a/src/backend/cuda/image.cpp +++ b/src/backend/cuda/image.cpp @@ -47,8 +47,8 @@ void copy_image(const Array &in, fg_image image) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, buffer); glBufferData(GL_PIXEL_UNPACK_BUFFER, data_size, 0, GL_STREAM_DRAW); - GLubyte *ptr = - (GLubyte *)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY); + auto *ptr = static_cast( + glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY)); if (ptr) { CUDA_CHECK(cudaMemcpyAsync(ptr, in.get(), data_size, cudaMemcpyDeviceToHost, stream)); diff --git a/src/backend/cuda/index.cpp b/src/backend/cuda/index.cpp index 3d4b0c1b8d..0974e71dbb 100644 --- a/src/backend/cuda/index.cpp +++ b/src/backend/cuda/index.cpp @@ -33,11 +33,11 @@ Array index(const Array& in, const af_index_t idxrs[]) { } // retrieve dimensions, strides and offsets - dim4 iDims = in.dims(); - dim4 dDims = in.getDataDims(); - dim4 oDims = toDims(seqs, iDims); - dim4 iOffs = toOffset(seqs, dDims); - dim4 iStrds = in.strides(); + const dim4& iDims = in.dims(); + dim4 dDims = in.getDataDims(); + dim4 oDims = toDims(seqs, iDims); + dim4 iOffs = toOffset(seqs, dDims); + dim4 iStrds = in.strides(); for (dim_t i = 0; i < 4; ++i) { p.isSeq[i] = idxrs[i].isSeq; diff --git a/src/backend/cuda/jit.cpp b/src/backend/cuda/jit.cpp index 54a98e3c2e..16542cf09e 100644 --- a/src/backend/cuda/jit.cpp +++ b/src/backend/cuda/jit.cpp @@ -48,16 +48,17 @@ static string getFuncName(const vector &output_nodes, stringstream funcName; stringstream hashName; - if (is_linear) + if (is_linear) { funcName << "L_"; // Kernel Linear - else + } else { funcName << "G_"; // Kernel General + } for (const auto &node : output_nodes) { funcName << node->getNameStr() << "_"; } - for (int i = 0; i < (int)full_nodes.size(); i++) { + for (int i = 0; i < static_cast(full_nodes.size()); i++) { full_nodes[i]->genKerName(funcName, full_ids[i]); } @@ -68,7 +69,7 @@ static string getFuncName(const vector &output_nodes, return hashName.str(); } -static string getKernelString(const string funcName, +static string getKernelString(const string &funcName, const vector &full_nodes, const vector &full_ids, const vector &output_ids, bool is_linear) { @@ -149,7 +150,7 @@ struct Param { stringstream opsStream; stringstream outrefstream; - for (int i = 0; i < (int)full_nodes.size(); i++) { + for (int i = 0; i < static_cast(full_nodes.size()); i++) { const auto &node = full_nodes[i]; const auto &ids_curr = full_ids[i]; // Generate input parameters, only needs current id @@ -163,8 +164,7 @@ struct Param { outrefstream << "const Param<" << full_nodes[output_ids[0]]->getTypeStr() << "> &outref = out" << output_ids[0] << ";\n"; - for (int i = 0; i < (int)output_ids.size(); i++) { - int id = output_ids[i]; + for (int id : output_ids) { // Generate output parameters outParamStream << "Param<" << full_nodes[id]->getTypeStr() << "> out" << id << ", \n"; @@ -206,7 +206,7 @@ static CUfunction getKernel(const vector &output_nodes, const vector &full_nodes, const vector &full_ids, const bool is_linear) { - typedef map kc_t; + using kc_t = map; thread_local kc_t kernelCaches[DeviceManager::MAX_DEVICES]; @@ -214,7 +214,7 @@ static CUfunction getKernel(const vector &output_nodes, getFuncName(output_nodes, full_nodes, full_ids, is_linear); int device = getActiveDeviceId(); - kc_t::iterator idx = kernelCaches[device].find(funcName); + auto idx = kernelCaches[device].find(funcName); Kernel entry{nullptr, nullptr}; if (idx == kernelCaches[device].end()) { @@ -231,11 +231,11 @@ static CUfunction getKernel(const vector &output_nodes, } template -void evalNodes(vector> &outputs, vector output_nodes) { - int num_outputs = (int)outputs.size(); - int device = getActiveDeviceId(); +void evalNodes(vector> &outputs, const vector &output_nodes) { + size_t num_outputs = outputs.size(); + int device = getActiveDeviceId(); - if (num_outputs == 0) return; + if (num_outputs == 0) { return; } // Use thread local to reuse the memory every time you are here. thread_local Node_map_t nodes; @@ -244,7 +244,7 @@ void evalNodes(vector> &outputs, vector output_nodes) { thread_local vector output_ids; // Reserve some space to improve performance at smaller sizes - if (nodes.size() == 0) { + if (nodes.empty()) { nodes.reserve(1024); output_ids.reserve(output_nodes.size()); full_nodes.reserve(1024); @@ -274,10 +274,11 @@ void evalNodes(vector> &outputs, vector output_nodes) { int num_odims = 4; while (num_odims >= 1) { - if (outputs[0].dims[num_odims - 1] == 1) + if (outputs[0].dims[num_odims - 1] == 1) { num_odims--; - else + } else { break; + } } if (is_linear) { @@ -317,14 +318,14 @@ void evalNodes(vector> &outputs, vector output_nodes) { }); } - for (int i = 0; i < num_outputs; i++) { - args.push_back((void *)&outputs[i]); + for (size_t i = 0; i < num_outputs; i++) { + args.push_back(static_cast(&outputs[i])); } - args.push_back((void *)&blocks_x_); - args.push_back((void *)&blocks_y_); - args.push_back((void *)&blocks_x_total); - args.push_back((void *)&num_odims); + args.push_back(static_cast(&blocks_x_)); + args.push_back(static_cast(&blocks_y_)); + args.push_back(static_cast(&blocks_x_total)); + args.push_back(static_cast(&num_odims)); CU_CHECK(cuLaunchKernel(ker, blocks_x, blocks_y, blocks_z, threads_x, threads_y, 1, 0, getActiveStream(), args.data(), @@ -345,7 +346,6 @@ void evalNodes(Param out, Node *node) { outputs.push_back(out); output_nodes.push_back(node); evalNodes(outputs, output_nodes); - return; } template void evalNodes(Param out, Node *node); @@ -362,21 +362,30 @@ template void evalNodes(Param out, Node *node); template void evalNodes(Param out, Node *node); template void evalNodes(Param out, Node *node); -template void evalNodes(vector> &out, vector node); +template void evalNodes(vector> &out, + const vector &node); template void evalNodes(vector> &out, - vector node); + const vector &node); template void evalNodes(vector> &out, - vector node); + const vector &node); template void evalNodes(vector> &out, - vector node); -template void evalNodes(vector> &out, vector node); -template void evalNodes(vector> &out, vector node); -template void evalNodes(vector> &out, vector node); -template void evalNodes(vector> &out, vector node); -template void evalNodes(vector> &out, vector node); -template void evalNodes(vector> &out, vector node); -template void evalNodes(vector> &out, vector node); + const vector &node); +template void evalNodes(vector> &out, + const vector &node); +template void evalNodes(vector> &out, + const vector &node); +template void evalNodes(vector> &out, + const vector &node); +template void evalNodes(vector> &out, + const vector &node); +template void evalNodes(vector> &out, + const vector &node); +template void evalNodes(vector> &out, + const vector &node); +template void evalNodes(vector> &out, + const vector &node); template void evalNodes(vector> &out, - vector node); -template void evalNodes(vector> &out, vector node); + const vector &node); +template void evalNodes(vector> &out, + const vector &node); } // namespace cuda diff --git a/src/backend/cuda/join.cpp b/src/backend/cuda/join.cpp index 1cf0f51423..6a94c8b644 100644 --- a/src/backend/cuda/join.cpp +++ b/src/backend/cuda/join.cpp @@ -20,7 +20,7 @@ using common::half; namespace cuda { -af::dim4 calcOffset(const af::dim4 dims, const int dim) { +af::dim4 calcOffset(const af::dim4 &dims, const int dim) { af::dim4 offset; offset[0] = (dim == 0) * dims[0]; offset[1] = (dim == 1) * dims[1]; @@ -77,7 +77,7 @@ Array join(const int dim, const std::vector> &inputs) { std::vector idims(n_arrays); dim_t dim_size = 0; - for (int i = 0; i < (int)idims.size(); i++) { + for (int i = 0; i < static_cast(idims.size()); i++) { idims[i] = inputs[i].dims(); dim_size += idims[i][dim]; } diff --git a/src/backend/cuda/lookup.cpp b/src/backend/cuda/lookup.cpp index 0aadb8dbcb..f5e6bebc69 100644 --- a/src/backend/cuda/lookup.cpp +++ b/src/backend/cuda/lookup.cpp @@ -20,11 +20,12 @@ namespace cuda { template Array lookup(const Array &input, const Array &indices, const unsigned dim) { - const dim4 iDims = input.dims(); + const dim4 &iDims = input.dims(); dim4 oDims(1); - for (dim_t d = 0; d < 4; ++d) + for (dim_t d = 0; d < 4; ++d) { oDims[d] = (d == dim ? indices.elements() : iDims[d]); + } Array out = createEmptyArray(oDims); diff --git a/src/backend/cuda/lu.cpp b/src/backend/cuda/lu.cpp index 5740522ab2..cf3dcc11ea 100644 --- a/src/backend/cuda/lu.cpp +++ b/src/backend/cuda/lu.cpp @@ -37,14 +37,14 @@ namespace cuda { template struct getrf_func_def_t { - typedef cusolverStatus_t (*getrf_func_def)(cusolverDnHandle_t, int, int, - T *, int, T *, int *, int *); + using getrf_func_def = cusolverStatus_t (*)(cusolverDnHandle_t, int, int, + T *, int, T *, int *, int *); }; template struct getrf_buf_func_def_t { - typedef cusolverStatus_t (*getrf_buf_func_def)(cusolverDnHandle_t, int, int, - T *, int, int *); + using getrf_buf_func_def = cusolverStatus_t (*)(cusolverDnHandle_t, int, + int, T *, int, int *); }; #define LU_FUNC_DEF(FUNC) \ @@ -129,7 +129,7 @@ Array lu_inplace(Array &in, const bool convert_pivot) { in.strides()[1], workspace.get(), pivot.get(), info.get())); - if (convert_pivot) convertPivot(pivot, M); + if (convert_pivot) { convertPivot(pivot, M); } return pivot; } diff --git a/src/backend/cuda/math.hpp b/src/backend/cuda/math.hpp index 5eadc9a449..a40a927807 100644 --- a/src/backend/cuda/math.hpp +++ b/src/backend/cuda/math.hpp @@ -38,7 +38,7 @@ namespace cuda { template static inline __DH__ T abs(T val) { - return abs(val); + return ::abs(val); } static inline __DH__ int abs(int val) { return (val > 0 ? val : -val); } static inline __DH__ char abs(char val) { return (val > 0 ? val : -val); } diff --git a/src/backend/cuda/meanshift.cpp b/src/backend/cuda/meanshift.cpp index 3f22ab53dd..c2f552df2b 100644 --- a/src/backend/cuda/meanshift.cpp +++ b/src/backend/cuda/meanshift.cpp @@ -20,8 +20,8 @@ template Array meanshift(const Array &in, const float &spatialSigma, const float &chromaticSigma, const unsigned &numIterations, const bool &isColor) { - const dim4 dims = in.dims(); - Array out = createEmptyArray(dims); + const dim4 &dims = in.dims(); + Array out = createEmptyArray(dims); kernel::meanshift(out, in, spatialSigma, chromaticSigma, numIterations, isColor); return out; diff --git a/src/backend/cuda/medfilt.cpp b/src/backend/cuda/medfilt.cpp index 41386203cc..fa8435ae80 100644 --- a/src/backend/cuda/medfilt.cpp +++ b/src/backend/cuda/medfilt.cpp @@ -23,8 +23,8 @@ Array medfilt1(const Array &in, dim_t w_wid) { ARG_ASSERT(2, (w_wid <= kernel::MAX_MEDFILTER1_LEN)); ARG_ASSERT(2, (w_wid % 2 != 0)); - const dim4 dims = in.dims(); - Array out = createEmptyArray(dims); + const dim4 &dims = in.dims(); + Array out = createEmptyArray(dims); kernel::medfilt1(out, in, pad, w_wid); @@ -36,8 +36,8 @@ Array medfilt2(const Array &in, dim_t w_len, dim_t w_wid) { ARG_ASSERT(2, (w_len <= kernel::MAX_MEDFILTER2_LEN)); ARG_ASSERT(2, (w_len % 2 != 0)); - const dim4 dims = in.dims(); - Array out = createEmptyArray(dims); + const dim4 &dims = in.dims(); + Array out = createEmptyArray(dims); kernel::medfilt2(out, in, pad, w_len, w_wid); diff --git a/src/backend/cuda/memory.cpp b/src/backend/cuda/memory.cpp index 6e1fba9178..d65122aff2 100644 --- a/src/backend/cuda/memory.cpp +++ b/src/backend/cuda/memory.cpp @@ -47,7 +47,7 @@ void setMemStepSize(size_t step_bytes) { memoryManager().setMemStepSize(step_bytes); } -size_t getMemStepSize(void) { return memoryManager().getMemStepSize(); } +size_t getMemStepSize() { return memoryManager().getMemStepSize(); } void signalMemoryCleanup() { memoryManager().signalMemoryCleanup(); } @@ -76,17 +76,21 @@ void *memAllocUser(const size_t &bytes) { template void memFree(T *ptr) { - memoryManager().unlock((void *)ptr, false); + memoryManager().unlock(static_cast(ptr), false); } -void memFreeUser(void *ptr) { memoryManager().unlock((void *)ptr, true); } +void memFreeUser(void *ptr) { memoryManager().unlock(ptr, true); } -void memLock(const void *ptr) { memoryManager().userLock((void *)ptr); } +void memLock(const void *ptr) { + memoryManager().userLock(const_cast(ptr)); +} -void memUnlock(const void *ptr) { memoryManager().userUnlock((void *)ptr); } +void memUnlock(const void *ptr) { + memoryManager().userUnlock(const_cast(ptr)); +} bool isLocked(const void *ptr) { - return memoryManager().isUserLocked((void *)ptr); + return memoryManager().isUserLocked(const_cast(ptr)); } void deviceMemoryInfo(size_t *alloc_bytes, size_t *alloc_buffers, @@ -105,7 +109,7 @@ T *pinnedAlloc(const size_t &elements) { template void pinnedFree(T *ptr) { - pinnedMemoryManager().unlock((void *)ptr, false); + pinnedMemoryManager().unlock(static_cast(ptr), false); } #define INSTANTIATE(T) \ @@ -135,7 +139,7 @@ void Allocator::shutdown() { try { cuda::setDevice(n); shutdownMemoryManager(); - } catch (AfError err) { + } catch (const AfError &err) { continue; // Do not throw any errors while shutting down } } diff --git a/src/backend/cuda/moments.cpp b/src/backend/cuda/moments.cpp index f963650148..a8c1a53ab7 100644 --- a/src/backend/cuda/moments.cpp +++ b/src/backend/cuda/moments.cpp @@ -16,10 +16,10 @@ namespace cuda { -static inline int bitCount(int v) { - v = v - ((v >> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >> 2) & 0x33333333); - return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; +static inline unsigned bitCount(unsigned v) { + v = v - ((v >> 1U) & 0x55555555U); + v = (v & 0x33333333U) + ((v >> 2U) & 0x33333333U); + return (((v + (v >> 4U)) & 0xF0F0F0FU) * 0x1010101U) >> 24U; } using af::dim4; diff --git a/src/backend/cuda/nvrtc/cache.cpp b/src/backend/cuda/nvrtc/cache.cpp index e2cbdb37c6..e3b28f325e 100644 --- a/src/backend/cuda/nvrtc/cache.cpp +++ b/src/backend/cuda/nvrtc/cache.cpp @@ -53,6 +53,7 @@ using std::accumulate; using std::array; +using std::back_insert_iterator; using std::begin; using std::end; using std::extent; @@ -245,7 +246,7 @@ Kernel buildKernel(const int device, const string &nameExpr, } auto computeFlag = getComputeCapability(device); - array arch; + array arch{}; snprintf(arch.data(), arch.size(), "--gpu-architecture=compute_%d%d", computeFlag.first, computeFlag.second); vector compiler_options = { @@ -257,7 +258,10 @@ Kernel buildKernel(const int device, const string &nameExpr, #endif }; if (!isJIT) { - for (auto &s : opts) { compiler_options.push_back(&s[0]); } + transform(begin(opts), end(opts), + back_insert_iterator>(compiler_options), + [](const std::string &s) { return s.data(); }); + compiler_options.push_back("--device-as-default-execution-space"); NVRTC_CHECK(nvrtcAddNameExpression(prog, ker_name)); } @@ -335,15 +339,15 @@ kc_t &getCache(int device) { return caches[device]; } -Kernel findKernel(int device, const string nameExpr) { +Kernel findKernel(int device, const string &nameExpr) { kc_t &cache = getCache(device); - kc_t::iterator iter = cache.find(nameExpr); + auto iter = cache.find(nameExpr); return (iter == cache.end() ? Kernel{0, 0} : iter->second); } -void addKernelToCache(int device, const string nameExpr, Kernel entry) { +void addKernelToCache(int device, const string &nameExpr, Kernel entry) { getCache(device).emplace(nameExpr, entry); } @@ -469,16 +473,16 @@ string toString(af_op_t val) { } template<> -string toString(const char *str) { - return string(str); +string toString(const char *val) { + return string(val); } template<> -string toString(af_interp_type p) { +string toString(af_interp_type val) { const char *retVal = NULL; #define CASE_STMT(v) \ case v: retVal = #v; break - switch (p) { + switch (val) { CASE_STMT(AF_INTERP_NEAREST); CASE_STMT(AF_INTERP_LINEAR); CASE_STMT(AF_INTERP_BILINEAR); @@ -495,11 +499,11 @@ string toString(af_interp_type p) { } template<> -string toString(af_border_type p) { +string toString(af_border_type val) { const char *retVal = NULL; #define CASE_STMT(v) \ case v: retVal = #v; break - switch (p) { + switch (val) { CASE_STMT(AF_PAD_ZERO); CASE_STMT(AF_PAD_SYM); CASE_STMT(AF_PAD_CLAMP_TO_EDGE); @@ -510,11 +514,11 @@ string toString(af_border_type p) { } template<> -string toString(af_moment_type p) { +string toString(af_moment_type val) { const char *retVal = NULL; #define CASE_STMT(v) \ case v: retVal = #v; break - switch (p) { + switch (val) { CASE_STMT(AF_MOMENT_M00); CASE_STMT(AF_MOMENT_M01); CASE_STMT(AF_MOMENT_M10); @@ -526,11 +530,11 @@ string toString(af_moment_type p) { } template<> -string toString(af_match_type p) { +string toString(af_match_type val) { const char *retVal = NULL; #define CASE_STMT(v) \ case v: retVal = #v; break - switch (p) { + switch (val) { CASE_STMT(AF_SAD); CASE_STMT(AF_ZSAD); CASE_STMT(AF_LSAD); @@ -539,47 +543,51 @@ string toString(af_match_type p) { CASE_STMT(AF_LSSD); CASE_STMT(AF_NCC); CASE_STMT(AF_ZNCC); + CASE_STMT(AF_SHD); } #undef CASE_STMT return retVal; } template<> -string toString(af_flux_function p) { +string toString(af_flux_function val) { const char *retVal = NULL; #define CASE_STMT(v) \ case v: retVal = #v; break - switch (p) { + switch (val) { CASE_STMT(AF_FLUX_QUADRATIC); CASE_STMT(AF_FLUX_EXPONENTIAL); + CASE_STMT(AF_FLUX_DEFAULT); } #undef CASE_STMT return retVal; } template<> -string toString(AF_BATCH_KIND p) { +string toString(AF_BATCH_KIND val) { const char *retVal = NULL; #define CASE_STMT(v) \ case v: retVal = #v; break - switch (p) { + switch (val) { CASE_STMT(AF_BATCH_NONE); CASE_STMT(AF_BATCH_LHS); CASE_STMT(AF_BATCH_RHS); CASE_STMT(AF_BATCH_SAME); CASE_STMT(AF_BATCH_DIFF); + CASE_STMT(AF_BATCH_UNSUPPORTED); } #undef CASE_STMT return retVal; } Kernel getKernel(const string &nameExpr, const string &source, - const vector &targs, + const vector &templateArgs, const vector &compileOpts) { vector args; - args.reserve(targs.size()); + args.reserve(templateArgs.size()); - transform(targs.begin(), targs.end(), std::back_inserter(args), + transform(templateArgs.begin(), templateArgs.end(), + std::back_inserter(args), [](const TemplateArg &arg) -> string { return arg._tparam; }); string tInstance = nameExpr + "<" + args[0]; diff --git a/src/backend/cuda/nvrtc/cache.hpp b/src/backend/cuda/nvrtc/cache.hpp index 462161ff98..ebea991241 100644 --- a/src/backend/cuda/nvrtc/cache.hpp +++ b/src/backend/cuda/nvrtc/cache.hpp @@ -105,12 +105,12 @@ struct Kernel { // TODO(pradeep): remove this in API and merge JIT and nvrtc caches Kernel buildKernel(const int device, const std::string& nameExpr, - const std::string& jitSourceString, + const std::string& jit_ker, const std::vector& opts = {}, const bool isJIT = false); template -std::string toString(T value); +std::string toString(T val); struct TemplateArg { std::string _tparam; diff --git a/src/backend/cuda/platform.cpp b/src/backend/cuda/platform.cpp index 78e58fa8a1..f6814254b4 100644 --- a/src/backend/cuda/platform.cpp +++ b/src/backend/cuda/platform.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -37,6 +38,7 @@ #include #include #include +#include #include #include @@ -62,7 +64,7 @@ using common::memory::MemoryManagerBase; namespace cuda { -static const std::string get_system(void) { +static std::string get_system() { std::string arch = (sizeof(void *) == 4) ? "32-bit " : "64-bit "; return arch + @@ -118,7 +120,7 @@ unique_handle *nnManager(const int deviceId) { // Not throwing an AF_ERROR here because we are in a lambda that could // be executing on another thread; - if (!(*handle)) getLogger()->error("Error initalizing cuDNN"); + if (!(*handle)) { getLogger()->error("Error initalizing cuDNN"); } }); if (error) { string error_msg = fmt::format("Error initializing cuDNN({}): {}.", @@ -136,7 +138,7 @@ unique_ptr &cufftManager(const int deviceId) { thread_local unique_ptr caches[DeviceManager::MAX_DEVICES]; thread_local once_flag initFlags[DeviceManager::MAX_DEVICES]; call_once(initFlags[deviceId], - [&] { caches[deviceId].reset(new PlanCache()); }); + [&] { caches[deviceId] = std::make_unique(); }); return caches[deviceId]; } @@ -178,17 +180,30 @@ unique_handle *cusparseManager(const int deviceId) { } DeviceManager::~DeviceManager() { - // Reset unique_ptrs for all cu[BLAS | Sparse | Solver] - // handles of all devices - for (int i = 0; i < nDevices; ++i) { - setDevice(i); - delete cusolverManager(i); - delete cusparseManager(i); - cufftManager(i).reset(); - delete cublasManager(i); + try { + // Reset unique_ptrs for all cu[BLAS | Sparse | Solver] + // handles of all devices + for (int i = 0; i < nDevices; ++i) { + setDevice(i); + delete cusolverManager(i); + delete cusparseManager(i); + cufftManager(i).reset(); + delete cublasManager(i); #ifdef WITH_CUDNN - delete nnManager(i); + delete nnManager(i); #endif + } + } catch (const AfError &err) { + AF_TRACE( + "Exception thrown during destruction of DeviceManager(ignoring). " + "{}({}):{} " + "{}", + err.getFileName(), err.getLine(), err.getFunctionName(), + err.what()); + } catch (...) { + AF_TRACE( + "Unknown exception thrown during destruction of " + "DeviceManager(ignoring)"); } } @@ -226,9 +241,9 @@ string getDeviceInfo() noexcept { } string getPlatformInfo() noexcept { - string driverVersion = getDriverVersion(); - std::string cudaRuntime = getCUDARuntimeVersion(); - string platform = "Platform: CUDA Runtime " + cudaRuntime; + string driverVersion = getDriverVersion(); + string cudaRuntime = getCUDARuntimeVersion(); + string platform = "Platform: CUDA Runtime " + cudaRuntime; if (!driverVersion.empty()) { platform.append(", Driver: "); platform.append(driverVersion); @@ -244,12 +259,12 @@ bool isDoubleSupported(int device) { bool isHalfSupported(int device) { std::array half_supported = []() { - std::array out; + std::array out{}; int count = getDeviceCount(); for (int i = 0; i < count; i++) { - auto prop = getDeviceProp(i); - float compute = prop.major * 1000 + prop.minor * 10; - out[i] = compute >= 5030; + auto prop = getDeviceProp(i); + int compute = prop.major * 1000 + prop.minor * 10; + out[i] = compute >= 5030; } return out; }(); @@ -275,15 +290,16 @@ void devprop(char *d_name, char *d_platform, char *d_toolkit, char *d_compute) { // Sanitize input for (int i = 0; i < 256; i++) { if (d_name[i] == ' ') { - if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') + if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') { d_name[i] = 0; - else + } else { d_name[i] = '_'; + } } } } -string getDriverVersion() { +string getDriverVersion() noexcept { char driverVersion[1024] = {" "}; int x = nvDriverVersion(driverVersion, sizeof(driverVersion)); if (x != 1) { @@ -293,7 +309,7 @@ string getDriverVersion() { return "N/A"; #endif int driver = 0; - CUDA_CHECK(cudaDriverGetVersion(&driver)); + if (cudaDriverGetVersion(&driver)) { return "N/A"; } return to_string(driver); } else { return string(driverVersion); @@ -343,8 +359,10 @@ int getDeviceCount() { int getActiveDeviceId() { return tlocalActiveDeviceId(); } int getDeviceNativeId(int device) { - if (device < (int)DeviceManager::getInstance().cuDevices.size()) + if (device < + static_cast(DeviceManager::getInstance().cuDevices.size())) { return DeviceManager::getInstance().cuDevices[device].nativeId; + } return -1; } @@ -353,7 +371,7 @@ int getDeviceIdFromNativeId(int nativeId) { int devId = 0; for (devId = 0; devId < mngr.nDevices; ++devId) { - if (nativeId == mngr.cuDevices[devId].nativeId) break; + if (nativeId == mngr.cuDevices[devId].nativeId) { break; } } return devId; } @@ -382,8 +400,10 @@ int setDevice(int device) { } cudaDeviceProp getDeviceProp(int device) { - if (device < (int)DeviceManager::getInstance().cuDevices.size()) + if (device < + static_cast(DeviceManager::getInstance().cuDevices.size())) { return DeviceManager::getInstance().cuDevices[device].prop; + } return DeviceManager::getInstance().cuDevices[0].prop; } @@ -394,9 +414,9 @@ MemoryManagerBase &memoryManager() { std::call_once(flag, [&]() { // By default, create an instance of the default memory manager - inst.memManager.reset(new common::DefaultMemoryManager( + inst.memManager = std::make_unique( getDeviceCount(), common::MAX_BUFFERS, - AF_MEM_DEBUG || AF_CUDA_MEM_DEBUG)); + AF_MEM_DEBUG || AF_CUDA_MEM_DEBUG); // Set the memory manager's device memory manager std::unique_ptr deviceMemoryManager( new cuda::Allocator()); @@ -414,9 +434,9 @@ MemoryManagerBase &pinnedMemoryManager() { std::call_once(flag, [&]() { // By default, create an instance of the default memory manager - inst.pinnedMemManager.reset(new common::DefaultMemoryManager( + inst.pinnedMemManager = std::make_unique( getDeviceCount(), common::MAX_BUFFERS, - AF_MEM_DEBUG || AF_CUDA_MEM_DEBUG)); + AF_MEM_DEBUG || AF_CUDA_MEM_DEBUG); // Set the memory manager's device memory manager std::unique_ptr deviceMemoryManager( new cuda::AllocatorPinned()); @@ -455,7 +475,7 @@ GraphicsResourceManager &interopManager() { DeviceManager &inst = DeviceManager::getInstance(); std::call_once(initFlags[id], [&] { - inst.gfxManagers[id].reset(new GraphicsResourceManager()); + inst.gfxManagers[id] = std::make_unique(); }); return *(inst.gfxManagers[id].get()); @@ -470,16 +490,16 @@ BlasHandle blasHandle() { return *cublasManager(cuda::getActiveDeviceId()); } #ifdef WITH_CUDNN cudnnHandle_t nnHandle() { // Keep the getCudnnPlugin call here because module loading can throw an - // exception the first time its called. We want to avoid that because the - // unique handle object is marked noexcept and could terminate. if the - // module is not loaded correctly + // exception the first time its called. We want to avoid that because + // the unique handle object is marked noexcept and could terminate. if + // the module is not loaded correctly static cudnnModule keep_me_to_avoid_exceptions_exceptions = getCudnnPlugin(); static unique_handle *handle = nnManager(cuda::getActiveDeviceId()); - if (*handle) + if (*handle) { return *handle; - else { + } else { AF_ERROR("Error Initializing cuDNN\n", AF_ERR_RUNTIME); } } @@ -549,6 +569,6 @@ template<> __half *array::device<__half>() const { void *ptr = NULL; af_get_device_ptr(&ptr, get()); - return (__half *)ptr; + return static_cast<__half *>(ptr); } } // namespace af diff --git a/src/backend/cuda/platform.hpp b/src/backend/cuda/platform.hpp index ce973bfd35..bfc67560f5 100644 --- a/src/backend/cuda/platform.hpp +++ b/src/backend/cuda/platform.hpp @@ -62,7 +62,7 @@ std::string getDeviceInfo(int device) noexcept; std::string getPlatformInfo() noexcept; -std::string getDriverVersion(); +std::string getDriverVersion() noexcept; // Returns the cuda runtime version as a string for the current build. If no // runtime is found or an error occured, the string "N/A" is returned diff --git a/src/backend/cuda/plot.cpp b/src/backend/cuda/plot.cpp index 9d4128f98d..c454b0dff1 100644 --- a/src/backend/cuda/plot.cpp +++ b/src/backend/cuda/plot.cpp @@ -45,7 +45,8 @@ void copy_plot(const Array &P, fg_plot plot) { CheckGL("Begin CUDA fallback-resource copy"); glBindBuffer(GL_ARRAY_BUFFER, buffer); - GLubyte *ptr = (GLubyte *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + auto *ptr = + static_cast(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); if (ptr) { CUDA_CHECK(cudaMemcpyAsync(ptr, P.get(), bytes, cudaMemcpyDeviceToHost, stream)); diff --git a/src/backend/cuda/qr.cpp b/src/backend/cuda/qr.cpp index f9a5ea8e1d..4c02e60fd0 100644 --- a/src/backend/cuda/qr.cpp +++ b/src/backend/cuda/qr.cpp @@ -51,23 +51,23 @@ namespace cuda { template struct geqrf_func_def_t { - typedef cusolverStatus_t (*geqrf_func_def)(cusolverDnHandle_t, int, int, - T *, int, T *, T *, int, int *); + using geqrf_func_def = cusolverStatus_t (*)(cusolverDnHandle_t, int, int, + T *, int, T *, T *, int, int *); }; template struct geqrf_buf_func_def_t { - typedef cusolverStatus_t (*geqrf_buf_func_def)(cusolverDnHandle_t, int, int, - T *, int, int *); + using geqrf_buf_func_def = cusolverStatus_t (*)(cusolverDnHandle_t, int, + int, T *, int, int *); }; template struct mqr_func_def_t { - typedef cusolverStatus_t (*mqr_func_def)(cusolverDnHandle_t, - cublasSideMode_t, - cublasOperation_t, int, int, int, - const T *, int, const T *, T *, - int, T *, int, int *); + using mqr_func_def = cusolverStatus_t (*)(cusolverDnHandle_t, + cublasSideMode_t, + cublasOperation_t, int, int, int, + const T *, int, const T *, T *, + int, T *, int, int *); }; #define QR_FUNC_DEF(FUNC) \ diff --git a/src/backend/cuda/random_engine.cu b/src/backend/cuda/random_engine.cu index 46714825d3..d03eb51e91 100644 --- a/src/backend/cuda/random_engine.cu +++ b/src/backend/cuda/random_engine.cu @@ -17,7 +17,7 @@ using common::half; namespace cuda { void initMersenneState(Array &state, const uintl seed, - const Array tbl) { + const Array &tbl) { kernel::initMersenneState(state.get(), tbl.get(), seed); } diff --git a/src/backend/cuda/random_engine.hpp b/src/backend/cuda/random_engine.hpp index a5047d3429..ca7bd1a233 100644 --- a/src/backend/cuda/random_engine.hpp +++ b/src/backend/cuda/random_engine.hpp @@ -14,10 +14,8 @@ #include namespace cuda { -Array initMersenneState(const uintl seed, Array tbl); - void initMersenneState(Array &state, const uintl seed, - const Array tbl); + const Array &tbl); template Array uniformDistribution(const af::dim4 &dims, diff --git a/src/backend/cuda/range.cpp b/src/backend/cuda/range.cpp index 8380241e2c..54cc76268e 100644 --- a/src/backend/cuda/range.cpp +++ b/src/backend/cuda/range.cpp @@ -28,8 +28,9 @@ Array range(const dim4& dim, const int seq_dim) { _seq_dim = 0; // column wise sequence } - if (_seq_dim < 0 || _seq_dim > 3) + if (_seq_dim < 0 || _seq_dim > 3) { AF_ERROR("Invalid rep selection", AF_ERR_ARG); + } Array out = createEmptyArray(dim); kernel::range(out, _seq_dim); diff --git a/src/backend/cuda/reorder.cpp b/src/backend/cuda/reorder.cpp index 99485516fe..fcc0e6a830 100644 --- a/src/backend/cuda/reorder.cpp +++ b/src/backend/cuda/reorder.cpp @@ -22,9 +22,9 @@ namespace cuda { template Array reorder(const Array &in, const af::dim4 &rdims) { - const af::dim4 iDims = in.dims(); + const af::dim4 &iDims = in.dims(); af::dim4 oDims(0); - for (int i = 0; i < 4; i++) oDims[i] = iDims[rdims[i]]; + for (int i = 0; i < 4; i++) { oDims[i] = iDims[rdims[i]]; } Array out = createEmptyArray(oDims); diff --git a/src/backend/cuda/resize.cpp b/src/backend/cuda/resize.cpp index b7e882d31c..25678976e3 100644 --- a/src/backend/cuda/resize.cpp +++ b/src/backend/cuda/resize.cpp @@ -17,7 +17,7 @@ namespace cuda { template Array resize(const Array &in, const dim_t odim0, const dim_t odim1, const af_interp_type method) { - const af::dim4 iDims = in.dims(); + const af::dim4 &iDims = in.dims(); af::dim4 oDims(odim0, odim1, iDims[2], iDims[3]); Array out = createEmptyArray(oDims); diff --git a/src/backend/cuda/select.cpp b/src/backend/cuda/select.cpp index e23917ce3b..7f0907d5d8 100644 --- a/src/backend/cuda/select.cpp +++ b/src/backend/cuda/select.cpp @@ -46,9 +46,9 @@ Array createSelectNode(const Array &cond, const Array &a, auto b_node = b.getNode(); int height = max(a_node->getHeight(), b_node->getHeight()); height = max(height, cond_node->getHeight()) + 1; - auto node = make_shared( - NaryNode(getFullName(), shortname(true), "__select", 3, - {{cond_node, a_node, b_node}}, (int)af_select_t, height)); + auto node = make_shared(NaryNode( + getFullName(), shortname(true), "__select", 3, + {{cond_node, a_node, b_node}}, static_cast(af_select_t), height)); if (detail::passesJitHeuristics(node.get()) == kJITHeuristics::Pass) { return createNodeArray(odims, node); @@ -78,7 +78,7 @@ Array createSelectNode(const Array &cond, const Array &a, auto node = make_shared(NaryNode( getFullName(), shortname(true), (flip ? "__not_select" : "__select"), 3, {{cond_node, a_node, b_node}}, - (int)(flip ? af_not_select_t : af_select_t), height)); + static_cast(flip ? af_not_select_t : af_select_t), height)); if (detail::passesJitHeuristics(node.get()) == kJITHeuristics::Pass) { return createNodeArray(odims, node); diff --git a/src/backend/cuda/shift.cpp b/src/backend/cuda/shift.cpp index c5ab83248e..e66fe381fc 100644 --- a/src/backend/cuda/shift.cpp +++ b/src/backend/cuda/shift.cpp @@ -39,15 +39,16 @@ Array shift(const Array &in, const int sdims[4]) { string name_str("Sh"); name_str += shortname(true); - const dim4 iDims = in.dims(); - dim4 oDims = iDims; + const dim4 &iDims = in.dims(); + dim4 oDims = iDims; - array shifts; + array shifts{}; for (int i = 0; i < 4; i++) { // sdims_[i] will always be positive and always [0, oDims[i]]. // Negative shifts are converted to position by going the other way // round - shifts[i] = -(sdims[i] % (int)oDims[i]) + oDims[i] * (sdims[i] > 0); + shifts[i] = -(sdims[i] % static_cast(oDims[i])) + + oDims[i] * (sdims[i] > 0); assert(shifts[i] >= 0 && shifts[i] <= oDims[i]); } diff --git a/src/backend/cuda/surface.cpp b/src/backend/cuda/surface.cpp index 6644d22eb5..ca38716f39 100644 --- a/src/backend/cuda/surface.cpp +++ b/src/backend/cuda/surface.cpp @@ -45,7 +45,8 @@ void copy_surface(const Array &P, fg_surface surface) { CheckGL("Begin CUDA fallback-resource copy"); glBindBuffer(GL_ARRAY_BUFFER, buffer); - GLubyte *ptr = (GLubyte *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + auto *ptr = + static_cast(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); if (ptr) { CUDA_CHECK(cudaMemcpyAsync(ptr, P.get(), bytes, cudaMemcpyDeviceToHost, stream)); diff --git a/src/backend/cuda/susan.cpp b/src/backend/cuda/susan.cpp index e905daf854..1f2a367e88 100644 --- a/src/backend/cuda/susan.cpp +++ b/src/backend/cuda/susan.cpp @@ -49,12 +49,12 @@ unsigned susan(Array &x_out, Array &y_out, Array &resp_out, resp_out = createEmptyArray(dim4()); return 0; } else { - x_out = createDeviceDataArray(dim4(corners_out), - (void *)x_corners.get()); - y_out = createDeviceDataArray(dim4(corners_out), - (void *)y_corners.get()); - resp_out = createDeviceDataArray(dim4(corners_out), - (void *)resp_corners.get()); + x_out = createDeviceDataArray( + dim4(corners_out), static_cast(x_corners.get())); + y_out = createDeviceDataArray( + dim4(corners_out), static_cast(y_corners.get())); + resp_out = createDeviceDataArray( + dim4(corners_out), static_cast(resp_corners.get())); x_corners.release(); y_corners.release(); resp_corners.release(); diff --git a/src/backend/cuda/susan.hpp b/src/backend/cuda/susan.hpp index 1d50a846be..bc27d5bc7f 100644 --- a/src/backend/cuda/susan.hpp +++ b/src/backend/cuda/susan.hpp @@ -15,10 +15,8 @@ using af::features; namespace cuda { template -unsigned susan(Array &x_out, Array &y_out, - Array &score_out, const Array &in, - const unsigned radius, const float diff_thr, +unsigned susan(Array &x_out, Array &y_out, Array &resp_out, + const Array &in, const unsigned radius, const float diff_thr, const float geom_thr, const float feature_ratio, const unsigned edge); - } diff --git a/src/backend/cuda/svd.cpp b/src/backend/cuda/svd.cpp index 012c04ece6..7c51fefc51 100644 --- a/src/backend/cuda/svd.cpp +++ b/src/backend/cuda/svd.cpp @@ -21,16 +21,17 @@ namespace cuda { template -cusolverStatus_t gesvd_buf_func(cusolverDnHandle_t handle, int m, int n, - int *Lwork) { +cusolverStatus_t gesvd_buf_func(cusolverDnHandle_t /*handle*/, int /*m*/, + int /*n*/, int * /*Lwork*/) { return CUSOLVER_STATUS_ARCH_MISMATCH; } template -cusolverStatus_t gesvd_func(cusolverDnHandle_t handle, char jobu, char jobvt, - int m, int n, T *A, int lda, Tr *S, T *U, int ldu, - T *VT, int ldvt, T *Work, int Lwork, Tr *rwork, - int *devInfo) { +cusolverStatus_t gesvd_func(cusolverDnHandle_t /*handle*/, char /*jobu*/, + char /*jobvt*/, int /*m*/, int /*n*/, T * /*A*/, + int /*lda*/, Tr * /*S*/, T * /*U*/, int /*ldu*/, + T * /*VT*/, int /*ldvt*/, T * /*Work*/, + int /*Lwork*/, Tr * /*rwork*/, int * /*devInfo*/) { return CUSOLVER_STATUS_ARCH_MISMATCH; } diff --git a/src/backend/cuda/tile.cpp b/src/backend/cuda/tile.cpp index 9457688e73..4b2839232e 100644 --- a/src/backend/cuda/tile.cpp +++ b/src/backend/cuda/tile.cpp @@ -21,8 +21,8 @@ using common::half; namespace cuda { template Array tile(const Array &in, const af::dim4 &tileDims) { - const af::dim4 iDims = in.dims(); - af::dim4 oDims = iDims; + const af::dim4 &iDims = in.dims(); + af::dim4 oDims = iDims; oDims *= tileDims; if (iDims.elements() == 0 || oDims.elements() == 0) { diff --git a/src/backend/cuda/transform.cpp b/src/backend/cuda/transform.cpp index 6ec97ebc8c..a143d74963 100644 --- a/src/backend/cuda/transform.cpp +++ b/src/backend/cuda/transform.cpp @@ -16,15 +16,15 @@ namespace cuda { template void transform(Array &out, const Array &in, const Array &tf, - const af::dim4 &odims, const af::interpType method, - const bool inverse, const bool perspective) { + const af::interpType method, const bool inverse, + const bool perspective) { kernel::transform(out, in, tf, inverse, perspective, method, interpOrder(method)); } #define INSTANTIATE(T) \ template void transform(Array &out, const Array &in, \ - const Array &tf, const af::dim4 &odims, \ + const Array &tf, \ const af_interp_type method, const bool inverse, \ const bool perspective); diff --git a/src/backend/cuda/transform.hpp b/src/backend/cuda/transform.hpp index f0fd721226..ee3596d3ef 100644 --- a/src/backend/cuda/transform.hpp +++ b/src/backend/cuda/transform.hpp @@ -12,6 +12,6 @@ namespace cuda { template void transform(Array &out, const Array &in, const Array &tf, - const af::dim4 &odims, const af_interp_type method, - const bool inverse, const bool perspective); + const af_interp_type method, const bool inverse, + const bool perspective); } diff --git a/src/backend/cuda/transpose.cpp b/src/backend/cuda/transpose.cpp index b891722f28..25f882b667 100644 --- a/src/backend/cuda/transpose.cpp +++ b/src/backend/cuda/transpose.cpp @@ -20,7 +20,7 @@ namespace cuda { template Array transpose(const Array &in, const bool conjugate) { - const dim4 inDims = in.dims(); + const dim4 &inDims = in.dims(); dim4 outDims = dim4(inDims[1], inDims[0], inDims[2], inDims[3]); diff --git a/src/backend/cuda/types.hpp b/src/backend/cuda/types.hpp index d18d747db5..97c9d91a16 100644 --- a/src/backend/cuda/types.hpp +++ b/src/backend/cuda/types.hpp @@ -139,7 +139,7 @@ const char *getFullName() { namespace common { template -class kernel_type; +struct kernel_type; } namespace common { diff --git a/src/backend/cuda/vector_field.cpp b/src/backend/cuda/vector_field.cpp index 60506c4597..eba52ad532 100644 --- a/src/backend/cuda/vector_field.cpp +++ b/src/backend/cuda/vector_field.cpp @@ -65,7 +65,8 @@ void copy_vector_field(const Array &points, const Array &directions, // Points glBindBuffer(GL_ARRAY_BUFFER, buff1); - GLubyte *ptr = (GLubyte *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + auto *ptr = + static_cast(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); if (ptr) { CUDA_CHECK(cudaMemcpyAsync(ptr, points.get(), size1, cudaMemcpyDeviceToHost, stream)); @@ -76,7 +77,8 @@ void copy_vector_field(const Array &points, const Array &directions, // Directions glBindBuffer(GL_ARRAY_BUFFER, buff2); - ptr = (GLubyte *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + ptr = + static_cast(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); if (ptr) { CUDA_CHECK(cudaMemcpyAsync(ptr, directions.get(), size2, cudaMemcpyDeviceToHost, stream)); diff --git a/src/backend/cuda/vector_field.hpp b/src/backend/cuda/vector_field.hpp index f42a241b86..abb375bcbc 100644 --- a/src/backend/cuda/vector_field.hpp +++ b/src/backend/cuda/vector_field.hpp @@ -14,6 +14,5 @@ namespace cuda { template void copy_vector_field(const Array &points, const Array &directions, - fg_vector_field vector_field); - + fg_vector_field vfield); } diff --git a/src/backend/cuda/wrap.cpp b/src/backend/cuda/wrap.cpp index 9c4dcbaffc..76834e6a10 100644 --- a/src/backend/cuda/wrap.cpp +++ b/src/backend/cuda/wrap.cpp @@ -23,17 +23,17 @@ using common::half; namespace cuda { template -void wrap(Array &out, const Array &in, const dim_t ox, const dim_t oy, - const dim_t wx, const dim_t wy, const dim_t sx, const dim_t sy, - const dim_t px, const dim_t py, const bool is_column) { +void wrap(Array &out, const Array &in, const dim_t wx, const dim_t wy, + const dim_t sx, const dim_t sy, const dim_t px, const dim_t py, + const bool is_column) { kernel::wrap(out, in, wx, wy, sx, sy, px, py, is_column); } #define INSTANTIATE(T) \ - template void wrap(Array & out, const Array &in, const dim_t ox, \ - const dim_t oy, const dim_t wx, const dim_t wy, \ - const dim_t sx, const dim_t sy, const dim_t px, \ - const dim_t py, const bool is_column); + template void wrap(Array & out, const Array &in, const dim_t wx, \ + const dim_t wy, const dim_t sx, const dim_t sy, \ + const dim_t px, const dim_t py, \ + const bool is_column); INSTANTIATE(float) INSTANTIATE(double) diff --git a/src/backend/cuda/wrap.hpp b/src/backend/cuda/wrap.hpp index d0cc38bbfe..d324975379 100644 --- a/src/backend/cuda/wrap.hpp +++ b/src/backend/cuda/wrap.hpp @@ -11,9 +11,9 @@ namespace cuda { template -void wrap(Array &out, const Array &in, const dim_t ox, const dim_t oy, - const dim_t wx, const dim_t wy, const dim_t sx, const dim_t sy, - const dim_t px, const dim_t py, const bool is_column); +void wrap(Array &out, const Array &in, const dim_t wx, const dim_t wy, + const dim_t sx, const dim_t sy, const dim_t px, const dim_t py, + const bool is_column); template Array wrap_dilated(const Array &in, const dim_t ox, const dim_t oy, diff --git a/src/backend/opencl/Array.cpp b/src/backend/opencl/Array.cpp index 7141f076a9..a01ac3071a 100644 --- a/src/backend/opencl/Array.cpp +++ b/src/backend/opencl/Array.cpp @@ -24,8 +24,10 @@ #include #include +#include using af::dim4; +using af::dtype_traits; using cl::Buffer; @@ -49,9 +51,7 @@ Node_ptr bufferNodePtr() { namespace { template -void verifyTypeSupport() { - return; -} +void verifyTypeSupport() {} template<> void verifyTypeSupport() { @@ -76,9 +76,9 @@ void verifyTypeSupport() { } // namespace template -Array::Array(dim4 dims) +Array::Array(const dim4 &dims) : info(getActiveDeviceId(), dims, 0, calcStrides(dims), - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data(memAlloc(info.elements()).release(), bufferFree) , data_dims(dims) , node(bufferNodePtr()) @@ -86,19 +86,18 @@ Array::Array(dim4 dims) , owner(true) {} template -Array::Array(dim4 dims, Node_ptr n) +Array::Array(const dim4 &dims, Node_ptr n) : info(getActiveDeviceId(), dims, 0, calcStrides(dims), - (af_dtype)dtype_traits::af_type) - , data() + static_cast(dtype_traits::af_type)) , data_dims(dims) - , node(n) + , node(std::move(std::move(n))) , ready(false) , owner(true) {} template -Array::Array(dim4 dims, const T *const in_data) +Array::Array(const dim4 &dims, const T *const in_data) : info(getActiveDeviceId(), dims, 0, calcStrides(dims), - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data(memAlloc(info.elements()).release(), bufferFree) , data_dims(dims) , node(bufferNodePtr()) @@ -114,9 +113,9 @@ Array::Array(dim4 dims, const T *const in_data) } template -Array::Array(dim4 dims, cl_mem mem, size_t src_offset, bool copy) +Array::Array(const dim4 &dims, cl_mem mem, size_t src_offset, bool copy) : info(getActiveDeviceId(), dims, 0, calcStrides(dims), - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data(copy ? memAlloc(info.elements()).release() : new Buffer(mem), bufferFree) , data_dims(dims) @@ -125,7 +124,7 @@ Array::Array(dim4 dims, cl_mem mem, size_t src_offset, bool copy) , owner(true) { if (copy) { clRetainMemObject(mem); - Buffer src_buf = Buffer((cl_mem)(mem)); + Buffer src_buf = Buffer(mem); getQueue().enqueueCopyBuffer(src_buf, *data.get(), src_offset, 0, sizeof(T) * info.elements()); } @@ -135,7 +134,7 @@ template Array::Array(const Array &parent, const dim4 &dims, const dim_t &offset_, const dim4 &stride) : info(parent.getDevId(), dims, offset_, stride, - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data(parent.getData()) , data_dims(parent.getDataDims()) , node(bufferNodePtr()) @@ -150,9 +149,9 @@ Array::Array(Param &tmp, bool owner_) 0, dim4(tmp.info.strides[0], tmp.info.strides[1], tmp.info.strides[2], tmp.info.strides[3]), - (af_dtype)dtype_traits::af_type) + static_cast(dtype_traits::af_type)) , data( - tmp.data, owner_ ? bufferFree : [](Buffer *) {}) + tmp.data, owner_ ? bufferFree : [](Buffer * /*unused*/) {}) , data_dims(dim4(tmp.info.dims[0], tmp.info.dims[1], tmp.info.dims[2], tmp.info.dims[3])) , node(bufferNodePtr()) @@ -160,13 +159,15 @@ Array::Array(Param &tmp, bool owner_) , owner(owner_) {} template -Array::Array(dim4 dims, dim4 strides, dim_t offset_, const T *const in_data, - bool is_device) +Array::Array(const dim4 &dims, const dim4 &strides, dim_t offset_, + const T *const in_data, bool is_device) : info(getActiveDeviceId(), dims, offset_, strides, - (af_dtype)dtype_traits::af_type) - , data(is_device ? (new Buffer((cl_mem)in_data)) - : (memAlloc(info.elements()).release()), - bufferFree) + static_cast(dtype_traits::af_type)) + , data( + is_device + ? (new Buffer(reinterpret_cast(const_cast(in_data)))) + : (memAlloc(info.elements()).release()), + bufferFree) , data_dims(dims) , node(bufferNodePtr()) , ready(true) @@ -179,7 +180,7 @@ Array::Array(dim4 dims, dim4 strides, dim_t offset_, const T *const in_data, template void Array::eval() { - if (isReady()) return; + if (isReady()) { return; } this->setId(getActiveDeviceId()); data = Buffer_ptr(memAlloc(info.elements()).release(), bufferFree); @@ -198,7 +199,7 @@ void Array::eval() { template void Array::eval() const { - if (isReady()) return; + if (isReady()) { return; } const_cast *>(this)->eval(); } @@ -255,15 +256,12 @@ void evalMultiple(vector *> arrays) { for (Array *array : output_arrays) { array->node = bufferNodePtr(); } } -template -Array::~Array() {} - template Node_ptr Array::getNode() { if (node->isBuffer()) { - KParam kinfo = *this; - BufferNode *bufNode = reinterpret_cast(node.get()); - unsigned bytes = this->getDataDims().elements() * sizeof(T); + KParam kinfo = *this; + auto *bufNode = reinterpret_cast(node.get()); + unsigned bytes = this->getDataDims().elements() * sizeof(T); bufNode->setData(kinfo, data, bytes, isLinear()); } return node; @@ -292,7 +290,7 @@ Node_ptr Array::getNode() const { template kJITHeuristics passesJitHeuristics(Node *root_node) { if (!evalFlag()) { return kJITHeuristics::Pass; } - if (root_node->getHeight() >= (int)getMaxJitSize()) { + if (root_node->getHeight() >= static_cast(getMaxJitSize())) { return kJITHeuristics::TreeHeight; } @@ -383,7 +381,7 @@ Array createSubArray(const Array &parent, const vector &index, return createSubArray(parentCopy, index, copy); } - dim4 pDims = parent.dims(); + const dim4 &pDims = parent.dims(); dim4 dims = toDims(index, pDims); dim4 strides = toStride(index, dDims); @@ -391,11 +389,11 @@ Array createSubArray(const Array &parent, const vector &index, // Find total offsets after indexing dim4 offsets = toOffset(index, pDims); dim_t offset = parent.getOffset(); - for (int i = 0; i < 4; i++) offset += offsets[i] * parent_strides[i]; + for (int i = 0; i < 4; i++) { offset += offsets[i] * parent_strides[i]; } Array out = Array(parent, dims, offset, strides); - if (!copy) return out; + if (!copy) { return out; } if (strides[0] != 1 || strides[1] < 0 || strides[2] < 0 || strides[3] < 0) { out = copyArray(out); @@ -405,29 +403,29 @@ Array createSubArray(const Array &parent, const vector &index, } template -Array createHostDataArray(const dim4 &size, const T *const data) { +Array createHostDataArray(const dim4 &dims, const T *const data) { verifyTypeSupport(); - return Array(size, data); + return Array(dims, data); } template -Array createDeviceDataArray(const dim4 &size, void *data) { +Array createDeviceDataArray(const dim4 &dims, void *data) { verifyTypeSupport(); bool copy_device = false; - return Array(size, static_cast(data), 0, copy_device); + return Array(dims, static_cast(data), 0, copy_device); } template -Array createValueArray(const dim4 &size, const T &value) { +Array createValueArray(const dim4 &dims, const T &value) { verifyTypeSupport(); - return createScalarNode(size, value); + return createScalarNode(dims, value); } template -Array createEmptyArray(const dim4 &size) { +Array createEmptyArray(const dim4 &dims) { verifyTypeSupport(); - return Array(size); + return Array(dims); } template @@ -448,8 +446,6 @@ void writeHostDataArray(Array &arr, const T *const data, getQueue().enqueueWriteBuffer(*arr.get(), CL_TRUE, arr.getOffset(), bytes, data); - - return; } template @@ -459,13 +455,12 @@ void writeDeviceDataArray(Array &arr, const void *const data, Buffer &buf = *arr.get(); - clRetainMemObject((cl_mem)(data)); - Buffer data_buf = Buffer((cl_mem)(data)); - - getQueue().enqueueCopyBuffer(data_buf, buf, 0, (size_t)arr.getOffset(), - bytes); + clRetainMemObject(reinterpret_cast(const_cast(data))); + Buffer data_buf = + Buffer(reinterpret_cast(const_cast(data))); - return; + getQueue().enqueueCopyBuffer(data_buf, buf, 0, + static_cast(arr.getOffset()), bytes); } template @@ -486,11 +481,11 @@ void Array::setDataDims(const dim4 &new_dims) { const Array &parent, const vector &index, bool copy); \ template void destroyArray(Array * A); \ template Array createNodeArray(const dim4 &dims, Node_ptr node); \ - template Array::Array(dim4 dims, dim4 strides, dim_t offset, \ - const T *const in_data, bool is_device); \ - template Array::Array(dim4 dims, cl_mem mem, size_t src_offset, \ + template Array::Array(const dim4 &dims, const dim4 &strides, \ + dim_t offset, const T *const in_data, \ + bool is_device); \ + template Array::Array(const dim4 &dims, cl_mem mem, size_t src_offset, \ bool copy); \ - template Array::~Array(); \ template Node_ptr Array::getNode() const; \ template void Array::eval(); \ template void Array::eval() const; \ diff --git a/src/backend/opencl/Array.hpp b/src/backend/opencl/Array.hpp index 81641a5923..e69e81578b 100644 --- a/src/backend/opencl/Array.hpp +++ b/src/backend/opencl/Array.hpp @@ -31,7 +31,8 @@ template void evalMultiple(std::vector *> arrays); void evalNodes(Param &out, common::Node *node); -void evalNodes(std::vector &outputs, std::vector nodes); +void evalNodes(std::vector &outputs, + const std::vector &nodes); /// Creates a new Array object on the heap and returns a reference to it. template @@ -49,8 +50,9 @@ template Array createDeviceDataArray(const af::dim4 &dims, void *data); template -Array createStridedArray(af::dim4 dims, af::dim4 strides, dim_t offset, - const T *const in_data, bool is_device) { +Array createStridedArray(const af::dim4 &dims, const af::dim4 &strides, + dim_t offset, const T *const in_data, + bool is_device) { return Array(dims, strides, offset, in_data, is_device); } @@ -126,18 +128,18 @@ class Array { bool ready; bool owner; - Array(af::dim4 dims); + Array(const af::dim4 &dims); - Array(const Array &parnt, const dim4 &dims, const dim_t &offset, + Array(const Array &parent, const dim4 &dims, const dim_t &offset, const dim4 &stride); Array(Param &tmp, bool owner); - explicit Array(af::dim4 dims, common::Node_ptr n); - explicit Array(af::dim4 dims, const T *const in_data); - explicit Array(af::dim4 dims, cl_mem mem, size_t offset, bool copy); + explicit Array(const af::dim4 &dims, common::Node_ptr n); + explicit Array(const af::dim4 &dims, const T *const in_data); + explicit Array(const af::dim4 &dims, cl_mem mem, size_t offset, bool copy); public: - Array(af::dim4 dims, af::dim4 strides, dim_t offset, const T *const in_data, - bool is_device = false); + Array(const af::dim4 &dims, const af::dim4 &strides, dim_t offset, + const T *const in_data, bool is_device = false); void resetInfo(const af::dim4 &dims) { info.resetInfo(dims); } void resetDims(const af::dim4 &dims) { info.resetDims(dims); } @@ -178,7 +180,7 @@ class Array { INFO_IS_FUNC(isSparse); #undef INFO_IS_FUNC - ~Array(); + ~Array() = default; bool isReady() const { return ready; } bool isOwner() const { return owner; } @@ -275,8 +277,9 @@ class Array { friend Array createHostDataArray(const af::dim4 &dims, const T *const data); friend Array createDeviceDataArray(const af::dim4 &dims, void *data); - friend Array createStridedArray(af::dim4 dims, af::dim4 strides, - dim_t offset, const T *const in_data, + friend Array createStridedArray(const af::dim4 &dims, + const af::dim4 &strides, dim_t offset, + const T *const in_data, bool is_device); friend Array createEmptyArray(const af::dim4 &dims); diff --git a/src/backend/opencl/Event.cpp b/src/backend/opencl/Event.cpp index 9a8dc24061..21523891d9 100644 --- a/src/backend/opencl/Event.cpp +++ b/src/backend/opencl/Event.cpp @@ -13,9 +13,13 @@ #include #include #include +#include #include +using std::make_unique; +using std::unique_ptr; + namespace opencl { /// \brief Creates a new event and marks it in the queue Event makeEvent(cl::CommandQueue& queue) { @@ -25,8 +29,7 @@ Event makeEvent(cl::CommandQueue& queue) { } af_event createEvent() { - std::unique_ptr e; - e.reset(new Event()); + auto e = make_unique(); // Ensure the default CL command queue is initialized getQueue()(); if (e->create() != CL_SUCCESS) { diff --git a/src/backend/opencl/GraphicsResourceManager.cpp b/src/backend/opencl/GraphicsResourceManager.cpp index 954e9e2b6b..e2cd64150f 100644 --- a/src/backend/opencl/GraphicsResourceManager.cpp +++ b/src/backend/opencl/GraphicsResourceManager.cpp @@ -12,12 +12,15 @@ namespace opencl { GraphicsResourceManager::ShrdResVector -GraphicsResourceManager::registerResources(std::vector resources) { +GraphicsResourceManager::registerResources( + const std::vector& resources) { ShrdResVector output; - for (auto id : resources) - output.emplace_back( - new cl::BufferGL(getContext(), CL_MEM_WRITE_ONLY, id, NULL)); + for (auto id : resources) { + output.emplace_back(new cl::BufferGL( + getContext(), CL_MEM_WRITE_ONLY, // NOLINT(hicpp-signed-bitwise) + id, NULL)); + } return output; } diff --git a/src/backend/opencl/GraphicsResourceManager.hpp b/src/backend/opencl/GraphicsResourceManager.hpp index 8924661572..618e46e2f4 100644 --- a/src/backend/opencl/GraphicsResourceManager.hpp +++ b/src/backend/opencl/GraphicsResourceManager.hpp @@ -25,7 +25,8 @@ class GraphicsResourceManager using ShrdResVector = std::vector>; GraphicsResourceManager() {} - ShrdResVector registerResources(std::vector resources); + static ShrdResVector registerResources( + const std::vector& resources); protected: GraphicsResourceManager(GraphicsResourceManager const&); diff --git a/src/backend/opencl/Param.cpp b/src/backend/opencl/Param.cpp index 6be8d546ab..34a01f4a5d 100644 --- a/src/backend/opencl/Param.cpp +++ b/src/backend/opencl/Param.cpp @@ -16,7 +16,7 @@ namespace opencl { Param::Param() : data(nullptr), info{{0, 0, 0, 0}, {0, 0, 0, 0}, 0} {} Param::Param(cl::Buffer *data_, KParam info_) : data(data_), info(info_) {} -Param makeParam(cl_mem mem, int off, int dims[4], int strides[4]) { +Param makeParam(cl_mem mem, int off, const int dims[4], const int strides[4]) { Param out; out.data = new cl::Buffer(mem); out.info.offset = off; diff --git a/src/backend/opencl/Param.hpp b/src/backend/opencl/Param.hpp index 484ef71030..392c9d07b7 100644 --- a/src/backend/opencl/Param.hpp +++ b/src/backend/opencl/Param.hpp @@ -28,5 +28,5 @@ struct Param { }; // AF_DEPRECATED("Use Array") -Param makeParam(cl_mem mem, int off, int dims[4], int strides[4]); +Param makeParam(cl_mem mem, int off, const int dims[4], const int strides[4]); } // namespace opencl diff --git a/src/backend/opencl/anisotropic_diffusion.cpp b/src/backend/opencl/anisotropic_diffusion.cpp index b5ce054750..e71a78cfc8 100644 --- a/src/backend/opencl/anisotropic_diffusion.cpp +++ b/src/backend/opencl/anisotropic_diffusion.cpp @@ -18,10 +18,11 @@ template void anisotropicDiffusion(Array& inout, const float dt, const float mct, const af::fluxFunction fftype, const af::diffusionEq eq) { - if (eq == AF_DIFFUSION_MCDE) + if (eq == AF_DIFFUSION_MCDE) { kernel::anisotropicDiffusion(inout, dt, mct, fftype); - else + } else { kernel::anisotropicDiffusion(inout, dt, mct, fftype); + } } #define INSTANTIATE(T) \ diff --git a/src/backend/opencl/api.cpp b/src/backend/opencl/api.cpp index ef8b9f9894..04b73eff4f 100644 --- a/src/backend/opencl/api.cpp +++ b/src/backend/opencl/api.cpp @@ -4,10 +4,11 @@ namespace af { template<> AFAPI cl_mem *array::device() const { - cl_mem *mem_ptr = new cl_mem; - af_err err = af_get_device_ptr((void **)mem_ptr, get()); - if (err != AF_SUCCESS) + auto *mem_ptr = new cl_mem; + af_err err = af_get_device_ptr(reinterpret_cast(mem_ptr), get()); + if (err != AF_SUCCESS) { throw af::exception("Failed to get cl_mem from array object"); + } return mem_ptr; } } // namespace af diff --git a/src/backend/opencl/assign.cpp b/src/backend/opencl/assign.cpp index 8bac7911a3..541deac27f 100644 --- a/src/backend/opencl/assign.cpp +++ b/src/backend/opencl/assign.cpp @@ -33,7 +33,7 @@ void assign(Array& out, const af_index_t idxrs[], const Array& rhs) { } // retrieve dimensions, strides and offsets - dim4 dDims = out.dims(); + const dim4& dDims = out.dims(); // retrieve dimensions & strides for array // to which rhs is being copied to dim4 dstOffs = toOffset(seqs, dDims); @@ -58,8 +58,9 @@ void assign(Array& out, const af_index_t idxrs[], const Array& rhs) { // alloc an 1-element buffer to avoid OpenCL from failing using // direct buffer allocation as opposed to mem manager to avoid // reference count desprepancies between different backends - static cl::Buffer* empty = - new Buffer(getContext(), CL_MEM_READ_ONLY, sizeof(uint)); + static auto* empty = new Buffer( + getContext(), CL_MEM_READ_ONLY, // NOLINT(hicpp-signed-bitwise) + sizeof(uint)); bPtrs[x] = empty; } } diff --git a/src/backend/opencl/blas.cpp b/src/backend/opencl/blas.cpp index 6870da0e50..263d07bd9f 100644 --- a/src/backend/opencl/blas.cpp +++ b/src/backend/opencl/blas.cpp @@ -54,10 +54,10 @@ void gemm_fallback(Array &out, af_mat_prop optLhs, af_mat_prop optRhs, } template<> -void gemm_fallback(Array &out, af_mat_prop optLhs, - af_mat_prop optRhs, const half *alpha, - const Array &lhs, const Array &rhs, - const half *beta) { +void gemm_fallback(Array & /*out*/, af_mat_prop /*optLhs*/, + af_mat_prop /*optRhs*/, const half * /*alpha*/, + const Array & /*lhs*/, + const Array & /*rhs*/, const half * /*beta*/) { assert(false && "CPU fallback not implemented for f16"); } @@ -66,7 +66,8 @@ void gemm(Array &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, const Array &lhs, const Array &rhs, const T *beta) { #if defined(WITH_LINEAR_ALGEBRA) // Do not force offload gemm on OSX Intel devices - if (OpenCLCPUOffload(false) && (af_dtype)dtype_traits::af_type != f16) { + if (OpenCLCPUOffload(false) && + static_cast(dtype_traits::af_type) != f16) { gemm_fallback(out, optLhs, optRhs, alpha, lhs, rhs, beta); return; } @@ -78,18 +79,18 @@ void gemm(Array &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, const auto aColDim = (lOpts == OPENCL_BLAS_NO_TRANS) ? 1 : 0; const auto bColDim = (rOpts == OPENCL_BLAS_NO_TRANS) ? 1 : 0; - const dim4 lDims = lhs.dims(); - const dim4 rDims = rhs.dims(); - const int M = lDims[aRowDim]; - const int N = rDims[bColDim]; - const int K = lDims[aColDim]; - const dim4 oDims = out.dims(); + const dim4 &lDims = lhs.dims(); + const dim4 &rDims = rhs.dims(); + const int M = lDims[aRowDim]; + const int N = rDims[bColDim]; + const int K = lDims[aColDim]; + const dim4 oDims = out.dims(); - const dim4 lStrides = lhs.strides(); - const dim4 rStrides = rhs.strides(); - const dim4 oStrides = out.strides(); + const dim4 &lStrides = lhs.strides(); + const dim4 &rStrides = rhs.strides(); + const dim4 oStrides = out.strides(); - int batchSize = oDims[2] * oDims[3]; + int batchSize = static_cast(oDims[2] * oDims[3]); bool is_l_d2_batched = oDims[2] == lDims[2]; bool is_l_d3_batched = oDims[3] == lDims[3]; @@ -97,8 +98,8 @@ void gemm(Array &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, bool is_r_d3_batched = oDims[3] == rDims[3]; for (int n = 0; n < batchSize; n++) { - int w = n / oDims[2]; - int z = n - w * oDims[2]; + int w = static_cast(n / oDims[2]); + int z = static_cast(n - w * oDims[2]); int loff = z * (is_l_d2_batched * lStrides[2]) + w * (is_l_d3_batched * lStrides[3]); diff --git a/src/backend/opencl/cholesky.cpp b/src/backend/opencl/cholesky.cpp index 963cf2299e..505ba2ea16 100644 --- a/src/backend/opencl/cholesky.cpp +++ b/src/backend/opencl/cholesky.cpp @@ -43,10 +43,11 @@ Array cholesky(int *info, const Array &in, const bool is_upper) { Array out = copyArray(in); *info = cholesky_inplace(out, is_upper); - if (is_upper) + if (is_upper) { triangle(out, out); - else + } else { triangle(out, out); + } return out; } diff --git a/src/backend/opencl/clfft.cpp b/src/backend/opencl/clfft.cpp index 49fd0fb430..e70a4a76db 100644 --- a/src/backend/opencl/clfft.cpp +++ b/src/backend/opencl/clfft.cpp @@ -11,8 +11,11 @@ #include #include #include + +#include #include +using std::make_unique; using std::string; namespace opencl { @@ -122,20 +125,21 @@ SharedPlan findPlan(clfftLayout iLayout, clfftLayout oLayout, clfftDim rank, key_string.append(std::string(key_str_temp)); } - sprintf(key_str_temp, "%d:" SIZE_T_FRMT_SPECIFIER, (int)precision, batch); + sprintf(key_str_temp, "%d:" SIZE_T_FRMT_SPECIFIER, + static_cast(precision), batch); key_string.append(std::string(key_str_temp)); PlanCache &planner = opencl::fftManager(); SharedPlan retVal = planner.find(key_string); - if (retVal) return retVal; + if (retVal) { return retVal; } - PlanType *temp = (PlanType *)malloc(sizeof(PlanType)); + auto temp = make_unique(); // getContext() returns object of type Context // Context() returns the actual cl_context handle - CLFFT_CHECK( - clfftCreateDefaultPlan(temp, opencl::getContext()(), rank, clLengths)); + CLFFT_CHECK(clfftCreateDefaultPlan(temp.get(), opencl::getContext()(), rank, + clLengths)); // complex to complex if (iLayout == oLayout) { @@ -156,7 +160,7 @@ SharedPlan findPlan(clfftLayout iLayout, clfftLayout oLayout, clfftDim rank, // CommandQueue() returns the actual cl_command_queue handle CLFFT_CHECK(clfftBakePlan(*temp, 1, &(opencl::getQueue()()), NULL, NULL)); - retVal.reset(temp, [](PlanType *p) { + retVal.reset(temp.release(), [](PlanType *p) { #ifndef OS_WIN // On Windows the resources that are released after the main function // have exited cause "Pure Virtual Function Called" errors. It seems diff --git a/src/backend/opencl/convolve.cpp b/src/backend/opencl/convolve.cpp index 40a2895a95..eff48d262b 100644 --- a/src/backend/opencl/convolve.cpp +++ b/src/backend/opencl/convolve.cpp @@ -33,8 +33,8 @@ namespace opencl { template Array convolve(Array const &signal, Array const &filter, AF_BATCH_KIND kind) { - const dim4 sDims = signal.dims(); - const dim4 fDims = filter.dims(); + const dim4 &sDims = signal.dims(); + const dim4 &fDims = filter.dims(); dim4 oDims(1); if (expand) { @@ -48,7 +48,7 @@ Array convolve(Array const &signal, Array const &filter, } else { oDims = sDims; if (kind == AF_BATCH_RHS) { - for (dim_t i = baseDim; i < 4; ++i) oDims[i] = fDims[i]; + for (dim_t i = baseDim; i < 4; ++i) { oDims[i] = fDims[i]; } } } @@ -59,15 +59,17 @@ Array convolve(Array const &signal, Array const &filter, dim_t MCFL3 = kernel::MAX_CONV3_FILTER_LEN; switch (baseDim) { case 1: - if (fDims[0] > kernel::MAX_CONV1_FILTER_LEN) callKernel = false; + if (fDims[0] > kernel::MAX_CONV1_FILTER_LEN) { callKernel = false; } break; case 2: - if ((fDims[0] * fDims[1]) > (MCFL2 * MCFL2)) callKernel = false; + if ((fDims[0] * fDims[1]) > (MCFL2 * MCFL2)) { callKernel = false; } break; case 3: - if ((fDims[0] * fDims[1] * fDims[2]) > (MCFL3 * MCFL3 * MCFL3)) + if ((fDims[0] * fDims[1] * fDims[2]) > (MCFL3 * MCFL3 * MCFL3)) { callKernel = false; + } break; + default: AF_ERROR("baseDim only supports values 1-3.", AF_ERR_UNKNOWN); } if (!callKernel) { @@ -120,8 +122,8 @@ INSTANTIATE(intl, float) template Array convolve2_unwrap(const Array &signal, const Array &filter, - const dim4 stride, const dim4 padding, - const dim4 dilation) { + const dim4 &stride, const dim4 &padding, + const dim4 &dilation) { dim4 sDims = signal.dims(); dim4 fDims = filter.dims(); @@ -179,11 +181,12 @@ template Array conv2DataGradient(const Array &incoming_gradient, const Array &original_signal, const Array &original_filter, - const Array &convolved_output, af::dim4 stride, - af::dim4 padding, af::dim4 dilation) { - const dim4 cDims = incoming_gradient.dims(); - const dim4 sDims = original_signal.dims(); - const dim4 fDims = original_filter.dims(); + const Array & /*convolved_output*/, + af::dim4 stride, af::dim4 padding, + af::dim4 dilation) { + const dim4 &cDims = incoming_gradient.dims(); + const dim4 &sDims = original_signal.dims(); + const dim4 &fDims = original_filter.dims(); Array collapsed_filter = original_filter; @@ -212,11 +215,12 @@ template Array conv2FilterGradient(const Array &incoming_gradient, const Array &original_signal, const Array &original_filter, - const Array &convolved_output, af::dim4 stride, - af::dim4 padding, af::dim4 dilation) { - const dim4 cDims = incoming_gradient.dims(); - const dim4 sDims = original_signal.dims(); - const dim4 fDims = original_filter.dims(); + const Array & /*convolved_output*/, + af::dim4 stride, af::dim4 padding, + af::dim4 dilation) { + const dim4 &cDims = incoming_gradient.dims(); + const dim4 &sDims = original_signal.dims(); + const dim4 &fDims = original_filter.dims(); const bool retCols = false; Array unwrapped = diff --git a/src/backend/opencl/convolve_separable.cpp b/src/backend/opencl/convolve_separable.cpp index 08c5f57841..19b312b3af 100644 --- a/src/backend/opencl/convolve_separable.cpp +++ b/src/backend/opencl/convolve_separable.cpp @@ -20,23 +20,23 @@ namespace opencl { template Array convolve2(Array const& signal, Array const& c_filter, Array const& r_filter) { - const dim_t cflen = (dim_t)c_filter.elements(); - const dim_t rflen = (dim_t)r_filter.elements(); + const auto cflen = c_filter.elements(); + const auto rflen = r_filter.elements(); if ((cflen > kernel::MAX_SCONV_FILTER_LEN) || (rflen > kernel::MAX_SCONV_FILTER_LEN)) { // TODO call upon fft char errMessage[256]; snprintf(errMessage, sizeof(errMessage), - "\nOpenCL Separable convolution doesn't support %lld(coloumn) " - "%lld(row) filters\n", + "\nOpenCL Separable convolution doesn't support %zu(coloumn) " + "%zu(row) filters\n", cflen, rflen); OPENCL_NOT_SUPPORTED(errMessage); } - const dim4 sDims = signal.dims(); - dim4 tDims = sDims; - dim4 oDims = sDims; + const dim4& sDims = signal.dims(); + dim4 tDims = sDims; + dim4 oDims = sDims; if (expand) { tDims[0] += cflen - 1; diff --git a/src/backend/opencl/copy.cpp b/src/backend/opencl/copy.cpp index 7e43a19dd1..7be07316ed 100644 --- a/src/backend/opencl/copy.cpp +++ b/src/backend/opencl/copy.cpp @@ -44,7 +44,6 @@ void copyData(T *data, const Array &A) { // FIXME: Add checks getQueue().enqueueReadBuffer(buf, CL_TRUE, sizeof(T) * offset, sizeof(T) * A.elements(), data); - return; } template @@ -69,12 +68,13 @@ Array padArray(Array const &in, dim4 const &dims, outType default_value, double factor) { Array ret = createEmptyArray(dims); - if (in.dims() == dims) + if (in.dims() == dims) { kernel::copy(ret, in, in.ndims(), default_value, factor); - else + } else { kernel::copy(ret, in, in.ndims(), default_value, factor); + } return ret; } @@ -86,12 +86,13 @@ void multiply_inplace(Array &in, double val) { template struct copyWrapper { void operator()(Array &out, Array const &in) { - if (in.dims() == out.dims()) + if (in.dims() == out.dims()) { kernel::copy(out, in, in.ndims(), scalar(0), 1); - else + } else { kernel::copy(out, in, in.ndims(), scalar(0), 1); + } } }; @@ -106,10 +107,11 @@ struct copyWrapper { getQueue().enqueueCopyBuffer(*in.get(), *out.get(), in_offset, out_offset, in.elements() * sizeof(T)); } else { - if (in.dims() == out.dims()) + if (in.dims() == out.dims()) { kernel::copy(out, in, in.ndims(), scalar(0), 1); - else + } else { kernel::copy(out, in, in.ndims(), scalar(0), 1); + } } } }; @@ -237,7 +239,7 @@ INSTANTIATE_PAD_ARRAY_COMPLEX(cdouble) template T getScalar(const Array &in) { - T retVal; + T retVal{}; getQueue().enqueueReadBuffer(*in.get(), CL_TRUE, sizeof(T) * in.getOffset(), sizeof(T), &retVal); return retVal; diff --git a/src/backend/opencl/cpu/cpu_blas.cpp b/src/backend/opencl/cpu/cpu_blas.cpp index ad8680cafe..6ae3f39c0f 100644 --- a/src/backend/opencl/cpu/cpu_blas.cpp +++ b/src/backend/opencl/cpu/cpu_blas.cpp @@ -180,12 +180,12 @@ void gemm(Array &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, const int aColDim = (lOpts == CblasNoTrans) ? 1 : 0; const int bColDim = (rOpts == CblasNoTrans) ? 1 : 0; - const dim4 lDims = lhs.dims(); - const dim4 rDims = rhs.dims(); - const int M = lDims[aRowDim]; - const int N = rDims[bColDim]; - const int K = lDims[aColDim]; - const dim4 oDims = out.dims(); + const dim4 &lDims = lhs.dims(); + const dim4 &rDims = rhs.dims(); + const int M = lDims[aRowDim]; + const int N = rDims[bColDim]; + const int K = lDims[aColDim]; + const dim4 &oDims = out.dims(); dim4 lStrides = lhs.strides(); dim4 rStrides = rhs.strides(); @@ -212,9 +212,10 @@ void gemm(Array &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, int roff = z * (is_r_d2_batched * rStrides[2]) + w * (is_r_d3_batched * rStrides[3]); - CBT *lptr = (CBT *)(lPtr.get() + loff); - CBT *rptr = (CBT *)(rPtr.get() + roff); - BT *optr = (BT *)(oPtr.get() + z * oStrides[2] + w * oStrides[3]); + CBT *lptr = static_cast(lPtr.get() + loff); + CBT *rptr = static_cast(rPtr.get() + roff); + BT *optr = + static_cast(oPtr.get() + z * oStrides[2] + w * oStrides[3]); if (rDims[bColDim] == 1) { dim_t incr = (rOpts == CblasNoTrans) ? rStrides[0] : rStrides[1]; diff --git a/src/backend/opencl/cpu/cpu_cholesky.cpp b/src/backend/opencl/cpu/cpu_cholesky.cpp index c8bb0a5084..fc066bd710 100644 --- a/src/backend/opencl/cpu/cpu_cholesky.cpp +++ b/src/backend/opencl/cpu/cpu_cholesky.cpp @@ -42,12 +42,13 @@ Array cholesky(int *info, const Array &in, const bool is_upper) { mapped_ptr oPtr = out.getMappedPtr(); - if (is_upper) + if (is_upper) { triangle(oPtr.get(), oPtr.get(), out.dims(), out.strides(), out.strides()); - else + } else { triangle(oPtr.get(), oPtr.get(), out.dims(), out.strides(), out.strides()); + } return out; } @@ -58,7 +59,7 @@ int cholesky_inplace(Array &in, const bool is_upper) { int N = iDims[0]; char uplo = 'L'; - if (is_upper) uplo = 'U'; + if (is_upper) { uplo = 'U'; } mapped_ptr inPtr = in.getMappedPtr(); diff --git a/src/backend/opencl/cpu/cpu_lu.cpp b/src/backend/opencl/cpu/cpu_lu.cpp index 30f7d4d64b..7793a3590e 100644 --- a/src/backend/opencl/cpu/cpu_lu.cpp +++ b/src/backend/opencl/cpu/cpu_lu.cpp @@ -76,14 +76,14 @@ void lu_split(Array &lower, Array &upper, const Array &in) { const dim_t uMem = uYZW + ox; const dim_t iMem = iYZW + ox; if (ox > oy) { - if (oy < ldm[1]) l[lMem] = i[iMem]; - if (ox < udm[0]) u[uMem] = scalar(0); + if (oy < ldm[1]) { l[lMem] = i[iMem]; } + if (ox < udm[0]) { u[uMem] = scalar(0); } } else if (oy > ox) { - if (oy < ldm[1]) l[lMem] = scalar(0); - if (ox < udm[0]) u[uMem] = i[iMem]; + if (oy < ldm[1]) { l[lMem] = scalar(0); } + if (ox < udm[0]) { u[uMem] = i[iMem]; } } else if (ox == oy) { - if (oy < ldm[1]) l[lMem] = scalar(1.0); - if (ox < udm[0]) u[uMem] = i[iMem]; + if (oy < ldm[1]) { l[lMem] = scalar(1.0); } + if (ox < udm[0]) { u[uMem] = i[iMem]; } } } } @@ -95,7 +95,7 @@ void convertPivot(int *pivot, int out_sz, size_t pivot_dim) { std::vector p(out_sz); iota(begin(p), end(p), 0); - for (int j = 0; j < (int)pivot_dim; j++) { + for (int j = 0; j < static_cast(pivot_dim); j++) { // 1 indexed in pivot std::swap(p[j], p[pivot[j] - 1]); } @@ -138,7 +138,7 @@ Array lu_inplace(Array &in, const bool convert_pivot) { getrf_func()(AF_LAPACK_COL_MAJOR, M, N, inPtr.get(), in.strides()[1], piPtr.get()); - if (convert_pivot) convertPivot(piPtr.get(), M, min(M, N)); + if (convert_pivot) { convertPivot(piPtr.get(), M, min(M, N)); } return pivot; } diff --git a/src/backend/opencl/cpu/cpu_sparse_blas.cpp b/src/backend/opencl/cpu/cpu_sparse_blas.cpp index dc08ef340d..0699c44717 100644 --- a/src/backend/opencl/cpu/cpu_sparse_blas.cpp +++ b/src/backend/opencl/cpu/cpu_sparse_blas.cpp @@ -57,8 +57,8 @@ using scale_type = const typename blas_base::type, const T>::type; template -To getScaleValue(Ti val) { - return (To)(val); +auto getScaleValue(Ti val) -> std::remove_cv_t { + return static_cast>(val); } #ifdef USE_MKL @@ -143,7 +143,7 @@ SPARSE_FUNC(mm, cdouble, z) #undef SPARSE_FUNC_DEF template<> -const sp_cfloat getScaleValue(cfloat val) { +sp_cfloat getScaleValue(cfloat val) { sp_cfloat ret; ret.real = val.s[0]; ret.imag = val.s[1]; @@ -151,7 +151,7 @@ const sp_cfloat getScaleValue(cfloat val) { } template<> -const sp_cdouble getScaleValue(cdouble val) { +sp_cdouble getScaleValue(cdouble val) { sp_cdouble ret; ret.real = val.s[0]; ret.imag = val.s[1]; @@ -181,7 +181,7 @@ sparse_operation_t toSparseTranspose(af_mat_prop opt) { } template -scale_type getScale() { +scale_type getScale() { // NOLINT(readability-const-return-type) thread_local T val = scalar(value); return getScaleValue, T>(val); } @@ -241,7 +241,7 @@ Array matmul(const common::SparseArray lhs, const Array rhs, lhs.dims()[1], pB, pE, cPtr.get(), reinterpret_cast>(vPtr.get())); - struct matrix_descr descrLhs; + struct matrix_descr descrLhs {}; descrLhs.type = SPARSE_MATRIX_TYPE_GENERAL; mkl_sparse_optimize(csrLhs); diff --git a/src/backend/opencl/device_manager.cpp b/src/backend/opencl/device_manager.cpp index 11ed2238e4..50a39ccdb6 100644 --- a/src/backend/opencl/device_manager.cpp +++ b/src/backend/opencl/device_manager.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #ifdef OS_MAC #include @@ -58,7 +59,7 @@ static const char* CL_GL_SHARING_EXT = "cl_APPLE_gl_sharing"; static const char* CL_GL_SHARING_EXT = "cl_khr_gl_sharing"; #endif -bool checkExtnAvailability(const Device& pDevice, string pName) { +bool checkExtnAvailability(const Device& pDevice, const string& pName) { bool ret_val = false; // find the extension required string exts = pDevice.getInfo(); @@ -73,8 +74,8 @@ bool checkExtnAvailability(const Device& pDevice, string pName) { return ret_val; } -static afcl::deviceType getDeviceTypeEnum(Device dev) { - return (afcl::deviceType)dev.getInfo(); +static afcl::deviceType getDeviceTypeEnum(const Device& dev) { + return static_cast(dev.getInfo()); } static inline bool compare_default(const Device* ldev, const Device* rdev) { @@ -89,16 +90,16 @@ static inline bool compare_default(const Device* ldev, const Device* rdev) { auto is_l_curr_type = l_dev_type == current_type; auto is_r_curr_type = r_dev_type == current_type; - if (is_l_curr_type && !is_r_curr_type) return true; - if (!is_l_curr_type && is_r_curr_type) return false; + if (is_l_curr_type && !is_r_curr_type) { return true; } + if (!is_l_curr_type && is_r_curr_type) { return false; } } // For GPUs, this ensures discrete > integrated auto is_l_integrated = ldev->getInfo(); auto is_r_integrated = rdev->getInfo(); - if (!is_l_integrated && is_r_integrated) return true; - if (is_l_integrated && !is_r_integrated) return false; + if (!is_l_integrated && is_r_integrated) { return true; } + if (is_l_integrated && !is_r_integrated) { return false; } // At this point, the devices are of same type. // Sort based on emperical evidence of preferred platforms @@ -114,12 +115,14 @@ static inline bool compare_default(const Device* ldev, const Device* rdev) { for (auto ref_name : platforms) { if (verify_present(lPlatName, ref_name) && - !verify_present(rPlatName, ref_name)) + !verify_present(rPlatName, ref_name)) { return true; + } if (!verify_present(lPlatName, ref_name) && - verify_present(rPlatName, ref_name)) + verify_present(rPlatName, ref_name)) { return false; + } } // Intel falls back to compare based on memory @@ -129,12 +132,14 @@ static inline bool compare_default(const Device* ldev, const Device* rdev) { for (auto ref_name : platforms) { if (verify_present(lPlatName, ref_name) && - !verify_present(rPlatName, ref_name)) + !verify_present(rPlatName, ref_name)) { return true; + } if (!verify_present(lPlatName, ref_name) && - verify_present(rPlatName, ref_name)) + verify_present(rPlatName, ref_name)) { return false; + } } } @@ -153,8 +158,8 @@ static inline bool compare_default(const Device* ldev, const Device* rdev) { (lversion[7] < rversion[7]) || ((lversion[7] == rversion[7]) && (lversion[9] < rversion[9])); - if (lres) return true; - if (rres) return false; + if (lres) { return true; } + if (rres) { return false; } } // Default criteria, sort based on memory @@ -182,7 +187,7 @@ DeviceManager::DeviceManager() AF_ERR_RUNTIME); } } - fgMngr.reset(new graphics::ForgeManager()); + fgMngr = std::make_unique(); // This is all we need because the sort takes care of the order of devices #ifdef OS_MAC @@ -193,9 +198,9 @@ DeviceManager::DeviceManager() string deviceENV = getEnvVar("AF_OPENCL_DEVICE_TYPE"); - if (deviceENV.compare("GPU") == 0) { + if (deviceENV == "GPU") { DEVICE_TYPES = CL_DEVICE_TYPE_GPU; - } else if (deviceENV.compare("CPU") == 0) { + } else if (deviceENV == "CPU") { DEVICE_TYPES = CL_DEVICE_TYPE_CPU; } else if (deviceENV.compare("ACC") >= 0) { DEVICE_TYPES = CL_DEVICE_TYPE_ACCELERATOR; @@ -214,7 +219,7 @@ DeviceManager::DeviceManager() } AF_TRACE("Found {} devices on platform {}", current_devices.size(), platform.getInfo()); - for (auto dev : current_devices) { + for (const auto& dev : current_devices) { mDevices.push_back(new Device(dev)); AF_TRACE("Found device {} on platform {}", dev.getInfo(), @@ -237,8 +242,8 @@ DeviceManager::DeviceManager() cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(device_platform), 0}; - Context* ctx = new Context(*mDevices[i], cps); - CommandQueue* cq = new CommandQueue(*ctx, *mDevices[i]); + auto* ctx = new Context(*mDevices[i], cps); + auto* cq = new CommandQueue(*ctx, *mDevices[i]); mContexts.push_back(ctx); mQueues.push_back(cq); mIsGLSharingOn.push_back(false); @@ -252,7 +257,7 @@ DeviceManager::DeviceManager() stringstream s(deviceENV); int def_device = -1; s >> def_device; - if (def_device < 0 || def_device >= (int)nDevices) { + if (def_device < 0 || def_device >= nDevices) { AF_TRACE( "AF_OPENCL_DEFAULT_DEVICE ({}) \ is out of range, Setting default device to 0", @@ -266,7 +271,7 @@ DeviceManager::DeviceManager() deviceENV = getEnvVar("AF_OPENCL_DEFAULT_DEVICE_TYPE"); if (!default_device_set && !deviceENV.empty()) { cl_device_type default_device_type = CL_DEVICE_TYPE_GPU; - if (deviceENV.compare("CPU") == 0) { + if (deviceENV == "CPU") { default_device_type = CL_DEVICE_TYPE_CPU; } else if (deviceENV.compare("ACC") >= 0) { default_device_type = CL_DEVICE_TYPE_ACCELERATOR; @@ -298,7 +303,9 @@ DeviceManager::DeviceManager() * OpenGL shared contexts whereever applicable */ int devCount = mDevices.size(); fg_window wHandle = fgMngr->getMainWindow(); - for (int i = 0; i < devCount; ++i) markDeviceForInterop(i, wHandle); + for (int i = 0; i < devCount; ++i) { + markDeviceForInterop(i, wHandle); + } } catch (...) {} } @@ -323,7 +330,7 @@ DeviceManager::DeviceManager() spdlog::logger* DeviceManager::getLogger() { return logger.get(); } DeviceManager& DeviceManager::getInstance() { - static DeviceManager* my_instance = new DeviceManager(); + static auto* my_instance = new DeviceManager(); return *my_instance; } @@ -381,9 +388,7 @@ void DeviceManager::resetMemoryManagerPinned() { } DeviceManager::~DeviceManager() { - for (int i = 0; i < getDeviceCount(); ++i) { - delete gfxManagers[i].release(); - } + for (int i = 0; i < getDeviceCount(); ++i) { gfxManagers[i] = nullptr; } #ifndef OS_WIN // TODO: FIXME: // clfftTeardown() causes a "Pure Virtual Function Called" crash on @@ -395,12 +400,11 @@ DeviceManager::~DeviceManager() { // deCache Boost program_cache #ifndef OS_WIN - namespace compute = boost::compute; - for (auto bCache : mBoostProgCacheVector) delete bCache; + for (auto bCache : mBoostProgCacheVector) { delete bCache; } #endif - delete memManager.release(); - delete pinnedMemManager.release(); + memManager = nullptr; + pinnedMemManager = nullptr; // TODO: FIXME: // OpenCL libs on Windows platforms @@ -410,17 +414,17 @@ DeviceManager::~DeviceManager() { // doesn't seem to happen on Linux or MacOSX. // So, clean up OpenCL resources on non-Windows platforms #ifndef OS_WIN - for (auto q : mQueues) delete q; - for (auto c : mContexts) delete c; - for (auto d : mDevices) delete d; + for (auto q : mQueues) { delete q; } + for (auto c : mContexts) { delete c; } + for (auto d : mDevices) { delete d; } #endif } void DeviceManager::markDeviceForInterop(const int device, const void* wHandle) { try { - if (device >= (int)mQueues.size() || - device >= (int)DeviceManager::MAX_DEVICES) { + if (device >= static_cast(mQueues.size()) || + device >= static_cast(DeviceManager::MAX_DEVICES)) { AF_TRACE("Invalid device (}) passed for CL-GL Interop", device); throw cl::Error(CL_INVALID_DEVICE, "Invalid device passed for CL-GL Interop"); @@ -455,13 +459,13 @@ void DeviceManager::markDeviceForInterop(const int device, #else cl_context_properties cps[] = { CL_GL_CONTEXT_KHR, - (cl_context_properties)wnd_ctx, + static_cast(wnd_ctx), #if defined(_WIN32) || defined(_MSC_VER) CL_WGL_HDC_KHR, (cl_context_properties)wnd_dsp, #else CL_GLX_DISPLAY_KHR, - (cl_context_properties)wnd_dsp, + static_cast(wnd_dsp), #endif CL_CONTEXT_PLATFORM, (cl_context_properties)plat(), @@ -471,19 +475,20 @@ void DeviceManager::markDeviceForInterop(const int device, // Check if current OpenCL device is belongs to the OpenGL context { cl_context_properties test_cps[] = { - CL_GL_CONTEXT_KHR, (cl_context_properties)wnd_ctx, + CL_GL_CONTEXT_KHR, + static_cast(wnd_ctx), CL_CONTEXT_PLATFORM, (cl_context_properties)plat(), 0}; // Load the extension // If cl_khr_gl_sharing is available, this function should be // present This has been checked earlier, it comes to this point // only if it is found - auto func = (clGetGLContextInfoKHR_fn) + auto func = reinterpret_cast( clGetExtensionFunctionAddressForPlatform( - plat(), "clGetGLContextInfoKHR"); + plat(), "clGetGLContextInfoKHR")); // If the function doesn't load, bail early - if (!func) return; + if (!func) { return; } // Get all devices associated with opengl context vector devices(16); @@ -491,21 +496,21 @@ void DeviceManager::markDeviceForInterop(const int device, cl_int err = func(test_cps, CL_DEVICES_FOR_GL_CONTEXT_KHR, devices.size() * sizeof(cl_device_id), &devices[0], &ret); - if (err != CL_SUCCESS) return; - int num = ret / sizeof(cl_device_id); + if (err != CL_SUCCESS) { return; } + size_t num = ret / sizeof(cl_device_id); devices.resize(num); // Check if current device is present in the associated devices cl_device_id current_device = (*mDevices[device])(); auto res = find(begin(devices), end(devices), current_device); - if (res == end(devices)) return; + if (res == end(devices)) { return; } } #endif // Change current device to use GL sharing - Context* ctx = new Context(*mDevices[device], cps); - CommandQueue* cq = new CommandQueue(*ctx, *mDevices[device]); + auto* ctx = new Context(*mDevices[device], cps); + auto* cq = new CommandQueue(*ctx, *mDevices[device]); // May be fixes the AMD GL issues we see on windows? #if !defined(_WIN32) && !defined(_MSC_VER) diff --git a/src/backend/opencl/device_manager.hpp b/src/backend/opencl/device_manager.hpp index 11cc5336c8..6a6b125cea 100644 --- a/src/backend/opencl/device_manager.hpp +++ b/src/backend/opencl/device_manager.hpp @@ -86,10 +86,10 @@ class DeviceManager { friend int setDevice(int device); - friend void addDeviceContext(cl_device_id dev, cl_context cxt, + friend void addDeviceContext(cl_device_id dev, cl_context ctx, cl_command_queue que); - friend void setDeviceContext(cl_device_id dev, cl_context cxt); + friend void setDeviceContext(cl_device_id dev, cl_context ctx); friend void removeDeviceContext(cl_device_id dev, cl_context ctx); diff --git a/src/backend/opencl/diff.cpp b/src/backend/opencl/diff.cpp index 2a556052da..e604404ee1 100644 --- a/src/backend/opencl/diff.cpp +++ b/src/backend/opencl/diff.cpp @@ -16,8 +16,8 @@ namespace opencl { template static Array diff(const Array &in, const int dim) { - const af::dim4 iDims = in.dims(); - af::dim4 oDims = iDims; + const af::dim4 &iDims = in.dims(); + af::dim4 oDims = iDims; oDims[dim] -= (isDiff2 + 1); if (iDims.elements() == 0 || oDims.elements() == 0) { @@ -27,13 +27,11 @@ static Array diff(const Array &in, const int dim) { Array out = createEmptyArray(oDims); switch (dim) { - case (0): kernel::diff(out, in, in.ndims()); break; - - case (1): kernel::diff(out, in, in.ndims()); break; - - case (2): kernel::diff(out, in, in.ndims()); break; - - case (3): kernel::diff(out, in, in.ndims()); break; + case 0: kernel::diff(out, in, in.ndims()); break; + case 1: kernel::diff(out, in, in.ndims()); break; + case 2: kernel::diff(out, in, in.ndims()); break; + case 3: kernel::diff(out, in, in.ndims()); break; + default: AF_ERROR("dim only supports values 0-3.", AF_ERR_UNKNOWN); } return out; diff --git a/src/backend/opencl/fft.cpp b/src/backend/opencl/fft.cpp index d0ae97d98b..466099dc92 100644 --- a/src/backend/opencl/fft.cpp +++ b/src/backend/opencl/fft.cpp @@ -37,32 +37,33 @@ struct Precision { }; static void computeDims(size_t rdims[4], const dim4 &idims) { - for (int i = 0; i < 4; i++) { rdims[i] = (size_t)idims[i]; } + for (int i = 0; i < 4; i++) { rdims[i] = static_cast(idims[i]); } } //(currently) true is in clFFT if length is a power of 2,3,5 inline bool isSupLen(dim_t length) { while (length > 1) { - if (length % 2 == 0) + if (length % 2 == 0) { length /= 2; - else if (length % 3 == 0) + } else if (length % 3 == 0) { length /= 3; - else if (length % 5 == 0) + } else if (length % 5 == 0) { length /= 5; - else if (length % 7 == 0) + } else if (length % 7 == 0) { length /= 7; - else if (length % 11 == 0) + } else if (length % 11 == 0) { length /= 11; - else if (length % 13 == 0) + } else if (length % 13 == 0) { length /= 13; - else + } else { return false; + } } return true; } template -void verifySupported(const dim4 dims) { +void verifySupported(const dim4 &dims) { for (int i = 0; i < rank; i++) { ARG_ASSERT(1, isSupLen(dims[i])); } } @@ -77,10 +78,10 @@ void fft_inplace(Array &in) { int batch = 1; for (int i = rank; i < 4; i++) { batch *= tdims[i]; } - SharedPlan plan = - findPlan(CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED, - (clfftDim)rank, tdims, istrides, istrides[rank], istrides, - istrides[rank], (clfftPrecision)Precision::type, batch); + SharedPlan plan = findPlan( + CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED, + static_cast(rank), tdims, istrides, istrides[rank], istrides, + istrides[rank], static_cast(Precision::type), batch); cl_mem imem = (*in.get())(); cl_command_queue queue = getQueue()(); @@ -108,10 +109,10 @@ Array fft_r2c(const Array &in) { int batch = 1; for (int i = rank; i < 4; i++) { batch *= tdims[i]; } - SharedPlan plan = - findPlan(CLFFT_REAL, CLFFT_HERMITIAN_INTERLEAVED, (clfftDim)rank, tdims, - istrides, istrides[rank], ostrides, ostrides[rank], - (clfftPrecision)Precision::type, batch); + SharedPlan plan = findPlan( + CLFFT_REAL, CLFFT_HERMITIAN_INTERLEAVED, static_cast(rank), + tdims, istrides, istrides[rank], ostrides, ostrides[rank], + static_cast(Precision::type), batch); cl_mem imem = (*in.get())(); cl_mem omem = (*out.get())(); @@ -137,10 +138,10 @@ Array fft_c2r(const Array &in, const dim4 &odims) { int batch = 1; for (int i = rank; i < 4; i++) { batch *= tdims[i]; } - SharedPlan plan = - findPlan(CLFFT_HERMITIAN_INTERLEAVED, CLFFT_REAL, (clfftDim)rank, tdims, - istrides, istrides[rank], ostrides, ostrides[rank], - (clfftPrecision)Precision::type, batch); + SharedPlan plan = findPlan( + CLFFT_HERMITIAN_INTERLEAVED, CLFFT_REAL, static_cast(rank), + tdims, istrides, istrides[rank], ostrides, ostrides[rank], + static_cast(Precision::type), batch); cl_mem imem = (*in.get())(); cl_mem omem = (*out.get())(); diff --git a/src/backend/opencl/fftconvolve.cpp b/src/backend/opencl/fftconvolve.cpp index e4b1e607d8..01707e5099 100644 --- a/src/backend/opencl/fftconvolve.cpp +++ b/src/backend/opencl/fftconvolve.cpp @@ -19,19 +19,20 @@ using af::dim4; namespace opencl { template -static const dim4 calcPackedSize(Array const& i1, Array const& i2, - const dim_t baseDim) { - const dim4 i1d = i1.dims(); - const dim4 i2d = i2.dims(); +static dim4 calcPackedSize(Array const& i1, Array const& i2, + const dim_t baseDim) { + const dim4& i1d = i1.dims(); + const dim4& i2d = i2.dims(); dim_t pd[4] = {1, 1, 1, 1}; // Pack both signal and filter on same memory array, this will ensure // better use of batched cuFFT capabilities - pd[0] = nextpow2((unsigned)((int)ceil(i1d[0] / 2.f) + i2d[0] - 1)); + pd[0] = nextpow2(static_cast( + static_cast(std::ceil(i1d[0] / 2.f)) + i2d[0] - 1)); for (dim_t k = 1; k < baseDim; k++) { - pd[k] = nextpow2((unsigned)(i1d[k] + i2d[k] - 1)); + pd[k] = nextpow2(static_cast(i1d[k] + i2d[k] - 1)); } dim_t i1batch = 1; @@ -49,8 +50,8 @@ template Array fftconvolve(Array const& signal, Array const& filter, const bool expand, AF_BATCH_KIND kind) { - const dim4 sDims = signal.dims(); - const dim4 fDims = filter.dims(); + const dim4& sDims = signal.dims(); + const dim4& fDims = filter.dims(); dim4 oDims(1); if (expand) { @@ -64,7 +65,7 @@ Array fftconvolve(Array const& signal, Array const& filter, } else { oDims = sDims; if (kind == AF_BATCH_RHS) { - for (dim_t i = baseDim; i < 4; ++i) oDims[i] = fDims[i]; + for (dim_t i = baseDim; i < 4; ++i) { oDims[i] = fDims[i]; } } } @@ -83,12 +84,13 @@ Array fftconvolve(Array const& signal, Array const& filter, if (kind == AF_BATCH_RHS) { std::vector seqs; for (dim_t k = 0; k < 4; k++) { - if (k < baseDim) + if (k < baseDim) { seqs.push_back({0., static_cast(pDims[k] - 1), 1.}); - else if (k == baseDim) + } else if (k == baseDim) { seqs.push_back({1., static_cast(pDims[k] - 1), 1.}); - else + } else { seqs.push_back({0., 0., 1.}); + } } Array subPacked = createSubArray(packed, seqs); @@ -96,12 +98,13 @@ Array fftconvolve(Array const& signal, Array const& filter, } else { std::vector seqs; for (dim_t k = 0; k < 4; k++) { - if (k < baseDim) - seqs.push_back({0., (double)pDims[k] - 1, 1.}); - else if (k == baseDim) + if (k < baseDim) { + seqs.push_back({0., static_cast(pDims[k]) - 1, 1.}); + } else if (k == baseDim) { seqs.push_back({0., static_cast(pDims[k] - 2), 1.}); - else + } else { seqs.push_back({0., 0., 1.}); + } } Array subPacked = createSubArray(packed, seqs); @@ -110,12 +113,13 @@ Array fftconvolve(Array const& signal, Array const& filter, Array out = createEmptyArray(oDims); - if (expand) + if (expand) { kernel::reorderOutputHelper( out, packed, signal, filter, baseDim, kind); - else + } else { kernel::reorderOutputHelper( out, packed, signal, filter, baseDim, kind); + } return out; } diff --git a/src/backend/opencl/hist_graphics.cpp b/src/backend/opencl/hist_graphics.cpp index b83a73274f..a1875686bc 100644 --- a/src/backend/opencl/hist_graphics.cpp +++ b/src/backend/opencl/hist_graphics.cpp @@ -51,7 +51,8 @@ void copy_histogram(const Array &data, fg_histogram hist) { CheckGL("Begin OpenCL fallback-resource copy"); glBindBuffer(GL_ARRAY_BUFFER, buffer); - GLubyte *ptr = (GLubyte *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + auto *ptr = + static_cast(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); if (ptr) { getQueue().enqueueReadBuffer(*data.get(), CL_TRUE, 0, bytes, ptr); glUnmapBuffer(GL_ARRAY_BUFFER); diff --git a/src/backend/opencl/histogram.cpp b/src/backend/opencl/histogram.cpp index 7735803519..40f4621660 100644 --- a/src/backend/opencl/histogram.cpp +++ b/src/backend/opencl/histogram.cpp @@ -22,7 +22,7 @@ namespace opencl { template Array histogram(const Array &in, const unsigned &nbins, const double &minval, const double &maxval) { - const dim4 dims = in.dims(); + const dim4 &dims = in.dims(); dim4 outDims = dim4(nbins, 1, dims[2], dims[3]); Array out = createValueArray(outDims, outType(0)); diff --git a/src/backend/opencl/homography.cpp b/src/backend/opencl/homography.cpp index 8eaa3bf394..229678f700 100644 --- a/src/backend/opencl/homography.cpp +++ b/src/backend/opencl/homography.cpp @@ -30,15 +30,16 @@ int homography(Array &bestH, const Array &x_src, const Array &y_dst, const Array &initial, const af_homography_type htype, const float inlier_thr, const unsigned iterations) { - const af::dim4 idims = x_src.dims(); + const af::dim4 &idims = x_src.dims(); const unsigned nsamples = idims[0]; unsigned iter = iterations; Array err = createEmptyArray(af::dim4()); if (htype == AF_HOMOGRAPHY_LMEDS) { - iter = ::std::min( - iter, (unsigned)(log(1.f - LMEDSConfidence) / - log(1.f - pow(1.f - LMEDSOutlierRatio, 4.f)))); + iter = + ::std::min(iter, static_cast( + log(1.f - LMEDSConfidence) / + log(1.f - pow(1.f - LMEDSOutlierRatio, 4.f)))); err = createValueArray(af::dim4(nsamples, iter), FLT_MAX); } else { // Avoid passing "null" cl_mem object to kernels @@ -48,12 +49,14 @@ int homography(Array &bestH, const Array &x_src, const size_t iter_sz = divup(iter, 256) * 256; af::dim4 rdims(4, iter_sz); - Array fctr = createValueArray(rdims, (float)nsamples); - Array rnd = arithOp(initial, fctr, rdims); + Array fctr = + createValueArray(rdims, static_cast(nsamples)); + Array rnd = arithOp(initial, fctr, rdims); - Array tmpH = createValueArray(af::dim4(9, iter_sz), (T)0); + Array tmpH = + createValueArray(af::dim4(9, iter_sz), static_cast(0)); - bestH = createValueArray(af::dim4(3, 3), (T)0); + bestH = createValueArray(af::dim4(3, 3), static_cast(0)); switch (htype) { case AF_HOMOGRAPHY_RANSAC: return kernel::computeH( diff --git a/src/backend/opencl/iir.cpp b/src/backend/opencl/iir.cpp index b2b7843459..3a70a3aa86 100644 --- a/src/backend/opencl/iir.cpp +++ b/src/backend/opencl/iir.cpp @@ -34,7 +34,7 @@ Array iir(const Array &b, const Array &a, const Array &x) { int num_a = a.dims()[0]; - if (num_a == 1) return c; + if (num_a == 1) { return c; } dim4 ydims = c.dims(); Array y = createEmptyArray(ydims); diff --git a/src/backend/opencl/image.cpp b/src/backend/opencl/image.cpp index f441f0d37f..15b6a614a6 100644 --- a/src/backend/opencl/image.cpp +++ b/src/backend/opencl/image.cpp @@ -57,8 +57,8 @@ void copy_image(const Array &in, fg_image image) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, buffer); glBufferData(GL_PIXEL_UNPACK_BUFFER, bytes, 0, GL_STREAM_DRAW); - GLubyte *ptr = - (GLubyte *)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY); + auto *ptr = static_cast( + glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY)); if (ptr) { getQueue().enqueueReadBuffer(*in.get(), CL_TRUE, 0, bytes, ptr); glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); diff --git a/src/backend/opencl/index.cpp b/src/backend/opencl/index.cpp index 4189d3ab4d..2478484977 100644 --- a/src/backend/opencl/index.cpp +++ b/src/backend/opencl/index.cpp @@ -31,14 +31,14 @@ Array index(const Array& in, const af_index_t idxrs[]) { } // retrieve dimensions, strides and offsets - dim4 iDims = in.dims(); - dim4 dDims = in.getDataDims(); - dim4 oDims = toDims(seqs, iDims); - dim4 iOffs = toOffset(seqs, dDims); - dim4 iStrds = in.strides(); + const dim4& iDims = in.dims(); + dim4 dDims = in.getDataDims(); + dim4 oDims = toDims(seqs, iDims); + dim4 iOffs = toOffset(seqs, dDims); + dim4 iStrds = in.strides(); for (dim_t i = 0; i < 4; ++i) { - p.isSeq[i] = idxrs[i].isSeq; + p.isSeq[i] = idxrs[i].isSeq ? 1 : 0; p.offs[i] = iOffs[i]; p.strds[i] = iStrds[i]; } @@ -66,7 +66,7 @@ Array index(const Array& in, const af_index_t idxrs[]) { kernel::index(out, in, p, bPtrs); for (dim_t x = 0; x < 4; ++x) { - if (p.isSeq[x]) bufferFree(bPtrs[x]); + if (p.isSeq[x]) { bufferFree(bPtrs[x]); } } return out; diff --git a/src/backend/opencl/inverse.cpp b/src/backend/opencl/inverse.cpp index a6f141385b..c5b62a861f 100644 --- a/src/backend/opencl/inverse.cpp +++ b/src/backend/opencl/inverse.cpp @@ -20,7 +20,7 @@ namespace opencl { template Array inverse(const Array &in) { if (OpenCLCPUOffload()) { - if (in.dims()[0] == in.dims()[1]) return cpu::inverse(in); + if (in.dims()[0] == in.dims()[1]) { return cpu::inverse(in); } } Array I = identity(in.dims()); return solve(in, I); diff --git a/src/backend/opencl/jit.cpp b/src/backend/opencl/jit.cpp index 50f513bf85..09c6399d7a 100644 --- a/src/backend/opencl/jit.cpp +++ b/src/backend/opencl/jit.cpp @@ -64,7 +64,7 @@ static string getFuncName(const vector &output_nodes, for (auto node : output_nodes) { funcName << node->getNameStr() << "_"; } - for (int i = 0; i < (int)full_nodes.size(); i++) { + for (size_t i = 0; i < full_nodes.size(); i++) { full_nodes[i]->genKerName(funcName, full_ids[i]); } @@ -73,7 +73,7 @@ static string getFuncName(const vector &output_nodes, return hashName.str(); } -static string getKernelString(const string funcName, +static string getKernelString(const string &funcName, const vector &full_nodes, const vector &full_ids, const vector &output_ids, bool is_linear) { @@ -129,7 +129,7 @@ static string getKernelString(const string funcName, stringstream offsetsStream; stringstream opsStream; - for (int i = 0; i < (int)full_nodes.size(); i++) { + for (size_t i = 0; i < full_nodes.size(); i++) { const auto &node = full_nodes[i]; const auto &ids_curr = full_ids[i]; // Generate input parameters, only needs current id @@ -140,8 +140,7 @@ static string getKernelString(const string funcName, node->genFuncs(opsStream, ids_curr); } - for (int i = 0; i < (int)output_ids.size(); i++) { - int id = output_ids[i]; + for (int id : output_ids) { // Generate output parameters outParamStream << "__global " << full_nodes[id]->getTypeStr() << " *out" << id << ", \n"; @@ -188,7 +187,7 @@ static Kernel getKernel(const vector &output_nodes, output_ids, is_linear); saveKernel(funcName, jit_ker, ".cl"); const char *ker_strs[] = {jit_cl, jit_ker.c_str()}; - const int ker_lens[] = {jit_cl_len, (int)jit_ker.size()}; + const int ker_lens[] = {jit_cl_len, static_cast(jit_ker.size())}; Program prog; string options = @@ -212,8 +211,8 @@ static Kernel getKernel(const vector &output_nodes, return *entry.ker; } -void evalNodes(vector &outputs, vector output_nodes) { - if (outputs.size() == 0) return; +void evalNodes(vector &outputs, const vector &output_nodes) { + if (outputs.empty()) { return; } // Assume all ouputs are of same size // FIXME: Add assert to check if all outputs are same size? @@ -226,7 +225,7 @@ void evalNodes(vector &outputs, vector output_nodes) { thread_local vector output_ids; // Reserve some space to improve performance at smaller sizes - if (nodes.size() == 0) { + if (nodes.empty()) { nodes.reserve(1024); output_ids.reserve(output_nodes.size()); full_nodes.reserve(1024); @@ -259,10 +258,11 @@ void evalNodes(vector &outputs, vector output_nodes) { (getActiveDeviceType() == AFCL_DEVICE_TYPE_CPU) ? 1024 : 256; while (num_odims >= 1) { - if (out_info.dims[num_odims - 1] == 1) + if (out_info.dims[num_odims - 1] == 1) { num_odims--; - else + } else { break; + } } if (is_linear) { diff --git a/src/backend/opencl/join.cpp b/src/backend/opencl/join.cpp index b4f910abb6..b6e8ab7e2c 100644 --- a/src/backend/opencl/join.cpp +++ b/src/backend/opencl/join.cpp @@ -13,14 +13,19 @@ #include #include +#include #include +#include +using af::dim4; using common::half; +using std::transform; +using std::vector; namespace opencl { template -af::dim4 calcOffset(const af::dim4 dims) { - af::dim4 offset; +dim4 calcOffset(const dim4 &dims) { + dim4 offset; offset[0] = (dim == 0) ? dims[0] : 0; offset[1] = (dim == 1) ? dims[1] : 0; offset[2] = (dim == 2) ? dims[2] : 0; @@ -32,9 +37,9 @@ template Array join(const int dim, const Array &first, const Array &second) { // All dimensions except join dimension must be equal // Compute output dims - af::dim4 odims; - af::dim4 fdims = first.dims(); - af::dim4 sdims = second.dims(); + dim4 odims; + dim4 fdims = first.dims(); + dim4 sdims = second.dims(); for (int i = 0; i < 4; i++) { if (i == dim) { @@ -46,7 +51,7 @@ Array join(const int dim, const Array &first, const Array &second) { Array out = createEmptyArray(odims); - af::dim4 zero(0, 0, 0, 0); + dim4 zero(0, 0, 0, 0); switch (dim) { case 0: @@ -72,9 +77,9 @@ Array join(const int dim, const Array &first, const Array &second) { template void join_wrapper(const int dim, Array &out, - const std::vector> &inputs) { - af::dim4 zero(0, 0, 0, 0); - af::dim4 d = zero; + const vector> &inputs) { + dim4 zero(0, 0, 0, 0); + dim4 d = zero; switch (dim) { case 0: @@ -109,15 +114,15 @@ void join_wrapper(const int dim, Array &out, } template -Array join(const int dim, const std::vector> &inputs) { +Array join(const int dim, const vector> &inputs) { // All dimensions except join dimension must be equal // Compute output dims - af::dim4 odims; + dim4 odims; const dim_t n_arrays = inputs.size(); - std::vector idims(n_arrays); + vector idims(n_arrays); dim_t dim_size = 0; - for (int i = 0; i < (int)idims.size(); i++) { + for (size_t i = 0; i < idims.size(); i++) { idims[i] = inputs[i].dims(); dim_size += idims[i][dim]; } @@ -130,12 +135,12 @@ Array join(const int dim, const std::vector> &inputs) { } } - std::vector *> input_ptrs(inputs.size()); - std::transform( + vector *> input_ptrs(inputs.size()); + transform( begin(inputs), end(inputs), begin(input_ptrs), [](const Array &input) { return const_cast *>(&input); }); evalMultiple(input_ptrs); - std::vector inputParams(inputs.begin(), inputs.end()); + vector inputParams(inputs.begin(), inputs.end()); Array out = createEmptyArray(odims); switch (n_arrays) { @@ -173,9 +178,8 @@ INSTANTIATE(half, half) #undef INSTANTIATE -#define INSTANTIATE(T) \ - template Array join(const int dim, \ - const std::vector> &inputs); +#define INSTANTIATE(T) \ + template Array join(const int dim, const vector> &inputs); INSTANTIATE(float) INSTANTIATE(double) diff --git a/src/backend/opencl/kernel/approx.hpp b/src/backend/opencl/kernel/approx.hpp index 9f1f8583a8..b31b68bc8d 100644 --- a/src/backend/opencl/kernel/approx.hpp +++ b/src/backend/opencl/kernel/approx.hpp @@ -50,8 +50,8 @@ std::string generateOptionsString() { << " -D InterpPosTy=" << dtype_traits::getName() << " -D ZERO=" << toNumStr(scalar(0)); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D IS_CPLX=1"; } else { options << " -D IS_CPLX=0"; diff --git a/src/backend/opencl/kernel/convolve/conv2_b8.cpp b/src/backend/opencl/kernel/convolve/conv2_b8.cpp index 2ddd478faf..75b34e5459 100644 --- a/src/backend/opencl/kernel/convolve/conv2_b8.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_b8.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(char, float) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_c32.cpp b/src/backend/opencl/kernel/convolve/conv2_c32.cpp index 253aeef4cb..d498dfeb7d 100644 --- a/src/backend/opencl/kernel/convolve/conv2_c32.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_c32.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(cfloat, cfloat) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_c64.cpp b/src/backend/opencl/kernel/convolve/conv2_c64.cpp index 9ba2ce1844..5996ce5e4f 100644 --- a/src/backend/opencl/kernel/convolve/conv2_c64.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_c64.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(cdouble, cdouble) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_f32.cpp b/src/backend/opencl/kernel/convolve/conv2_f32.cpp index b1567ac9d8..48bbc3f055 100644 --- a/src/backend/opencl/kernel/convolve/conv2_f32.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_f32.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(float, float) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_f64.cpp b/src/backend/opencl/kernel/convolve/conv2_f64.cpp index aff172d7db..50b3bcc2b7 100644 --- a/src/backend/opencl/kernel/convolve/conv2_f64.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_f64.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(double, double) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_impl.hpp b/src/backend/opencl/kernel/convolve/conv2_impl.hpp index 7df69c2f60..404cd48fac 100644 --- a/src/backend/opencl/kernel/convolve/conv2_impl.hpp +++ b/src/backend/opencl/kernel/convolve/conv2_impl.hpp @@ -45,8 +45,8 @@ void conv2Helper(const conv_kparam_t& param, Param out, const Param signal, << " -D EXPAND=" << expand << " -D C_SIZE=" << LOC_SIZE << " -D " << binOpName(); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D CPLX=1"; } else { options << " -D CPLX=0"; diff --git a/src/backend/opencl/kernel/convolve/conv2_s16.cpp b/src/backend/opencl/kernel/convolve/conv2_s16.cpp index d8b7f33af0..30eccdf891 100644 --- a/src/backend/opencl/kernel/convolve/conv2_s16.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_s16.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(short, float) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_s32.cpp b/src/backend/opencl/kernel/convolve/conv2_s32.cpp index 7b73459ec2..a8e2a4e8f7 100644 --- a/src/backend/opencl/kernel/convolve/conv2_s32.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_s32.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(int, float) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_s64.cpp b/src/backend/opencl/kernel/convolve/conv2_s64.cpp index 39a06ae060..408b3a0df3 100644 --- a/src/backend/opencl/kernel/convolve/conv2_s64.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_s64.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(intl, float) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_u16.cpp b/src/backend/opencl/kernel/convolve/conv2_u16.cpp index 8404825a23..26f46ae7d5 100644 --- a/src/backend/opencl/kernel/convolve/conv2_u16.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_u16.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(ushort, float) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_u32.cpp b/src/backend/opencl/kernel/convolve/conv2_u32.cpp index 2dd7dfe3a4..6c87a7fbb2 100644 --- a/src/backend/opencl/kernel/convolve/conv2_u32.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_u32.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(uint, float) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_u64.cpp b/src/backend/opencl/kernel/convolve/conv2_u64.cpp index 7c40aac13f..717b331628 100644 --- a/src/backend/opencl/kernel/convolve/conv2_u64.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_u64.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(uintl, float) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv2_u8.cpp b/src/backend/opencl/kernel/convolve/conv2_u8.cpp index 4c0d2580a5..37f2e7f4cb 100644 --- a/src/backend/opencl/kernel/convolve/conv2_u8.cpp +++ b/src/backend/opencl/kernel/convolve/conv2_u8.cpp @@ -15,6 +15,6 @@ namespace kernel { INSTANTIATE(uchar, float) -} +} // namespace kernel } // namespace opencl diff --git a/src/backend/opencl/kernel/convolve/conv_common.hpp b/src/backend/opencl/kernel/convolve/conv_common.hpp index f71f5ee0e1..7380f7dc1e 100644 --- a/src/backend/opencl/kernel/convolve/conv_common.hpp +++ b/src/backend/opencl/kernel/convolve/conv_common.hpp @@ -112,8 +112,8 @@ void convNHelper(const conv_kparam_t& param, Param& out, const Param& signal, << " -D BASE_DIM=" << bDim << " -D EXPAND=" << expand << " -D " << binOpName(); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D CPLX=1"; } else { options << " -D CPLX=0"; diff --git a/src/backend/opencl/kernel/convolve_separable.cpp b/src/backend/opencl/kernel/convolve_separable.cpp index e5b051f12e..cc5c20aaba 100644 --- a/src/backend/opencl/kernel/convolve_separable.cpp +++ b/src/backend/opencl/kernel/convolve_separable.cpp @@ -66,8 +66,8 @@ void convSep(Param out, const Param signal, const Param filter) { << " -D FLEN=" << fLen << " -D LOCAL_MEM_SIZE=" << locSize << " -D " << binOpName(); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D CPLX=1"; } else { options << " -D CPLX=0"; diff --git a/src/backend/opencl/kernel/fftconvolve.hpp b/src/backend/opencl/kernel/fftconvolve.hpp index ac24c432d3..7494fc92dd 100644 --- a/src/backend/opencl/kernel/fftconvolve.hpp +++ b/src/backend/opencl/kernel/fftconvolve.hpp @@ -83,9 +83,10 @@ void packDataHelper(Param packed, Param sig, Param filter, const int baseDim, options << " -D T=" << dtype_traits::getName(); - if ((af_dtype)dtype_traits::af_type == c32) { + if (static_cast(dtype_traits::af_type) == c32) { options << " -D CONVT=float"; - } else if ((af_dtype)dtype_traits::af_type == c64 && isDouble) { + } else if (static_cast(dtype_traits::af_type) == c64 && + isDouble) { options << " -D CONVT=double" << " -D USE_DOUBLE"; } @@ -140,9 +141,10 @@ void packDataHelper(Param packed, Param sig, Param filter, const int baseDim, options << " -D T=" << dtype_traits::getName(); - if ((af_dtype)dtype_traits::af_type == c32) { + if (static_cast(dtype_traits::af_type) == c32) { options << " -D CONVT=float"; - } else if ((af_dtype)dtype_traits::af_type == c64 && isDouble) { + } else if (static_cast(dtype_traits::af_type) == c64 && + isDouble) { options << " -D CONVT=double" << " -D USE_DOUBLE"; } @@ -189,9 +191,10 @@ void complexMultiplyHelper(Param packed, Param sig, Param filter, << " -D AF_BATCH_RHS=" << (int)AF_BATCH_RHS << " -D AF_BATCH_SAME=" << (int)AF_BATCH_SAME; - if ((af_dtype)dtype_traits::af_type == c32) { + if (static_cast(dtype_traits::af_type) == c32) { options << " -D CONVT=float"; - } else if ((af_dtype)dtype_traits::af_type == c64 && isDouble) { + } else if (static_cast(dtype_traits::af_type) == c64 && + isDouble) { options << " -D CONVT=double" << " -D USE_DOUBLE"; } @@ -251,9 +254,10 @@ void reorderOutputHelper(Param out, Param packed, Param sig, Param filter, << " -D ROUND_OUT=" << (int)roundOut << " -D EXPAND=" << (int)expand; - if ((af_dtype)dtype_traits::af_type == c32) { + if (static_cast(dtype_traits::af_type) == c32) { options << " -D CONVT=float"; - } else if ((af_dtype)dtype_traits::af_type == c64 && isDouble) { + } else if (static_cast(dtype_traits::af_type) == c64 && + isDouble) { options << " -D CONVT=double" << " -D USE_DOUBLE"; } diff --git a/src/backend/opencl/kernel/gradient.hpp b/src/backend/opencl/kernel/gradient.hpp index 0fd5473937..19cf0ac7c1 100644 --- a/src/backend/opencl/kernel/gradient.hpp +++ b/src/backend/opencl/kernel/gradient.hpp @@ -48,8 +48,8 @@ void gradient(Param grad0, Param grad1, const Param in) { options << " -D T=" << dtype_traits::getName() << " -D TX=" << TX << " -D TY=" << TY << " -D ZERO=" << toNumStr(scalar(0)); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D CPLX=1"; } else { options << " -D CPLX=0"; diff --git a/src/backend/opencl/kernel/ireduce.hpp b/src/backend/opencl/kernel/ireduce.hpp index 145171ad3d..106b600aa4 100644 --- a/src/backend/opencl/kernel/ireduce.hpp +++ b/src/backend/opencl/kernel/ireduce.hpp @@ -326,20 +326,21 @@ T ireduce_all(uint *loc, Param in) { cl::Buffer *tidx = bufferAlloc(tmp_elements * sizeof(uint)); Param rlen; - rlen.data = new cl::Buffer(); + auto buff = std::make_unique(); + rlen.data = buff.get(); ireduce_first_launcher(tmp, tidx, in, tidx, threads_x, true, groups_x, groups_y, rlen); - unique_ptr h_ptr(new T[tmp_elements]); - unique_ptr h_iptr(new uint[tmp_elements]); + std::vector h_ptr(tmp_elements); + std::vector h_iptr(tmp_elements); getQueue().enqueueReadBuffer(*tmp.get(), CL_TRUE, 0, - sizeof(T) * tmp_elements, h_ptr.get()); - getQueue().enqueueReadBuffer(*tidx, CL_TRUE, 0, - sizeof(uint) * tmp_elements, h_iptr.get()); + sizeof(T) * tmp_elements, h_ptr.data()); + getQueue().enqueueReadBuffer( + *tidx, CL_TRUE, 0, sizeof(uint) * tmp_elements, h_iptr.data()); - T *h_ptr_raw = h_ptr.get(); - uint *h_iptr_raw = h_iptr.get(); + T *h_ptr_raw = h_ptr.data(); + uint *h_iptr_raw = h_iptr.data(); if (!is_linear) { // Converting n-d index into a linear index diff --git a/src/backend/opencl/kernel/resize.hpp b/src/backend/opencl/kernel/resize.hpp index 3095eb562e..bc16d9ae18 100644 --- a/src/backend/opencl/kernel/resize.hpp +++ b/src/backend/opencl/kernel/resize.hpp @@ -55,8 +55,8 @@ void resize(Param out, const Param in) { default: break; } - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D CPLX=1"; options << " -D TB=" << dtype_traits::getName(); } else { diff --git a/src/backend/opencl/kernel/rotate.hpp b/src/backend/opencl/kernel/rotate.hpp index c69c9fa502..bc11a35b25 100644 --- a/src/backend/opencl/kernel/rotate.hpp +++ b/src/backend/opencl/kernel/rotate.hpp @@ -63,8 +63,8 @@ void rotate(Param out, const Param in, const float theta, options << " -D InterpValTy=" << dtype_traits>::getName(); options << " -D InterpPosTy=" << dtype_traits>::getName(); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D IS_CPLX=1"; options << " -D TB=" << dtype_traits::getName(); } else { diff --git a/src/backend/opencl/kernel/sparse_arith.hpp b/src/backend/opencl/kernel/sparse_arith.hpp index a1b7445ddc..14936b99b2 100644 --- a/src/backend/opencl/kernel/sparse_arith.hpp +++ b/src/backend/opencl/kernel/sparse_arith.hpp @@ -60,8 +60,8 @@ void sparseArithOpCSR(Param out, const Param values, const Param rowIdx, options << " -D T=" << dtype_traits::getName(); options << " -D OP=" << getOpString(); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D IS_CPLX=1"; } else { options << " -D IS_CPLX=0"; @@ -113,8 +113,8 @@ void sparseArithOpCOO(Param out, const Param values, const Param rowIdx, options << " -D T=" << dtype_traits::getName(); options << " -D OP=" << getOpString(); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D IS_CPLX=1"; } else { options << " -D IS_CPLX=0"; @@ -166,8 +166,8 @@ void sparseArithOpCSR(Param values, Param rowIdx, Param colIdx, const Param rhs, options << " -D T=" << dtype_traits::getName(); options << " -D OP=" << getOpString(); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D IS_CPLX=1"; } else { options << " -D IS_CPLX=0"; @@ -218,8 +218,8 @@ void sparseArithOpCOO(Param values, Param rowIdx, Param colIdx, const Param rhs, options << " -D T=" << dtype_traits::getName(); options << " -D OP=" << getOpString(); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D IS_CPLX=1"; } else { options << " -D IS_CPLX=0"; diff --git a/src/backend/opencl/kernel/transform.hpp b/src/backend/opencl/kernel/transform.hpp index 9adc9d08ba..b42a94d446 100644 --- a/src/backend/opencl/kernel/transform.hpp +++ b/src/backend/opencl/kernel/transform.hpp @@ -65,8 +65,8 @@ void transform(Param out, const Param in, const Param tf, bool isInverse, options << " -D InterpValTy=" << dtype_traits>::getName(); options << " -D InterpPosTy=" << dtype_traits>::getName(); - if ((af_dtype)dtype_traits::af_type == c32 || - (af_dtype)dtype_traits::af_type == c64) { + if (static_cast(dtype_traits::af_type) == c32 || + static_cast(dtype_traits::af_type) == c64) { options << " -D IS_CPLX=1"; options << " -D TB=" << dtype_traits::getName(); } else { diff --git a/src/backend/opencl/lookup.cpp b/src/backend/opencl/lookup.cpp index 692b26b768..ff71368e61 100644 --- a/src/backend/opencl/lookup.cpp +++ b/src/backend/opencl/lookup.cpp @@ -21,11 +21,12 @@ namespace opencl { template Array lookup(const Array &input, const Array &indices, const unsigned dim) { - const dim4 iDims = input.dims(); + const dim4 &iDims = input.dims(); dim4 oDims(1); - for (int d = 0; d < 4; ++d) + for (int d = 0; d < 4; ++d) { oDims[d] = (d == int(dim) ? indices.elements() : iDims[d]); + } Array out = createEmptyArray(oDims); @@ -34,6 +35,7 @@ Array lookup(const Array &input, const Array &indices, case 1: kernel::lookup(out, input, indices); break; case 2: kernel::lookup(out, input, indices); break; case 3: kernel::lookup(out, input, indices); break; + default: AF_ERROR("dim only supports values 0-3.", AF_ERR_UNKNOWN); } return out; diff --git a/src/backend/opencl/lu.cpp b/src/backend/opencl/lu.cpp index 3c99dfd392..a06fc90939 100644 --- a/src/backend/opencl/lu.cpp +++ b/src/backend/opencl/lu.cpp @@ -71,7 +71,7 @@ Array lu_inplace(Array &in, const bool convert_pivot) { magma_getrf_gpu(M, N, (*in_buf)(), in.getOffset(), in.strides()[1], &ipiv[0], getQueue()(), &info); - if (!convert_pivot) return createHostDataArray(dim4(MN), &ipiv[0]); + if (!convert_pivot) { return createHostDataArray(dim4(MN), &ipiv[0]); } Array pivot = convertPivot(&ipiv[0], MN, M); return pivot; diff --git a/src/backend/opencl/magma/gebrd.cpp b/src/backend/opencl/magma/gebrd.cpp index 57bd505c31..4e88a498ae 100644 --- a/src/backend/opencl/magma/gebrd.cpp +++ b/src/backend/opencl/magma/gebrd.cpp @@ -190,7 +190,7 @@ magma_int_t magma_gebrd_hybrid(magma_int_t m, magma_int_t n, Ty *a, the vector defining G(i). ===================================================================== */ - typedef typename af::dtype_traits::base_type Tr; + using Tr = typename af::dtype_traits::base_type; Tr *d = (Tr *)_d; Tr *e = (Tr *)_e; @@ -228,8 +228,9 @@ magma_int_t magma_gebrd_hybrid(magma_int_t m, magma_int_t n, Ty *a, if (*info < 0) { // magma_xerbla(__func__, -(*info)); return *info; - } else if (lquery) + } else if (lquery) { return *info; + } /* Quick return if possible */ minmn = std::min(m, n); diff --git a/src/backend/opencl/magma/geqrf2.cpp b/src/backend/opencl/magma/geqrf2.cpp index 29dc4cf94c..2d09f0ba60 100644 --- a/src/backend/opencl/magma/geqrf2.cpp +++ b/src/backend/opencl/magma/geqrf2.cpp @@ -210,7 +210,7 @@ magma_int_t magma_geqrf2_gpu(magma_int_t m, magma_int_t n, cl_mem dA, } k = std::min(m, n); - if (k == 0) return *info; + if (k == 0) { return *info; } nb = magma_get_geqrf_nb(m); diff --git a/src/backend/opencl/magma/geqrf3.cpp b/src/backend/opencl/magma/geqrf3.cpp index 40bfd875db..ced1e01f4a 100644 --- a/src/backend/opencl/magma/geqrf3.cpp +++ b/src/backend/opencl/magma/geqrf3.cpp @@ -193,7 +193,7 @@ magma_int_t magma_geqrf3_gpu(magma_int_t m, magma_int_t n, cl_mem dA, } k = minmn = std::min(m, n); - if (k == 0) return *info; + if (k == 0) { return *info; } nb = magma_get_geqrf_nb(m); @@ -252,7 +252,7 @@ magma_int_t magma_geqrf3_gpu(magma_int_t m, magma_int_t n, cl_mem dA, /* Put 0s in the upper triangular part of a panel (and 1s on the diagonal); copy the upper triangular in ut and invert it. */ - if (i > 0) magma_event_sync(event[0]); + if (i > 0) { magma_event_sync(event[0]); } // Change me split_diag_block(ib, work_ref(i), ldwork, ut); magma_setmatrix(rows, ib, work_ref(i), ldwork, a_ref(i, i), diff --git a/src/backend/opencl/magma/getrf.cpp b/src/backend/opencl/magma/getrf.cpp index f8b756e61b..4fa3960791 100644 --- a/src/backend/opencl/magma/getrf.cpp +++ b/src/backend/opencl/magma/getrf.cpp @@ -130,12 +130,13 @@ magma_int_t magma_getrf_gpu(magma_int_t m, magma_int_t n, cl_mem dA, /* Check arguments */ *info = 0; - if (m < 0) + if (m < 0) { *info = -1; - else if (n < 0) + } else if (n < 0) { *info = -2; - else if (ldda < std::max(1, m)) + } else if (ldda < std::max(1, m)) { *info = -4; + } if (*info != 0) { // magma_xerbla(__func__, -(*info)); @@ -143,7 +144,7 @@ magma_int_t magma_getrf_gpu(magma_int_t m, magma_int_t n, cl_mem dA, } /* Quick return if possible */ - if (m == 0 || n == 0) return *info; + if (m == 0 || n == 0) { return *info; } gpu_blas_gemm_func gpu_blas_gemm; gpu_blas_trsm_func gpu_blas_trsm; @@ -196,7 +197,7 @@ magma_int_t magma_getrf_gpu(magma_int_t m, magma_int_t n, cl_mem dA, ldwork = maxm; if (MAGMA_SUCCESS != magma_malloc_cpu(&work, ldwork * nb)) { magma_free(dAP); - if (dA != dAT) magma_free(dAT); + if (dA != dAT) { magma_free(dAT); } *info = MAGMA_ERR_HOST_ALLOC; return *info; @@ -232,7 +233,7 @@ magma_int_t magma_getrf_gpu(magma_int_t m, magma_int_t n, cl_mem dA, rows = m - j * nb; LAPACKE_CHECK( cpu_lapack_getrf(rows, nb, work, ldwork, ipiv + j * nb)); - if (*info == 0 && iinfo > 0) *info = iinfo + j * nb; + if (*info == 0 && iinfo > 0) { *info = iinfo + j * nb; } for (i = j * nb; i < j * nb + nb; ++i) { ipiv[i] += j * nb; } magmablas_laswp(n, dAT(0, 0), lddat, j * nb + 1, j * nb + nb, @@ -291,7 +292,7 @@ magma_int_t magma_getrf_gpu(magma_int_t m, magma_int_t n, cl_mem dA, // do the cpu part LAPACKE_CHECK( cpu_lapack_getrf(rows, nb0, work, ldwork, ipiv + s * nb)); - if (*info == 0 && iinfo > 0) *info = iinfo + s * nb; + if (*info == 0 && iinfo > 0) { *info = iinfo + s * nb; } for (i = s * nb; i < s * nb + nb0; ++i) { ipiv[i] += s * nb; } magmablas_laswp(n, dAT(0, 0), lddat, s * nb + 1, s * nb + nb0, diff --git a/src/backend/opencl/magma/getrs.cpp b/src/backend/opencl/magma/getrs.cpp index 829b909d2d..1f4578db6b 100644 --- a/src/backend/opencl/magma/getrs.cpp +++ b/src/backend/opencl/magma/getrs.cpp @@ -245,7 +245,7 @@ magma_int_t magma_getrs_gpu(magma_trans_t trans, magma_int_t n, magma_setmatrix(n, nrhs, work, n, dB, dB_offset, lddb, queue); } - if (nrhs > 1 && dAT != 0) magma_free(dAT); + if (nrhs > 1 && dAT != 0) { magma_free(dAT); } magma_free_cpu(work); return *info; } diff --git a/src/backend/opencl/magma/labrd.cpp b/src/backend/opencl/magma/labrd.cpp index ed566f7956..010a3675a7 100644 --- a/src/backend/opencl/magma/labrd.cpp +++ b/src/backend/opencl/magma/labrd.cpp @@ -201,7 +201,7 @@ magma_int_t magma_labrd_gpu(magma_int_t m, magma_int_t n, magma_int_t nb, Ty *a, of the vector defining G(i). ===================================================================== */ - typedef typename af::dtype_traits::base_type Tr; + using Tr = typename af::dtype_traits::base_type; constexpr bool is_cplx = common::is_complex::value; @@ -216,7 +216,7 @@ magma_int_t magma_labrd_gpu(magma_int_t m, magma_int_t n, magma_int_t nb, Ty *a, magma_int_t a_dim1, a_offset, x_dim1, x_offset, y_dim1, y_offset, i__2, i__3; magma_int_t i__; - Ty alpha; + Ty alpha{}; a_dim1 = lda; a_offset = 1 + a_dim1; diff --git a/src/backend/opencl/magma/larfb.cpp b/src/backend/opencl/magma/larfb.cpp index abb8d7a60f..b7513bd971 100644 --- a/src/backend/opencl/magma/larfb.cpp +++ b/src/backend/opencl/magma/larfb.cpp @@ -237,10 +237,11 @@ magma_int_t magma_larfb_gpu(magma_side_t side, magma_trans_t trans, // whether T is upper or lower triangular OPENCL_BLAS_TRIANGLE_T uplo; - if (direct == MagmaForward) + if (direct == MagmaForward) { uplo = OPENCL_BLAS_TRIANGLE_UPPER; - else + } else { uplo = OPENCL_BLAS_TRIANGLE_LOWER; + } // whether V is stored transposed or not OPENCL_BLAS_TRANS_T notransV, transV; diff --git a/src/backend/opencl/magma/laset.cpp b/src/backend/opencl/magma/laset.cpp index 5af6d859e7..a08b7af2fa 100644 --- a/src/backend/opencl/magma/laset.cpp +++ b/src/backend/opencl/magma/laset.cpp @@ -61,14 +61,15 @@ void magmablas_laset(magma_uplo_t uplo, magma_int_t m, magma_int_t n, T offdiag, T diag, cl_mem dA, size_t dA_offset, magma_int_t ldda, magma_queue_t queue) { magma_int_t info = 0; - if (uplo != MagmaLower && uplo != MagmaUpper && uplo != MagmaFull) + if (uplo != MagmaLower && uplo != MagmaUpper && uplo != MagmaFull) { info = -1; - else if (m < 0) + } else if (m < 0) { info = -2; - else if (n < 0) + } else if (n < 0) { info = -3; - else if (ldda < std::max(1, m)) + } else if (ldda < std::max(1, m)) { info = -7; + } if (info != 0) { return; // info; diff --git a/src/backend/opencl/magma/laswp.cpp b/src/backend/opencl/magma/laswp.cpp index 62fdaff9c5..53f4cccbea 100644 --- a/src/backend/opencl/magma/laswp.cpp +++ b/src/backend/opencl/magma/laswp.cpp @@ -62,14 +62,15 @@ void magmablas_laswp(magma_int_t n, cl_mem dAT, size_t dAT_offset, const magma_int_t *ipiv, magma_int_t inci, magma_queue_t queue) { magma_int_t info = 0; - if (n < 0) + if (n < 0) { info = -1; - else if (k1 < 1) + } else if (k1 < 1) { info = -4; - else if (k2 < 1) + } else if (k2 < 1) { info = -5; - else if (inci <= 0) + } else if (inci <= 0) { info = -7; + } if (info != 0) { // magma_xerbla( __func__, -(info) ); diff --git a/src/backend/opencl/magma/magma_helper.cpp b/src/backend/opencl/magma/magma_helper.cpp index a05d1d0fe9..19467d2277 100644 --- a/src/backend/opencl/magma/magma_helper.cpp +++ b/src/backend/opencl/magma/magma_helper.cpp @@ -63,11 +63,11 @@ template double magma_real(float val); template double magma_real(double val); template<> double magma_real(magmaFloatComplex val) { - return (double)val.s[0]; + return static_cast(val.s[0]); } template<> double magma_real(magmaDoubleComplex val) { - return (double)val.s[0]; + return static_cast(val.s[0]); } #define INSTANTIATE_CPLX_SCALAR(T) \ @@ -99,60 +99,66 @@ bool magma_is_real() { template magma_int_t magma_get_getrf_nb(magma_int_t m) { - if (m <= 3200) + if (m <= 3200) { return 128; - else if (m < 9000) + } else if (m < 9000) { return 256; - else + } else { return 320; + } } template magma_int_t magma_get_getrf_nb(magma_int_t m); template<> magma_int_t magma_get_getrf_nb(magma_int_t m) { - if (m <= 2048) + if (m <= 2048) { return 64; - else if (m < 7200) + } else if (m < 7200) { return 192; - else + } else { return 256; + } } template<> magma_int_t magma_get_getrf_nb(magma_int_t m) { - if (m <= 2048) + if (m <= 2048) { return 64; - else + } else { return 128; + } } template<> magma_int_t magma_get_getrf_nb(magma_int_t m) { - if (m <= 3072) + if (m <= 3072) { return 32; - else if (m <= 9024) + } else if (m <= 9024) { return 64; - else + } else { return 128; + } } template magma_int_t magma_get_potrf_nb(magma_int_t m) { - if (m <= 1024) + if (m <= 1024) { return 128; - else + } else { return 320; + } } template magma_int_t magma_get_potrf_nb(magma_int_t m); template<> magma_int_t magma_get_potrf_nb(magma_int_t m) { - if (m <= 4256) + if (m <= 4256) { return 128; - else + } else { return 256; + } } template<> @@ -177,28 +183,30 @@ template magma_int_t magma_get_geqrf_nb(magma_int_t m); template<> magma_int_t magma_get_geqrf_nb(magma_int_t m) { - if (m <= 2048) return 64; + if (m <= 2048) { return 64; } return 128; } template<> magma_int_t magma_get_geqrf_nb(magma_int_t m) { - if (m <= 2048) + if (m <= 2048) { return 32; - else if (m <= 4032) + } else if (m <= 4032) { return 64; - else + } else { return 128; + } } template<> magma_int_t magma_get_geqrf_nb(magma_int_t m) { - if (m <= 2048) + if (m <= 2048) { return 32; - else if (m <= 4032) + } else if (m <= 4032) { return 64; - else + } else { return 128; + } } #if defined(__GNUC__) || defined(__GNUG__) @@ -218,7 +226,7 @@ template float magma_make(double r, double i); template double magma_make(double r, double i); template<> magmaFloatComplex magma_make(double r, double i) { - magmaFloatComplex tmp = {(float)r, (float)i}; + magmaFloatComplex tmp = {static_cast(r), static_cast(i)}; return tmp; } template<> diff --git a/src/backend/opencl/magma/transpose.cpp b/src/backend/opencl/magma/transpose.cpp index 5ccc6c3cbe..856679d3ca 100644 --- a/src/backend/opencl/magma/transpose.cpp +++ b/src/backend/opencl/magma/transpose.cpp @@ -60,14 +60,15 @@ void magmablas_transpose(magma_int_t m, magma_int_t n, cl_mem dA, size_t dAT_offset, magma_int_t lddat, magma_queue_t queue) { magma_int_t info = 0; - if (m < 0) + if (m < 0) { info = -1; - else if (n < 0) + } else if (n < 0) { info = -2; - else if (ldda < m) + } else if (ldda < m) { info = -4; - else if (lddat < n) + } else if (lddat < n) { info = -6; + } if (info != 0) { // magma_xerbla( __func__, -(info) ); @@ -75,7 +76,7 @@ void magmablas_transpose(magma_int_t m, magma_int_t n, cl_mem dA, } /* Quick return */ - if ((m == 0) || (n == 0)) return; + if ((m == 0) || (n == 0)) { return; } int idims[] = {m, n, 1, 1}; int odims[] = {n, m, 1, 1}; diff --git a/src/backend/opencl/magma/transpose_inplace.cpp b/src/backend/opencl/magma/transpose_inplace.cpp index d99d727927..040a90ff22 100644 --- a/src/backend/opencl/magma/transpose_inplace.cpp +++ b/src/backend/opencl/magma/transpose_inplace.cpp @@ -58,17 +58,18 @@ template void magmablas_transpose_inplace(magma_int_t n, cl_mem dA, size_t dA_offset, magma_int_t ldda, magma_queue_t queue) { magma_int_t info = 0; - if (n < 0) + if (n < 0) { info = -1; - else if (ldda < n) + } else if (ldda < n) { info = -3; + } if (info != 0) { // magma_xerbla( __func__, -(info) ); return; // info; } - if (n == 0) return; + if (n == 0) { return; } int dims[] = {n, n, 1, 1}; int strides[] = {1, ldda, ldda * n, ldda * n}; diff --git a/src/backend/opencl/magma/unmqr.cpp b/src/backend/opencl/magma/unmqr.cpp index 420c5a3572..81dae4a340 100644 --- a/src/backend/opencl/magma/unmqr.cpp +++ b/src/backend/opencl/magma/unmqr.cpp @@ -296,13 +296,13 @@ magma_int_t magma_unmqr_gpu(magma_side_t side, magma_trans_t trans, jc = i; } - if (mi == 0 || ni == 0) break; + if (mi == 0 || ni == 0) { break; } ret = magma_larfb_gpu( MagmaLeft, is_real ? MagmaTrans : MagmaConjTrans, MagmaForward, MagmaColumnwise, mi, ni, ib, a_ref(i, i), ldda, t_ref(i), nb, c_ref(ic, jc), lddc, dwork, 0, nw, queue); - if (ret != MAGMA_SUCCESS) return ret; + if (ret != MAGMA_SUCCESS) { return ret; } } } else { i = i1; diff --git a/src/backend/opencl/match_template.cpp b/src/backend/opencl/match_template.cpp index c94b42770f..bbe01d5882 100644 --- a/src/backend/opencl/match_template.cpp +++ b/src/backend/opencl/match_template.cpp @@ -26,10 +26,11 @@ Array match_template(const Array &sImg, bool needMean = mType == AF_ZSAD || mType == AF_LSAD || mType == AF_ZSSD || mType == AF_LSSD || mType == AF_ZNCC; - if (needMean) + if (needMean) { kernel::matchTemplate(out, sImg, tImg); - else + } else { kernel::matchTemplate(out, sImg, tImg); + } return out; } diff --git a/src/backend/opencl/math.cpp b/src/backend/opencl/math.cpp index ff445a710a..82f03722f2 100644 --- a/src/backend/opencl/math.cpp +++ b/src/backend/opencl/math.cpp @@ -11,26 +11,26 @@ #include namespace opencl { -bool operator==(cfloat a, cfloat b) { - return (a.s[0] == b.s[0]) && (a.s[1] == b.s[1]); +bool operator==(cfloat lhs, cfloat rhs) { + return (lhs.s[0] == rhs.s[0]) && (lhs.s[1] == rhs.s[1]); } -bool operator!=(cfloat a, cfloat b) { return !(a == b); } -bool operator==(cdouble a, cdouble b) { - return (a.s[0] == b.s[0]) && (a.s[1] == b.s[1]); +bool operator!=(cfloat lhs, cfloat rhs) { return !(lhs == rhs); } +bool operator==(cdouble lhs, cdouble rhs) { + return (lhs.s[0] == rhs.s[0]) && (lhs.s[1] == rhs.s[1]); } -bool operator!=(cdouble a, cdouble b) { return !(a == b); } +bool operator!=(cdouble lhs, cdouble rhs) { return !(lhs == rhs); } -cfloat operator+(cfloat a, cfloat b) { - cfloat res = {{a.s[0] + b.s[0], a.s[1] + b.s[1]}}; +cfloat operator+(cfloat lhs, cfloat rhs) { + cfloat res = {{lhs.s[0] + rhs.s[0], lhs.s[1] + rhs.s[1]}}; return res; } -common::half operator+(common::half a, common::half b) noexcept { - return common::half(static_cast(a) + static_cast(b)); +common::half operator+(common::half lhs, common::half rhs) noexcept { + return common::half(static_cast(lhs) + static_cast(rhs)); } -cdouble operator+(cdouble a, cdouble b) { - cdouble res = {{a.s[0] + b.s[0], a.s[1] + b.s[1]}}; +cdouble operator+(cdouble lhs, cdouble rhs) { + cdouble res = {{lhs.s[0] + rhs.s[0], lhs.s[1] + rhs.s[1]}}; return res; } diff --git a/src/backend/opencl/math.hpp b/src/backend/opencl/math.hpp index 06a728fac4..dd62930678 100644 --- a/src/backend/opencl/math.hpp +++ b/src/backend/opencl/math.hpp @@ -135,16 +135,16 @@ static inline float real(cfloat in) { return in.s[0]; } static inline double imag(cdouble in) { return in.s[1]; } static inline float imag(cfloat in) { return in.s[1]; } -bool operator==(cfloat a, cfloat b); -bool operator!=(cfloat a, cfloat b); -bool operator==(cdouble a, cdouble b); -bool operator!=(cdouble a, cdouble b); -cfloat operator+(cfloat a, cfloat b); -cfloat operator+(cfloat a); -cdouble operator+(cdouble a, cdouble b); -cdouble operator+(cdouble a); -cfloat operator*(cfloat a, cfloat b); -cdouble operator*(cdouble a, cdouble b); +bool operator==(cfloat lhs, cfloat rhs); +bool operator!=(cfloat lhs, cfloat rhs); +bool operator==(cdouble lhs, cdouble rhs); +bool operator!=(cdouble lhs, cdouble rhs); +cfloat operator+(cfloat lhs, cfloat rhs); +cfloat operator+(cfloat lhs); +cdouble operator+(cdouble lhs, cdouble rhs); +cdouble operator+(cdouble lhs); +cfloat operator*(cfloat lhs, cfloat rhs); +cdouble operator*(cdouble lhs, cdouble rhs); common::half operator+(common::half lhs, common::half rhs) noexcept; } // namespace opencl diff --git a/src/backend/opencl/meanshift.cpp b/src/backend/opencl/meanshift.cpp index 5ab1d0ddc1..95257633de 100644 --- a/src/backend/opencl/meanshift.cpp +++ b/src/backend/opencl/meanshift.cpp @@ -20,14 +20,15 @@ template Array meanshift(const Array &in, const float &spatialSigma, const float &chromaticSigma, const unsigned &numIterations, const bool &isColor) { - const dim4 dims = in.dims(); - Array out = createEmptyArray(dims); - if (isColor) + const dim4 &dims = in.dims(); + Array out = createEmptyArray(dims); + if (isColor) { kernel::meanshift(out, in, spatialSigma, chromaticSigma, numIterations); - else + } else { kernel::meanshift(out, in, spatialSigma, chromaticSigma, numIterations); + } return out; } diff --git a/src/backend/opencl/medfilt.cpp b/src/backend/opencl/medfilt.cpp index 72600dcb59..d2ab6674f3 100644 --- a/src/backend/opencl/medfilt.cpp +++ b/src/backend/opencl/medfilt.cpp @@ -22,7 +22,7 @@ Array medfilt1(const Array &in, dim_t w_wid) { ARG_ASSERT(2, (w_wid <= kernel::MAX_MEDFILTER1_LEN)); ARG_ASSERT(2, (w_wid % 2 != 0)); - const dim4 dims = in.dims(); + const dim4 &dims = in.dims(); Array out = createEmptyArray(dims); @@ -37,7 +37,7 @@ Array medfilt2(const Array &in, dim_t w_len, dim_t w_wid) { ARG_ASSERT(2, (w_len <= kernel::MAX_MEDFILTER2_LEN)); ARG_ASSERT(2, (w_len % 2 != 0)); - const dim4 dims = in.dims(); + const dim4 &dims = in.dims(); Array out = createEmptyArray(dims); @@ -49,6 +49,9 @@ Array medfilt2(const Array &in, dim_t w_len, dim_t w_wid) { case 11: kernel::medfilt2(out, in); break; case 13: kernel::medfilt2(out, in); break; case 15: kernel::medfilt2(out, in); break; + default: + AF_ERROR("w_len only supports values 3, 5, 7, 9, 11, 12, and 15.", + AF_ERR_UNKNOWN); } return out; } diff --git a/src/backend/opencl/memory.cpp b/src/backend/opencl/memory.cpp index 782a19b06a..b1051d29ec 100644 --- a/src/backend/opencl/memory.cpp +++ b/src/backend/opencl/memory.cpp @@ -39,7 +39,7 @@ void setMemStepSize(size_t step_bytes) { memoryManager().setMemStepSize(step_bytes); } -size_t getMemStepSize(void) { return memoryManager().getMemStepSize(); } +size_t getMemStepSize() { return memoryManager().getMemStepSize(); } void signalMemoryCleanup() { memoryManager().signalMemoryCleanup(); } @@ -56,8 +56,8 @@ unique_ptr> memAlloc( const size_t &elements) { // TODO: make memAlloc aware of array shapes dim4 dims(elements); - void *ptr = memoryManager().alloc(false, 1, dims.get(), sizeof(T)); - cl::Buffer *buf = static_cast(ptr); + void *ptr = memoryManager().alloc(false, 1, dims.get(), sizeof(T)); + auto *buf = static_cast(ptr); return unique_ptr>(buf, bufferFree); } @@ -70,10 +70,10 @@ void *memAllocUser(const size_t &bytes) { template void memFree(T *ptr) { - return memoryManager().unlock((void *)ptr, false); + return memoryManager().unlock(static_cast(ptr), false); } -void memFreeUser(void *ptr) { memoryManager().unlock((void *)ptr, true); } +void memFreeUser(void *ptr) { memoryManager().unlock(ptr, true); } cl::Buffer *bufferAlloc(const size_t &bytes) { dim4 dims(bytes); @@ -82,15 +82,19 @@ cl::Buffer *bufferAlloc(const size_t &bytes) { } void bufferFree(cl::Buffer *buf) { - return memoryManager().unlock((void *)buf, false); + return memoryManager().unlock(static_cast(buf), false); } -void memLock(const void *ptr) { memoryManager().userLock((void *)ptr); } +void memLock(const void *ptr) { + memoryManager().userLock(const_cast(ptr)); +} -void memUnlock(const void *ptr) { memoryManager().userUnlock((void *)ptr); } +void memUnlock(const void *ptr) { + memoryManager().userUnlock(const_cast(ptr)); +} bool isLocked(const void *ptr) { - return memoryManager().isUserLocked((void *)ptr); + return memoryManager().isUserLocked(const_cast(ptr)); } void deviceMemoryInfo(size_t *alloc_bytes, size_t *alloc_buffers, @@ -109,7 +113,7 @@ T *pinnedAlloc(const size_t &elements) { template void pinnedFree(T *ptr) { - pinnedMemoryManager().unlock((void *)ptr, false); + pinnedMemoryManager().unlock(static_cast(ptr), false); } #define INSTANTIATE(T) \ @@ -140,7 +144,7 @@ void Allocator::shutdown() { try { opencl::setDevice(n); shutdownMemoryManager(); - } catch (AfError err) { + } catch (const AfError &err) { continue; // Do not throw any errors while shutting down } } @@ -153,14 +157,16 @@ size_t Allocator::getMaxMemorySize(int id) { } void *Allocator::nativeAlloc(const size_t bytes) { - auto ptr = (void *)(new cl::Buffer(getContext(), CL_MEM_READ_WRITE, bytes)); + auto ptr = static_cast(new cl::Buffer( + getContext(), CL_MEM_READ_WRITE, // NOLINT(hicpp-signed-bitwise) + bytes)); AF_TRACE("nativeAlloc: {} {}", bytesToString(bytes), ptr); return ptr; } void Allocator::nativeFree(void *ptr) { AF_TRACE("nativeFree: {}", ptr); - delete (cl::Buffer *)ptr; + delete static_cast(ptr); } AllocatorPinned::AllocatorPinned() : pinnedMaps(opencl::getDeviceCount()) { @@ -187,8 +193,7 @@ size_t AllocatorPinned::getMaxMemorySize(int id) { void *AllocatorPinned::nativeAlloc(const size_t bytes) { void *ptr = NULL; - cl::Buffer *buf = - new cl::Buffer(getContext(), CL_MEM_ALLOC_HOST_PTR, bytes); + auto *buf = new cl::Buffer(getContext(), CL_MEM_ALLOC_HOST_PTR, bytes); ptr = getQueue().enqueueMapBuffer(*buf, true, CL_MAP_READ | CL_MAP_WRITE, 0, bytes); AF_TRACE("Pinned::nativeAlloc: {:>7} {}", bytesToString(bytes), ptr); diff --git a/src/backend/opencl/moments.cpp b/src/backend/opencl/moments.cpp index 8074c3ed4e..ef378762e2 100644 --- a/src/backend/opencl/moments.cpp +++ b/src/backend/opencl/moments.cpp @@ -14,10 +14,10 @@ namespace opencl { -static inline int bitCount(int v) { - v = v - ((v >> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >> 2) & 0x33333333); - return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; +static inline unsigned bitCount(unsigned v) { + v = v - ((v >> 1U) & 0x55555555U); + v = (v & 0x33333333U) + ((v >> 2U) & 0x33333333U); + return (((v + (v >> 4U)) & 0xF0F0F0FU) * 0x1010101U) >> 24U; } template diff --git a/src/backend/opencl/nearest_neighbour.cpp b/src/backend/opencl/nearest_neighbour.cpp index f51a7336a1..3945077e68 100644 --- a/src/backend/opencl/nearest_neighbour.cpp +++ b/src/backend/opencl/nearest_neighbour.cpp @@ -24,9 +24,9 @@ template void nearest_neighbour_(Array& idx, Array& dist, const Array& query, const Array& train, const uint dist_dim, const uint n_dist) { - uint sample_dim = (dist_dim == 0) ? 1 : 0; - const dim4 qDims = query.dims(); - const dim4 tDims = train.dims(); + uint sample_dim = (dist_dim == 0) ? 1 : 0; + const dim4& qDims = query.dims(); + const dim4& tDims = train.dims(); const dim4 outDims(n_dist, qDims[sample_dim]); const dim4 distDims(tDims[sample_dim], qDims[sample_dim]); diff --git a/src/backend/opencl/platform.cpp b/src/backend/opencl/platform.cpp index 14a3bb795f..fa1d29c111 100644 --- a/src/backend/opencl/platform.cpp +++ b/src/backend/opencl/platform.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #ifdef OS_MAC #include @@ -68,7 +69,7 @@ using common::memory::MemoryManagerBase; namespace opencl { -static const string get_system(void) { +static string get_system() { string arch = (sizeof(void*) == 4) ? "32-bit " : "64-bit "; return arch + @@ -92,7 +93,7 @@ static inline string& ltrim(string& s) { } static string platformMap(string& platStr) { - typedef map strmap_t; + using strmap_t = map; static const strmap_t platMap = { make_pair("NVIDIA CUDA", "NVIDIA"), make_pair("Intel(R) OpenCL", "INTEL"), @@ -127,8 +128,9 @@ string getDeviceInfo() noexcept { for (auto device : devices) { const Platform platform(device->getInfo()); - string dstr = device->getInfo(); - bool show_braces = ((unsigned)getActiveDeviceId() == nDevices); + string dstr = device->getInfo(); + bool show_braces = + (static_cast(getActiveDeviceId()) == nDevices); string id = (show_braces ? string("[") : "-") + to_string(nDevices) + (show_braces ? string("]") : "-"); @@ -208,7 +210,7 @@ int getDeviceIdFromNativeId(cl_device_id id) { int nDevices = devMngr.mDevices.size(); int devId = 0; for (devId = 0; devId < nDevices; ++devId) { - if (id == devMngr.mDevices[devId]->operator()()) break; + if (id == devMngr.mDevices[devId]->operator()()) { break; } } return devId; @@ -256,7 +258,7 @@ CommandQueue& getQueue() { const cl::Device& getDevice(int id) { device_id_t& devId = tlocalActiveDeviceId(); - if (id == -1) id = get<1>(devId); + if (id == -1) { id = get<1>(devId); } DeviceManager& devMngr = DeviceManager::getInstance(); @@ -280,8 +282,8 @@ size_t getDeviceMemorySize(int device) { size_t getHostMemorySize() { return common::getHostMemorySize(); } cl_device_type getDeviceType() { - cl::Device device = getDevice(); - cl_device_type type = device.getInfo(); + const cl::Device& device = getDevice(); + cl_device_type type = device.getInfo(); return type; } @@ -292,7 +294,7 @@ bool isHostUnifiedMemory(const cl::Device& device) { bool OpenCLCPUOffload(bool forceOffloadOSX) { static const bool offloadEnv = getEnvVar("AF_OPENCL_CPU_OFFLOAD") != "0"; bool offload = false; - if (offloadEnv) offload = isHostUnifiedMemory(getDevice()); + if (offloadEnv) { offload = isHostUnifiedMemory(getDevice()); } #if OS_MAC // FORCED OFFLOAD FOR LAPACK FUNCTIONS ON OSX UNIFIED MEMORY DEVICES // @@ -353,16 +355,17 @@ bool isHalfSupported(int device) { clGetDeviceInfo(dev(), CL_DEVICE_HALF_FP_CONFIG, sizeof(cl_device_fp_config), &config, &ret_size); - if (err) + if (err) { return false; - else + } else { return config > 0; + } } void devprop(char* d_name, char* d_platform, char* d_toolkit, char* d_compute) { - unsigned nDevices = 0; - unsigned currActiveDevId = (unsigned)getActiveDeviceId(); - bool devset = false; + unsigned nDevices = 0; + auto currActiveDevId = static_cast(getActiveDeviceId()); + bool devset = false; DeviceManager& devMngr = DeviceManager::getInstance(); @@ -399,19 +402,20 @@ void devprop(char* d_name, char* d_platform, char* d_toolkit, char* d_compute) { snprintf(d_compute, 10, "%s", com_str.c_str()); devset = true; } - if (devset) break; + if (devset) { break; } nDevices++; } - if (devset) break; + if (devset) { break; } } // Sanitize input for (int i = 0; i < 31; i++) { if (d_name[i] == ' ') { - if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') + if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') { d_name[i] = 0; - else + } else { d_name[i] = '_'; + } } } } @@ -421,8 +425,8 @@ int setDevice(int device) { common::lock_guard_t lock(devMngr.deviceMutex); - if (device >= (int)devMngr.mQueues.size() || - device >= (int)DeviceManager::MAX_DEVICES) { + if (device >= static_cast(devMngr.mQueues.size()) || + device >= static_cast(DeviceManager::MAX_DEVICES)) { return -1; } else { int old = getActiveDeviceId(); @@ -449,8 +453,8 @@ void addDeviceContext(cl_device_id dev, cl_context ctx, cl_command_queue que) { { common::lock_guard_t lock(devMngr.deviceMutex); - cl::Device* tDevice = new cl::Device(dev); - cl::Context* tContext = new cl::Context(ctx); + auto* tDevice = new cl::Device(dev); + auto* tContext = new cl::Context(ctx); cl::CommandQueue* tQueue = (que == NULL ? new cl::CommandQueue(*tContext, *tDevice) : new cl::CommandQueue(que)); @@ -514,7 +518,7 @@ void removeDeviceContext(cl_device_id dev, cl_context ctx) { } } - if (deleteIdx < (int)devMngr.mUserDeviceOffset) { + if (deleteIdx < static_cast(devMngr.mUserDeviceOffset)) { AF_ERROR("Cannot pop ArrayFire internal devices", AF_ERR_ARG); } else if (deleteIdx == -1) { AF_ERROR("No matching device found", AF_ERR_ARG); @@ -546,7 +550,7 @@ void removeDeviceContext(cl_device_id dev, cl_context ctx) { // OTHERWISE, update(decrement) the thread local active device ids device_id_t& devId = tlocalActiveDeviceId(); - if (deleteIdx < (int)devId.first) { + if (deleteIdx < static_cast(devId.first)) { device_id_t newVals = make_pair(devId.first - 1, devId.second - 1); devId = newVals; } @@ -589,12 +593,12 @@ MemoryManagerBase& memoryManager() { std::call_once(flag, [&]() { // By default, create an instance of the default memory manager - inst.memManager.reset(new common::DefaultMemoryManager( + inst.memManager = std::make_unique( getDeviceCount(), common::MAX_BUFFERS, - AF_MEM_DEBUG || AF_OPENCL_MEM_DEBUG)); + AF_MEM_DEBUG || AF_OPENCL_MEM_DEBUG); // Set the memory manager's device memory manager std::unique_ptr deviceMemoryManager; - deviceMemoryManager.reset(new opencl::Allocator()); + deviceMemoryManager = std::make_unique(); inst.memManager->setAllocator(std::move(deviceMemoryManager)); inst.memManager->initialize(); }); @@ -609,12 +613,12 @@ MemoryManagerBase& pinnedMemoryManager() { std::call_once(flag, [&]() { // By default, create an instance of the default memory manager - inst.pinnedMemManager.reset(new common::DefaultMemoryManager( + inst.pinnedMemManager = std::make_unique( getDeviceCount(), common::MAX_BUFFERS, - AF_MEM_DEBUG || AF_OPENCL_MEM_DEBUG)); + AF_MEM_DEBUG || AF_OPENCL_MEM_DEBUG); // Set the memory manager's device memory manager std::unique_ptr deviceMemoryManager; - deviceMemoryManager.reset(new opencl::AllocatorPinned()); + deviceMemoryManager = std::make_unique(); inst.pinnedMemManager->setAllocator(std::move(deviceMemoryManager)); inst.pinnedMemManager->initialize(); }); @@ -650,7 +654,7 @@ GraphicsResourceManager& interopManager() { DeviceManager& inst = DeviceManager::getInstance(); call_once(initFlags[id], [&] { - inst.gfxManagers[id].reset(new GraphicsResourceManager()); + inst.gfxManagers[id] = std::make_unique(); }); return *(inst.gfxManagers[id].get()); @@ -679,7 +683,7 @@ void removeKernelFromCache(int device, const string& key) { kc_entry_t kernelCache(int device, const string& key) { kc_t& cache = getKernelCache(device); - kc_t::iterator iter = cache.find(key); + auto iter = cache.find(key); return (iter == cache.end() ? kc_entry_t{0, 0} : iter->second); } @@ -690,7 +694,7 @@ using namespace opencl; af_err afcl_get_device_type(afcl_device_type* res) { try { - *res = (afcl_device_type)getActiveDeviceType(); + *res = static_cast(getActiveDeviceType()); } CATCHALL; return AF_SUCCESS; @@ -698,7 +702,7 @@ af_err afcl_get_device_type(afcl_device_type* res) { af_err afcl_get_platform(afcl_platform* res) { try { - *res = (afcl_platform)getActivePlatform(); + *res = static_cast(getActivePlatform()); } CATCHALL; return AF_SUCCESS; @@ -707,7 +711,7 @@ af_err afcl_get_platform(afcl_platform* res) { af_err afcl_get_context(cl_context* ctx, const bool retain) { try { *ctx = getContext()(); - if (retain) clRetainContext(*ctx); + if (retain) { clRetainContext(*ctx); } } CATCHALL; return AF_SUCCESS; @@ -716,7 +720,7 @@ af_err afcl_get_context(cl_context* ctx, const bool retain) { af_err afcl_get_queue(cl_command_queue* queue, const bool retain) { try { *queue = getQueue()(); - if (retain) clRetainCommandQueue(*queue); + if (retain) { clRetainCommandQueue(*queue); } } CATCHALL; return AF_SUCCESS; diff --git a/src/backend/opencl/platform.hpp b/src/backend/opencl/platform.hpp index 5ab5249e93..5aeff25598 100644 --- a/src/backend/opencl/platform.hpp +++ b/src/backend/opencl/platform.hpp @@ -96,9 +96,9 @@ std::string getPlatformName(const cl::Device& device); int setDevice(int device); -void addDeviceContext(cl_device_id dev, cl_context cxt, cl_command_queue que); +void addDeviceContext(cl_device_id dev, cl_context ctx, cl_command_queue que); -void setDeviceContext(cl_device_id dev, cl_context cxt); +void setDeviceContext(cl_device_id dev, cl_context ctx); void removeDeviceContext(cl_device_id dev, cl_context ctx); diff --git a/src/backend/opencl/plot.cpp b/src/backend/opencl/plot.cpp index 00da7e2bde..bf4a1e7370 100644 --- a/src/backend/opencl/plot.cpp +++ b/src/backend/opencl/plot.cpp @@ -53,7 +53,8 @@ void copy_plot(const Array &P, fg_plot plot) { CheckGL("Begin OpenCL fallback-resource copy"); glBindBuffer(GL_ARRAY_BUFFER, buffer); - GLubyte *ptr = (GLubyte *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + auto *ptr = + static_cast(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); if (ptr) { getQueue().enqueueReadBuffer(*P.get(), CL_TRUE, 0, bytes, ptr); glUnmapBuffer(GL_ARRAY_BUFFER); diff --git a/src/backend/opencl/program.cpp b/src/backend/opencl/program.cpp index 586d2b3e33..e252fc0c4d 100644 --- a/src/backend/opencl/program.cpp +++ b/src/backend/opencl/program.cpp @@ -11,6 +11,7 @@ #include #include #include +#include using cl::Buffer; using cl::EnqueueArgs; @@ -20,32 +21,32 @@ using cl::Program; using std::string; namespace opencl { -const static std::string DEFAULT_MACROS_STR( - "\n\ - #ifdef USE_DOUBLE\n\ - #pragma OPENCL EXTENSION cl_khr_fp64 : enable\n\ - #endif\n \ - #ifdef USE_HALF\n\ - #pragma OPENCL EXTENSION cl_khr_fp16 : enable\n\ - #else\n \ - #define half short\n \ - #endif\n \ - #ifndef M_PI\n \ - #define M_PI 3.1415926535897932384626433832795028841971693993751058209749445923078164\n \ - #endif\n \ - "); + void buildProgram(cl::Program &prog, const char *ker_str, const int ker_len, - std::string options) { + const std::string &options) { buildProgram(prog, 1, &ker_str, &ker_len, options); } void buildProgram(cl::Program &prog, const int num_files, const char **ker_strs, - const int *ker_lens, std::string options) { + const int *ker_lens, const std::string &options) { try { - Program::Sources setSrc; - setSrc.emplace_back(DEFAULT_MACROS_STR.c_str(), - DEFAULT_MACROS_STR.length()); - setSrc.emplace_back(KParam_hpp, KParam_hpp_len); + constexpr char kernel_header[] = + R"jit(#ifdef USE_DOUBLE +#pragma OPENCL EXTENSION cl_khr_fp64 : enable +#endif +#ifdef USE_HALF +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#else +#define half short +#endif +#ifndef M_PI +#define M_PI 3.1415926535897932384626433832795028841971693993751058209749445923078164 +#endif +)jit"; + + Program::Sources setSrc{ + {kernel_header, std::extent() - 1}, + {KParam_hpp, KParam_hpp_len}}; for (int i = 0; i < num_files; i++) { setSrc.emplace_back(ker_strs[i], ker_lens[i]); @@ -55,8 +56,8 @@ void buildProgram(cl::Program &prog, const int num_files, const char **ker_strs, std::string(" -D dim_t=") + std::string(dtype_traits::getName()); - prog = cl::Program(getContext(), setSrc); - auto device = getDevice(); + prog = cl::Program(getContext(), setSrc); + const auto &device = getDevice(); std::string cl_std = std::string(" -cl-std=CL") + @@ -64,7 +65,6 @@ void buildProgram(cl::Program &prog, const int num_files, const char **ker_strs, // Braces needed to list initialize the vector for the first argument prog.build({device}, (cl_std + defaults + options).c_str()); - } catch (...) { SHOW_BUILD_INFO(prog); throw; diff --git a/src/backend/opencl/program.hpp b/src/backend/opencl/program.hpp index 34eef3b8db..ba2ff9eb4d 100644 --- a/src/backend/opencl/program.hpp +++ b/src/backend/opencl/program.hpp @@ -45,8 +45,8 @@ class Program; namespace opencl { void buildProgram(cl::Program &prog, const char *ker_str, const int ker_len, - std::string options); + const std::string &options); void buildProgram(cl::Program &prog, const int num_files, const char **ker_str, - const int *ker_len, std::string options); + const int *ker_len, const std::string &options); } // namespace opencl diff --git a/src/backend/opencl/qr.hpp b/src/backend/opencl/qr.hpp index 26a877ba5a..b202aec88a 100644 --- a/src/backend/opencl/qr.hpp +++ b/src/backend/opencl/qr.hpp @@ -11,7 +11,7 @@ namespace opencl { template -void qr(Array &q, Array &r, Array &t, const Array &in); +void qr(Array &q, Array &r, Array &t, const Array &orig); template Array qr_inplace(Array &in); diff --git a/src/backend/opencl/random_engine.cpp b/src/backend/opencl/random_engine.cpp index 976b8a7cc2..c112df4196 100644 --- a/src/backend/opencl/random_engine.cpp +++ b/src/backend/opencl/random_engine.cpp @@ -16,7 +16,7 @@ using common::half; namespace opencl { void initMersenneState(Array &state, const uintl seed, - const Array tbl) { + const Array &tbl) { kernel::initMersenneState(*state.get(), *tbl.get(), seed); } diff --git a/src/backend/opencl/random_engine.hpp b/src/backend/opencl/random_engine.hpp index c3a692ec0b..279db75fc1 100644 --- a/src/backend/opencl/random_engine.hpp +++ b/src/backend/opencl/random_engine.hpp @@ -14,10 +14,8 @@ #include namespace opencl { -Array initMersenneState(const uintl seed, Array tbl); - void initMersenneState(Array &state, const uintl seed, - const Array tbl); + const Array &tbl); template Array uniformDistribution(const af::dim4 &dims, diff --git a/src/backend/opencl/range.cpp b/src/backend/opencl/range.cpp index e6b4c76eaf..b98d9ba584 100644 --- a/src/backend/opencl/range.cpp +++ b/src/backend/opencl/range.cpp @@ -27,8 +27,9 @@ Array range(const dim4& dim, const int seq_dim) { _seq_dim = 0; // column wise sequence } - if (_seq_dim < 0 || _seq_dim > 3) + if (_seq_dim < 0 || _seq_dim > 3) { AF_ERROR("Invalid rep selection", AF_ERR_ARG); + } Array out = createEmptyArray(dim); kernel::range(out, _seq_dim); diff --git a/src/backend/opencl/regions.cpp b/src/backend/opencl/regions.cpp index 9229d0005e..82d287508d 100644 --- a/src/backend/opencl/regions.cpp +++ b/src/backend/opencl/regions.cpp @@ -19,7 +19,7 @@ namespace opencl { template Array regions(const Array &in, af_connectivity connectivity) { - const af::dim4 dims = in.dims(); + const af::dim4 &dims = in.dims(); Array out = createEmptyArray(dims); diff --git a/src/backend/opencl/reorder.cpp b/src/backend/opencl/reorder.cpp index 637654d49d..720d415883 100644 --- a/src/backend/opencl/reorder.cpp +++ b/src/backend/opencl/reorder.cpp @@ -19,9 +19,9 @@ using common::half; namespace opencl { template Array reorder(const Array &in, const af::dim4 &rdims) { - const af::dim4 iDims = in.dims(); + const af::dim4 &iDims = in.dims(); af::dim4 oDims(0); - for (int i = 0; i < 4; i++) oDims[i] = iDims[rdims[i]]; + for (int i = 0; i < 4; i++) { oDims[i] = iDims[rdims[i]]; } Array out = createEmptyArray(oDims); diff --git a/src/backend/opencl/resize.cpp b/src/backend/opencl/resize.cpp index 4bb68a6a64..a911bacc6a 100644 --- a/src/backend/opencl/resize.cpp +++ b/src/backend/opencl/resize.cpp @@ -17,7 +17,7 @@ namespace opencl { template Array resize(const Array &in, const dim_t odim0, const dim_t odim1, const af_interp_type method) { - const af::dim4 iDims = in.dims(); + const af::dim4 &iDims = in.dims(); af::dim4 oDims(odim0, odim1, iDims[2], iDims[3]); Array out = createEmptyArray(oDims); diff --git a/src/backend/opencl/scan.cpp b/src/backend/opencl/scan.cpp index 6b75549773..c21c77badc 100644 --- a/src/backend/opencl/scan.cpp +++ b/src/backend/opencl/scan.cpp @@ -25,15 +25,17 @@ Array scan(const Array& in, const int dim, bool inclusive_scan) { Param In = in; if (inclusive_scan) { - if (dim == 0) + if (dim == 0) { kernel::scan_first(Out, In); - else + } else { kernel::scan_dim(Out, In, dim); + } } else { - if (dim == 0) + if (dim == 0) { kernel::scan_first(Out, In); - else + } else { kernel::scan_dim(Out, In, dim); + } } return out; diff --git a/src/backend/opencl/scan_by_key.cpp b/src/backend/opencl/scan_by_key.cpp index 0e63e52651..9d7cf450a7 100644 --- a/src/backend/opencl/scan_by_key.cpp +++ b/src/backend/opencl/scan_by_key.cpp @@ -27,15 +27,17 @@ Array scan(const Array& key, const Array& in, const int dim, Param In = in; if (inclusive_scan) { - if (dim == 0) + if (dim == 0) { kernel::scan_first(Out, In, Key); - else + } else { kernel::scan_dim(Out, In, Key, dim); + } } else { - if (dim == 0) + if (dim == 0) { kernel::scan_first(Out, In, Key); - else + } else { kernel::scan_dim(Out, In, Key, dim); + } } return out; } diff --git a/src/backend/opencl/select.cpp b/src/backend/opencl/select.cpp index 64006f6218..5a98433372 100644 --- a/src/backend/opencl/select.cpp +++ b/src/backend/opencl/select.cpp @@ -34,9 +34,9 @@ Array createSelectNode(const Array &cond, const Array &a, auto b_node = b.getNode(); int height = max(a_node->getHeight(), b_node->getHeight()); height = max(height, cond_node->getHeight()) + 1; - auto node = make_shared( - NaryNode(dtype_traits::getName(), shortname(true), "__select", 3, - {{cond_node, a_node, b_node}}, (int)af_select_t, height)); + auto node = make_shared(NaryNode( + dtype_traits::getName(), shortname(true), "__select", 3, + {{cond_node, a_node, b_node}}, static_cast(af_select_t), height)); if (detail::passesJitHeuristics(node.get()) == kJITHeuristics::Pass) { return createNodeArray(odims, node); @@ -66,7 +66,7 @@ Array createSelectNode(const Array &cond, const Array &a, auto node = make_shared(NaryNode( dtype_traits::getName(), shortname(true), (flip ? "__not_select" : "__select"), 3, {{cond_node, a_node, b_node}}, - (int)(flip ? af_not_select_t : af_select_t), height)); + static_cast(flip ? af_not_select_t : af_select_t), height)); if (detail::passesJitHeuristics(node.get()) == kJITHeuristics::Pass) { return createNodeArray(odims, node); diff --git a/src/backend/opencl/set.cpp b/src/backend/opencl/set.cpp index 7afb23d95e..cb83765be2 100644 --- a/src/backend/opencl/set.cpp +++ b/src/backend/opencl/set.cpp @@ -56,7 +56,7 @@ Array setUnique(const Array &in, const bool is_sorted) { out.resetDims(dim4(std::distance(begin, end), 1, 1, 1)); return out; - } catch (std::exception &ex) { AF_ERROR(ex.what(), AF_ERR_INTERNAL); } + } catch (const std::exception &ex) { AF_ERROR(ex.what(), AF_ERR_INTERNAL); } } template @@ -94,7 +94,7 @@ Array setUnion(const Array &first, const Array &second, out.resetDims(dim4(std::distance(out_begin, out_end), 1, 1, 1)); return out; - } catch (std::exception &ex) { AF_ERROR(ex.what(), AF_ERR_INTERNAL); } + } catch (const std::exception &ex) { AF_ERROR(ex.what(), AF_ERR_INTERNAL); } } template @@ -132,7 +132,7 @@ Array setIntersect(const Array &first, const Array &second, out.resetDims(dim4(std::distance(out_begin, out_end), 1, 1, 1)); return out; - } catch (std::exception &ex) { AF_ERROR(ex.what(), AF_ERR_INTERNAL); } + } catch (const std::exception &ex) { AF_ERROR(ex.what(), AF_ERR_INTERNAL); } } #define INSTANTIATE(T) \ diff --git a/src/backend/opencl/shift.cpp b/src/backend/opencl/shift.cpp index da86c46cdf..f3e14270c4 100644 --- a/src/backend/opencl/shift.cpp +++ b/src/backend/opencl/shift.cpp @@ -37,15 +37,16 @@ Array shift(const Array &in, const int sdims[4]) { string name_str("Sh"); name_str += shortname(true); - const dim4 iDims = in.dims(); - dim4 oDims = iDims; + const dim4 &iDims = in.dims(); + dim4 oDims = iDims; - array shifts; + array shifts{}; for (int i = 0; i < 4; i++) { // sdims_[i] will always be positive and always [0, oDims[i]]. // Negative shifts are converted to position by going the other way // round - shifts[i] = -(sdims[i] % (int)oDims[i]) + oDims[i] * (sdims[i] > 0); + shifts[i] = -(sdims[i] % static_cast(oDims[i])) + + oDims[i] * (sdims[i] > 0); assert(shifts[i] >= 0 && shifts[i] <= oDims[i]); } diff --git a/src/backend/opencl/sift.cpp b/src/backend/opencl/sift.cpp index 35289495e1..626654c053 100644 --- a/src/backend/opencl/sift.cpp +++ b/src/backend/opencl/sift.cpp @@ -74,14 +74,15 @@ unsigned sift(Array& x_out, Array& y_out, Array& score_out, UNUSED(double_input); UNUSED(img_scale); UNUSED(feature_ratio); - if (compute_GLOH) + if (compute_GLOH) { AF_ERROR( "ArrayFire was not built with nonfree support, GLOH disabled\n", AF_ERR_NONFREE); - else + } else { AF_ERROR( "ArrayFire was not built with nonfree support, SIFT disabled\n", AF_ERR_NONFREE); + } #endif } diff --git a/src/backend/opencl/sort.cpp b/src/backend/opencl/sort.cpp index 08f51faeaf..e73f4db312 100644 --- a/src/backend/opencl/sort.cpp +++ b/src/backend/opencl/sort.cpp @@ -34,7 +34,7 @@ Array sort(const Array &in, const unsigned dim, bool isAscending) { af::dim4 reorderDims(0, 1, 2, 3); reorderDims[dim] = 0; preorderDims[0] = out.dims()[dim]; - for (int i = 1; i <= (int)dim; i++) { + for (int i = 1; i <= static_cast(dim); i++) { reorderDims[i - 1] = i; preorderDims[i] = out.dims()[i - 1]; } diff --git a/src/backend/opencl/sort_by_key.cpp b/src/backend/opencl/sort_by_key.cpp index f6cbb6158c..f98a70e057 100644 --- a/src/backend/opencl/sort_by_key.cpp +++ b/src/backend/opencl/sort_by_key.cpp @@ -39,7 +39,7 @@ void sort_by_key(Array &okey, Array &oval, const Array &ikey, af::dim4 reorderDims(0, 1, 2, 3); reorderDims[dim] = 0; preorderDims[0] = okey.dims()[dim]; - for (int i = 1; i <= (int)dim; i++) { + for (unsigned i = 1; i <= dim; i++) { reorderDims[i - 1] = i; preorderDims[i] = okey.dims()[i - 1]; } @@ -50,7 +50,7 @@ void sort_by_key(Array &okey, Array &oval, const Array &ikey, okey = reorder(okey, reorderDims); oval = reorder(oval, reorderDims); } - } catch (std::exception &ex) { AF_ERROR(ex.what(), AF_ERR_INTERNAL); } + } catch (const std::exception &ex) { AF_ERROR(ex.what(), AF_ERR_INTERNAL); } } #define INSTANTIATE(Tk, Tv) \ diff --git a/src/backend/opencl/sort_index.cpp b/src/backend/opencl/sort_index.cpp index da70519840..869dd7bdc0 100644 --- a/src/backend/opencl/sort_index.cpp +++ b/src/backend/opencl/sort_index.cpp @@ -45,7 +45,7 @@ void sort_index(Array &okey, Array &oval, const Array &in, af::dim4 reorderDims(0, 1, 2, 3); reorderDims[dim] = 0; preorderDims[0] = okey.dims()[dim]; - for (int i = 1; i <= (int)dim; i++) { + for (uint i = 1; i <= dim; i++) { reorderDims[i - 1] = i; preorderDims[i] = okey.dims()[i - 1]; } @@ -56,7 +56,7 @@ void sort_index(Array &okey, Array &oval, const Array &in, okey = reorder(okey, reorderDims); oval = reorder(oval, reorderDims); } - } catch (std::exception &ex) { AF_ERROR(ex.what(), AF_ERR_INTERNAL); } + } catch (const std::exception &ex) { AF_ERROR(ex.what(), AF_ERR_INTERNAL); } } #define INSTANTIATE(T) \ diff --git a/src/backend/opencl/sort_index.hpp b/src/backend/opencl/sort_index.hpp index 5b9560439d..573a61d247 100644 --- a/src/backend/opencl/sort_index.hpp +++ b/src/backend/opencl/sort_index.hpp @@ -11,6 +11,6 @@ namespace opencl { template -void sort_index(Array &val, Array &idx, const Array &in, +void sort_index(Array &okey, Array &oval, const Array &in, const unsigned dim, bool isAscending); } diff --git a/src/backend/opencl/sparse.cpp b/src/backend/opencl/sparse.cpp index c36e950ffe..2e79d558c2 100644 --- a/src/backend/opencl/sparse.cpp +++ b/src/backend/opencl/sparse.cpp @@ -94,9 +94,10 @@ Array sparseConvertCOOToDense(const SparseArray &in) { template Array sparseConvertStorageToDense(const SparseArray &in_) { - if (stype != AF_STORAGE_CSR) + if (stype != AF_STORAGE_CSR) { AF_ERROR("OpenCL Backend only supports CSR or COO to Dense", AF_ERR_NOT_SUPPORTED); + } in_.eval(); @@ -107,11 +108,12 @@ Array sparseConvertStorageToDense(const SparseArray &in_) { const Array &rowIdx = in_.getRowIdx(); const Array &colIdx = in_.getColIdx(); - if (stype == AF_STORAGE_CSR) + if (stype == AF_STORAGE_CSR) { kernel::csr2dense(dense_, values, rowIdx, colIdx); - else + } else { AF_ERROR("OpenCL Backend only supports CSR or COO to Dense", AF_ERR_NOT_SUPPORTED); + } return dense_; } @@ -120,8 +122,8 @@ template SparseArray sparseConvertStorageToStorage(const SparseArray &in) { in.eval(); - SparseArray converted = - createEmptySparseArray(in.dims(), (int)in.getNNZ(), dest); + SparseArray converted = createEmptySparseArray( + in.dims(), static_cast(in.getNNZ()), dest); converted.eval(); if (src == AF_STORAGE_CSR && dest == AF_STORAGE_COO) { diff --git a/src/backend/opencl/sparse_arith.cpp b/src/backend/opencl/sparse_arith.cpp index da376b3ee5..9e7545503d 100644 --- a/src/backend/opencl/sparse_arith.cpp +++ b/src/backend/opencl/sparse_arith.cpp @@ -115,7 +115,7 @@ SparseArray arithOp(const SparseArray &lhs, const SparseArray &rhs) { rhs.eval(); af::storage sfmt = lhs.getStorage(); - const dim4 ldims = lhs.dims(); + const dim4 &ldims = lhs.dims(); const uint M = ldims[0]; const uint N = ldims[1]; diff --git a/src/backend/opencl/surface.cpp b/src/backend/opencl/surface.cpp index 71a78589ab..abec7e6913 100644 --- a/src/backend/opencl/surface.cpp +++ b/src/backend/opencl/surface.cpp @@ -56,7 +56,8 @@ void copy_surface(const Array &P, fg_surface surface) { CheckGL("Begin OpenCL fallback-resource copy"); glBindBuffer(GL_ARRAY_BUFFER, buffer); - GLubyte *ptr = (GLubyte *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + auto *ptr = + static_cast(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); if (ptr) { getQueue().enqueueReadBuffer(*P.get(), CL_TRUE, 0, bytes, ptr); glUnmapBuffer(GL_ARRAY_BUFFER); diff --git a/src/backend/opencl/svd.cpp b/src/backend/opencl/svd.cpp index ffdf69dfb3..2db7b17a5f 100644 --- a/src/backend/opencl/svd.cpp +++ b/src/backend/opencl/svd.cpp @@ -65,9 +65,9 @@ void svd(Array &arrU, Array &arrS, Array &arrVT, Array &arrA, dim4 idims = arrA.dims(); dim4 istrides = arrA.strides(); - const int m = (int)idims[0]; - const int n = (int)idims[1]; - const int ldda = (int)istrides[1]; + const int m = static_cast(idims[0]); + const int n = static_cast(idims[1]); + const int ldda = static_cast(istrides[1]); const int lda = m; const int min_mn = std::min(m, n); const int ldu = m; @@ -92,12 +92,12 @@ void svd(Array &arrU, Array &arrS, Array &arrVT, Array &arrA, static const int ione = 1; static const int izero = 0; - bool iscl = 0; + bool iscl = false; if (anrm > 0. && anrm < smlnum) { - iscl = 1; + iscl = true; scale = scalar(calc_scale(anrm, smlnum)); } else if (anrm > bignum) { - iscl = 1; + iscl = true; scale = scalar(calc_scale(anrm, bignum)); } @@ -109,9 +109,9 @@ void svd(Array &arrU, Array &arrS, Array &arrVT, Array &arrA, // Instead of copying U, S, VT, and A to the host and copying the results // back to the device, create a pointer that's mapped to device memory where // the computation can directly happen - T *mappedA = (T *)getQueue().enqueueMapBuffer( + T *mappedA = static_cast(getQueue().enqueueMapBuffer( *arrA.get(), CL_FALSE, CL_MAP_READ, sizeof(T) * arrA.getOffset(), - sizeof(T) * arrA.elements()); + sizeof(T) * arrA.elements())); std::vector tauq(min_mn), taup(min_mn); std::vector work(lwork); Tr *mappedS0 = (Tr *)getQueue().enqueueMapBuffer( @@ -126,20 +126,20 @@ void svd(Array &arrU, Array &arrS, Array &arrVT, Array &arrA, // (CWorkspace: need 2*N + M, prefer 2*N + (M + N)*NB) // (RWorkspace: need N) magma_gebrd_hybrid(m, n, mappedA, lda, (*arrA.get())(), arrA.getOffset(), - ldda, (void *)mappedS0, (void *)&s1[0], &tauq[0], - &taup[0], &work[0], lwork, getQueue()(), &info, - false); + ldda, (void *)mappedS0, static_cast(&s1[0]), + &tauq[0], &taup[0], &work[0], lwork, getQueue()(), + &info, false); T *mappedU = nullptr, *mappedVT = nullptr; std::vector cdummy(1); if (want_vectors) { - mappedU = (T *)getQueue().enqueueMapBuffer( + mappedU = static_cast(getQueue().enqueueMapBuffer( *arrU.get(), CL_FALSE, CL_MAP_WRITE, sizeof(T) * arrU.getOffset(), - sizeof(T) * arrU.elements()); - mappedVT = (T *)getQueue().enqueueMapBuffer( + sizeof(T) * arrU.elements())); + mappedVT = static_cast(getQueue().enqueueMapBuffer( *arrVT.get(), CL_TRUE, CL_MAP_WRITE, sizeof(T) * arrVT.getOffset(), - sizeof(T) * arrVT.elements()); + sizeof(T) * arrVT.elements())); // If left singular vectors desired in U, copy result to U // and generate left bidiagonalizing vectors in U diff --git a/src/backend/opencl/tile.cpp b/src/backend/opencl/tile.cpp index 5c32c4582c..c3e2604970 100644 --- a/src/backend/opencl/tile.cpp +++ b/src/backend/opencl/tile.cpp @@ -18,8 +18,8 @@ using common::half; namespace opencl { template Array tile(const Array &in, const af::dim4 &tileDims) { - const af::dim4 iDims = in.dims(); - af::dim4 oDims = iDims; + const af::dim4 &iDims = in.dims(); + af::dim4 oDims = iDims; oDims *= tileDims; Array out = createEmptyArray(oDims); diff --git a/src/backend/opencl/topk.cpp b/src/backend/opencl/topk.cpp index 356811ddd5..5795ddd380 100644 --- a/src/backend/opencl/topk.cpp +++ b/src/backend/opencl/topk.cpp @@ -33,7 +33,7 @@ using std::vector; namespace opencl { vector indexForTopK(const int k) { af_index_t idx; - idx.idx.seq = af_seq{0.0, (double)k - 1, 1.0}; + idx.idx.seq = af_seq{0.0, static_cast(k) - 1.0, 1.0}; idx.isSeq = true; idx.isBatch = false; diff --git a/src/backend/opencl/transform.cpp b/src/backend/opencl/transform.cpp index b4b640e71b..57103e9e90 100644 --- a/src/backend/opencl/transform.cpp +++ b/src/backend/opencl/transform.cpp @@ -17,8 +17,8 @@ namespace opencl { template void transform(Array &out, const Array &in, const Array &tf, - const dim4 &odims, const af_interp_type method, - const bool inverse, const bool perspective) { + const af_interp_type method, const bool inverse, + const bool perspective) { switch (method) { case AF_INTERP_NEAREST: case AF_INTERP_LOWER: @@ -38,7 +38,7 @@ void transform(Array &out, const Array &in, const Array &tf, #define INSTANTIATE(T) \ template void transform(Array &out, const Array &in, \ - const Array &tf, const dim4 &odims, \ + const Array &tf, \ const af_interp_type method, const bool inverse, \ const bool perspective); diff --git a/src/backend/opencl/transform.hpp b/src/backend/opencl/transform.hpp index 847271f913..809294fc6f 100644 --- a/src/backend/opencl/transform.hpp +++ b/src/backend/opencl/transform.hpp @@ -12,6 +12,6 @@ namespace opencl { template void transform(Array &out, const Array &in, const Array &tf, - const af::dim4 &odims, const af_interp_type method, - const bool inverse, const bool perspective); + const af_interp_type method, const bool inverse, + const bool perspective); } diff --git a/src/backend/opencl/transpose.cpp b/src/backend/opencl/transpose.cpp index ce1760b26e..1881603dda 100644 --- a/src/backend/opencl/transpose.cpp +++ b/src/backend/opencl/transpose.cpp @@ -20,22 +20,24 @@ namespace opencl { template Array transpose(const Array &in, const bool conjugate) { - const dim4 inDims = in.dims(); - dim4 outDims = dim4(inDims[1], inDims[0], inDims[2], inDims[3]); - Array out = createEmptyArray(outDims); + const dim4 &inDims = in.dims(); + dim4 outDims = dim4(inDims[1], inDims[0], inDims[2], inDims[3]); + Array out = createEmptyArray(outDims); if (conjugate) { if (inDims[0] % kernel::TILE_DIM == 0 && - inDims[1] % kernel::TILE_DIM == 0) + inDims[1] % kernel::TILE_DIM == 0) { kernel::transpose(out, in, getQueue()); - else + } else { kernel::transpose(out, in, getQueue()); + } } else { if (inDims[0] % kernel::TILE_DIM == 0 && - inDims[1] % kernel::TILE_DIM == 0) + inDims[1] % kernel::TILE_DIM == 0) { kernel::transpose(out, in, getQueue()); - else + } else { kernel::transpose(out, in, getQueue()); + } } return out; } diff --git a/src/backend/opencl/transpose_inplace.cpp b/src/backend/opencl/transpose_inplace.cpp index e36dedb0cb..bf3705e290 100644 --- a/src/backend/opencl/transpose_inplace.cpp +++ b/src/backend/opencl/transpose_inplace.cpp @@ -24,16 +24,18 @@ void transpose_inplace(Array &in, const bool conjugate) { if (conjugate) { if (iDims[0] % kernel::TILE_DIM == 0 && - iDims[1] % kernel::TILE_DIM == 0) + iDims[1] % kernel::TILE_DIM == 0) { kernel::transpose_inplace(in, getQueue()); - else + } else { kernel::transpose_inplace(in, getQueue()); + } } else { if (iDims[0] % kernel::TILE_DIM == 0 && - iDims[1] % kernel::TILE_DIM == 0) + iDims[1] % kernel::TILE_DIM == 0) { kernel::transpose_inplace(in, getQueue()); - else + } else { kernel::transpose_inplace(in, getQueue()); + } } } diff --git a/src/backend/opencl/types.cpp b/src/backend/opencl/types.cpp index 775a3936b3..a7d255a987 100644 --- a/src/backend/opencl/types.cpp +++ b/src/backend/opencl/types.cpp @@ -65,7 +65,7 @@ std::string ToNumStr::operator()(half val) { static const char *PINF = "+INFINITY"; static const char *NINF = "-INFINITY"; if (common::isinf(val)) { return val < 0.f ? NINF : PINF; } - return to_string(move(val)); + return common::to_string(val); } template<> diff --git a/src/backend/opencl/vector_field.cpp b/src/backend/opencl/vector_field.cpp index b8e8cd0318..508ff0ded9 100644 --- a/src/backend/opencl/vector_field.cpp +++ b/src/backend/opencl/vector_field.cpp @@ -65,7 +65,8 @@ void copy_vector_field(const Array &points, const Array &directions, // Points glBindBuffer(GL_ARRAY_BUFFER, buff1); - GLubyte *pPtr = (GLubyte *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + auto *pPtr = + static_cast(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); if (pPtr) { getQueue().enqueueReadBuffer(*points.get(), CL_TRUE, 0, size1, pPtr); @@ -75,7 +76,8 @@ void copy_vector_field(const Array &points, const Array &directions, // Directions glBindBuffer(GL_ARRAY_BUFFER, buff2); - GLubyte *dPtr = (GLubyte *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + auto *dPtr = + static_cast(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); if (dPtr) { getQueue().enqueueReadBuffer(*directions.get(), CL_TRUE, 0, size2, dPtr); diff --git a/src/backend/opencl/vector_field.hpp b/src/backend/opencl/vector_field.hpp index 62b5db39c0..2c3447aa4a 100644 --- a/src/backend/opencl/vector_field.hpp +++ b/src/backend/opencl/vector_field.hpp @@ -14,6 +14,5 @@ namespace opencl { template void copy_vector_field(const Array &points, const Array &directions, - fg_vector_field vector_field); - + fg_vector_field vfield); } diff --git a/src/backend/opencl/wrap.cpp b/src/backend/opencl/wrap.cpp index 41e841c5b5..76847e1988 100644 --- a/src/backend/opencl/wrap.cpp +++ b/src/backend/opencl/wrap.cpp @@ -21,17 +21,17 @@ using common::half; namespace opencl { template -void wrap(Array &out, const Array &in, const dim_t ox, const dim_t oy, - const dim_t wx, const dim_t wy, const dim_t sx, const dim_t sy, - const dim_t px, const dim_t py, const bool is_column) { +void wrap(Array &out, const Array &in, const dim_t wx, const dim_t wy, + const dim_t sx, const dim_t sy, const dim_t px, const dim_t py, + const bool is_column) { kernel::wrap(out, in, wx, wy, sx, sy, px, py, is_column); } #define INSTANTIATE(T) \ - template void wrap(Array & out, const Array &in, const dim_t ox, \ - const dim_t oy, const dim_t wx, const dim_t wy, \ - const dim_t sx, const dim_t sy, const dim_t px, \ - const dim_t py, const bool is_column); + template void wrap(Array & out, const Array &in, const dim_t wx, \ + const dim_t wy, const dim_t sx, const dim_t sy, \ + const dim_t px, const dim_t py, \ + const bool is_column); INSTANTIATE(float) INSTANTIATE(double) diff --git a/src/backend/opencl/wrap.hpp b/src/backend/opencl/wrap.hpp index e28cc6e9d8..7a7815caa1 100644 --- a/src/backend/opencl/wrap.hpp +++ b/src/backend/opencl/wrap.hpp @@ -12,9 +12,9 @@ namespace opencl { template -void wrap(Array &out, const Array &in, const dim_t ox, const dim_t oy, - const dim_t wx, const dim_t wy, const dim_t sx, const dim_t sy, - const dim_t px, const dim_t py, const bool is_column); +void wrap(Array &out, const Array &in, const dim_t wx, const dim_t wy, + const dim_t sx, const dim_t sy, const dim_t px, const dim_t py, + const bool is_column); template Array wrap_dilated(const Array &in, const dim_t ox, const dim_t oy,