From cf3818a12a00b63a3070b57f5ca182644dca229b Mon Sep 17 00:00:00 2001 From: Bruce Collie Date: Wed, 7 Feb 2024 12:03:04 +0000 Subject: [PATCH] Enable clang-tidy core guideline checks (#971) This is another PR to enable a greater set of `clang-tidy` checks; as usual it can be reviewed commit-by-commit to see the changes that fix a particular error from the checker (with the exception of https://github.com/runtimeverification/llvm-backend/pull/971/commits/525da5a60f71a10aa13f1e653be80a59e8c78508, which is an enabling refactoring that's big enough to warrant its own separate commit). --- .clang-tidy | 15 ++++- bindings/python/runtime.cpp | 4 +- include/kllvm/codegen/CreateTerm.h | 4 +- include/runtime/header.h | 15 ++++- lib/ast/AST.cpp | 2 +- lib/ast/definition.cpp | 2 +- lib/binary/serializer.cpp | 12 +++- lib/codegen/CreateStaticTerm.cpp | 8 +-- lib/codegen/CreateTerm.cpp | 18 +++--- lib/codegen/Debug.cpp | 20 +++---- lib/codegen/Decision.cpp | 40 ++++++------- lib/codegen/DecisionParser.cpp | 6 +- lib/codegen/EmitConfigParser.cpp | 6 +- lib/parser/KOREParser.cpp | 2 +- runtime/alloc/arena.cpp | 10 +++- runtime/arithmetic/int.cpp | 2 +- runtime/collect/collect.cpp | 14 ++--- runtime/collect/migrate_collection.cpp | 2 +- runtime/io/io.cpp | 20 ++++--- runtime/json/json.cpp | 29 ++++----- runtime/meta/ffi.cpp | 20 ++++--- runtime/meta/substitution.cpp | 2 +- runtime/strings/CMakeLists.txt | 3 + runtime/strings/bytes.cpp | 30 +++++----- runtime/strings/numeric.cpp | 29 ++++----- runtime/strings/strings.cpp | 12 ++-- runtime/util/ConfigurationPrinter.cpp | 68 +++++----------------- runtime/util/ConfigurationSerializer.cpp | 42 +++++++------ runtime/util/match_log.cpp | 6 +- runtime/util/search.cpp | 2 + runtime/util/util.cpp | 4 +- scripts/clang-tidy.sh | 2 +- tools/k-rule-apply/main.cpp | 4 +- tools/k-rule-find/main.cpp | 2 +- tools/kore-convert/main.cpp | 3 +- tools/llvm-kompile-codegen/main.cpp | 2 +- tools/llvm-kompile-gc-stats/CMakeLists.txt | 2 +- tools/llvm-kompile-gc-stats/main.cpp | 32 +++++----- unittests/runtime-collections/lists.cpp | 6 +- 39 files changed, 263 insertions(+), 239 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 4b8a941ee..e7075bb75 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,7 @@ Checks: clang-analyzer-* -clang-analyzer-cplusplus.PlacementNew + -clang-analyzer-optin.cplusplus.UninitializedObject misc-* -misc-no-recursion -misc-unused-parameters @@ -19,7 +20,17 @@ Checks: -bugprone-narrowing-conversions -bugprone-exception-escape -bugprone-implicit-widening-of-multiplication-result - -bugprone-unchecked-optional-access # false positives + -bugprone-unchecked-optional-access + cppcoreguidelines-* + -cppcoreguidelines-avoid-magic-numbers + -cppcoreguidelines-avoid-non-const-global-variables + -cppcoreguidelines-narrowing-conversions + -cppcoreguidelines-no-malloc + -cppcoreguidelines-owning-memory + -cppcoreguidelines-pro-bounds-array-to-pointer-decay + -cppcoreguidelines-pro-bounds-pointer-arithmetic + -cppcoreguidelines-pro-type-cstyle-cast + -cppcoreguidelines-pro-type-union-access WarningsAsErrors: '*' @@ -29,3 +40,5 @@ CheckOptions: value: false - key: 'readability-function-cognitive-complexity.IgnoreMacros' value: true + - key: 'cppcoreguidelines-macro-usage.CheckCapsOnly' + value: true diff --git a/bindings/python/runtime.cpp b/bindings/python/runtime.cpp index 8683734e7..22231e485 100644 --- a/bindings/python/runtime.cpp +++ b/bindings/python/runtime.cpp @@ -81,8 +81,8 @@ void bind_runtime(py::module_ &m) { .def( "serialize", [](block *term, bool emit_size) { - char *data; - size_t size; + char *data = nullptr; + size_t size = 0; serializeConfiguration(term, nullptr, &data, &size, emit_size); return py::bytes(std::string(data, data + size)); }, diff --git a/include/kllvm/codegen/CreateTerm.h b/include/kllvm/codegen/CreateTerm.h index 3f2ec08df..dfd7cccd1 100644 --- a/include/kllvm/codegen/CreateTerm.h +++ b/include/kllvm/codegen/CreateTerm.h @@ -32,8 +32,8 @@ class CreateTerm { KORECompositePattern *constructor, llvm::Value *val, std::string locationStack = "0"); bool populateStaticSet(KOREPattern *pattern); - std::pair - createAllocation(KOREPattern *pattern, std::string locationStack = "0"); + std::pair createAllocation( + KOREPattern *pattern, std::string const &locationStack = "0"); public: CreateTerm( diff --git a/include/runtime/header.h b/include/runtime/header.h index 3eb0450b4..b6d9271d6 100644 --- a/include/runtime/header.h +++ b/include/runtime/header.h @@ -9,6 +9,8 @@ #include #include +#include + #include "config/macros.h" #include "runtime/alloc.h" #include "runtime/fmt_error_handling.h" @@ -384,8 +386,6 @@ void printList( writer *, list *, char const *, char const *, char const *, void *); void visitChildren(block *subject, writer *file, visitor *printer, void *state); -void sfprintf(writer *, char const *, ...); - stringbuffer *hook_BUFFER_empty(void); stringbuffer *hook_BUFFER_concat(stringbuffer *buf, string *s); stringbuffer * @@ -422,4 +422,15 @@ std::string intToString(mpz_t); void printValueOfType( std::ostream &os, std::string const &definitionPath, void *value, std::string const &type); + +template +void sfprintf(writer *file, char const *fmt, Args &&...args) { + if (file->file) { + fmt::fprintf(file->file, fmt, args...); + } else { + auto str = fmt::sprintf(fmt, args...); + hook_BUFFER_concat_raw(file->buffer, str.data(), str.size()); + } +} + #endif // RUNTIME_HEADER_H diff --git a/lib/ast/AST.cpp b/lib/ast/AST.cpp index 124aafeea..81de9d07b 100644 --- a/lib/ast/AST.cpp +++ b/lib/ast/AST.cpp @@ -191,7 +191,7 @@ std::string KORECompositeSort::getHook(KOREDefinition *definition) const { } ValueType KORECompositeSort::getCategory(std::string const &hookName) { - SortCategory category; + SortCategory category = SortCategory::Uncomputed; uint64_t bits = 0; if (hookName == "MAP.Map") { category = SortCategory::Map; diff --git a/lib/ast/definition.cpp b/lib/ast/definition.cpp index 3ec16101a..538ec9310 100644 --- a/lib/ast/definition.cpp +++ b/lib/ast/definition.cpp @@ -12,7 +12,7 @@ std::unordered_map, Hash, Equal> transitiveClosure(std::unordered_map< Elem *, std::unordered_set, Hash, Equal> relations) { - bool dirty; + bool dirty = false; do { dirty = false; for (auto &entry : relations) { diff --git a/lib/binary/serializer.cpp b/lib/binary/serializer.cpp index 5eb1fba77..a93e71c57 100644 --- a/lib/binary/serializer.cpp +++ b/lib/binary/serializer.cpp @@ -7,7 +7,7 @@ namespace detail { bool is_big_endian() { uint32_t i = 1; - auto *c = reinterpret_cast(&i); + auto *c = static_cast(static_cast(&i)); return *c == 0x00; } @@ -29,8 +29,14 @@ serializer::serializer(flags f) } std::string serializer::byte_string() const { - auto const *ptr = reinterpret_cast(buffer_.data()); - return {ptr, ptr + buffer_.size()}; + auto ret = std::string{}; + ret.reserve(buffer_.size()); + + for (auto byte : buffer_) { + ret.push_back(static_cast(byte)); + } + + return ret; } void serializer::reset() { diff --git a/lib/codegen/CreateStaticTerm.cpp b/lib/codegen/CreateStaticTerm.cpp index a1e0010e4..2573ed5d4 100644 --- a/lib/codegen/CreateStaticTerm.cpp +++ b/lib/codegen/CreateStaticTerm.cpp @@ -60,7 +60,7 @@ llvm::Constant *CreateStaticTerm::notInjectionCase( int idx = 2; for (auto const &child : constructor->getArguments()) { - llvm::Constant *ChildValue; + llvm::Constant *ChildValue = nullptr; if (idx++ == 2 && val != nullptr) { ChildValue = val; } else { @@ -200,8 +200,8 @@ CreateStaticTerm::createToken(ValueType sort, std::string contents) { Module->getContext(), FLOAT_WRAPPER_STRUCT)); auto *globalVar = llvm::dyn_cast(global); if (!globalVar->hasInitializer()) { - size_t prec; - size_t exp; + size_t prec = 0; + size_t exp = 0; char const last = contents.back(); if (last == 'f' || last == 'F') { prec = 24; @@ -222,7 +222,7 @@ CreateStaticTerm::createToken(ValueType sort, std::string contents) { } mpfr_t value; mpfr_init2(value, prec); - int retValue; + int retValue = 0; if (contents == "+Infinity" || contents == "-Infinity" || contents == "Infinity") { retValue = mpfr_set_str(value, contents.c_str(), 10, MPFR_RNDN); diff --git a/lib/codegen/CreateTerm.cpp b/lib/codegen/CreateTerm.cpp index 3a20bcd46..c9eb9307f 100644 --- a/lib/codegen/CreateTerm.cpp +++ b/lib/codegen/CreateTerm.cpp @@ -462,7 +462,7 @@ llvm::Value *CreateTerm::createHook( llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), nwords * 8), CurrentBlock, "koreAllocAlwaysGC"); if (nwords == 1) { - llvm::Value *Word; + llvm::Value *Word = nullptr; if (cat.bits == 64) { Word = mint; } else { @@ -514,7 +514,7 @@ llvm::Value *CreateTerm::createHook( llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), nwords * 8), CurrentBlock, "koreAllocAlwaysGC"); if (nwords == 1) { - llvm::Value *Word; + llvm::Value *Word = nullptr; if (cat.bits == 64) { Word = mint; } else { @@ -717,13 +717,13 @@ llvm::Value *CreateTerm::createFunctionCall( case SortCategory::Set: collection = true; break; default: sret = false; break; } - llvm::Value *AllocSret; + llvm::Value *AllocSret = nullptr; types.reserve(args.size()); for (auto *arg : args) { types.push_back(arg->getType()); } std::vector realArgs = args; - llvm::Type *sretType; + llvm::Type *sretType = nullptr; if (sret) { // we don't use alloca here because the tail call optimization pass for llvm // doesn't handle correctly functions with alloca @@ -769,7 +769,7 @@ llvm::Value *CreateTerm::notInjectionCase( int idx = 2; std::vector children; for (auto const &child : constructor->getArguments()) { - llvm::Value *ChildValue; + llvm::Value *ChildValue = nullptr; if (idx == 2 && val != nullptr) { ChildValue = val; } else { @@ -856,8 +856,8 @@ bool CreateTerm::populateStaticSet(KOREPattern *pattern) { return can_be_static; } -std::pair -CreateTerm::createAllocation(KOREPattern *pattern, std::string locationStack) { +std::pair CreateTerm::createAllocation( + KOREPattern *pattern, std::string const &locationStack) { if (staticTerms.count(pattern)) { auto *staticTerm = new CreateStaticTerm(Definition, Module); return (*staticTerm)(pattern); @@ -1257,10 +1257,10 @@ bool isCollectionSort(ValueType cat) { } } -bool isInjectionSymbol(KOREPattern *p, KORESymbol *inj) { +bool isInjectionSymbol(KOREPattern *p, KORESymbol *sym) { if (auto *constructor = dynamic_cast(p)) { KORESymbol const *symbol = constructor->getConstructor(); - if (symbol->getName() == inj->getName()) { + if (symbol->getName() == sym->getName()) { return true; } } diff --git a/lib/codegen/Debug.cpp b/lib/codegen/Debug.cpp index cd845bd41..6dc15912b 100644 --- a/lib/codegen/Debug.cpp +++ b/lib/codegen/Debug.cpp @@ -165,16 +165,16 @@ llvm::DIType *getDebugType(ValueType type, std::string const &typeName) { return nullptr; } static std::map types; - llvm::DIType *map; - llvm::DIType *rangemap; - llvm::DIType *list; - llvm::DIType *set; - llvm::DIType *integer; - llvm::DIType *floating; - llvm::DIType *buffer; - llvm::DIType *boolean; - llvm::DIType *mint; - llvm::DIType *symbol; + llvm::DIType *map = nullptr; + llvm::DIType *rangemap = nullptr; + llvm::DIType *list = nullptr; + llvm::DIType *set = nullptr; + llvm::DIType *integer = nullptr; + llvm::DIType *floating = nullptr; + llvm::DIType *buffer = nullptr; + llvm::DIType *boolean = nullptr; + llvm::DIType *mint = nullptr; + llvm::DIType *symbol = nullptr; if (types[typeName]) { return types[typeName]; } diff --git a/lib/codegen/Decision.cpp b/lib/codegen/Decision.cpp index 25cb8d453..5b680373a 100644 --- a/lib/codegen/Decision.cpp +++ b/lib/codegen/Decision.cpp @@ -158,7 +158,7 @@ void SwitchNode::codegen(Decision *d) { bool isInt = false; for (auto &_case : cases) { auto *child = _case.getChild(); - llvm::BasicBlock *CaseBlock; + llvm::BasicBlock *CaseBlock = nullptr; if (child == FailNode::get()) { CaseBlock = d->FailureBlock; } else { @@ -187,8 +187,8 @@ void SwitchNode::codegen(Decision *d) { val = cmp; isInt = true; } - llvm::Value *failSort; - llvm::Value *failPattern; + llvm::Value *failSort = nullptr; + llvm::Value *failPattern = nullptr; if (d->FailPattern) { auto failReason = getFailPattern(caseData, isInt, d->FailureBlock); failSort = d->stringLiteral(failReason.first); @@ -241,7 +241,7 @@ void SwitchNode::codegen(Decision *d) { KORESymbolDeclaration *symbolDecl = d->Definition->getSymbolDeclarations().at( _case.getConstructor()->getName()); - llvm::Instruction *Renamed; + llvm::Instruction *Renamed = nullptr; for (auto const &binding : _case.getBindings()) { llvm::Value *ChildPtr = llvm::GetElementPtrInst::CreateInBounds( BlockType, Cast, @@ -250,7 +250,7 @@ void SwitchNode::codegen(Decision *d) { llvm::Type::getInt32Ty(d->Ctx), offset + 2)}, "", d->CurrentBlock); - llvm::Value *Child; + llvm::Value *Child = nullptr; auto cat = dynamic_cast( _case.getConstructor()->getArguments()[offset].get()) ->getCategory(d->Definition); @@ -413,7 +413,7 @@ void FunctionNode::codegen(Decision *d) { std::vector args; llvm::StringMap finalSubst; for (auto [arg, cat] : bindings) { - llvm::Value *val; + llvm::Value *val = nullptr; if (arg.first.find_first_not_of("-0123456789") == std::string::npos) { val = llvm::ConstantInt::get( llvm::Type::getInt64Ty(d->Ctx), std::stoi(arg.first)); @@ -771,9 +771,9 @@ void makeEvalOrAnywhereFunction( llvm::BasicBlock *fail = llvm::BasicBlock::Create(module->getContext(), "fail", matchFunc); - llvm::AllocaInst *choiceBuffer; - llvm::AllocaInst *choiceDepth; - llvm::IndirectBrInst *jump; + llvm::AllocaInst *choiceBuffer = nullptr; + llvm::AllocaInst *choiceDepth = nullptr; + llvm::IndirectBrInst *jump = nullptr; initChoiceBuffer( dt, module, block, stuck, fail, &choiceBuffer, &choiceDepth, &jump); @@ -800,7 +800,7 @@ void abortWhenStuck( auto &Ctx = Module->getContext(); symbol = d->getAllSymbols().at(ast_to_string(*symbol)); auto *BlockType = getBlockType(Module, d, symbol); - llvm::Value *Ptr; + llvm::Value *Ptr = nullptr; auto *BlockPtr = llvm::PointerType::getUnqual( llvm::StructType::getTypeByName(Module->getContext(), BLOCK_STRUCT)); if (symbol->getArguments().empty()) { @@ -1056,7 +1056,7 @@ void makeStepFunction( auto *blockType = getValueType({SortCategory::Symbol, 0}, module); auto *debugType = getDebugType({SortCategory::Symbol, 0}, "SortGeneratedTopCell{}"); - llvm::FunctionType *funcType; + llvm::FunctionType *funcType = nullptr; std::string name; if (search) { name = "stepAll"; @@ -1088,9 +1088,9 @@ void makeStepFunction( llvm::BasicBlock *fail = llvm::BasicBlock::Create(module->getContext(), "fail", matchFunc); - llvm::AllocaInst *choiceBuffer; - llvm::AllocaInst *choiceDepth; - llvm::IndirectBrInst *jump; + llvm::AllocaInst *choiceBuffer = nullptr; + llvm::AllocaInst *choiceDepth = nullptr; + llvm::IndirectBrInst *jump = nullptr; initChoiceBuffer( dt, module, block, pre_stuck, fail, &choiceBuffer, &choiceDepth, &jump); @@ -1207,9 +1207,9 @@ void makeMatchReasonFunction( {FailSubject, FailPattern, FailSort}, "", fail); setDebugLoc(call); - llvm::AllocaInst *choiceBuffer; - llvm::AllocaInst *choiceDepth; - llvm::IndirectBrInst *jump; + llvm::AllocaInst *choiceBuffer = nullptr; + llvm::AllocaInst *choiceDepth = nullptr; + llvm::IndirectBrInst *jump = nullptr; initChoiceBuffer( dt, module, block, pre_stuck, fail, &choiceBuffer, &choiceDepth, &jump); @@ -1303,9 +1303,9 @@ void makeStepFunction( llvm::BasicBlock *fail = llvm::BasicBlock::Create(module->getContext(), "fail", matchFunc); - llvm::AllocaInst *choiceBuffer; - llvm::AllocaInst *choiceDepth; - llvm::IndirectBrInst *jump; + llvm::AllocaInst *choiceBuffer = nullptr; + llvm::AllocaInst *choiceDepth = nullptr; + llvm::IndirectBrInst *jump = nullptr; initChoiceBuffer( res.dt, module, block, pre_stuck, fail, &choiceBuffer, &choiceDepth, &jump); diff --git a/lib/codegen/DecisionParser.cpp b/lib/codegen/DecisionParser.cpp index 058a6cc3b..e916344ad 100644 --- a/lib/codegen/DecisionParser.cpp +++ b/lib/codegen/DecisionParser.cpp @@ -76,7 +76,7 @@ class DTPreprocessor { public: yaml_node_t *get(yaml_node_t *node, std::string const &name) { - yaml_node_pair_t *entry; + yaml_node_pair_t *entry = nullptr; for (entry = node->data.mapping.pairs.start; entry < node->data.mapping.pairs.top; ++entry) { yaml_node_t *key = yaml_document_get_node(doc, entry->key); @@ -97,7 +97,7 @@ class DTPreprocessor { std::vector vec(yaml_node_t *node) { std::vector result; - yaml_node_item_t *entry; + yaml_node_item_t *entry = nullptr; for (entry = node->data.sequence.items.start; entry < node->data.sequence.items.top; ++entry) { result.push_back(str(yaml_document_get_node(doc, *entry))); @@ -260,7 +260,7 @@ class DTPreprocessor { iter < list->data.sequence.items.top; ++iter) { auto *_case = yaml_document_get_node(doc, *iter); std::vector> bindings; - KORESymbol *symbol; + KORESymbol *symbol = nullptr; if (kind == SwitchLiteral || kind == CheckNull) { symbol = dv; } else { diff --git a/lib/codegen/EmitConfigParser.cpp b/lib/codegen/EmitConfigParser.cpp index a7cea9cb2..7c49c7494 100644 --- a/lib/codegen/EmitConfigParser.cpp +++ b/lib/codegen/EmitConfigParser.cpp @@ -369,7 +369,7 @@ static std::pair getEval( } CreateTerm creator(subst, def, CaseBlock, mod, false); llvm::Value *result = creator(pattern.get()).first; - llvm::Value *retval; + llvm::Value *retval = nullptr; ValueType cat = dynamic_cast(symbol->getSort().get()) ->getCategory(def); switch (cat.cat) { @@ -883,7 +883,7 @@ static void visitCollection( auto indices = std::vector{zero, zero}; auto *sortDecl = definition->getSortDeclarations().at(compositeSort->getName()); - llvm::Constant *concatPtr; + llvm::Constant *concatPtr = nullptr; if (sortDecl->getAttributes().count("concat")) { auto *concat = (KORECompositePattern *)sortDecl->getAttributes() .at("concat") @@ -1034,7 +1034,7 @@ static void getVisitor( llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), nwords * 8), CaseBlock, "koreAllocAlwaysGC"); if (nwords == 1) { - llvm::Value *Word; + llvm::Value *Word = nullptr; if (cat.bits == 64) { Word = mint; } else { diff --git a/lib/parser/KOREParser.cpp b/lib/parser/KOREParser.cpp index 47e8711d0..aa639e67c 100644 --- a/lib/parser/KOREParser.cpp +++ b/lib/parser/KOREParser.cpp @@ -56,7 +56,7 @@ static std::string str(token tok) { std::string KOREParser::consume(token next) { std::string data; - token actual; + token actual = token::EMPTY; if (buffer.tok == token::EMPTY) { actual = scanner.yylex(&data, &loc); } else { diff --git a/runtime/alloc/arena.cpp b/runtime/alloc/arena.cpp index d6c83ed99..483d44a8b 100644 --- a/runtime/alloc/arena.cpp +++ b/runtime/alloc/arena.cpp @@ -10,8 +10,12 @@ size_t const BLOCK_SIZE = 1024 * 1024; -#define mem_block_header(ptr) \ - ((memory_block_header *)(((uintptr_t)(ptr)-1) & ~(BLOCK_SIZE - 1))) +__attribute__((always_inline)) memory_block_header * +mem_block_header(void *ptr) { + // NOLINTNEXTLINE(*-reinterpret-cast) + return reinterpret_cast( + ((uintptr_t)(ptr)-1) & ~(BLOCK_SIZE - 1)); +} __attribute__((always_inline)) void arenaReset(struct arena *Arena) { char id = Arena->allocation_semispace_id; @@ -72,7 +76,7 @@ static void *megabyte_malloc() { } static void freshBlock(struct arena *Arena) { - char *nextBlock; + char *nextBlock = nullptr; if (Arena->block_start == nullptr) { nextBlock = (char *)megabyte_malloc(); Arena->first_block = nextBlock; diff --git a/runtime/arithmetic/int.cpp b/runtime/arithmetic/int.cpp index 9b1133e3a..94e9788c4 100644 --- a/runtime/arithmetic/int.cpp +++ b/runtime/arithmetic/int.cpp @@ -418,7 +418,7 @@ size_t *hook_MINT_export(mpz_t in, uint64_t bits) { auto *allocptr = (size_t *)koreAllocAlwaysGC(allocsize); memset(allocptr, 0, allocsize); size_t *exportptr = nwords > count ? allocptr + nwords - count : allocptr; - size_t actualcount; + size_t actualcount = 0; mpz_export(exportptr, &actualcount, 1, sizeof(size_t), 0, 0, twos); assert(count == actualcount); if (count == 0) { diff --git a/runtime/collect/collect.cpp b/runtime/collect/collect.cpp index 3f558b4fe..44b3845a5 100644 --- a/runtime/collect/collect.cpp +++ b/runtime/collect/collect.cpp @@ -52,7 +52,7 @@ void migrate(block **blockPtr) { size_t lenInBytes = get_size(hdr, layout); auto **forwardingAddress = (block **)(currBlock + 1); if (!hasForwardingAddress) { - block *newBlock; + block *newBlock = nullptr; if (shouldPromote || (isInOldGen && collect_old)) { newBlock = (block *)koreAllocOld(lenInBytes); } else { @@ -92,8 +92,8 @@ static void migrate_string_buffer(stringbuffer **bufferPtr) { uint64_t const cap = len(buffer->contents); initialize_migrate(); if (!hasForwardingAddress) { - stringbuffer *newBuffer; - string *newContents; + stringbuffer *newBuffer = nullptr; + string *newContents = nullptr; if (shouldPromote || (isInOldGen && collect_old)) { newBuffer = (stringbuffer *)koreAllocOld(sizeof(stringbuffer)); newContents = (string *)koreAllocTokenOld(sizeof(string) + cap); @@ -120,8 +120,8 @@ static void migrate_mpz(mpz_ptr *mpzPtr) { uint64_t const hdr = intgr->h.hdr; initialize_migrate(); if (!hasForwardingAddress) { - mpz_hdr *newIntgr; - string *newLimbs; + mpz_hdr *newIntgr = nullptr; + string *newLimbs = nullptr; bool hasLimbs = intgr->i->_mp_alloc > 0; #ifdef GC_DBG numBytesLiveAtCollection[oldAge] += sizeof(mpz_hdr); @@ -167,8 +167,8 @@ static void migrate_floating(floating **floatingPtr) { uint64_t const hdr = flt->h.hdr; initialize_migrate(); if (!hasForwardingAddress) { - floating_hdr *newFlt; - string *newLimbs; + floating_hdr *newFlt = nullptr; + string *newLimbs = nullptr; string *limbs = struct_base(string, data, flt->f.f->_mpfr_d - 1); size_t lenLimbs = len(limbs); diff --git a/runtime/collect/migrate_collection.cpp b/runtime/collect/migrate_collection.cpp index 2e1a8c961..534cbc939 100644 --- a/runtime/collect/migrate_collection.cpp +++ b/runtime/collect/migrate_collection.cpp @@ -16,7 +16,7 @@ void migrate_collection_node(void **nodePtr) { initialize_migrate(); size_t lenInBytes = get_size(hdr, 0); if (!hasForwardingAddress) { - string *newBlock; + string *newBlock = nullptr; if (shouldPromote || (isInOldGen && collect_old)) { newBlock = (string *)koreAllocOld(lenInBytes); } else { diff --git a/runtime/io/io.cpp b/runtime/io/io.cpp index fdb0fc541..8224f2903 100644 --- a/runtime/io/io.cpp +++ b/runtime/io/io.cpp @@ -35,7 +35,7 @@ static blockheader kseqHeader static std::map logFiles; static block *block_errno() { - char const *errStr; + char const *errStr = nullptr; switch (errno) { case EOF: errStr = GETTAG(EOF); break; case E2BIG: errStr = GETTAG(E2BIG); break; @@ -218,7 +218,7 @@ SortIOInt hook_IO_open(SortString filename, SortString control) { int flags = 0; int access = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; int modes = getFileModes(control); - int fd; + int fd = 0; mpz_t result; if (-1 != modes) { @@ -246,7 +246,7 @@ SortIOInt hook_IO_open(SortString filename, SortString control) { } char *f = getTerminatedString(filename); - fd = open(f, flags, access); + fd = open(f, flags, access); // NOLINT(*-vararg) } else { errno = EINVAL; fd = -1; @@ -293,7 +293,7 @@ SortIOInt hook_IO_getc(SortInt i) { } int fd = mpz_get_si(i); - char c; + char c = 0; ssize_t ret = read(fd, &c, sizeof(char)); if (ret == 0) { @@ -440,7 +440,7 @@ SortK hook_IO_lock(SortInt i, SortInt len) { lockp.l_whence = SEEK_CUR; lockp.l_start = 0; lockp.l_len = l; - int ret = fcntl(fd, F_SETLKW, &lockp); + int ret = fcntl(fd, F_SETLKW, &lockp); // NOLINT(*-vararg) if (ret == -1) { return getKSeqErrorBlock(); @@ -463,7 +463,7 @@ SortK hook_IO_unlock(SortInt i, SortInt len) { lockp.l_whence = SEEK_CUR; lockp.l_start = 0; lockp.l_len = l; - int ret = fcntl(fd, F_SETLKW, &lockp); + int ret = fcntl(fd, F_SETLKW, &lockp); // NOLINT(*-vararg) if (ret == -1) { return getKSeqErrorBlock(); @@ -664,7 +664,7 @@ SortIOFile hook_IO_mkstemp(SortString filename) { // NOLINTNEXTLINE(*-cognitive-complexity) SortKItem hook_IO_system(SortString cmd) { - pid_t pid; + pid_t pid = 0; int ret = 0; int out[2]; int err[2]; @@ -687,6 +687,8 @@ SortKItem hook_IO_system(SortString cmd) { if (len(cmd) > 0) { char *command = getTerminatedString(cmd); + + // NOLINTNEXTLINE(*-vararg) ret = execl("/bin/sh", "/bin/sh", "-c", command, nullptr); ret == -1 ? exit(127) : exit(0); } else { @@ -752,8 +754,8 @@ SortKItem hook_IO_system(SortString cmd) { retBlock->h = getBlockHeaderForSymbol( (uint64_t)getTagForSymbolName(GETTAG(systemResult))); - string *outStr; - string *errStr; + string *outStr = nullptr; + string *errStr = nullptr; outStr = hook_BUFFER_toString(outBuffer); errStr = hook_BUFFER_toString(errBuffer); memcpy(retBlock->children + 1, &outStr, sizeof(string *)); diff --git a/runtime/json/json.cpp b/runtime/json/json.cpp index 804e26323..528be1385 100644 --- a/runtime/json/json.cpp +++ b/runtime/json/json.cpp @@ -59,7 +59,7 @@ static block *dotK = leaf_block(getTagForSymbolName("dotk{}")); static blockheader kseqHeader = {getBlockHeaderForSymbol((uint64_t)getTagForSymbolName("kseq{}"))}; -#define get_header(name, symbol) \ +#define GET_HEADER(name, symbol) \ static struct blockheader name() { \ static struct blockheader hdr = {(uint64_t)-1}; \ if (hdr.hdr == -1) { \ @@ -68,16 +68,16 @@ static blockheader kseqHeader return hdr; \ } -get_header(boolHdr, "inj{SortBool{}, SortJSON{}}"); -get_header(intHdr, "inj{SortInt{}, SortJSON{}}"); -get_header(floatHdr, "inj{SortFloat{}, SortJSON{}}"); -get_header(strHdr, "inj{SortString{}, SortJSON{}}"); -get_header(listHdr, "LblJSONs{}"); -get_header(membHdr, "LblJSONEntry{}"); -get_header(objHdr, "LblJSONObject{}"); -get_header(listWrapHdr, "LblJSONList{}"); +GET_HEADER(boolHdr, "inj{SortBool{}, SortJSON{}}"); +GET_HEADER(intHdr, "inj{SortInt{}, SortJSON{}}"); +GET_HEADER(floatHdr, "inj{SortFloat{}, SortJSON{}}"); +GET_HEADER(strHdr, "inj{SortString{}, SortJSON{}}"); +GET_HEADER(listHdr, "LblJSONs{}"); +GET_HEADER(membHdr, "LblJSONEntry{}"); +GET_HEADER(objHdr, "LblJSONObject{}"); +GET_HEADER(listWrapHdr, "LblJSONList{}"); -#define get_block(name, symbol) \ +#define GET_BLOCK(name, symbol) \ static block *name() { \ static uint64_t tag = (uint64_t)-1; \ if (tag == -1) { \ @@ -86,11 +86,11 @@ get_header(listWrapHdr, "LblJSONList{}"); return (block *)tag; \ } -get_block(dotList, "Lbl'Stop'List'LBraQuot'JSONs'QuotRBra'{}"); -get_block(null, "LblJSONnull{}"); +GET_BLOCK(dotList, "Lbl'Stop'List'LBraQuot'JSONs'QuotRBra'{}"); +GET_BLOCK(null, "LblJSONnull{}"); struct KoreHandler : BaseReaderHandler, KoreHandler> { - block *result; + block *result = nullptr; std::vector stack; bool Null() { @@ -117,8 +117,9 @@ struct KoreHandler : BaseReaderHandler, KoreHandler> { stack.push_back(result); return true; } + mpz_clear(z); - floating f[1]; // NOLINT(modernize-avoid-c-arrays) + floating f[1]; // NOLINT(*-avoid-c-arrays) mpfr_init2(f->f, 53); f->exp = 11; mpfr_set_str(f->f, str, 9, MPFR_RNDN); diff --git a/runtime/meta/ffi.cpp b/runtime/meta/ffi.cpp index 01144da10..9f3fd52d4 100644 --- a/runtime/meta/ffi.cpp +++ b/runtime/meta/ffi.cpp @@ -145,7 +145,7 @@ static ffi_type *getTypeFromBlock(block *elem) { tag_hdr(elem->h.hdr) == (uint64_t)getTagForSymbolName(TYPETAG(struct))) { list *elements = (list *)*elem->children; size_t numFields = hook_LIST_size_long(elements); - block *structField; + block *structField = nullptr; auto *structType = (ffi_type *)malloc(sizeof(ffi_type)); structType->size = 0; @@ -183,9 +183,9 @@ string *ffiCall( bool isVariadic, mpz_t addr, list *args, list *fixtypes, list *vartypes, block *ret) { ffi_cif cif; - ffi_type **argtypes; - ffi_type *rtype; - void (*address)(); + ffi_type **argtypes = nullptr; + ffi_type *rtype = nullptr; + void (*address)() = nullptr; if (!mpz_fits_ulong_p(addr)) { KLLVM_HOOK_INVALID_ARGUMENT("Addr is too large: {}", intToString(addr)); @@ -209,7 +209,7 @@ string *ffiCall( argtypes = (ffi_type **)malloc(sizeof(ffi_type *) * nargs); - block *elem; + block *elem = nullptr; for (int i = 0; i < nfixtypes; i++) { elem = hook_LIST_get_long(fixtypes, i); if (tag_hdr(elem->h.hdr) @@ -242,7 +242,7 @@ string *ffiCall( rtype = getTypeFromBlock(ret); - ffi_status status; + ffi_status status = FFI_OK; if (isVariadic) { status = ffi_prep_cif_var( &cif, FFI_DEFAULT_ABI, nfixtypes, nargs, rtype, argtypes); @@ -324,7 +324,7 @@ SortInt hook_FFI_address(SortString fn) { static std::map const privateSymbols = getPrivateSymbols(); - void *address; + void *address = nullptr; if (auto it = privateSymbols.find(funcStr); it != privateSymbols.end()) { address = it->second; } else { @@ -340,6 +340,7 @@ SortInt hook_FFI_address(SortString fn) { static std::pair< std::vector::iterator, std::vector::iterator> firstBlockEnumerator() { + // NOLINTBEGIN(*-const-cast) static std::vector blocks; blocks.clear(); @@ -349,11 +350,13 @@ firstBlockEnumerator() { } return std::make_pair(blocks.begin(), blocks.end()); + // NOLINTEND(*-const-cast) } static std::pair< std::vector::iterator, std::vector::iterator> secondBlockEnumerator() { + // NOLINTBEGIN(*-const-cast) static std::vector blocks; blocks.clear(); @@ -363,6 +366,7 @@ secondBlockEnumerator() { } return std::make_pair(blocks.begin(), blocks.end()); + // NOLINTEND(*-const-cast) } string *hook_FFI_alloc(block *kitem, mpz_t size, mpz_t align) { @@ -394,7 +398,7 @@ string *hook_FFI_alloc(block *kitem, mpz_t size, mpz_t align) { size_t s = mpz_get_ui(size); - string *ret; + string *ret = nullptr; int result = posix_memalign( (void **)&ret, a < sizeof(void *) ? sizeof(void *) : a, sizeof(string *) + s); diff --git a/runtime/meta/substitution.cpp b/runtime/meta/substitution.cpp index 62354abfd..1a51e2330 100644 --- a/runtime/meta/substitution.cpp +++ b/runtime/meta/substitution.cpp @@ -342,7 +342,7 @@ block *incrementDebruijn(block *currBlock) { case VARIABLE_LAYOUT: case SYMBOL_LAYOUT: { block *oldArg = *(block **)arg; - block *newArg; + block *newArg = nullptr; if (i == 0 && isBinder) { newArg = alphaRename(oldArg); } else { diff --git a/runtime/strings/CMakeLists.txt b/runtime/strings/CMakeLists.txt index 5bfb53dfa..5ad108202 100644 --- a/runtime/strings/CMakeLists.txt +++ b/runtime/strings/CMakeLists.txt @@ -13,6 +13,9 @@ add_library(numeric_strings STATIC numeric.cpp ) +target_link_libraries(numeric_strings PUBLIC + fmt::fmt-header-only) + install( TARGETS strings numeric_strings ARCHIVE DESTINATION lib/kllvm diff --git a/runtime/strings/bytes.cpp b/runtime/strings/bytes.cpp index a37c45179..92fb37223 100644 --- a/runtime/strings/bytes.cpp +++ b/runtime/strings/bytes.cpp @@ -13,8 +13,8 @@ void copy_if_needed(SortBytes &b); extern "C" { -#undef get_ui -#define get_ui(x) get_ui_named(x, __func__) +#undef GET_UI +#define GET_UI(x) get_ui_named(x, __func__) #define KCHAR char SortBytes hook_BYTES_empty() { @@ -53,7 +53,7 @@ SortInt hook_BYTES_bytes2int( int order = endianness == tag_big_endian() ? 1 : -1; mpz_import(result, len(b), order, 1, 0, 0, b->data); if (signedness != tag_unsigned() && len(b) != 0) { - bool msb; + bool msb = false; if (endianness == tag_big_endian()) { msb = b->data[0] & 0x80; } else { @@ -121,8 +121,8 @@ SortBytes hook_BYTES_string2bytes(SortString s) { } SortBytes hook_BYTES_substr(SortBytes input, SortInt start, SortInt end) { - uint64_t ustart = get_ui(start); - uint64_t uend = get_ui(end); + uint64_t ustart = GET_UI(start); + uint64_t uend = GET_UI(end); if (uend < ustart) { KLLVM_HOOK_INVALID_ARGUMENT( "Invalid string slice: Requested start index {} is greater than " @@ -145,7 +145,7 @@ SortBytes hook_BYTES_substr(SortBytes input, SortInt start, SortInt end) { } SortInt hook_BYTES_get(SortBytes b, SortInt off) { - unsigned long off_long = get_ui(off); + unsigned long off_long = GET_UI(off); if (off_long >= len(b)) { KLLVM_HOOK_INVALID_ARGUMENT( "Buffer overflow on get: off={}, len={}", off_long, len(b)); @@ -158,12 +158,12 @@ SortInt hook_BYTES_get(SortBytes b, SortInt off) { SortBytes hook_BYTES_update(SortBytes b, SortInt off, SortInt val) { copy_if_needed(b); - unsigned long off_long = get_ui(off); + unsigned long off_long = GET_UI(off); if (off_long >= len(b)) { KLLVM_HOOK_INVALID_ARGUMENT( "Buffer overflow on update: off={}, len={}", off_long, len(b)); } - unsigned long val_long = get_ui(val); + unsigned long val_long = GET_UI(val); if (val_long >= 256) { KLLVM_HOOK_INVALID_ARGUMENT( "Not a valid value for a byte in update: {}", val_long); @@ -175,7 +175,7 @@ SortBytes hook_BYTES_update(SortBytes b, SortInt off, SortInt val) { SortBytes hook_BYTES_replaceAt(SortBytes b, SortInt start, SortBytes b2) { copy_if_needed(b); - unsigned long start_long = get_ui(start); + unsigned long start_long = GET_UI(start); if (start_long + len(b2) > len(b)) { KLLVM_HOOK_INVALID_ARGUMENT( "Buffer overflow on replaceAt: start={}, dest_len={}, src_len={}", @@ -189,8 +189,8 @@ SortBytes hook_BYTES_memset(SortBytes b, SortInt start, SortInt count, SortInt value) { copy_if_needed(b); - uint64_t ustart = get_ui(start); - uint64_t ucount = get_ui(count); + uint64_t ustart = GET_UI(start); + uint64_t ucount = GET_UI(count); uint64_t uend = ustart + ucount; if ((uend < ustart) || (uend < ucount)) { KLLVM_HOOK_INVALID_ARGUMENT( @@ -221,11 +221,11 @@ SortInt hook_BYTES_length(SortBytes a) { } SortBytes hook_BYTES_padRight(SortBytes b, SortInt length, SortInt v) { - unsigned long ulen = get_ui(length); + unsigned long ulen = GET_UI(length); if (ulen <= len(b)) { return b; } - unsigned long uv = get_ui(v); + unsigned long uv = GET_UI(v); if (uv > 255) { KLLVM_HOOK_INVALID_ARGUMENT("Integer overflow on value: {}", uv); } @@ -237,11 +237,11 @@ SortBytes hook_BYTES_padRight(SortBytes b, SortInt length, SortInt v) { } SortBytes hook_BYTES_padLeft(SortBytes b, SortInt length, SortInt v) { - unsigned long ulen = get_ui(length); + unsigned long ulen = GET_UI(length); if (ulen <= len(b)) { return b; } - unsigned long uv = get_ui(v); + unsigned long uv = GET_UI(v); if (uv > 255) { KLLVM_HOOK_INVALID_ARGUMENT("Integer overflow on value: {}", uv); } diff --git a/runtime/strings/numeric.cpp b/runtime/strings/numeric.cpp index 18ee2d0ee..3bb43b6e8 100644 --- a/runtime/strings/numeric.cpp +++ b/runtime/strings/numeric.cpp @@ -17,7 +17,7 @@ std::string floatToString(floating const *f, char const *suffix) { } return "Infinity" + std::string(suffix); } - mpfr_exp_t printed_exp; + mpfr_exp_t printed_exp = 0; char *str = mpfr_get_str(nullptr, &printed_exp, 10, 0, f->f, MPFR_RNDN); size_t len = strlen(str); auto *newstr = (string *)koreAllocToken(sizeof(string) + len + 2); @@ -37,24 +37,27 @@ std::string floatToString(floating const *f, char const *suffix) { std::string floatToString(floating const *f) { uint64_t prec = mpfr_get_prec(f->f); uint64_t exp = f->exp; - auto suffix - = std::array{}; // 19 chars per long + p and x and null byte - if (prec == 53 && exp == 11) { - suffix[0] = 0; - } else if (prec == 24 && exp == 8) { - suffix[0] = 'f'; - suffix[1] = 0; - } else { - snprintf(suffix.data(), sizeof(suffix), "p%" PRIu64 "x%" PRIu64, prec, exp); - } - return floatToString(f, suffix.data()); + + auto suffix = [&]() -> std::string { + if (prec == 53 && exp == 11) { + return ""; + } + + if (prec == 24 && exp == 8) { + return "f"; + } + + return fmt::sprintf("p%" PRIu64 "x%" PRIu64, prec, exp); + }(); + + return floatToString(f, suffix.c_str()); } std::string intToStringInBase(mpz_t i, uint64_t base) { char *tmp = mpz_get_str(nullptr, base, i); auto ret = std::string(tmp); - void (*mpz_free)(void *, size_t); + void (*mpz_free)(void *, size_t) = nullptr; mp_get_memory_functions(nullptr, nullptr, &mpz_free); mpz_free(tmp, strlen(tmp) + 1); diff --git a/runtime/strings/strings.cpp b/runtime/strings/strings.cpp index 41cfd9a18..a443f0804 100644 --- a/runtime/strings/strings.cpp +++ b/runtime/strings/strings.cpp @@ -213,8 +213,8 @@ SortString hook_STRING_base2string_long(SortInt input, uint64_t base) { SortInt hook_STRING_string2base_long(SortString input, uint64_t base) { mpz_t result; - size_t length; - char const *dataStart; + size_t length = 0; + char const *dataStart = nullptr; if (*(input->data) == '+') { length = len(input) - 1; @@ -419,7 +419,7 @@ hook_BUFFER_concat_raw(stringbuffer *buf, char const *data, uint64_t n) { if (newCapacity < minCapacity) { newCapacity = minCapacity; } - string *new_contents; + string *new_contents = nullptr; if (notYoungObjectBit) { assert(buf->h.hdr & AGE_MASK); new_contents = static_cast( @@ -443,8 +443,8 @@ SortString hook_BUFFER_toString(SortStringBuffer buf) { } void init_float2(floating *result, std::string contents) { - size_t prec; - size_t exp; + size_t prec = 0; + size_t exp = 0; char const last = contents.back(); if (last == 'f' || last == 'F') { prec = 24; @@ -464,7 +464,7 @@ void init_float2(floating *result, std::string contents) { } result->exp = exp; mpfr_init2(result->f, prec); - int retValue; + int retValue = 0; if (contents == "+Infinity" || contents == "-Infinity" || contents == "Infinity") { retValue = mpfr_set_str(result->f, contents.c_str(), 10, MPFR_RNDN); diff --git a/runtime/util/ConfigurationPrinter.cpp b/runtime/util/ConfigurationPrinter.cpp index 0d32b12a3..7fabc6933 100644 --- a/runtime/util/ConfigurationPrinter.cpp +++ b/runtime/util/ConfigurationPrinter.cpp @@ -39,6 +39,12 @@ struct print_state { // We never want to copy the state; it should only ever get passed around by // reference. print_state(print_state const &) = delete; + print_state &operator=(print_state const &) = delete; + + print_state(print_state &&) = default; + print_state &operator=(print_state &&) = default; + + ~print_state() = default; std::vector boundVariables; std::unordered_map varNames; @@ -78,50 +84,6 @@ void printMInt( } } -void sfprintf(writer *file, char const *fmt, ...) { - va_list args; - va_start(args, fmt); - if (file->file) { - vfprintf(file->file, fmt, args); - } else { - char buf[8192]; - char *finalBuf = buf; - va_list args_copy; - va_copy(args_copy, args); - int res = vsnprintf( - buf + sizeof(blockheader), sizeof(buf) - sizeof(blockheader), fmt, - args); - if (res >= sizeof(buf) - sizeof(blockheader)) { - size_t size = sizeof(buf) * 2; - finalBuf = (char *)malloc(size); - memcpy(finalBuf, buf, sizeof(buf)); - va_list args_temp; - va_copy(args_temp, args_copy); - res = vsnprintf( - finalBuf + sizeof(blockheader), size - sizeof(blockheader), fmt, - args_temp); - va_end(args_temp); - if (res >= size - sizeof(blockheader)) { - do { - size *= 2; - finalBuf = (char *)realloc(finalBuf, size); - va_list args_temp; - va_copy(args_temp, args_copy); - res = vsnprintf( - finalBuf + sizeof(blockheader), size - sizeof(blockheader), fmt, - args_temp); - va_end(args_temp); - } while (res >= size - sizeof(blockheader)); - } - } - va_end(args_copy); - auto *str = (string *)finalBuf; - init_with_len(str, res); - hook_BUFFER_concat(file->buffer, str); - } - va_end(args); -} - void printComma(writer *file, void *state) { sfprintf(file, ","); } @@ -223,7 +185,7 @@ void printConfigurationInternal( void printStatistics(char const *filename, uint64_t steps) { FILE *file = fopen(filename, "w"); - fprintf(file, "%" PRIu64 "\n", steps - 1); // off by one adjustment + fmt::print(file, "{}\n", steps - 1); // off by one adjustment fclose(file); } @@ -335,13 +297,13 @@ extern "C" void printMatchResult( os << matchLog[i].debugName << "("; for (int j = 0; j < matchLog[i].args.size(); j += 2) { - auto *typeName = reinterpret_cast(matchLog[i].args[j + 1]); + auto *typeName = static_cast(matchLog[i].args[j + 1]); printValueOfType(os, definitionPath, matchLog[i].args[j], typeName); if (j + 2 != matchLog[i].args.size()) { os << ", "; } } - os << ") => " << *reinterpret_cast(matchLog[i].result) << "\n"; + os << ") => " << *static_cast(matchLog[i].result) << "\n"; } } } @@ -350,23 +312,23 @@ void printValueOfType( std::ostream &os, std::string const &definitionPath, void *value, std::string const &type) { if (type == "%mpz*") { - os << reinterpret_cast(value); + os << static_cast(value); } else if (type == "%block*") { if ((((uintptr_t)value) & 3) == 1) { auto f = temporary_file("subject_XXXXXX"); - string *s = printConfigurationToString(reinterpret_cast(value)); + string *s = printConfigurationToString(static_cast(value)); f.ofstream() << std::string(s->data, len(s)) << std::endl; kllvm::printKORE(os, definitionPath, f.filename(), false, true); } else if ((((uintptr_t)value) & 1) == 0) { - auto *s = reinterpret_cast(value); + auto *s = static_cast(value); os << std::string(s->data, len(s)); } else { os << "Error: " << type << " not implemented!"; } } else if (type == "%floating*") { - os << floatToString(reinterpret_cast(value)); + os << floatToString(static_cast(value)); } else if (type == "i1") { - os << *reinterpret_cast(value); + os << *static_cast(value); } else { os << "Error: " << type << " not implemented!"; } @@ -375,7 +337,7 @@ void printValueOfType( void printVariableToFile(char const *filename, char const *varname) { FILE *file = fopen(filename, "a"); - fprintf(file, "%s", varname); + fmt::print(file, "{}", varname); char n = 0; fwrite(&n, 1, 1, file); fflush(file); diff --git a/runtime/util/ConfigurationSerializer.cpp b/runtime/util/ConfigurationSerializer.cpp index c79d7d777..35cca58bf 100644 --- a/runtime/util/ConfigurationSerializer.cpp +++ b/runtime/util/ConfigurationSerializer.cpp @@ -5,6 +5,8 @@ #include "runtime/header.h" +#include + #include #include #include @@ -32,6 +34,12 @@ struct serialization_state { // We never want to copy the state; it should only ever get passed around by // reference. serialization_state(serialization_state const &) = delete; + serialization_state &operator=(serialization_state const &) = delete; + + serialization_state(serialization_state &&) = default; + serialization_state &operator=(serialization_state &&) = default; + + ~serialization_state() = default; serializer instance; std::vector boundVariables; @@ -239,21 +247,11 @@ void serializeMInt( writer *file, size_t *i, size_t bits, char const *sort, void *state) { auto &instance = static_cast(state)->instance; - auto const *fmt = "%sp%zd"; - auto str = std::string{}; - - if (i == nullptr) { - str = "0"; - } else { - mpz_ptr z = hook_MINT_import(i, bits, false); - str = intToString(z); - } - - auto buf_len = snprintf(nullptr, 0, fmt, str.c_str(), bits); - auto buffer = std::vector(buf_len + 1); + auto str = (i == nullptr) ? std::string("0") + : intToString(hook_MINT_import(i, bits, false)); - snprintf(buffer.data(), buf_len + 1, fmt, str.c_str(), bits); - emitToken(instance, sort, buffer.data()); + auto buffer = fmt::format("{}p{}", str, bits); + emitToken(instance, sort, buffer.c_str()); } void serializeComma(writer *file, void *state) { } @@ -401,8 +399,8 @@ void serializeConfigurations( void serializeConfigurationToFile( char const *filename, block *subject, bool emit_size) { - char *data; - size_t size; + char *data = nullptr; + size_t size = 0; serializeConfiguration(subject, nullptr, &data, &size, emit_size); FILE *file = fopen(filename, "a"); @@ -440,8 +438,8 @@ void writeUInt64ToFile(char const *filename, uint64_t i) { void serializeTermToFile( char const *filename, block *subject, char const *sort) { - char *data; - size_t size; + char *data = nullptr; + size_t size = 0; serializeConfiguration(subject, sort, &data, &size, true); FILE *file = fopen(filename, "a"); @@ -455,8 +453,8 @@ void serializeRawTermToFile( char const *filename, void *subject, char const *sort) { block *term = constructRawTerm(subject, sort, true); - char *data; - size_t size; + char *data = nullptr; + size_t size = 0; serializeConfiguration(term, "SortKItem{}", &data, &size, true); FILE *file = fopen(filename, "a"); @@ -471,8 +469,8 @@ sortedTermToKorePattern(block *subject, char const *sort) { auto is_kitem = (std::string(sort) == "SortKItem{}"); block *term = is_kitem ? subject : constructRawTerm(subject, sort, false); - char *data_out; - size_t size_out; + char *data_out = nullptr; + size_t size_out = 0; serializeConfiguration(term, "SortKItem{}", &data_out, &size_out, true); auto result = deserialize_pattern(data_out, data_out + size_out); diff --git a/runtime/util/match_log.cpp b/runtime/util/match_log.cpp index 17df958b0..2e5abe1f2 100644 --- a/runtime/util/match_log.cpp +++ b/runtime/util/match_log.cpp @@ -47,7 +47,10 @@ void addMatchFailReason(void *subject, char const *pattern, char const *sort) { void addMatchFunction( char const *debugName, char const *function, void *result, ...) { - va_list ap; + // This function needs to use C variadic arguments because it's called from + // generated LLVM IR. + // NOLINTBEGIN(*-vararg) + va_list ap; // NOLINT(*-init-variables) va_start(ap, result); std::vector args; @@ -64,6 +67,7 @@ void addMatchFunction( nullptr}); va_end(ap); + // NOLINTEND(*-vararg) } } diff --git a/runtime/util/search.cpp b/runtime/util/search.cpp index 5b7419998..b1a5c288e 100644 --- a/runtime/util/search.cpp +++ b/runtime/util/search.cpp @@ -25,6 +25,7 @@ static std::unordered_set results; static std::pair< std::vector::iterator, std::vector::iterator> blockEnumerator() { + // NOLINTBEGIN(*-const-cast) static std::vector blocks; blocks.clear(); @@ -46,6 +47,7 @@ blockEnumerator() { } return std::make_pair(blocks.begin(), blocks.end()); + // NOLINTEND(*-const-cast) } // NOLINTNEXTLINE(*-cognitive-complexity) diff --git a/runtime/util/util.cpp b/runtime/util/util.cpp index 7a01da9d0..351c924c4 100644 --- a/runtime/util/util.cpp +++ b/runtime/util/util.cpp @@ -1,5 +1,7 @@ #include "runtime/header.h" +#include + extern "C" { block *dot_k() { @@ -39,7 +41,7 @@ block *constructRawTerm(void *subject, char const *sort, bool raw_value) { void printProofHintHeader(char *output_file) { uint32_t version = 4; FILE *file = fopen(output_file, "a"); - fprintf(file, "HINT"); + fmt::print(file, "HINT"); fwrite(&version, sizeof(version), 1, file); fflush(file); fclose(file); diff --git a/scripts/clang-tidy.sh b/scripts/clang-tidy.sh index d412d121c..e13fe0b7a 100755 --- a/scripts/clang-tidy.sh +++ b/scripts/clang-tidy.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -set -e +set -euxo pipefail LLVM_VERSION=15 BUILD_DIR=build diff --git a/tools/k-rule-apply/main.cpp b/tools/k-rule-apply/main.cpp index 04bb9c4bd..c3ec6c83d 100644 --- a/tools/k-rule-apply/main.cpp +++ b/tools/k-rule-apply/main.cpp @@ -51,7 +51,7 @@ int main(int argc, char **argv) { // Parse the given KORE Pattern and get the block* to use as input for the // match function. - parser::KOREParser parser(KOREPatternFilename); + parser::KOREParser parser(KOREPatternFilename.getValue()); auto InitialConfiguration = parser.pattern(); auto match_function_name = getMatchFunctionName(); @@ -77,6 +77,8 @@ int main(int argc, char **argv) { dlclose(handle); return EXIT_FAILURE; } + + // NOLINTNEXTLINE(*-reinterpret-cast) auto match_function = reinterpret_cast(match_function_ptr); resetMatchReason(handle); diff --git a/tools/k-rule-find/main.cpp b/tools/k-rule-find/main.cpp index be0f2dabd..638a618f4 100644 --- a/tools/k-rule-find/main.cpp +++ b/tools/k-rule-find/main.cpp @@ -76,7 +76,7 @@ Location parseLocation(std::string const &loc) { size_t pos_lc = lineColumn.find(':'); // If another “:” isn’t found, the tool assumes no column number was given. - int64_t line; + int64_t line = 0; int64_t column = -1; if (pos_lc == std::string::npos) { line = stoi(lineColumn); diff --git a/tools/kore-convert/main.cpp b/tools/kore-convert/main.cpp index 9f083280b..ec12d0c20 100644 --- a/tools/kore-convert/main.cpp +++ b/tools/kore-convert/main.cpp @@ -73,7 +73,8 @@ cl::opt UseSize( cl::cat(KoreConvertCat)); sptr get_input_pattern() { - auto get_text = [&]() { return KOREParser(InputFilename).pattern(); }; + auto get_text + = [&]() { return KOREParser(InputFilename.getValue()).pattern(); }; auto get_binary = [&]() { return deserialize_pattern(InputFilename); }; switch (InputFormat) { diff --git a/tools/llvm-kompile-codegen/main.cpp b/tools/llvm-kompile-codegen/main.cpp index c71f30749..93e808752 100644 --- a/tools/llvm-kompile-codegen/main.cpp +++ b/tools/llvm-kompile-codegen/main.cpp @@ -133,7 +133,7 @@ int main(int argc, char **argv) { validate_codegen_args(OutputFile == "-"); - KOREParser parser(Definition); + KOREParser parser(Definition.getValue()); ptr definition = parser.definition(); definition->preprocess(); diff --git a/tools/llvm-kompile-gc-stats/CMakeLists.txt b/tools/llvm-kompile-gc-stats/CMakeLists.txt index bf9113782..a3e407b38 100644 --- a/tools/llvm-kompile-gc-stats/CMakeLists.txt +++ b/tools/llvm-kompile-gc-stats/CMakeLists.txt @@ -2,7 +2,7 @@ kllvm_add_tool(llvm-kompile-gc-stats main.cpp ) -target_link_libraries(llvm-kompile-gc-stats PUBLIC gmp) +target_link_libraries(llvm-kompile-gc-stats PUBLIC gmp fmt::fmt-header-only) target_compile_options(llvm-kompile-gc-stats PUBLIC -O3) install( diff --git a/tools/llvm-kompile-gc-stats/main.cpp b/tools/llvm-kompile-gc-stats/main.cpp index ff057e65f..114ffbe62 100644 --- a/tools/llvm-kompile-gc-stats/main.cpp +++ b/tools/llvm-kompile-gc-stats/main.cpp @@ -1,5 +1,7 @@ #include +#include + #include #include #include @@ -11,7 +13,7 @@ int main(int argc, char **argv) { char const *usage = "usage: %s [dump|analyze|generation|count] " " [ ]\n"; if (argc < 3) { - fprintf(stderr, usage, argv[0]); + fmt::fprintf(stderr, usage, argv[0]); return 1; } FILE *f = fopen(argv[2], "rb"); @@ -41,8 +43,8 @@ int main(int argc, char **argv) { mpz_init(i); } } - int lowerBound; - int upperBound; + int lowerBound = 0; + int upperBound = 0; mpz_t size; if (generation) { lowerBound = atoi(argv[3]); @@ -56,7 +58,7 @@ int main(int argc, char **argv) { // frame[0] contains the total number of bytes allocated since the last // collection cycle // - // frame[i] for i in [1..2047] contains the total number of bytes that + // frame.at(i) for i in [1..2047] contains the total number of bytes that // survived exactly i collection cycles that are alive at that point in // time. // @@ -66,17 +68,17 @@ int main(int argc, char **argv) { break; } if (dump) { - printf("Collection %zd\n", step); + fmt::printf("Collection %zd\n", step); for (int i = 0; i < 2048; i++) { - printf("%d: %zd\n", i, frame[i]); + fmt::printf("%d: %zd\n", i, frame.at(i)); } - printf("saturated: %zd\n", frame[2048]); + fmt::printf("saturated: %zd\n", frame[2048]); } else if (analyze) { for (int i = 0; i < 2048; i++) { - mpz_add_ui(total[i], total[i], frame[i]); + mpz_add_ui(total.at(i), total.at(i), frame.at(i)); if (i > 0) { - assert(mpz_cmp_ui(total[i - 1], frame[i]) >= 0); - mpz_sub_ui(total[i - 1], total[i - 1], frame[i]); + assert(mpz_cmp_ui(total.at(i - 1), frame.at(i)) >= 0); + mpz_sub_ui(total.at(i - 1), total.at(i - 1), frame.at(i)); } } } else if (generation) { @@ -86,25 +88,25 @@ int main(int argc, char **argv) { mpz_add_ui(size, size, frame[0]); mpz_sub_ui(size, size, frame[1]); } else { - mpz_add_ui(size, size, frame[i]); + mpz_add_ui(size, size, frame.at(i)); } } gmp_printf("%zd: %Zd\n", step, size); } else if (alloc) { - printf("%zd: %zd\n", step, frame[0]); + fmt::printf("%zd: %zd\n", step, frame[0]); } else if (!count) { - fprintf(stderr, usage, argv[0]); + fmt::fprintf(stderr, usage, argv[0]); return 1; } step++; } if (analyze) { for (int i = 0; i < 2047; i++) { - gmp_printf("%d: %Zd\n", i, total[i]); + gmp_printf("%d: %Zd\n", i, total.at(i)); } gmp_printf("saturated: %Zd\n", total[2047]); } else if (count) { - printf("%zd collections\n", step); + fmt::printf("%zd collections\n", step); } return 0; } diff --git a/unittests/runtime-collections/lists.cpp b/unittests/runtime-collections/lists.cpp index fdc23366c..acd0cb2cc 100644 --- a/unittests/runtime-collections/lists.cpp +++ b/unittests/runtime-collections/lists.cpp @@ -39,7 +39,11 @@ char const **getArgumentSortsForTag(uint32_t tag) { void printConfigurationInternal( writer *file, block *subject, char const *sort, bool, void *) { } -void sfprintf(writer *, char const *, ...) { } + +SortStringBuffer +hook_BUFFER_concat_raw(SortStringBuffer, char const *, uint64_t) { + __builtin_unreachable(); +} bool hook_KEQUAL_eq(block *b1, block *b2) { return b1->h.hdr == b2->h.hdr;