diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000000..0c679897b1 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1 @@ +Checks: -*,modernize-*,-modernize-redundant-void-arg,google-readability-braces-around-statements,google-explicit-constructor,google-readability-casting,misc-assert-side-effect,misc-assign-operator-signature,misc-inefficient-algorithm,misc-move-constructor-init,misc-non-copyable-objects,misc-sizeof-container,misc-undelegated-constructor,misc-unused-alias-decls,readability-container-size-empty,readability-redundant-string-cstr diff --git a/gen/aa.cpp b/gen/aa.cpp index 229fd25ea3..f66d8e460d 100644 --- a/gen/aa.cpp +++ b/gen/aa.cpp @@ -71,8 +71,9 @@ DValue *DtoAAIndex(Loc &loc, Type *type, DValue *aa, DValue *key, bool lvalue) { // cast return value LLType *targettype = DtoPtrToType(type); - if (ret->getType() != targettype) + if (ret->getType() != targettype) { ret = DtoBitCast(ret, targettype); + } // Only check bounds for rvalues ('aa[key]'). // Lvalue use ('aa[key] = value') auto-adds an element. @@ -144,8 +145,9 @@ DValue *DtoAAIn(Loc &loc, Type *type, DValue *aa, DValue *key) { // cast return value LLType *targettype = DtoType(type); - if (ret->getType() != targettype) + if (ret->getType() != targettype) { ret = DtoBitCast(ret, targettype); + } return new DImValue(type, ret); } @@ -206,7 +208,8 @@ LLValue *DtoAAEquals(Loc &loc, TOK op, DValue *l, DValue *r) { gIR->CreateCallOrInvoke(func, aaTypeInfo, aaval, abval, "aaEqRes") .getInstruction(); res = gIR->ir->CreateICmpNE(res, DtoConstInt(0)); - if (op == TOKnotequal) + if (op == TOKnotequal) { res = gIR->ir->CreateNot(res); + } return res; } diff --git a/gen/abi-aarch64.cpp b/gen/abi-aarch64.cpp index 74035b41e9..f56383d9c1 100644 --- a/gen/abi-aarch64.cpp +++ b/gen/abi-aarch64.cpp @@ -31,9 +31,10 @@ struct AArch64TargetABI : TargetABI { } } - bool returnInArg(TypeFunction *tf) { - if (tf->isref) + bool returnInArg(TypeFunction *tf) override { + if (tf->isref) { return false; + } // Return structs and static arrays on the stack. The latter is needed // because otherwise LLVM tries to actually return the array in a number @@ -43,16 +44,17 @@ struct AArch64TargetABI : TargetABI { return (rt->ty == Tstruct || rt->ty == Tsarray); } - bool passByVal(Type *t) { return t->toBasetype()->ty == Tstruct; } + bool passByVal(Type *t) override { return t->toBasetype()->ty == Tstruct; } - void rewriteFunctionType(TypeFunction *t, IrFuncTy &fty) { + void rewriteFunctionType(TypeFunction *t, IrFuncTy &fty) override { for (auto arg : fty.args) { - if (!arg->byref) + if (!arg->byref) { rewriteArgument(fty, *arg); + } } } - void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) { + void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) override { // FIXME } @@ -89,7 +91,7 @@ struct AArch64TargetABI : TargetABI { return LLStructType::get(gIR->context(), parts); } - LLValue *prepareVaStart(LLValue *pAp) { + LLValue *prepareVaStart(LLValue *pAp) override { // Since the user only created a char* pointer (ap) on the stack before // invoking va_start, // we first need to allocate the actual __va_list struct and set 'ap' to its @@ -102,7 +104,7 @@ struct AArch64TargetABI : TargetABI { return valistmem; } - void vaCopy(LLValue *pDest, LLValue *src) { + void vaCopy(LLValue *pDest, LLValue *src) override { // Analog to va_start, we need to allocate a new __va_list struct on the // stack, // fill it with a bitcopy of the source struct... @@ -115,13 +117,13 @@ struct AArch64TargetABI : TargetABI { DtoBitCast(pDest, getPtrToType(getVoidPtrType()))); } - LLValue *prepareVaArg(LLValue *pAp) { + LLValue *prepareVaArg(LLValue *pAp) override { // pass a void* pointer to the actual __va_list struct to LLVM's va_arg // intrinsic return DtoLoad(pAp); } - Type *vaListType() { + Type *vaListType() override { // We need to pass the actual va_list type for correct mangling. Simply // using TypeIdentifier here is a bit wonky but works, as long as the name // is actually available in the scope (this is what DMD does, so if a better diff --git a/gen/abi-generic.h b/gen/abi-generic.h index 6c181f6378..236a803431 100644 --- a/gen/abi-generic.h +++ b/gen/abi-generic.h @@ -27,8 +27,9 @@ struct LLTypeMemoryLayout { // Pointer types are folded to an integer type. static LLType *fold(LLType *type) { // T* => integer - if (type->isPointerTy()) + if (type->isPointerTy()) { return LLIntegerType::get(gIR->context(), getTypeBitSize(type)); + } if (LLStructType *structType = isaStruct(type)) { unsigned numElements = structType->getNumElements(); @@ -36,12 +37,14 @@ struct LLTypeMemoryLayout { // fold each element std::vector elements; elements.reserve(numElements); - for (unsigned i = 0; i < numElements; ++i) + for (unsigned i = 0; i < numElements; ++i) { elements.push_back(fold(structType->getElementType(i))); + } // single element? then discard wrapping struct - if (numElements == 1) + if (numElements == 1) { return elements[0]; + } return LLStructType::get(gIR->context(), elements, structType->isPacked()); @@ -52,8 +55,9 @@ struct LLTypeMemoryLayout { LLType *foldedElementType = fold(arrayType->getElementType()); // single element? then fold to scalar - if (numElements == 1) + if (numElements == 1) { return foldedElementType; + } // otherwise: convert to struct of N folded elements std::vector elements(numElements, foldedElementType); @@ -65,10 +69,12 @@ struct LLTypeMemoryLayout { // Checks two LLVM types for memory-layout equivalency. static bool typesAreEquivalent(LLType *a, LLType *b) { - if (a == b) + if (a == b) { return true; - if (!a || !b) + } + if (!a || !b) { return false; + } return fold(a) == fold(b); } @@ -79,7 +85,7 @@ struct LLTypeMemoryLayout { /// Removes padding fields for (non-union-containing!) structs struct RemoveStructPadding : ABIRewrite { /// get a rewritten value back to its original form - LLValue *get(Type *dty, LLValue *v) { + LLValue *get(Type *dty, LLValue *v) override { LLValue *lval = DtoAlloca(dty, ".rewritetmp"); getL(dty, v, lval); return lval; @@ -87,7 +93,7 @@ struct RemoveStructPadding : ABIRewrite { /// get a rewritten value back to its original form and store result in /// provided lvalue - void getL(Type *dty, LLValue *v, LLValue *lval) { + void getL(Type *dty, LLValue *v, LLValue *lval) override { // Make sure the padding is zero, so struct comparisons work. // TODO: Only do this if there's padding, and/or only initialize padding. DtoMemSetZero(lval, DtoConstSize_t(getTypePaddedSize(DtoType(dty)))); @@ -95,12 +101,12 @@ struct RemoveStructPadding : ABIRewrite { } /// put out rewritten value - LLValue *put(DValue *v) { + LLValue *put(DValue *v) override { return DtoUnpaddedStruct(v->getType()->toBasetype(), v->getRVal()); } /// return the transformed type for this rewrite - LLType *type(Type *dty, LLType *t) { + LLType *type(Type *dty, LLType *t) override { return DtoUnpaddedStructType(dty->toBasetype()); } }; @@ -113,8 +119,9 @@ struct RemoveStructPadding : ABIRewrite { */ struct IntegerRewrite : ABIRewrite { static LLType *getIntegerType(unsigned minSizeInBytes) { - if (minSizeInBytes > 8) - return NULL; + if (minSizeInBytes > 8) { + return nullptr; + } unsigned size = minSizeInBytes; switch (minSizeInBytes) { @@ -148,21 +155,23 @@ struct IntegerRewrite : ABIRewrite { return LLTypeMemoryLayout::typesAreEquivalent(llType, integerType); } - LLValue *get(Type *dty, LLValue *v) { + LLValue *get(Type *dty, LLValue *v) override { LLValue *integerDump = DtoAllocaDump(v, dty, ".IntegerRewrite_dump"); LLType *type = DtoType(dty); return loadFromMemory(integerDump, type, ".IntegerRewrite_getResult"); } - void getL(Type *dty, LLValue *v, LLValue *lval) { storeToMemory(v, lval); } + void getL(Type *dty, LLValue *v, LLValue *lval) override { + storeToMemory(v, lval); + } - LLValue *put(DValue *dv) { + LLValue *put(DValue *dv) override { LLValue *address = getAddressOf(dv); LLType *integerType = getIntegerType(dv->getType()->size()); return loadFromMemory(address, integerType, ".IntegerRewrite_putResult"); } - LLType *type(Type *t, LLType *) { return getIntegerType(t->size()); } + LLType *type(Type *t, LLType *) override { return getIntegerType(t->size()); } }; ////////////////////////////////////////////////////////////////////////////// @@ -183,15 +192,17 @@ struct IntegerRewrite : ABIRewrite { struct ExplicitByvalRewrite : ABIRewrite { const size_t alignment; - ExplicitByvalRewrite(size_t alignment = 16) : alignment(alignment) {} + explicit ExplicitByvalRewrite(size_t alignment = 16) : alignment(alignment) {} - LLValue *get(Type *dty, LLValue *v) { + LLValue *get(Type *dty, LLValue *v) override { return DtoLoad(v, ".ExplicitByvalRewrite_getResult"); } - void getL(Type *dty, LLValue *v, LLValue *lval) { DtoAggrCopy(lval, v); } + void getL(Type *dty, LLValue *v, LLValue *lval) override { + DtoAggrCopy(lval, v); + } - LLValue *put(DValue *v) { + LLValue *put(DValue *v) override { if (DtoIsPassedByRef(v->getType())) { LLValue *originalPointer = v->getRVal(); LLType *type = originalPointer->getType()->getPointerElementType(); @@ -205,7 +216,7 @@ struct ExplicitByvalRewrite : ABIRewrite { ".ExplicitByvalRewrite_putResult"); } - LLType *type(Type *dty, LLType *t) { return DtoPtrToType(dty); } + LLType *type(Type *dty, LLType *t) override { return DtoPtrToType(dty); } }; #endif diff --git a/gen/abi-mips64.cpp b/gen/abi-mips64.cpp index e076f6ab59..7c28922413 100644 --- a/gen/abi-mips64.cpp +++ b/gen/abi-mips64.cpp @@ -25,11 +25,12 @@ struct MIPS64TargetABI : TargetABI { IntegerRewrite integerRewrite; const bool Is64Bit; - MIPS64TargetABI(const bool Is64Bit) : Is64Bit(Is64Bit) {} + explicit MIPS64TargetABI(const bool Is64Bit) : Is64Bit(Is64Bit) {} - bool returnInArg(TypeFunction *tf) { - if (tf->isref) + bool returnInArg(TypeFunction *tf) override { + if (tf->isref) { return false; + } // Return structs and static arrays on the stack. The latter is needed // because otherwise LLVM tries to actually return the array in a number @@ -39,19 +40,20 @@ struct MIPS64TargetABI : TargetABI { return (rt->ty == Tstruct || rt->ty == Tsarray); } - bool passByVal(Type *t) { + bool passByVal(Type *t) override { TY ty = t->toBasetype()->ty; return ty == Tstruct || ty == Tsarray; } - void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) { + void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) override { for (auto arg : fty.args) { - if (!arg->byref) + if (!arg->byref) { rewriteArgument(fty, *arg); + } } } - void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) { + void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) override { // FIXME } diff --git a/gen/abi-ppc64.cpp b/gen/abi-ppc64.cpp index bae4f81e6c..5fae84e977 100644 --- a/gen/abi-ppc64.cpp +++ b/gen/abi-ppc64.cpp @@ -25,11 +25,12 @@ struct PPC64TargetABI : TargetABI { IntegerRewrite integerRewrite; const bool Is64Bit; - PPC64TargetABI(const bool Is64Bit) : Is64Bit(Is64Bit) {} + explicit PPC64TargetABI(const bool Is64Bit) : Is64Bit(Is64Bit) {} - bool returnInArg(TypeFunction *tf) { - if (tf->isref) + bool returnInArg(TypeFunction *tf) override { + if (tf->isref) { return false; + } // Return structs and static arrays on the stack. The latter is needed // because otherwise LLVM tries to actually return the array in a number @@ -39,20 +40,21 @@ struct PPC64TargetABI : TargetABI { return (rt->ty == Tstruct || rt->ty == Tsarray); } - bool passByVal(Type *t) { + bool passByVal(Type *t) override { TY ty = t->toBasetype()->ty; return ty == Tstruct || ty == Tsarray; } - void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) { + void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) override { // EXPLICIT PARAMETERS for (auto arg : fty.args) { - if (!arg->byref) + if (!arg->byref) { rewriteArgument(fty, *arg); + } } } - void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) { + void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) override { Type *ty = arg.type->toBasetype(); if (ty->ty == Tstruct || ty->ty == Tsarray) { diff --git a/gen/abi-win64.cpp b/gen/abi-win64.cpp index d6bc0acf72..c066188a44 100644 --- a/gen/abi-win64.cpp +++ b/gen/abi-win64.cpp @@ -35,15 +35,15 @@ struct Win64TargetABI : TargetABI { ExplicitByvalRewrite byvalRewrite; IntegerRewrite integerRewrite; - bool returnInArg(TypeFunction *tf); + bool returnInArg(TypeFunction *tf) override; - bool passByVal(Type *t); + bool passByVal(Type *t) override; - bool passThisBeforeSret(TypeFunction *tf); + bool passThisBeforeSret(TypeFunction *tf) override; - void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty); + void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) override; - void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg); + void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) override; private: // Returns true if the D type is an aggregate: @@ -83,14 +83,16 @@ private: TargetABI *getWin64TargetABI() { return new Win64TargetABI; } bool Win64TargetABI::returnInArg(TypeFunction *tf) { - if (tf->isref) + if (tf->isref) { return false; + } Type *rt = tf->next->toBasetype(); // * let LLVM return 80-bit real/ireal on the x87 stack, for DMD compliance - if (realIs80bits() && (rt->ty == Tfloat80 || rt->ty == Timaginary80)) + if (realIs80bits() && (rt->ty == Tfloat80 || rt->ty == Timaginary80)) { return false; + } // * all POD types <= 64 bits and of a size that is a power of 2 // (incl. 2x32-bit cfloat) are returned in a register (RAX, or @@ -108,18 +110,21 @@ bool Win64TargetABI::passThisBeforeSret(TypeFunction *tf) { void Win64TargetABI::rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) { // RETURN VALUE - if (!fty.ret->byref && fty.ret->type->toBasetype()->ty != Tvoid) + if (!fty.ret->byref && fty.ret->type->toBasetype()->ty != Tvoid) { rewriteArgument(fty, *fty.ret); + } // EXPLICIT PARAMETERS for (auto arg : fty.args) { - if (!arg->byref) + if (!arg->byref) { rewriteArgument(fty, *arg); + } } // extern(D): reverse parameter order for non variadics, for DMD-compliance - if (tf->linkage == LINKd && tf->varargs != 1 && fty.args.size() > 1) + if (tf->linkage == LINKd && tf->varargs != 1 && fty.args.size() > 1) { fty.reverseParams = true; + } } void Win64TargetABI::rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) { diff --git a/gen/abi-x86-64.cpp b/gen/abi-x86-64.cpp index 116bd8a51c..60d02a3014 100644 --- a/gen/abi-x86-64.cpp +++ b/gen/abi-x86-64.cpp @@ -53,16 +53,18 @@ namespace dmd_abi { // needed. LLType *getAbiType(Type *ty) { // First, check if there's any need of a transformation: - if (!(ty->ty == Tcomplex32 || ty->ty == Tstruct || ty->ty == Tsarray)) - return NULL; // Nothing to do + if (!(ty->ty == Tcomplex32 || ty->ty == Tstruct || ty->ty == Tsarray)) { + return nullptr; // Nothing to do + } // Okay, we may need to transform. Figure out a canonical type: TypeTuple *argTypes = toArgTypes(ty); - if (!argTypes || argTypes->arguments->empty()) - return NULL; // don't rewrite + if (!argTypes || argTypes->arguments->empty()) { + return nullptr; // don't rewrite + } - LLType *abiTy = NULL; + LLType *abiTy = nullptr; if (argTypes->arguments->size() == 1) { abiTy = DtoType((*argTypes->arguments->begin())->type); // don't rewrite to a single bit (assertions in tollvm.cpp), choose a byte @@ -76,10 +78,11 @@ LLType *getAbiType(Type *ty) { // corresponding 64-bit type // this makes sure that 64 bits of the chosen register are used and thus // makes sure all potential padding bytes of a struct are copied - if (partType->isIntegerTy()) + if (partType->isIntegerTy()) { partType = LLType::getInt64Ty(gIR->context()); - else if (partType->isFloatTy()) + } else if (partType->isFloatTy()) { partType = LLType::getDoubleTy(gIR->context()); + } parts.push_back(partType); } abiTy = LLStructType::get(gIR->context(), parts); @@ -90,8 +93,9 @@ LLType *getAbiType(Type *ty) { bool passByVal(Type *ty) { TypeTuple *argTypes = toArgTypes(ty); - if (!argTypes) + if (!argTypes) { return false; + } return argTypes->arguments->empty(); // empty => cannot be passed in registers } @@ -118,8 +122,9 @@ struct RegCount { ++int_regs; } else if (ty->isFloatingPointTy() || ty->isVectorTy()) { // X87 reals are passed on the stack - if (!ty->isX86_FP80Ty()) + if (!ty->isX86_FP80Ty()) { ++sse_regs; + } } else { unsigned sizeInBits = gDataLayout->getTypeSizeInBits(ty); IF_LOG Logger::cout() @@ -142,11 +147,13 @@ struct RegCount { const bool anyRegAvailable = (wanted.int_regs > 0 && int_regs > 0) || (wanted.sse_regs > 0 && sse_regs > 0); - if (!anyRegAvailable) + if (!anyRegAvailable) { return ArgumentDoesntFitIn; + } - if (int_regs < wanted.int_regs || sse_regs < wanted.sse_regs) + if (int_regs < wanted.int_regs || sse_regs < wanted.sse_regs) { return ArgumentWouldFitInPartially; + } int_regs -= wanted.int_regs; sse_regs -= wanted.sse_regs; @@ -161,15 +168,17 @@ struct RegCount { * memory so that it's then readable as the other type (i.e., bit-casting). */ struct X86_64_C_struct_rewrite : ABIRewrite { - LLValue *get(Type *dty, LLValue *v) { + LLValue *get(Type *dty, LLValue *v) override { LLValue *address = DtoAllocaDump(v, dty, ".X86_64_C_struct_rewrite_dump"); LLType *type = DtoType(dty); return loadFromMemory(address, type, ".X86_64_C_struct_rewrite_getResult"); } - void getL(Type *dty, LLValue *v, LLValue *lval) { storeToMemory(v, lval); } + void getL(Type *dty, LLValue *v, LLValue *lval) override { + storeToMemory(v, lval); + } - LLValue *put(DValue *v) { + LLValue *put(DValue *v) override { LLValue *address = getAddressOf(v); LLType *abiTy = getAbiType(v->getType()); @@ -178,7 +187,7 @@ struct X86_64_C_struct_rewrite : ABIRewrite { return loadFromMemory(address, abiTy, ".X86_64_C_struct_rewrite_putResult"); } - LLType *type(Type *dty, LLType *t) { return getAbiType(dty); } + LLType *type(Type *dty, LLType *t) override { return getAbiType(dty); } }; /** @@ -190,37 +199,39 @@ struct X86_64_C_struct_rewrite : ABIRewrite { * the ByVal LLVM attribute. */ struct ImplicitByvalRewrite : ABIRewrite { - LLValue *get(Type *dty, LLValue *v) { + LLValue *get(Type *dty, LLValue *v) override { return DtoLoad(v, ".ImplicitByvalRewrite_getResult"); } - void getL(Type *dty, LLValue *v, LLValue *lval) { DtoAggrCopy(lval, v); } + void getL(Type *dty, LLValue *v, LLValue *lval) override { + DtoAggrCopy(lval, v); + } - LLValue *put(DValue *v) { return getAddressOf(v); } + LLValue *put(DValue *v) override { return getAddressOf(v); } - LLType *type(Type *dty, LLType *t) { return DtoPtrToType(dty); } + LLType *type(Type *dty, LLType *t) override { return DtoPtrToType(dty); } }; struct X86_64TargetABI : TargetABI { X86_64_C_struct_rewrite struct_rewrite; ImplicitByvalRewrite byvalRewrite; - bool returnInArg(TypeFunction *tf); + bool returnInArg(TypeFunction *tf) override; - bool passByVal(Type *t); + bool passByVal(Type *t) override; - void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty); - void rewriteVarargs(IrFuncTy &fty, std::vector &args); - void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg); + void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) override; + void rewriteVarargs(IrFuncTy &fty, std::vector &args) override; + void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) override; void rewriteArgument(IrFuncTyArg &arg, RegCount ®Count); - LLValue *prepareVaStart(LLValue *pAp); + LLValue *prepareVaStart(LLValue *pAp) override; - void vaCopy(LLValue *pDest, LLValue *src); + void vaCopy(LLValue *pDest, LLValue *src) override; - LLValue *prepareVaArg(LLValue *pAp); + LLValue *prepareVaArg(LLValue *pAp) override; - Type *vaListType(); + Type *vaListType() override; private: LLType *getValistType(); @@ -233,8 +244,9 @@ private: TargetABI *getX86_64TargetABI() { return new X86_64TargetABI; } bool X86_64TargetABI::returnInArg(TypeFunction *tf) { - if (tf->isref) + if (tf->isref) { return false; + } Type *rt = tf->next; return passByVal(rt); @@ -289,20 +301,24 @@ void X86_64TargetABI::rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) { } // IMPLICIT PARAMETERS - if (fty.arg_sret) + if (fty.arg_sret) { regCount.int_regs--; - if (fty.arg_this || fty.arg_nest) + } + if (fty.arg_this || fty.arg_nest) { regCount.int_regs--; - if (fty.arg_arguments) + } + if (fty.arg_arguments) { regCount.int_regs -= 2; // dynamic array + } // EXPLICIT PARAMETERS Logger::println("x86-64 ABI: Transforming argument types"); LOG_SCOPE; // extern(D): reverse parameter order for non variadics, for DMD-compliance - if (tf->linkage == LINKd && tf->varargs != 1 && fty.args.size() > 1) + if (tf->linkage == LINKd && tf->varargs != 1 && fty.args.size() > 1) { fty.reverseParams = true; + } int begin = 0, end = fty.args.size(), step = 1; if (fty.reverseParams) { @@ -314,8 +330,9 @@ void X86_64TargetABI::rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) { IrFuncTyArg &arg = *fty.args[i]; if (arg.byref) { - if (!arg.isByVal() && regCount.int_regs > 0) + if (!arg.isByVal() && regCount.int_regs > 0) { regCount.int_regs--; + } continue; } @@ -333,10 +350,11 @@ void X86_64TargetABI::rewriteVarargs(IrFuncTy &fty, // fty.tag RegCount regCount = getRegCount(fty); - for (unsigned i = 0; i < args.size(); ++i) { - IrFuncTyArg &arg = *args[i]; - if (!arg.byref) // don't rewrite ByVal arguments + for (auto &Elem : args) { + IrFuncTyArg &arg = *Elem; + if (!arg.byref) { // don't rewrite ByVal arguments rewriteArgument(arg, regCount); + } } } diff --git a/gen/abi-x86.cpp b/gen/abi-x86.cpp index 66295c742c..b32ad69526 100644 --- a/gen/abi-x86.cpp +++ b/gen/abi-x86.cpp @@ -26,7 +26,7 @@ struct X86TargetABI : TargetABI { X86TargetABI() : isOSX(global.params.isOSX) {} - llvm::CallingConv::ID callingConv(llvm::FunctionType *ft, LINK l) { + llvm::CallingConv::ID callingConv(llvm::FunctionType *ft, LINK l) override { switch (l) { case LINKc: case LINKcpp: @@ -42,7 +42,7 @@ struct X86TargetABI : TargetABI { } } - std::string mangleForLLVM(llvm::StringRef name, LINK l) { + std::string mangleForLLVM(llvm::StringRef name, LINK l) override { switch (l) { case LINKc: case LINKcpp: @@ -84,17 +84,19 @@ private: // on the stack. Type *const bt = t->toBasetype(); - if (bt->ty != Tstruct) + if (bt->ty != Tstruct) { return false; + } Identifier *id = static_cast(bt)->sym->ident; return (id == Id::__c_long) || (id == Id::__c_ulong); } public: - bool returnInArg(TypeFunction *tf) { - if (tf->isref) + bool returnInArg(TypeFunction *tf) override { + if (tf->isref) { return false; + } Type *rt = tf->next->toBasetype(); // D only returns structs on the stack @@ -104,8 +106,9 @@ public: // other ABI's follow C, which is cdouble and creal returned on the stack // as well as structs (except for some OSX cases). else { - if (isMagicCLong(rt)) + if (isMagicCLong(rt)) { return false; + } if (rt->ty == Tstruct) { return !isOSX || returnOSXStructInArg((TypeStruct *)rt); @@ -115,11 +118,11 @@ public: } } - bool passByVal(Type *t) { + bool passByVal(Type *t) override { return t->toBasetype()->ty == Tstruct || t->toBasetype()->ty == Tsarray; } - void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) { + void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) override { // extern(D) if (tf->linkage == LINKd) { // IMPLICIT PARAMETERS @@ -228,8 +231,7 @@ public: } } - for (size_t i = 0; i < fty.args.size(); ++i) { - IrFuncTyArg *arg = fty.args[i]; + for (auto arg : fty.args) { if (!arg->byref && isMagicCLong(arg->type)) { arg->rewrite = &integerRewrite; arg->ltype = integerRewrite.type(arg->type, arg->ltype); diff --git a/gen/abi.cpp b/gen/abi.cpp index c648e42aec..c3c036b9f4 100644 --- a/gen/abi.cpp +++ b/gen/abi.cpp @@ -43,8 +43,9 @@ LLValue *ABIRewrite::getAddressOf(DValue *v) { return v->getRVal(); } - if (v->isLVal()) + if (v->isLVal()) { return v->getLVal(); + } return DtoAllocaDump(v, ".getAddressOf_dump"); } @@ -76,8 +77,9 @@ LLValue *ABIRewrite::loadFromMemory(LLValue *address, LLType *asType, assert(pointerType->isPointerTy()); LLType *pointeeType = pointerType->getPointerElementType(); - if (asType == pointeeType) + if (asType == pointeeType) { return DtoLoad(address, name); + } if (getTypeStoreSize(asType) > getTypeAllocSize(pointeeType)) { // not enough allocated memory @@ -96,10 +98,11 @@ LLValue *ABIRewrite::loadFromMemory(LLValue *address, LLType *asType, void TargetABI::rewriteVarargs(IrFuncTy &fty, std::vector &args) { - for (unsigned i = 0; i < args.size(); ++i) { - IrFuncTyArg &arg = *args[i]; - if (!arg.byref) // don't rewrite ByVal arguments + for (auto &Elem : args) { + IrFuncTyArg &arg = *Elem; + if (!arg.byref) { // don't rewrite ByVal arguments rewriteArgument(fty, arg); + } } } @@ -135,9 +138,10 @@ Type *TargetABI::vaListType() { // Some reasonable defaults for when we don't know what ABI to use. struct UnknownTargetABI : TargetABI { - bool returnInArg(TypeFunction *tf) { - if (tf->isref) + bool returnInArg(TypeFunction *tf) override { + if (tf->isref) { return false; + } // Return structs and static arrays on the stack. The latter is needed // because otherwise LLVM tries to actually return the array in a number @@ -147,9 +151,9 @@ struct UnknownTargetABI : TargetABI { return (rt->ty == Tstruct || rt->ty == Tsarray); } - bool passByVal(Type *t) { return t->toBasetype()->ty == Tstruct; } + bool passByVal(Type *t) override { return t->toBasetype()->ty == Tstruct; } - void rewriteFunctionType(TypeFunction *t, IrFuncTy &fty) { + void rewriteFunctionType(TypeFunction *t, IrFuncTy &fty) override { // why? } }; @@ -161,10 +165,11 @@ TargetABI *TargetABI::getTarget() { case llvm::Triple::x86: return getX86TargetABI(); case llvm::Triple::x86_64: - if (global.params.targetTriple.isOSWindows()) + if (global.params.targetTriple.isOSWindows()) { return getWin64TargetABI(); - else + } else { return getX86_64TargetABI(); + } case llvm::Triple::mips: case llvm::Triple::mipsel: case llvm::Triple::mips64: @@ -192,14 +197,15 @@ TargetABI *TargetABI::getTarget() { struct IntrinsicABI : TargetABI { RemoveStructPadding remove_padding; - bool returnInArg(TypeFunction *tf) { return false; } + bool returnInArg(TypeFunction *tf) override { return false; } - bool passByVal(Type *t) { return false; } + bool passByVal(Type *t) override { return false; } - void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) { + void rewriteArgument(IrFuncTy &fty, IrFuncTyArg &arg) override { Type *ty = arg.type->toBasetype(); - if (ty->ty != Tstruct) + if (ty->ty != Tstruct) { return; + } // TODO: Check that no unions are passed in or returned. LLType *abiTy = DtoUnpaddedStructType(arg.type); @@ -210,7 +216,7 @@ struct IntrinsicABI : TargetABI { } } - void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) { + void rewriteFunctionType(TypeFunction *tf, IrFuncTy &fty) override { if (!fty.arg_sret) { Type *rt = fty.ret->type->toBasetype(); if (rt->ty == Tstruct) { @@ -226,8 +232,9 @@ struct IntrinsicABI : TargetABI { IF_LOG Logger::cout() << "Arg: " << arg->type->toChars() << '\n'; // Arguments that are in memory are of no interest to us. - if (arg->byref) + if (arg->byref) { continue; + } rewriteArgument(fty, *arg); diff --git a/gen/abi.h b/gen/abi.h index b2071975ef..e72d1f529e 100644 --- a/gen/abi.h +++ b/gen/abi.h @@ -35,7 +35,7 @@ class FunctionType; // return rewrite rule struct ABIRewrite { - virtual ~ABIRewrite() {} + virtual ~ABIRewrite() = default; /// get a rewritten value back to its original form virtual llvm::Value *get(Type *dty, llvm::Value *v) = 0; @@ -71,7 +71,7 @@ protected: // interface called by codegen struct TargetABI { - virtual ~TargetABI() {} + virtual ~TargetABI() = default; /// Returns the ABI for the target we're compiling for static TargetABI *getTarget(); diff --git a/gen/arrays.cpp b/gen/arrays.cpp index 42c40fe80e..1d81211301 100644 --- a/gen/arrays.cpp +++ b/gen/arrays.cpp @@ -43,9 +43,10 @@ static LLValue *DtoSlice(DValue *dval) { } static LLValue *DtoSlice(LLValue *ptr, LLValue *length, - LLType *elemType = NULL) { - if (elemType == NULL) + LLType *elemType = nullptr) { + if (elemType == nullptr) { elemType = ptr->getType()->getContainedType(0); + } elemType = i1ToI8(voidToI8(elemType)); LLStructType *type = DtoArrayType(elemType); @@ -61,8 +62,9 @@ static LLValue *DtoSlicePtr(DValue *dval) { Loc loc; LLStructType *type = DtoArrayType(LLType::getInt8Ty(gIR->context())); Type *vt = dval->getType()->toBasetype(); - if (vt->ty == Tarray) + if (vt->ty == Tarray) { return makeLValue(loc, dval); + } bool isStaticArray = vt->ty == Tsarray; LLValue *val = isStaticArray ? dval->getRVal() : makeLValue(loc, dval); @@ -125,10 +127,11 @@ static void DtoArrayInit(Loc &loc, LLValue *ptr, LLValue *length, (isaConstant(value)->isNullValue() || value->getType() == LLType::getInt8Ty(gIR->context()))) { LLValue *nbytes = gIR->ir->CreateMul(length, elementSize, ".nbytes"); - if (isaConstant(value)->isNullValue()) + if (isaConstant(value)->isNullValue()) { DtoMemSetZero(ptr, nbytes); - else + } else { DtoMemSet(ptr, value, nbytes); + } return; } @@ -183,8 +186,9 @@ static void DtoArrayInit(Loc &loc, LLValue *ptr, LLValue *length, static Type *DtoArrayElementType(Type *arrayType) { assert(arrayType->toBasetype()->nextOf()); Type *t = arrayType->toBasetype()->nextOf()->toBasetype(); - while (t->ty == Tsarray) + while (t->ty == Tsarray) { t = t->nextOf()->toBasetype(); + } return t; } @@ -211,8 +215,9 @@ static void copySlice(Loc &loc, LLValue *dstarr, LLValue *sz1, LLValue *srcarr, // Determine whether t is an array of structs that need a postblit. static bool arrayNeedsPostblit(Type *t) { t = DtoArrayElementType(t); - if (t->ty == Tstruct) - return static_cast(t)->sym->postblit != NULL; + if (t->ty == Tstruct) { + return static_cast(t)->sym->postblit != nullptr; + } return false; } @@ -231,10 +236,11 @@ void DtoArrayAssign(Loc &loc, DValue *lhs, DValue *rhs, int op, // reference assignment for dynamic array? if (t->ty == Tarray && !lhs->isSlice()) { assert(t2->ty == Tarray || t2->ty == Tsarray); - if (rhs->isNull()) + if (rhs->isNull()) { DtoSetArrayToNull(lhs->getLVal()); - else + } else { DtoSetArray(lhs, DtoArrayLen(rhs), DtoArrayPtr(rhs)); + } return; } @@ -256,7 +262,7 @@ void DtoArrayAssign(Loc &loc, DValue *lhs, DValue *rhs, int op, // for DMD issue 7493). // TODO: This should use AssignExp::ismemset. LLValue *realRhsArrayPtr = - (t2->ty == Tarray || t2->ty == Tsarray ? DtoArrayPtr(rhs) : NULL); + (t2->ty == Tarray || t2->ty == Tsarray ? DtoArrayPtr(rhs) : nullptr); if (realRhsArrayPtr && realRhsArrayPtr->getType() == realLhsPtr->getType()) { // T[] = T[] T[] = T[n] // T[n] = T[n] T[n] = T[] @@ -364,17 +370,18 @@ LLConstant *DtoConstArrayInitializer(ArrayInitializer *arrinit, // get elem type Type *elemty; - if (arrty->ty == Tvector) + if (arrty->ty == Tvector) { elemty = static_cast(arrty)->elementType(); - else + } else { elemty = arrty->nextOf(); + } LLType *llelemty = DtoMemType(elemty); // true if array elements differ in type, can happen with array of unions bool mismatch = false; // allocate room for initializers - std::vector initvals(arrlen, NULL); + std::vector initvals(arrlen, nullptr); // go through each initializer, they're not sorted by index by the frontend size_t j = 0; @@ -383,8 +390,9 @@ LLConstant *DtoConstArrayInitializer(ArrayInitializer *arrinit, Expression *idx = static_cast(arrinit->index.data[i]); // idx can be null, then it's just the next element - if (idx) + if (idx) { j = idx->toInteger(); + } assert(j < arrlen); // get value @@ -392,33 +400,36 @@ LLConstant *DtoConstArrayInitializer(ArrayInitializer *arrinit, assert(val); // error check from dmd - if (initvals[j] != NULL) { + if (initvals[j] != nullptr) { error(arrinit->loc, "duplicate initialization for index %llu", static_cast(j)); } LLConstant *c = DtoConstInitializer(val->loc, elemty, val); assert(c); - if (c->getType() != llelemty) + if (c->getType() != llelemty) { mismatch = true; + } initvals[j] = c; j++; } // die now if there was errors - if (global.errors) + if (global.errors) { fatal(); + } // Fill out any null entries still left with default values. // Element default initializer. Compute lazily to be able to avoid infinite // recursion for types with members that are default initialized to empty // arrays of themselves. - LLConstant *elemDefaultInit = NULL; + LLConstant *elemDefaultInit = nullptr; for (size_t i = 0; i < arrlen; i++) { - if (initvals[i] != NULL) + if (initvals[i] != nullptr) { continue; + } if (!elemDefaultInit) { elemDefaultInit = DtoConstExpInit(arrinit->loc, elemty, @@ -432,34 +443,37 @@ LLConstant *DtoConstArrayInitializer(ArrayInitializer *arrinit, } LLConstant *constarr; - if (mismatch) + if (mismatch) { constarr = LLConstantStruct::getAnon(gIR->context(), initvals); // FIXME should this pack? - else { - if (arrty->ty == Tvector) + } else { + if (arrty->ty == Tvector) { constarr = llvm::ConstantVector::get(initvals); - else + } else { constarr = LLConstantArray::get(LLArrayType::get(llelemty, arrlen), initvals); + } } // std::cout << "constarr: " << *constarr << std::endl; // if the type is a static array, we're done - if (arrty->ty == Tsarray || arrty->ty == Tvector) + if (arrty->ty == Tsarray || arrty->ty == Tvector) { return constarr; + } // we need to make a global with the data, so we have a pointer to the array // Important: don't make the gvar constant, since this const initializer might // be used as an initializer for a static T[] - where modifying contents is // allowed. - LLGlobalVariable *gvar = new LLGlobalVariable( - gIR->module, constarr->getType(), false, LLGlobalValue::InternalLinkage, - constarr, ".constarray"); + auto gvar = new LLGlobalVariable(gIR->module, constarr->getType(), false, + LLGlobalValue::InternalLinkage, constarr, + ".constarray"); - if (arrty->ty == Tpointer) + if (arrty->ty == Tpointer) { // we need to return pointer to the static array. return DtoBitCast(gvar, DtoType(arrty)); + } LLConstant *idxs[2] = {DtoConstUint(0), DtoConstUint(0)}; @@ -482,8 +496,9 @@ bool isConstLiteral(ArrayLiteralExp *ale) { for (size_t i = 0; i < ale->elements->dim; ++i) { // We have to check specifically for '1', as SymOffExp is classified as // '2' and the address of a local variable is not an LLVM constant. - if ((*ale->elements)[i]->isConst() != 1) + if ((*ale->elements)[i]->isConst() != 1) { return false; + } } return true; } @@ -495,22 +510,24 @@ llvm::Constant *arrayLiteralToConst(IRState *p, ArrayLiteralExp *ale) { // element types (with different fields being initialized), we can end up // with different types for the initializer values. In this case, we // generate a packed struct constant instead of an array constant. - LLType *elementType = NULL; + LLType *elementType = nullptr; bool differentTypes = false; std::vector vals; vals.reserve(ale->elements->dim); for (unsigned i = 0; i < ale->elements->dim; ++i) { llvm::Constant *val = toConstElem((*ale->elements)[i], p); - if (!elementType) + if (!elementType) { elementType = val->getType(); - else + } else { differentTypes |= (elementType != val->getType()); + } vals.push_back(val); } - if (differentTypes) + if (differentTypes) { return llvm::ConstantStruct::getAnon(vals, true); + } if (!elementType) { assert(ale->elements->dim == 0); @@ -529,8 +546,9 @@ void initializeArrayLiteral(IRState *p, ArrayLiteralExp *ale, LLValue *dstMem) { // Don't try to write nothing to a zero-element array, we might represent it // as a null pointer. - if (elemCount == 0) + if (elemCount == 0) { return; + } if (isConstLiteral(ale)) { llvm::Constant *constarr = arrayLiteralToConst(p, ale); @@ -542,9 +560,9 @@ void initializeArrayLiteral(IRState *p, ArrayLiteralExp *ale, LLValue *dstMem) { if (elemCount <= 4) { DtoStore(constarr, DtoBitCast(dstMem, getPtrToType(constarr->getType()))); } else { - llvm::GlobalVariable *gvar = new llvm::GlobalVariable( - gIR->module, constarr->getType(), true, - LLGlobalValue::InternalLinkage, constarr, ".arrayliteral"); + auto gvar = new llvm::GlobalVariable(gIR->module, constarr->getType(), + true, LLGlobalValue::InternalLinkage, + constarr, ".arrayliteral"); gvar->setUnnamedAddr(true); DtoMemCpy(dstMem, gvar, DtoConstSize_t(getTypePaddedSize(constarr->getType()))); @@ -555,7 +573,7 @@ void initializeArrayLiteral(IRState *p, ArrayLiteralExp *ale, LLValue *dstMem) { DValue *e = toElem((*ale->elements)[i]); LLValue *elemAddr = DtoGEPi(dstMem, 0, i, "", p->scopebb()); - DVarValue *vv = new DVarValue(e->type, elemAddr); + auto vv = new DVarValue(e->type, elemAddr); DtoAssign(ale->loc, vv, e, TOKconstruct, true); } } @@ -580,8 +598,9 @@ static DSliceValue *getSlice(Type *arrayType, LLValue *array) { // cast pointer to wanted type LLType *dstType = DtoType(arrayType)->getContainedType(1); - if (newptr->getType() != dstType) + if (newptr->getType() != dstType) { newptr = DtoBitCast(newptr, dstType, ".gc_mem"); + } return new DSliceValue(arrayType, arrayLen, newptr); } @@ -627,8 +646,9 @@ DSliceValue *DtoNewMulDimDynArray(Loc &loc, Type *arrayType, DValue **dims, // get value type Type *vtype = arrayType->toBasetype(); - for (size_t i = 0; i < ndims; ++i) + for (size_t i = 0; i < ndims; ++i) { vtype = vtype->nextOf(); + } // get runtime function const char *fnname = @@ -638,8 +658,9 @@ DSliceValue *DtoNewMulDimDynArray(Loc &loc, Type *arrayType, DValue **dims, // Check if constant bool allDimsConst = true; for (size_t i = 0; i < ndims; ++i) { - if (!isaConstant(dims[i]->getRVal())) + if (!isaConstant(dims[i]->getRVal())) { allDimsConst = false; + } } // build dims @@ -654,16 +675,17 @@ DSliceValue *DtoNewMulDimDynArray(Loc &loc, Type *arrayType, DValue **dims, llvm::Constant *dims = llvm::ConstantArray::get( llvm::ArrayType::get(DtoSize_t(), ndims), argsdims); - LLGlobalVariable *gvar = new llvm::GlobalVariable( - gIR->module, dims->getType(), true, LLGlobalValue::InternalLinkage, - dims, ".dimsarray"); + auto gvar = new llvm::GlobalVariable(gIR->module, dims->getType(), true, + LLGlobalValue::InternalLinkage, dims, + ".dimsarray"); array = llvm::ConstantExpr::getBitCast(gvar, getPtrToType(dims->getType())); } else { // Build static array for dimensions LLArrayType *type = LLArrayType::get(DtoSize_t(), ndims); array = DtoRawAlloca(type, 0, ".dimarray"); - for (size_t i = 0; i < ndims; ++i) + for (size_t i = 0; i < ndims; ++i) { DtoStore(dims[i]->getRVal(), DtoGEPi(array, 0, i, ".ndim")); + } } LLStructType *dtype = DtoArrayType(DtoSize_t()); @@ -774,7 +796,7 @@ DSliceValue *DtoCatArrays(Loc &loc, Type *arrayType, Expression *exp1, LOG_SCOPE; llvm::SmallVector args; - LLFunction *fn = 0; + LLFunction *fn = nullptr; if (exp1->op == TOKcat) { // handle multiple concat fn = LLVM_D_GetRuntimeFunction(loc, gIR->module, "_d_arraycatnTX"); @@ -915,24 +937,26 @@ static LLValue *DtoArrayEqCmp_impl(Loc &loc, const char *func, DValue *l, LLValue *DtoArrayEquals(Loc &loc, TOK op, DValue *l, DValue *r) { LLValue *res = DtoArrayEqCmp_impl(loc, "_adEq2", l, r, true); res = gIR->ir->CreateICmpNE(res, DtoConstInt(0)); - if (op == TOKnotequal) + if (op == TOKnotequal) { res = gIR->ir->CreateNot(res); + } return res; } ////////////////////////////////////////////////////////////////////////////////////////// LLValue *DtoArrayCompare(Loc &loc, TOK op, DValue *l, DValue *r) { - LLValue *res = 0; + LLValue *res = nullptr; llvm::ICmpInst::Predicate cmpop; tokToIcmpPred(op, false, &cmpop, &res); if (!res) { Type *t = l->getType()->toBasetype()->nextOf()->toBasetype(); - if (t->ty == Tchar) + if (t->ty == Tchar) { res = DtoArrayEqCmp_impl(loc, "_adCmpChar", l, r, false); - else + } else { res = DtoArrayEqCmp_impl(loc, "_adCmp2", l, r, true); + } res = gIR->ir->CreateICmp(cmpop, res, DtoConstInt(0)); } @@ -952,8 +976,9 @@ LLValue *DtoArrayCastLength(Loc &loc, LLValue *len, LLType *elemty, size_t esz = getTypePaddedSize(elemty); size_t nsz = getTypePaddedSize(newelemty); - if (esz == nsz) + if (esz == nsz) { return len; + } LLFunction *fn = LLVM_D_GetRuntimeFunction(loc, gIR->module, "_d_array_cast_len"); @@ -994,12 +1019,13 @@ LLValue *DtoArrayLen(DValue *v) { Type *t = v->getType()->toBasetype(); if (t->ty == Tarray) { - if (DSliceValue *s = v->isSlice()) + if (DSliceValue *s = v->isSlice()) { return s->len; - else if (v->isNull()) + } else if (v->isNull()) { return DtoConstSize_t(0); - else if (v->isLVal()) + } else if (v->isLVal()) { return DtoLoad(DtoGEPi(v->getLVal(), 0, 0), ".len"); + } return gIR->ir->CreateExtractValue(v->getRVal(), 0, ".len"); } else if (t->ty == Tsarray) { assert(!v->isSlice()); @@ -1020,23 +1046,25 @@ LLValue *DtoArrayPtr(DValue *v) { // v's LL array element type may not be the real one // due to implicit casts (e.g., to base class) LLType *wantedLLPtrType = DtoPtrToType(t->nextOf()); - LLValue *ptr = NULL; + LLValue *ptr = nullptr; if (t->ty == Tarray) { - if (DSliceValue *s = v->isSlice()) + if (DSliceValue *s = v->isSlice()) { ptr = s->ptr; - else if (v->isNull()) + } else if (v->isNull()) { ptr = getNullPtr(wantedLLPtrType); - else if (v->isLVal()) + } else if (v->isLVal()) { ptr = DtoLoad(DtoGEPi(v->getLVal(), 0, 1), ".ptr"); - else + } else { ptr = gIR->ir->CreateExtractValue(v->getRVal(), 1, ".ptr"); + } } else if (t->ty == Tsarray) { assert(!v->isSlice()); assert(!v->isNull()); ptr = DtoGEPi(v->getRVal(), 0, 0, "sarrayptr"); - } else + } else { llvm_unreachable("Unexpected array type."); + } return DtoBitCast(ptr, wantedLLPtrType); } @@ -1064,8 +1092,9 @@ DValue *DtoCastArray(Loc &loc, DValue *u, Type *to) { if (totype->ty == Tpointer) { IF_LOG Logger::cout() << "to pointer" << '\n'; rval = DtoArrayPtr(u); - if (rval->getType() != tolltype) + if (rval->getType() != tolltype) { rval = gIR->ir->CreateBitCast(rval, tolltype); + } } else if (totype->ty == Tarray) { IF_LOG Logger::cout() << "to array" << '\n'; @@ -1091,13 +1120,15 @@ DValue *DtoCastArray(Loc &loc, DValue *u, Type *to) { uinteger_t len = static_cast(fromtype)->dim->toUInteger(); rval2 = LLConstantInt::get(DtoSize_t(), len, false); - if (fromtype->nextOf()->size() != totype->nextOf()->size()) + if (fromtype->nextOf()->size() != totype->nextOf()->size()) { rval2 = DtoArrayCastLength(loc, rval2, ety, ptrty->getContainedType(0)); + } rval = DtoBitCast(uval, ptrty); } else { rval2 = DtoArrayLen(u); - if (fromtype->nextOf()->size() != totype->nextOf()->size()) + if (fromtype->nextOf()->size() != totype->nextOf()->size()) { rval2 = DtoArrayCastLength(loc, rval2, ety, ptrty->getContainedType(0)); + } rval = DtoArrayPtr(u); rval = DtoBitCast(rval, ptrty); @@ -1129,8 +1160,9 @@ DValue *DtoCastArray(Loc &loc, DValue *u, Type *to) { } else { rval = DtoArrayPtr(u); rval = DtoBitCast(rval, getPtrToType(tolltype)); - if (totype->ty != Tstruct) + if (totype->ty != Tstruct) { rval = DtoLoad(rval); + } } if (isslice) { diff --git a/gen/arrays.h b/gen/arrays.h index 60b7daee68..aa9aebfa9c 100644 --- a/gen/arrays.h +++ b/gen/arrays.h @@ -35,7 +35,8 @@ llvm::ArrayType *DtoStaticArrayType(Type *sarrayTy); /// ArrayInitializers for vectors typed as static arrays. LLConstant *DtoConstArrayInitializer(ArrayInitializer *si, Type *targetType); -LLConstant *DtoConstSlice(LLConstant *dim, LLConstant *ptr, Type *type = 0); +LLConstant *DtoConstSlice(LLConstant *dim, LLConstant *ptr, + Type *type = nullptr); /// Returns whether the array literal can be evaluated to a (LLVM) constant. bool isConstLiteral(ArrayLiteralExp *ale); diff --git a/gen/asm-x86.h b/gen/asm-x86.h index edf6f04aa2..2f6591e14c 100644 --- a/gen/asm-x86.h +++ b/gen/asm-x86.h @@ -185,134 +185,134 @@ static struct { char size; signed char baseReg; // %% todo: Reg, Reg_XX } regInfo[N_Regs] = { - {"EAX", NULL_TREE, NULL, 4, Reg_EAX}, - {"EBX", NULL_TREE, NULL, 4, Reg_EBX}, - {"ECX", NULL_TREE, NULL, 4, Reg_ECX}, - {"EDX", NULL_TREE, NULL, 4, Reg_EDX}, - {"ESI", NULL_TREE, NULL, 4, Reg_ESI}, - {"EDI", NULL_TREE, NULL, 4, Reg_EDI}, - {"EBP", NULL_TREE, NULL, 4, Reg_EBP}, - {"ESP", NULL_TREE, NULL, 4, Reg_ESP}, - {"ST", NULL_TREE, NULL, 10, Reg_ST}, - {"ST(1)", NULL_TREE, NULL, 10, Reg_ST1}, - {"ST(2)", NULL_TREE, NULL, 10, Reg_ST2}, - {"ST(3)", NULL_TREE, NULL, 10, Reg_ST3}, - {"ST(4)", NULL_TREE, NULL, 10, Reg_ST4}, - {"ST(5)", NULL_TREE, NULL, 10, Reg_ST5}, - {"ST(6)", NULL_TREE, NULL, 10, Reg_ST6}, - {"ST(7)", NULL_TREE, NULL, 10, Reg_ST7}, - {"MM0", NULL_TREE, NULL, 8, Reg_MM0}, - {"MM1", NULL_TREE, NULL, 8, Reg_MM1}, - {"MM2", NULL_TREE, NULL, 8, Reg_MM2}, - {"MM3", NULL_TREE, NULL, 8, Reg_MM3}, - {"MM4", NULL_TREE, NULL, 8, Reg_MM4}, - {"MM5", NULL_TREE, NULL, 8, Reg_MM5}, - {"MM6", NULL_TREE, NULL, 8, Reg_MM6}, - {"MM7", NULL_TREE, NULL, 8, Reg_MM7}, - {"XMM0", NULL_TREE, NULL, 16, Reg_XMM0}, - {"XMM1", NULL_TREE, NULL, 16, Reg_XMM1}, - {"XMM2", NULL_TREE, NULL, 16, Reg_XMM2}, - {"XMM3", NULL_TREE, NULL, 16, Reg_XMM3}, - {"XMM4", NULL_TREE, NULL, 16, Reg_XMM4}, - {"XMM5", NULL_TREE, NULL, 16, Reg_XMM5}, - {"XMM6", NULL_TREE, NULL, 16, Reg_XMM6}, - {"XMM7", NULL_TREE, NULL, 16, Reg_XMM7}, + {"EAX", NULL_TREE, nullptr, 4, Reg_EAX}, + {"EBX", NULL_TREE, nullptr, 4, Reg_EBX}, + {"ECX", NULL_TREE, nullptr, 4, Reg_ECX}, + {"EDX", NULL_TREE, nullptr, 4, Reg_EDX}, + {"ESI", NULL_TREE, nullptr, 4, Reg_ESI}, + {"EDI", NULL_TREE, nullptr, 4, Reg_EDI}, + {"EBP", NULL_TREE, nullptr, 4, Reg_EBP}, + {"ESP", NULL_TREE, nullptr, 4, Reg_ESP}, + {"ST", NULL_TREE, nullptr, 10, Reg_ST}, + {"ST(1)", NULL_TREE, nullptr, 10, Reg_ST1}, + {"ST(2)", NULL_TREE, nullptr, 10, Reg_ST2}, + {"ST(3)", NULL_TREE, nullptr, 10, Reg_ST3}, + {"ST(4)", NULL_TREE, nullptr, 10, Reg_ST4}, + {"ST(5)", NULL_TREE, nullptr, 10, Reg_ST5}, + {"ST(6)", NULL_TREE, nullptr, 10, Reg_ST6}, + {"ST(7)", NULL_TREE, nullptr, 10, Reg_ST7}, + {"MM0", NULL_TREE, nullptr, 8, Reg_MM0}, + {"MM1", NULL_TREE, nullptr, 8, Reg_MM1}, + {"MM2", NULL_TREE, nullptr, 8, Reg_MM2}, + {"MM3", NULL_TREE, nullptr, 8, Reg_MM3}, + {"MM4", NULL_TREE, nullptr, 8, Reg_MM4}, + {"MM5", NULL_TREE, nullptr, 8, Reg_MM5}, + {"MM6", NULL_TREE, nullptr, 8, Reg_MM6}, + {"MM7", NULL_TREE, nullptr, 8, Reg_MM7}, + {"XMM0", NULL_TREE, nullptr, 16, Reg_XMM0}, + {"XMM1", NULL_TREE, nullptr, 16, Reg_XMM1}, + {"XMM2", NULL_TREE, nullptr, 16, Reg_XMM2}, + {"XMM3", NULL_TREE, nullptr, 16, Reg_XMM3}, + {"XMM4", NULL_TREE, nullptr, 16, Reg_XMM4}, + {"XMM5", NULL_TREE, nullptr, 16, Reg_XMM5}, + {"XMM6", NULL_TREE, nullptr, 16, Reg_XMM6}, + {"XMM7", NULL_TREE, nullptr, 16, Reg_XMM7}, #ifdef ASM_X86_64 - {"RAX", NULL_TREE, NULL, 8, Reg_RAX}, - {"RBX", NULL_TREE, NULL, 8, Reg_RBX}, - {"RCX", NULL_TREE, NULL, 8, Reg_RCX}, - {"RDX", NULL_TREE, NULL, 8, Reg_RDX}, - {"RSI", NULL_TREE, NULL, 8, Reg_RSI}, - {"RDI", NULL_TREE, NULL, 8, Reg_RDI}, - {"RBP", NULL_TREE, NULL, 8, Reg_RBP}, - {"RSP", NULL_TREE, NULL, 8, Reg_RSP}, - {"R8", NULL_TREE, NULL, 8, Reg_R8}, - {"R9", NULL_TREE, NULL, 8, Reg_R9}, - {"R10", NULL_TREE, NULL, 8, Reg_R10}, - {"R11", NULL_TREE, NULL, 8, Reg_R11}, - {"R12", NULL_TREE, NULL, 8, Reg_R12}, - {"R13", NULL_TREE, NULL, 8, Reg_R13}, - {"R14", NULL_TREE, NULL, 8, Reg_R14}, - {"R15", NULL_TREE, NULL, 8, Reg_R15}, - {"R8B", NULL_TREE, NULL, 1, Reg_R8}, - {"R9B", NULL_TREE, NULL, 1, Reg_R9}, - {"R10B", NULL_TREE, NULL, 1, Reg_R10}, - {"R11B", NULL_TREE, NULL, 1, Reg_R11}, - {"R12B", NULL_TREE, NULL, 1, Reg_R12}, - {"R13B", NULL_TREE, NULL, 1, Reg_R13}, - {"R14B", NULL_TREE, NULL, 1, Reg_R14}, - {"R15B", NULL_TREE, NULL, 1, Reg_R15}, - {"R8W", NULL_TREE, NULL, 2, Reg_R8}, - {"R9W", NULL_TREE, NULL, 2, Reg_R9}, - {"R10W", NULL_TREE, NULL, 2, Reg_R10}, - {"R11W", NULL_TREE, NULL, 2, Reg_R11}, - {"R12W", NULL_TREE, NULL, 2, Reg_R12}, - {"R13W", NULL_TREE, NULL, 2, Reg_R13}, - {"R14W", NULL_TREE, NULL, 2, Reg_R14}, - {"R15W", NULL_TREE, NULL, 2, Reg_R15}, - {"R8D", NULL_TREE, NULL, 4, Reg_R8}, - {"R9D", NULL_TREE, NULL, 4, Reg_R9}, - {"R10D", NULL_TREE, NULL, 4, Reg_R10}, - {"R11D", NULL_TREE, NULL, 4, Reg_R11}, - {"R12D", NULL_TREE, NULL, 4, Reg_R12}, - {"R13D", NULL_TREE, NULL, 4, Reg_R13}, - {"R14D", NULL_TREE, NULL, 4, Reg_R14}, - {"R15D", NULL_TREE, NULL, 4, Reg_R15}, - {"XMM8", NULL_TREE, NULL, 16, Reg_XMM8}, - {"XMM9", NULL_TREE, NULL, 16, Reg_XMM9}, - {"XMM10", NULL_TREE, NULL, 16, Reg_XMM10}, - {"XMM11", NULL_TREE, NULL, 16, Reg_XMM11}, - {"XMM12", NULL_TREE, NULL, 16, Reg_XMM12}, - {"XMM13", NULL_TREE, NULL, 16, Reg_XMM13}, - {"XMM14", NULL_TREE, NULL, 16, Reg_XMM14}, - {"XMM15", NULL_TREE, NULL, 16, Reg_XMM15}, - {"RIP", NULL_TREE, NULL, 8, Reg_RIP}, - {"SIL", NULL_TREE, NULL, 1, Reg_SIL}, - {"DIL", NULL_TREE, NULL, 1, Reg_DIL}, - {"BPL", NULL_TREE, NULL, 1, Reg_BPL}, - {"SPL", NULL_TREE, NULL, 1, Reg_SPL}, + {"RAX", NULL_TREE, nullptr, 8, Reg_RAX}, + {"RBX", NULL_TREE, nullptr, 8, Reg_RBX}, + {"RCX", NULL_TREE, nullptr, 8, Reg_RCX}, + {"RDX", NULL_TREE, nullptr, 8, Reg_RDX}, + {"RSI", NULL_TREE, nullptr, 8, Reg_RSI}, + {"RDI", NULL_TREE, nullptr, 8, Reg_RDI}, + {"RBP", NULL_TREE, nullptr, 8, Reg_RBP}, + {"RSP", NULL_TREE, nullptr, 8, Reg_RSP}, + {"R8", NULL_TREE, nullptr, 8, Reg_R8}, + {"R9", NULL_TREE, nullptr, 8, Reg_R9}, + {"R10", NULL_TREE, nullptr, 8, Reg_R10}, + {"R11", NULL_TREE, nullptr, 8, Reg_R11}, + {"R12", NULL_TREE, nullptr, 8, Reg_R12}, + {"R13", NULL_TREE, nullptr, 8, Reg_R13}, + {"R14", NULL_TREE, nullptr, 8, Reg_R14}, + {"R15", NULL_TREE, nullptr, 8, Reg_R15}, + {"R8B", NULL_TREE, nullptr, 1, Reg_R8}, + {"R9B", NULL_TREE, nullptr, 1, Reg_R9}, + {"R10B", NULL_TREE, nullptr, 1, Reg_R10}, + {"R11B", NULL_TREE, nullptr, 1, Reg_R11}, + {"R12B", NULL_TREE, nullptr, 1, Reg_R12}, + {"R13B", NULL_TREE, nullptr, 1, Reg_R13}, + {"R14B", NULL_TREE, nullptr, 1, Reg_R14}, + {"R15B", NULL_TREE, nullptr, 1, Reg_R15}, + {"R8W", NULL_TREE, nullptr, 2, Reg_R8}, + {"R9W", NULL_TREE, nullptr, 2, Reg_R9}, + {"R10W", NULL_TREE, nullptr, 2, Reg_R10}, + {"R11W", NULL_TREE, nullptr, 2, Reg_R11}, + {"R12W", NULL_TREE, nullptr, 2, Reg_R12}, + {"R13W", NULL_TREE, nullptr, 2, Reg_R13}, + {"R14W", NULL_TREE, nullptr, 2, Reg_R14}, + {"R15W", NULL_TREE, nullptr, 2, Reg_R15}, + {"R8D", NULL_TREE, nullptr, 4, Reg_R8}, + {"R9D", NULL_TREE, nullptr, 4, Reg_R9}, + {"R10D", NULL_TREE, nullptr, 4, Reg_R10}, + {"R11D", NULL_TREE, nullptr, 4, Reg_R11}, + {"R12D", NULL_TREE, nullptr, 4, Reg_R12}, + {"R13D", NULL_TREE, nullptr, 4, Reg_R13}, + {"R14D", NULL_TREE, nullptr, 4, Reg_R14}, + {"R15D", NULL_TREE, nullptr, 4, Reg_R15}, + {"XMM8", NULL_TREE, nullptr, 16, Reg_XMM8}, + {"XMM9", NULL_TREE, nullptr, 16, Reg_XMM9}, + {"XMM10", NULL_TREE, nullptr, 16, Reg_XMM10}, + {"XMM11", NULL_TREE, nullptr, 16, Reg_XMM11}, + {"XMM12", NULL_TREE, nullptr, 16, Reg_XMM12}, + {"XMM13", NULL_TREE, nullptr, 16, Reg_XMM13}, + {"XMM14", NULL_TREE, nullptr, 16, Reg_XMM14}, + {"XMM15", NULL_TREE, nullptr, 16, Reg_XMM15}, + {"RIP", NULL_TREE, nullptr, 8, Reg_RIP}, + {"SIL", NULL_TREE, nullptr, 1, Reg_SIL}, + {"DIL", NULL_TREE, nullptr, 1, Reg_DIL}, + {"BPL", NULL_TREE, nullptr, 1, Reg_BPL}, + {"SPL", NULL_TREE, nullptr, 1, Reg_SPL}, #endif - {"FLAGS", NULL_TREE, NULL, 0, + {"FLAGS", NULL_TREE, nullptr, 0, Reg_EFLAGS}, // the gcc name is "flags"; not used in assembler input - {"CS", NULL_TREE, NULL, 2, -1}, - {"DS", NULL_TREE, NULL, 2, -1}, - {"SS", NULL_TREE, NULL, 2, -1}, - {"ES", NULL_TREE, NULL, 2, -1}, - {"FS", NULL_TREE, NULL, 2, -1}, - {"GS", NULL_TREE, NULL, 2, -1}, - {"AX", NULL_TREE, NULL, 2, Reg_EAX}, - {"BX", NULL_TREE, NULL, 2, Reg_EBX}, - {"CX", NULL_TREE, NULL, 2, Reg_ECX}, - {"DX", NULL_TREE, NULL, 2, Reg_EDX}, - {"SI", NULL_TREE, NULL, 2, Reg_ESI}, - {"DI", NULL_TREE, NULL, 2, Reg_EDI}, - {"BP", NULL_TREE, NULL, 2, Reg_EBP}, - {"SP", NULL_TREE, NULL, 2, Reg_ESP}, - {"AL", NULL_TREE, NULL, 1, Reg_EAX}, - {"AH", NULL_TREE, NULL, 1, Reg_EAX}, - {"BL", NULL_TREE, NULL, 1, Reg_EBX}, - {"BH", NULL_TREE, NULL, 1, Reg_EBX}, - {"CL", NULL_TREE, NULL, 1, Reg_ECX}, - {"CH", NULL_TREE, NULL, 1, Reg_ECX}, - {"DL", NULL_TREE, NULL, 1, Reg_EDX}, - {"DH", NULL_TREE, NULL, 1, Reg_EDX}, - {"CR0", NULL_TREE, NULL, 0, -1}, - {"CR2", NULL_TREE, NULL, 0, -1}, - {"CR3", NULL_TREE, NULL, 0, -1}, - {"CR4", NULL_TREE, NULL, 0, -1}, - {"DR0", NULL_TREE, NULL, 0, -1}, - {"DR1", NULL_TREE, NULL, 0, -1}, - {"DR2", NULL_TREE, NULL, 0, -1}, - {"DR3", NULL_TREE, NULL, 0, -1}, - {"DR6", NULL_TREE, NULL, 0, -1}, - {"DR7", NULL_TREE, NULL, 0, -1}, - {"TR3", NULL_TREE, NULL, 0, -1}, - {"TR4", NULL_TREE, NULL, 0, -1}, - {"TR5", NULL_TREE, NULL, 0, -1}, - {"TR6", NULL_TREE, NULL, 0, -1}, - {"TR7", NULL_TREE, NULL, 0, -1}}; + {"CS", NULL_TREE, nullptr, 2, -1}, + {"DS", NULL_TREE, nullptr, 2, -1}, + {"SS", NULL_TREE, nullptr, 2, -1}, + {"ES", NULL_TREE, nullptr, 2, -1}, + {"FS", NULL_TREE, nullptr, 2, -1}, + {"GS", NULL_TREE, nullptr, 2, -1}, + {"AX", NULL_TREE, nullptr, 2, Reg_EAX}, + {"BX", NULL_TREE, nullptr, 2, Reg_EBX}, + {"CX", NULL_TREE, nullptr, 2, Reg_ECX}, + {"DX", NULL_TREE, nullptr, 2, Reg_EDX}, + {"SI", NULL_TREE, nullptr, 2, Reg_ESI}, + {"DI", NULL_TREE, nullptr, 2, Reg_EDI}, + {"BP", NULL_TREE, nullptr, 2, Reg_EBP}, + {"SP", NULL_TREE, nullptr, 2, Reg_ESP}, + {"AL", NULL_TREE, nullptr, 1, Reg_EAX}, + {"AH", NULL_TREE, nullptr, 1, Reg_EAX}, + {"BL", NULL_TREE, nullptr, 1, Reg_EBX}, + {"BH", NULL_TREE, nullptr, 1, Reg_EBX}, + {"CL", NULL_TREE, nullptr, 1, Reg_ECX}, + {"CH", NULL_TREE, nullptr, 1, Reg_ECX}, + {"DL", NULL_TREE, nullptr, 1, Reg_EDX}, + {"DH", NULL_TREE, nullptr, 1, Reg_EDX}, + {"CR0", NULL_TREE, nullptr, 0, -1}, + {"CR2", NULL_TREE, nullptr, 0, -1}, + {"CR3", NULL_TREE, nullptr, 0, -1}, + {"CR4", NULL_TREE, nullptr, 0, -1}, + {"DR0", NULL_TREE, nullptr, 0, -1}, + {"DR1", NULL_TREE, nullptr, 0, -1}, + {"DR2", NULL_TREE, nullptr, 0, -1}, + {"DR3", NULL_TREE, nullptr, 0, -1}, + {"DR6", NULL_TREE, nullptr, 0, -1}, + {"DR7", NULL_TREE, nullptr, 0, -1}, + {"TR3", NULL_TREE, nullptr, 0, -1}, + {"TR4", NULL_TREE, nullptr, 0, -1}, + {"TR5", NULL_TREE, nullptr, 0, -1}, + {"TR6", NULL_TREE, nullptr, 0, -1}, + {"TR7", NULL_TREE, nullptr, 0, -1}}; typedef enum { No_Type_Needed, @@ -529,14 +529,15 @@ typedef struct { unsigned link; unsigned nOperands() { - if (!operands[0]) + if (!operands[0]) { return 0; - else if (!operands[1]) + } else if (!operands[1]) { return 1; - else if (!operands[2]) + } else if (!operands[2]) { return 2; - else + } else { return 3; + } } } AsmOpInfo; @@ -2042,51 +2043,57 @@ struct AsmProcessor { this->stmt = stmt; token = stmt->tokens; - opInfo = NULL; + opInfo = nullptr; if (!regInfo[0].ident) { char buf[8], *p; for (int i = 0; i < N_Regs; i++) { strncpy(buf, regInfo[i].name, sizeof(buf) - 1); - for (p = buf; *p; p++) + for (p = buf; *p; p++) { *p = std::tolower(*p); + } regInfo[i].gccName = std::string(buf, p - buf); - if ((i <= Reg_ST || i > Reg_ST7) && i != Reg_EFLAGS) + if ((i <= Reg_ST || i > Reg_ST7) && i != Reg_EFLAGS) { regInfo[i].ident = Identifier::idPool(regInfo[i].name); + } } - for (int i = 0; i < N_PtrNames; i++) + for (int i = 0; i < N_PtrNames; i++) { ptrTypeIdentTable[i] = Identifier::idPool(ptrTypeNameTable[i]); + } Handled = new Expression(Loc(), TOKvoid, sizeof(Expression)); ident_seg = Identifier::idPool("seg"); eof_tok.value = TOKeof; - eof_tok.next = 0; + eof_tok.next = nullptr; } } void run() { parse(); } void nextToken() { - if (token->next) + if (token->next) { token = token->next; - else + } else { token = &eof_tok; + } } Token *peekToken() { - if (token->next) + if (token->next) { return token->next; - else + } else { return &eof_tok; + } } void expectEnd() { - if (token->value != TOKeof) + if (token->value != TOKeof) { stmt->error("expected end of statement"); // %% extra at end... + } } void parse() { @@ -2108,10 +2115,11 @@ struct AsmProcessor { case Op_Invalid: break; default: - if (op >= Op_db && op <= Op_de) + if (op >= Op_db && op <= Op_de) { doData(); - else + } else { doInstruction(); + } } } @@ -2152,12 +2160,13 @@ struct AsmProcessor { do { k = (i + j) / 2; l = strcmp(opcode, opData[k].inMnemonic); - if (!l) + if (!l) { return opData[k].asmOp; - else if (l < 0) + } else if (l < 0) { j = k; - else + } else { i = k + 1; + } } while (i != j); stmt->error("unknown opcode '%s'", opcode); @@ -2194,10 +2203,11 @@ struct AsmProcessor { parseOperand(); if (matchOperands(operand_i)) { - AsmCode *asmcode = new AsmCode(N_Regs); + auto asmcode = new AsmCode(N_Regs); - if (formatInstruction(operand_i, asmcode)) + if (formatInstruction(operand_i, asmcode)) { stmt->asmcode = (code *)asmcode; + } } } return; @@ -2227,15 +2237,16 @@ struct AsmProcessor { // } if (matchOperands(operand_i)) { - AsmCode *asmcode = new AsmCode(N_Regs); + auto asmcode = new AsmCode(N_Regs); - if (formatInstruction(operand_i, asmcode)) + if (formatInstruction(operand_i, asmcode)) { stmt->asmcode = (code *)asmcode; + } } } void setAsmCode() { - AsmCode *asmcode = new AsmCode(N_Regs); + auto asmcode = new AsmCode(N_Regs); asmcode->insnTemplate = insnTemplate.str(); Logger::cout() << "insnTemplate = " << asmcode->insnTemplate << '\n'; stmt->asmcode = (code *)asmcode; @@ -2245,8 +2256,9 @@ struct AsmProcessor { bool matchOperands(unsigned nOperands) { bool wrong_number = true; - for (unsigned i = 0; i < nOperands; i++) + for (unsigned i = 0; i < nOperands; i++) { classifyOperand(&operands[i]); + } while (1) { if (nOperands == opInfo->nOperands()) { @@ -2259,12 +2271,14 @@ struct AsmProcessor { switch (opInfo->operands[i] & Opr_ClassMask) { case OprC_Mem: // no FPMem currently - if (operand->cls != Opr_Mem) + if (operand->cls != Opr_Mem) { goto no_match; + } break; case OprC_RFP: - if (!(operand->reg >= Reg_ST && operand->reg <= Reg_ST7)) + if (!(operand->reg >= Reg_ST && operand->reg <= Reg_ST7)) { goto no_match; + } break; default: break; @@ -2274,15 +2288,17 @@ struct AsmProcessor { return true; } no_match: - if (opInfo->linkType == Next_Form) - opInfo = &asmOpInfo[op = (AsmOp)opInfo->link]; - else + if (opInfo->linkType == Next_Form) { + opInfo = &asmOpInfo[op = static_cast(opInfo->link)]; + } else { break; + } } - if (wrong_number) + if (wrong_number) { stmt->error("wrong number of operands"); - else + } else { stmt->error("wrong operand types"); + } return false; } @@ -2300,14 +2316,15 @@ struct AsmProcessor { if (sc->func->naked) { switch (type) { case Arg_Integer: - if (e->type->isunsigned()) + if (e->type->isunsigned()) { insnTemplate << "$" << e->toUInteger(); - else + } else { #ifndef ASM_X86_64 - insnTemplate << "$" << (sinteger_t)e->toInteger(); + insnTemplate << "$" << static_cast(e->toInteger()); #else insnTemplate << "$" << e->toInteger(); #endif + } break; case Arg_Pointer: @@ -2358,8 +2375,8 @@ struct AsmProcessor { AsmArgMode mode = Mode_Input) { if (sc->func->naked) { // taken from above - stmt->error( - "only global variables can be referenced by identifier in naked asm"); + stmt->error("only global variables can be referenced by identifier in " + "naked asm"); return; } @@ -2392,8 +2409,9 @@ struct AsmProcessor { really_have_symbol = !is_localsize; } - if (operand->isOffset && !operand->hasBracket) + if (operand->isOffset && !operand->hasBracket) { return Opr_Immediate; + } if (operand->hasBracket || really_have_symbol) // %% redo for 'offset' function @@ -2420,27 +2438,31 @@ struct AsmProcessor { return Opr_Mem; } - if (operand->reg != Reg_Invalid && !operand->hasNumber) + if (operand->reg != Reg_Invalid && !operand->hasNumber) { return Opr_Reg; + } // should check immediate given (operand->hasNumber); // if (operand->hasNumber || is_localsize) { // size determination not correct if there are symbols Opr_Immediate if (operand->dataSize == Default_Ptr) { - if (operand->constDisplacement < 0x100) + if (operand->constDisplacement < 0x100) { operand->dataSize = Byte_Ptr; - else if (operand->constDisplacement < 0x10000) + } else if (operand->constDisplacement < 0x10000) { operand->dataSize = Short_Ptr; + } #ifndef ASM_X86_64 - else + else { operand->dataSize = Int_Ptr; + } #else - else if (operand->constDisplacement <= 0xFFFFFFFF) + else if (operand->constDisplacement <= 0xFFFFFFFF) { operand->dataSize = Int_Ptr; - else + } else { // This could be possible since we are using 48 bits operand->dataSize = QWord_Ptr; + } #endif } return Opr_Immediate; @@ -2470,8 +2492,9 @@ struct AsmProcessor { case Byte_NoType: return ptrtype == Byte_Ptr; case Word_Types: - if (ptrtype == Byte_Ptr) + if (ptrtype == Byte_Ptr) { return false; + } // drop through case Int_Types: switch (ptrtype) { @@ -2519,10 +2542,11 @@ struct AsmProcessor { break; case Extended_Ptr: // MS C runtime: real = 64-bit double - if (global.params.targetTriple.isWindowsMSVCEnvironment()) + if (global.params.targetTriple.isWindowsMSVCEnvironment()) { type_suffix = 'l'; - else + } else { type_suffix = 't'; + } break; default: return false; @@ -2544,18 +2568,20 @@ struct AsmProcessor { insnTemplate.str(""); // %% todo: special case for something.. - if (opInfo->linkType == Out_Mnemonic) + if (opInfo->linkType == Out_Mnemonic) { mnemonic = alternateMnemonics[opInfo->link]; - else + } else { mnemonic = opIdent->string; + } // handle two-operand form where second arg is ignored. // must be done before type_suffix detection if (op == Op_FidR_P || op == Op_fxch || op == Op_FfdRR_P) { - if (operands[1].cls == Opr_Reg && operands[1].reg == Reg_ST) + if (operands[1].cls == Opr_Reg && operands[1].reg == Reg_ST) { nOperands = 1; - else + } else { stmt->error("instruction allows only ST as second argument"); + } } #ifdef ASM_X86_64 @@ -2578,7 +2604,8 @@ struct AsmProcessor { PtrType min_type = Default_Ptr; PtrType hint_type = Default_Ptr; - /* Default types: This attempts to match the observed behavior of DMD */ + /* Default types: This attempts to match the observed behavior of DMD + */ switch (opInfo->needsType) { case Int_Types: min_type = Byte_Ptr; @@ -2587,29 +2614,33 @@ struct AsmProcessor { min_type = Short_Ptr; break; case FPInt_Types: - if (op == Op_Fis_ST) // integer math instructions + if (op == Op_Fis_ST) { // integer math instructions min_type = Int_Ptr; - else // compare, load, store + } else { // compare, load, store min_type = Short_Ptr; + } break; case FP_Types: min_type = Float_Ptr; break; } - if (op == Op_push && operands[0].cls == Opr_Immediate) + if (op == Op_push && operands[0].cls == Opr_Immediate) { #ifndef ASM_X86_64 min_type = Int_Ptr; #else min_type = QWord_Ptr; #endif + } for (int i = 0; i < nOperands; i++) { - if (hint_type == Default_Ptr && !(opInfo->operands[i] & Opr_NoType)) + if (hint_type == Default_Ptr && !(opInfo->operands[i] & Opr_NoType)) { hint_type = operands[i].dataSizeHint; + } if ((opInfo->operands[i] & Opr_NoType) || - operands[i].dataSize == Default_Ptr) + operands[i].dataSize == Default_Ptr) { continue; + } if (operands[i].cls == Opr_Immediate) { min_type = operands[i].dataSize > min_type ? operands[i].dataSize : min_type; @@ -2622,24 +2653,27 @@ struct AsmProcessor { bool type_ok; if (exact_type == Default_Ptr) { - type_ok = getTypeSuffix((TypeNeeded)opInfo->needsType, hint_type, - type_suffix); - if (!type_ok) - type_ok = getTypeSuffix((TypeNeeded)opInfo->needsType, min_type, - type_suffix); - } else - type_ok = getTypeSuffix((TypeNeeded)opInfo->needsType, exact_type, - type_suffix); + type_ok = getTypeSuffix(static_cast(opInfo->needsType), + hint_type, type_suffix); + if (!type_ok) { + type_ok = getTypeSuffix(static_cast(opInfo->needsType), + min_type, type_suffix); + } + } else { + type_ok = getTypeSuffix(static_cast(opInfo->needsType), + exact_type, type_suffix); + } if (!type_ok) { stmt->error("invalid operand size"); return false; } } else if (op == Op_Branch) { - if (operands[0].dataSize == Far_Ptr) // %% type=Far_Ptr not set by - // Seg:Ofss OTOH, we don't support - // that.. + if (operands[0].dataSize == Far_Ptr) { // %% type=Far_Ptr not set by + // Seg:Ofss OTOH, we don't support + // that.. insnTemplate << 'l'; + } } else if (op == Op_FMath0 || op == Op_FdST0ST1) { operands[0].cls = Opr_Reg; operands[0].reg = Reg_ST1; @@ -2651,9 +2685,9 @@ struct AsmProcessor { switch (op) { case Op_SizedStack: { int mlen = strlen(mnemonic); - if (mnemonic[mlen - 1] == 'd') + if (mnemonic[mlen - 1] == 'd') { insnTemplate.write(mnemonic, mlen - 1); - else { + } else { insnTemplate << mnemonic << 'w'; } } break; @@ -2676,8 +2710,9 @@ struct AsmProcessor { char tc_1; int mlen = strlen(mnemonic); PtrType op1_size = operands[1].dataSize; - if (op1_size == Default_Ptr) + if (op1_size == Default_Ptr) { op1_size = operands[1].dataSizeHint; + } // Need type char for source arg switch (op1_size) { case Byte_Ptr: @@ -2713,8 +2748,9 @@ struct AsmProcessor { insnTemplate << mnemonic; } // the no-operand versions of floating point ops always pop - if (op == Op_FMath0) + if (op == Op_FMath0) { insnTemplate << "p"; + } insnTemplate << type_suffix; break; } @@ -2726,8 +2762,9 @@ struct AsmProcessor { break; case Clb_SizeDXAX: asmcode->regs[Reg_EAX] = true; - if (type_suffix != "b") + if (type_suffix != "b") { asmcode->regs[Reg_EDX] = true; + } break; #ifdef ASM_X86_64 case Clb_SizeRDXRAX: @@ -2740,14 +2777,18 @@ struct AsmProcessor { break; } - if (opInfo->implicitClobbers & Clb_DI) + if (opInfo->implicitClobbers & Clb_DI) { asmcode->regs[Reg_EDI] = true; - if (opInfo->implicitClobbers & Clb_SI) + } + if (opInfo->implicitClobbers & Clb_SI) { asmcode->regs[Reg_ESI] = true; - if (opInfo->implicitClobbers & Clb_CX) + } + if (opInfo->implicitClobbers & Clb_CX) { asmcode->regs[Reg_ECX] = true; - if (opInfo->implicitClobbers & Clb_SP) + } + if (opInfo->implicitClobbers & Clb_SP) { asmcode->regs[Reg_ESP] = true; + } if (opInfo->implicitClobbers & Clb_ST) { /* Can't figure out how to tell GCC that an asm statement leaves an arg pushed on the stack. @@ -2763,8 +2804,9 @@ struct AsmProcessor { asmcode->regs[Reg_ST6] = true; asmcode->regs[Reg_ST7] = true; } - if (opInfo->implicitClobbers & Clb_Flags) + if (opInfo->implicitClobbers & Clb_Flags) { asmcode->regs[Reg_EFLAGS] = true; + } if (op == Op_cpuid) { asmcode->regs[Reg_EAX] = true; asmcode->regs[Reg_EBX] = true; @@ -2775,14 +2817,15 @@ struct AsmProcessor { insnTemplate << ' '; for (int i__ = 0; i__ < nOperands; i__++) { int i; - if (i__ != 0) + if (i__ != 0) { insnTemplate << ", "; - + } fmt = "$"; switch (op) { case Op_mul: - // gas won't accept the two-operand form; skip to the source operand + // gas won't accept the two-operand form; skip to the source + // operand i__ = 1; // drop through case Op_bound: @@ -2805,7 +2848,8 @@ struct AsmProcessor { // DMD doesn't seem to allow this /* if ( opTakesLabel() ) tho... (near ptr would be abs?) - fmt = "$a"; // GAS won't accept "jmp $42"; must be "jmp 42" (rel) or + fmt = "$a"; // GAS won't accept "jmp $42"; must be "jmp 42" + (rel) or "jmp *42" (abs) */ if (opTakesLabel()) { @@ -2821,10 +2865,11 @@ struct AsmProcessor { addOperand("$", Arg_LocalSize, (Expression *)operand->symbolDisplacement.data[0], asmcode); - if (operand->constDisplacement) + if (operand->constDisplacement) { insnTemplate << '+'; - else + } else { break; + } } if (operand->symbolDisplacement.dim) { @@ -2833,24 +2878,26 @@ struct AsmProcessor { (Expression *)operand->symbolDisplacement.data[0], asmcode); - if (operand->constDisplacement) + if (operand->constDisplacement) { insnTemplate << '+'; - else + } else { // skip the addOperand(fmt, Arg_Integer...) below break; + } } addOperand(fmt, Arg_Integer, newIntExp(operand->constDisplacement), asmcode); break; case Opr_Reg: if (opInfo->operands[i] & Opr_Dest) { - Reg clbr_reg = (Reg)regInfo[operand->reg].baseReg; + Reg clbr_reg = static_cast(regInfo[operand->reg].baseReg); if (clbr_reg != Reg_Invalid) { asmcode->regs[clbr_reg] = true; } } - if (opTakesLabel()) + if (opTakesLabel()) { insnTemplate << '*'; + } writeReg(operand->reg); /* insnTemplate << "%"; @@ -2887,9 +2934,10 @@ struct AsmProcessor { if (op != Op_Branch) { writeReg(operand->segmentPrefix); insnTemplate << ':'; - } else - stmt->error( - "Cannot generate a segment prefix for a branching instruction"); + } else { + stmt->error("Cannot generate a segment prefix for a " + "branching instruction"); + } } if ((operand->segmentPrefix != Reg_Invalid && operand->symbolDisplacement.dim == 0) || @@ -2899,17 +2947,20 @@ struct AsmProcessor { insnTemplate << '+'; } operand->constDisplacement = 0; - // addOperand(fmt, Arg_Integer, newIntExp(operand->constDisplacement), + // addOperand(fmt, Arg_Integer, + // newIntExp(operand->constDisplacement), // asmcode); - if (opInfo->operands[i] & Opr_Dest) + if (opInfo->operands[i] & Opr_Dest) { asmcode->clobbersMemory = 1; + } } if (operand->symbolDisplacement.dim) { Expression *e = (Expression *)operand->symbolDisplacement.data[0]; - Declaration *decl = 0; + Declaration *decl = nullptr; - if (e->op == TOKvar) + if (e->op == TOKvar) { decl = ((VarExp *)e)->var; + } if (operand->baseReg != Reg_Invalid && decl && !decl->isDataseg()) { @@ -2949,12 +3000,14 @@ struct AsmProcessor { // FIXME: what is this ? addOperand2("${", ":a}", Arg_FrameRelative, e, asmcode); } - if (opInfo->operands[i] & Opr_Dest) + if (opInfo->operands[i] & Opr_Dest) { asmcode->clobbersMemory = 1; + } } else { // Plain memory reference to variable or reference to label. - /* If in a reg, DMD moves to memory.. even with -O, so we'll do the + /* If in a reg, DMD moves to memory.. even with -O, so we'll + do the same by always using the "m" contraint. @@ -2979,7 +3032,8 @@ struct AsmProcessor { insnTemplate << "_"; } insnTemplate << mangle(decl); - // addOperand2("${", ":c}", Arg_Pointer, e, asmcode); + // addOperand2("${", ":c}", Arg_Pointer, e, + // asmcode); } else { if (use_star) { insnTemplate << '*'; @@ -2997,13 +3051,15 @@ struct AsmProcessor { } } } - if (use_star) + if (use_star) { insnTemplate << '*'; + } if (operand->baseReg != Reg_Invalid || operand->indexReg != Reg_Invalid) { insnTemplate << '('; - if (operand->baseReg != Reg_Invalid) + if (operand->baseReg != Reg_Invalid) { writeReg(operand->baseReg); + } if (operand->indexReg != Reg_Invalid) { insnTemplate << ','; writeReg(operand->indexReg); @@ -3012,8 +3068,9 @@ struct AsmProcessor { } } insnTemplate << ')'; - if (opInfo->operands[i] & Opr_Dest) + if (opInfo->operands[i] & Opr_Dest) { asmcode->clobbersMemory = 1; + } } break; case Opr_Invalid: @@ -3039,7 +3096,7 @@ struct AsmProcessor { } Expression *newRegExp(int regno) { - IntegerExp *e = new IntegerExp(regno); + auto e = new IntegerExp(regno); e->op = TOKmod; return e; } @@ -3078,24 +3135,28 @@ struct AsmProcessor { } if (isIntExp(exp)) { - if (is_offset) + if (is_offset) { invalidExpression(); + } operand->constDisplacement += exp->toInteger(); - if (!operand->inBracket) - operand->hasNumber = 1; - } else if (isRegExp(exp)) { - if (is_offset) - invalidExpression(); if (!operand->inBracket) { - if (operand->reg == Reg_Invalid) - operand->reg = (Reg)exp->toInteger(); - else + operand->hasNumber = 1; + } + } else if (isRegExp(exp)) { + if (is_offset) { + invalidExpression(); + } + if (!operand->inBracket) { + if (operand->reg == Reg_Invalid) { + operand->reg = static_cast(exp->toInteger()); + } else { stmt->error("too many registers in operand (use brackets)"); + } } else { - if (operand->baseReg == Reg_Invalid) - operand->baseReg = (Reg)exp->toInteger(); - else if (operand->indexReg == Reg_Invalid) { - operand->indexReg = (Reg)exp->toInteger(); + if (operand->baseReg == Reg_Invalid) { + operand->baseReg = static_cast(exp->toInteger()); + } else if (operand->indexReg == Reg_Invalid) { + operand->indexReg = static_cast(exp->toInteger()); operand->scale = 1; } else { stmt->error("too many registers memory operand"); @@ -3106,20 +3167,24 @@ struct AsmProcessor { if (v && v->storage_class & STCfield) { operand->constDisplacement += v->offset; - if (!operand->inBracket) + if (!operand->inBracket) { operand->hasNumber = 1; + } } else { if (v && v->type->isscalar()) { - // DMD doesn't check Tcomplex*, and counts Tcomplex32 as Tfloat64 + // DMD doesn't check Tcomplex*, and counts Tcomplex32 as + // Tfloat64 TY ty = v->type->toBasetype()->ty; - operand->dataSizeHint = ty == Tfloat80 || ty == Timaginary80 - ? Extended_Ptr - : (PtrType)v->type->size(Loc()); + operand->dataSizeHint = + ty == Tfloat80 || ty == Timaginary80 + ? Extended_Ptr + : static_cast(v->type->size(Loc())); } if (!operand->symbolDisplacement.dim) { - if (is_offset && !operand->inBracket) + if (is_offset && !operand->inBracket) { operand->isOffset = 1; + } operand->symbolDisplacement.push(exp); } else { stmt->error("too many symbols in operand"); @@ -3150,16 +3215,18 @@ struct AsmProcessor { if (isIntExp(e1) && (!e2 || isIntExp(e2))) { switch (op) { case TOKadd: - if (e2) + if (e2) { e = new AddExp(stmt->loc, e1, e2); - else + } else { e = e1; + } break; case TOKmin: - if (e2) + if (e2) { e = new MinExp(stmt->loc, e1, e2); - else + } else { e = new NegExp(stmt->loc, e1); + } break; case TOKmul: e = new MulExp(stmt->loc, e1, e2); @@ -3224,8 +3291,9 @@ struct AsmProcessor { void parseOperand() { Expression *exp = parseAsmExp(); slotExp(exp); - if (isRegExp(exp)) - operand->dataSize = (PtrType)regInfo[exp->toInteger()].size; + if (isRegExp(exp)) { + operand->dataSize = static_cast(regInfo[exp->toInteger()].size); + } } Expression *parseAsmExp() { return parseCondExp(); } @@ -3235,8 +3303,9 @@ struct AsmProcessor { if (token->value == TOKquestion) { nextToken(); Expression *exp2 = parseCondExp(); - if (token->value != TOKcolon) + if (token->value != TOKcolon) { return exp; + } nextToken(); Expression *exp3 = parseCondExp(); exp = exp->toUInteger() ? exp2 : exp3; @@ -3249,10 +3318,11 @@ struct AsmProcessor { while (token->value == TOKoror) { nextToken(); Expression *exp2 = parseLogAndExp(); - if (isIntExp(exp) && isIntExp(exp2)) + if (isIntExp(exp) && isIntExp(exp2)) { exp = intOp(TOKandand, exp, exp2); - else + } else { stmt->error("bad integral operand"); + } } return exp; } @@ -3262,10 +3332,11 @@ struct AsmProcessor { while (token->value == TOKoror) { nextToken(); Expression *exp2 = parseIncOrExp(); - if (isIntExp(exp) && isIntExp(exp2)) + if (isIntExp(exp) && isIntExp(exp2)) { exp = intOp(TOKoror, exp, exp2); - else + } else { stmt->error("bad integral operand"); + } } return exp; } @@ -3275,10 +3346,11 @@ struct AsmProcessor { while (token->value == TOKor) { nextToken(); Expression *exp2 = parseXOrExp(); - if (isIntExp(exp) && isIntExp(exp2)) + if (isIntExp(exp) && isIntExp(exp2)) { exp = intOp(TOKor, exp, exp2); - else + } else { stmt->error("bad integral operand"); + } } return exp; } @@ -3288,10 +3360,11 @@ struct AsmProcessor { while (token->value == TOKxor) { nextToken(); Expression *exp2 = parseAndExp(); - if (isIntExp(exp) && isIntExp(exp2)) + if (isIntExp(exp) && isIntExp(exp2)) { exp = intOp(TOKxor, exp, exp2); - else + } else { stmt->error("bad integral operand"); + } } return exp; } @@ -3301,10 +3374,11 @@ struct AsmProcessor { while (token->value == TOKand) { nextToken(); Expression *exp2 = parseEqualExp(); - if (isIntExp(exp) && isIntExp(exp2)) + if (isIntExp(exp) && isIntExp(exp2)) { exp = intOp(TOKand, exp, exp2); - else + } else { stmt->error("bad integral operand"); + } } return exp; } @@ -3318,10 +3392,11 @@ struct AsmProcessor { TOK tok = token->value; nextToken(); Expression *exp2 = parseRelExp(); - if (isIntExp(exp) && isIntExp(exp2)) + if (isIntExp(exp) && isIntExp(exp2)) { exp = intOp(tok, exp, exp2); - else + } else { stmt->error("bad integral operand"); + } } default: return exp; @@ -3341,10 +3416,11 @@ struct AsmProcessor { TOK tok = token->value; nextToken(); Expression *exp2 = parseShiftExp(); - if (isIntExp(exp) && isIntExp(exp2)) + if (isIntExp(exp) && isIntExp(exp2)) { exp = intOp(tok, exp, exp2); - else + } else { stmt->error("bad integral operand"); + } } default: return exp; @@ -3385,9 +3461,9 @@ struct AsmProcessor { case TOKadd: nextToken(); e2 = parseMultExp(); - if (isIntExp(e1) && isIntExp(e2)) + if (isIntExp(e1) && isIntExp(e2)) { e1 = intOp(tv, e1, e2); - else { + } else { slotExp(e1); slotExp(e2); e1 = Handled; @@ -3397,11 +3473,11 @@ struct AsmProcessor { // Note: no support for symbol address difference nextToken(); e2 = parseMultExp(); - if (isIntExp(e1) && isIntExp(e2)) + if (isIntExp(e1) && isIntExp(e2)) { e1 = intOp(tv, e1, e2); - else { + } else { slotExp(e1); - e2 = intOp(TOKmin, e2, NULL); // verifies e2 is an int + e2 = intOp(TOKmin, e2, nullptr); // verifies e2 is an int slotExp(e2); e1 = Handled; } @@ -3432,7 +3508,7 @@ struct AsmProcessor { return true; } - operand->indexReg = (Reg)e1->toInteger(); + operand->indexReg = static_cast(e1->toInteger()); operand->scale = e2->toInteger(); switch (operand->scale) { case 1: @@ -3461,12 +3537,13 @@ struct AsmProcessor { case TOKmul: nextToken(); e2 = parseMultExp(); - if (isIntExp(e1) && isIntExp(e2)) + if (isIntExp(e1) && isIntExp(e2)) { e1 = intOp(tv, e1, e2); - else if (tryScale(e1, e2)) + } else if (tryScale(e1, e2)) { e1 = Handled; - else + } else { invalidExpression(); + } continue; case TOKdiv: case TOKmod: @@ -3490,10 +3567,11 @@ struct AsmProcessor { // the spec'd syntax Expression *e; - if (token->value == TOKlbracket) + if (token->value == TOKlbracket) { e = Handled; - else + } else { e = parseUnaExp(); + } // DMD allows multiple bracket expressions. while (token->value == TOKlbracket) { @@ -3503,10 +3581,11 @@ struct AsmProcessor { slotExp(parseAsmExp()); operand->inBracket = 0; - if (token->value == TOKrbracket) + if (token->value == TOKrbracket) { nextToken(); - else + } else { stmt->error("missing ']'"); + } } return e; @@ -3533,9 +3612,11 @@ struct AsmProcessor { case TOKfloat80: return Extended_Ptr; case TOKidentifier: - for (int i = 0; i < N_PtrNames; i++) - if (tok->ident == ptrTypeIdentTable[i]) + for (int i = 0; i < N_PtrNames; i++) { + if (tok->ident == ptrTypeIdentTable[i]) { return ptrTypeValueTable[i]; + } + } break; default: break; @@ -3544,7 +3625,7 @@ struct AsmProcessor { } Expression *parseUnaExp() { - Expression *e = NULL; + Expression *e = nullptr; PtrType ptr_type; // First, check for type prefix. @@ -3553,12 +3634,14 @@ struct AsmProcessor { ptr_type = isPtrType(token); if (ptr_type != Default_Ptr) { - if (operand->dataSize == Default_Ptr) + if (operand->dataSize == Default_Ptr) { operand->dataSize = ptr_type; - else + } else { stmt->error("multiple specifications of operand size"); - } else + } + } else { stmt->error("unknown operand size '%s'", token->toChars()); + } nextToken(); nextToken(); return parseAsmExp(); @@ -3572,8 +3655,9 @@ struct AsmProcessor { stmt->error("'seg' not supported"); e = parseAsmExp(); } else if (token->ident == Id::offset || token->ident == Id::offsetof) { - if (token->ident == Id::offset && !global.params.useDeprecated) + if (token->ident == Id::offset && !global.params.useDeprecated) { stmt->error("offset deprecated, use offsetof"); + } nextToken(); e = parseAsmExp(); e = new AddrExp(stmt->loc, e); @@ -3588,7 +3672,7 @@ struct AsmProcessor { case TOKtilde: nextToken(); e = parseUnaExp(); - return intOp(tv, e, NULL); + return intOp(tv, e, nullptr); default: // primary exp break; @@ -3598,12 +3682,13 @@ struct AsmProcessor { Expression *parsePrimaryExp() { Expression *e; - Identifier *ident = NULL; + Identifier *ident = nullptr; // get rid of short/long prefixes for branches if (opTakesLabel() && - (token->value == TOKint16 || token->value == TOKint64)) + (token->value == TOKint16 || token->value == TOKint64)) { nextToken(); + } switch (token->value) { case TOKint32v: @@ -3639,7 +3724,8 @@ struct AsmProcessor { e = new IdentifierExp(stmt->loc, ident); } - // If this is more than one component ref, it gets complicated: *(&Field + + // If this is more than one component ref, it gets complicated: + // *(&Field + // n) // maybe just do one step at a time.. // simple case is Type.f -> VarDecl(field) @@ -3661,24 +3747,25 @@ struct AsmProcessor { if (e->op == TOKidentifier) { for (int i = 0; i < N_Regs; i++) { if (ident == regInfo[i].ident) { - if ((Reg)i == Reg_ST && token->value == TOKlparen) { + if (static_cast(i) == Reg_ST && token->value == TOKlparen) { nextToken(); switch (token->value) { case TOKint32v: case TOKuns32v: case TOKint64v: case TOKuns64v: - if (token->uns64value < 8) - e = newRegExp((Reg)(Reg_ST + token->uns64value)); - else { + if (token->uns64value < 8) { + e = newRegExp(static_cast(Reg_ST + token->uns64value)); + } else { stmt->error("invalid floating point register index"); e = Handled; } nextToken(); - if (token->value == TOKrparen) + if (token->value == TOKrparen) { nextToken(); - else + } else { stmt->error("expected ')'"); + } return e; default: break; @@ -3687,15 +3774,16 @@ struct AsmProcessor { return Handled; } else if (token->value == TOKcolon) { nextToken(); - if (operand->segmentPrefix != Reg_Invalid) + if (operand->segmentPrefix != Reg_Invalid) { stmt->error("too many segment prefixes"); - else if (i >= Reg_CS && i <= Reg_GS) - operand->segmentPrefix = (Reg)i; - else + } else if (i >= Reg_CS && i <= Reg_GS) { + operand->segmentPrefix = static_cast(i); + } else { stmt->error("'%s' is not a segment register", ident->string); + } return parseAsmExp(); } else { - return newRegExp((Reg)i); + return newRegExp(static_cast(i)); } } } @@ -3708,8 +3796,9 @@ struct AsmProcessor { if (!sc->search(stmt->loc, ident, &scopesym)) { if (LabelDsymbol *labelsym = sc->func->searchLabel(ident)) { e = new DsymbolExp(stmt->loc, labelsym); - if (opTakesLabel()) + if (opTakesLabel()) { return e; + } return new AddrExp(stmt->loc, e); } } @@ -3720,7 +3809,7 @@ struct AsmProcessor { // Special case for floating point constant declarations. if (e->op == TOKfloat64) { - Dsymbol *sym = sc->search(stmt->loc, ident, NULL); + Dsymbol *sym = sc->search(stmt->loc, ident, nullptr); if (sym) { VarDeclaration *v = sym->isVarDeclaration(); if (v) { @@ -3738,8 +3827,9 @@ struct AsmProcessor { goto do_dollar; break; default: - if (op == Op_FMath0 || op == Op_FdST0ST1 || op == Op_FMath) + if (op == Op_FMath0 || op == Op_FdST0ST1 || op == Op_FMath) { return Handled; + } // DMD does not emit an error message here. // invalidExpression(); return Handled; @@ -3767,7 +3857,8 @@ struct AsmProcessor { insnTemplate << ".align\t" << align; #endif } else { - stmt->error("alignment must be a power of 2, not %u", (unsigned)align); + stmt->error("alignment must be a power of 2, not %u", + static_cast(align)); } setAsmCode(); @@ -3884,7 +3975,8 @@ bool getFrameRelativeValue(LLValue *decl, HOST_WIDE_INT *result) { // FIXME // // Using this instead of DECL_RTL for struct args seems like a // // good way to get hit by a truck because it may not agree with - // // non-asm access, but asm code wouldn't know what GCC does anyway. */ + // // non-asm access, but asm code wouldn't know what GCC does + // anyway. */ // rtx r = DECL_INCOMING_RTL(decl); // rtx e1, e2; // @@ -3892,15 +3984,18 @@ bool getFrameRelativeValue(LLValue *decl, HOST_WIDE_INT *result) { // if (r == NULL_RTX) // r = DECL_RTL(decl); // - // if (r != NULL_RTX && GET_CODE(r) == MEM /* && r->frame_related */ ) { + // if (r != NULL_RTX && GET_CODE(r) == MEM /* && r->frame_related */ + // ) { // r = XEXP(r, 0); // if (GET_CODE(r) == PLUS) { // e1 = XEXP(r, 0); // e2 = XEXP(r, 1); - // if (e1 == virtual_incoming_args_rtx && GET_CODE(e2) == CONST_INT) { + // if (e1 == virtual_incoming_args_rtx && GET_CODE(e2) == + // CONST_INT) { // *result = INTVAL(e2) + 8; // %% 8 is 32-bit specific... // return true; - // } else if (e1 == virtual_stack_vars_rtx && GET_CODE(e2) == CONST_INT) + // } else if (e1 == virtual_stack_vars_rtx && GET_CODE(e2) == + // CONST_INT) // { // *result = INTVAL(e2); // %% 8 is 32-bit specific... // return true; @@ -3916,11 +4011,11 @@ bool getFrameRelativeValue(LLValue *decl, HOST_WIDE_INT *result) { } struct AsmParser : public AsmParserCommon { - virtual void run(Scope *sc, AsmStatement *asmst) { + void run(Scope *sc, AsmStatement *asmst) override { AsmProcessor ap(sc, asmst); ap.run(); } - virtual std::string getRegName(int i) { return regInfo[i].gccName; } + std::string getRegName(int i) override { return regInfo[i].gccName; } }; } diff --git a/gen/asmstmt.cpp b/gen/asmstmt.cpp index c4c4fa0d6d..905ed915d2 100644 --- a/gen/asmstmt.cpp +++ b/gen/asmstmt.cpp @@ -63,7 +63,7 @@ struct AsmCode { std::vector regs; unsigned dollarLabel; int clobbersMemory; - AsmCode(int n_regs) { + explicit AsmCode(int n_regs) { regs.resize(n_regs, false); dollarLabel = 0; clobbersMemory = 0; @@ -72,17 +72,17 @@ struct AsmCode { AsmStatement::AsmStatement(Loc loc, Token *tokens) : Statement(loc) { this->tokens = tokens; // Do I need to copy these? - asmcode = 0; + asmcode = nullptr; asmalign = 0; refparam = 0; naked = 0; - isBranchToLabel = NULL; + isBranchToLabel = nullptr; } Statement *AsmStatement::syntaxCopy() { // copy tokens? copy 'code'? - AsmStatement *a_s = new AsmStatement(loc, tokens); + auto a_s = new AsmStatement(loc, tokens); a_s->asmcode = asmcode; a_s->refparam = refparam; a_s->naked = naked; @@ -90,11 +90,11 @@ Statement *AsmStatement::syntaxCopy() { } struct AsmParserCommon { - virtual ~AsmParserCommon() {} + virtual ~AsmParserCommon() = default; virtual void run(Scope *sc, AsmStatement *asmst) = 0; virtual std::string getRegName(int i) = 0; }; -AsmParserCommon *asmparser = NULL; +AsmParserCommon *asmparser = nullptr; #include "asm-x86.h" // x86 assembly parser #define ASM_X86_64 @@ -132,8 +132,9 @@ Statement *asmSemantic(AsmStatement *s, Scope *sc) { s->error("inline asm is not allowed when the -noasm switch is used"); err = true; } - if (err) + if (err) { fatal(); + } // puts(toChars()); @@ -141,14 +142,16 @@ Statement *asmSemantic(AsmStatement *s, Scope *sc) { // empty statement -- still do the above things because they might be // expected? - if (!s->tokens) + if (!s->tokens) { return s; + } if (!asmparser) { - if (t.getArch() == llvm::Triple::x86) + if (t.getArch() == llvm::Triple::x86) { asmparser = new AsmParserx8632::AsmParser; - else if (t.getArch() == llvm::Triple::x86_64) + } else if (t.getArch() == llvm::Triple::x86_64) { asmparser = new AsmParserx8664::AsmParser; + } } asmparser->run(sc, s); @@ -170,8 +173,9 @@ void AsmStatement_toIR(AsmStatement *stmt, IRState *irs) { // debug info gIR->DBuilder.EmitStopPoint(stmt->loc); - if (!stmt->asmcode) + if (!stmt->asmcode) { return; + } static std::string i_cns = "i"; static std::string p_cns = "i"; @@ -200,7 +204,7 @@ void AsmStatement_toIR(AsmStatement *stmt, IRState *irs) { auto arg = code->args.begin(); for (unsigned i = 0; i < code->args.size(); i++, ++arg) { bool is_input = true; - LLValue *arg_val = 0; + LLValue *arg_val = nullptr; std::string cns; switch (arg->type) { @@ -287,14 +291,16 @@ void AsmStatement_toIR(AsmStatement *stmt, IRState *irs) { clobbers.push_back(asmparser->getRegName(i)); } } - if (clobbers_mem) + if (clobbers_mem) { clobbers.push_back(memory_name); + } // } // Remap argument numbers for (unsigned i = 0; i < code->args.size(); i++) { - if (arg_map[i] < 0) + if (arg_map[i] < 0) { arg_map[i] = -arg_map[i] - 1 + n_outputs; + } } bool pct = false; @@ -311,8 +317,9 @@ void AsmStatement_toIR(AsmStatement *stmt, IRState *irs) { pct = false; } // assert(*p == '%');// could be 'a', etc. so forget it.. - } else if (*p == '$') + } else if (*p == '$') { pct = true; + } ++p; } @@ -407,7 +414,7 @@ void AsmStatement_toIR(AsmStatement *stmt, IRState *irs) { replace_func_name(irs, code->insnTemplate); // push asm statement - IRAsmStmt *asmStmt = new IRAsmStmt; + auto asmStmt = new IRAsmStmt; asmStmt->code = code->insnTemplate; asmStmt->out_c = llvmOutConstraints; asmStmt->in_c = llvmInConstraints; @@ -435,10 +442,12 @@ static void remap_outargs(std::string &insnt, size_t nargs, size_t idx) { for (unsigned i = 0; i < nargs; i++) { needle = prefix + digits[i] + suffix; size_t pos = insnt.find(needle); - if (std::string::npos != pos) + if (std::string::npos != pos) { sprintf(buf, "%llu", static_cast(idx++)); - while (std::string::npos != (pos = insnt.find(needle))) + } + while (std::string::npos != (pos = insnt.find(needle))) { insnt.replace(pos, needle.size(), buf); + } } } @@ -456,10 +465,12 @@ static void remap_inargs(std::string &insnt, size_t nargs, size_t idx) { for (unsigned i = 0; i < nargs; i++) { needle = prefix + digits[i] + suffix; size_t pos = insnt.find(needle); - if (std::string::npos != pos) + if (std::string::npos != pos) { sprintf(buf, "%llu", static_cast(idx++)); - while (std::string::npos != (pos = insnt.find(needle))) + } + while (std::string::npos != (pos = insnt.find(needle))) { insnt.replace(pos, needle.size(), buf); + } } } @@ -469,12 +480,13 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { LOG_SCOPE; // disable inlining by default - if (!p->func()->decl->allowInlining) + if (!p->func()->decl->allowInlining) { p->func()->setNeverInline(); + } // create asm block structure assert(!p->asmBlock); - IRAsmBlock *asmblock = new IRAsmBlock(stmt); + auto asmblock = new IRAsmBlock(stmt); assert(asmblock); p->asmBlock = asmblock; @@ -496,7 +508,7 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { // location of the special value determining the goto label // will be set if post-asm dispatcher block is needed - LLValue *jump_target = 0; + LLValue *jump_target = nullptr; { FuncDeclaration *fd = gIR->func()->decl; @@ -509,7 +521,7 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { asmGotoEndLabel << uniqueLabelsId++; // initialize the setter statement we're going to build - IRAsmStmt *outSetterStmt = new IRAsmStmt; + auto outSetterStmt = new IRAsmStmt; std::string asmGotoEnd = "\n\tjmp " + asmGotoEndLabel.str() + "\n"; std::ostringstream code; code << asmGotoEnd; @@ -521,22 +533,27 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { IRAsmStmt *a = asmblock->s[i]; // skip non-branch statements - if (!a->isBranchToLabel) + if (!a->isBranchToLabel) { continue; + } // if internal, no special handling is necessary, skip std::vector::const_iterator it, end; end = asmblock->internalLabels.end(); bool skip = false; - for (auto il : asmblock->internalLabels) - if (il->equals(a->isBranchToLabel->ident)) + for (auto il : asmblock->internalLabels) { + if (il->equals(a->isBranchToLabel->ident)) { skip = true; - if (skip) + } + } + if (skip) { continue; + } // if we already set things up for this branch target, skip - if (gotoToVal.find(a->isBranchToLabel) != gotoToVal.end()) + if (gotoToVal.find(a->isBranchToLabel) != gotoToVal.end()) { continue; + } // record that the jump needs to be handled in the post-asm dispatcher gotoToVal[a->isBranchToLabel] = n_goto; @@ -568,15 +585,16 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { outSetterStmt->out.push_back(jump_target); asmblock->s.push_back(outSetterStmt); - } else + } else { delete outSetterStmt; + } } // build a fall-off-end-properly asm statement FuncDeclaration *thisfunc = p->func()->decl; bool useabiret = false; - p->asmBlock->asmBlock->abiret = NULL; + p->asmBlock->asmBlock->abiret = nullptr; if (thisfunc->fbody->endsWithAsm() == stmt && thisfunc->type->nextOf()->ty != Tvoid) { // there can't be goto forwarders in this case @@ -627,8 +645,9 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { } remap_inargs(a->code, inn + a->out.size(), asmIdx); asmIdx += inn; - if (!code.empty()) + if (!code.empty()) { code += "\n\t"; + } code += a->code; } asmblock->s.clear(); @@ -642,8 +661,9 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { } // remove excessive comma - if (!out_c.empty()) + if (!out_c.empty()) { out_c.resize(out_c.size() - 1); + } IF_LOG { Logger::println("code = \"%s\"", code.c_str()); @@ -652,10 +672,11 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { // build return types LLType *retty; - if (asmblock->retn) + if (asmblock->retn) { retty = asmblock->retty; - else + } else { retty = llvm::Type::getVoidTy(gIR->context()); + } // build argument types std::vector types; @@ -675,8 +696,10 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { for (auto arg : args) { Stream cout = Logger::cout(); cout << '$' << i << " ==> " << *arg; - if (!llvm::isa(arg) && !llvm::isa(arg)) + if (!llvm::isa(arg) && + !llvm::isa(arg)) { cout << '\n'; + } ++i; } Logger::undent(); @@ -692,15 +715,16 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { // capture abi return value if (useabiret) { IRAsmBlock *block = p->asmBlock; - if (block->retfixup) + if (block->retfixup) { block->asmBlock->abiret = (*block->retfixup)(p->ir, call); - else if (p->asmBlock->retemu) + } else if (p->asmBlock->retemu) { block->asmBlock->abiret = DtoLoad(block->asmBlock->abiret); - else + } else { block->asmBlock->abiret = call; + } } - p->asmBlock = NULL; + p->asmBlock = nullptr; // if asm contained external branches, emit goto forwarder code if (!gotoToVal.empty()) { @@ -734,7 +758,7 @@ void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) { CompoundAsmStatement *Statement::endsWithAsm() { // does not end with inline asm - return NULL; + return nullptr; } CompoundAsmStatement *CompoundStatement::endsWithAsm() { @@ -742,10 +766,11 @@ CompoundAsmStatement *CompoundStatement::endsWithAsm() { if (statements && statements->dim) { unsigned last = statements->dim - 1; Statement *s = (*statements)[last]; - if (s) + if (s) { return s->endsWithAsm(); + } } - return NULL; + return nullptr; } CompoundAsmStatement *CompoundAsmStatement::endsWithAsm() { @@ -760,8 +785,9 @@ void AsmStatement_toNakedIR(AsmStatement *stmt, IRState *irs) { LOG_SCOPE; // is there code? - if (!stmt->asmcode) + if (!stmt->asmcode) { return; + } AsmCode *code = static_cast(stmt->asmcode); // build asm stmt diff --git a/gen/attributes.cpp b/gen/attributes.cpp index e68e529593..d6c09fc8de 100644 --- a/gen/attributes.cpp +++ b/gen/attributes.cpp @@ -23,15 +23,17 @@ AttrBuilder &AttrBuilder::clear() { AttrBuilder &AttrBuilder::add(LLAttribute attribute) { // never set 'None' explicitly - if (attribute) + if (attribute) { builder.addAttribute(attribute); + } return *this; } AttrBuilder &AttrBuilder::remove(LLAttribute attribute) { // never remove 'None' explicitly - if (attribute) + if (attribute) { builder.removeAttribute(attribute); + } return *this; } diff --git a/gen/binops.cpp b/gen/binops.cpp index 7ce61d6bd2..59bf8e48bd 100644 --- a/gen/binops.cpp +++ b/gen/binops.cpp @@ -25,10 +25,11 @@ DValue *DtoBinAdd(DValue *lhs, DValue *rhs) { r = rhs->getRVal(); LLValue *res; - if (t->isfloating()) + if (t->isfloating()) { res = gIR->ir->CreateFAdd(l, r); - else + } else { res = gIR->ir->CreateAdd(l, r); + } return new DImValue(t, res); } @@ -42,10 +43,11 @@ DValue *DtoBinSub(DValue *lhs, DValue *rhs) { r = rhs->getRVal(); LLValue *res; - if (t->isfloating()) + if (t->isfloating()) { res = gIR->ir->CreateFSub(l, r); - else + } else { res = gIR->ir->CreateSub(l, r); + } return new DImValue(t, res); } @@ -59,10 +61,11 @@ DValue *DtoBinMul(Type *targettype, DValue *lhs, DValue *rhs) { r = rhs->getRVal(); LLValue *res; - if (t->isfloating()) + if (t->isfloating()) { res = gIR->ir->CreateFMul(l, r); - else + } else { res = gIR->ir->CreateMul(l, r); + } return new DImValue(targettype, res); } @@ -75,12 +78,13 @@ DValue *DtoBinDiv(Type *targettype, DValue *lhs, DValue *rhs) { r = rhs->getRVal(); LLValue *res; - if (t->isfloating()) + if (t->isfloating()) { res = gIR->ir->CreateFDiv(l, r); - else if (!isLLVMUnsigned(t)) + } else if (!isLLVMUnsigned(t)) { res = gIR->ir->CreateSDiv(l, r); - else + } else { res = gIR->ir->CreateUDiv(l, r); + } return new DImValue(targettype, res); } @@ -92,12 +96,13 @@ DValue *DtoBinRem(Type *targettype, DValue *lhs, DValue *rhs) { l = lhs->getRVal(); r = rhs->getRVal(); LLValue *res; - if (t->isfloating()) + if (t->isfloating()) { res = gIR->ir->CreateFRem(l, r); - else if (!isLLVMUnsigned(t)) + } else if (!isLLVMUnsigned(t)) { res = gIR->ir->CreateSRem(l, r); - else + } else { res = gIR->ir->CreateURem(l, r); + } return new DImValue(targettype, res); } @@ -110,7 +115,7 @@ LLValue *DtoBinNumericEquals(Loc &loc, DValue *lhs, DValue *rhs, TOK op) { assert(t->isfloating()); Logger::println("numeric equality"); - LLValue *res = 0; + LLValue *res = nullptr; if (t->iscomplex()) { Logger::println("complex"); res = DtoComplexEquals(loc, op, lhs, rhs); @@ -126,17 +131,18 @@ LLValue *DtoBinNumericEquals(Loc &loc, DValue *lhs, DValue *rhs, TOK op) { ////////////////////////////////////////////////////////////////////////////// LLValue *DtoBinFloatsEquals(Loc &loc, DValue *lhs, DValue *rhs, TOK op) { - LLValue *res = 0; + LLValue *res = nullptr; if (op == TOKequal) { res = gIR->ir->CreateFCmpOEQ(lhs->getRVal(), rhs->getRVal()); } else if (op == TOKnotequal) { res = gIR->ir->CreateFCmpUNE(lhs->getRVal(), rhs->getRVal()); } else { llvm::ICmpInst::Predicate cmpop; - if (op == TOKidentity) + if (op == TOKidentity) { cmpop = llvm::ICmpInst::ICMP_EQ; - else + } else { cmpop = llvm::ICmpInst::ICMP_NE; + } LLValue *sz = DtoConstSize_t(getTypeStoreSize(DtoType(lhs->getType()))); LLValue *val = DtoMemCmp(makeLValue(loc, lhs), makeLValue(loc, rhs), sz); diff --git a/gen/cl_helpers.cpp b/gen/cl_helpers.cpp index b1454be8dc..62dd26e459 100644 --- a/gen/cl_helpers.cpp +++ b/gen/cl_helpers.cpp @@ -38,11 +38,13 @@ void MultiSetter::operator=(bool val) { } void StringsAdapter::push_back(const char *cstr) { - if (!cstr || !*cstr) + if (!cstr || !*cstr) { error(Loc(), "Expected argument to '-%s'", name); + } - if (!*arrp) + if (!*arrp) { *arrp = new Strings; + } (*arrp)->push(mem.xstrdup(cstr)); } diff --git a/gen/cl_helpers.h b/gen/cl_helpers.h index 060b2079bd..6a8a0ebbaa 100644 --- a/gen/cl_helpers.h +++ b/gen/cl_helpers.h @@ -56,7 +56,7 @@ public: #if LDC_LLVM_VER >= 307 FlagParser(cl::Option &O) : generic_parser_base(O) {} #else - FlagParser() : generic_parser_base(), Owner(0) {} + FlagParser() : generic_parser_base(), Owner(nullptr) {} #endif typedef DataType parser_data_type; @@ -99,7 +99,7 @@ public: private: struct OptionValue : cl::OptionValueBase { - OptionValue(){}; + OptionValue() {} }; const OptionValue EmptyOptionValue; @@ -157,7 +157,7 @@ private: class MultiSetter { std::vector locations; bool invert; - MultiSetter(bool); // not implemented, disable auto-conversion + explicit MultiSetter(bool); // not implemented, disable auto-conversion public: MultiSetter(bool invert, bool *p, ...) LLVM_END_WITH_NULL; diff --git a/gen/classes.cpp b/gen/classes.cpp index 3bd95d0219..8b5f29349b 100644 --- a/gen/classes.cpp +++ b/gen/classes.cpp @@ -34,8 +34,9 @@ // FIXME: this needs to be cleaned up void DtoResolveClass(ClassDeclaration *cd) { - if (cd->ir.isResolved()) + if (cd->ir.isResolved()) { return; + } cd->ir.setResolved(); IF_LOG Logger::println("DtoResolveClass(%s): %s", cd->toPrettyChars(), @@ -56,15 +57,17 @@ void DtoResolveClass(ClassDeclaration *cd) { // make sure all fields really get their ir field for (auto vd : cd->fields) { IF_LOG { - if (isIrFieldCreated(vd)) + if (isIrFieldCreated(vd)) { Logger::println("class field already exists"); + } } getIrField(vd, true); } // emit the interfaceInfosZ symbol if necessary - if (cd->vtblInterfaces && cd->vtblInterfaces->dim > 0) + if (cd->vtblInterfaces && cd->vtblInterfaces->dim > 0) { irAggr->getInterfaceArraySymbol(); // initializer is applied when it's built + } // interface only emit typeinfo and classinfo if (cd->isInterfaceDeclaration()) { @@ -88,7 +91,7 @@ DValue *DtoNewClass(Loc &loc, TypeClass *tc, NewExp *newexp) { else if (newexp->allocator) { DtoResolveFunction(newexp->allocator); DFuncValue dfn(newexp->allocator, getIrFunc(newexp->allocator)->func); - DValue *res = DtoCallFunction(newexp->loc, NULL, &dfn, newexp->newargs); + DValue *res = DtoCallFunction(newexp->loc, nullptr, &dfn, newexp->newargs); mem = DtoBitCast(res->getRVal(), DtoType(tc), ".newclass_custom"); } // default allocator @@ -124,8 +127,9 @@ DValue *DtoNewClass(Loc &loc, TypeClass *tc, NewExp *newexp) { // call constructor if (newexp->member) { // evaluate argprefix - if (newexp->argprefix) + if (newexp->argprefix) { toElemDtor(newexp->argprefix); + } Logger::println("Calling constructor"); assert(newexp->arguments != NULL); @@ -163,8 +167,9 @@ void DtoInitClass(TypeClass *tc, LLValue *dst) { unsigned const firstDataIdx = isCPPclass ? 1 : 2; uint64_t const dataBytes = tc->sym->structsize - Target::ptrsize * firstDataIdx; - if (dataBytes == 0) + if (dataBytes == 0) { return; + } LLValue *dstarr = DtoGEPi(dst, 0, firstDataIdx); @@ -251,7 +256,7 @@ DValue *DtoCastClass(Loc &loc, DValue *val, Type *_to) { return DtoDynamicCastInterface(loc, val, _to); } // class -> interface - static cast - else if (it->isBaseOf(fc->sym, NULL)) { + else if (it->isBaseOf(fc->sym, nullptr)) { Logger::println("static down cast"); // get the from class @@ -304,7 +309,7 @@ DValue *DtoCastClass(Loc &loc, DValue *val, Type *_to) { return DtoDynamicCastInterface(loc, val, _to); } // class -> class - static down cast - else if (tc->sym->isBaseOf(fc->sym, NULL)) { + else if (tc->sym->isBaseOf(fc->sym, nullptr)) { Logger::println("static down cast"); LLType *tolltype = DtoType(_to); LLValue *rval = DtoBitCast(val->getRVal(), tolltype); @@ -498,8 +503,9 @@ static LLConstant *build_class_dtor(ClassDeclaration *cd) { FuncDeclaration *dtor = cd->dtor; // if no destructor emit a null - if (!dtor) + if (!dtor) { return getNullPtr(getVoidPtrType()); + } DtoResolveFunction(dtor); return llvm::ConstantExpr::getBitCast( @@ -513,33 +519,39 @@ static ClassFlags::Type build_classinfo_flags(ClassDeclaration *cd) { ClassFlags::Type flags = ClassFlags::hasOffTi | ClassFlags::hasTypeInfo; if (cd->isInterfaceDeclaration()) { - if (cd->isCOMinterface()) + if (cd->isCOMinterface()) { flags |= ClassFlags::isCOMclass; + } return flags; } - if (cd->isCOMclass()) + if (cd->isCOMclass()) { flags |= ClassFlags::isCOMclass; - if (cd->isCPPclass()) + } + if (cd->isCPPclass()) { flags |= ClassFlags::isCPPclass; + } flags |= ClassFlags::hasGetMembers; - if (cd->ctor) + if (cd->ctor) { flags |= ClassFlags::hasCtor; + } for (ClassDeclaration *pc = cd; pc; pc = pc->baseClass) { if (pc->dtor) { flags |= ClassFlags::hasDtor; break; } } - if (cd->isabstract) + if (cd->isabstract) { flags |= ClassFlags::isAbstract; + } for (ClassDeclaration *pc = cd; pc; pc = pc->baseClass) { if (pc->members) { for (size_t i = 0; i < pc->members->dim; i++) { Dsymbol *sm = (*pc->members)[i]; // printf("sm = %s %s\n", sm->kind(), sm->toChars()); - if (sm->hasPointers()) + if (sm->hasPointers()) { return flags; + } } } } @@ -620,16 +632,18 @@ LLConstant *DtoDefineClassInfo(ClassDeclaration *cd) { // base // interfaces never get a base, just the interfaces[] - if (cd->baseClass && !cd->isInterfaceDeclaration()) + if (cd->baseClass && !cd->isInterfaceDeclaration()) { b.push_classinfo(cd->baseClass); - else + } else { b.push_null(cinfo->type); + } // destructor - if (cd->isInterfaceDeclaration()) + if (cd->isInterfaceDeclaration()) { b.push_null_vp(); - else + } else { b.push(build_class_dtor(cd)); + } // invariant VarDeclaration *invVar = cinfo->fields[6]; @@ -656,19 +670,21 @@ LLConstant *DtoDefineClassInfo(ClassDeclaration *cd) { // defaultConstructor VarDeclaration *defConstructorVar = cinfo->fields.data[10]; CtorDeclaration *defConstructor = cd->defaultCtor; - if (defConstructor && (defConstructor->storage_class & STCdisable)) - defConstructor = NULL; + if (defConstructor && (defConstructor->storage_class & STCdisable)) { + defConstructor = nullptr; + } b.push_funcptr(defConstructor, defConstructorVar->type); // m_RTInfo // The cases where getRTInfo is null are not quite here, but the code is // modelled after what DMD does. - if (cd->getRTInfo) + if (cd->getRTInfo) { b.push(toConstElem(cd->getRTInfo, gIR)); - else if (flags & ClassFlags::noPointers) + } else if (flags & ClassFlags::noPointers) { b.push_size_as_vp(0); // no pointers - else + } else { b.push_size_as_vp(1); // has pointers + } /*size_t n = inits.size(); for (size_t i=0; itoBasetype()->ty) { default: llvm_unreachable("Unexpected complex floating point type"); @@ -90,10 +90,12 @@ DValue *DtoComplex(Loc &loc, Type *to, DValue *val) { LLValue *re, *im; DtoGetComplexParts(loc, to, val, re, im); - if (!re) + if (!re) { re = LLConstant::getNullValue(DtoType(baserety)); - if (!im) + } + if (!im) { im = LLConstant::getNullValue(DtoType(baseimty)); + } LLValue *res = DtoAggrPair(complexTy, re, im); @@ -150,17 +152,18 @@ void DtoGetComplexParts(Loc &loc, Type *to, DValue *val, DValue *&re, re = new DImValue(baserety, reVal); im = new DImValue(baseimty, imVal); } - } else + } else { DtoGetComplexParts(loc, to, v, re, im); + } } else if (t->isimaginary()) { - re = NULL; + re = nullptr; im = DtoCastFloat(loc, val, baseimty); } else if (t->isfloating()) { re = DtoCastFloat(loc, val, baserety); - im = NULL; + im = nullptr; } else if (t->isintegral()) { re = DtoCastInt(loc, val, baserety); - im = NULL; + im = nullptr; } else { llvm_unreachable("Unexpected numeric type."); } @@ -172,8 +175,8 @@ void DtoGetComplexParts(Loc &loc, Type *to, DValue *val, LLValue *&re, LLValue *&im) { DValue *dre, *dim; DtoGetComplexParts(loc, to, val, dre, dim); - re = dre ? dre->getRVal() : 0; - im = dim ? dim->getRVal() : 0; + re = dre ? dre->getRVal() : nullptr; + im = dim ? dim->getRVal() : nullptr; } ////////////////////////////////////////////////////////////////////////////////////////// @@ -187,19 +190,21 @@ DValue *DtoComplexAdd(Loc &loc, Type *type, DValue *lhs, DValue *rhs) { DtoGetComplexParts(loc, type, rhs, rhs_re, rhs_im); // add up - if (lhs_re && rhs_re) + if (lhs_re && rhs_re) { res_re = gIR->ir->CreateFAdd(lhs_re, rhs_re); - else if (lhs_re) + } else if (lhs_re) { res_re = lhs_re; - else // either rhs_re or no re at all (then use any) + } else { // either rhs_re or no re at all (then use any) res_re = rhs_re; + } - if (lhs_im && rhs_im) + if (lhs_im && rhs_im) { res_im = gIR->ir->CreateFAdd(lhs_im, rhs_im); - else if (lhs_im) + } else if (lhs_im) { res_im = lhs_im; - else // either rhs_im or no im at all (then use any) + } else { // either rhs_im or no im at all (then use any) res_im = rhs_im; + } LLValue *res = DtoAggrPair(DtoType(type), res_re, res_im); return new DImValue(type, res); @@ -216,19 +221,21 @@ DValue *DtoComplexSub(Loc &loc, Type *type, DValue *lhs, DValue *rhs) { DtoGetComplexParts(loc, type, rhs, rhs_re, rhs_im); // add up - if (lhs_re && rhs_re) + if (lhs_re && rhs_re) { res_re = gIR->ir->CreateFSub(lhs_re, rhs_re); - else if (lhs_re) + } else if (lhs_re) { res_re = lhs_re; - else // either rhs_re or no re at all (then use any) + } else { // either rhs_re or no re at all (then use any) res_re = gIR->ir->CreateFNeg(rhs_re, "neg"); + } - if (lhs_im && rhs_im) + if (lhs_im && rhs_im) { res_im = gIR->ir->CreateFSub(lhs_im, rhs_im); - else if (lhs_im) + } else if (lhs_im) { res_im = lhs_im; - else // either rhs_im or no im at all (then use any) + } else { // either rhs_im or no im at all (then use any) res_im = gIR->ir->CreateFNeg(rhs_im, "neg"); + } LLValue *res = DtoAggrPair(DtoType(type), res_re, res_im); return new DImValue(type, res); @@ -245,37 +252,43 @@ DValue *DtoComplexMul(Loc &loc, Type *type, DValue *lhs, DValue *rhs) { DtoGetComplexParts(loc, type, rhs, rhs_re, rhs_im); // mul up - llvm::Value *rere = NULL; - llvm::Value *reim = NULL; - llvm::Value *imre = NULL; - llvm::Value *imim = NULL; + llvm::Value *rere = nullptr; + llvm::Value *reim = nullptr; + llvm::Value *imre = nullptr; + llvm::Value *imim = nullptr; - if (lhs_re && rhs_re) + if (lhs_re && rhs_re) { rere = gIR->ir->CreateFMul(lhs_re, rhs_re, "rere_mul"); - if (lhs_re && rhs_im) + } + if (lhs_re && rhs_im) { reim = gIR->ir->CreateFMul(lhs_re, rhs_im, "reim_mul"); - if (lhs_im && rhs_re) + } + if (lhs_im && rhs_re) { imre = gIR->ir->CreateFMul(lhs_im, rhs_re, "imre_mul"); - if (lhs_im && rhs_im) + } + if (lhs_im && rhs_im) { imim = gIR->ir->CreateFMul(lhs_im, rhs_im, "imim_mul"); + } - if (rere && imim) + if (rere && imim) { res_re = gIR->ir->CreateFSub(rere, imim, "rere_imim_sub"); - else if (rere) + } else if (rere) { res_re = rere; - else if (imim) + } else if (imim) { res_re = gIR->ir->CreateFNeg(imim, "imim_neg"); - else + } else { res_re = lhs_re ? rhs_re : lhs_re; // null! + } - if (reim && imre) + if (reim && imre) { res_im = gIR->ir->CreateFAdd(reim, imre, "reim_imre_add"); - else if (reim) + } else if (reim) { res_im = reim; - else if (imre) + } else if (imre) { res_im = imre; - else + } else { res_im = lhs_re ? rhs_im : lhs_re; // null! + } LLValue *res = DtoAggrPair(DtoType(type), res_re, res_im); return new DImValue(type, res); @@ -293,26 +306,30 @@ DValue *DtoComplexDiv(Loc &loc, Type *type, DValue *lhs, DValue *rhs) { // if divisor is only real, division is simple if (rhs_re && !rhs_im) { - if (lhs_re) + if (lhs_re) { res_re = gIR->ir->CreateFDiv(lhs_re, rhs_re, "re_divby_re"); - else + } else { res_re = lhs_re; - if (lhs_im) + } + if (lhs_im) { res_im = gIR->ir->CreateFDiv(lhs_im, rhs_re, "im_divby_re"); - else + } else { res_im = lhs_im; + } } // if divisor is only imaginary, division is simple too else if (!rhs_re && rhs_im) { - if (lhs_re) + if (lhs_re) { res_im = gIR->ir->CreateFNeg( gIR->ir->CreateFDiv(lhs_re, rhs_im, "re_divby_im"), "neg"); - else + } else { res_im = lhs_re; - if (lhs_im) + } + if (lhs_im) { res_re = gIR->ir->CreateFDiv(lhs_im, rhs_im, "im_divby_im"); - else + } else { res_re = lhs_im; + } } // full division else { @@ -334,8 +351,9 @@ DValue *DtoComplexDiv(Loc &loc, Type *type, DValue *lhs, DValue *rhs) { } else if (lhs_im) { res_re = gIR->ir->CreateFMul(lhs_im, rhs_im, "imim"); res_im = gIR->ir->CreateFMul(lhs_im, rhs_re, "imre"); - } else + } else { llvm_unreachable("lhs has neither real nor imaginary part"); + } tmp1 = gIR->ir->CreateFMul(rhs_re, rhs_re, "rhs_resq"); tmp2 = gIR->ir->CreateFMul(rhs_im, rhs_im, "rhs_imsq"); @@ -403,10 +421,11 @@ LLValue *DtoComplexEquals(Loc &loc, TOK op, DValue *lhs, DValue *rhs) { LLValue *b1 = DtoBinFloatsEquals(loc, lhs_re, rhs_re, op); LLValue *b2 = DtoBinFloatsEquals(loc, lhs_im, rhs_im, op); - if (op == TOKequal) + if (op == TOKequal) { return gIR->ir->CreateAnd(b1, b2); - else + } else { return gIR->ir->CreateOr(b1, b2); + } } ////////////////////////////////////////////////////////////////////////////////////////// @@ -415,8 +434,9 @@ DValue *DtoCastComplex(Loc &loc, DValue *val, Type *_to) { Type *to = _to->toBasetype(); Type *vty = val->getType()->toBasetype(); if (to->iscomplex()) { - if (vty->size() == to->size()) + if (vty->size() == to->size()) { return val; + } llvm::Value *re, *im; DtoGetComplexParts(loc, val->getType(), val, re, im); @@ -450,7 +470,7 @@ DValue *DtoCastComplex(Loc &loc, DValue *val, Type *_to) { extractty = Type::timaginary80; break; } - DImValue *im = new DImValue(extractty, impart); + auto im = new DImValue(extractty, impart); return DtoCastFloat(loc, im, to); } else if (to->ty == Tbool) { return new DImValue( @@ -473,7 +493,7 @@ DValue *DtoCastComplex(Loc &loc, DValue *val, Type *_to) { extractty = Type::tfloat80; break; } - DImValue *re = new DImValue(extractty, repart); + auto re = new DImValue(extractty, repart); return DtoCastFloat(loc, re, to); } else { error(loc, "Don't know how to cast %s to %s", vty->toChars(), diff --git a/gen/declarations.cpp b/gen/declarations.cpp index 6a2856c853..0d2d1dedc9 100644 --- a/gen/declarations.cpp +++ b/gen/declarations.cpp @@ -41,31 +41,34 @@ bool isSpeculativeType(Type *t) { SpeculativeTypeVisitor() : result(false) {} - void visit(Type *t) { + void visit(Type *t) override { Type *tb = t->toBasetype(); - if (tb != t) + if (tb != t) { tb->accept(this); + } } - void visit(TypeNext *t) { - if (t->next) + void visit(TypeNext *t) override { + if (t->next) { t->next->accept(this); + } } - void visit(TypeBasic *t) {} - void visit(TypeVector *t) { t->basetype->accept(this); } - void visit(TypeAArray *t) { + void visit(TypeBasic *t) override {} + void visit(TypeVector *t) override { t->basetype->accept(this); } + void visit(TypeAArray *t) override { t->index->accept(this); visit((TypeNext *)t); } - void visit(TypeFunction *t) { + void visit(TypeFunction *t) override { visit((TypeNext *)t); // Currently TypeInfo_Function doesn't store parameter types. } - void visit(TypeStruct *t) { + void visit(TypeStruct *t) override { StructDeclaration *sd = t->sym; if (TemplateInstance *ti = sd->isInstantiated()) { if (!ti->needsCodegen()) { - if (ti->minst || sd->requestTypeInfo) + if (ti->minst || sd->requestTypeInfo) { return; + } /* Bugzilla 14425: TypeInfo_Struct would refer the members of * struct (e.g. opEquals via xopEquals field), so if it's instantiated @@ -85,15 +88,17 @@ bool isSpeculativeType(Type *t) { // assert(!sd->inNonRoot() || sd->requestTypeInfo); // valid? } } - void visit(TypeClass *t) {} - void visit(TypeTuple *t) { + void visit(TypeClass *t) override {} + void visit(TypeTuple *t) override { if (t->arguments) { for (size_t i = 0; i < t->arguments->dim; i++) { Type *tprm = (*t->arguments)[i]->type; - if (tprm) + if (tprm) { tprm->accept(this); - if (result) + } + if (result) { return; + } } } } @@ -110,7 +115,7 @@ class CodegenVisitor : public Visitor { IRState *irs; public: - CodegenVisitor(IRState *irs) : irs(irs) {} + explicit CodegenVisitor(IRState *irs) : irs(irs) {} ////////////////////////////////////////////////////////////////////////// @@ -131,8 +136,9 @@ public: decl->toPrettyChars()); LOG_SCOPE - if (decl->ir.isDefined()) + if (decl->ir.isDefined()) { return; + } if (decl->type->ty == Terror) { error(decl->loc, "had semantic errors when compiling"); @@ -145,8 +151,9 @@ public: decl->ir.setDefined(); // Emit any members (e.g. final functions). - for (auto m : *decl->members) + for (auto m : *decl->members) { m->accept(this); + } // Emit TypeInfo. DtoTypeInfoOf(decl->type); @@ -157,8 +164,9 @@ public: interfaceZ->setInitializer(ir->getClassInfoInit()); LinkageWithCOMDAT lwc = DtoLinkage(decl); interfaceZ->setLinkage(lwc.first); - if (lwc.second) + if (lwc.second) { SET_COMDAT(interfaceZ, gIR->module); + } } } @@ -169,8 +177,9 @@ public: decl->toPrettyChars()); LOG_SCOPE - if (decl->ir.isDefined()) + if (decl->ir.isDefined()) { return; + } if (decl->type->ty == Terror) { error(decl->loc, "had semantic errors when compiling"); @@ -182,8 +191,9 @@ public: DtoResolveStruct(decl); decl->ir.setDefined(); - for (auto m : *decl->members) + for (auto m : *decl->members) { m->accept(this); + } // Define the __initZ symbol. IrAggr *ir = getIrAggr(decl); @@ -191,19 +201,23 @@ public: initZ->setInitializer(ir->getDefaultInit()); LinkageWithCOMDAT lwc = DtoLinkage(decl); initZ->setLinkage(lwc.first); - if (lwc.second) + if (lwc.second) { SET_COMDAT(initZ, gIR->module); + } // emit typeinfo DtoTypeInfoOf(decl->type); // Emit __xopEquals/__xopCmp/__xtoHash. - if (decl->xeq && decl->xeq != decl->xerreq) + if (decl->xeq && decl->xeq != decl->xerreq) { decl->xeq->accept(this); - if (decl->xcmp && decl->xcmp != decl->xerrcmp) + } + if (decl->xcmp && decl->xcmp != decl->xerrcmp) { decl->xcmp->accept(this); - if (decl->xhash) + } + if (decl->xhash) { decl->xhash->accept(this); + } } } @@ -214,8 +228,9 @@ public: decl->toPrettyChars()); LOG_SCOPE - if (decl->ir.isDefined()) + if (decl->ir.isDefined()) { return; + } if (decl->type->ty == Terror) { error(decl->loc, "had semantic errors when compiling"); @@ -227,8 +242,9 @@ public: DtoResolveClass(decl); decl->ir.setDefined(); - for (auto m : *decl->members) + for (auto m : *decl->members) { m->accept(this); + } IrAggr *ir = getIrAggr(decl); const LinkageWithCOMDAT lwc = DtoLinkage(decl); @@ -236,20 +252,23 @@ public: llvm::GlobalVariable *initZ = ir->getInitSymbol(); initZ->setInitializer(ir->getDefaultInit()); initZ->setLinkage(lwc.first); - if (lwc.second) + if (lwc.second) { SET_COMDAT(initZ, gIR->module); + } llvm::GlobalVariable *vtbl = ir->getVtblSymbol(); vtbl->setInitializer(ir->getVtblInit()); vtbl->setLinkage(lwc.first); - if (lwc.second) + if (lwc.second) { SET_COMDAT(vtbl, gIR->module); + } llvm::GlobalVariable *classZ = ir->getClassInfoSymbol(); classZ->setInitializer(ir->getClassInfoInit()); classZ->setLinkage(lwc.first); - if (lwc.second) + if (lwc.second) { SET_COMDAT(classZ, gIR->module); + } // No need to do TypeInfo here, it is __classZ for classes in D2. } @@ -262,8 +281,9 @@ public: decl->toPrettyChars()); LOG_SCOPE - if (decl->ir.isDefined()) + if (decl->ir.isDefined()) { return; + } decl->ir.setDefined(); assert(decl->isexp); @@ -283,8 +303,9 @@ public: decl->toPrettyChars()); LOG_SCOPE; - if (decl->ir.isDefined()) + if (decl->ir.isDefined()) { return; + } if (decl->type->ty == Terror) { error(decl->loc, "had semantic errors when compiling"); @@ -326,11 +347,12 @@ public: if (initVal->getType() != gvar->getType()->getElementType()) { llvm::GlobalVariable *newGvar = getOrCreateGlobal( decl->loc, irs->module, initVal->getType(), gvar->isConstant(), - lwc.first, 0, + lwc.first, nullptr, "", // We take on the name of the old global below. gvar->isThreadLocal()); - if (lwc.second) + if (lwc.second) { SET_COMDAT(newGvar, gIR->module); + } newGvar->setAlignment(gvar->getAlignment()); newGvar->takeName(gvar); @@ -349,8 +371,9 @@ public: irGlobal->constInit = initVal; gvar->setInitializer(initVal); gvar->setLinkage(lwc.first); - if (lwc.second) + if (lwc.second) { SET_COMDAT(gvar, gIR->module); + } // Also set up the debug info. irs->DBuilder.EmitGlobalVariable(gvar, decl); @@ -359,8 +382,9 @@ public: // If this global is used from a naked function, we need to create an // artificial "use" for it, or it could be removed by the optimizer if // the only reference to it is in inline asm. - if (irGlobal->nakedUse) + if (irGlobal->nakedUse) { irs->usedArray.push_back(DtoBitCast(gvar, getVoidPtrType())); + } IF_LOG Logger::cout() << *gvar << '\n'; } @@ -394,17 +418,20 @@ public: decl->toPrettyChars()); LOG_SCOPE - if (decl->ir.isDefined()) + if (decl->ir.isDefined()) { return; + } decl->ir.setDefined(); // FIXME: This is #673 all over again. - if (!decl->needsCodegen()) + if (!decl->needsCodegen()) { return; + } if (!isError(decl) && decl->members) { - for (auto m : *decl->members) + for (auto m : *decl->members) { m->accept(this); + } } } @@ -415,24 +442,27 @@ public: decl->toPrettyChars()); LOG_SCOPE - if (decl->ir.isDefined()) + if (decl->ir.isDefined()) { return; + } decl->ir.setDefined(); if (!isError(decl) && decl->members) { - for (auto m : *decl->members) + for (auto m : *decl->members) { m->accept(this); + } } } ////////////////////////////////////////////////////////////////////////// void visit(AttribDeclaration *decl) LLVM_OVERRIDE { - Dsymbols *d = decl->include(NULL, NULL); + Dsymbols *d = decl->include(nullptr, nullptr); if (d) { - for (auto s : *d) + for (auto s : *d) { s->accept(this); + } } } @@ -472,10 +502,12 @@ public: llvm::StringRef(static_cast(se->string), nameLen)); // Win32: /DEFAULTLIB:"curl" - if (LibName.endswith(".a")) + if (LibName.endswith(".a")) { LibName = LibName.substr(0, LibName.size() - 2); - if (LibName.endswith(".lib")) + } + if (LibName.endswith(".lib")) { LibName = LibName.substr(0, LibName.size() - 4); + } llvm::SmallString<24> tmp("/DEFAULTLIB:\""); tmp.append(LibName); tmp.append("\""); @@ -507,16 +539,18 @@ public: ////////////////////////////////////////////////////////////////////////// void visit(TypeInfoDeclaration *decl) LLVM_OVERRIDE { - if (isSpeculativeType(decl->tinfo)) + if (isSpeculativeType(decl->tinfo)) { return; + } TypeInfoDeclaration_codegen(decl, irs); } ////////////////////////////////////////////////////////////////////////// void visit(TypeInfoClassDeclaration *decl) LLVM_OVERRIDE { - if (isSpeculativeType(decl->tinfo)) + if (isSpeculativeType(decl->tinfo)) { return; + } TypeInfoClassDeclaration_codegen(decl, irs); } }; diff --git a/gen/dibuilder.cpp b/gen/dibuilder.cpp index 3822420424..4f6f28d8c8 100644 --- a/gen/dibuilder.cpp +++ b/gen/dibuilder.cpp @@ -43,8 +43,9 @@ Module *ldc::DIBuilder::getDefinedModule(Dsymbol *s) { } // array operations as well else if (FuncDeclaration *fd = s->isFuncDeclaration()) { - if (fd->isArrayOp && (willInline() || !isDruntimeArrayOp(fd))) + if (fd->isArrayOp && (willInline() || !isDruntimeArrayOp(fd))) { return IR->dmodule; + } } // otherwise use the symbol's module return s->getModule(); @@ -53,7 +54,7 @@ Module *ldc::DIBuilder::getDefinedModule(Dsymbol *s) { //////////////////////////////////////////////////////////////////////////////// ldc::DIBuilder::DIBuilder(IRState *const IR) - : IR(IR), DBuilder(IR->module), CUNode(0) {} + : IR(IR), DBuilder(IR->module), CUNode(nullptr) {} llvm::LLVMContext &ldc::DIBuilder::getContext() { return IR->context(); } @@ -281,10 +282,11 @@ void ldc::DIBuilder::AddBaseFields(ClassDeclaration *sd, ldc::DIFile file, size_t narr = sd->fields.dim; elems.reserve(narr); - for (auto vd : sd->fields) + for (auto vd : sd->fields) { elems.push_back(CreateMemberType(vd->loc.linnum, vd->type, file, vd->toChars(), vd->offset, vd->prot().kind)); + } } ldc::DIType ldc::DIBuilder::CreateCompositeType(Type *type) { @@ -307,13 +309,15 @@ ldc::DIType ldc::DIBuilder::CreateCompositeType(Type *type) { IrTypeAggr *ir = sd->type->ctype->isAggr(); assert(ir); - if (static_cast(ir->diCompositeType) != 0) + if (static_cast(ir->diCompositeType) != nullptr) { return ir->diCompositeType; + } // if we don't know the aggregate's size, we don't know enough about it // to provide debug info. probably a forward-declared struct? - if (sd->sizeok == SIZEOKnone) + if (sd->sizeok == SIZEOKnone) { return DBuilder.createUnspecifiedType(sd->toChars()); + } // elements #if LDC_LLVM_VER >= 306 @@ -357,8 +361,9 @@ ldc::DIType ldc::DIBuilder::CreateCompositeType(Type *type) { } else { ClassDeclaration *classDecl = sd->isClassDeclaration(); AddBaseFields(classDecl, file, elems); - if (classDecl->baseClass) + if (classDecl->baseClass) { derivedFrom = CreateCompositeType(classDecl->baseClass->getType()); + } } } @@ -541,28 +546,31 @@ ldc::DIType ldc::DIBuilder::CreateTypeDescription(Type *type, bool derefclass) { t = type->toBasetype(); } - if (t->ty == Tvoid || t->ty == Tnull) + if (t->ty == Tvoid || t->ty == Tnull) { return DBuilder.createUnspecifiedType(t->toChars()); - else if (t->isintegral() || t->isfloating()) { - if (t->ty == Tvector) + } else if (t->isintegral() || t->isfloating()) { + if (t->ty == Tvector) { return CreateVectorType(type); - if (type->ty == Tenum) + } + if (type->ty == Tenum) { return CreateEnumType(type); + } return CreateBasicType(type); - } else if (t->ty == Tpointer) + } else if (t->ty == Tpointer) { return CreatePointerType(type); - else if (t->ty == Tarray) + } else if (t->ty == Tarray) { return CreateArrayType(type); - else if (t->ty == Tsarray) + } else if (t->ty == Tsarray) { return CreateSArrayType(type); - else if (t->ty == Taarray) + } else if (t->ty == Taarray) { return CreateAArrayType(type); - else if (t->ty == Tstruct || t->ty == Tclass) + } else if (t->ty == Tstruct || t->ty == Tclass) { return CreateCompositeType(type); - else if (t->ty == Tfunction) + } else if (t->ty == Tfunction) { return CreateFunctionType(type); - else if (t->ty == Tdelegate) + } else if (t->ty == Tdelegate) { return CreateDelegateType(type); + } // Crash if the type is not supported. llvm_unreachable("Unsupported type in debug info"); @@ -571,8 +579,9 @@ ldc::DIType ldc::DIBuilder::CreateTypeDescription(Type *type, bool derefclass) { //////////////////////////////////////////////////////////////////////////////// void ldc::DIBuilder::EmitCompileUnit(Module *m) { - if (!global.params.symdebug) + if (!global.params.symdebug) { return; + } Logger::println("D to dwarf compile_unit"); LOG_SCOPE; @@ -603,280 +612,300 @@ void ldc::DIBuilder::EmitCompileUnit(Module *m) { } ldc::DISubprogram ldc::DIBuilder::EmitSubProgram(FuncDeclaration *fd) { - if (!global.params.symdebug) + if (!global.params.symdebug) { #if LDC_LLVM_VER >= 307 return nullptr; #else return llvm::DISubprogram(); + } #endif - Logger::println("D to dwarf subprogram"); - LOG_SCOPE; + Logger::println("D to dwarf subprogram"); + LOG_SCOPE; - ldc::DICompileUnit CU(GetCU()); - assert(CU && - "Compilation unit missing or corrupted in DIBuilder::EmitSubProgram"); + ldc::DICompileUnit CU(GetCU()); + assert( + CU && + "Compilation unit missing or corrupted in DIBuilder::EmitSubProgram"); - ldc::DIFile file(CreateFile(fd->loc)); + ldc::DIFile file(CreateFile(fd->loc)); - // Create subroutine type - ldc::DISubroutineType DIFnType = - CreateFunctionType(static_cast(fd->type)); + // Create subroutine type + ldc::DISubroutineType DIFnType = + CreateFunctionType(static_cast(fd->type)); - // FIXME: duplicates ? - return DBuilder.createFunction(CU, // context - fd->toPrettyChars(), // name - mangleExact(fd), // linkage name - file, // file - fd->loc.linnum, // line no - DIFnType, // type - fd->protection == - PROTprivate, // is local to unit - true, // isdefinition - fd->loc.linnum, // FIXME: scope line - DIFlags::FlagPrototyped, // Flags - isOptimizationEnabled(), // isOptimized - getIrFunc(fd)->func); -} + // FIXME: duplicates ? + return DBuilder.createFunction(CU, // context + fd->toPrettyChars(), // name + mangleExact(fd), // linkage name + file, // file + fd->loc.linnum, // line no + DIFnType, // type + fd->protection == + PROTprivate, // is local to unit + true, // isdefinition + fd->loc.linnum, // FIXME: scope line + DIFlags::FlagPrototyped, // Flags + isOptimizationEnabled(), // isOptimized + getIrFunc(fd)->func); + } -ldc::DISubprogram ldc::DIBuilder::EmitModuleCTor(llvm::Function *Fn, - llvm::StringRef prettyname) { - if (!global.params.symdebug) + ldc::DISubprogram ldc::DIBuilder::EmitModuleCTor(llvm::Function * Fn, + llvm::StringRef prettyname) { + if (!global.params.symdebug) { #if LDC_LLVM_VER >= 307 - return nullptr; + return nullptr; #else return llvm::DISubprogram(); + } #endif - Logger::println("D to dwarf subprogram"); - LOG_SCOPE; + Logger::println("D to dwarf subprogram"); + LOG_SCOPE; - ldc::DICompileUnit CU(GetCU()); - assert(CU && - "Compilation unit missing or corrupted in DIBuilder::EmitSubProgram"); + ldc::DICompileUnit CU(GetCU()); + assert( + CU && + "Compilation unit missing or corrupted in DIBuilder::EmitSubProgram"); - Loc loc(IR->dmodule->srcfile->toChars(), 0, 0); - ldc::DIFile file(CreateFile(loc)); + Loc loc(IR->dmodule->srcfile->toChars(), 0, 0); + ldc::DIFile file(CreateFile(loc)); // Create "dummy" subroutine type for the return type #if LDC_LLVM_VER >= 306 - llvm::SmallVector Elts; + llvm::SmallVector Elts; #else llvm::SmallVector Elts; #endif - Elts.push_back(CreateTypeDescription(Type::tvoid, true)); + Elts.push_back(CreateTypeDescription(Type::tvoid, true)); #if LDC_LLVM_VER >= 307 - llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); + llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); #elif LDC_LLVM_VER >= 306 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); #else - llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); + llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); #endif #if LDC_LLVM_VER >= 308 - ldc::DISubroutineType DIFnType = DBuilder.createSubroutineType(EltTypeArray); + ldc::DISubroutineType DIFnType = + DBuilder.createSubroutineType(EltTypeArray); #else ldc::DISubroutineType DIFnType = DBuilder.createSubroutineType(file, EltTypeArray); #endif - // FIXME: duplicates ? - return DBuilder.createFunction(CU, // context - prettyname, // name - Fn->getName(), // linkage name - file, // file - 0, // line no - DIFnType, // return type. TODO: fill it up - true, // is local to unit - true, // isdefinition - 0, // FIXME: scope line - DIFlags::FlagPrototyped | - DIFlags::FlagArtificial, - isOptimizationEnabled(), // isOptimized - Fn); -} + // FIXME: duplicates ? + return DBuilder.createFunction(CU, // context + prettyname, // name + Fn->getName(), // linkage name + file, // file + 0, // line no + DIFnType, // return type. TODO: fill it up + true, // is local to unit + true, // isdefinition + 0, // FIXME: scope line + DIFlags::FlagPrototyped | + DIFlags::FlagArtificial, + isOptimizationEnabled(), // isOptimized + Fn); + } -void ldc::DIBuilder::EmitFuncStart(FuncDeclaration *fd) { - if (!global.params.symdebug) - return; + void ldc::DIBuilder::EmitFuncStart(FuncDeclaration * fd) { + if (!global.params.symdebug) { + return; + } - Logger::println("D to dwarf funcstart"); - LOG_SCOPE; + Logger::println("D to dwarf funcstart"); + LOG_SCOPE; - assert(static_cast(getIrFunc(fd)->diSubprogram) != 0); - EmitStopPoint(fd->loc); -} + assert(static_cast(getIrFunc(fd)->diSubprogram) != 0); + EmitStopPoint(fd->loc); + } -void ldc::DIBuilder::EmitFuncEnd(FuncDeclaration *fd) { - if (!global.params.symdebug) - return; + void ldc::DIBuilder::EmitFuncEnd(FuncDeclaration * fd) { + if (!global.params.symdebug) { + return; + } - Logger::println("D to dwarf funcend"); - LOG_SCOPE; + Logger::println("D to dwarf funcend"); + LOG_SCOPE; - assert(static_cast(getIrFunc(fd)->diSubprogram) != 0); - EmitStopPoint(fd->endloc); -} + assert(static_cast(getIrFunc(fd)->diSubprogram) != 0); + EmitStopPoint(fd->endloc); + } -void ldc::DIBuilder::EmitBlockStart(Loc &loc) { - if (!global.params.symdebug) - return; + void ldc::DIBuilder::EmitBlockStart(Loc & loc) { + if (!global.params.symdebug) { + return; + } - Logger::println("D to dwarf block start"); - LOG_SCOPE; + Logger::println("D to dwarf block start"); + LOG_SCOPE; - ldc::DILexicalBlock block = - DBuilder.createLexicalBlock(GetCurrentScope(), // scope - CreateFile(loc), // file - loc.linnum, // line - loc.linnum ? loc.charnum : 0 // column + ldc::DILexicalBlock block = + DBuilder.createLexicalBlock(GetCurrentScope(), // scope + CreateFile(loc), // file + loc.linnum, // line + loc.linnum ? loc.charnum : 0 // column #if LDC_LLVM_VER == 305 - , - 0 // DWARF path discriminator value + , + 0 // DWARF path discriminator value #endif - ); - IR->func()->diLexicalBlocks.push(block); - EmitStopPoint(loc); -} + ); + IR->func()->diLexicalBlocks.push(block); + EmitStopPoint(loc); + } -void ldc::DIBuilder::EmitBlockEnd() { - if (!global.params.symdebug) - return; + void ldc::DIBuilder::EmitBlockEnd() { + if (!global.params.symdebug) { + return; + } - Logger::println("D to dwarf block end"); - LOG_SCOPE; + Logger::println("D to dwarf block end"); + LOG_SCOPE; - IrFunction *fn = IR->func(); - assert(!fn->diLexicalBlocks.empty()); - fn->diLexicalBlocks.pop(); -} + IrFunction *fn = IR->func(); + assert(!fn->diLexicalBlocks.empty()); + fn->diLexicalBlocks.pop(); + } -void ldc::DIBuilder::EmitStopPoint(Loc &loc) { - if (!global.params.symdebug) - return; + void ldc::DIBuilder::EmitStopPoint(Loc & loc) { + if (!global.params.symdebug) { + return; + } - // If we already have a location set and the current loc is invalid - // (line 0), then we can just ignore it (see GitHub issue #998 for why we - // cannot do this in all cases). - if (!loc.linnum && + // If we already have a location set and the current loc is invalid + // (line 0), then we can just ignore it (see GitHub issue #998 for why we + // cannot do this in all cases). + if (!loc.linnum && #if LDC_LLVM_VER >= 307 - IR->ir->getCurrentDebugLocation() + IR->ir->getCurrentDebugLocation() #else !IR->ir->getCurrentDebugLocation().isUnknown() #endif - ) - return; + ) + return; - unsigned charnum = (loc.linnum ? loc.charnum : 0); - Logger::println("D to dwarf stoppoint at line %u, column %u", loc.linnum, - charnum); - LOG_SCOPE; - IR->ir->SetCurrentDebugLocation( - llvm::DebugLoc::get(loc.linnum, charnum, GetCurrentScope())); -} + unsigned charnum = (loc.linnum ? loc.charnum : 0); + Logger::println("D to dwarf stoppoint at line %u, column %u", loc.linnum, + charnum); + LOG_SCOPE; + IR->ir->SetCurrentDebugLocation( + llvm::DebugLoc::get(loc.linnum, charnum, GetCurrentScope())); + } -void ldc::DIBuilder::EmitValue(llvm::Value *val, VarDeclaration *vd) { - auto sub = IR->func()->variableMap.find(vd); - if (sub == IR->func()->variableMap.end()) - return; - - ldc::DILocalVariable debugVariable = sub->second; - if (!global.params.symdebug || !debugVariable) - return; - - llvm::Instruction *instr = - DBuilder.insertDbgValueIntrinsic(val, 0, debugVariable, -#if LDC_LLVM_VER >= 306 - DBuilder.createExpression(), -#endif -#if LDC_LLVM_VER >= 307 - IR->ir->getCurrentDebugLocation(), -#endif - IR->scopebb()); - instr->setDebugLoc(IR->ir->getCurrentDebugLocation()); -} - -void ldc::DIBuilder::EmitLocalVariable(llvm::Value *ll, VarDeclaration *vd, - Type *type, bool isThisPtr, -#if LDC_LLVM_VER >= 306 - llvm::ArrayRef addr -#else - llvm::ArrayRef addr -#endif - ) { - if (!global.params.symdebug) - return; - - Logger::println("D to dwarf local variable"); - LOG_SCOPE; - - auto &variableMap = IR->func()->variableMap; - auto sub = variableMap.find(vd); - if (sub != variableMap.end()) - return; // ensure that the debug variable is created only once - - // get type description - ldc::DIType TD = CreateTypeDescription(type ? type : vd->type, true); - if (static_cast(TD) == 0) - return; // unsupported - - if (vd->storage_class & (STCref | STCout)) - TD = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, TD); - - // get variable description - assert(!vd->isDataseg() && "static variable"); - -#if LDC_LLVM_VER < 308 - unsigned tag; - if (vd->isParameter()) - tag = llvm::dwarf::DW_TAG_arg_variable; - else - tag = llvm::dwarf::DW_TAG_auto_variable; -#endif - - ldc::DILocalVariable debugVariable; - unsigned Flags = 0; - if (isThisPtr) - Flags |= DIFlags::FlagArtificial | DIFlags::FlagObjectPointer; - -#if LDC_LLVM_VER < 306 - if (addr.empty()) { -#endif -#if LDC_LLVM_VER >= 308 - if (vd->isParameter()) { - FuncDeclaration *fd = vd->parent->isFuncDeclaration(); - assert(fd); - int argNo; - if (fd->vthis == vd) - argNo = 0; - else { - assert(fd->parameters); - for (argNo = 0; argNo < fd->parameters->dim; argNo++) - if ((*fd->parameters)[argNo] == vd) - break; - assert(argNo < fd->parameters->dim); - if (fd->vthis) - argNo++; + void ldc::DIBuilder::EmitValue(llvm::Value * val, VarDeclaration * vd) { + auto sub = IR->func()->variableMap.find(vd); + if (sub == IR->func()->variableMap.end()) { + return; } - debugVariable = - DBuilder.createParameterVariable(GetCurrentScope(), // scope - vd->toChars(), // name - argNo + 1, - CreateFile(vd->loc), // file - vd->loc.linnum, // line num - TD, // type - true, // preserve - Flags // flags - ); - } else - debugVariable = DBuilder.createAutoVariable(GetCurrentScope(), // scope - vd->toChars(), // name - CreateFile(vd->loc), // file - vd->loc.linnum, // line num - TD, // type - true, // preserve - Flags // flags - ); + ldc::DILocalVariable debugVariable = sub->second; + if (!global.params.symdebug || !debugVariable) { + return; + } + + llvm::Instruction *instr = + DBuilder.insertDbgValueIntrinsic(val, 0, debugVariable, +#if LDC_LLVM_VER >= 306 + DBuilder.createExpression(), +#endif +#if LDC_LLVM_VER >= 307 + IR->ir->getCurrentDebugLocation(), +#endif + IR->scopebb()); + instr->setDebugLoc(IR->ir->getCurrentDebugLocation()); + } + + void ldc::DIBuilder::EmitLocalVariable( + llvm::Value * ll, VarDeclaration * vd, Type * type, bool isThisPtr, +#if LDC_LLVM_VER >= 306 + llvm::ArrayRef addr +#else + llvm::ArrayRef addr +#endif + ) { + if (!global.params.symdebug) { + return; + } + + Logger::println("D to dwarf local variable"); + LOG_SCOPE; + + auto &variableMap = IR->func()->variableMap; + auto sub = variableMap.find(vd); + if (sub != variableMap.end()) { + return; // ensure that the debug variable is created only once + } + + // get type description + ldc::DIType TD = CreateTypeDescription(type ? type : vd->type, true); + if (static_cast(TD) == nullptr) { + return; // unsupported + } + + if (vd->storage_class & (STCref | STCout)) { + TD = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, + TD); + } + + // get variable description + assert(!vd->isDataseg() && "static variable"); + +#if LDC_LLVM_VER < 308 + unsigned tag; + if (vd->isParameter()) { + tag = llvm::dwarf::DW_TAG_arg_variable; + } else { + tag = llvm::dwarf::DW_TAG_auto_variable; + } +#endif + + ldc::DILocalVariable debugVariable; + unsigned Flags = 0; + if (isThisPtr) { + Flags |= DIFlags::FlagArtificial | DIFlags::FlagObjectPointer; + } + +#if LDC_LLVM_VER < 306 + if (addr.empty()) { +#endif +#if LDC_LLVM_VER >= 308 + if (vd->isParameter()) { + FuncDeclaration *fd = vd->parent->isFuncDeclaration(); + assert(fd); + int argNo; + if (fd->vthis == vd) + argNo = 0; + else { + assert(fd->parameters); + for (argNo = 0; argNo < fd->parameters->dim; argNo++) + if ((*fd->parameters)[argNo] == vd) + break; + assert(argNo < fd->parameters->dim); + if (fd->vthis) + argNo++; + } + + debugVariable = + DBuilder.createParameterVariable(GetCurrentScope(), // scope + vd->toChars(), // name + argNo + 1, + CreateFile(vd->loc), // file + vd->loc.linnum, // line num + TD, // type + true, // preserve + Flags // flags + ); + } else + debugVariable = + DBuilder.createAutoVariable(GetCurrentScope(), // scope + vd->toChars(), // name + CreateFile(vd->loc), // file + vd->loc.linnum, // line num + TD, // type + true, // preserve + Flags // flags + ); #else debugVariable = DBuilder.createLocalVariable(tag, // tag GetCurrentScope(), // scope @@ -889,61 +918,63 @@ void ldc::DIBuilder::EmitLocalVariable(llvm::Value *ll, VarDeclaration *vd, ); #endif #if LDC_LLVM_VER < 306 - } else { - debugVariable = DBuilder.createComplexVariable(tag, // tag - GetCurrentScope(), // scope - vd->toChars(), // name - CreateFile(vd->loc), // file - vd->loc.linnum, // line num - TD, // type - addr); - } + } else { + debugVariable = + DBuilder.createComplexVariable(tag, // tag + GetCurrentScope(), // scope + vd->toChars(), // name + CreateFile(vd->loc), // file + vd->loc.linnum, // line num + TD, // type + addr); + } #endif - variableMap[vd] = debugVariable; + variableMap[vd] = debugVariable; // declare #if LDC_LLVM_VER >= 306 - Declare(vd->loc, ll, debugVariable, addr.empty() - ? DBuilder.createExpression() - : DBuilder.createExpression(addr)); + Declare(vd->loc, ll, debugVariable, + addr.empty() ? DBuilder.createExpression() + : DBuilder.createExpression(addr)); #else Declare(vd->loc, ll, debugVariable); #endif -} + } -ldc::DIGlobalVariable -ldc::DIBuilder::EmitGlobalVariable(llvm::GlobalVariable *ll, - VarDeclaration *vd) { - if (!global.params.symdebug) + ldc::DIGlobalVariable ldc::DIBuilder::EmitGlobalVariable( + llvm::GlobalVariable * ll, VarDeclaration * vd) { + if (!global.params.symdebug) { #if LDC_LLVM_VER >= 307 - return nullptr; + return nullptr; #else return llvm::DIGlobalVariable(); + } #endif - Logger::println("D to dwarf global_variable"); - LOG_SCOPE; + Logger::println("D to dwarf global_variable"); + LOG_SCOPE; - assert(vd->isDataseg() || - (vd->storage_class & (STCconst | STCimmutable) && vd->init)); + assert(vd->isDataseg() || + (vd->storage_class & (STCconst | STCimmutable) && vd->init)); - return DBuilder.createGlobalVariable( + return DBuilder.createGlobalVariable( #if LDC_LLVM_VER >= 306 - GetCU(), // context + GetCU(), // context #endif - vd->toChars(), // name - mangle(vd), // linkage name - CreateFile(vd->loc), // file - vd->loc.linnum, // line num - CreateTypeDescription(vd->type, false), // type - vd->protection == PROTprivate, // is local to unit - ll // value - ); -} + vd->toChars(), // name + mangle(vd), // linkage name + CreateFile(vd->loc), // file + vd->loc.linnum, // line num + CreateTypeDescription(vd->type, false), // type + vd->protection == PROTprivate, // is local to unit + ll // value + ); + } -void ldc::DIBuilder::Finalize() { - if (!global.params.symdebug) - return; + void ldc::DIBuilder::Finalize() { + if (!global.params.symdebug) { + return; + } - DBuilder.finalize(); -} + DBuilder.finalize(); + } diff --git a/gen/dibuilder.h b/gen/dibuilder.h index 18471351cb..14fba85198 100644 --- a/gen/dibuilder.h +++ b/gen/dibuilder.h @@ -88,7 +88,7 @@ class DIBuilder { } public: - DIBuilder(IRState *const IR); + explicit DIBuilder(IRState *const IR); /// \brief Emit the Dwarf compile_unit global for a Module m. /// \param m Module to emit as compile unit. @@ -132,7 +132,7 @@ public: /// \param isThisPtr Parameter is hidden this pointer /// \param addr An array of complex address operations. void - EmitLocalVariable(llvm::Value *ll, VarDeclaration *vd, Type *type = 0, + EmitLocalVariable(llvm::Value *ll, VarDeclaration *vd, Type *type = nullptr, bool isThisPtr = false, #if LDC_LLVM_VER >= 306 llvm::ArrayRef addr = llvm::ArrayRef() @@ -186,8 +186,9 @@ private: public: template void OpOffset(T &addr, llvm::StructType *type, int index) { - if (!global.params.symdebug) + if (!global.params.symdebug) { return; + } uint64_t offset = gDataLayout->getStructLayout(type)->getElementOffset(index); @@ -202,8 +203,9 @@ public: } template void OpOffset(T &addr, llvm::Value *val, int index) { - if (!global.params.symdebug) + if (!global.params.symdebug) { return; + } llvm::StructType *type = isaStruct(val->getType()->getContainedType(0)); assert(type); @@ -211,8 +213,9 @@ public: } template void OpDeref(T &addr) { - if (!global.params.symdebug) + if (!global.params.symdebug) { return; + } #if LDC_LLVM_VER >= 306 addr.push_back(llvm::dwarf::DW_OP_deref); diff --git a/gen/dvalue.cpp b/gen/dvalue.cpp index 83bca621f4..e90e9e9993 100644 --- a/gen/dvalue.cpp +++ b/gen/dvalue.cpp @@ -21,19 +21,22 @@ static bool checkVarValueType(LLType *t, bool extraDeref) { if (extraDeref) { llvm::PointerType *pt = llvm::dyn_cast(t); - if (!pt) + if (!pt) { return false; + } t = pt->getElementType(); } llvm::PointerType *pt = llvm::dyn_cast(t); - if (!pt) + if (!pt) { return false; + } // bools should not be stored as i1 any longer. - if (pt->getElementType() == llvm::Type::getInt1Ty(gIR->context())) + if (pt->getElementType() == llvm::Type::getInt1Ty(gIR->context())) { return false; + } return true; } @@ -44,14 +47,15 @@ DVarValue::DVarValue(Type *t, VarDeclaration *vd, LLValue *llvmValue) } DVarValue::DVarValue(Type *t, LLValue *llvmValue) - : DValue(t), var(0), val(llvmValue) { + : DValue(t), var(nullptr), val(llvmValue) { assert(checkVarValueType(llvmValue->getType(), false)); } LLValue *DVarValue::getLVal() { assert(val); - if (var && isSpecialRefVar(var)) + if (var && isSpecialRefVar(var)) { return DtoLoad(val); + } return val; } @@ -59,11 +63,13 @@ LLValue *DVarValue::getRVal() { assert(val); llvm::Value *storage = val; - if (var && isSpecialRefVar(var)) + if (var && isSpecialRefVar(var)) { storage = DtoLoad(storage); + } - if (DtoIsPassedByRef(type->toBasetype())) + if (DtoIsPassedByRef(type->toBasetype())) { return storage; + } llvm::Value *rawValue = DtoLoad(storage); diff --git a/gen/dvalue.h b/gen/dvalue.h index 97036d1199..4fcc5d803b 100644 --- a/gen/dvalue.h +++ b/gen/dvalue.h @@ -43,8 +43,8 @@ class DSliceValue; class DValue { public: Type *type; - DValue(Type *ty) : type(ty) {} - virtual ~DValue() {} + explicit DValue(Type *ty) : type(ty) {} + virtual ~DValue() = default; Type *&getType() { assert(type); @@ -53,25 +53,25 @@ public: virtual llvm::Value *getLVal() { assert(0); - return 0; + return nullptr; } virtual llvm::Value *getRVal() { assert(0); - return 0; + return nullptr; } virtual bool isLVal() { return false; } - virtual DImValue *isIm() { return NULL; } - virtual DConstValue *isConst() { return NULL; } - virtual DNullValue *isNull() { return NULL; } - virtual DVarValue *isVar() { return NULL; } - virtual DFieldValue *isField() { return NULL; } - virtual DSliceValue *isSlice() { return NULL; } - virtual DFuncValue *isFunc() { return NULL; } + virtual DImValue *isIm() { return nullptr; } + virtual DConstValue *isConst() { return nullptr; } + virtual DNullValue *isNull() { return nullptr; } + virtual DVarValue *isVar() { return nullptr; } + virtual DFieldValue *isField() { return nullptr; } + virtual DSliceValue *isSlice() { return nullptr; } + virtual DFuncValue *isFunc() { return nullptr; } protected: - DValue() {} + DValue() = default; DValue(const DValue &) {} DValue &operator=(const DValue &other) { type = other.type; @@ -84,12 +84,12 @@ class DImValue : public DValue { public: DImValue(Type *t, llvm::Value *v) : DValue(t), val(v) {} - virtual llvm::Value *getRVal() { + llvm::Value *getRVal() override { assert(val); return val; } - virtual DImValue *isIm() { return this; } + DImValue *isIm() override { return this; } protected: llvm::Value *val; @@ -100,9 +100,9 @@ class DConstValue : public DValue { public: DConstValue(Type *t, llvm::Constant *con) : DValue(t), c(con) {} - virtual llvm::Value *getRVal(); + llvm::Value *getRVal() override; - virtual DConstValue *isConst() { return this; } + DConstValue *isConst() override { return this; } llvm::Constant *c; }; @@ -111,7 +111,7 @@ public: class DNullValue : public DConstValue { public: DNullValue(Type *t, llvm::Constant *con) : DConstValue(t, con) {} - virtual DNullValue *isNull() { return this; } + DNullValue *isNull() override { return this; } }; // variable d-value @@ -120,15 +120,15 @@ public: DVarValue(Type *t, VarDeclaration *vd, llvm::Value *llvmValue); DVarValue(Type *t, llvm::Value *llvmValue); - virtual bool isLVal() { return true; } - virtual llvm::Value *getLVal(); - virtual llvm::Value *getRVal(); + bool isLVal() override { return true; } + llvm::Value *getLVal() override; + llvm::Value *getRVal() override; /// Returns the underlying storage for special internal ref variables. /// Illegal to call on any other value. virtual llvm::Value *getRefStorage(); - virtual DVarValue *isVar() { return this; } + DVarValue *isVar() override { return this; } VarDeclaration *var; @@ -140,7 +140,7 @@ protected: class DFieldValue : public DVarValue { public: DFieldValue(Type *t, llvm::Value *llvmValue) : DVarValue(t, llvmValue) {} - virtual DFieldValue *isField() { return this; } + DFieldValue *isField() override { return this; } }; // slice d-value @@ -149,9 +149,9 @@ public: DSliceValue(Type *t, llvm::Value *l, llvm::Value *p) : DValue(t), len(l), ptr(p) {} - virtual llvm::Value *getRVal(); + llvm::Value *getRVal() override; - virtual DSliceValue *isSlice() { return this; } + DSliceValue *isSlice() override { return this; } llvm::Value *len; llvm::Value *ptr; @@ -160,12 +160,13 @@ public: // function d-value class DFuncValue : public DValue { public: - DFuncValue(Type *t, FuncDeclaration *fd, llvm::Value *v, llvm::Value *vt = 0); - DFuncValue(FuncDeclaration *fd, llvm::Value *v, llvm::Value *vt = 0); + DFuncValue(Type *t, FuncDeclaration *fd, llvm::Value *v, + llvm::Value *vt = nullptr); + DFuncValue(FuncDeclaration *fd, llvm::Value *v, llvm::Value *vt = nullptr); - virtual llvm::Value *getRVal(); + llvm::Value *getRVal() override; - virtual DFuncValue *isFunc() { return this; } + DFuncValue *isFunc() override { return this; } FuncDeclaration *func; llvm::Value *val; diff --git a/gen/functions.cpp b/gen/functions.cpp index f61fba935d..cf05892575 100644 --- a/gen/functions.cpp +++ b/gen/functions.cpp @@ -51,8 +51,9 @@ llvm::FunctionType *DtoFunctionType(Type *type, IrFuncTy &irFty, Type *thistype, "trying to codegen function ignored by the frontend?"); // Return cached type if available - if (irFty.funcType) + if (irFty.funcType) { return irFty.funcType; + } TargetABI *abi = (isIntrinsic ? TargetABI::getIntrinsic() : gABI); @@ -89,8 +90,9 @@ llvm::FunctionType *DtoFunctionType(Type *type, IrFuncTy &irFty, Type *thistype, if (thistype) { // Add the this pointer for member functions AttrBuilder attrBuilder; - if (isCtor) + if (isCtor) { attrBuilder.add(LLAttribute::Returned); + } newIrFty.arg_this = new IrFuncTyArg( thistype, thistype->toBasetype()->ty == Tstruct, attrBuilder); ++nextLLArgIdx; @@ -137,8 +139,8 @@ llvm::FunctionType *DtoFunctionType(Type *type, IrFuncTy &irFty, Type *thistype, if (arg->storageClass & STClazy) { // Lazy arguments are lowered to delegates. Logger::println("lazy param"); - TypeFunction *ltf = new TypeFunction(NULL, arg->type, 0, LINKd); - TypeDelegate *ltd = new TypeDelegate(ltf); + auto ltf = new TypeFunction(nullptr, arg->type, 0, LINKd); + auto ltd = new TypeDelegate(ltf); loweredDType = ltd; } else if (!passPointer) { if (abi->passByVal(loweredDType)) { @@ -166,17 +168,22 @@ llvm::FunctionType *DtoFunctionType(Type *type, IrFuncTy &irFty, Type *thistype, llvm::SmallVector argtypes; argtypes.reserve(nextLLArgIdx); - if (irFty.arg_sret) + if (irFty.arg_sret) { argtypes.push_back(irFty.arg_sret->ltype); - if (irFty.arg_this) + } + if (irFty.arg_this) { argtypes.push_back(irFty.arg_this->ltype); - if (irFty.arg_nest) + } + if (irFty.arg_nest) { argtypes.push_back(irFty.arg_nest->ltype); - if (irFty.arg_arguments) + } + if (irFty.arg_arguments) { argtypes.push_back(irFty.arg_arguments->ltype); + } - if (irFty.arg_sret && irFty.arg_this && abi->passThisBeforeSret(f)) + if (irFty.arg_sret && irFty.arg_this && abi->passThisBeforeSret(f)) { std::swap(argtypes[0], argtypes[1]); + } const size_t firstExplicitArg = argtypes.size(); const size_t numExplicitLLArgs = irFty.args.size(); @@ -201,20 +208,22 @@ llvm::FunctionType *DtoFunctionType(Type *type, IrFuncTy &irFty, Type *thistype, static llvm::FunctionType *DtoVaFunctionType(FuncDeclaration *fdecl) { IrFuncTy &irFty = getIrFunc(fdecl, true)->irFty; - if (irFty.funcType) + if (irFty.funcType) { return irFty.funcType; + } irFty.ret = new IrFuncTyArg(Type::tvoid, false); irFty.args.push_back(new IrFuncTyArg(Type::tvoid->pointerTo(), false)); - if (fdecl->llvmInternal == LLVMva_start) + if (fdecl->llvmInternal == LLVMva_start) { irFty.funcType = GET_INTRINSIC_DECL(vastart)->getFunctionType(); - else if (fdecl->llvmInternal == LLVMva_copy) { + } else if (fdecl->llvmInternal == LLVMva_copy) { irFty.funcType = GET_INTRINSIC_DECL(vacopy)->getFunctionType(); irFty.args.push_back(new IrFuncTyArg(Type::tvoid->pointerTo(), false)); - } else if (fdecl->llvmInternal == LLVMva_end) + } else if (fdecl->llvmInternal == LLVMva_end) { irFty.funcType = GET_INTRINSIC_DECL(vaend)->getFunctionType(); + } assert(irFty.funcType); return irFty.funcType; @@ -224,10 +233,11 @@ static llvm::FunctionType *DtoVaFunctionType(FuncDeclaration *fdecl) { llvm::FunctionType *DtoFunctionType(FuncDeclaration *fdecl) { // handle for C vararg intrinsics - if (DtoIsVaIntrinsic(fdecl)) + if (DtoIsVaIntrinsic(fdecl)) { return DtoVaFunctionType(fdecl); + } - Type *dthis = 0, *dnest = 0; + Type *dthis = nullptr, *dnest = nullptr; if (fdecl->ident == Id::ensure || fdecl->ident == Id::require) { FuncDeclaration *p = fdecl->parent->isFuncDeclaration(); @@ -241,8 +251,9 @@ llvm::FunctionType *DtoFunctionType(FuncDeclaration *fdecl) { dthis = ad->type; LLType *thisty = DtoType(dthis); // Logger::cout() << "this llvm type: " << *thisty << '\n'; - if (ad->isStructDeclaration()) + if (ad->isStructDeclaration()) { thisty = getPtrToType(thisty); + } } else { IF_LOG Logger::println("chars: %s type: %s kind: %s", fdecl->toChars(), fdecl->type->toChars(), fdecl->kind()); @@ -263,14 +274,15 @@ llvm::FunctionType *DtoFunctionType(FuncDeclaration *fdecl) { static llvm::Function *DtoDeclareVaFunction(FuncDeclaration *fdecl) { DtoVaFunctionType(fdecl); - llvm::Function *func = 0; + llvm::Function *func = nullptr; - if (fdecl->llvmInternal == LLVMva_start) + if (fdecl->llvmInternal == LLVMva_start) { func = GET_INTRINSIC_DECL(vastart); - else if (fdecl->llvmInternal == LLVMva_copy) + } else if (fdecl->llvmInternal == LLVMva_copy) { func = GET_INTRINSIC_DECL(vacopy); - else if (fdecl->llvmInternal == LLVMva_end) + } else if (fdecl->llvmInternal == LLVMva_end) { func = GET_INTRINSIC_DECL(vaend); + } assert(func); getIrFunc(fdecl)->func = func; @@ -286,21 +298,23 @@ void DtoResolveFunction(FuncDeclaration *fdecl) { return; // ignore declaration completely } - if (fdecl->ir.isResolved()) + if (fdecl->ir.isResolved()) { return; + } fdecl->ir.setResolved(); Type *type = fdecl->type; // If errors occurred compiling it, such as bugzilla 6118 if (type && type->ty == Tfunction) { Type *next = static_cast(type)->next; - if (!next || next->ty == Terror) + if (!next || next->ty == Terror) { return; + } } // printf("resolve function: %s\n", fdecl->toPrettyChars()); - if (fdecl->parent) + if (fdecl->parent) { if (TemplateInstance *tinst = fdecl->parent->isTemplateInstance()) { if (TemplateDeclaration *tempdecl = tinst->tempdecl->isTemplateDeclaration()) { @@ -345,6 +359,7 @@ void DtoResolveFunction(FuncDeclaration *fdecl) { } } } + } DtoFunctionType(fdecl); @@ -405,8 +420,9 @@ static void set_param_attrs(TypeFunction *f, llvm::Function *func, void DtoDeclareFunction(FuncDeclaration *fdecl) { DtoResolveFunction(fdecl); - if (fdecl->ir.isDeclared()) + if (fdecl->ir.isDeclared()) { return; + } fdecl->ir.setDeclared(); IF_LOG Logger::println("DtoDeclareFunction(%s): %s", fdecl->toPrettyChars(), @@ -433,9 +449,10 @@ void DtoDeclareFunction(FuncDeclaration *fdecl) { // create IrFunction IrFunction *irFunc = getIrFunc(fdecl, true); - LLFunction *vafunc = 0; - if (DtoIsVaIntrinsic(fdecl)) + LLFunction *vafunc = nullptr; + if (DtoIsVaIntrinsic(fdecl)) { vafunc = DtoDeclareVaFunction(fdecl); + } // calling convention LINK link = f->linkage; @@ -583,19 +600,22 @@ void DtoDeclareFunction(FuncDeclaration *fdecl) { static LinkageWithCOMDAT lowerFuncLinkage(FuncDeclaration *fdecl) { // Intrinsics are always external. - if (DtoIsIntrinsic(fdecl)) + if (DtoIsIntrinsic(fdecl)) { return LinkageWithCOMDAT(llvm::GlobalValue::ExternalLinkage, false); + } // Generated array op functions behave like templates in that they might be // emitted into many different modules. - if (fdecl->isArrayOp && (willInline() || !isDruntimeArrayOp(fdecl))) + if (fdecl->isArrayOp && (willInline() || !isDruntimeArrayOp(fdecl))) { return LinkageWithCOMDAT(templateLinkage, supportsCOMDAT()); + } // A body-less declaration always needs to be marked as external in LLVM // (also e.g. naked template functions which would otherwise be weak_odr, // but where the definition is in module-level inline asm). - if (!fdecl->fbody || fdecl->naked) + if (!fdecl->fbody || fdecl->naked) { return LinkageWithCOMDAT(llvm::GlobalValue::ExternalLinkage, false); + } return DtoLinkage(fdecl); } @@ -605,12 +625,13 @@ void DtoDefineFunction(FuncDeclaration *fd) { fd->loc.toChars()); LOG_SCOPE; - if (fd->ir.isDefined()) + if (fd->ir.isDefined()) { return; + } if ((fd->type && fd->type->ty == Terror) || (fd->type && fd->type->ty == Tfunction && - static_cast(fd->type)->next == NULL) || + static_cast(fd->type)->next == nullptr) || (fd->type && fd->type->ty == Tfunction && static_cast(fd->type)->next->ty == Terror)) { IF_LOG Logger::println( @@ -657,10 +678,11 @@ void DtoDefineFunction(FuncDeclaration *fd) { fd->ir.setDefined(); return; } - if (f->isNested()) + if (f->isNested()) { f = f->toParent2()->isFuncDeclaration(); - else + } else { break; + } } DtoDeclareFunction(fd); @@ -668,8 +690,9 @@ void DtoDefineFunction(FuncDeclaration *fd) { // DtoResolveFunction might also set the defined flag for functions we // should not touch. - if (fd->ir.isDefined()) + if (fd->ir.isDefined()) { return; + } fd->ir.setDefined(); // We cannot emit nested functions with parents that have not gone through @@ -728,16 +751,18 @@ void DtoDefineFunction(FuncDeclaration *fd) { llvm::Function *func = irFunc->func; // is there a body? - if (fd->fbody == NULL) + if (fd->fbody == nullptr) { return; + } IF_LOG Logger::println("Doing function body for: %s", fd->toChars()); gIR->functions.push_back(irFunc); LinkageWithCOMDAT lwc = lowerFuncLinkage(fd); func->setLinkage(lwc.first); - if (lwc.second) + if (lwc.second) { SET_COMDAT(func, gIR->module); + } // On x86_64, always set 'uwtable' for System V ABI compatibility. // TODO: Find a better place for this. @@ -804,12 +829,13 @@ void DtoDefineFunction(FuncDeclaration *fd) { assert(getIrParameter(fd->vthis)->value == thisvar); getIrParameter(fd->vthis)->value = thismem; - gIR->DBuilder.EmitLocalVariable(thismem, fd->vthis, 0, true); + gIR->DBuilder.EmitLocalVariable(thismem, fd->vthis, nullptr, true); } // give the 'nestArg' storage - if (irFty.arg_nest) + if (irFty.arg_nest) { irFunc->nestArg = DtoAllocaDump(irFunc->nestArg, 0, "nestedFrame"); + } // give arguments storage and debug info if (fd->parameters) { @@ -851,8 +877,9 @@ void DtoDefineFunction(FuncDeclaration *fd) { if (global.params.symdebug && !(isaArgument(irparam->value) && - isaArgument(irparam->value)->hasByValAttr())) + isaArgument(irparam->value)->hasByValAttr())) { gIR->DBuilder.EmitLocalVariable(irparam->value, vd, debugInfoType); + } } } @@ -886,7 +913,7 @@ void DtoDefineFunction(FuncDeclaration *fd) { // output function body Statement_toIR(fd->fbody, gIR); - irFunc->scopes = 0; + irFunc->scopes = nullptr; } llvm::BasicBlock *bb = gIR->scopebb(); @@ -913,16 +940,18 @@ void DtoDefineFunction(FuncDeclaration *fd) { } else { gIR->ir->CreateRet(llvm::UndefValue::get(func->getReturnType())); } - } else + } else { gIR->ir->CreateRet(LLConstant::getNullValue(func->getReturnType())); + } } gIR->DBuilder.EmitFuncEnd(fd); // erase alloca point - if (allocaPoint->getParent()) + if (allocaPoint->getParent()) { allocaPoint->eraseFromParent(); - allocaPoint = 0; - gIR->func()->allocapoint = 0; + } + allocaPoint = nullptr; + gIR->func()->allocapoint = nullptr; gIR->scopes.pop_back(); @@ -955,7 +984,7 @@ DValue *DtoArgument(Parameter *fnarg, Expression *argexp) { // byval arg, but expr has no storage yet if (DtoIsPassedByRef(argexp->type) && (arg->isSlice() || arg->isNull())) { LLValue *alloc = DtoAlloca(argexp->type, ".tmp_arg"); - DVarValue *vv = new DVarValue(argexp->type, alloc); + auto vv = new DVarValue(argexp->type, alloc); DtoAssign(argexp->loc, vv, arg); arg = vv; } @@ -970,12 +999,13 @@ int binary(const char *p, const char **tab, int high) { do { k = (i + j) / 2; l = strcmp(p, tab[k]); - if (!l) + if (!l) { return k; - else if (l < 0) + } else if (l < 0) { j = k; - else + } else { i = k + 1; + } } while (i != j); return -1; } @@ -1098,8 +1128,9 @@ int isDruntimeArrayOp(FuncDeclaration *fd) { char *name = fd->ident->toChars(); int i = binary(name, libArrayopFuncs, sizeof(libArrayopFuncs) / sizeof(char *)); - if (i != -1) + if (i != -1) { return 1; + } #ifdef DEBUG // Make sure our array is alphabetized for (i = 0; i < sizeof(libArrayopFuncs) / sizeof(char *); i++) { diff --git a/gen/inlineir.cpp b/gen/inlineir.cpp index 72ebeb0864..0313900396 100644 --- a/gen/inlineir.cpp +++ b/gen/inlineir.cpp @@ -48,14 +48,16 @@ llvm::Function *DtoInlineIRFunction(FuncDeclaration *fdecl) { stream << *DtoType(ty); i++; - if (i >= arg_types.dim) + if (i >= arg_types.dim) { break; + } stream << ", "; } - if (ret->ty == Tvoid) + if (ret->ty == Tvoid) { code.append("\nret void"); + } stream << ")\n{\n" << code << "\n}"; @@ -70,12 +72,13 @@ llvm::Function *DtoInlineIRFunction(FuncDeclaration *fdecl) { #endif std::string errstr = err.getMessage(); - if (errstr != "") + if (errstr != "") { error(tinst->loc, "can't parse inline LLVM IR:\n%s\n%s\n%s\nThe input string was: \n%s", err.getLineContents().str().c_str(), (std::string(err.getColumnNo(), ' ') + '^').c_str(), errstr.c_str(), stream.str().c_str()); + } #if LDC_LLVM_VER >= 306 llvm::Linker(&gIR->module).linkInModule(m.get()); diff --git a/gen/irstate.cpp b/gen/irstate.cpp index 21ef8530d0..21877008e6 100644 --- a/gen/irstate.cpp +++ b/gen/irstate.cpp @@ -16,13 +16,13 @@ #include "ir/irfunction.h" #include -IRState *gIR = 0; -llvm::TargetMachine *gTargetMachine = 0; -const llvm::DataLayout *gDataLayout = 0; -TargetABI *gABI = 0; +IRState *gIR = nullptr; +llvm::TargetMachine *gTargetMachine = nullptr; +const llvm::DataLayout *gDataLayout = nullptr; +TargetABI *gABI = nullptr; ////////////////////////////////////////////////////////////////////////////////////////// -IRScope::IRScope() : builder(gIR->context()) { begin = NULL; } +IRScope::IRScope() : builder(gIR->context()) { begin = nullptr; } IRScope::IRScope(llvm::BasicBlock *b) : begin(b), builder(b) {} @@ -35,13 +35,13 @@ const IRScope &IRScope::operator=(const IRScope &rhs) { ////////////////////////////////////////////////////////////////////////////////////////// IRState::IRState(const char *name, llvm::LLVMContext &context) : module(name, context), DBuilder(this) { - mutexType = NULL; - moduleRefType = NULL; + mutexType = nullptr; + moduleRefType = nullptr; - dmodule = 0; - mainFunc = 0; + dmodule = nullptr; + mainFunc = nullptr; ir.state = this; - asmBlock = NULL; + asmBlock = nullptr; } IrFunction *IRState::func() { @@ -112,8 +112,9 @@ bool IRState::emitArrayBoundsChecks() { } // Safe functions only. - if (functions.empty()) + if (functions.empty()) { return false; + } Type *t = func()->decl->type; return t->ty == Tfunction && ((TypeFunction *)t)->trust == TRUSTsafe; diff --git a/gen/irstate.h b/gen/irstate.h index ebc9ec5ec6..9761e30f99 100644 --- a/gen/irstate.h +++ b/gen/irstate.h @@ -71,7 +71,7 @@ struct IRBuilderHelper { }; struct IRAsmStmt { - IRAsmStmt() : isBranchToLabel(NULL) {} + IRAsmStmt() : isBranchToLabel(nullptr) {} std::string code; std::string out_c; @@ -97,9 +97,9 @@ struct IRAsmBlock { bool retemu; // emulate abi ret with a temporary LLValue *(*retfixup)(IRBuilderHelper b, LLValue *orig); // Modifies retval - IRAsmBlock(CompoundAsmStatement *b) - : outputcount(0), asmBlock(b), retty(NULL), retn(0), retemu(false), - retfixup(NULL) {} + explicit IRAsmBlock(CompoundAsmStatement *b) + : outputcount(0), asmBlock(b), retty(nullptr), retn(0), retemu(false), + retfixup(nullptr) {} }; // represents the module diff --git a/gen/llvmhelpers.cpp b/gen/llvmhelpers.cpp index 6ad3d45e3d..7b15543d7d 100644 --- a/gen/llvmhelpers.cpp +++ b/gen/llvmhelpers.cpp @@ -140,8 +140,9 @@ void DtoDeleteArray(Loc &loc, DValue *arr) { unsigned DtoAlignment(Type *type) { structalign_t alignment = type->alignment(); - if (alignment == STRUCTALIGN_DEFAULT) + if (alignment == STRUCTALIGN_DEFAULT) { alignment = type->alignsize(); + } return (alignment == STRUCTALIGN_DEFAULT ? 0 : alignment); } @@ -166,18 +167,18 @@ llvm::AllocaInst *DtoAlloca(VarDeclaration *vd, const char *name) { llvm::AllocaInst *DtoArrayAlloca(Type *type, unsigned arraysize, const char *name) { LLType *lltype = DtoType(type); - llvm::AllocaInst *ai = new llvm::AllocaInst(lltype, DtoConstUint(arraysize), - name, gIR->topallocapoint()); + auto ai = new llvm::AllocaInst(lltype, DtoConstUint(arraysize), name, + gIR->topallocapoint()); ai->setAlignment(DtoAlignment(type)); return ai; } llvm::AllocaInst *DtoRawAlloca(LLType *lltype, size_t alignment, const char *name) { - llvm::AllocaInst *ai = - new llvm::AllocaInst(lltype, name, gIR->topallocapoint()); - if (alignment) + auto ai = new llvm::AllocaInst(lltype, name, gIR->topallocapoint()); + if (alignment) { ai->setAlignment(alignment); + } return ai; } @@ -310,8 +311,9 @@ void DtoAssign(Loc &loc, DValue *lhs, DValue *rhs, int op, // Check whether source and destination values are the same at compile // time as to not emit an invalid (overlapping) memcpy on trivial // struct self-assignments like 'A a; a = a;'. - if (src != dst) + if (src != dst) { DtoAggrCopy(dst, src); + } } } else if (t->ty == Tarray || t->ty == Tsarray) { DtoArrayAssign(loc, lhs, rhs, op, canSkipPostblit); @@ -355,8 +357,9 @@ void DtoAssign(Loc &loc, DValue *lhs, DValue *rhs, int op, } #if 1 if (r->getType() != - lit) // It's wierd but it happens. TODO: try to remove this hack + lit) { // It's wierd but it happens. TODO: try to remove this hack r = DtoBitCast(r, lit); + } #else assert(r->getType() == lit); #endif @@ -488,8 +491,9 @@ DValue *DtoCastPtr(Loc &loc, DValue *val, Type *to) { } DValue *DtoCastFloat(Loc &loc, DValue *val, Type *to) { - if (val->getType() == to) + if (val->getType() == to) { return val; + } LLType *tolltype = DtoType(to); @@ -541,8 +545,8 @@ DValue *DtoCastDelegate(Loc &loc, DValue *val, Type *to) { if (to->toBasetype()->ty == Tdelegate) { return DtoPaintType(loc, val, to); } else if (to->toBasetype()->ty == Tbool) { - return new DImValue(to, - DtoDelegateEquals(TOKnotequal, val->getRVal(), NULL)); + return new DImValue( + to, DtoDelegateEquals(TOKnotequal, val->getRVal(), nullptr)); } else { error(loc, "invalid cast from '%s' to '%s'", val->getType()->toChars(), to->toChars()); @@ -611,8 +615,9 @@ DValue *DtoCast(Loc &loc, DValue *val, Type *to) { } } - if (fromtype->equals(totype)) + if (fromtype->equals(totype)) { return val; + } IF_LOG Logger::println("Casting from '%s' to '%s'", fromtype->toChars(), to->toChars()); @@ -707,13 +712,16 @@ DValue *DtoPaintType(Loc &loc, DValue *val, Type *to) { ////////////////////////////////////////////////////////////////////////////////////////*/ TemplateInstance *DtoIsTemplateInstance(Dsymbol *s) { - if (!s) - return NULL; - if (s->isTemplateInstance() && !s->isTemplateMixin()) + if (!s) { + return nullptr; + } + if (s->isTemplateInstance() && !s->isTemplateMixin()) { return s->isTemplateInstance(); - if (s->parent) + } + if (s->parent) { return DtoIsTemplateInstance(s->parent); - return NULL; + } + return nullptr; } /****************************************************************************************/ @@ -736,8 +744,9 @@ void DtoResolveDsymbol(Dsymbol *dsym) { } void DtoResolveVariable(VarDeclaration *vd) { - if (vd->isTypeInfoDeclaration()) + if (vd->isTypeInfoDeclaration()) { return DtoResolveTypeInfo(static_cast(vd)); + } IF_LOG Logger::println("DtoResolveVariable(%s)", vd->toPrettyChars()); LOG_SCOPE; @@ -751,8 +760,9 @@ void DtoResolveVariable(VarDeclaration *vd) { return; } - if (AggregateDeclaration *ad = vd->isMember()) + if (AggregateDeclaration *ad = vd->isMember()) { DtoResolveDsymbol(ad); + } // global variable if (vd->isDataseg()) { @@ -762,18 +772,20 @@ void DtoResolveVariable(VarDeclaration *vd) { "manifest constant being codegen'd!"); // don't duplicate work - if (vd->ir.isResolved()) + if (vd->ir.isResolved()) { return; + } vd->ir.setDeclared(); getIrGlobal(vd, true); IF_LOG { - if (vd->parent) + if (vd->parent) { Logger::println("parent: %s (%s)", vd->parent->toChars(), vd->parent->kind()); - else + } else { Logger::println("parent: null"); + } } // If a const/immutable value has a proper initializer (not "= void"), @@ -783,8 +795,9 @@ void DtoResolveVariable(VarDeclaration *vd) { !vd->init->isVoidInitializer(); assert(!vd->ir.isInitialized()); - if (gIR->dmodule) + if (gIR->dmodule) { vd->ir.setInitialized(); + } std::string llName(mangle(vd)); // Since the type of a global must exactly match the type of its @@ -806,7 +819,7 @@ void DtoResolveVariable(VarDeclaration *vd) { llvm::GlobalVariable *gvar = getOrCreateGlobal(vd->loc, gIR->module, DtoMemType(vd->type), isLLConst, - linkage, 0, llName, vd->isThreadlocal()); + linkage, nullptr, llName, vd->isThreadlocal()); getIrGlobal(vd)->value = gvar; // Set the alignment and use the target pointer size as lower bound. @@ -868,12 +881,13 @@ void DtoVarDeclaration(VarDeclaration *vd) { llvm::Value *allocainst; LLType *lltype = DtoType(type); - if (gDataLayout->getTypeSizeInBits(lltype) == 0) + if (gDataLayout->getTypeSizeInBits(lltype) == 0) { allocainst = llvm::ConstantPointerNull::get(getPtrToType(lltype)); - else if (type != vd->type) + } else if (type != vd->type) { allocainst = DtoAlloca(type, vd->toChars()); - else + } else { allocainst = DtoAlloca(vd, vd->toChars()); + } irLocal->value = allocainst; @@ -883,7 +897,7 @@ void DtoVarDeclaration(VarDeclaration *vd) { T t = f(); // t's memory address is taken hidden pointer */ Type *vdBasetype = vd->type->toBasetype(); - ExpInitializer *ei = 0; + ExpInitializer *ei = nullptr; if ((vdBasetype->ty == Tstruct || vdBasetype->ty == Tsarray) && vd->init && (ei = vd->init->isExpInitializer())) { if (ei->exp->op == TOKconstruct) { @@ -945,12 +959,13 @@ DValue *DtoDeclarationExp(Dsymbol *declaration) { // if aliassym is set, this VarDecl is redone as an alias to another symbol // this seems to be done to rewrite Tuple!(...) v; // as a TupleDecl that contains a bunch of individual VarDecls - if (vd->aliassym) + if (vd->aliassym) { return DtoDeclarationExp(vd->aliassym); + } if (vd->storage_class & STCmanifest) { IF_LOG Logger::println("Manifest constant, nothing to do."); - return 0; + return nullptr; } // static @@ -980,11 +995,12 @@ DValue *DtoDeclarationExp(Dsymbol *declaration) { else if (AttribDeclaration *a = declaration->isAttribDeclaration()) { Logger::println("AttribDeclaration"); // choose the right set in case this is a conditional declaration - Dsymbols *d = a->include(NULL, NULL); - if (d) + Dsymbols *d = a->include(nullptr, nullptr); + if (d) { for (unsigned i = 0; i < d->dim; ++i) { DtoDeclarationExp((*d)[i]); } + } } // mixin declaration else if (TemplateMixin *m = declaration->isTemplateMixin()) { @@ -1010,7 +1026,7 @@ DValue *DtoDeclarationExp(Dsymbol *declaration) { IF_LOG Logger::println("Ignoring Symbol: %s", declaration->kind()); } - return 0; + return nullptr; } // does pretty much the same as DtoDeclarationExp, except it doesn't initialize, @@ -1022,14 +1038,15 @@ LLValue *DtoRawVarDeclaration(VarDeclaration *var, LLValue *addr) { // we don't handle aliases either assert(!var->aliassym); - IrLocal *irLocal = isIrLocalCreated(var) ? getIrLocal(var) : 0; + IrLocal *irLocal = isIrLocalCreated(var) ? getIrLocal(var) : nullptr; // alloca if necessary if (!addr && (!irLocal || !irLocal->value)) { addr = DtoAlloca(var, var->toChars()); // add debug info - if (!irLocal) + if (!irLocal) { irLocal = getIrLocal(var, true); + } gIR->DBuilder.EmitLocalVariable(addr, var); } @@ -1040,8 +1057,9 @@ LLValue *DtoRawVarDeclaration(VarDeclaration *var, LLValue *addr) { if (!irLocal->value) { assert(addr); irLocal->value = addr; - } else + } else { assert(!addr || addr == irLocal->value); + } } // normal local variable else { @@ -1077,7 +1095,7 @@ LLValue *DtoRawVarDeclaration(VarDeclaration *var, LLValue *addr) { ////////////////////////////////////////////////////////////////////////////////////////*/ LLConstant *DtoConstInitializer(Loc &loc, Type *type, Initializer *init) { - LLConstant *_init = 0; // may return zero + LLConstant *_init = nullptr; // may return zero if (!init) { IF_LOG Logger::println("const default initializer for %s", type->toChars()); Expression *initExp = type->defaultInit(); @@ -1183,15 +1201,16 @@ LLConstant *DtoTypeInfoOf(Type *type, bool base) { LOG_SCOPE type = type->merge2(); // needed.. getTypeInfo does the same - getTypeInfoType(type, NULL); + getTypeInfoType(type, nullptr); TypeInfoDeclaration *tidecl = type->vtinfo; assert(tidecl); Declaration_codegen(tidecl); assert(getIrGlobal(tidecl)->value != NULL); LLConstant *c = isaConstant(getIrGlobal(tidecl)->value); assert(c != NULL); - if (base) + if (base) { return llvm::ConstantExpr::getBitCast(c, DtoType(Type::dtypeinfo->type)); + } return c; } @@ -1262,12 +1281,14 @@ bool hasUnalignedFields(Type *t) { if (t->ty == Tsarray) { assert(t->nextOf()->size() % t->nextOf()->alignsize() == 0); return hasUnalignedFields(t->nextOf()); - } else if (t->ty != Tstruct) + } else if (t->ty != Tstruct) { return false; + } TypeStruct *ts = static_cast(t); - if (ts->unaligned) + if (ts->unaligned) { return (ts->unaligned == 2); + } StructDeclaration *sym = ts->sym; @@ -1276,11 +1297,12 @@ bool hasUnalignedFields(Type *t) { for (unsigned i = 0; i < sym->fields.dim; i++) { VarDeclaration *f = static_cast(sym->fields.data[i]); unsigned a = f->type->alignsize() - 1; - if (((f->offset + a) & ~a) != f->offset) + if (((f->offset + a) & ~a) != f->offset) { return true; - else if (f->type->toBasetype()->ty == Tstruct && - hasUnalignedFields(f->type)) + } else if (f->type->toBasetype()->ty == Tstruct && + hasUnalignedFields(f->type)) { return true; + } } ts->unaligned = 1; @@ -1308,13 +1330,15 @@ size_t getMemberSize(Type *type) { ////////////////////////////////////////////////////////////////////////////////////////// Type *stripModifiers(Type *type, bool transitive) { - if (type->ty == Tfunction) + if (type->ty == Tfunction) { return type; + } - if (transitive) + if (transitive) { return type->unqualify(MODimmutable | MODconst | MODwild); - else + } else { return type->castMod(0); + } } ////////////////////////////////////////////////////////////////////////////////////////// @@ -1339,8 +1363,9 @@ LLValue *makeLValue(Loc &loc, DValue *value) { needsMemory = false; } - if (needsMemory) + if (needsMemory) { valuePointer = DtoAllocaDump(value, ".makelvaluetmp"); + } return valuePointer; } @@ -1356,9 +1381,10 @@ void callPostblit(Loc &loc, Expression *exp, LLValue *val) { StructDeclaration *sd = static_cast(tb)->sym; if (sd->postblit) { FuncDeclaration *fd = sd->postblit; - if (fd->storage_class & STCdisable) + if (fd->storage_class & STCdisable) { fd->toParent()->error( loc, "is not copyable because it is annotated with @disable"); + } DtoResolveFunction(fd); Expressions args; DFuncValue dfn(fd, getIrFunc(fd)->func, val); @@ -1390,10 +1416,11 @@ void printLabelName(std::ostream &target, const char *func_mangle, void AppendFunctionToLLVMGlobalCtorsDtors(llvm::Function *func, const uint32_t priority, const bool isCtor) { - if (isCtor) + if (isCtor) { llvm::appendToGlobalCtors(gIR->module, func, priority); - else + } else { llvm::appendToGlobalDtors(gIR->module, func, priority); + } } ////////////////////////////////////////////////////////////////////////////////////////// @@ -1467,7 +1494,7 @@ DValue *DtoSymbolAddress(Loc &loc, Type *type, Declaration *decl) { // _dollar else if (vd->ident == Id::dollar) { Logger::println("Id::dollar"); - LLValue *val = 0; + LLValue *val = nullptr; if (isIrVarCreated(vd) && (val = getIrValue(vd))) { // It must be length of a range return new DVarValue(type, vd, val); @@ -1483,8 +1510,9 @@ DValue *DtoSymbolAddress(Loc &loc, Type *type, Declaration *decl) { assert(getIrValue(tid)); LLType *vartype = DtoType(type); LLValue *m = getIrValue(tid); - if (m->getType() != getPtrToType(vartype)) + if (m->getType() != getPtrToType(vartype)) { m = gIR->ir->CreateBitCast(m, vartype); + } return new DImValue(type, m); } // nested variable @@ -1511,15 +1539,17 @@ DValue *DtoSymbolAddress(Loc &loc, Type *type, Declaration *decl) { return new DVarValue(type, vd, getIrValue(vd)); } else if (llvm::isa(getIrValue(vd))) { return new DImValue(type, getIrValue(vd)); - } else + } else { llvm_unreachable("Unexpected parameter value."); + } } else { Logger::println("a normal variable"); // take care of forward references of global variables const bool isGlobal = vd->isDataseg() || (vd->storage_class & STCextern); - if (isGlobal) + if (isGlobal) { DtoResolveVariable(vd); + } assert(isIrVarCreated(vd) && "Variable not resolved."); @@ -1554,8 +1584,9 @@ DValue *DtoSymbolAddress(Loc &loc, Type *type, Declaration *decl) { fatal(); } DtoResolveFunction(fdecl); - return new DFuncValue( - fdecl, fdecl->llvmInternal != LLVMva_arg ? getIrFunc(fdecl)->func : 0); + return new DFuncValue(fdecl, fdecl->llvmInternal != LLVMva_arg + ? getIrFunc(fdecl)->func + : nullptr); } if (SymbolDeclaration *sdecl = decl->isSymbolDeclaration()) { @@ -1594,9 +1625,10 @@ llvm::Constant *DtoConstSymbolAddress(Loc &loc, Declaration *decl) { error(loc, "cannot use address of non-global variable '%s' " "as constant initializer", vd->toChars()); - if (!global.gag) + if (!global.gag) { fatal(); - return NULL; + } + return nullptr; } DtoResolveVariable(vd); @@ -1639,12 +1671,13 @@ llvm::GlobalVariable *getOrCreateGlobal(Loc &loc, llvm::Module &module, : clThreadModel.getValue()) : llvm::GlobalVariable::NotThreadLocal; return new llvm::GlobalVariable(module, type, isConstant, linkage, init, name, - 0, tlsModel); + nullptr, tlsModel); } FuncDeclaration *getParentFunc(Dsymbol *sym, bool stopOnStatic) { - if (!sym) - return NULL; + if (!sym) { + return nullptr; + } // check if symbol is itself a static function/aggregate if (stopOnStatic) { @@ -1655,29 +1688,33 @@ FuncDeclaration *getParentFunc(Dsymbol *sym, bool stopOnStatic) { fd->isStatic() || (fd->isFuncLiteralDeclaration() && static_cast(fd)->tok == TOKfunction); - if (certainlyNewRoot) - return NULL; + if (certainlyNewRoot) { + return nullptr; + } } // Fun fact: AggregateDeclarations are not Declarations. else if (AggregateDeclaration *ad = sym->isAggregateDeclaration()) { - if (!ad->isNested()) - return NULL; - } - } - - for (Dsymbol *parent = sym->parent; parent; parent = parent->parent) { - if (FuncDeclaration *fd = parent->isFuncDeclaration()) - return fd; - - if (stopOnStatic) { - if (AggregateDeclaration *ad = parent->isAggregateDeclaration()) { - if (!ad->isNested()) - return NULL; + if (!ad->isNested()) { + return nullptr; } } } - return NULL; + for (Dsymbol *parent = sym->parent; parent; parent = parent->parent) { + if (FuncDeclaration *fd = parent->isFuncDeclaration()) { + return fd; + } + + if (stopOnStatic) { + if (AggregateDeclaration *ad = parent->isAggregateDeclaration()) { + if (!ad->isNested()) { + return nullptr; + } + } + } + } + + return nullptr; } LLValue *DtoIndexAggregate(LLValue *src, AggregateDeclaration *ad, @@ -1693,8 +1730,9 @@ LLValue *DtoIndexAggregate(LLValue *src, AggregateDeclaration *ad, // Cast the pointer we got to the canonical struct type the indices are // based on. LLType *st = DtoType(ad->type); - if (ad->isStructDeclaration()) + if (ad->isStructDeclaration()) { st = getPtrToType(st); + } src = DtoBitCast(src, st); // Look up field to index and any offset to apply. diff --git a/gen/llvmhelpers.h b/gen/llvmhelpers.h index 2eb6c3f46c..8051342c86 100644 --- a/gen/llvmhelpers.h +++ b/gen/llvmhelpers.h @@ -108,7 +108,7 @@ void DtoResolveVariable(VarDeclaration *var); // declaration inside a declarationexp void DtoVarDeclaration(VarDeclaration *var); DValue *DtoDeclarationExp(Dsymbol *declaration); -LLValue *DtoRawVarDeclaration(VarDeclaration *var, LLValue *addr = 0); +LLValue *DtoRawVarDeclaration(VarDeclaration *var, LLValue *addr = nullptr); // initializer helpers LLConstant *DtoConstInitializer(Loc &loc, Type *type, Initializer *init); @@ -209,7 +209,7 @@ bool DtoLowerMagicIntrinsic(IRState *p, FuncDeclaration *fndecl, CallExp *e, /// DValue *DtoCallFunction(Loc &loc, Type *resulttype, DValue *fnval, - Expressions *arguments, LLValue *retvar = 0); + Expressions *arguments, LLValue *retvar = nullptr); Type *stripModifiers(Type *type, bool transitive = false); @@ -228,8 +228,9 @@ LLConstant *toConstantArray(LLType *ct, LLArrayType *at, T *str, size_t len, for (size_t i = 0; i < len; ++i) { vals.push_back(LLConstantInt::get(ct, str[i], false)); } - if (nullterm) + if (nullterm) { vals.push_back(LLConstantInt::get(ct, 0, false)); + } return LLConstantArray::get(at, vals); } diff --git a/gen/logger.cpp b/gen/logger.cpp index bb633aed56..fb7aa67cb9 100644 --- a/gen/logger.cpp +++ b/gen/logger.cpp @@ -35,10 +35,11 @@ void Stream::writeValue(std::ostream &OS, const llvm::Value &V) { // (Only treat non-global constants like this, so that e.g. global variables // still get their initializers printed) llvm::raw_os_ostream raw(OS); - if (llvm::isa(V) && !llvm::isa(V)) + if (llvm::isa(V) && !llvm::isa(V)) { V.printAsOperand(raw, true, &gIR->module); - else + } else { V.print(raw); + } } namespace Logger { @@ -54,17 +55,20 @@ void indent() { indent_str += "* "; } } + void undent() { if (_enabled) { assert(!indent_str.empty()); indent_str.resize(indent_str.size() - 2); } } + Stream cout() { - if (_enabled) - return std::cout << indent_str; - else - return 0; + if (_enabled) { + return Stream(std::cout << indent_str); + } else { + return Stream(nullptr); + } } #if defined(_MSC_VER) diff --git a/gen/logger.h b/gen/logger.h index 3e4ef1f02c..883acdd998 100644 --- a/gen/logger.h +++ b/gen/logger.h @@ -38,9 +38,9 @@ class Stream { std::ostream *OS; public: - Stream() : OS(0) {} - Stream(std::ostream *S) : OS(S) {} - Stream(std::ostream &S) : OS(&S) {} + Stream() : OS(nullptr) {} + explicit Stream(std::ostream *S) : OS(S) {} + explicit Stream(std::ostream &S) : OS(&S) {} /* Stream operator << (std::ios_base &(*Func)(std::ios_base&)) { @@ -50,14 +50,16 @@ public: */ Stream operator<<(std::ostream &(*Func)(std::ostream &)) { - if (OS) + if (OS) { Func(*OS); + } return *this; } template Stream &operator<<(const Ty &Thing) { - if (OS) + if (OS) { Writer::write(*OS, Thing); + } return *this; } diff --git a/gen/module.cpp b/gen/module.cpp index d9be51ac39..32af4ad6af 100644 --- a/gen/module.cpp +++ b/gen/module.cpp @@ -75,32 +75,36 @@ static void check_and_add_output_file(Module *NewMod, const std::string &str) { } void Module::buildTargetFiles(bool singleObj, bool library) { - if (objfile && (!doDocComment || docfile) && (!doHdrGen || hdrfile)) + if (objfile && (!doDocComment || docfile) && (!doHdrGen || hdrfile)) { return; + } if (!objfile) { - const char *objname = library ? 0 : global.params.objname; - if (global.params.output_o) + const char *objname = library ? nullptr : global.params.objname; + if (global.params.output_o) { objfile = Module::buildFilePath(objname, global.params.objdir, global.params.targetTriple.isOSWindows() ? global.obj_ext_alt : global.obj_ext); - else if (global.params.output_bc) + } else if (global.params.output_bc) { objfile = Module::buildFilePath(objname, global.params.objdir, global.bc_ext); - else if (global.params.output_ll) + } else if (global.params.output_ll) { objfile = Module::buildFilePath(objname, global.params.objdir, global.ll_ext); - else if (global.params.output_s) + } else if (global.params.output_s) { objfile = Module::buildFilePath(objname, global.params.objdir, global.s_ext); + } } - if (doDocComment && !docfile) + if (doDocComment && !docfile) { docfile = Module::buildFilePath(global.params.docname, global.params.docdir, global.doc_ext); - if (doHdrGen && !hdrfile) + } + if (doHdrGen && !hdrfile) { hdrfile = Module::buildFilePath(global.params.hdrname, global.params.hdrdir, global.hdr_ext); + } // safety check: never allow obj, doc or hdr file to have the source file's // name @@ -127,10 +131,12 @@ void Module::buildTargetFiles(bool singleObj, bool library) { // LDC // another safety check to make sure we don't overwrite previous output files - if (!singleObj && global.params.obj) + if (!singleObj && global.params.obj) { check_and_add_output_file(this, objfile->name->str); - if (docfile) + } + if (docfile) { check_and_add_output_file(this, docfile->name->str); + } // FIXME: DMD overwrites header files. This should be done only in a DMD mode. // if (hdrfile) // check_and_add_output_file(this, hdrfile->name->str); @@ -142,10 +148,11 @@ File *Module::buildFilePath(const char *forcename, const char *path, if (forcename) { argobj = forcename; } else { - if (preservePaths) + if (preservePaths) { argobj = this->arg; - else + } else { argobj = FileName::name(this->arg); + } if (fqnNames) { char *name = md ? md->toChars() : toChars(); @@ -154,7 +161,7 @@ File *Module::buildFilePath(const char *forcename, const char *path, // add ext, otherwise forceExt will make nested.module into nested.bc size_t len = strlen(argobj); size_t extlen = strlen(ext); - char *s = (char *)alloca(len + 1 + extlen + 1); + char *s = reinterpret_cast(alloca(len + 1 + extlen + 1)); memcpy(s, argobj, len); s[len] = '.'; memcpy(s + len + 1, ext, extlen + 1); @@ -163,8 +170,9 @@ File *Module::buildFilePath(const char *forcename, const char *path, } } - if (!FileName::absolute(argobj)) + if (!FileName::absolute(argobj)) { argobj = FileName::combine(path, argobj); + } FileName::ensurePathExists(FileName::path(argobj)); @@ -177,11 +185,13 @@ static llvm::Function *build_module_function( const std::string &name, const std::list &funcs, const std::list &gates = std::list()) { if (gates.empty()) { - if (funcs.empty()) - return NULL; + if (funcs.empty()) { + return nullptr; + } - if (funcs.size() == 1) + if (funcs.size() == 1) { return getIrFunc(funcs.front())->func; + } } // build ctor type @@ -319,10 +329,11 @@ static LLFunction *build_module_reference_and_ctor(const char *moduleMangle, // make sure _Dmodule_ref is declared LLConstant *mref = gIR->module.getNamedGlobal("_Dmodule_ref"); LLType *modulerefPtrTy = getPtrToType(modulerefTy); - if (!mref) + if (!mref) { mref = new LLGlobalVariable(gIR->module, modulerefPtrTy, false, - LLGlobalValue::ExternalLinkage, NULL, + LLGlobalValue::ExternalLinkage, nullptr, "_Dmodule_ref"); + } mref = DtoBitCast(mref, getPtrToType(modulerefPtrTy)); // make the function insert this moduleinfo as the beginning of the @@ -428,7 +439,7 @@ static void build_module_ref(std::string moduleMangle, std::string thismrefname = "_D"; thismrefname += moduleMangle; thismrefname += "11__moduleRefZ"; - llvm::GlobalVariable *thismref = new llvm::GlobalVariable( + auto thismref = new llvm::GlobalVariable( gIR->module, moduleInfoPtrTy, false, // FIXME: mRelocModel != llvm::Reloc::PIC_ llvm::GlobalValue::LinkOnceODRLinkage, @@ -445,7 +456,7 @@ static void build_dso_registry_calls(std::string moduleMangle, // Order is important here: We must create the symbols in the // bracketing sections right before/after the ModuleInfo reference // so that they end up in the correct order in the object file. - llvm::GlobalVariable *minfoBeg = + auto minfoBeg = new llvm::GlobalVariable(gIR->module, moduleInfoPtrTy, false, // FIXME: mRelocModel != llvm::Reloc::PIC_ llvm::GlobalValue::LinkOnceODRLinkage, @@ -456,7 +467,7 @@ static void build_dso_registry_calls(std::string moduleMangle, std::string thismrefname = "_D"; thismrefname += moduleMangle; thismrefname += "11__moduleRefZ"; - llvm::GlobalVariable *thismref = new llvm::GlobalVariable( + auto thismref = new llvm::GlobalVariable( gIR->module, moduleInfoPtrTy, false, // FIXME: mRelocModel != llvm::Reloc::PIC_ llvm::GlobalValue::LinkOnceODRLinkage, @@ -464,7 +475,7 @@ static void build_dso_registry_calls(std::string moduleMangle, thismref->setSection(".minfo"); gIR->usedArray.push_back(thismref); - llvm::GlobalVariable *minfoEnd = + auto minfoEnd = new llvm::GlobalVariable(gIR->module, moduleInfoPtrTy, false, // FIXME: mRelocModel != llvm::Reloc::PIC_ llvm::GlobalValue::LinkOnceODRLinkage, @@ -475,7 +486,7 @@ static void build_dso_registry_calls(std::string moduleMangle, // Build the ctor to invoke _d_dso_registry. // This is the DSO slot for use by the druntime implementation. - llvm::GlobalVariable *dsoSlot = + auto dsoSlot = new llvm::GlobalVariable(gIR->module, getVoidPtrType(), false, llvm::GlobalValue::LinkOnceODRLinkage, getNullPtr(getVoidPtrType()), "ldc.dso_slot"); @@ -510,7 +521,7 @@ static void build_dso_registry_calls(std::string moduleMangle, // problems. This would mean that it is no longer safe to link D objects // directly using e.g. "g++ dcode.o cppcode.o", though. - llvm::GlobalVariable *dsoInitialized = new llvm::GlobalVariable( + auto dsoInitialized = new llvm::GlobalVariable( gIR->module, llvm::Type::getInt8Ty(gIR->context()), false, llvm::GlobalValue::LinkOnceODRLinkage, llvm::ConstantInt::get(llvm::Type::getInt8Ty(gIR->context()), 0), @@ -546,18 +557,20 @@ static void build_dso_registry_calls(std::string moduleMangle, } static void build_llvm_used_array(IRState *p) { - if (p->usedArray.empty()) + if (p->usedArray.empty()) { return; + } std::vector usedVoidPtrs; usedVoidPtrs.reserve(p->usedArray.size()); - for (auto constant : p->usedArray) + for (auto constant : p->usedArray) { usedVoidPtrs.push_back(DtoBitCast(constant, getVoidPtrType())); + } llvm::ArrayType *arrayType = llvm::ArrayType::get(getVoidPtrType(), usedVoidPtrs.size()); - llvm::GlobalVariable *llvmUsed = new llvm::GlobalVariable( + auto llvmUsed = new llvm::GlobalVariable( p->module, arrayType, false, llvm::GlobalValue::AppendingLinkage, llvm::ConstantArray::get(arrayType, usedVoidPtrs), "llvm.used"); llvmUsed->setSection("llvm.metadata"); @@ -572,7 +585,7 @@ static void addCoverageAnalysis(Module *m) { } // size_t[# source lines / # bits in sizeTy] _d_cover_valid - LLValue *d_cover_valid_slice = NULL; + LLValue *d_cover_valid_slice = nullptr; { unsigned Dsizet_bits = gDataLayout->getTypeSizeInBits(DtoSize_t()); size_t array_size = (m->numlines + (Dsizet_bits - 1)) / Dsizet_bits; // ceil @@ -609,7 +622,7 @@ static void addCoverageAnalysis(Module *m) { } // uint[# source lines] _d_cover_data - LLValue *d_cover_data_slice = NULL; + LLValue *d_cover_data_slice = nullptr; { IF_LOG Logger::println("Build private variable: uint[%d] _d_cover_data", m->numlines); @@ -634,7 +647,7 @@ static void addCoverageAnalysis(Module *m) { // Create "static constructor" that calls _d_cover_register2(string filename, // size_t[] valid, uint[] data, ubyte minPercent) // Build ctor name - LLFunction *ctor = NULL; + LLFunction *ctor = nullptr; std::string ctorname = "_D"; ctorname += mangle(m); ctorname += "12_coverageanalysisCtor1FZv"; @@ -677,7 +690,7 @@ static void addCoverageAnalysis(Module *m) { IF_LOG Logger::println("Add %s to module's shared static constructor list", ctorname.c_str()); FuncDeclaration *fd = - FuncDeclaration::genCfunc(NULL, Type::tvoid, ctorname.c_str()); + FuncDeclaration::genCfunc(nullptr, Type::tvoid, ctorname.c_str()); fd->linkage = LINKd; IrFunction *irfunc = getIrFunc(fd, true); irfunc->func = ctor; @@ -725,8 +738,9 @@ void codegenModule(IRState *irs, Module *m, bool emitFullModuleInfo) { Declaration_codegen(dsym); } - if (global.errors) + if (global.errors) { fatal(); + } // Skip emission of all the additional module metadata if requested by the // user. @@ -741,8 +755,8 @@ void codegenModule(IRState *irs, Module *m, bool emitFullModuleInfo) { addCoverageAnalysisInitializer(m); } - gIR = 0; - irs->dmodule = 0; + gIR = nullptr; + irs->dmodule = nullptr; } // Put out instance of ModuleInfo for this Module @@ -771,12 +785,13 @@ static void genModuleInfo(Module *m, bool emitFullModuleInfo) { // importedModules[] std::vector importInits; - LLConstant *importedModules = 0; - llvm::ArrayType *importedModulesTy = 0; + LLConstant *importedModules = nullptr; + llvm::ArrayType *importedModulesTy = nullptr; for (size_t i = 0; i < m->aimports.dim; i++) { Module *mod = static_cast(m->aimports.data[i]); - if (!mod->needModuleInfo() || mod == m) + if (!mod->needModuleInfo() || mod == m) { continue; + } importInits.push_back( DtoBitCast(getIrModule(mod)->moduleInfoSymbol(), moduleInfoPtrTy)); @@ -789,8 +804,8 @@ static void genModuleInfo(Module *m, bool emitFullModuleInfo) { } // localClasses[] - LLConstant *localClasses = 0; - llvm::ArrayType *localClassesTy = 0; + LLConstant *localClasses = nullptr; + llvm::ArrayType *localClassesTy = nullptr; ClassDeclarations aclasses; // printf("members->dim = %d\n", members->dim); for (size_t i = 0; i < m->members->dim; i++) { @@ -843,49 +858,62 @@ static void genModuleInfo(Module *m, bool emitFullModuleInfo) { llvm::Function *fdtor = build_module_dtor(m); unsigned flags = MInew; - if (fctor) + if (fctor) { flags |= MItlsctor; - if (fdtor) + } + if (fdtor) { flags |= MItlsdtor; - if (fsharedctor) + } + if (fsharedctor) { flags |= MIctor; - if (fshareddtor) + } + if (fshareddtor) { flags |= MIdtor; + } #if 0 if (fgetmembers) flags |= MIxgetMembers; if (fictor) flags |= MIictor; #endif - if (funittest) + if (funittest) { flags |= MIunitTest; - if (importedModules) + } + if (importedModules) { flags |= MIimportedModules; - if (localClasses) + } + if (localClasses) { flags |= MIlocalClasses; + } - if (!m->needmoduleinfo) + if (!m->needmoduleinfo) { flags |= MIstandalone; + } b.push_uint(flags); // flags b.push_uint(0); // index - if (fctor) + if (fctor) { b.push(fctor); - if (fdtor) + } + if (fdtor) { b.push(fdtor); - if (fsharedctor) + } + if (fsharedctor) { b.push(fsharedctor); - if (fshareddtor) + } + if (fshareddtor) { b.push(fshareddtor); + } #if 0 if (fgetmembers) b.push(fgetmembers); if (fictor) b.push(fictor); #endif - if (funittest) + if (funittest) { b.push(funittest); + } if (importedModules) { b.push_size(importInits.size()); b.push(importedModules); @@ -908,10 +936,11 @@ static void genModuleInfo(Module *m, bool emitFullModuleInfo) { moduleInfoSym->setLinkage(llvm::GlobalValue::ExternalLinkage); if (global.params.isLinux) { - if (emitFullModuleInfo) + if (emitFullModuleInfo) { build_dso_registry_calls(mangle(m), moduleInfoSym); - else + } else { build_module_ref(mangle(m), moduleInfoSym); + } } else { // build the modulereference and ctor for registering it LLFunction *mictor = diff --git a/gen/naked.cpp b/gen/naked.cpp index ac0b672821..f079cfe713 100644 --- a/gen/naked.cpp +++ b/gen/naked.cpp @@ -31,7 +31,7 @@ class ToNakedIRVisitor : public Visitor { IRState *irs; public: - ToNakedIRVisitor(IRState *irs) : irs(irs) {} + explicit ToNakedIRVisitor(IRState *irs) : irs(irs) {} ////////////////////////////////////////////////////////////////////////// @@ -57,10 +57,13 @@ public: stmt->loc.toChars()); LOG_SCOPE; - if (stmt->statements) - for (auto s : *stmt->statements) - if (s) + if (stmt->statements) { + for (auto s : *stmt->statements) { + if (s) { s->accept(this); + } + } + } } ////////////////////////////////////////////////////////////////////////// @@ -73,8 +76,9 @@ public: // This happens only if there is a ; at the end: // asm { naked; ... }; // Is this a legal AST? - if (!stmt->exp) + if (!stmt->exp) { return; + } // only expstmt supported in declarations if (!stmt->exp || stmt->exp->op != TOKdeclaration) { @@ -120,8 +124,9 @@ public: stmt->ident->toChars()); irs->nakedAsm << ":"; - if (stmt->statement) + if (stmt->statement) { stmt->statement->accept(this); + } } }; @@ -187,8 +192,9 @@ void DtoDefineNakedFunction(FuncDeclaration *fd) { if (DtoIsTemplateInstance(fd)) { asmstr << "\t.section\t.text$" << fullMangle << ",\"xr\"" << std::endl; asmstr << "\t.linkonce\tdiscard" << std::endl; - } else + } else { asmstr << "\t.text" << std::endl; + } asmstr << "\t.globl\t" << fullMangle << std::endl; asmstr << "\t.align\t16, 0x90" << std::endl; asmstr << fullMangle << ":" << std::endl; @@ -212,8 +218,9 @@ void DtoDefineNakedFunction(FuncDeclaration *fd) { // We could have generated new errors in toNakedIR(), but we are in codegen // already so we have to abort here. - if (global.errors) + if (global.errors) { fatal(); + } // emit size after body // llvm does this on linux, but not on osx or Win @@ -235,7 +242,7 @@ void emitABIReturnAsmStmt(IRAsmBlock *asmblock, Loc &loc, IF_LOG Logger::println("emitABIReturnAsmStmt(%s)", mangleExact(fdecl)); LOG_SCOPE; - IRAsmStmt *as = new IRAsmStmt; + auto as = new IRAsmStmt; LLType *llretTy = DtoType(fdecl->type->nextOf()); asmblock->retty = llretTy; diff --git a/gen/nested.cpp b/gen/nested.cpp index 0254fac847..1febccb975 100644 --- a/gen/nested.cpp +++ b/gen/nested.cpp @@ -35,9 +35,10 @@ static void storeVariable(VarDeclaration *vd, LLValue *dst) { LLValue *mem = DtoGcMalloc(vd->loc, DtoType(vd->type), ".gc_mem"); DtoAggrCopy(mem, value); DtoAlignedStore(mem, dst); - } else + } else { // Store the address into the frame DtoAlignedStore(value, dst); + } } static unsigned getVthisIdx(AggregateDeclaration *ad) { @@ -79,7 +80,7 @@ DValue *DtoNestedVariable(Loc &loc, Type *astype, VarDeclaration *vd, return new DVarValue(astype, vd, val); } - LLValue *dwarfValue = 0; + LLValue *dwarfValue = nullptr; #if LDC_LLVM_VER >= 306 std::vector dwarfAddr; #else @@ -87,7 +88,7 @@ DValue *DtoNestedVariable(Loc &loc, Type *astype, VarDeclaration *vd, #endif // get the nested context - LLValue *ctx = 0; + LLValue *ctx = nullptr; if (irfunc->nestedVar) { // If this function has its own nested context struct, always load it. ctx = irfunc->nestedVar; @@ -97,16 +98,18 @@ DValue *DtoNestedVariable(Loc &loc, Type *astype, VarDeclaration *vd, // context, load the vthis member. AggregateDeclaration *cd = irfunc->decl->isMember2(); LLValue *val = irfunc->thisArg; - if (cd->isClassDeclaration()) + if (cd->isClassDeclaration()) { val = DtoLoad(val); + } ctx = DtoLoad(DtoGEPi(val, 0, getVthisIdx(cd), ".vthis")); } else { // Otherwise, this is a simple nested function, load from the context // argument. ctx = DtoLoad(irfunc->nestArg); dwarfValue = irfunc->nestArg; - if (global.params.symdebug) + if (global.params.symdebug) { gIR->DBuilder.OpDeref(dwarfAddr); + } } assert(ctx); @@ -153,8 +156,9 @@ DValue *DtoNestedVariable(Loc &loc, Type *astype, VarDeclaration *vd, int idx = getIrLocal(vd)->nestedIndex; assert(idx != -1 && "Nested context not yet resolved for variable."); - if (dwarfValue && global.params.symdebug) + if (dwarfValue && global.params.symdebug) { gIR->DBuilder.OpOffset(dwarfAddr, val, idx); + } val = DtoGEPi(val, 0, idx, vd->toChars()); IF_LOG { @@ -171,8 +175,9 @@ DValue *DtoNestedVariable(Loc &loc, Type *astype, VarDeclaration *vd, } } - if (dwarfValue && global.params.symdebug) - gIR->DBuilder.EmitLocalVariable(dwarfValue, vd, 0, false, dwarfAddr); + if (dwarfValue && global.params.symdebug) { + gIR->DBuilder.EmitLocalVariable(dwarfValue, vd, nullptr, false, dwarfAddr); + } return new DVarValue(astype, vd, val); } @@ -267,7 +272,7 @@ LLValue *DtoNestedContext(Loc &loc, Dsymbol *sym) { return llvm::ConstantPointerNull::get(getVoidPtrType()); } - FuncDeclaration *frameToPass = 0; + FuncDeclaration *frameToPass = nullptr; if (AggregateDeclaration *ad = sym->isAggregateDeclaration()) { // If sym is a nested struct or a nested class, pass the frame // of the function where sym is declared. @@ -327,14 +332,16 @@ static void DtoCreateNestedContextType(FuncDeclaration *fd) { IrFunction &irFunc = *getIrFunc(fd); - if (irFunc.nestedContextCreated) + if (irFunc.nestedContextCreated) { return; + } irFunc.nestedContextCreated = true; FuncDeclaration *parentFunc = getParentFunc(fd, true); // Make sure the parent has already been analyzed. - if (parentFunc) + if (parentFunc) { DtoCreateNestedContextType(parentFunc); + } // construct nested variables array if (fd->closureVars.dim > 0) { @@ -342,14 +349,15 @@ static void DtoCreateNestedContextType(FuncDeclaration *fd) { // start with adding all enclosing parent frames until a static parent is // reached - LLStructType *innerFrameType = NULL; + LLStructType *innerFrameType = nullptr; unsigned depth = 0; if (parentFunc) { IrFunction &parentIrFunc = *getIrFunc(parentFunc); innerFrameType = parentIrFunc.frameType; - if (innerFrameType) + if (innerFrameType) { depth = parentIrFunc.depth + 1; + } } irFunc.depth = depth; @@ -363,8 +371,9 @@ static void DtoCreateNestedContextType(FuncDeclaration *fd) { assert(innerFrameType); unsigned ptrSize = gDataLayout->getPointerSize(); // Add frame pointer types for all but last frame - for (unsigned i = 0; i < (depth - 1); ++i) + for (unsigned i = 0; i < (depth - 1); ++i) { builder.addType(innerFrameType->getElementType(i), ptrSize); + } // Add frame pointer type for last frame builder.addType(LLPointerType::getUnqual(innerFrameType), ptrSize); } @@ -374,14 +383,15 @@ static void DtoCreateNestedContextType(FuncDeclaration *fd) { // TODO: optimize ordering for minimal space usage? for (auto vd : fd->closureVars) { unsigned alignment = DtoAlignment(vd); - if (alignment > 1) + if (alignment > 1) { builder.alignCurrentOffset(alignment); + } IrLocal &irLocal = *getIrLocal(vd, true); irLocal.nestedIndex = builder.currentFieldIndex(); irLocal.nestedDepth = depth; - LLType *t = NULL; + LLType *t = nullptr; if (vd->isParameter() && getIrParameter(vd)->arg) { // Parameters that are part of the LLVM signature will have // storage associated with them (to handle byref etc.), so @@ -394,16 +404,19 @@ static void DtoCreateNestedContextType(FuncDeclaration *fd) { const bool isVthisPtr = irparam->isVthis && !byref; if (!(refout || (byref && !lazy)) || isVthisPtr) { // This will be copied to the nesting frame. - if (lazy) + if (lazy) { t = irparam->value->getType()->getContainedType(0); - else + } else { t = DtoMemType(vd->type); - } else + } + } else { t = irparam->value->getType(); - } else if (isSpecialRefVar(vd)) + } + } else if (isSpecialRefVar(vd)) { t = DtoType(vd->type->pointerTo()); - else + } else { t = DtoMemType(vd->type); + } builder.addType(t, getTypeAllocSize(t)); @@ -445,7 +458,7 @@ void DtoCreateNestedContext(FuncDeclaration *fd) { unsigned depth = irfunction->depth; LLStructType *frameType = irfunction->frameType; // Create frame for current function and append to frames list - LLValue *frame = 0; + LLValue *frame = nullptr; bool needsClosure = fd->needsClosure(); if (needsClosure) { // FIXME: alignment ? @@ -467,10 +480,11 @@ void DtoCreateNestedContext(FuncDeclaration *fd) { assert(cd); assert(cd->vthis); Logger::println("Indexing to 'this'"); - if (cd->isStructDeclaration()) + if (cd->isStructDeclaration()) { src = DtoExtractValue(thisval, getVthisIdx(cd), ".vthis"); - else + } else { src = DtoLoad(DtoGEPi(thisval, 0, getVthisIdx(cd), ".vthis")); + } } else { src = DtoLoad(src); } @@ -529,7 +543,7 @@ void DtoCreateNestedContext(FuncDeclaration *fd) { LLSmallVector addr; #endif gIR->DBuilder.OpOffset(addr, frameType, irLocal->nestedIndex); - gIR->DBuilder.EmitLocalVariable(gep, vd, 0, false, addr); + gIR->DBuilder.EmitLocalVariable(gep, vd, nullptr, false, addr); } } } diff --git a/gen/optimizer.cpp b/gen/optimizer.cpp index a470c443a8..036883164f 100644 --- a/gen/optimizer.cpp +++ b/gen/optimizer.cpp @@ -144,18 +144,20 @@ llvm::CodeGenOpt::Level codeGenOptLevel() { // Use same appoach as clang (see lib/CodeGen/BackendUtil.cpp) llvm::CodeGenOpt::Level codeGenOptLevel = llvm::CodeGenOpt::Default; // Debug info doesn't work properly with CodeGenOpt <> None - if (global.params.symdebug || !opt) + if (global.params.symdebug || !opt) { codeGenOptLevel = llvm::CodeGenOpt::None; - else if (opt >= 3) + } else if (opt >= 3) { codeGenOptLevel = llvm::CodeGenOpt::Aggressive; + } return codeGenOptLevel; } static inline void addPass(PassManagerBase &pm, Pass *pass) { pm.add(pass); - if (verifyEach) + if (verifyEach) { pm.add(createVerifierPass()); + } } static void addStripExternalsPass(const PassManagerBuilder &builder, @@ -168,14 +170,16 @@ static void addStripExternalsPass(const PassManagerBuilder &builder, static void addSimplifyDRuntimeCallsPass(const PassManagerBuilder &builder, PassManagerBase &pm) { - if (builder.OptLevel >= 2 && builder.SizeLevel == 0) + if (builder.OptLevel >= 2 && builder.SizeLevel == 0) { addPass(pm, createSimplifyDRuntimeCalls()); + } } static void addGarbageCollect2StackPass(const PassManagerBuilder &builder, PassManagerBase &pm) { - if (builder.OptLevel >= 2 && builder.SizeLevel == 0) + if (builder.OptLevel >= 2 && builder.SizeLevel == 0) { addPass(pm, createGarbageCollect2Stack()); + } } static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, @@ -229,12 +233,14 @@ static void addOptimizationPasses(PassManagerBase &mpm, if (willInline()) { unsigned threshold = 225; - if (sizeLevel == 1) // -Os + if (sizeLevel == 1) { // -Os threshold = 75; - else if (sizeLevel == 2) // -Oz + } else if (sizeLevel == 2) { // -Oz threshold = 25; - if (optLevel > 2) + } + if (optLevel > 2) { threshold = 275; + } builder.Inliner = createFunctionInliningPass(threshold); } else { builder.Inliner = createAlwaysInlinerPass(); @@ -247,11 +253,12 @@ static void addOptimizationPasses(PassManagerBase &mpm, : optLevel == 0; // This is final, unless there is a #pragma vectorize enable - if (disableLoopVectorization) + if (disableLoopVectorization) { builder.LoopVectorize = false; - // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize) - else if (!builder.LoopVectorize) + // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize) + } else if (!builder.LoopVectorize) { builder.LoopVectorize = optLevel > 1 && sizeLevel < 2; + } // When #pragma vectorize is on for SLP, do the same as above builder.SLPVectorize = @@ -279,13 +286,15 @@ static void addOptimizationPasses(PassManagerBase &mpm, } if (!disableLangSpecificPasses) { - if (!disableSimplifyDruntimeCalls) + if (!disableSimplifyDruntimeCalls) { builder.addExtension(PassManagerBuilder::EP_LoopOptimizerEnd, addSimplifyDRuntimeCallsPass); + } - if (!disableGCToStack) + if (!disableGCToStack) { builder.addExtension(PassManagerBuilder::EP_LoopOptimizerEnd, addGarbageCollect2StackPass); + } } // EP_OptimizerLast does not exist in LLVM 3.0, add it manually below. @@ -322,8 +331,9 @@ bool ldc_optimize_module(llvm::Module *M) { TargetLibraryInfo *tli = new TargetLibraryInfo(Triple(M->getTargetTriple())); // The -disable-simplify-libcalls flag actually disables all builtin optzns. - if (disableSimplifyLibCalls) + if (disableSimplifyLibCalls) { tli->disableAllFunctions(); + } mpm.add(tli); #endif @@ -372,8 +382,9 @@ bool ldc_optimize_module(llvm::Module *M) { // If the -strip-debug command line option was specified, add it before // anything else. - if (stripDebug) + if (stripDebug) { mpm.add(createStripSymbolsPass(true)); + } bool defaultsAdded = false; // Create a new optimization pass for each one specified on the command line @@ -385,15 +396,16 @@ bool ldc_optimize_module(llvm::Module *M) { } const PassInfo *passInf = passList[i]; - Pass *pass = 0; - if (passInf->getNormalCtor()) + Pass *pass = nullptr; + if (passInf->getNormalCtor()) { pass = passInf->getNormalCtor()(); - else { + } else { const char *arg = passInf->getPassArgument(); // may return null - if (arg) + if (arg) { error(Loc(), "Can't create pass '-%s' (%s)", arg, pass->getPassName()); - else + } else { error(Loc(), "Can't create pass (%s)", pass->getPassName()); + } llvm_unreachable("pass creation failed"); } if (pass) { @@ -402,13 +414,15 @@ bool ldc_optimize_module(llvm::Module *M) { } // Add the default passes for the specified optimization level. - if (!defaultsAdded) + if (!defaultsAdded) { addOptimizationPasses(mpm, fpm, optLevel(), sizeLevel()); + } // Run per-function passes. fpm.doInitialization(); - for (auto &F : *M) + for (auto &F : *M) { fpm.run(F); + } fpm.doFinalization(); // Run per-module passes. diff --git a/gen/passes/GarbageCollect2Stack.cpp b/gen/passes/GarbageCollect2Stack.cpp index 4a8d051d39..e6f0bb32ca 100644 --- a/gen/passes/GarbageCollect2Stack.cpp +++ b/gen/passes/GarbageCollect2Stack.cpp @@ -76,9 +76,10 @@ void EmitMemSet(IRBuilder<> &B, Value *Dst, Value *Val, Value *Len, CallSite CS = B.CreateMemSet(Dst, Val, Len, 1 /*Align*/, false /*isVolatile*/); - if (A.CGNode) + if (A.CGNode) { A.CGNode->addCalledFunction( CS, A.CG->getOrInsertFunction(CS.getCalledFunction())); + } } static void EmitMemZero(IRBuilder<> &B, Value *Dst, Value *Len, @@ -118,8 +119,8 @@ public: return new AllocaInst(Ty, ".nongc_mem", Begin); // FIXME: align? } - FunctionInfo(ReturnType::Type returnType) : ReturnType(returnType) {} - virtual ~FunctionInfo() {} + explicit FunctionInfo(ReturnType::Type returnType) : ReturnType(returnType) {} + virtual ~FunctionInfo() = default; }; static bool isKnownLessThan(Value *Val, uint64_t Limit, const Analysis &A) { @@ -129,8 +130,9 @@ static bool isKnownLessThan(Value *Val, uint64_t Limit, const Analysis &A) { BitsLimit = std::min(BitsLimit, 32U); const IntegerType *SizeType = dyn_cast(Val->getType()); - if (!SizeType) + if (!SizeType) { return false; + } unsigned Bits = SizeType->getBitWidth(); if (Bits > BitsLimit) { @@ -143,8 +145,9 @@ static bool isKnownLessThan(Value *Val, uint64_t Limit, const Analysis &A) { computeKnownBits(Val, KnownZero, KnownOne, &A.DL); #endif - if ((KnownZero & Mask) != Mask) + if ((KnownZero & Mask) != Mask) { return false; + } } return true; @@ -157,11 +160,12 @@ public: TypeInfoFI(ReturnType::Type returnType, unsigned tiArgNr) : FunctionInfo(returnType), TypeInfoArgNr(tiArgNr) {} - virtual bool analyze(CallSite CS, const Analysis &A) { + bool analyze(CallSite CS, const Analysis &A) override { Value *TypeInfo = CS.getArgument(TypeInfoArgNr); Ty = A.getTypeFor(TypeInfo); - if (!Ty) + if (!Ty) { return false; + } return A.DL.getTypeAllocSize(Ty) < SizeLimit; } }; @@ -177,9 +181,10 @@ public: : TypeInfoFI(returnType, tiArgNr), ArrSizeArgNr(arrSizeArgNr), Initialized(initialized) {} - virtual bool analyze(CallSite CS, const Analysis &A) { - if (!TypeInfoFI::analyze(CS, A)) + bool analyze(CallSite CS, const Analysis &A) override { + if (!TypeInfoFI::analyze(CS, A)) { return false; + } arrSize = CS.getArgument(ArrSizeArgNr); @@ -197,14 +202,15 @@ public: // useful for experimenting. if (SizeLimit > 0) { uint64_t ElemSize = A.DL.getTypeAllocSize(Ty); - if (!isKnownLessThan(arrSize, SizeLimit / ElemSize, A)) + if (!isKnownLessThan(arrSize, SizeLimit / ElemSize, A)) { return false; + } } return true; } - virtual Value *promote(CallSite CS, IRBuilder<> &B, const Analysis &A) { + Value *promote(CallSite CS, IRBuilder<> &B, const Analysis &A) override { IRBuilder<> Builder = B; // If the allocation is of constant size it's best to put it in the // entry block, so do so if we're not already there. @@ -213,8 +219,9 @@ public: // While we're at it, update statistics too. if (isa(arrSize)) { BasicBlock &Entry = CS.getCaller()->getEntryBlock(); - if (Builder.GetInsertBlock() != &Entry) + if (Builder.GetInsertBlock() != &Entry) { Builder.SetInsertPoint(&Entry, Entry.begin()); + } NumGcToStack++; } else { NumToDynSize++; @@ -251,24 +258,28 @@ public: // FunctionInfo for _d_newclass class AllocClassFI : public FunctionInfo { public: - virtual bool analyze(CallSite CS, const Analysis &A) { - if (CS.arg_size() != 1) + bool analyze(CallSite CS, const Analysis &A) override { + if (CS.arg_size() != 1) { return false; + } Value *arg = CS.getArgument(0)->stripPointerCasts(); GlobalVariable *ClassInfo = dyn_cast(arg); - if (!ClassInfo) + if (!ClassInfo) { return false; + } std::string metaname = CD_PREFIX; metaname += ClassInfo->getName(); NamedMDNode *meta = A.M.getNamedMetadata(metaname); - if (!meta) + if (!meta) { return false; + } MDNode *node = static_cast(meta->getOperand(0)); - if (!node || node->getNumOperands() != CD_NumFields) + if (!node || node->getNumOperands() != CD_NumFields) { return false; + } // Inserting destructor calls is not implemented yet, so classes // with destructors are ignored for now. @@ -288,12 +299,14 @@ public: Constant *hasCustomDelete = dyn_cast(node->getOperand(CD_CustomDelete)); #endif - if (hasDestructor == NULL || hasCustomDelete == NULL) + if (hasDestructor == nullptr || hasCustomDelete == nullptr) { return false; + } if (ConstantExpr::getOr(hasDestructor, hasCustomDelete) != - ConstantInt::getFalse(A.M.getContext())) + ConstantInt::getFalse(A.M.getContext())) { return false; + } #if LDC_LLVM_VER >= 306 Ty = mdconst::dyn_extract(node->getOperand(CD_BodyType)) @@ -316,9 +329,10 @@ class UntypedMemoryFI : public FunctionInfo { Value *SizeArg; public: - virtual bool analyze(CallSite CS, const Analysis &A) { - if (CS.arg_size() < SizeArgNr + 1) + bool analyze(CallSite CS, const Analysis &A) override { + if (CS.arg_size() < SizeArgNr + 1) { return false; + } SizeArg = CS.getArgument(SizeArgNr); @@ -328,8 +342,9 @@ public: // "range" (set bits) inference algorithm is rather limited, this // is useful for experimenting. if (SizeLimit > 0) { - if (!isKnownLessThan(SizeArg, SizeLimit, A)) + if (!isKnownLessThan(SizeArg, SizeLimit, A)) { return false; + } } // Should be i8. @@ -337,7 +352,7 @@ public: return true; } - virtual Value *promote(CallSite CS, IRBuilder<> &B, const Analysis &A) { + Value *promote(CallSite CS, IRBuilder<> &B, const Analysis &A) override { IRBuilder<> Builder = B; // If the allocation is of constant size it's best to put it in the // entry block, so do so if we're not already there. @@ -346,8 +361,9 @@ public: // While we're at it, update statistics too. if (isa(SizeArg)) { BasicBlock &Entry = CS.getCaller()->getEntryBlock(); - if (Builder.GetInsertBlock() != &Entry) + if (Builder.GetInsertBlock() != &Entry) { Builder.SetInsertPoint(&Entry, Entry.begin()); + } NumGcToStack++; } else { NumToDynSize++; @@ -361,7 +377,7 @@ public: return Builder.CreateBitCast(alloca, CS.getType()); } - UntypedMemoryFI(unsigned sizeArgNr) + explicit UntypedMemoryFI(unsigned sizeArgNr) : FunctionInfo(ReturnType::Pointer), SizeArgNr(sizeArgNr) {} }; } @@ -387,14 +403,14 @@ public: static char ID; // Pass identification GarbageCollect2Stack(); - bool doInitialization(Module &M) { + bool doInitialization(Module &M) override { this->M = &M; return false; } - bool runOnFunction(Function &F); + bool runOnFunction(Function &F) override; - virtual void getAnalysisUsage(AnalysisUsage &AU) const { + void getAnalysisUsage(AnalysisUsage &AU) const override { #if LDC_LLVM_VER < 307 AU.addRequired(); #endif @@ -436,8 +452,9 @@ static void RemoveCall(CallSite CS, const Analysis &A) { } // Remove the runtime call. - if (A.CGNode) + if (A.CGNode) { A.CGNode->removeCallEdgeFor(CS); + } CS->eraseFromParent(); } @@ -464,9 +481,9 @@ bool GarbageCollect2Stack::runOnFunction(Function &F) { const DataLayout &DL = DLP->getDataLayout(); DominatorTree &DT = getAnalysis().getDomTree(); CallGraphWrapperPass *CGPass = getAnalysisIfAvailable(); - CallGraph *CG = CGPass ? &CGPass->getCallGraph() : 0; + CallGraph *CG = CGPass ? &CGPass->getCallGraph() : nullptr; #endif - CallGraphNode *CGNode = CG ? (*CG)[&F] : NULL; + CallGraphNode *CGNode = CG ? (*CG)[&F] : nullptr; Analysis A = {DL, *M, CG, CGNode}; @@ -480,19 +497,22 @@ bool GarbageCollect2Stack::runOnFunction(Function &F) { // Ignore non-calls. Instruction *Inst = I++; CallSite CS(Inst); - if (!CS.getInstruction()) + if (!CS.getInstruction()) { continue; + } // Ignore indirect calls and calls to non-external functions. Function *Callee = CS.getCalledFunction(); - if (Callee == 0 || !Callee->isDeclaration() || - !Callee->hasExternalLinkage()) + if (Callee == nullptr || !Callee->isDeclaration() || + !Callee->hasExternalLinkage()) { continue; + } // Ignore unknown calls. auto OMI = KnownFunctions.find(Callee->getName()); - if (OMI == KnownFunctions.end()) + if (OMI == KnownFunctions.end()) { continue; + } FunctionInfo *info = OMI->getValue(); @@ -505,16 +525,19 @@ bool GarbageCollect2Stack::runOnFunction(Function &F) { DEBUG(errs() << "GarbageCollect2Stack inspecting: " << *Inst); - if (!info->analyze(CS, A)) + if (!info->analyze(CS, A)) { continue; + } SmallVector RemoveTailCallInsts; if (info->ReturnType == ReturnType::Array) { - if (!isSafeToStackAllocateArray(Inst, DT, RemoveTailCallInsts)) + if (!isSafeToStackAllocateArray(Inst, DT, RemoveTailCallInsts)) { continue; + } } else { - if (!isSafeToStackAllocate(Inst, Inst, DT, RemoveTailCallInsts)) + if (!isSafeToStackAllocate(Inst, Inst, DT, RemoveTailCallInsts)) { continue; + } } // Let's alloca this! @@ -522,8 +545,9 @@ bool GarbageCollect2Stack::runOnFunction(Function &F) { // First demote tail calls which use the value so there IR is never // in an invalid state. - for (auto i : RemoveTailCallInsts) + for (auto i : RemoveTailCallInsts) { i->setTailCall(false); + } IRBuilder<> Builder(&BB, Inst); Value *newVal = info->promote(CS, Builder, A); @@ -532,8 +556,9 @@ bool GarbageCollect2Stack::runOnFunction(Function &F) { // Make sure the type is the same as it was before, and replace all // uses of the runtime call with the alloca. - if (newVal->getType() != Inst->getType()) + if (newVal->getType() != Inst->getType()) { newVal = Builder.CreateBitCast(newVal, Inst->getType()); + } Inst->replaceAllUsesWith(newVal); RemoveCall(CS, A); @@ -546,22 +571,26 @@ bool GarbageCollect2Stack::runOnFunction(Function &F) { Type *Analysis::getTypeFor(Value *typeinfo) const { GlobalVariable *ti_global = dyn_cast(typeinfo->stripPointerCasts()); - if (!ti_global) - return NULL; + if (!ti_global) { + return nullptr; + } std::string metaname = TD_PREFIX; metaname += ti_global->getName(); NamedMDNode *meta = M.getNamedMetadata(metaname); - if (!meta) - return NULL; + if (!meta) { + return nullptr; + } MDNode *node = static_cast(meta->getOperand(0)); - if (!node) - return NULL; + if (!node) { + return nullptr; + } - if (node->getNumOperands() != TD_NumFields) - return NULL; + if (node->getNumOperands() != TD_NumFields) { + return nullptr; + } #if LDC_LLVM_VER >= 306 Value *ti = llvm::MetadataAsValue::get(node->getContext(), @@ -569,8 +598,9 @@ Type *Analysis::getTypeFor(Value *typeinfo) const { #else Value *ti = node->getOperand(TD_TypeInfo); #endif - if (!ti || ti->stripPointerCasts() != ti_global) - return NULL; + if (!ti || ti->stripPointerCasts() != ti_global) { + return nullptr; + } #if LDC_LLVM_VER >= 306 return llvm::MetadataAsValue::get(node->getContext(), @@ -665,8 +695,9 @@ static bool mayBeUsedAfterRealloc(Instruction *Def, Instruction *Alloc, // We need to walk the instructions in the block to see whether we // reach a user before we reach the definition or the allocation. for (BasicBlock::iterator E = B->end(); BBI != E; ++BBI) { - if (&*BBI == Alloc || &*BBI == Def) + if (&*BBI == Alloc || &*BBI == Def) { break; + } if (Users.count(BBI)) { DEBUG(errs() << "### Problematic user: " << *BBI); return true; @@ -710,8 +741,9 @@ static bool mayBeUsedAfterRealloc(Instruction *Def, Instruction *Alloc, #else && Visited.insert(Succ) #endif - && DT.dominates(DefBlock, Succ)) + && DT.dominates(DefBlock, Succ)) { Worklist.push_back(StartPoint(Succ, BBI)); + } } } // No users found in any block reachable from Alloc @@ -748,8 +780,9 @@ bool isSafeToStackAllocateArray( "First array field not length?"); } else { assert(idx == 1 && "Invalid array struct access."); - if (!isSafeToStackAllocate(Alloc, EVI, DT, RemoveTailCallInsts)) + if (!isSafeToStackAllocate(Alloc, EVI, DT, RemoveTailCallInsts)) { return false; + } } break; } @@ -813,8 +846,9 @@ bool isSafeToStackAllocate(Instruction *Alloc, Value *V, DominatorTree &DT, // its return value and doesn't unwind (a readonly function can leak bits // by throwing an exception or not depending on the input value). if (CS.onlyReadsMemory() && CS.doesNotThrow() && - I->getType() == Type::getVoidTy(I->getContext())) + I->getType() == Type::getVoidTy(I->getContext())) { break; + } // Not captured if only passed via 'nocapture' arguments. Note that // calling a function pointer does not in itself cause the pointer to @@ -824,7 +858,7 @@ bool isSafeToStackAllocate(Instruction *Alloc, Value *V, DominatorTree &DT, // captured, even though the loaded value might be the pointer itself // (think of self-referential objects). CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end(); - for (CallSite::arg_iterator A = B; A != E; ++A) + for (CallSite::arg_iterator A = B; A != E; ++A) { if (A->get() == V) { if (!CS.paramHasAttr(A - B + 1, LLAttribute::NoCapture)) { // The parameter is not marked 'nocapture' - captured. @@ -838,6 +872,7 @@ bool isSafeToStackAllocate(Instruction *Alloc, Value *V, DominatorTree &DT, } } } + } // Only passed via 'nocapture' arguments, or is the called function - not // captured. break; @@ -846,9 +881,10 @@ bool isSafeToStackAllocate(Instruction *Alloc, Value *V, DominatorTree &DT, // Loading from a pointer does not cause it to be captured. break; case Instruction::Store: - if (V == I->getOperand(0)) + if (V == I->getOperand(0)) { // Stored the pointer - it may be captured. return false; + } // Storing to the pointee does not cause the pointer to be captured. break; case Instruction::BitCast: @@ -857,19 +893,21 @@ bool isSafeToStackAllocate(Instruction *Alloc, Value *V, DominatorTree &DT, case Instruction::Select: // It's not safe to stack-allocate if this derived pointer is live across // the original allocation. - if (mayBeUsedAfterRealloc(I, Alloc, DT)) + if (mayBeUsedAfterRealloc(I, Alloc, DT)) { return false; + } // The original value is not captured via this if the new value isn't. for (Instruction::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; ++UI) { Use *U = &(*UI); #if LDC_LLVM_VER >= 306 - if (Visited.insert(U).second) + if (Visited.insert(U).second) { #else - if (Visited.insert(U)) + if (Visited.insert(U)) { #endif Worklist.push_back(U); + } } break; default: diff --git a/gen/passes/SimplifyDRuntimeCalls.cpp b/gen/passes/SimplifyDRuntimeCalls.cpp index 8d70437ea6..9d12bbacda 100644 --- a/gen/passes/SimplifyDRuntimeCalls.cpp +++ b/gen/passes/SimplifyDRuntimeCalls.cpp @@ -69,8 +69,8 @@ protected: IRBuilder<> &B); public: - LibCallOptimization() {} - virtual ~LibCallOptimization() {} + LibCallOptimization() = default; + virtual ~LibCallOptimization() = default; /// CallOptimizer - This pure virtual method is implemented by base classes to /// do various optimizations. If this returns null then no transformation was @@ -86,8 +86,9 @@ public: this->Changed = &Changed; this->DL = DL; this->AA = &AA; - if (CI->getCalledFunction()) + if (CI->getCalledFunction()) { Context = &CI->getCalledFunction()->getContext(); + } return CallOptimizer(CI->getCalledFunction(), CI, B); } }; @@ -116,19 +117,22 @@ namespace { /// ArraySetLengthOpt - remove libcall for arr.length = N if N <= arr.length struct LLVM_LIBRARY_VISIBILITY ArraySetLengthOpt : public LibCallOptimization { - virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { + Value *CallOptimizer(Function *Callee, CallInst *CI, + IRBuilder<> &B) override { // Verify we have a reasonable prototype for _d_arraysetlength[i]T const FunctionType *FT = Callee->getFunctionType(); if (Callee->arg_size() != 4 || !isa(FT->getReturnType()) || !isa(FT->getParamType(1)) || FT->getParamType(1) != FT->getParamType(2) || - FT->getParamType(3) != FT->getReturnType()) - return 0; + FT->getParamType(3) != FT->getReturnType()) { + return nullptr; + } // Whether or not this allocates is irrelevant if the result isn't used. // Just delete if that's the case. - if (CI->use_empty()) + if (CI->use_empty()) { return CI; + } Value *NewLen = CI->getOperand(1); if (Constant *NewCst = dyn_cast(NewLen)) { @@ -142,64 +146,77 @@ struct LLVM_LIBRARY_VISIBILITY ArraySetLengthOpt : public LibCallOptimization { // safely transform that example if arr.length may be 0) // Setting length to 0 never reallocates, so replace by data argument - if (NewCst->isNullValue()) + if (NewCst->isNullValue()) { return Data; + } // If both lengths are constant integers, see if NewLen <= OldLen Value *OldLen = CI->getOperand(2); - if (ConstantInt *OldInt = dyn_cast(OldLen)) - if (ConstantInt *NewInt = dyn_cast(NewCst)) - if (NewInt->getValue().ule(OldInt->getValue())) + if (ConstantInt *OldInt = dyn_cast(OldLen)) { + if (ConstantInt *NewInt = dyn_cast(NewCst)) { + if (NewInt->getValue().ule(OldInt->getValue())) { return Data; + } + } + } } - return 0; + return nullptr; } }; /// ArrayCastLenOpt - remove libcall for cast(T[]) arr if it's safe to do so. struct LLVM_LIBRARY_VISIBILITY ArrayCastLenOpt : public LibCallOptimization { - virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { + Value *CallOptimizer(Function *Callee, CallInst *CI, + IRBuilder<> &B) override { // Verify we have a reasonable prototype for _d_array_cast_len const FunctionType *FT = Callee->getFunctionType(); const Type *RetTy = FT->getReturnType(); if (Callee->arg_size() != 3 || !isa(RetTy) || FT->getParamType(0) != RetTy || FT->getParamType(1) != RetTy || - FT->getParamType(2) != RetTy) - return 0; + FT->getParamType(2) != RetTy) { + return nullptr; + } Value *OldLen = CI->getOperand(0); Value *OldSize = CI->getOperand(1); Value *NewSize = CI->getOperand(2); // If the old length was zero, always return zero. - if (Constant *LenCst = dyn_cast(OldLen)) - if (LenCst->isNullValue()) + if (Constant *LenCst = dyn_cast(OldLen)) { + if (LenCst->isNullValue()) { return OldLen; + } + } // Equal sizes are much faster to check for, so do so now. - if (OldSize == NewSize) + if (OldSize == NewSize) { return OldLen; + } // If both sizes are constant integers, see if OldSize is a multiple of // NewSize - if (ConstantInt *OldInt = dyn_cast(OldSize)) + if (ConstantInt *OldInt = dyn_cast(OldSize)) { if (ConstantInt *NewInt = dyn_cast(NewSize)) { // Don't crash on NewSize == 0, even though it shouldn't happen. - if (NewInt->isNullValue()) - return 0; + if (NewInt->isNullValue()) { + return nullptr; + } APInt Quot, Rem; APInt::udivrem(OldInt->getValue(), NewInt->getValue(), Quot, Rem); - if (Rem == 0) + if (Rem == 0) { return B.CreateMul(OldLen, ConstantInt::get(*Context, Quot)); + } } - return 0; + } + return nullptr; } }; /// AllocationOpt - Common optimizations for various GC allocations. struct LLVM_LIBRARY_VISIBILITY AllocationOpt : public LibCallOptimization { - virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { + Value *CallOptimizer(Function *Callee, CallInst *CI, + IRBuilder<> &B) override { // Allocations are never equal to constants, so remove any equality // comparisons to constants. (Most importantly comparisons to null at // the start of inlined member functions) @@ -208,9 +225,10 @@ struct LLVM_LIBRARY_VISIBILITY AllocationOpt : public LibCallOptimization { Instruction *User = cast(*I++); if (ICmpInst *Cmp = dyn_cast(User)) { - if (!Cmp->isEquality()) + if (!Cmp->isEquality()) { continue; - Constant *C = 0; + } + Constant *C = nullptr; if ((C = dyn_cast(Cmp->getOperand(0))) || (C = dyn_cast(Cmp->getOperand(1)))) { Value *Result = @@ -229,15 +247,17 @@ struct LLVM_LIBRARY_VISIBILITY AllocationOpt : public LibCallOptimization { } // If it's not used (anymore), pre-emptively GC it. - if (CI->use_empty()) + if (CI->use_empty()) { return CI; - return 0; + } + return nullptr; } }; /// ArraySliceCopyOpt - Turn slice copies into llvm.memcpy when safe struct LLVM_LIBRARY_VISIBILITY ArraySliceCopyOpt : public LibCallOptimization { - virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { + Value *CallOptimizer(Function *Callee, CallInst *CI, + IRBuilder<> &B) override { // Verify we have a reasonable prototype for _d_array_slice_copy const FunctionType *FT = Callee->getFunctionType(); const Type *VoidPtrTy = PointerType::getUnqual(B.getInt8Ty()); @@ -245,24 +265,29 @@ struct LLVM_LIBRARY_VISIBILITY ArraySliceCopyOpt : public LibCallOptimization { FT->getParamType(0) != VoidPtrTy || !isa(FT->getParamType(1)) || FT->getParamType(2) != VoidPtrTy || - FT->getParamType(3) != FT->getParamType(1)) - return 0; + FT->getParamType(3) != FT->getParamType(1)) { + return nullptr; + } Value *Size = CI->getOperand(1); // Check the lengths match - if (CI->getOperand(3) != Size) - return 0; + if (CI->getOperand(3) != Size) { + return nullptr; + } // Assume unknown size unless we have constant size (that fits in an uint) unsigned Sz = ~0U; - if (ConstantInt *Int = dyn_cast(Size)) - if (Int->getValue().isIntN(32)) + if (ConstantInt *Int = dyn_cast(Size)) { + if (Int->getValue().isIntN(32)) { Sz = Int->getValue().getZExtValue(); + } + } // Check if the pointers may alias - if (AA->alias(CI->getOperand(0), Sz, CI->getOperand(2), Sz)) - return 0; + if (AA->alias(CI->getOperand(0), Sz, CI->getOperand(2), Sz)) { + return nullptr; + } // Equal length and the pointers definitely don't alias, so it's safe to // replace the call with memcpy @@ -297,11 +322,11 @@ public: SimplifyDRuntimeCalls() : FunctionPass(ID) {} void InitOptimizations(); - bool runOnFunction(Function &F); + bool runOnFunction(Function &F) override; bool runOnce(Function &F, const DataLayout *DL, AliasAnalysisPass &AA); - virtual void getAnalysisUsage(AnalysisUsage &AU) const { + void getAnalysisUsage(AnalysisUsage &AU) const override { #if LDC_LLVM_VER >= 307 // The DataLayoutPass is removed. #else @@ -352,14 +377,15 @@ void SimplifyDRuntimeCalls::InitOptimizations() { /// runOnFunction - Top level algorithm. /// bool SimplifyDRuntimeCalls::runOnFunction(Function &F) { - if (Optimizations.empty()) + if (Optimizations.empty()) { InitOptimizations(); + } #if LDC_LLVM_VER >= 307 const DataLayout *DL = &F.getParent()->getDataLayout(); #else DataLayoutPass *DLP = getAnalysisIfAvailable(); - const DataLayout *DL = DLP ? &DLP->getDataLayout() : 0; + const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr; #endif AliasAnalysisPass &AA = getAnalysis(); @@ -387,19 +413,22 @@ bool SimplifyDRuntimeCalls::runOnce(Function &F, const DataLayout *DL, for (auto I = BB.begin(); I != BB.end();) { // Ignore non-calls. CallInst *CI = dyn_cast(I++); - if (!CI) + if (!CI) { continue; + } // Ignore indirect calls and calls to non-external functions. Function *Callee = CI->getCalledFunction(); if (Callee == nullptr || !Callee->isDeclaration() || - !Callee->hasExternalLinkage()) + !Callee->hasExternalLinkage()) { continue; + } // Ignore unknown calls. auto OMI = Optimizations.find(Callee->getName()); - if (OMI == Optimizations.end()) + if (OMI == Optimizations.end()) { continue; + } DEBUG(errs() << "SimplifyDRuntimeCalls inspecting: " << *CI); @@ -413,8 +442,9 @@ bool SimplifyDRuntimeCalls::runOnce(Function &F, const DataLayout *DL, AliasAnalysis &AA = AAP; #endif Value *Result = OMI->second->OptimizeCall(CI, Changed, DL, AA, Builder); - if (Result == 0) + if (Result == nullptr) { continue; + } DEBUG(errs() << "SimplifyDRuntimeCalls simplified: " << *CI; errs() << " into: " << *Result << "\n"); @@ -434,11 +464,13 @@ bool SimplifyDRuntimeCalls::runOnce(Function &F, const DataLayout *DL, AA.replaceWithNewValue(CI, Result); #endif - if (!CI->use_empty()) + if (!CI->use_empty()) { CI->replaceAllUsesWith(Result); + } - if (!Result->hasName()) + if (!Result->hasName()) { Result->takeName(CI); + } } // Inspect the instruction after the call (which was potentially just diff --git a/gen/passes/StripExternals.cpp b/gen/passes/StripExternals.cpp index 91a49ae34c..f0d0c0e00d 100644 --- a/gen/passes/StripExternals.cpp +++ b/gen/passes/StripExternals.cpp @@ -37,7 +37,7 @@ struct LLVM_LIBRARY_VISIBILITY StripExternals : public ModulePass { // run - Do the StripExternals pass on the specified module. // - bool runOnModule(Module &M); + bool runOnModule(Module &M) override; }; } @@ -83,7 +83,7 @@ bool StripExternals::runOnModule(Module &M) { todelete->eraseFromParent(); continue; } else { - I->setInitializer(0); + I->setInitializer(nullptr); I->setLinkage(GlobalValue::ExternalLinkage); DEBUG(errs() << "Deleted initializer: " << *I); } diff --git a/gen/pragma.cpp b/gen/pragma.cpp index 579355f5cd..a2431d3f10 100644 --- a/gen/pragma.cpp +++ b/gen/pragma.cpp @@ -18,7 +18,7 @@ #include "llvm/Support/CommandLine.h" static bool parseStringExp(Expression *e, std::string &res) { - StringExp *s = NULL; + StringExp *s = nullptr; e = e->optimize(WANTvalue); if (e->op == TOKstring && (s = static_cast(e))) { @@ -30,7 +30,7 @@ static bool parseStringExp(Expression *e, std::string &res) { } static bool parseIntExp(Expression *e, dinteger_t &res) { - IntegerExp *i = NULL; + IntegerExp *i = nullptr; e = e->optimize(WANTvalue); if (e->op == TOKint64 && (i = static_cast(e))) { @@ -43,7 +43,8 @@ static bool parseIntExp(Expression *e, dinteger_t &res) { Pragma DtoGetPragma(Scope *sc, PragmaDeclaration *decl, std::string &arg1str) { Identifier *ident = decl->ident; Expressions *args = decl->args; - Expression *expr = (args && args->dim > 0) ? (*args)[0]->semantic(sc) : 0; + Expression *expr = + (args && args->dim > 0) ? (*args)[0]->semantic(sc) : nullptr; // pragma(LDC_intrinsic, "string") { funcdecl(s) } if (ident == Id::LDC_intrinsic) { @@ -72,12 +73,13 @@ Pragma DtoGetPragma(Scope *sc, PragmaDeclaration *decl, std::string &arg1str) { do { size_t k = (i + j) / 2; int cmp = name.compare(ldcIntrinsic[k].name); - if (!cmp) + if (!cmp) { return ldcIntrinsic[k].pragma; - else if (cmp < 0) + } else if (cmp < 0) { j = k; - else + } else { i = k + 1; + } } while (i != j); } @@ -97,8 +99,9 @@ Pragma DtoGetPragma(Scope *sc, PragmaDeclaration *decl, std::string &arg1str) { error(Loc(), "priority may not be greater then 65535"); priority = 65535; } - } else + } else { priority = 65535; + } char buf[8]; sprintf(buf, "%llu", static_cast(priority)); arg1str = std::string(buf); @@ -257,8 +260,9 @@ Pragma DtoGetPragma(Scope *sc, PragmaDeclaration *decl, std::string &arg1str) { void DtoCheckPragma(PragmaDeclaration *decl, Dsymbol *s, Pragma llvm_internal, const std::string &arg1str) { - if (llvm_internal == LLVMnone || llvm_internal == LLVMignore) + if (llvm_internal == LLVMnone || llvm_internal == LLVMignore) { return; + } if (s->llvmInternal) { error(Loc(), diff --git a/gen/programs.cpp b/gen/programs.cpp index bfc6bb0327..578c9df017 100644 --- a/gen/programs.cpp +++ b/gen/programs.cpp @@ -31,19 +31,22 @@ static std::string findProgramByName(const std::string &name) { } static std::string getProgram(const char *name, const cl::opt *opt, - const char *envVar = NULL) { + const char *envVar = nullptr) { std::string path; - const char *prog = NULL; + const char *prog = nullptr; if (opt && opt->getNumOccurrences() > 0 && opt->length() > 0 && - (prog = opt->c_str())) + (prog = opt->c_str())) { path = findProgramByName(prog); + } - if (path.empty() && envVar && (prog = getenv(envVar)) && prog[0] != '\0') + if (path.empty() && envVar && (prog = getenv(envVar)) && prog[0] != '\0') { path = findProgramByName(prog); + } - if (path.empty()) + if (path.empty()) { path = findProgramByName(name); + } if (path.empty()) { error(Loc(), "failed to locate %s", name); @@ -54,7 +57,7 @@ static std::string getProgram(const char *name, const cl::opt *opt, } std::string getProgram(const char *name, const char *envVar) { - return getProgram(name, NULL, envVar); + return getProgram(name, nullptr, envVar); } std::string getGcc() { diff --git a/gen/programs.h b/gen/programs.h index 43f2b23719..c26ac70664 100644 --- a/gen/programs.h +++ b/gen/programs.h @@ -16,7 +16,7 @@ #include -std::string getProgram(const char *name, const char *envVar = 0); +std::string getProgram(const char *name, const char *envVar = nullptr); std::string getGcc(); std::string getArchiver(); diff --git a/gen/rttibuilder.cpp b/gen/rttibuilder.cpp index fd3dbe80b5..c0d4e4a895 100644 --- a/gen/rttibuilder.cpp +++ b/gen/rttibuilder.cpp @@ -80,8 +80,8 @@ void RTTIBuilder::push_void_array(llvm::Constant *CI, Type *valtype, std::string initname(mangle(mangle_sym)); initname.append(".rtti.voidarr.data"); - LLGlobalVariable *G = new LLGlobalVariable( - gIR->module, CI->getType(), true, TYPEINFO_LINKAGE_TYPE, CI, initname); + auto G = new LLGlobalVariable(gIR->module, CI->getType(), true, + TYPEINFO_LINKAGE_TYPE, CI, initname); SET_COMDAT(G, gIR->module); G->setAlignment(DtoAlignment(valtype)); @@ -100,8 +100,8 @@ void RTTIBuilder::push_array(llvm::Constant *CI, uint64_t dim, Type *valtype, initname.append(tmpStr); initname.append(".data"); - LLGlobalVariable *G = new LLGlobalVariable( - gIR->module, CI->getType(), true, TYPEINFO_LINKAGE_TYPE, CI, initname); + auto G = new LLGlobalVariable(gIR->module, CI->getType(), true, + TYPEINFO_LINKAGE_TYPE, CI, initname); SET_COMDAT(G, gIR->module); G->setAlignment(DtoAlignment(valtype)); @@ -124,8 +124,9 @@ void RTTIBuilder::push_funcptr(FuncDeclaration *fd, Type *castto) { if (fd) { DtoResolveFunction(fd); LLConstant *F = getIrFunc(fd)->func; - if (castto) + if (castto) { F = DtoBitCast(F, DtoType(castto)); + } push(F); } else if (castto) { push_null(castto); @@ -146,8 +147,9 @@ void RTTIBuilder::finalize(LLType *type, LLValue *value) { const int n = inits.size(); std::vector types; types.reserve(n); - for (int i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { types.push_back(inits[i]->getType()); + } st->setBody(types); } diff --git a/gen/rttibuilder.h b/gen/rttibuilder.h index d773b0d12e..981c07daa9 100644 --- a/gen/rttibuilder.h +++ b/gen/rttibuilder.h @@ -43,7 +43,7 @@ public: // padding llvm::SmallVector inits; - RTTIBuilder(AggregateDeclaration *base_class); + explicit RTTIBuilder(AggregateDeclaration *base_class); void push(llvm::Constant *C); void push_null(Type *T); @@ -57,7 +57,7 @@ public: void push_classinfo(ClassDeclaration *cd); /// pushes the function pointer or a null void* if it cannot. - void push_funcptr(FuncDeclaration *fd, Type *castto = NULL); + void push_funcptr(FuncDeclaration *fd, Type *castto = nullptr); /// pushes the array slice given. void push_array(uint64_t dim, llvm::Constant *ptr); diff --git a/gen/runtime.cpp b/gen/runtime.cpp index d5058c2a6a..e93ad02f22 100644 --- a/gen/runtime.cpp +++ b/gen/runtime.cpp @@ -41,7 +41,7 @@ static llvm::cl::opt nogc( ////////////////////////////////////////////////////////////////////////////////////////////////// -static llvm::Module *M = NULL; +static llvm::Module *M = nullptr; static void LLVM_D_BuildRuntimeModule(); @@ -111,7 +111,7 @@ void LLVM_D_FreeRuntime() { if (M) { Logger::println("*** Freeing D runtime declarations ***"); delete M; - M = NULL; + M = nullptr; } } @@ -126,8 +126,9 @@ llvm::Function *LLVM_D_GetRuntimeFunction(const Loc &loc, llvm::Module &target, } LLFunction *fn = target.getFunction(name); - if (fn) + if (fn) { return fn; + } fn = M->getFunction(name); assert(fn && "Runtime function not found."); @@ -164,7 +165,7 @@ llvm::GlobalVariable *LLVM_D_GetRuntimeGlobal(Loc &loc, llvm::Module &target, LLPointerType *t = g->getType(); return getOrCreateGlobal(loc, target, t->getElementType(), g->isConstant(), - g->getLinkage(), NULL, g->getName()); + g->getLinkage(), nullptr, g->getName()); } ////////////////////////////////////////////////////////////////////////////////////////////////// @@ -502,9 +503,9 @@ static void LLVM_D_BuildRuntimeModule() { #define STR_APPLY1(TY, a, b) \ { \ const std::string prefix = "_aApply"; \ - std::string fname1 = prefix + a + '1', fname2 = prefix + b + '1', \ - fname3 = prefix + 'R' + a + '1', \ - fname4 = prefix + 'R' + b + '1'; \ + std::string fname1 = prefix + (a) + '1', fname2 = prefix + (b) + '1', \ + fname3 = prefix + 'R' + (a) + '1', \ + fname4 = prefix + 'R' + (b) + '1'; \ LLType *types[] = {TY, rt_dg1()}; \ LLFunctionType *fty = llvm::FunctionType::get(intTy, types, false); \ llvm::Function::Create(fty, llvm::GlobalValue::ExternalLinkage, fname1, \ @@ -526,9 +527,9 @@ static void LLVM_D_BuildRuntimeModule() { #define STR_APPLY2(TY, a, b) \ { \ const std::string prefix = "_aApply"; \ - std::string fname1 = prefix + a + '2', fname2 = prefix + b + '2', \ - fname3 = prefix + 'R' + a + '2', \ - fname4 = prefix + 'R' + b + '2'; \ + std::string fname1 = prefix + (a) + '2', fname2 = prefix + (b) + '2', \ + fname3 = prefix + 'R' + (a) + '2', \ + fname4 = prefix + 'R' + (b) + '2'; \ LLType *types[] = {TY, rt_dg2()}; \ LLFunctionType *fty = llvm::FunctionType::get(intTy, types, false); \ llvm::Function::Create(fty, llvm::GlobalValue::ExternalLinkage, fname1, \ @@ -851,7 +852,7 @@ static void LLVM_D_BuildRuntimeModule() { // int _d_eh_personality(...) { - LLFunctionType *fty = NULL; + LLFunctionType *fty = nullptr; if (global.params.targetTriple.isWindowsMSVCEnvironment()) { // int _d_eh_personality(ptr ExceptionRecord, ptr EstablisherFrame, ptr // ContextRecord, ptr DispatcherContext) @@ -899,10 +900,10 @@ static void LLVM_D_BuildRuntimeModule() { // for more efficient parameter passing on x86. This complicates our code // here // quite a bit, though. - Parameters *params = new Parameters(); + auto params = new Parameters(); params->push( - new Parameter(STCin, ClassDeclaration::object->type, NULL, NULL)); - TypeFunction *dty = new TypeFunction(params, Type::tvoid, 0, LINKd); + new Parameter(STCin, ClassDeclaration::object->type, nullptr, nullptr)); + auto dty = new TypeFunction(params, Type::tvoid, 0, LINKd); llvm::Function *fn = llvm::Function::Create( llvm::cast(DtoType(dty)), llvm::GlobalValue::ExternalLinkage, diff --git a/gen/statements.cpp b/gen/statements.cpp index 3b9aaf9727..96273298b6 100644 --- a/gen/statements.cpp +++ b/gen/statements.cpp @@ -52,7 +52,7 @@ struct Case : RootObject { index = i; } - int compare(RootObject *obj) { + int compare(RootObject *obj) override { Case *c2 = static_cast(obj); return str->compare(c2->str); } @@ -96,7 +96,7 @@ class ToIRVisitor : public Visitor { IRState *irs; public: - ToIRVisitor(IRState *irs) : irs(irs) {} + explicit ToIRVisitor(IRState *irs) : irs(irs) {} ////////////////////////////////////////////////////////////////////////// @@ -129,7 +129,7 @@ public: emitCoverageLinecountInc(stmt->loc); // The LLVM value to return, or null for void returns. - llvm::Value *returnValue = 0; + llvm::Value *returnValue = nullptr; // is there a return value expression? if (stmt->exp || (!stmt->exp && (irs->topfunc() == irs->mainFunc))) { @@ -154,8 +154,9 @@ public: // call postblit if necessary if (!irs->func()->type->isref && - !(f->decl->nrvo_can && f->decl->nrvo_var)) + !(f->decl->nrvo_can && f->decl->nrvo_var)) { callPostblit(stmt->loc, stmt->exp, rvar->getLVal()); + } } // the return type is not void, so this is a normal "register" return else { @@ -163,9 +164,10 @@ public: returnValue = LLConstant::getNullValue(irs->mainFunc->getReturnType()); } else { - if (stmt->exp->op == TOKnull) + if (stmt->exp->op == TOKnull) { stmt->exp->type = irs->func()->type->next; - DValue *dval = 0; + } + DValue *dval = nullptr; // call postblit if necessary if (!irs->func()->type->isref) { dval = toElemDtor(stmt->exp); @@ -198,12 +200,13 @@ public: // return type remains i32, we just throw away the exp value // and return 0 instead // if we're not in main, just bitcast - if (irs->topfunc() == irs->mainFunc) + if (irs->topfunc() == irs->mainFunc) { returnValue = LLConstant::getNullValue(irs->mainFunc->getReturnType()); - else + } else { returnValue = irs->ir->CreateBitCast( returnValue, irs->topfunc()->getReturnType()); + } IF_LOG Logger::cout() << "return value after cast: " << *returnValue << '\n'; @@ -252,8 +255,9 @@ public: // Hack: the frontend generates 'return 0;' as last statement of // 'void main()'. But the debug location is missing. Use the end // of function as debug location. - if (irs->func()->decl->isMain() && !stmt->loc.linnum) + if (irs->func()->decl->isMain() && !stmt->loc.linnum) { irs->DBuilder.EmitStopPoint(irs->func()->decl->endloc); + } irs->ir->CreateRet(loadFromSlot ? DtoLoad(irs->func()->retValSlot) : returnValue); @@ -285,8 +289,9 @@ public: if (stmt->exp->op == TOKcast && stmt->exp->type == Type::tvoid) { CastExp *cexp = static_cast(stmt->exp); e = toElemDtor(cexp->e1); - } else + } else { e = toElemDtor(stmt->exp); + } delete e; } } @@ -301,8 +306,9 @@ public: irs->DBuilder.EmitBlockStart(stmt->loc); emitCoverageLinecountInc(stmt->loc); - if (stmt->match) + if (stmt->match) { DtoRawVarDeclaration(stmt->match); + } DValue *cond_e = toElemDtor(stmt->condition); LLValue *cond_val = cond_e->getRVal(); @@ -404,13 +410,15 @@ public: // while body code irs->func()->scopes->pushLoopTarget(stmt, whilebb, endbb); - if (stmt->body) + if (stmt->body) { stmt->body->accept(this); + } irs->func()->scopes->popLoopTarget(); // loop - if (!irs->scopereturned()) + if (!irs->scopereturned()) { llvm::BranchInst::Create(whilebb, irs->scopebb()); + } // rewrite the scope irs->scope() = IRScope(endbb); @@ -445,8 +453,9 @@ public: // do-while body code irs->func()->scopes->pushLoopTarget(stmt, condbb, endbb); - if (stmt->body) + if (stmt->body) { stmt->body->accept(this); + } irs->func()->scopes->popLoopTarget(); // branch to condition block @@ -489,8 +498,9 @@ public: llvm::BasicBlock::Create(irs->context(), "endfor", irs->topfunc()); // init - if (stmt->init != 0) + if (stmt->init != nullptr) { stmt->init->accept(this); + } // move into the for condition block, ie. start the loop assert(!irs->scopereturned()); @@ -527,12 +537,14 @@ public: irs->scope() = IRScope(forbodybb); // do for body code - if (stmt->body) + if (stmt->body) { stmt->body->accept(this); + } // move into the for increment block - if (!irs->scopereturned()) + if (!irs->scopereturned()) { llvm::BranchInst::Create(forincbb, irs->scopebb()); + } irs->scope() = IRScope(forincbb); // increment @@ -543,8 +555,9 @@ public: } // loop - if (!irs->scopereturned()) + if (!irs->scopereturned()) { llvm::BranchInst::Create(forbb, irs->scopebb()); + } irs->func()->scopes->popLoopTarget(); @@ -564,8 +577,9 @@ public: // don't emit two terminators in a row // happens just before DMD generated default statements if the last case // terminates - if (irs->scopereturned()) + if (irs->scopereturned()) { return; + } // emit dwarf stop point irs->DBuilder.EmitStopPoint(stmt->loc); @@ -578,8 +592,9 @@ public: // Get the loop or break statement the label refers to Statement *targetStatement = stmt->target->statement; ScopeStatement *tmp; - while ((tmp = targetStatement->isScopeStatement())) + while ((tmp = targetStatement->isScopeStatement())) { targetStatement = tmp->statement; + } irs->func()->scopes->breakToStatement(targetStatement); } else { @@ -610,8 +625,9 @@ public: // get the loop statement the label refers to Statement *targetLoopStatement = stmt->target->statement; ScopeStatement *tmp; - while ((tmp = targetLoopStatement->isScopeStatement())) + while ((tmp = targetLoopStatement->isScopeStatement())) { targetLoopStatement = tmp->statement; + } irs->func()->scopes->continueWithLoop(targetLoopStatement); } else { @@ -858,8 +874,9 @@ public: bool useSwitchInst = true; for (auto cs : *stmt->cases) { VarDeclaration *vd = nullptr; - if (cs->exp->op == TOKvar) + if (cs->exp->op == TOKvar) { vd = static_cast(cs->exp)->var->isVarDeclaration(); + } if (vd && (!vd->init || !vd->isConst())) { cs->llvmIdx = toElemDtor(cs->exp)->getRVal(); useSwitchInst = false; @@ -872,7 +889,7 @@ public: llvm::BasicBlock::Create(irs->context(), "switchbody", irs->topfunc()); // default - llvm::BasicBlock *defbb = 0; + llvm::BasicBlock *defbb = nullptr; if (stmt->sdefault) { Logger::println("has default"); defbb = @@ -890,13 +907,14 @@ public: irs->func()->scopes->pushBreakTarget(stmt, endbb); stmt->body->accept(this); irs->func()->scopes->popBreakTarget(); - if (!irs->scopereturned()) + if (!irs->scopereturned()) { llvm::BranchInst::Create(endbb, irs->scopebb()); + } irs->scope() = IRScope(oldbb); if (useSwitchInst) { // string switch? - llvm::Value *switchTable = 0; + llvm::Value *switchTable = nullptr; Objects caseArray; if (!stmt->condition->type->isintegral()) { Logger::println("is string switch"); @@ -912,7 +930,7 @@ public: // first sort it caseArray.sort(); // iterate and add indices to cases - std::vector inits(caseArray.dim, 0); + std::vector inits(caseArray.dim, nullptr); for (size_t i = 0; i < caseArray.dim; ++i) { Case *c = static_cast(caseArray.data[i]); CaseStatement *cs = @@ -924,7 +942,7 @@ public: llvm::Type *elemTy = DtoType(stmt->condition->type); LLArrayType *arrTy = llvm::ArrayType::get(elemTy, inits.size()); LLConstant *arrInit = LLConstantArray::get(arrTy, inits); - LLGlobalVariable *arr = new llvm::GlobalVariable( + auto arr = new llvm::GlobalVariable( irs->module, arrTy, true, llvm::GlobalValue::InternalLinkage, arrInit, ".string_switch_table_data"); @@ -954,8 +972,9 @@ public: // create switch and add the cases llvm::SwitchInst *si = llvm::SwitchInst::Create( condVal, defbb ? defbb : endbb, stmt->cases->dim, irs->scopebb()); - for (auto cs : *stmt->cases) + for (auto cs : *stmt->cases) { si->addCase(isaConstantInt(cs->llvmIdx), cs->bodyBB); + } } else { // we can't use switch, so we will use a bunch of br instructions // instead DValue *cond = toElemDtor(stmt->condition); @@ -999,13 +1018,14 @@ public: } stmt->bodyBB = nbb; - if (stmt->llvmIdx == NULL) { + if (stmt->llvmIdx == nullptr) { llvm::Constant *c = toConstElem(stmt->exp, irs); stmt->llvmIdx = isaConstantInt(c); } - if (!irs->scopereturned()) + if (!irs->scopereturned()) { llvm::BranchInst::Create(stmt->bodyBB, irs->scopebb()); + } irs->scope() = IRScope(stmt->bodyBB); @@ -1032,8 +1052,9 @@ public: } stmt->bodyBB = nbb; - if (!irs->scopereturned()) + if (!irs->scopereturned()) { llvm::BranchInst::Create(stmt->bodyBB, irs->scopebb()); + } irs->scope() = IRScope(stmt->bodyBB); @@ -1052,8 +1073,9 @@ public: LOG_SCOPE; // if no statements, there's nothing to do - if (!stmt->statements || !stmt->statements->dim) + if (!stmt->statements || !stmt->statements->dim) { return; + } // start a dwarf lexical block irs->DBuilder.EmitBlockStart(stmt->loc); @@ -1065,7 +1087,7 @@ public: // create a block for each statement size_t nstmt = stmt->statements->dim; - llvm::SmallVector blocks(nstmt, NULL); + llvm::SmallVector blocks(nstmt, nullptr); for (size_t i = 0; i < nstmt; i++) { blocks[i] = llvm::BasicBlock::Create(irs->context(), "unrolledstmt", @@ -1077,8 +1099,9 @@ public: llvm::BasicBlock::Create(irs->context(), "unrolledend", irs->topfunc()); // enter first stmt - if (!irs->scopereturned()) + if (!irs->scopereturned()) { irs->ir->CreateBr(blocks[0]); + } // do statements Statement **stmts = static_cast(stmt->statements->data); @@ -1104,13 +1127,15 @@ public: irs->func()->scopes->popLoopTarget(); // next stmt - if (!irs->scopereturned()) + if (!irs->scopereturned()) { irs->ir->CreateBr(nextbb); + } } // finish scope - if (!irs->scopereturned()) + if (!irs->scopereturned()) { irs->ir->CreateBr(endbb); + } irs->scope() = IRScope(endbb); // end the dwarf lexical block @@ -1139,15 +1164,16 @@ public: // key LLType *keytype = stmt->key ? DtoType(stmt->key->type) : DtoSize_t(); LLValue *keyvar; - if (stmt->key) + if (stmt->key) { keyvar = DtoRawVarDeclaration(stmt->key); - else + } else { keyvar = DtoRawAlloca(keytype, 0, "foreachkey"); + } LLValue *zerokey = LLConstantInt::get(keytype, 0, false); // value IF_LOG Logger::println("value = %s", stmt->value->toPrettyChars()); - LLValue *valvar = NULL; + LLValue *valvar = nullptr; if (!stmt->value->isRef() && !stmt->value->isOut()) { // Create a local variable to serve as the value. DtoRawVarDeclaration(stmt->value); @@ -1164,12 +1190,13 @@ public: if (niters->getType() != keytype) { size_t sz1 = getTypeBitSize(niters->getType()); size_t sz2 = getTypeBitSize(keytype); - if (sz1 < sz2) + if (sz1 < sz2) { niters = irs->ir->CreateZExt(niters, keytype, "foreachtrunckey"); - else if (sz1 > sz2) + } else if (sz1 > sz2) { niters = irs->ir->CreateTrunc(niters, keytype, "foreachtrunckey"); - else + } else { niters = irs->ir->CreateBitCast(niters, keytype, "foreachtrunckey"); + } } if (stmt->op == TOKforeach) { @@ -1192,7 +1219,7 @@ public: // condition irs->scope() = IRScope(condbb); - LLValue *done = 0; + LLValue *done = nullptr; LLValue *load = DtoLoad(keyvar); if (stmt->op == TOKforeach) { done = irs->ir->CreateICmpULT(load, niters); @@ -1223,12 +1250,14 @@ public: // emit body irs->func()->scopes->pushLoopTarget(stmt, nextbb, endbb); - if (stmt->body) + if (stmt->body) { stmt->body->accept(this); + } irs->func()->scopes->popLoopTarget(); - if (!irs->scopereturned()) + if (!irs->scopereturned()) { llvm::BranchInst::Create(nextbb, irs->scopebb()); + } // next irs->scope() = IRScope(nextbb); @@ -1267,10 +1296,11 @@ public: LLValue *keyval = DtoRawVarDeclaration(stmt->key); // store initial value in key - if (stmt->op == TOKforeach) + if (stmt->op == TOKforeach) { DtoStore(lower, keyval); - else + } else { DtoStore(upper, keyval); + } // set up the block we'll need llvm::BasicBlock *condbb = llvm::BasicBlock::Create( @@ -1317,13 +1347,15 @@ public: // emit body irs->func()->scopes->pushLoopTarget(stmt, nextbb, endbb); - if (stmt->body) + if (stmt->body) { stmt->body->accept(this); + } irs->func()->scopes->popLoopTarget(); // jump to next iteration - if (!irs->scopereturned()) + if (!irs->scopereturned()) { llvm::BranchInst::Create(nextbb, irs->scopebb()); + } // NEXT irs->scope() = IRScope(nextbb); @@ -1355,7 +1387,7 @@ public: // if it's an inline asm label, we don't create a basicblock, just emit it // in the asm if (irs->asmBlock) { - IRAsmStmt *a = new IRAsmStmt; + auto a = new IRAsmStmt; std::stringstream label; printLabelName(label, mangleExact(irs->func()->decl), stmt->ident->toChars()); @@ -1372,8 +1404,9 @@ public: irs->topfunc()); irs->func()->scopes->addLabelTarget(stmt->ident, labelBB); - if (!irs->scopereturned()) + if (!irs->scopereturned()) { llvm::BranchInst::Create(labelBB, irs->scopebb()); + } irs->scope() = IRScope(labelBB); } @@ -1476,8 +1509,9 @@ public: DtoStore(e->getRVal(), mem); } - if (stmt->body) + if (stmt->body) { stmt->body->accept(this); + } irs->DBuilder.EmitBlockEnd(); } diff --git a/gen/structs.cpp b/gen/structs.cpp index 2cda14ec12..54238dff8f 100644 --- a/gen/structs.cpp +++ b/gen/structs.cpp @@ -32,8 +32,9 @@ void DtoResolveStruct(StructDeclaration *sd) { DtoResolveStruct(sd, sd->loc); } void DtoResolveStruct(StructDeclaration *sd, Loc &callerLoc) { // Make sure to resolve each struct type exactly once. - if (sd->ir.isResolved()) + if (sd->ir.isResolved()) { return; + } sd->ir.setResolved(); IF_LOG Logger::println("Resolving struct type: %s (%s)", sd->toChars(), @@ -56,8 +57,9 @@ void DtoResolveStruct(StructDeclaration *sd, Loc &callerLoc) { // Set up our field metadata. for (auto vd : sd->fields) { IF_LOG { - if (isIrFieldCreated(vd)) + if (isIrFieldCreated(vd)) { Logger::println("struct field already exists"); + } } getIrField(vd, true); } @@ -74,14 +76,16 @@ LLValue *DtoStructEquals(TOK op, DValue *lhs, DValue *rhs) { // set predicate llvm::ICmpInst::Predicate cmpop; - if (op == TOKequal || op == TOKidentity) + if (op == TOKequal || op == TOKidentity) { cmpop = llvm::ICmpInst::ICMP_EQ; - else + } else { cmpop = llvm::ICmpInst::ICMP_NE; + } // empty struct? EQ always true, NE always false - if (static_cast(t)->sym->fields.dim == 0) + if (static_cast(t)->sym->fields.dim == 0) { return DtoConstBool(cmpop == llvm::ICmpInst::ICMP_EQ); + } // call memcmp size_t sz = getTypePaddedSize(DtoType(t)); @@ -101,8 +105,9 @@ LLType *DtoUnpaddedStructType(Type *dty) { typedef llvm::DenseMap CacheT; static llvm::ManagedStatic cache; auto it = cache->find(dty); - if (it != cache->end()) + if (it != cache->end()) { return it->second; + } TypeStruct *sty = static_cast(dty); VarDeclarations &fields = sty->sym->fields; diff --git a/gen/target.cpp b/gen/target.cpp index 6cb40b3996..c0c23bc51d 100644 --- a/gen/target.cpp +++ b/gen/target.cpp @@ -48,8 +48,9 @@ void Target::init() { unsigned Target::alignsize(Type *type) { assert(type->isTypeBasic()); - if (type->ty == Tvoid) + if (type->ty == Tvoid) { return 1; + } return gDataLayout->getABITypeAlignment(DtoType(type)); } @@ -65,12 +66,13 @@ unsigned Target::critsecsize() { // Return sizeof(RTL_CRITICAL_SECTION) return global.params.is64bit ? 40 : 24; #else - if (global.params.targetTriple.isOSWindows()) + if (global.params.targetTriple.isOSWindows()) { return global.params.is64bit ? 40 : 24; - else if (global.params.targetTriple.getOS() == llvm::Triple::FreeBSD) + } else if (global.params.targetTriple.getOS() == llvm::Triple::FreeBSD) { return sizeof(size_t); - else + } else { return sizeof(pthread_mutex_t); + } #endif } @@ -95,12 +97,12 @@ Expression *Target::paintAsType(Expression *e, Type *type) { switch (e->type->ty) { case Tint32: case Tuns32: - u.int32value = (d_int32)e->toInteger(); + u.int32value = static_cast(e->toInteger()); break; case Tint64: case Tuns64: - u.int64value = (d_int64)e->toInteger(); + u.int64value = static_cast(e->toInteger()); break; case Tfloat32: @@ -134,7 +136,7 @@ Expression *Target::paintAsType(Expression *e, Type *type) { assert(0); } - return NULL; // avoid warning + return nullptr; // avoid warning } /****************************** diff --git a/gen/tocall.cpp b/gen/tocall.cpp index d026d13a8b..608553263d 100644 --- a/gen/tocall.cpp +++ b/gen/tocall.cpp @@ -28,8 +28,9 @@ IrFuncTy &DtoIrTypeFunction(DValue *fnval) { if (DFuncValue *dfnval = fnval->isFunc()) { - if (dfnval->func) + if (dfnval->func) { return getIrFunc(dfnval->func)->irFty; + } } Type *type = stripModifiers(fnval->getType()->toBasetype()); @@ -88,13 +89,14 @@ LLValue *DtoCallableValue(DValue *fn) { ////////////////////////////////////////////////////////////////////////////////////////// LLFunctionType *DtoExtractFunctionType(LLType *type) { - if (LLFunctionType *fty = isaFunction(type)) + if (LLFunctionType *fty = isaFunction(type)) { return fty; - else if (LLPointerType *pty = isaPointer(type)) { - if (LLFunctionType *fty = isaFunction(pty->getElementType())) + } else if (LLPointerType *pty = isaPointer(type)) { + if (LLFunctionType *fty = isaFunction(pty->getElementType())) { return fty; + } } - return NULL; + return nullptr; } ////////////////////////////////////////////////////////////////////////////////////////// @@ -121,10 +123,11 @@ static void addExplicitArguments(std::vector &args, AttrSet &attrs, bool passByVal = gABI->passByVal(argType); AttrBuilder initialAttrs; - if (passByVal) + if (passByVal) { initialAttrs.add(LLAttribute::ByVal); - else + } else { initialAttrs.add(DtoShouldExtend(argType)); + } optionalIrArgs.push_back(new IrFuncTyArg(argType, passByVal, initialAttrs)); optionalIrArgs.back()->parametersIdx = i; @@ -135,32 +138,34 @@ static void addExplicitArguments(std::vector &args, AttrSet &attrs, const size_t explicitLLArgCount = formalLLArgCount + optionalIrArgs.size(); args.resize(implicitLLArgCount + explicitLLArgCount, - static_cast(0)); + static_cast(nullptr)); // Iterate the explicit arguments from left to right in the D source, // which is the reverse of the LLVM order if irFty.reverseParams is true. for (size_t i = 0; i < explicitLLArgCount; ++i) { const bool isVararg = (i >= irFty.args.size()); - IrFuncTyArg *irArg = NULL; - if (isVararg) + IrFuncTyArg *irArg = nullptr; + if (isVararg) { irArg = optionalIrArgs[i - numFormalParams]; - else + } else { irArg = irFty.args[i]; + } DValue *const argval = argvals[irArg->parametersIdx]; Type *const argType = argval->getType(); - llvm::Value *llVal = NULL; - if (isVararg) + llvm::Value *llVal = nullptr; + if (isVararg) { llVal = irFty.putParam(*irArg, argval); - else + } else { llVal = irFty.putParam(i, argval); + } const size_t llArgIdx = implicitLLArgCount + (irFty.reverseParams ? explicitLLArgCount - i - 1 : i); llvm::Type *const callableArgType = - (isVararg ? NULL : callableTy->getParamType(llArgIdx)); + (isVararg ? nullptr : callableTy->getParamType(llArgIdx)); // Hack around LDC assuming structs and static arrays are in memory: // If the function wants a struct, and the argument value is a @@ -178,18 +183,20 @@ static void addExplicitArguments(std::vector &args, AttrSet &attrs, Logger::cout() << "arg: " << *llVal << '\n'; Logger::cout() << "expects: " << *callableArgType << '\n'; } - if (isaStruct(llVal)) + if (isaStruct(llVal)) { llVal = DtoAggrPaint(llVal, callableArgType); - else + } else { llVal = DtoBitCast(llVal, callableArgType); + } } args[llArgIdx] = llVal; // +1 as index 0 contains the function attributes. attrs.add(llArgIdx + 1, irArg->attrs); - if (isVararg) + if (isVararg) { delete irArg; + } } } @@ -213,9 +220,9 @@ static LLValue *getTypeinfoArrayArgumentForDVarArg(Expressions *arguments, LLArrayType *typeinfoarraytype = LLArrayType::get(typeinfotype, numVariadicArgs); - llvm::GlobalVariable *typeinfomem = new llvm::GlobalVariable( + auto typeinfomem = new llvm::GlobalVariable( gIR->module, typeinfoarraytype, true, llvm::GlobalValue::InternalLinkage, - NULL, "._arguments.storage"); + nullptr, "._arguments.storage"); IF_LOG Logger::cout() << "_arguments storage: " << *typeinfomem << '\n'; std::vector vtypeinfos; @@ -288,8 +295,9 @@ bool DtoLowerMagicIntrinsic(IRState *p, FuncDeclaration *fndecl, CallExp *e, LLValue *pAp = toElem((*e->arguments)[0])->getLVal(); // va_list* LLValue *vaArgArg = gABI->prepareVaArg(pAp); LLType *llType = DtoType(e->type); - if (DtoIsPassedByRef(e->type)) + if (DtoIsPassedByRef(e->type)) { llType = getPtrToType(llType); + } result = new DImValue(e->type, p->ir->CreateVAArg(vaArgArg, llType)); return true; } @@ -302,8 +310,9 @@ bool DtoLowerMagicIntrinsic(IRState *p, FuncDeclaration *fndecl, CallExp *e, } Expression *exp = (*e->arguments)[0]; DValue *expv = toElem(exp); - if (expv->getType()->toBasetype()->ty != Tint32) + if (expv->getType()->toBasetype()->ty != Tint32) { expv = DtoCast(e->loc, expv, Type::tint32); + } result = new DImValue(e->type, p->ir->CreateAlloca(LLType::getInt8Ty(p->context()), expv->getRVal(), ".alloca")); @@ -404,8 +413,9 @@ bool DtoLowerMagicIntrinsic(IRState *p, FuncDeclaration *fndecl, CallExp *e, load->setAlignment(getTypeAllocSize(load->getType())); load->setAtomic(llvm::AtomicOrdering(atomicOrdering)); llvm::Value *val = load; - if (val->getType() != ptrTy) + if (val->getType() != ptrTy) { val = DtoAllocaDump(val, retType); + } result = new DImValue(retType, val); return true; } @@ -459,8 +469,9 @@ bool DtoLowerMagicIntrinsic(IRState *p, FuncDeclaration *fndecl, CallExp *e, // Use the same quickfix as for dragonegg - see r210956 ret = p->ir->CreateExtractValue(ret, 0); llvm::Value *retVal = ret; - if (retVal->getType() != retTy) + if (retVal->getType() != retTy) { retVal = DtoAllocaDump(retVal, exp3->type); + } result = new DImValue(exp3->type, retVal); return true; } @@ -473,17 +484,18 @@ bool DtoLowerMagicIntrinsic(IRState *p, FuncDeclaration *fndecl, CallExp *e, } static const char *ops[] = {"xchg", "add", "sub", "and", "nand", "or", - "xor", "max", "min", "umax", "umin", 0}; + "xor", "max", "min", "umax", "umin", nullptr}; int op = 0; for (;; ++op) { - if (ops[op] == 0) { + if (ops[op] == nullptr) { e->error("unknown atomic_rmw operation %s", fndecl->intrinsicName.c_str()); fatal(); } - if (fndecl->intrinsicName == ops[op]) + if (fndecl->intrinsicName == ops[op]) { break; + } } Expression *exp1 = (*e->arguments)[0]; @@ -637,16 +649,18 @@ private: // Adds an optional sret pointer argument. void addSret() { - if (!irFty.arg_sret) + if (!irFty.arg_sret) { return; + } size_t index = args.size(); LLType *llArgType = *(llArgTypesBegin + index); LLValue *var = retvar; - if (!var) + if (!var) { var = DtoRawAlloca(llArgType->getContainedType(0), DtoAlignment(resulttype), ".rettmp"); + } args.push_back(var); attrs.add(index + 1, irFty.arg_sret->attrs); @@ -664,8 +678,9 @@ private: bool delegatecall = (calleeType->toBasetype()->ty == Tdelegate); bool nestedcall = irFty.arg_nest; - if (!thiscall && !delegatecall && !nestedcall) + if (!thiscall && !delegatecall && !nestedcall) { return; + } size_t index = args.size(); LLType *llArgType = *(llArgTypesBegin + index); @@ -687,10 +702,11 @@ private: } else if (delegatecall) { // ... or a delegate context arg LLValue *ctxarg; - if (fnval->isLVal()) + if (fnval->isLVal()) { ctxarg = DtoLoad(DtoGEPi(fnval->getLVal(), 0, 0), ".ptr"); - else + } else { ctxarg = gIR->ir->CreateExtractValue(fnval->getRVal(), 0, ".ptr"); + } ctxarg = DtoBitCast(ctxarg, llArgType); args.push_back(ctxarg); } else if (nestedcall) { @@ -699,24 +715,27 @@ private: LLValue *contextptr = DtoNestedContext(loc, dfnval->func); contextptr = DtoBitCast(contextptr, getVoidPtrType()); args.push_back(contextptr); - } else + } else { args.push_back(llvm::UndefValue::get(getVoidPtrType())); + } } else { error(loc, "Context argument required but none given"); fatal(); } // add attributes - if (irFty.arg_this) + if (irFty.arg_this) { attrs.add(index + 1, irFty.arg_this->attrs); - else if (irFty.arg_nest) + } else if (irFty.arg_nest) { attrs.add(index + 1, irFty.arg_nest->attrs); + } } // D vararg functions need a "TypeInfo[] _arguments" argument. void addArguments() { - if (!irFty.arg_arguments) + if (!irFty.arg_arguments) { return; + } int numFormalParams = Parameter::dim(tf->parameters); LLValue *argumentsArg = @@ -748,8 +767,9 @@ DValue *DtoCallFunction(Loc &loc, Type *resulttype, DValue *fnval, Type *const returntype = tf->next; const TY returnTy = returntype->toBasetype()->ty; - if (resulttype == NULL) + if (resulttype == nullptr) { resulttype = returntype; + } // get callee llvm value LLValue *const callable = DtoCallableValue(fnval); @@ -781,8 +801,8 @@ DValue *DtoCallFunction(Loc &loc, Type *resulttype, DValue *fnval, IF_LOG { Logger::println("Arguments so far: (%d)", static_cast(args.size())); Logger::indent(); - for (size_t i = 0; i < args.size(); i++) { - Logger::cout() << *args[i] << '\n'; + for (auto &arg : args) { + Logger::cout() << *arg << '\n'; } Logger::undent(); Logger::cout() << "Function type: " << tf->toChars() << '\n'; @@ -793,7 +813,7 @@ DValue *DtoCallFunction(Loc &loc, Type *resulttype, DValue *fnval, const size_t n_arguments = arguments ? arguments->dim : 0; // number of explicit arguments - std::vector argvals(n_arguments, static_cast(0)); + std::vector argvals(n_arguments, static_cast(nullptr)); if (dfnval && dfnval->func->isArrayOp) { // For array ops, the druntime implementation signatures are crafted // specifically such that the evaluation order is as expected with @@ -814,8 +834,9 @@ DValue *DtoCallFunction(Loc &loc, Type *resulttype, DValue *fnval, } } // add varargs - for (size_t i = numFormalParams; i < n_arguments; ++i) - argvals[i] = DtoArgument(0, (*arguments)[i]); + for (size_t i = numFormalParams; i < n_arguments; ++i) { + argvals[i] = DtoArgument(nullptr, (*arguments)[i]); + } addExplicitArguments(args, attrs, irFty, callableTy, argvals, numFormalParams); @@ -875,10 +896,11 @@ DValue *DtoCallFunction(Loc &loc, Type *resulttype, DValue *fnval, returntype->toChars(), rbase->toChars()); switch (rbase->ty) { case Tarray: - if (tf->isref) + if (tf->isref) { retllval = DtoBitCast(retllval, DtoType(rbase->pointerTo())); - else + } else { retllval = DtoAggrPaint(retllval, DtoType(rbase)); + } break; case Tsarray: @@ -888,10 +910,11 @@ DValue *DtoCallFunction(Loc &loc, Type *resulttype, DValue *fnval, case Tclass: case Taarray: case Tpointer: - if (tf->isref) + if (tf->isref) { retllval = DtoBitCast(retllval, DtoType(rbase->pointerTo())); - else + } else { retllval = DtoBitCast(retllval, DtoType(rbase)); + } break; case Tstruct: @@ -979,8 +1002,9 @@ DValue *DtoCallFunction(Loc &loc, Type *resulttype, DValue *fnval, // if we are returning through a pointer arg // or if we are returning a reference // make sure we provide a lvalue back! - if (retinptr || (tf->isref && returnTy != Tvoid) || retValIsAlloca) + if (retinptr || (tf->isref && returnTy != Tvoid) || retValIsAlloca) { return new DVarValue(resulttype, retllval); + } return new DImValue(resulttype, retllval); } diff --git a/gen/toconstelem.cpp b/gen/toconstelem.cpp index e6905efa48..8281a83d8b 100644 --- a/gen/toconstelem.cpp +++ b/gen/toconstelem.cpp @@ -37,7 +37,7 @@ class ToConstElemVisitor : public Visitor { LLConstant *result; public: - ToConstElemVisitor(IRState *p_) : p(p_) {} + explicit ToConstElemVisitor(IRState *p_) : p(p_) {} // Import all functions from class Visitor using Visitor::visit; @@ -45,14 +45,14 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// LLConstant *toConstElem(Expression *e) { - result = 0; + result = nullptr; e->accept(this); return result; } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(VarExp *e) { + void visit(VarExp *e) override { IF_LOG Logger::print("VarExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -71,8 +71,9 @@ public: if (TypeInfoDeclaration *ti = e->var->isTypeInfoDeclaration()) { LLType *vartype = DtoType(e->type); result = DtoTypeInfoOf(ti->tinfo, false); - if (result->getType() != getPtrToType(vartype)) + if (result->getType() != getPtrToType(vartype)) { result = llvm::ConstantExpr::getBitCast(result, vartype); + } return; } @@ -97,19 +98,19 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(IntegerExp *e) { + void visit(IntegerExp *e) override { IF_LOG Logger::print("IntegerExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; LLType *t = DtoType(e->type); if (isaPointer(t)) { Logger::println("pointer"); - LLConstant *i = - LLConstantInt::get(DtoSize_t(), (uint64_t)e->getInteger(), false); + LLConstant *i = LLConstantInt::get( + DtoSize_t(), static_cast(e->getInteger()), false); result = llvm::ConstantExpr::getIntToPtr(i, t); } else { assert(llvm::isa(t)); - result = LLConstantInt::get(t, (uint64_t)e->getInteger(), + result = LLConstantInt::get(t, static_cast(e->getInteger()), !e->type->isunsigned()); assert(result); IF_LOG Logger::cout() << "value = " << *result << '\n'; @@ -118,7 +119,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(RealExp *e) { + void visit(RealExp *e) override { IF_LOG Logger::print("RealExp::toConstElem: %s @ %s | %La\n", e->toChars(), e->type->toChars(), e->value); LOG_SCOPE; @@ -128,7 +129,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(NullExp *e) { + void visit(NullExp *e) override { IF_LOG Logger::print("NullExp::toConstElem(type=%s): %s\n", e->type->toChars(), e->toChars()); LOG_SCOPE; @@ -143,7 +144,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(ComplexExp *e) { + void visit(ComplexExp *e) override { IF_LOG Logger::print("ComplexExp::toConstElem(): %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -152,7 +153,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(StringExp *e) { + void visit(StringExp *e) override { IF_LOG Logger::print("StringExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -166,7 +167,7 @@ public: LLType *ct = DtoMemType(cty); LLArrayType *at = LLArrayType::get(ct, endlen); - llvm::StringMap *stringLiteralCache = 0; + llvm::StringMap *stringLiteralCache = nullptr; LLConstant *_init; switch (cty->size()) { default: @@ -196,9 +197,9 @@ public: llvm::StringRef key(e->toChars()); llvm::GlobalVariable *gvar = (stringLiteralCache->find(key) == stringLiteralCache->end()) - ? 0 + ? nullptr : (*stringLiteralCache)[key]; - if (gvar == 0) { + if (gvar == nullptr) { llvm::GlobalValue::LinkageTypes _linkage = llvm::GlobalValue::PrivateLinkage; gvar = new llvm::GlobalVariable(gIR->module, _init->getType(), true, @@ -229,7 +230,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(AddExp *e) { + void visit(AddExp *e) override { IF_LOG Logger::print("AddExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -247,13 +248,14 @@ public: #endif } else { e->error("expression '%s' is not a constant", e->toChars()); - if (!global.gag) + if (!global.gag) { fatal(); + } result = llvm::UndefValue::get(DtoType(e->type)); } } - void visit(MinExp *e) { + void visit(MinExp *e) override { IF_LOG Logger::print("MinExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -272,15 +274,16 @@ public: #endif } else { e->error("expression '%s' is not a constant", e->toChars()); - if (!global.gag) + if (!global.gag) { fatal(); + } result = llvm::UndefValue::get(DtoType(e->type)); } } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(CastExp *e) { + void visit(CastExp *e) override { IF_LOG Logger::print("CastExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -315,9 +318,10 @@ public: assert(vd); DtoResolveVariable(vd); LLConstant *value = - isIrGlobalCreated(vd) ? isaConstant(getIrGlobal(vd)->value) : 0; - if (!value) + isIrGlobalCreated(vd) ? isaConstant(getIrGlobal(vd)->value) : nullptr; + if (!value) { goto Lerr; + } Type *type = vd->type->toBasetype(); if (type->ty == Tarray || type->ty == Tdelegate) { LLConstant *idxs[2] = {DtoConstSize_t(0), DtoConstSize_t(1)}; @@ -357,20 +361,21 @@ public: Lerr: e->error("cannot cast %s to %s at compile time", e->e1->type->toChars(), e->type->toChars()); - if (!global.gag) + if (!global.gag) { fatal(); + } result = llvm::UndefValue::get(DtoType(e->type)); } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(SymOffExp *e) { + void visit(SymOffExp *e) override { IF_LOG Logger::println("SymOffExp::toConstElem: %s @ %s", e->toChars(), e->type->toChars()); LOG_SCOPE; llvm::Constant *base = DtoConstSymbolAddress(e->loc, e->var); - if (base == 0) { + if (base == nullptr) { result = llvm::UndefValue::get(DtoType(e->type)); return; } @@ -408,7 +413,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(AddrExp *e) { + void visit(AddrExp *e) override { IF_LOG Logger::println("AddrExp::toConstElem: %s @ %s", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -419,7 +424,7 @@ public: if (e->e1->op == TOKvar) { VarExp *vexp = static_cast(e->e1); LLConstant *c = DtoConstSymbolAddress(e->loc, vexp->var); - result = c ? DtoBitCast(c, DtoType(e->type)) : 0; + result = c ? DtoBitCast(c, DtoType(e->type)) : nullptr; } // address of indexExp else if (e->e1->op == TOKindex) { @@ -464,14 +469,14 @@ public: se->globalVar = new llvm::GlobalVariable( p->module, DtoType(e->e1->type), false, - llvm::GlobalValue::InternalLinkage, 0, ".structliteral"); + llvm::GlobalValue::InternalLinkage, nullptr, ".structliteral"); llvm::Constant *constValue = toConstElem(se); if (constValue->getType() != se->globalVar->getType()->getContainedType(0)) { - llvm::GlobalVariable *finalGlobalVar = new llvm::GlobalVariable( + auto finalGlobalVar = new llvm::GlobalVariable( p->module, constValue->getType(), false, - llvm::GlobalValue::InternalLinkage, 0, ".structliteral"); + llvm::GlobalValue::InternalLinkage, nullptr, ".structliteral"); se->globalVar->replaceAllUsesWith( DtoBitCast(finalGlobalVar, se->globalVar->getType())); se->globalVar->eraseFromParent(); @@ -483,8 +488,9 @@ public: result = se->globalVar; } else if (e->e1->op == TOKslice) { e->error("non-constant expression '%s'", e->toChars()); - if (!global.gag) + if (!global.gag) { fatal(); + } result = llvm::UndefValue::get(DtoType(e->type)); } // not yet supported @@ -496,7 +502,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(FuncExp *e) { + void visit(FuncExp *e) override { IF_LOG Logger::print("FuncExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -510,15 +516,16 @@ public: // Horrible hack, but DMD does the same thing in FuncExp::toElem and // other random places. fd->tok = TOKfunction; - fd->vthis = NULL; + fd->vthis = nullptr; } if (fd->tok != TOKfunction) { assert(fd->tok == TOKdelegate || fd->tok == TOKreserved); e->error("non-constant nested delegate literal expression %s", e->toChars()); - if (!global.gag) + if (!global.gag) { fatal(); + } result = llvm::UndefValue::get(DtoType(e->type)); } else { // We need to actually codegen the function here, as literals are not @@ -533,7 +540,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(ArrayLiteralExp *e) { + void visit(ArrayLiteralExp *e) override { IF_LOG Logger::print("ArrayLiteralExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -558,7 +565,7 @@ public: } bool canBeConst = e->type->isConst() || e->type->isImmutable(); - llvm::GlobalVariable *gvar = new llvm::GlobalVariable( + auto gvar = new llvm::GlobalVariable( gIR->module, initval->getType(), canBeConst, llvm::GlobalValue::InternalLinkage, initval, ".dynarrayStorage"); gvar->setUnnamedAddr(canBeConst); @@ -586,7 +593,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(StructLiteralExp *e) { + void visit(StructLiteralExp *e) override { // type can legitimately be null for ClassReferenceExp::value. IF_LOG Logger::print("StructLiteralExp::toConstElem: %s @ %s\n", e->toChars(), e->type ? e->type->toChars() : "(null)"); @@ -619,7 +626,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(ClassReferenceExp *e) { + void visit(ClassReferenceExp *e) override { IF_LOG Logger::print("ClassReferenceExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -634,7 +641,7 @@ public: } else { value->globalVar = new llvm::GlobalVariable( p->module, origClass->type->ctype->isClass()->getMemoryLLType(), - false, llvm::GlobalValue::InternalLinkage, 0, ".classref"); + false, llvm::GlobalValue::InternalLinkage, nullptr, ".classref"); std::map varInits; @@ -672,9 +679,9 @@ public: if (constValue->getType() != value->globalVar->getType()->getContainedType(0)) { - llvm::GlobalVariable *finalGlobalVar = new llvm::GlobalVariable( + auto finalGlobalVar = new llvm::GlobalVariable( p->module, constValue->getType(), false, - llvm::GlobalValue::InternalLinkage, 0, ".classref"); + llvm::GlobalValue::InternalLinkage, nullptr, ".classref"); value->globalVar->replaceAllUsesWith( DtoBitCast(finalGlobalVar, value->globalVar->getType())); value->globalVar->eraseFromParent(); @@ -707,7 +714,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(VectorExp *e) { + void visit(VectorExp *e) override { IF_LOG Logger::print("VectorExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -733,7 +740,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(TypeidExp *e) { + void visit(TypeidExp *e) override { IF_LOG Logger::print("TypeidExp::toConstElem: %s @ %s\n", e->toChars(), e->type->toChars()); @@ -743,17 +750,18 @@ public: return; } - TypeInfoDeclaration *tid = getOrCreateTypeInfoDeclaration(t, NULL); + TypeInfoDeclaration *tid = getOrCreateTypeInfoDeclaration(t, nullptr); TypeInfoDeclaration_codegen(tid, p); result = llvm::cast(getIrGlobal(tid)->value); } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(Expression *e) { + void visit(Expression *e) override { e->error("expression '%s' is not a constant", e->toChars()); - if (!global.gag) + if (!global.gag) { fatal(); + } // Do not return null here, as AssocArrayLiteralExp::toElem determines // whether it can allocate the needed arrays statically by just invoking diff --git a/gen/toir.cpp b/gen/toir.cpp index 3aeb673d14..504033eab1 100644 --- a/gen/toir.cpp +++ b/gen/toir.cpp @@ -98,7 +98,7 @@ static void write_struct_literal(Loc loc, LLValue *mem, StructDeclaration *sd, VarDeclaration *vd = sd->fields[index]; // get initializer expression - Expression *expr = (index < nexprs) ? exprs[index] : NULL; + Expression *expr = (index < nexprs) ? exprs[index] : nullptr; if (!expr) { // In case of an union, we can't simply use the default initializer. // Consider the type union U7727A1 { int i; double d; } and @@ -108,10 +108,11 @@ static void write_struct_literal(Loc loc, LLValue *mem, StructDeclaration *sd, // peek at the next variables. for (size_t index2 = index + 1; index2 < nfields; ++index2) { VarDeclaration *vd2 = sd->fields[index2]; - if (vd->offset != vd2->offset) + if (vd->offset != vd2->offset) { break; + } ++index; // skip var - Expression *expr2 = (index2 < nexprs) ? exprs[index2] : NULL; + Expression *expr2 = (index2 < nexprs) ? exprs[index2] : nullptr; if (expr2) { vd = vd2; expr = expr2; @@ -128,8 +129,9 @@ static void write_struct_literal(Loc loc, LLValue *mem, StructDeclaration *sd, } // initialize any padding so struct comparisons work - if (vd->offset != offset) + if (vd->offset != offset) { voidptr = write_zeroes(voidptr, offset, vd->offset); + } offset = vd->offset + vd->type->size(); IF_LOG Logger::println("initializing field: %s %s (+%u)", @@ -139,7 +141,7 @@ static void write_struct_literal(Loc loc, LLValue *mem, StructDeclaration *sd, // get initializer DValue *val; DConstValue cv(vd->type, - NULL); // Only used in one branch; value is set beforehand + nullptr); // Only used in one branch; value is set beforehand if (expr) { IF_LOG Logger::println("expr %llu = %s", static_cast(index), @@ -151,11 +153,12 @@ static void write_struct_literal(Loc loc, LLValue *mem, StructDeclaration *sd, val = new DImValue( vd->type, DtoBitCast(DtoNestedContext(loc, sd), DtoType(vd->type))); } else { - if (vd->init && vd->init->isVoidInitializer()) + if (vd->init && vd->init->isVoidInitializer()) { continue; + } IF_LOG Logger::println("using default initializer"); LOG_SCOPE - cv.c = get_default_initializer(vd, NULL); + cv.c = get_default_initializer(vd, nullptr); val = &cv; } @@ -165,8 +168,9 @@ static void write_struct_literal(Loc loc, LLValue *mem, StructDeclaration *sd, // store the initializer there DtoAssign(loc, &field, val, TOKconstruct, true); - if (expr && expr->isLvalue()) + if (expr && expr->isLvalue()) { callPostblit(loc, expr, field.getLVal()); + } // Also zero out padding bytes counted as being part of the type in DMD // but not in LLVM; e.g. real/x86_fp80. @@ -179,8 +183,9 @@ static void write_struct_literal(Loc loc, LLValue *mem, StructDeclaration *sd, } } // initialize trailing padding - if (sd->structsize != offset) + if (sd->structsize != offset) { voidptr = write_zeroes(voidptr, offset, sd->structsize); + } } namespace { @@ -207,7 +212,7 @@ static Expression *findLvalueExp(Expression *e) { public: Expression *result; - FindLvalueVisitor() : result(NULL) {} + FindLvalueVisitor() : result(nullptr) {} void visit(Expression *e) LLVM_OVERRIDE {} @@ -246,13 +251,14 @@ static DValue *toElemAndCacheLvalue(Expression *e) { // (casted) nested lvalue if one is found. // Otherwise simply returns the expression's result. DValue *toElem(Expression *e, bool tryGetLvalue) { - if (!tryGetLvalue) + if (!tryGetLvalue) { return toElem(e); + } Expression *lvalExp = findLvalueExp(e); // may be null - Expression *nestedLvalExp = (lvalExp == e ? NULL : lvalExp); + Expression *nestedLvalExp = (lvalExp == e ? nullptr : lvalExp); - DValue *nestedLval = NULL; + DValue *nestedLval = nullptr; if (nestedLvalExp) { IF_LOG Logger::println("Caching l-value of %s => %s", e->toChars(), nestedLvalExp->toChars()); @@ -263,8 +269,9 @@ DValue *toElem(Expression *e, bool tryGetLvalue) { DValue *value = toElem(e); - if (nestedLvalExp) - nestedLvalExp->cachedLvalue = NULL; + if (nestedLvalExp) { + nestedLvalExp->cachedLvalue = nullptr; + } return !nestedLval ? value : DtoCast(e->loc, nestedLval, e->type); } @@ -279,7 +286,7 @@ class ToElemVisitor : public Visitor { public: ToElemVisitor(IRState *p_, bool destructTemporaries_) - : p(p_), destructTemporaries(destructTemporaries_), result(NULL) { + : p(p_), destructTemporaries(destructTemporaries_), result(nullptr) { initialCleanupScope = p->func()->scopes->currentCleanupScope(); } @@ -314,7 +321,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(DeclarationExp *e) { + void visit(DeclarationExp *e) override { IF_LOG Logger::print("DeclarationExp::toElem: %s | T=%s\n", e->toChars(), e->type ? e->type->toChars() : "(null)"); LOG_SCOPE; @@ -333,7 +340,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(VarExp *e) { + void visit(VarExp *e) override { IF_LOG Logger::print("VarExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -351,7 +358,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(IntegerExp *e) { + void visit(IntegerExp *e) override { IF_LOG Logger::print("IntegerExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -361,7 +368,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(RealExp *e) { + void visit(RealExp *e) override { IF_LOG Logger::print("RealExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -371,7 +378,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(NullExp *e) { + void visit(NullExp *e) override { IF_LOG Logger::print("NullExp::toElem(type=%s): %s\n", e->type->toChars(), e->toChars()); LOG_SCOPE; @@ -381,7 +388,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(ComplexExp *e) { + void visit(ComplexExp *e) override { IF_LOG Logger::print("ComplexExp::toElem(): %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -412,7 +419,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(StringExp *e) { + void visit(StringExp *e) override { IF_LOG Logger::print("StringExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -423,7 +430,7 @@ public: LLType *ct = DtoMemType(cty); LLArrayType *at = LLArrayType::get(ct, e->len + 1); - llvm::StringMap *stringLiteralCache = 0; + llvm::StringMap *stringLiteralCache = nullptr; LLConstant *_init; switch (cty->size()) { default: @@ -448,9 +455,9 @@ public: llvm::StringRef key(e->toChars()); llvm::GlobalVariable *gvar = (stringLiteralCache->find(key) == stringLiteralCache->end()) - ? 0 + ? nullptr : (*stringLiteralCache)[key]; - if (gvar == 0) { + if (gvar == nullptr) { llvm::GlobalValue::LinkageTypes _linkage = llvm::GlobalValue::PrivateLinkage; IF_LOG { @@ -490,11 +497,11 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(AssignExp *e) { + void visit(AssignExp *e) override { IF_LOG Logger::print("AssignExp::toElem: %s | (%s)(%s = %s)\n", e->toChars(), e->type->toChars(), e->e1->type->toChars(), - e->e2->type ? e->e2->type->toChars() : 0); + e->e2->type ? e->e2->type->toChars() : nullptr); LOG_SCOPE; if (e->e1->op == TOKarraylength) { @@ -543,7 +550,7 @@ public: Type *const t2 = e->e2->type->toBasetype(); Type *const ta = se->e1->type->toBasetype(); - if (se->lwr == NULL && ta->ty == Tsarray && + if (se->lwr == nullptr && ta->ty == Tsarray && e->e2->op == TOKarrayliteral && e->op == TOKconstruct && // DMD Bugzilla 11238: avoid aliasing issue t2->nextOf()->mutableOf()->implicitConvTo(ta->nextOf())) { @@ -574,8 +581,9 @@ public: assert(e->e2->toInteger() == 0); DtoAggrZeroInit(l->getLVal()); TypeStruct *ts = static_cast(e->e1->type); - if (ts->sym->isNested() && ts->sym->vthis) + if (ts->sym->isNested() && ts->sym->vthis) { DtoResolveNestedContext(e->loc, ts->sym, l->getLVal()); + } // Return value should be irrelevant. result = r; return; @@ -614,7 +622,7 @@ public: } // pre-evaluate and cache the lvalue subexpression - DValue *lval = NULL; + DValue *lval = nullptr; { IF_LOG Logger::println("Caching l-value of %s => %s", e->toChars(), lvalExp->toChars()); @@ -629,7 +637,7 @@ public: binExp.type = lhsForBinExp->type; DValue *result = toElem(&binExp); - lvalExp->cachedLvalue = NULL; + lvalExp->cachedLvalue = nullptr; // assign the (casted) result to lval DValue *assignedResult = DtoCast(loc, result, lval->type); @@ -693,15 +701,17 @@ public: break; } - return NULL; + return nullptr; } - if (!mul->e2->isConst()) - return NULL; + if (!mul->e2->isConst()) { + return nullptr; + } dinteger_t stride = mul->e2->toInteger(); - if (stride != baseSize) - return NULL; + if (stride != baseSize) { + return nullptr; + } return mul->e1; } @@ -713,7 +723,7 @@ public: // pointer elements. We try to undo this before resorting to // temporarily bitcasting the pointer to i8. - llvm::Value *noStrideInc = NULL; + llvm::Value *noStrideInc = nullptr; if (offset->isConst()) { dinteger_t byteOffset = offset->toInteger(); if (byteOffset == 0) { @@ -727,8 +737,9 @@ public: } if (noStrideInc) { - if (negateOffset) + if (negateOffset) { noStrideInc = p->ir->CreateNeg(noStrideInc); + } return new DImValue( base->type, DtoGEP1(base->getRVal(), noStrideInc, "", p->scopebb())); } @@ -736,14 +747,15 @@ public: // This might not actually be generated by the frontend, just to be // safe. llvm::Value *inc = toElem(offset)->getRVal(); - if (negateOffset) + if (negateOffset) { inc = p->ir->CreateNeg(inc); + } llvm::Value *bytePtr = DtoBitCast(base->getRVal(), getVoidPtrType()); DValue *result = new DImValue(Type::tvoidptr, DtoGEP1(bytePtr, inc)); return DtoCast(loc, result, resultType); } - void visit(AddExp *e) { + void visit(AddExp *e) override { IF_LOG Logger::print("AddExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -766,7 +778,7 @@ public: } } - void visit(MinExp *e) { + void visit(MinExp *e) override { IF_LOG Logger::print("MinExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -786,8 +798,9 @@ public: lv = p->ir->CreatePtrToInt(lv, DtoSize_t()); rv = p->ir->CreatePtrToInt(rv, DtoSize_t()); LLValue *diff = p->ir->CreateSub(lv, rv); - if (diff->getType() != DtoType(e->type)) + if (diff->getType() != DtoType(e->type)) { diff = p->ir->CreateIntToPtr(diff, DtoType(e->type)); + } result = new DImValue(e->type, diff); } else if (t1->ty == Tpointer && t2->isintegral()) { Logger::println("Subtracting integer from pointer"); @@ -801,7 +814,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(MulExp *e) { + void visit(MulExp *e) override { IF_LOG Logger::print("MulExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -811,15 +824,16 @@ public: errorOnIllegalArrayOp(e, e->e1, e->e2); - if (e->type->iscomplex()) + if (e->type->iscomplex()) { result = DtoComplexMul(e->loc, e->type, l, r); - else + } else { result = DtoBinMul(e->type, l, r); + } } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(DivExp *e) { + void visit(DivExp *e) override { IF_LOG Logger::print("DivExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -829,15 +843,16 @@ public: errorOnIllegalArrayOp(e, e->e1, e->e2); - if (e->type->iscomplex()) + if (e->type->iscomplex()) { result = DtoComplexDiv(e->loc, e->type, l, r); - else + } else { result = DtoBinDiv(e->type, l, r); + } } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(ModExp *e) { + void visit(ModExp *e) override { IF_LOG Logger::print("ModExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -847,15 +862,16 @@ public: errorOnIllegalArrayOp(e, e->e1, e->e2); - if (e->type->iscomplex()) + if (e->type->iscomplex()) { result = DtoComplexRem(e->loc, e->type, l, r); - else + } else { result = DtoBinRem(e->type, l, r); + } } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(CallExp *e) { + void visit(CallExp *e) override { IF_LOG Logger::print("CallExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -887,8 +903,8 @@ public: // The correct fix for this (DMD issue 13095) would have been to adapt // the AST, but we are stuck with this as DMD also patched over it with // a similar hack. - VarDeclaration *delayedDtorVar = NULL; - Expression *delayedDtorExp = NULL; + VarDeclaration *delayedDtorVar = nullptr; + Expression *delayedDtorExp = nullptr; if (e->f && e->f->isCtorDeclaration() && e->e1->op == TOKdotvar) { DotVarExp *dve = static_cast(e->e1); if (dve->e1->op == TOKcomma) { @@ -900,7 +916,7 @@ public: Logger::println("Delaying edtor"); delayedDtorVar = vd; delayedDtorExp = vd->edtor; - vd->edtor = NULL; + vd->edtor = nullptr; } } } @@ -938,8 +954,9 @@ public: } } - if (DtoLowerMagicIntrinsic(p, fndecl, e, result)) + if (DtoLowerMagicIntrinsic(p, fndecl, e, result)) { return; + } } result = DtoCallFunction(e->loc, e->type, fnval, e->arguments); @@ -952,7 +969,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(CastExp *e) { + void visit(CastExp *e) override { IF_LOG Logger::print("CastExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -970,17 +987,19 @@ public: // cast it to the 'to' type, if necessary result = u; - if (!e->to->equals(e->e1->type)) + if (!e->to->equals(e->e1->type)) { result = DtoCast(e->loc, u, e->to); + } // paint the type, if necessary - if (!e->type->equals(e->to)) + if (!e->type->equals(e->to)) { result = DtoPaintType(e->loc, result, e->type); + } } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(SymOffExp *e) { + void visit(SymOffExp *e) override { IF_LOG Logger::print("SymOffExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -992,10 +1011,11 @@ public: // as well due to the level-of-indirection hack in Type::getTypeInfo that // is unfortunately required by the frontend). llvm::Value *baseValue; - if (base->isLVal()) + if (base->isLVal()) { baseValue = base->getLVal(); - else + } else { baseValue = base->getRVal(); + } assert(isaPointer(baseValue)); llvm::Value *offsetValue; @@ -1026,7 +1046,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(AddrExp *e) { + void visit(AddrExp *e) override { IF_LOG Logger::println("AddrExp::toElem: %s @ %s", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1066,9 +1086,9 @@ public: // we special case here, since apparently taking the address of a slice is // ok LLValue *lval; - if (v->isLVal()) + if (v->isLVal()) { lval = v->getLVal(); - else { + } else { assert(v->isSlice()); lval = DtoAllocaDump(v, ".tmp_slice_storage"); } @@ -1079,7 +1099,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(PtrExp *e) { + void visit(PtrExp *e) override { IF_LOG Logger::println("PtrExp::toElem: %s @ %s", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1088,10 +1108,11 @@ public: if (e->type->toBasetype()->ty == Tfunction) { assert(!e->cachedLvalue); DValue *dv = toElem(e->e1); - if (DFuncValue *dfv = dv->isFunc()) + if (DFuncValue *dfv = dv->isFunc()) { result = new DFuncValue(e->type, dfv->func, dfv->getRVal()); - else + } else { result = new DImValue(e->type, dv->getRVal()); + } return; } @@ -1127,7 +1148,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(DotVarExp *e) { + void visit(DotVarExp *e) override { IF_LOG Logger::print("DotVarExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1165,8 +1186,9 @@ public: else if (e1type->ty == Tclass) { TypeClass *tc = static_cast(e1type); arrptr = DtoIndexAggregate(l->getRVal(), tc->sym, vd); - } else + } else { llvm_unreachable("Unknown DotVarExp type for VarDeclaration."); + } // Logger::cout() << "mem: " << *arrptr << '\n'; result = new DVarValue(e->type, vd, arrptr); @@ -1182,7 +1204,7 @@ public: fdecl->prot().kind != PROTprivate; // Get the actual function value to call. - LLValue *funcval = 0; + LLValue *funcval = nullptr; if (nonFinal) { DImValue thisVal(e1type, l->getRVal()); funcval = DtoVirtualFunctionPointer(&thisVal, fdecl, e->toChars()); @@ -1199,7 +1221,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(ThisExp *e) { + void visit(ThisExp *e) override { IF_LOG Logger::print("ThisExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1238,7 +1260,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(IndexExp *e) { + void visit(IndexExp *e) override { IF_LOG Logger::print("IndexExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1259,16 +1281,18 @@ public: LLValue *zero = DtoConstUint(0); - LLValue *arrptr = 0; + LLValue *arrptr = nullptr; if (e1type->ty == Tpointer) { arrptr = DtoGEP1(l->getRVal(), r->getRVal()); } else if (e1type->ty == Tsarray) { - if (p->emitArrayBoundsChecks() && !e->indexIsInBounds) + if (p->emitArrayBoundsChecks() && !e->indexIsInBounds) { DtoIndexBoundsCheck(e->loc, l, r); + } arrptr = DtoGEP(l->getRVal(), zero, r->getRVal()); } else if (e1type->ty == Tarray) { - if (p->emitArrayBoundsChecks() && !e->indexIsInBounds) + if (p->emitArrayBoundsChecks() && !e->indexIsInBounds) { DtoIndexBoundsCheck(e->loc, l, r); + } arrptr = DtoArrayPtr(l); arrptr = DtoGEP1(arrptr, r->getRVal()); } else if (e1type->ty == Taarray) { @@ -1283,7 +1307,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(SliceExp *e) { + void visit(SliceExp *e) override { IF_LOG Logger::print("SliceExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1295,7 +1319,7 @@ public: // now all slices have *both* the 'len' and 'ptr' fields set to != null. // value being sliced - LLValue *elen = 0; + LLValue *elen = nullptr; LLValue *eptr; DValue *v = toElem(e->e1); @@ -1332,7 +1356,7 @@ public: llvm::BasicBlock *okbb = llvm::BasicBlock::Create(p->context(), "bounds.ok", p->topfunc()); - llvm::Value *okCond = NULL; + llvm::Value *okCond = nullptr; if (needCheckUpper) { okCond = p->ir->CreateICmp(llvm::ICmpInst::ICMP_ULE, vup, DtoArrayLen(v), "bounds.cmp.lo"); @@ -1341,10 +1365,11 @@ public: if (needCheckLower) { llvm::Value *cmp = p->ir->CreateICmp(llvm::ICmpInst::ICMP_ULE, vlo, vup, "bounds.cmp.up"); - if (okCond) + if (okCond) { okCond = p->ir->CreateAnd(okCond, cmp); - else + } else { okCond = cmp; + } } p->ir->CreateCondBr(okCond, okbb, failbb); @@ -1387,14 +1412,15 @@ public: return; } - if (!elen) + if (!elen) { elen = DtoArrayLen(v); + } result = new DSliceValue(e->type, elen, eptr); } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(CmpExp *e) { + void visit(CmpExp *e) override { IF_LOG Logger::print("CmpExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1404,7 +1430,7 @@ public: Type *t = e->e1->type->toBasetype(); - LLValue *eval = 0; + LLValue *eval = nullptr; if (t->isintegral() || t->ty == Tpointer || t->ty == Tnull) { llvm::ICmpInst::Predicate icmpPred; @@ -1417,8 +1443,9 @@ public: Logger::cout() << "type 1: " << *a << '\n'; Logger::cout() << "type 2: " << *b << '\n'; } - if (a->getType() != b->getType()) + if (a->getType() != b->getType()) { b = DtoBitCast(b, a->getType()); + } eval = p->ir->CreateICmp(icmpPred, a, b); } } else if (t->isfloating()) { @@ -1521,7 +1548,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(EqualExp *e) { + void visit(EqualExp *e) override { IF_LOG Logger::print("EqualExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1533,7 +1560,7 @@ public: Type *t = e->e1->type->toBasetype(); - LLValue *eval = 0; + LLValue *eval = nullptr; // the Tclass catches interface comparisons, regular // class equality should be rewritten as a.opEquals(b) by this time @@ -1584,7 +1611,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(PostExp *e) { + void visit(PostExp *e) override { IF_LOG Logger::print("PostExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1593,7 +1620,7 @@ public: toElem(e->e2); LLValue *val = l->getRVal(); - LLValue *post = 0; + LLValue *post = nullptr; Type *e1type = e->e1->type->toBasetype(); Type *e2type = e->e2->type->toBasetype(); @@ -1610,12 +1637,13 @@ public: } else if (e1type->ty == Tpointer) { assert(e->e2->op == TOKint64); LLConstant *offset; - if (e->op == TOKplusplus) + if (e->op == TOKplusplus) { offset = LLConstantInt::get(DtoSize_t(), static_cast(1), false); - else + } else { offset = LLConstantInt::get(DtoSize_t(), static_cast(-1), true); + } post = llvm::GetElementPtrInst::Create( #if LDC_LLVM_VER >= 307 isaPointer(val)->getElementType(), @@ -1629,8 +1657,9 @@ public: } else if (e->op == TOKminusminus) { post = llvm::BinaryOperator::CreateFSub(val, one, "", p->scopebb()); } - } else + } else { assert(post); + } DtoStore(post, l->getLVal()); result = new DImValue(e->type, val); @@ -1638,7 +1667,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(NewExp *e) { + void visit(NewExp *e) override { IF_LOG Logger::print("NewExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1669,8 +1698,9 @@ public: size_t ndims = e->arguments->dim; std::vector dims; dims.reserve(ndims); - for (size_t i = 0; i < ndims; ++i) + for (size_t i = 0; i < ndims; ++i) { dims.push_back(toElem((*e->arguments)[i])); + } result = DtoNewMulDimDynArray(e->loc, e->newtype, &dims[0], ndims); } } @@ -1685,12 +1715,12 @@ public: TypeStruct *ts = static_cast(ntype); // allocate - LLValue *mem = 0; + LLValue *mem = nullptr; if (e->allocator) { // custom allocator DtoResolveFunction(e->allocator); DFuncValue dfn(e->allocator, getIrFunc(e->allocator)->func); - DValue *res = DtoCallFunction(e->loc, NULL, &dfn, e->newargs); + DValue *res = DtoCallFunction(e->loc, nullptr, &dfn, e->newargs); mem = DtoBitCast(res->getRVal(), DtoType(ntype->pointerTo()), ".newstruct_custom"); } else { @@ -1703,8 +1733,9 @@ public: write_struct_literal(e->loc, mem, ts->sym, e->arguments); } else { // set nested context - if (ts->sym->isNested() && ts->sym->vthis) + if (ts->sym->isNested() && ts->sym->vthis) { DtoResolveNestedContext(e->loc, ts->sym, mem); + } // call constructor if (e->member) { @@ -1733,7 +1764,7 @@ public: LLValue *mem = DtoNew(e->loc, e->newtype); DVarValue tmpvar(e->newtype, mem); - Expression *exp = 0; + Expression *exp = nullptr; if (!e->arguments || e->arguments->dim == 0) { IF_LOG Logger::println("default initializer\n"); // static arrays never appear here, so using the defaultInit is ok! @@ -1756,7 +1787,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(DeleteExp *e) { + void visit(DeleteExp *e) override { IF_LOG Logger::print("DeleteExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1767,10 +1798,11 @@ public: // pointer if (et->ty == Tpointer) { Type *elementType = et->nextOf()->toBasetype(); - if (elementType->ty == Tstruct && elementType->needsDestruction()) + if (elementType->ty == Tstruct && elementType->needsDestruction()) { DtoDeleteStruct(e->loc, dval); - else + } else { DtoDeleteMemory(e->loc, dval); + } } // class else if (et->ty == Tclass) { @@ -1786,9 +1818,9 @@ public: } } - if (!onstack) + if (!onstack) { DtoDeleteClass(e->loc, dval); // sets dval to null - else if (dval->isVar()) { + } else if (dval->isVar()) { LLValue *lval = dval->getLVal(); DtoStore(LLConstant::getNullValue(lval->getType()->getContainedType(0)), lval); @@ -1797,8 +1829,9 @@ public: // dyn array else if (et->ty == Tarray) { DtoDeleteArray(e->loc, dval); - if (dval->isLVal()) + if (dval->isLVal()) { DtoSetArrayToNull(dval->getLVal()); + } } // unknown/invalid else { @@ -1808,7 +1841,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(ArrayLengthExp *e) { + void visit(ArrayLengthExp *e) override { IF_LOG Logger::print("ArrayLengthExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1819,7 +1852,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(AssertExp *e) { + void visit(AssertExp *e) override { IF_LOG Logger::print("AssertExp::toElem: %s\n", e->toChars()); LOG_SCOPE; @@ -1827,15 +1860,16 @@ public: // f() == 0 || assert(false) result = new DImValue(e->type, DtoConstBool(false)); - if (!global.params.useAssert) + if (!global.params.useAssert) { return; + } // condition DValue *cond; Type *condty; // special case for dmd generated assert(this); when not in -release mode - if (e->e1->op == TOKthis && static_cast(e->e1)->var == NULL) { + if (e->e1->op == TOKthis && static_cast(e->e1)->var == nullptr) { LLValue *thisarg = p->func()->thisArg; assert(thisarg && "null thisarg, but we're in assert(this) exp;"); LLValue *thisptr = DtoLoad(thisarg); @@ -1866,7 +1900,7 @@ public: * instead of toElem(). */ DtoAssert(p->func()->decl->getModule(), e->loc, - e->msg ? toElemDtor(e->msg) : NULL); + e->msg ? toElemDtor(e->msg) : nullptr); // passed: p->scope() = IRScope(passedbb); @@ -1889,17 +1923,17 @@ public: else if (global.params.useInvariants && condty->ty == Tpointer && condty->nextOf()->ty == Tstruct && (invdecl = static_cast(condty->nextOf()) - ->sym->inv) != NULL) { + ->sym->inv) != nullptr) { Logger::print("calling struct invariant"); DtoResolveFunction(invdecl); DFuncValue invfunc(invdecl, getIrFunc(invdecl)->func, cond->getRVal()); - DtoCallFunction(e->loc, NULL, &invfunc, NULL); + DtoCallFunction(e->loc, nullptr, &invfunc, nullptr); } } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(NotExp *e) { + void visit(NotExp *e) override { IF_LOG Logger::print("NotExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1916,7 +1950,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(AndAndExp *e) { + void visit(AndAndExp *e) override { IF_LOG Logger::print("AndAndExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1937,7 +1971,7 @@ public: emitCoverageLinecountInc(e->e2->loc); DValue *v = toElemDtor(e->e2); - LLValue *vbool = 0; + LLValue *vbool = nullptr; if (v && !v->isFunc() && v->getType() != Type::tvoid) { vbool = DtoCast(e->loc, v, Type::tbool)->getRVal(); } @@ -1946,7 +1980,7 @@ public: llvm::BranchInst::Create(andandend, p->scopebb()); p->scope() = IRScope(andandend); - LLValue *resval = 0; + LLValue *resval = nullptr; if (ubool == vbool || !vbool) { // No need to create a PHI node. resval = ubool; @@ -1965,7 +1999,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(OrOrExp *e) { + void visit(OrOrExp *e) override { IF_LOG Logger::print("OrOrExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -1986,7 +2020,7 @@ public: emitCoverageLinecountInc(e->e2->loc); DValue *v = toElemDtor(e->e2); - LLValue *vbool = 0; + LLValue *vbool = nullptr; if (v && !v->isFunc() && v->getType() != Type::tvoid) { vbool = DtoCast(e->loc, v, Type::tbool)->getRVal(); } @@ -1995,7 +2029,7 @@ public: llvm::BranchInst::Create(ororend, p->scopebb()); p->scope() = IRScope(ororend); - LLValue *resval = 0; + LLValue *resval = nullptr; if (ubool == vbool || !vbool) { // No need to create a PHI node. resval = ubool; @@ -2031,7 +2065,7 @@ public: BinBitExp(And, And) BinBitExp(Or, Or) BinBitExp(Xor, Xor) BinBitExp(Shl, Shl) BinBitExp(Ushr, LShr) - void visit(ShrExp *e) { + void visit(ShrExp *e) override { IF_LOG Logger::print("ShrExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2039,16 +2073,17 @@ public: DValue *v = toElem(e->e2); v = DtoCast(e->loc, v, e->e1->type); LLValue *x; - if (isLLVMUnsigned(e->e1->type)) + if (isLLVMUnsigned(e->e1->type)) { x = p->ir->CreateLShr(u->getRVal(), v->getRVal()); - else + } else { x = p->ir->CreateAShr(u->getRVal(), v->getRVal()); + } result = new DImValue(e->type, x); } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(HaltExp *e) { + void visit(HaltExp *e) override { IF_LOG Logger::print("HaltExp::toElem: %s\n", e->toChars()); LOG_SCOPE; @@ -2069,15 +2104,16 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(DelegateExp *e) { + void visit(DelegateExp *e) override { IF_LOG Logger::print("DelegateExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; - if (e->func->isStatic()) + if (e->func->isStatic()) { e->error("can't take delegate of static function %s, it does not require " "a context ptr", e->func->toChars()); + } LLPointerType *int8ptrty = getPtrToType(LLType::getInt8Ty(gIR->context())); @@ -2103,21 +2139,22 @@ public: LLValue *castfptr; if (e->e1->op != TOKsuper && e->e1->op != TOKdottype && - e->func->isVirtual() && !e->func->isFinalFunc()) + e->func->isVirtual() && !e->func->isFinalFunc()) { castfptr = DtoVirtualFunctionPointer(u, e->func, e->toChars()); - else if (e->func->isAbstract()) + } else if (e->func->isAbstract()) { llvm_unreachable("Delegate to abstract method not implemented."); - else if (e->func->toParent()->isInterfaceDeclaration()) + } else if (e->func->toParent()->isInterfaceDeclaration()) { llvm_unreachable("Delegate to interface method not implemented."); - else { + } else { DtoResolveFunction(e->func); // We need to actually codegen the function here, as literals are not // added to the module member list. if (e->func->semanticRun == PASSsemantic3done) { Dsymbol *owner = e->func->toParent(); - while (!owner->isTemplateInstance() && owner->toParent()) + while (!owner->isTemplateInstance() && owner->toParent()) { owner = owner->toParent(); + } if (owner->isTemplateInstance() || owner == p->dmodule) { Declaration_codegen(e->func, p); } @@ -2134,7 +2171,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(IdentityExp *e) { + void visit(IdentityExp *e) override { IF_LOG Logger::print("IdentityExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2158,11 +2195,11 @@ public: } // FIXME this stuff isn't pretty - LLValue *eval = 0; + LLValue *eval = nullptr; if (t1->ty == Tdelegate) { if (r->isNull()) { - rv = NULL; + rv = nullptr; } else { assert(lv->getType() == rv->getType()); } @@ -2172,10 +2209,11 @@ public: eval = DtoBinNumericEquals(e->loc, l, r, e->op); } else if (t1->ty == Tpointer || t1->ty == Tclass) { if (lv->getType() != rv->getType()) { - if (r->isNull()) + if (r->isNull()) { rv = llvm::ConstantPointerNull::get(isaPointer(lv->getType())); - else + } else { rv = DtoBitCast(rv, lv->getType()); + } } eval = (e->op == TOKidentity) ? p->ir->CreateICmpEQ(lv, rv) : p->ir->CreateICmpNE(lv, rv); @@ -2189,7 +2227,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(CommaExp *e) { + void visit(CommaExp *e) override { IF_LOG Logger::print("CommaExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2209,13 +2247,13 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(CondExp *e) { + void visit(CondExp *e) override { IF_LOG Logger::print("CondExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; Type *dtype = e->type->toBasetype(); - LLValue *retPtr = 0; + LLValue *retPtr = nullptr; if (dtype->ty != Tvoid) { // allocate a temporary for pointer to the final result. retPtr = DtoAlloca(dtype->pointerTo(), "condtmp"); @@ -2249,15 +2287,16 @@ public: llvm::BranchInst::Create(condend, p->scopebb()); p->scope() = IRScope(condend); - if (retPtr) + if (retPtr) { result = new DVarValue(e->type, DtoLoad(retPtr)); - else + } else { result = new DConstValue(e->type, getNullValue(DtoMemType(dtype))); + } } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(ComExp *e) { + void visit(ComExp *e) override { IF_LOG Logger::print("ComExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2275,7 +2314,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(NegExp *e) { + void visit(NegExp *e) override { IF_LOG Logger::print("NegExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2289,17 +2328,18 @@ public: LLValue *val = l->getRVal(); - if (e->type->isintegral()) + if (e->type->isintegral()) { val = p->ir->CreateNeg(val, "negval"); - else + } else { val = p->ir->CreateFNeg(val, "negval"); + } result = new DImValue(e->type, val); } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(CatExp *e) { + void visit(CatExp *e) override { IF_LOG Logger::print("CatExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2309,7 +2349,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(CatAssignExp *e) { + void visit(CatAssignExp *e) override { IF_LOG Logger::print("CatAssignExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2323,12 +2363,13 @@ public: if (e1type->ty == Tarray && e2type->ty == Tdchar && (elemtype->ty == Tchar || elemtype->ty == Twchar)) { - if (elemtype->ty == Tchar) + if (elemtype->ty == Tchar) { // append dchar to char[] DtoAppendDCharToString(e->loc, result, e->e2); - else /*if (elemtype->ty == Twchar)*/ + } else { /*if (elemtype->ty == Twchar)*/ // append dchar to wchar[] DtoAppendDCharToUnicodeString(e->loc, result, e->e2); + } } else if (e1type->equals(e2type)) { // append array DSliceValue *slice = DtoCatAssignArray(e->loc, result, e->e2); @@ -2341,7 +2382,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(FuncExp *e) { + void visit(FuncExp *e) override { IF_LOG Logger::print("FuncExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2355,11 +2396,12 @@ public: // of a delegate, so set tok here in order to get correct types/mangling. // Horrible hack, but DMD does the same thing. fd->tok = TOKfunction; - fd->vthis = NULL; + fd->vthis = nullptr; } - if (fd->isNested()) + if (fd->isNested()) { Logger::println("nested"); + } Logger::println("kind = %s", fd->kind()); // We need to actually codegen the function here, as literals are not added @@ -2412,7 +2454,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(ArrayLiteralExp *e) { + void visit(ArrayLiteralExp *e) override { IF_LOG Logger::print("ArrayLiteralExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2446,7 +2488,7 @@ public: } else if (dyn) { if (arrayType->isImmutable() && isConstLiteral(e)) { llvm::Constant *init = arrayLiteralToConst(p, e); - llvm::GlobalVariable *global = new llvm::GlobalVariable( + auto global = new llvm::GlobalVariable( gIR->module, init->getType(), true, llvm::GlobalValue::InternalLinkage, init, ".immutablearray"); result = new DSliceValue(arrayType, DtoConstSize_t(e->elements->dim), @@ -2469,7 +2511,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(StructLiteralExp *e) { + void visit(StructLiteralExp *e) override { IF_LOG Logger::print("StructLiteralExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2505,12 +2547,12 @@ public: // return as a var result = new DVarValue(e->type, e->inProgressMemory); - e->inProgressMemory = 0; + e->inProgressMemory = nullptr; } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(ClassReferenceExp *e) { + void visit(ClassReferenceExp *e) override { IF_LOG Logger::print("ClassReferenceExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2520,7 +2562,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(InExp *e) { + void visit(InExp *e) override { IF_LOG Logger::print("InExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2531,7 +2573,7 @@ public: result = DtoAAIn(e->loc, e->type, aa, key); } - void visit(RemoveExp *e) { + void visit(RemoveExp *e) override { IF_LOG Logger::print("RemoveExp::toElem: %s\n", e->toChars()); LOG_SCOPE; @@ -2553,23 +2595,25 @@ public: return llvm::ConstantArray::get(type, vals); } - llvm::Type *elementType = NULL; + llvm::Type *elementType = nullptr; bool differentTypes = false; for (auto v : vals) { - if (!elementType) + if (!elementType) { elementType = v->getType(); - else + } else { differentTypes |= (elementType != v->getType()); + } } - if (differentTypes) + if (differentTypes) { return llvm::ConstantStruct::getAnon(vals, true); + } llvm::ArrayType *t = llvm::ArrayType::get(elementType, vals.size()); return llvm::ConstantArray::get(t, vals); } - void visit(AssocArrayLiteralExp *e) { + void visit(AssocArrayLiteralExp *e) override { IF_LOG Logger::print("AssocArrayLiteralExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2582,15 +2626,16 @@ public: Type *aatype = basetype; Type *vtype = aatype->nextOf(); - if (!e->keys->dim) + if (!e->keys->dim) { goto LruntimeInit; + } if (aatype->ty != Taarray) { // It's the AssociativeArray type. // Turn it back into a TypeAArray vtype = e->values->tdata()[0]->type; aatype = new TypeAArray(vtype, e->keys->tdata()[0]->type); - aatype = aatype->semantic(e->loc, NULL); + aatype = aatype->semantic(e->loc, nullptr); } { @@ -2606,8 +2651,9 @@ public: unsigned errors = global.startGagging(); LLConstant *ekeyConst = toConstElem(ekey, p); LLConstant *evalConst = toConstElem(eval, p); - if (global.endGagging(errors)) + if (global.endGagging(errors)) { goto LruntimeInit; + } assert(ekeyConst && evalConst); keysInits.push_back(ekeyConst); valuesInits.push_back(evalConst); @@ -2702,7 +2748,7 @@ public: return new DVarValue(exp->type, DtoBitCast(v, DtoPtrToType(exp->type))); } - void visit(DelegatePtrExp *e) { + void visit(DelegatePtrExp *e) override { IF_LOG Logger::print("DelegatePtrExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2710,7 +2756,7 @@ public: result = toGEP(e, 0); } - void visit(DelegateFuncptrExp *e) { + void visit(DelegateFuncptrExp *e) override { IF_LOG Logger::print("DelegateFuncptrExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2720,7 +2766,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(BoolExp *e) { + void visit(BoolExp *e) override { IF_LOG Logger::print("BoolExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2731,7 +2777,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(DotTypeExp *e) { + void visit(DotTypeExp *e) override { IF_LOG Logger::print("DotTypeExp::toElem: %s @ %s\n", e->toChars(), e->type->toChars()); LOG_SCOPE; @@ -2742,7 +2788,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(TypeExp *e) { + void visit(TypeExp *e) override { e->error("type %s is not an expression", e->toChars()); // TODO: Improve error handling. DMD just returns some value here and hopes // some more sensible error messages will be triggered. @@ -2751,13 +2797,14 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(TupleExp *e) { + void visit(TupleExp *e) override { IF_LOG Logger::print("TupleExp::toElem() %s\n", e->toChars()); LOG_SCOPE; // If there are any side effects, evaluate them first. - if (e->e0) + if (e->e0) { toElem(e->e0); + } std::vector types; types.reserve(e->exps->dim); @@ -2770,20 +2817,21 @@ public: Expression *el = (*e->exps)[i]; DValue *ep = toElem(el); LLValue *gep = DtoGEPi(val, 0, i); - if (DtoIsPassedByRef(el->type)) + if (DtoIsPassedByRef(el->type)) { DtoStore(DtoLoad(ep->getRVal()), gep); - else if (el->type->ty != Tvoid) + } else if (el->type->ty != Tvoid) { DtoStoreZextI8(ep->getRVal(), gep); - else + } else { DtoStore(LLConstantInt::get(LLType::getInt8Ty(p->context()), 0, false), gep); + } } result = new DVarValue(e->type, val); } ////////////////////////////////////////////////////////////////////////////////////////// - void visit(VectorExp *e) { + void visit(VectorExp *e) override { IF_LOG Logger::print("VectorExp::toElem() %s\n", e->toChars()); LOG_SCOPE; @@ -2819,7 +2867,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(PowExp *e) { + void visit(PowExp *e) override { IF_LOG Logger::print("PowExp::toElem() %s\n", e->toChars()); LOG_SCOPE; @@ -2829,10 +2877,10 @@ public: ////////////////////////////////////////////////////////////////////////////////////////// - void visit(TypeidExp *e) { + void visit(TypeidExp *e) override { if (Type *t = isType(e->obj)) { result = DtoSymbolAddress(e->loc, e->type, - getOrCreateTypeInfoDeclaration(t, NULL)); + getOrCreateTypeInfoDeclaration(t, nullptr)); return; } if (Expression *ex = isExpression(e->obj)) { @@ -2875,6 +2923,7 @@ public: STUB(ScopeExp) STUB(SymbolExp) STUB(PowAssignExp) +#undef STUB }; ////////////////////////////////////////////////////////////////////////////////////////////// @@ -2892,10 +2941,10 @@ DValue *toElemDtor(Expression *e) { } // FIXME: Implement & place in right module -Symbol *toModuleAssert(Module *m) { return NULL; } +Symbol *toModuleAssert(Module *m) { return nullptr; } // FIXME: Implement & place in right module -Symbol *toModuleUnittest(Module *m) { return NULL; } +Symbol *toModuleUnittest(Module *m) { return nullptr; } // FIXME: Implement & place in right module -Symbol *toModuleArray(Module *m) { return NULL; } +Symbol *toModuleArray(Module *m) { return nullptr; } diff --git a/gen/tollvm.cpp b/gen/tollvm.cpp index 4aa7376ffb..f0e68694a7 100644 --- a/gen/tollvm.cpp +++ b/gen/tollvm.cpp @@ -47,8 +47,9 @@ RET retStyle(TypeFunction *tf) { bool DtoIsReturnInArg(CallExp *ce) { TypeFunction *tf = static_cast(ce->e1->type->toBasetype()); - if (tf->ty == Tfunction && (!ce->f || !DtoIsIntrinsic(ce->f))) + if (tf->ty == Tfunction && (!ce->f || !DtoIsIntrinsic(ce->f))) { return retStyle(tf) == RETstack; + } return false; } @@ -186,7 +187,7 @@ LLType *DtoType(Type *t) { default: llvm_unreachable("Unknown class of D Type!"); } - return 0; + return nullptr; } LLType *DtoMemType(Type *t) { return i1ToI8(voidToI8(DtoType(t))); } @@ -194,14 +195,16 @@ LLType *DtoMemType(Type *t) { return i1ToI8(voidToI8(DtoType(t))); } LLPointerType *DtoPtrToType(Type *t) { return DtoMemType(t)->getPointerTo(); } LLType *voidToI8(LLType *t) { - if (t == LLType::getVoidTy(gIR->context())) + if (t == LLType::getVoidTy(gIR->context())) { return LLType::getInt8Ty(gIR->context()); + } return t; } LLType *i1ToI8(LLType *t) { - if (t == LLType::getInt1Ty(gIR->context())) + if (t == LLType::getInt1Ty(gIR->context())) { return LLType::getInt8Ty(gIR->context()); + } return t; } @@ -210,7 +213,7 @@ LLType *i1ToI8(LLType *t) { LLValue *DtoDelegateEquals(TOK op, LLValue *lhs, LLValue *rhs) { Logger::println("Doing delegate equality"); llvm::Value *b1, *b2; - if (rhs == NULL) { + if (rhs == nullptr) { rhs = LLConstant::getNullValue(lhs->getType()); } @@ -224,8 +227,9 @@ LLValue *DtoDelegateEquals(TOK op, LLValue *lhs, LLValue *rhs) { LLValue *b = gIR->ir->CreateAnd(b1, b2); - if (op == TOKnotequal || op == TOKnotidentity) + if (op == TOKnotequal || op == TOKnotidentity) { return gIR->ir->CreateNot(b); + } return b; } @@ -233,8 +237,9 @@ LLValue *DtoDelegateEquals(TOK op, LLValue *lhs, LLValue *rhs) { ////////////////////////////////////////////////////////////////////////////////////////// LinkageWithCOMDAT DtoLinkage(Dsymbol *sym) { - if (DtoIsTemplateInstance(sym)) + if (DtoIsTemplateInstance(sym)) { return LinkageWithCOMDAT(templateLinkage, supportsCOMDAT()); + } return LinkageWithCOMDAT(llvm::GlobalValue::ExternalLinkage, false); } @@ -242,10 +247,11 @@ LinkageWithCOMDAT DtoLinkage(Dsymbol *sym) { LLIntegerType *DtoSize_t() { // the type of size_t does not change once set - static LLIntegerType *t = NULL; - if (t == NULL) + static LLIntegerType *t = nullptr; + if (t == nullptr) { t = (global.params.isLP64) ? LLType::getInt64Ty(gIR->context()) : LLType::getInt32Ty(gIR->context()); + } return t; } @@ -405,9 +411,9 @@ LLConstant *DtoConstFP(Type *t, longdouble value) { assert(llty->isFloatingPointTy()); if (llty == LLType::getFloatTy(gIR->context()) || - llty == LLType::getDoubleTy(gIR->context())) + llty == LLType::getDoubleTy(gIR->context())) { return LLConstantFP::get(llty, value); - else if (llty == LLType::getX86_FP80Ty(gIR->context())) { + } else if (llty == LLType::getX86_FP80Ty(gIR->context())) { uint64_t bits[] = {0, 0}; bits[0] = *reinterpret_cast(&value); bits[1] = @@ -432,9 +438,9 @@ LLConstant *DtoConstString(const char *str) { llvm::StringRef s(str ? str : ""); llvm::GlobalVariable *gvar = (gIR->stringLiteral1ByteCache.find(s) == gIR->stringLiteral1ByteCache.end()) - ? 0 + ? nullptr : gIR->stringLiteral1ByteCache[s]; - if (gvar == 0) { + if (gvar == nullptr) { llvm::Constant *init = llvm::ConstantDataArray::getString(gIR->context(), s, true); gvar = new llvm::GlobalVariable(gIR->module, init->getType(), true, @@ -510,15 +516,17 @@ void DtoAlignedStore(LLValue *src, LLValue *dst) { ////////////////////////////////////////////////////////////////////////////////////////// LLValue *DtoBitCast(LLValue *v, LLType *t, const char *name) { - if (v->getType() == t) + if (v->getType() == t) { return v; + } assert(!isaStruct(t)); return gIR->ir->CreateBitCast(v, t, name); } LLConstant *DtoBitCast(LLConstant *v, LLType *t) { - if (v->getType() == t) + if (v->getType() == t) { return v; + } return llvm::ConstantExpr::getBitCast(v, t); } @@ -602,8 +610,9 @@ llvm::GlobalVariable *isaGlobalVar(LLValue *v) { ////////////////////////////////////////////////////////////////////////////////////////// LLPointerType *getPtrToType(LLType *t) { - if (t == LLType::getVoidTy(gIR->context())) + if (t == LLType::getVoidTy(gIR->context())) { t = LLType::getInt8Ty(gIR->context()); + } return LLPointerType::get(t, 0); } @@ -639,8 +648,9 @@ unsigned int getABITypeAlign(LLType *t) { ////////////////////////////////////////////////////////////////////////////////////////// LLStructType *DtoMutexType() { - if (gIR->mutexType) + if (gIR->mutexType) { return gIR->mutexType; + } // The structures defined here must be the same as in // druntime/src/rt/critical.c @@ -705,8 +715,9 @@ LLStructType *DtoMutexType() { ////////////////////////////////////////////////////////////////////////////////////////// LLStructType *DtoModuleReferenceType() { - if (gIR->moduleRefType) + if (gIR->moduleRefType) { return gIR->moduleRefType; + } // this is a recursive type so start out with a struct without body LLStructType *st = LLStructType::create(gIR->context(), "ModuleReference"); @@ -738,8 +749,9 @@ LLValue *DtoAggrPair(LLValue *V1, LLValue *V2, const char *name) { } LLValue *DtoAggrPaint(LLValue *aggr, LLType *as) { - if (aggr->getType() == as) + if (aggr->getType() == as) { return aggr; + } LLValue *res = llvm::UndefValue::get(as); diff --git a/gen/tollvm.h b/gen/tollvm.h index 9d8fd7e875..fc0cca63b5 100644 --- a/gen/tollvm.h +++ b/gen/tollvm.h @@ -70,14 +70,14 @@ LLStructType *DtoModuleReferenceType(); // getelementptr helpers LLValue *DtoGEP1(LLValue *ptr, LLValue *i0, const char *name = "", - llvm::BasicBlock *bb = NULL); + llvm::BasicBlock *bb = nullptr); LLValue *DtoGEP(LLValue *ptr, LLValue *i0, LLValue *i1, const char *name = "", - llvm::BasicBlock *bb = NULL); + llvm::BasicBlock *bb = nullptr); LLValue *DtoGEPi1(LLValue *ptr, unsigned i0, const char *name = "", - llvm::BasicBlock *bb = NULL); + llvm::BasicBlock *bb = nullptr); LLValue *DtoGEPi(LLValue *ptr, unsigned i0, unsigned i1, const char *name = "", - llvm::BasicBlock *bb = NULL); + llvm::BasicBlock *bb = nullptr); LLConstant *DtoGEPi(LLConstant *ptr, unsigned i0, unsigned i1); // to constant helpers diff --git a/gen/typinf.cpp b/gen/typinf.cpp index f7c0105bea..11737d12e5 100644 --- a/gen/typinf.cpp +++ b/gen/typinf.cpp @@ -78,10 +78,11 @@ TypeInfoDeclaration *createUnqualified(Type *t) { case Ttuple: return TypeInfoTupleDeclaration::create(t); case Tclass: - if (((TypeClass *)t)->sym->isInterfaceDeclaration()) + if (((TypeClass *)t)->sym->isInterfaceDeclaration()) { return TypeInfoInterfaceDeclaration::create(t); - else + } else { return TypeInfoClassDeclaration::create(t); + } default: return TypeInfoDeclaration::create(t, 0); } @@ -100,16 +101,17 @@ TypeInfoDeclaration *getOrCreateTypeInfoDeclaration(Type *torig, Scope *sc) { Type *t = torig->merge2(); // do this since not all Type's are merge'd if (!t->vtinfo) { - if (t->isShared()) // does both 'shared' and 'shared const' + if (t->isShared()) { // does both 'shared' and 'shared const' t->vtinfo = new TypeInfoSharedDeclaration(t); - else if (t->isConst()) + } else if (t->isConst()) { t->vtinfo = new TypeInfoConstDeclaration(t); - else if (t->isImmutable()) + } else if (t->isImmutable()) { t->vtinfo = new TypeInfoInvariantDeclaration(t); - else if (t->isWild()) + } else if (t->isWild()) { t->vtinfo = new TypeInfoWildDeclaration(t); - else + } else { t->vtinfo = createUnqualified(t); + } assert(t->vtinfo); torig->vtinfo = t->vtinfo; @@ -130,9 +132,10 @@ TypeInfoDeclaration *getOrCreateTypeInfoDeclaration(Type *torig, Scope *sc) { } } } - if (!torig->vtinfo) + if (!torig->vtinfo) { torig->vtinfo = t->vtinfo; // Types aren't merged, but we can share the vtinfo's + } assert(torig->vtinfo); return torig->vtinfo; } @@ -156,13 +159,14 @@ static bool builtinTypeInfo(Type *t) { if (t->isTypeBasic() || t->ty == Tclass) return !t->mod; #else - if (t->isTypeBasic()) + if (t->isTypeBasic()) { return !t->mod; + } #endif if (t->ty == Tarray) { Type *next = t->nextOf(); - return !t->mod && ((next->isTypeBasic() != NULL && !next->mod) || + return !t->mod && ((next->isTypeBasic() != nullptr && !next->mod) || // strings are so common, make them builtin (next->ty == Tchar && next->mod == MODimmutable) || (next->ty == Tchar && next->mod == MODconst)); @@ -213,8 +217,9 @@ static void emitTypeMetadata(TypeInfoDeclaration *tid) { } void DtoResolveTypeInfo(TypeInfoDeclaration *tid) { - if (tid->ir.isResolved()) + if (tid->ir.isResolved()) { return; + } tid->ir.setResolved(); // TypeInfo instances (except ClassInfo ones) are always emitted as weak @@ -224,7 +229,7 @@ void DtoResolveTypeInfo(TypeInfoDeclaration *tid) { // that we actually need the value somewhere else in codegen. // TODO: DMD does not seem to call semanticTypeInfo() from the glue layer, // so there might be a structural issue somewhere. - semanticTypeInfo(NULL, tid->tinfo); + semanticTypeInfo(nullptr, tid->tinfo); Declaration_codegen(tid); } @@ -238,7 +243,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoDeclaration *decl) { + void visit(TypeInfoDeclaration *decl) override { IF_LOG Logger::println("TypeInfoDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -250,7 +255,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoEnumDeclaration *decl) { + void visit(TypeInfoEnumDeclaration *decl) override { IF_LOG Logger::println("TypeInfoEnumDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -279,16 +284,17 @@ public: LLType *memty = DtoType(memtype); LLConstant *C; Expression *defaultval = sd->getDefaultValue(decl->loc); - if (memtype->isintegral()) + if (memtype->isintegral()) { C = LLConstantInt::get(memty, defaultval->toInteger(), !isLLVMUnsigned(memtype)); - else if (memtype->isString()) + } else if (memtype->isString()) { C = DtoConstString( static_cast(defaultval->toStringExp()->string)); - else if (memtype->isfloating()) + } else if (memtype->isfloating()) { C = LLConstantFP::get(memty, defaultval->toReal()); - else + } else { llvm_unreachable("Unsupported type"); + } b.push_void_array(C, memtype, sd); } @@ -300,7 +306,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoPointerDeclaration *decl) { + void visit(TypeInfoPointerDeclaration *decl) override { IF_LOG Logger::println("TypeInfoPointerDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -315,7 +321,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoArrayDeclaration *decl) { + void visit(TypeInfoArrayDeclaration *decl) override { IF_LOG Logger::println("TypeInfoArrayDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -330,7 +336,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoStaticArrayDeclaration *decl) { + void visit(TypeInfoStaticArrayDeclaration *decl) override { IF_LOG Logger::println("TypeInfoStaticArrayDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -353,7 +359,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoAssociativeArrayDeclaration *decl) { + void visit(TypeInfoAssociativeArrayDeclaration *decl) override { IF_LOG Logger::println( "TypeInfoAssociativeArrayDeclaration::llvmDefine() %s", decl->toChars()); @@ -377,7 +383,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoFunctionDeclaration *decl) { + void visit(TypeInfoFunctionDeclaration *decl) override { IF_LOG Logger::println("TypeInfoFunctionDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -394,7 +400,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoDelegateDeclaration *decl) { + void visit(TypeInfoDelegateDeclaration *decl) override { IF_LOG Logger::println("TypeInfoDelegateDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -414,7 +420,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoStructDeclaration *decl) { + void visit(TypeInfoStructDeclaration *decl) override { IF_LOG Logger::println("TypeInfoStructDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -472,8 +478,9 @@ public: // (m_arg1/m_arg2) which are used for the X86_64 System V ABI varargs // implementation. They are not present on any other cpu/os. unsigned expectedFields = 12; - if (global.params.targetTriple.getArch() == llvm::Triple::x86_64) + if (global.params.targetTriple.getArch() == llvm::Triple::x86_64) { expectedFields += 2; + } if (Type::typeinfostruct->fields.dim != expectedFields) { error(Loc(), "Unexpected number of object.TypeInfo_Struct fields; " "druntime version does not match compiler"); @@ -487,10 +494,11 @@ public: // The protocol is to write a null pointer for zero-initialized arrays. The // length field is always needed for tsize(). llvm::Constant *initPtr; - if (tc->isZeroInit(Loc())) + if (tc->isZeroInit(Loc())) { initPtr = getNullValue(getVoidPtrType()); - else + } else { initPtr = iraggr->getInitSymbol(); + } b.push_void_array(getTypeStoreSize(DtoType(tc)), initPtr); // toHash @@ -518,8 +526,9 @@ public: // void function(void*) xpostblit; FuncDeclaration *xpostblit = sd->postblit; - if (xpostblit && sd->postblit->storage_class & STCdisable) - xpostblit = 0; + if (xpostblit && sd->postblit->storage_class & STCdisable) { + xpostblit = nullptr; + } b.push_funcptr(xpostblit); // uint m_align; @@ -533,8 +542,9 @@ public: if (t) { t = t->merge(); b.push_typeinfo(t); - } else + } else { b.push_null(Type::dtypeinfo->type); + } t = sd->arg2type; } @@ -543,12 +553,13 @@ public: // immutable(void)* m_RTInfo; // The cases where getRTInfo is null are not quite here, but the code is // modelled after what DMD does. - if (sd->getRTInfo) + if (sd->getRTInfo) { b.push(toConstElem(sd->getRTInfo, gIR)); - else if (!tc->hasPointers()) + } else if (!tc->hasPointers()) { b.push_size_as_vp(0); // no pointers - else + } else { b.push_size_as_vp(1); // has pointers + } // finish b.finalize(getIrGlobal(decl)); @@ -557,7 +568,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoClassDeclaration *decl) { + void visit(TypeInfoClassDeclaration *decl) override { llvm_unreachable( "TypeInfoClassDeclaration::llvmDefine() should not be called, " "as a custom Dsymbol::codegen() override is used"); @@ -566,7 +577,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoInterfaceDeclaration *decl) { + void visit(TypeInfoInterfaceDeclaration *decl) override { IF_LOG Logger::println("TypeInfoInterfaceDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -588,7 +599,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoTupleDeclaration *decl) { + void visit(TypeInfoTupleDeclaration *decl) override { IF_LOG Logger::println("TypeInfoTupleDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -615,7 +626,7 @@ public: RTTIBuilder b(Type::typeinfotypelist); // push TypeInfo[] - b.push_array(arrC, dim, Type::dtypeinfo->type, NULL); + b.push_array(arrC, dim, Type::dtypeinfo->type, nullptr); // finish b.finalize(getIrGlobal(decl)); @@ -624,7 +635,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoConstDeclaration *decl) { + void visit(TypeInfoConstDeclaration *decl) override { IF_LOG Logger::println("TypeInfoConstDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -639,7 +650,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoInvariantDeclaration *decl) { + void visit(TypeInfoInvariantDeclaration *decl) override { IF_LOG Logger::println("TypeInfoInvariantDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -654,7 +665,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoSharedDeclaration *decl) { + void visit(TypeInfoSharedDeclaration *decl) override { IF_LOG Logger::println("TypeInfoSharedDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -669,7 +680,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoWildDeclaration *decl) { + void visit(TypeInfoWildDeclaration *decl) override { IF_LOG Logger::println("TypeInfoWildDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -684,7 +695,7 @@ public: /* ========================================================================= */ - void visit(TypeInfoVectorDeclaration *decl) { + void visit(TypeInfoVectorDeclaration *decl) override { IF_LOG Logger::println("TypeInfoVectorDeclaration::llvmDefine() %s", decl->toChars()); LOG_SCOPE; @@ -707,8 +718,9 @@ void TypeInfoDeclaration_codegen(TypeInfoDeclaration *decl, IRState *p) { decl->toPrettyChars()); LOG_SCOPE; - if (decl->ir.isDefined()) + if (decl->ir.isDefined()) { return; + } decl->ir.setDefined(); std::string mangled(mangle(decl)); @@ -724,13 +736,14 @@ void TypeInfoDeclaration_codegen(TypeInfoDeclaration *decl, IRState *p) { assert(irg->type->isStructTy()); } else { if (builtinTypeInfo( - decl->tinfo)) // this is a declaration of a builtin __initZ var + decl->tinfo)) { // this is a declaration of a builtin __initZ var irg->type = Type::dtypeinfo->type->ctype->isClass()->getMemoryLLType(); - else + } else { irg->type = LLStructType::create(gIR->context(), decl->toPrettyChars()); + } irg->value = new llvm::GlobalVariable(gIR->module, irg->type, true, llvm::GlobalValue::ExternalLinkage, - NULL, mangled); + nullptr, mangled); } emitTypeMetadata(decl); diff --git a/gen/warnings.cpp b/gen/warnings.cpp index abc64ac8cb..1428f1c8a8 100644 --- a/gen/warnings.cpp +++ b/gen/warnings.cpp @@ -15,8 +15,9 @@ void warnInvalidPrintfCall(Loc loc, Expression *arguments, size_t nargs) { // make sure first argument is a string literal, or we can't do much // TODO make it smarter ? - if (arg->op != TOKstring) + if (arg->op != TOKstring) { return; // assume valid + } StringExp *strexp = static_cast(arg); diff --git a/ir/iraggr.cpp b/ir/iraggr.cpp index b18c592ade..cae44c260d 100644 --- a/ir/iraggr.cpp +++ b/ir/iraggr.cpp @@ -34,16 +34,18 @@ IrAggr::IrAggr(AggregateDeclaration *aggr) ////////////////////////////////////////////////////////////////////////////// LLGlobalVariable *IrAggr::getInitSymbol() { - if (init) + if (init) { return init; + } // create the initZ symbol std::string initname("_D"); initname.append(mangle(aggrdecl)); initname.append("6__initZ"); - init = getOrCreateGlobal(aggrdecl->loc, gIR->module, init_type, true, - llvm::GlobalValue::ExternalLinkage, NULL, initname); + init = + getOrCreateGlobal(aggrdecl->loc, gIR->module, init_type, true, + llvm::GlobalValue::ExternalLinkage, nullptr, initname); // set alignment init->setAlignment(DtoAlignment(type)); @@ -54,8 +56,9 @@ LLGlobalVariable *IrAggr::getInitSymbol() { ////////////////////////////////////////////////////////////////////////////// llvm::Constant *IrAggr::getDefaultInit() { - if (constInit) + if (constInit) { return constInit; + } IF_LOG Logger::println("Building default initializer for %s", aggrdecl->toPrettyChars()); @@ -123,8 +126,9 @@ static llvm::Constant *FillSArrayDims(Type *arrTypeD, llvm::Constant *init) { // the size without doing an expensive recursive D <-> LLVM type comparison. // The better way to solve this would be to just fix the initializer // codegen in any place where a scalar initializer might still be generated. - if (gDataLayout->getTypeStoreSize(init->getType()) >= arrTypeD->size()) + if (gDataLayout->getTypeStoreSize(init->getType()) >= arrTypeD->size()) { return init; + } if (arrTypeD->ty == Tsarray) { init = FillSArrayDims(arrTypeD->nextOf(), init); @@ -175,12 +179,14 @@ IrAggr::createInitializerConstant(const VarInitMap &explicitInitializers, if (!initializerType || initializerType->isOpaque()) { llvm::SmallVector types; types.reserve(constants.size()); - for (auto c : constants) + for (auto c : constants) { types.push_back(c->getType()); - if (!initializerType) + } + if (!initializerType) { initializerType = LLStructType::get(gIR->context(), types, isPacked()); - else + } else { initializerType->setBody(types, isPacked()); + } } // build constant @@ -208,15 +214,17 @@ void IrAggr::addFieldInitializers( // Fill in explicit initializers. for (size_t i = 0; i < n; ++i) { VarDeclaration *vd = decl->fields[i]; - VarInitMap::const_iterator expl = explicitInitializers.find(vd); - if (expl != explicitInitializers.end()) + auto expl = explicitInitializers.find(vd); + if (expl != explicitInitializers.end()) { data[i] = *expl; + } } // Fill in implicit initializers for (size_t i = 0; i < n; i++) { - if (data[i].first) + if (data[i].first) { continue; + } VarDeclaration *vd = decl->fields[i]; @@ -227,8 +235,10 @@ void IrAggr::addFieldInitializers( dchar b = 'a'; } */ - if (decl->isUnionDeclaration() && vd->init && vd->init->isVoidInitializer()) + if (decl->isUnionDeclaration() && vd->init && + vd->init->isVoidInitializer()) { continue; + } unsigned vd_begin = vd->offset; unsigned vd_end = vd_begin + vd->type->size(); @@ -238,23 +248,26 @@ void IrAggr::addFieldInitializers( ubyte[0] test; } */ - if (vd_begin == vd_end) + if (vd_begin == vd_end) { continue; + } // make sure it doesn't overlap any explicit initializers. bool overlaps = false; if (type->ty == Tstruct) { // Only structs and unions can have overlapping fields. for (size_t j = 0; j < n; ++j) { - if (i == j || !data[j].first) + if (i == j || !data[j].first) { continue; + } VarDeclaration *it = decl->fields[j]; unsigned f_begin = it->offset; unsigned f_end = f_begin + it->type->size(); - if (vd_begin >= f_end || vd_end <= f_begin) + if (vd_begin >= f_end || vd_end <= f_begin) { continue; + } overlaps = true; break; @@ -267,7 +280,7 @@ void IrAggr::addFieldInitializers( LOG_SCOPE; data[i].first = vd; - data[i].second = get_default_initializer(vd, NULL); + data[i].second = get_default_initializer(vd, nullptr); } } @@ -282,8 +295,9 @@ void IrAggr::addFieldInitializers( // when necessary. for (size_t i = 0; i < n; i++) { VarDeclaration *vd = data[i].first; - if (vd == NULL) + if (vd == nullptr) { continue; + } // Explicitly zero the padding as per TDPL §7.1.1. Otherwise, it would // be left uninitialized by LLVM. @@ -321,8 +335,9 @@ void IrAggr::addFieldInitializers( offset += Target::ptrsize; inter_idx++; - if (populateInterfacesWithVtbls) + if (populateInterfacesWithVtbls) { interfacesWithVtbls.push_back(bc); + } } } } diff --git a/ir/iraggr.h b/ir/iraggr.h index b0c9eabef3..f3f8c3458c 100644 --- a/ir/iraggr.h +++ b/ir/iraggr.h @@ -87,7 +87,7 @@ struct IrAggr { /// returned type is not necessarily the same as getLLType(). llvm::Constant * createInitializerConstant(const VarInitMap &explicitInitializers, - llvm::StructType *initializerType = 0); + llvm::StructType *initializerType = nullptr); protected: /// Static default initializer global. diff --git a/ir/irclass.cpp b/ir/irclass.cpp index c96e2b33ea..2dc0f5aa8c 100644 --- a/ir/irclass.cpp +++ b/ir/irclass.cpp @@ -44,8 +44,9 @@ extern LLConstant *DtoDefineClassInfo(ClassDeclaration *cd); ////////////////////////////////////////////////////////////////////////////// LLGlobalVariable *IrAggr::getVtblSymbol() { - if (vtbl) + if (vtbl) { return vtbl; + } // create the initZ symbol std::string initname("_D"); @@ -54,8 +55,9 @@ LLGlobalVariable *IrAggr::getVtblSymbol() { LLType *vtblTy = stripModifiers(type)->ctype->isClass()->getVtbl(); - vtbl = getOrCreateGlobal(aggrdecl->loc, gIR->module, vtblTy, true, - llvm::GlobalValue::ExternalLinkage, NULL, initname); + vtbl = + getOrCreateGlobal(aggrdecl->loc, gIR->module, vtblTy, true, + llvm::GlobalValue::ExternalLinkage, nullptr, initname); return vtbl; } @@ -63,17 +65,19 @@ LLGlobalVariable *IrAggr::getVtblSymbol() { ////////////////////////////////////////////////////////////////////////////// LLGlobalVariable *IrAggr::getClassInfoSymbol() { - if (classInfo) + if (classInfo) { return classInfo; + } // create the initZ symbol std::string initname("_D"); initname.append(mangle(aggrdecl)); - if (aggrdecl->isInterfaceDeclaration()) + if (aggrdecl->isInterfaceDeclaration()) { initname.append("11__InterfaceZ"); - else + } else { initname.append("7__ClassZ"); + } // The type is also ClassInfo for interfaces – the actual TypeInfo for them // is a TypeInfo_Interface instance that references __ClassZ in its "base" @@ -86,7 +90,7 @@ LLGlobalVariable *IrAggr::getClassInfoSymbol() { // classinfos cannot be constants since they're used as locks for synchronized classInfo = getOrCreateGlobal( aggrdecl->loc, gIR->module, tc->getMemoryLLType(), false, - llvm::GlobalValue::ExternalLinkage, NULL, initname); + llvm::GlobalValue::ExternalLinkage, nullptr, initname); // Generate some metadata on this ClassInfo if it's for a class. ClassDeclaration *classdecl = aggrdecl->isClassDeclaration(); @@ -94,8 +98,8 @@ LLGlobalVariable *IrAggr::getClassInfoSymbol() { // Gather information LLType *type = DtoType(aggrdecl->type); LLType *bodyType = llvm::cast(type)->getElementType(); - bool hasDestructor = (classdecl->dtor != NULL); - bool hasCustomDelete = (classdecl->aggDelete != NULL); + bool hasDestructor = (classdecl->dtor != nullptr); + bool hasCustomDelete = (classdecl->aggDelete != nullptr); // Construct the fields #if LDC_LLVM_VER >= 306 llvm::Metadata *mdVals[CD_NumFields]; @@ -127,8 +131,9 @@ LLGlobalVariable *IrAggr::getClassInfoSymbol() { ////////////////////////////////////////////////////////////////////////////// LLGlobalVariable *IrAggr::getInterfaceArraySymbol() { - if (classInterfacesArray) + if (classInterfacesArray) { return classInterfacesArray; + } ClassDeclaration *cd = aggrdecl->isClassDeclaration(); @@ -150,7 +155,7 @@ LLGlobalVariable *IrAggr::getInterfaceArraySymbol() { // we emit the initializer later. classInterfacesArray = getOrCreateGlobal(cd->loc, gIR->module, array_type, true, - llvm::GlobalValue::ExternalLinkage, NULL, name); + llvm::GlobalValue::ExternalLinkage, nullptr, name); return classInterfacesArray; } @@ -158,8 +163,9 @@ LLGlobalVariable *IrAggr::getInterfaceArraySymbol() { ////////////////////////////////////////////////////////////////////////////// LLConstant *IrAggr::getVtblInit() { - if (constVtbl) + if (constVtbl) { return constVtbl; + } IF_LOG Logger::println("Building vtbl initializer"); LOG_SCOPE; @@ -199,12 +205,14 @@ LLConstant *IrAggr::getVtblInit() { * issue 'hidden' error. */ for (size_t j = 1; j < n; j++) { - if (j == i) + if (j == i) { continue; + } FuncDeclaration *fd2 = static_cast(cd->vtbl.data[j])->isFuncDeclaration(); - if (!fd2->ident->equals(fd->ident)) + if (!fd2->ident->equals(fd->ident)) { continue; + } if (fd->leastAsSpecialized(fd2) || fd2->leastAsSpecialized(fd)) { TypeFunction *tf = static_cast(fd->type); if (tf->ty == Tfunction) { @@ -256,8 +264,9 @@ LLConstant *IrAggr::getVtblInit() { ////////////////////////////////////////////////////////////////////////////// LLConstant *IrAggr::getClassInfoInit() { - if (constClassInfo) + if (constClassInfo) { return constClassInfo; + } constClassInfo = DtoDefineClassInfo(aggrdecl->isClassDeclaration()); return constClassInfo; } @@ -267,8 +276,9 @@ LLConstant *IrAggr::getClassInfoInit() { llvm::GlobalVariable *IrAggr::getInterfaceVtbl(BaseClass *b, bool new_instance, size_t interfaces_index) { auto it = interfaceVtblMap.find(b->base); - if (it != interfaceVtblMap.end()) + if (it != interfaceVtblMap.end()) { return it->second; + } IF_LOG Logger::println( "Building vtbl for implementation of interface %s in class %s", @@ -303,7 +313,7 @@ llvm::GlobalVariable *IrAggr::getInterfaceVtbl(BaseClass *b, bool new_instance, size_t n = vtbl_array.dim; for (size_t i = b->base->vtblOffset(); i < n; i++) { Dsymbol *dsym = static_cast(vtbl_array.data[i]); - if (dsym == NULL) { + if (dsym == nullptr) { // FIXME // why is this null? // happens for mini/s.d @@ -374,11 +384,12 @@ llvm::GlobalVariable *IrAggr::getInterfaceVtbl(BaseClass *b, bool new_instance, call.setCallingConv(irFunc->func->getCallingConv()); // return from the thunk - if (thunk->getReturnType() == LLType::getVoidTy(gIR->context())) + if (thunk->getReturnType() == LLType::getVoidTy(gIR->context())) { llvm::ReturnInst::Create(gIR->context(), beginbb); - else + } else { llvm::ReturnInst::Create(gIR->context(), call.getInstruction(), beginbb); + } // clean up gIR->scopes.pop_back(); @@ -401,8 +412,9 @@ llvm::GlobalVariable *IrAggr::getInterfaceVtbl(BaseClass *b, bool new_instance, llvm::GlobalVariable *GV = getOrCreateGlobal(cd->loc, gIR->module, vtbl_constant->getType(), true, lwc.first, vtbl_constant, mangledName); - if (lwc.second) + if (lwc.second) { SET_COMDAT(GV, gIR->module); + } // insert into the vtbl map interfaceVtblMap.insert(std::make_pair(b->base, GV)); @@ -429,8 +441,9 @@ LLConstant *IrAggr::getClassInfoInterfaces() { VarDeclaration *interfaces_idx = Type::typeinfoclass->fields[3]; - if (n == 0) + if (n == 0) { return getNullValue(DtoType(interfaces_idx->type)); + } // Build array of: // @@ -495,8 +508,9 @@ LLConstant *IrAggr::getClassInfoInterfaces() { classInterfacesArray->setInitializer(arr); const LinkageWithCOMDAT lwc = DtoLinkage(cd); classInterfacesArray->setLinkage(lwc.first); - if (lwc.second) + if (lwc.second) { SET_COMDAT(classInterfacesArray, gIR->module); + } // return null, only baseclass provide interfaces if (cd->vtblInterfaces->dim == 0) { @@ -525,8 +539,9 @@ void IrAggr::initializeInterface() { assert(base && "not interface"); // has interface vtbls? - if (!base->vtblInterfaces) + if (!base->vtblInterfaces) { return; + } for (auto bc : *base->vtblInterfaces) { // add to the interface list diff --git a/ir/irdsymbol.cpp b/ir/irdsymbol.cpp index 4bf31b2de7..01d1d2da4d 100644 --- a/ir/irdsymbol.cpp +++ b/ir/irdsymbol.cpp @@ -18,8 +18,9 @@ void IrDsymbol::resetAll() { Logger::println("resetting %llu Dsymbols", static_cast(list.size())); - for (auto s : list) + for (auto s : list) { s->reset(); + } } IrDsymbol::IrDsymbol() { list.push_back(this); } @@ -49,21 +50,25 @@ void IrDsymbol::reset() { } void IrDsymbol::setResolved() { - if (m_state < Resolved) + if (m_state < Resolved) { m_state = Resolved; + } } void IrDsymbol::setDeclared() { - if (m_state < Declared) + if (m_state < Declared) { m_state = Declared; + } } void IrDsymbol::setInitialized() { - if (m_state < Initialized) + if (m_state < Initialized) { m_state = Initialized; + } } void IrDsymbol::setDefined() { - if (m_state < Defined) + if (m_state < Defined) { m_state = Defined; + } } diff --git a/ir/irfunction.cpp b/ir/irfunction.cpp index 4b5051a167..a4f56ed5a8 100644 --- a/ir/irfunction.cpp +++ b/ir/irfunction.cpp @@ -23,7 +23,7 @@ JumpTarget::JumpTarget(llvm::BasicBlock *targetBlock, GotoJump::GotoJump(Loc loc, llvm::BasicBlock *sourceBlock, llvm::BasicBlock *tentativeTarget, Identifier *targetLabel) - : sourceLoc(loc), sourceBlock(sourceBlock), + : sourceLoc(std::move(loc)), sourceBlock(sourceBlock), tentativeTarget(tentativeTarget), targetLabel(targetLabel) {} CatchScope::CatchScope(llvm::Constant *classInfoPtr, @@ -119,8 +119,9 @@ ScopeStack::~ScopeStack() { // down or "sideways" (i.e. down another branch) of the tree of all // cleanup scopes, both of which are not allowed in D. if (!topLevelUnresolvedGotos.empty()) { - for (const auto &i : topLevelUnresolvedGotos) + for (const auto &i : topLevelUnresolvedGotos) { error(i.sourceLoc, "goto into try/finally scope is not allowed"); + } fatal(); } } @@ -159,8 +160,9 @@ void ScopeStack::runAllCleanups(llvm::BasicBlock *continueWith) { void ScopeStack::popCleanups(CleanupCursor targetScope) { assert(targetScope <= currentCleanupScope()); - if (targetScope == currentCleanupScope()) + if (targetScope == currentCleanupScope()) { return; + } for (CleanupCursor i = currentCleanupScope(); i-- > targetScope;) { // Any gotos that are still unresolved necessarily leave this scope. @@ -219,7 +221,7 @@ void ScopeStack::popBreakTarget() { breakTargets.pop_back(); } void ScopeStack::addLabelTarget(Identifier *labelName, llvm::BasicBlock *targetBlock) { - labelTargets[labelName] = {targetBlock, currentCleanupScope(), 0}; + labelTargets[labelName] = {targetBlock, currentCleanupScope(), nullptr}; // See whether any of the unresolved gotos target this label, and resolve // those that do. @@ -254,9 +256,7 @@ void ScopeStack::jumpToLabel(Loc loc, Identifier *labelName) { void ScopeStack::jumpToStatement(std::vector &targets, Statement *loopOrSwitchStatement) { - for (std::vector::reverse_iterator it = targets.rbegin(), - end = targets.rend(); - it != end; ++it) { + for (auto it = targets.rbegin(), end = targets.rend(); it != end; ++it) { if (it->targetStatement == loopOrSwitchStatement) { runCleanups(it->cleanupScope, it->targetBlock); return; diff --git a/ir/irfunction.h b/ir/irfunction.h index b809c620a9..19311ce1ba 100644 --- a/ir/irfunction.h +++ b/ir/irfunction.h @@ -372,7 +372,7 @@ llvm::CallSite ScopeStack::callOrInvoke(llvm::Value *callee, const T &args, // Have not encountered any catches (for which we would push a scope) or // calls to throwing functions (where we would have already executed // this if) in this cleanup scope yet. - currentLandingPads().push_back(0); + currentLandingPads().push_back(nullptr); } llvm::BasicBlock *&landingPad = currentLandingPads().back(); @@ -396,7 +396,7 @@ llvm::CallSite ScopeStack::callOrInvoke(llvm::Value *callee, const T &args, // represents a function struct IrFunction { // constructor - IrFunction(FuncDeclaration *fd); + explicit IrFunction(FuncDeclaration *fd); // annotations void setNeverInline(); diff --git a/ir/irfuncty.cpp b/ir/irfuncty.cpp index 2e11f7198f..35f6f4de86 100644 --- a/ir/irfuncty.cpp +++ b/ir/irfuncty.cpp @@ -15,10 +15,10 @@ #include "gen/logger.h" #include "gen/tollvm.h" -IrFuncTyArg::IrFuncTyArg(Type *t, bool bref, const AttrBuilder &a) +IrFuncTyArg::IrFuncTyArg(Type *t, bool bref, AttrBuilder a) : type(t), ltype(t != Type::tvoid && bref ? DtoType(t->pointerTo()) : DtoType(t)), - attrs(a), byref(bref) {} + attrs(std::move(a)), byref(bref) {} bool IrFuncTyArg::isInReg() const { return attrs.contains(LLAttribute::InReg); } bool IrFuncTyArg::isSRet() const { diff --git a/ir/irfuncty.h b/ir/irfuncty.h index 5dcd577b4b..ca913e23a3 100644 --- a/ir/irfuncty.h +++ b/ir/irfuncty.h @@ -78,7 +78,7 @@ struct IrFuncTyArg { * @param byref Initial value for the 'byref' field. If true the initial * LLVM Type will be of DtoType(type->pointerTo()), instead * of just DtoType(type) */ - IrFuncTyArg(Type *t, bool byref, const AttrBuilder &attrs = AttrBuilder()); + IrFuncTyArg(Type *t, bool byref, AttrBuilder attrs = AttrBuilder()); }; // represents a function type diff --git a/ir/irmodule.cpp b/ir/irmodule.cpp index 5b3879a040..98e71c72d1 100644 --- a/ir/irmodule.cpp +++ b/ir/irmodule.cpp @@ -18,8 +18,9 @@ IrModule::IrModule(Module *module, const char *srcfilename) : M(module) {} llvm::GlobalVariable *IrModule::moduleInfoSymbol() { - if (moduleInfoVar) + if (moduleInfoVar) { return moduleInfoVar; + } std::string name("_D"); name.append(mangle(M)); @@ -27,13 +28,14 @@ llvm::GlobalVariable *IrModule::moduleInfoSymbol() { moduleInfoVar = new llvm::GlobalVariable( gIR->module, llvm::StructType::create(gIR->context()), false, - llvm::GlobalValue::ExternalLinkage, NULL, name); + llvm::GlobalValue::ExternalLinkage, nullptr, name); return moduleInfoVar; } IrModule *getIrModule(Module *m) { - if (!m) + if (!m) { m = gIR->func()->decl->getModule(); + } assert(m && "null module"); if (m->ir.m_type == IrDsymbol::NotSet) { diff --git a/ir/irtype.cpp b/ir/irtype.cpp index e44fb820fd..65376bab8c 100644 --- a/ir/irtype.cpp +++ b/ir/irtype.cpp @@ -43,7 +43,7 @@ IrTypeBasic::IrTypeBasic(Type *dt) : IrType(dt, basic2llvm(dt)) {} ////////////////////////////////////////////////////////////////////////////// IrTypeBasic *IrTypeBasic::get(Type *dt) { - IrTypeBasic *t = new IrTypeBasic(dt); + auto t = new IrTypeBasic(dt); dt->ctype = t; return t; } @@ -62,8 +62,9 @@ static inline llvm::Type *getReal80Type(llvm::LLVMContext &ctx) { bool const anyX86 = (a == llvm::Triple::x86) || (a == llvm::Triple::x86_64); // only x86 has 80bit float - but no support with MS C Runtime! - if (anyX86 && !global.params.targetTriple.isWindowsMSVCEnvironment()) + if (anyX86 && !global.params.targetTriple.isWindowsMSVCEnvironment()) { return llvm::Type::getX86_FP80Ty(ctx); + } return llvm::Type::getDoubleTy(ctx); } @@ -148,11 +149,12 @@ IrTypePointer *IrTypePointer::get(Type *dt) { // DtoType could have already created the same type, e.g. for // dt == Node* in struct Node { Node* n; }. - if (dt->ctype) + if (dt->ctype) { return dt->ctype->isPointer(); + } } - IrTypePointer *t = new IrTypePointer(dt, llvm::PointerType::get(elemType, 0)); + auto t = new IrTypePointer(dt, llvm::PointerType::get(elemType, 0)); dt->ctype = t; return t; } @@ -166,7 +168,7 @@ IrTypeSArray::IrTypeSArray(Type *dt) : IrType(dt, sarray2llvm(dt)) {} ////////////////////////////////////////////////////////////////////////////// IrTypeSArray *IrTypeSArray::get(Type *dt) { - IrTypeSArray *t = new IrTypeSArray(dt); + auto t = new IrTypeSArray(dt); dt->ctype = t; return t; } @@ -215,7 +217,7 @@ IrTypeVector::IrTypeVector(Type *dt) : IrType(dt, vector2llvm(dt)) {} ////////////////////////////////////////////////////////////////////////////// IrTypeVector *IrTypeVector::get(Type *dt) { - IrTypeVector *t = new IrTypeVector(dt); + auto t = new IrTypeVector(dt); dt->ctype = t; return t; } diff --git a/ir/irtype.h b/ir/irtype.h index d81fa730dd..8498b82752 100644 --- a/ir/irtype.h +++ b/ir/irtype.h @@ -110,11 +110,11 @@ public: static IrTypeBasic *get(Type *dt); /// - IrTypeBasic *isBasic() { return this; } + IrTypeBasic *isBasic() override { return this; } protected: /// - IrTypeBasic(Type *dt); + explicit IrTypeBasic(Type *dt); /// static llvm::Type *getComplexType(llvm::LLVMContext &ctx, llvm::Type *type); /// @@ -130,7 +130,7 @@ public: static IrTypePointer *get(Type *dt); /// - IrTypePointer *isPointer() { return this; } + IrTypePointer *isPointer() override { return this; } protected: /// @@ -146,11 +146,11 @@ public: static IrTypeSArray *get(Type *dt); /// - IrTypeSArray *isSArray() { return this; } + IrTypeSArray *isSArray() override { return this; } protected: /// - IrTypeSArray(Type *dt); + explicit IrTypeSArray(Type *dt); /// static llvm::Type *sarray2llvm(Type *t); @@ -165,7 +165,7 @@ public: static IrTypeArray *get(Type *dt); /// - IrTypeArray *isArray() { return this; } + IrTypeArray *isArray() override { return this; } protected: /// @@ -181,11 +181,11 @@ public: static IrTypeVector *get(Type *dt); /// - IrTypeVector *isVector() { return this; } + IrTypeVector *isVector() override { return this; } protected: /// - IrTypeVector(Type *dt); + explicit IrTypeVector(Type *dt); static llvm::Type *vector2llvm(Type *dt); }; diff --git a/ir/irtypeaggr.cpp b/ir/irtypeaggr.cpp index 4f412431f4..76adddd3f2 100644 --- a/ir/irtypeaggr.cpp +++ b/ir/irtypeaggr.cpp @@ -35,8 +35,9 @@ static inline size_t add_zeros(std::vector &defaultTypes, } bool var_offset_sort_cb(const VarDeclaration *v1, const VarDeclaration *v2) { - if (v1 && v2) + if (v1 && v2) { return v1->offset < v2->offset; + } // sort NULL pointers towards the end return v1 && !v2; } @@ -54,7 +55,7 @@ void AggrTypeBuilder::addType(llvm::Type *type, unsigned size) { void AggrTypeBuilder::addAggregate(AggregateDeclaration *ad) { // mirror the ad->fields array but only fill in contributors const size_t n = ad->fields.dim; - LLSmallVector data(n, NULL); + LLSmallVector data(n, nullptr); unsigned int errors = global.errors; @@ -63,27 +64,29 @@ void AggrTypeBuilder::addAggregate(AggregateDeclaration *ad) { VarDeclaration *field = ad->fields[index]; // init is !null for explicit inits - if (field->init != NULL && !field->init->isVoidInitializer()) { + if (field->init != nullptr && !field->init->isVoidInitializer()) { IF_LOG Logger::println("adding explicit initializer for struct field %s", field->toChars()); size_t f_size = field->type->size(); size_t f_begin = field->offset; size_t f_end = f_begin + f_size; - if (f_size == 0) + if (f_size == 0) { continue; + } data[index] = field; // make sure there is no overlap for (size_t i = 0; i < index; i++) { - if (data[i] != NULL) { + if (data[i] != nullptr) { VarDeclaration *vd = data[i]; size_t v_begin = vd->offset; size_t v_end = v_begin + vd->type->size(); - if (v_begin >= f_end || v_end <= f_begin) + if (v_begin >= f_end || v_end <= f_begin) { continue; + } ad->error(vd->loc, "has overlapping initialization for %s and %s", field->toChars(), vd->toChars()); @@ -95,22 +98,25 @@ void AggrTypeBuilder::addAggregate(AggregateDeclaration *ad) { if (errors != global.errors) { // There was an overlapping initialization. // Return if errors are gagged otherwise abort. - if (global.gag) + if (global.gag) { return; + } fatal(); } // fill in default initializers for (size_t index = 0; index < n; ++index) { - if (data[index]) + if (data[index]) { continue; + } VarDeclaration *field = ad->fields[index]; size_t f_size = field->type->size(); size_t f_begin = field->offset; size_t f_end = f_begin + f_size; - if (f_size == 0) + if (f_size == 0) { continue; + } // make sure it doesn't overlap anything explicit bool overlaps = false; @@ -119,8 +125,9 @@ void AggrTypeBuilder::addAggregate(AggregateDeclaration *ad) { size_t v_begin = data[i]->offset; size_t v_end = v_begin + data[i]->type->size(); - if (v_begin >= f_end || v_end <= f_begin) + if (v_begin >= f_end || v_end <= f_begin) { continue; + } overlaps = true; break; @@ -147,8 +154,9 @@ void AggrTypeBuilder::addAggregate(AggregateDeclaration *ad) { for (size_t i = 0; i < n; i++) { VarDeclaration *vd = data[i]; - if (vd == NULL) + if (vd == nullptr) { continue; + } assert(vd->offset >= m_offset && "Variable overlaps previous field."); @@ -197,13 +205,15 @@ IrTypeAggr::IrTypeAggr(AggregateDeclaration *ad) aggr(ad) {} bool IrTypeAggr::isPacked(AggregateDeclaration *ad) { - if (ad->isUnionDeclaration()) + if (ad->isUnionDeclaration()) { return true; + } for (unsigned i = 0; i < ad->fields.dim; i++) { VarDeclaration *vd = static_cast(ad->fields.data[i]); unsigned a = vd->type->alignsize() - 1; - if (((vd->offset + a) & ~a) != vd->offset) + if (((vd->offset + a) & ~a) != vd->offset) { return true; + } } return false; } @@ -213,8 +223,7 @@ void IrTypeAggr::getMemberLocation(VarDeclaration *var, unsigned &fieldIndex, // Note: The interface is a bit more general than what we actually return. // Specifically, the frontend offset information we use for overlapping // fields is always based at the object start. - std::map::const_iterator it = - varGEPIndices.find(var); + auto it = varGEPIndices.find(var); if (it != varGEPIndices.end()) { fieldIndex = it->second; byteOffset = 0; diff --git a/ir/irtypeaggr.h b/ir/irtypeaggr.h index 8717dc2d48..f45579c947 100644 --- a/ir/irtypeaggr.h +++ b/ir/irtypeaggr.h @@ -51,7 +51,7 @@ protected: class IrTypeAggr : public IrType { public: /// - IrTypeAggr *isAggr() { return this; } + IrTypeAggr *isAggr() override { return this; } /// Returns the index of the field in the LLVM struct type that corresponds /// to the given member variable, plus the offset to the actual field start @@ -72,7 +72,7 @@ public: protected: /// - IrTypeAggr(AggregateDeclaration *ad); + explicit IrTypeAggr(AggregateDeclaration *ad); /// Returns true, if the LLVM struct type for the aggregate must be declared /// as packed. diff --git a/ir/irtypeclass.cpp b/ir/irtypeclass.cpp index 46b128ff5f..4334001a61 100644 --- a/ir/irtypeclass.cpp +++ b/ir/irtypeclass.cpp @@ -76,7 +76,7 @@ void IrTypeClass::addBaseClassData(AggrTypeBuilder &builder, ////////////////////////////////////////////////////////////////////////////// IrTypeClass *IrTypeClass::get(ClassDeclaration *cd) { - IrTypeClass *t = new IrTypeClass(cd); + auto t = new IrTypeClass(cd); cd->type->ctype = t; IF_LOG Logger::println("Building class type %s @ %s", cd->toPrettyChars(), @@ -86,7 +86,7 @@ IrTypeClass *IrTypeClass::get(ClassDeclaration *cd) { // This class may contain an align declaration. See issue 726. t->packed = false; - for (ClassDeclaration *base = cd; base != 0 && !t->packed; + for (ClassDeclaration *base = cd; base != nullptr && !t->packed; base = base->baseClass) { t->packed = isPacked(base); } @@ -117,8 +117,9 @@ IrTypeClass *IrTypeClass::get(ClassDeclaration *cd) { } // errors are fatal during codegen - if (global.errors) + if (global.errors) { fatal(); + } // set struct body and copy GEP indices isaStruct(t->type)->setBody(builder.defaultTypes(), t->packed); @@ -129,7 +130,7 @@ IrTypeClass *IrTypeClass::get(ClassDeclaration *cd) { // set vtbl type body FuncDeclarations vtbl; vtbl.reserve(cd->vtbl.dim); - vtbl.push(0); + vtbl.push(nullptr); for (size_t i = cd->vtblOffset(); i < cd->vtbl.dim; ++i) { FuncDeclaration *fd = cd->vtbl[i]->isFuncDeclaration(); assert(fd); @@ -154,13 +155,14 @@ IrTypeClass::buildVtblType(Type *first, FuncDeclarations *vtbl_array) { types.reserve(vtbl_array->dim); // first comes the classinfo - if (!cd->isCPPclass() && !cd->isCPPinterface()) + if (!cd->isCPPclass() && !cd->isCPPinterface()) { types.push_back(DtoType(first)); + } // then come the functions for (auto I = vtbl_array->begin() + 1, E = vtbl_array->end(); I != E; ++I) { FuncDeclaration *fd = *I; - if (fd == NULL) { + if (fd == nullptr) { // FIXME // why is this null? // happens for mini/s.d @@ -178,8 +180,9 @@ IrTypeClass::buildVtblType(Type *first, FuncDeclarations *vtbl_array) { TemplateInstance *spec = fd->isSpeculative(); unsigned int olderrs = global.errors; fd->semantic3(fd->scope); - if (spec && global.errors != olderrs) + if (spec && global.errors != olderrs) { spec->errors = global.errors - olderrs; + } } if (!fd->type->nextOf()) { @@ -209,8 +212,9 @@ llvm::Type *IrTypeClass::getMemoryLLType() { return type; } size_t IrTypeClass::getInterfaceIndex(ClassDeclaration *inter) { auto it = interfaceMap.find(inter); - if (it == interfaceMap.end()) + if (it == interfaceMap.end()) { return ~0UL; + } return it->second; } @@ -218,8 +222,9 @@ size_t IrTypeClass::getInterfaceIndex(ClassDeclaration *inter) { void IrTypeClass::addInterfaceToMap(ClassDeclaration *inter, size_t index) { // don't duplicate work or overwrite indices - if (interfaceMap.find(inter) != interfaceMap.end()) + if (interfaceMap.find(inter) != interfaceMap.end()) { return; + } // add this interface interfaceMap.insert(std::make_pair(inter, index)); diff --git a/ir/irtypeclass.h b/ir/irtypeclass.h index 07f0b756f8..9d579e0a09 100644 --- a/ir/irtypeclass.h +++ b/ir/irtypeclass.h @@ -27,10 +27,10 @@ public: static IrTypeClass *get(ClassDeclaration *cd); /// - virtual IrTypeClass *isClass() { return this; } + IrTypeClass *isClass() override { return this; } /// - llvm::Type *getLLType(); + llvm::Type *getLLType() override; /// Returns the actual storage type, i.e. without the indirection /// for the class reference. @@ -53,7 +53,7 @@ public: protected: /// - IrTypeClass(ClassDeclaration *cd); + explicit IrTypeClass(ClassDeclaration *cd); /// ClassDeclaration *cd = nullptr; diff --git a/ir/irtypefunction.cpp b/ir/irtypefunction.cpp index 5a888aae93..1183de0529 100644 --- a/ir/irtypefunction.cpp +++ b/ir/irtypefunction.cpp @@ -16,25 +16,25 @@ #include "ir/irtypefunction.h" -IrTypeFunction::IrTypeFunction(Type *dt, llvm::Type *lt, const IrFuncTy &irFty_) - : IrType(dt, lt), irFty(irFty_) {} +IrTypeFunction::IrTypeFunction(Type *dt, llvm::Type *lt, IrFuncTy irFty_) + : IrType(dt, lt), irFty(std::move(irFty_)) {} IrTypeFunction *IrTypeFunction::get(Type *dt) { assert(!dt->ctype); assert(dt->ty == Tfunction); IrFuncTy irFty; - llvm::Type *lt = DtoFunctionType(dt, irFty, NULL, NULL); + llvm::Type *lt = DtoFunctionType(dt, irFty, nullptr, nullptr); - IrTypeFunction *result = new IrTypeFunction(dt, lt, irFty); + auto result = new IrTypeFunction(dt, lt, irFty); dt->ctype = result; return result; } ////////////////////////////////////////////////////////////////////////////// -IrTypeDelegate::IrTypeDelegate(Type *dt, llvm::Type *lt, const IrFuncTy &irFty_) - : IrType(dt, lt), irFty(irFty_) {} +IrTypeDelegate::IrTypeDelegate(Type *dt, llvm::Type *lt, IrFuncTy irFty_) + : IrType(dt, lt), irFty(std::move(irFty_)) {} IrTypeDelegate *IrTypeDelegate::get(Type *t) { assert(!t->ctype); @@ -43,11 +43,11 @@ IrTypeDelegate *IrTypeDelegate::get(Type *t) { IrFuncTy irFty; llvm::Type *ltf = - DtoFunctionType(t->nextOf(), irFty, NULL, Type::tvoid->pointerTo()); + DtoFunctionType(t->nextOf(), irFty, nullptr, Type::tvoid->pointerTo()); llvm::Type *types[] = {getVoidPtrType(), getPtrToType(ltf)}; LLStructType *lt = LLStructType::get(gIR->context(), types, false); - IrTypeDelegate *result = new IrTypeDelegate(t, lt, irFty); + auto result = new IrTypeDelegate(t, lt, irFty); t->ctype = result; return result; } diff --git a/ir/irtypefunction.h b/ir/irtypefunction.h index ea4d55e8ea..91c56727b3 100644 --- a/ir/irtypefunction.h +++ b/ir/irtypefunction.h @@ -25,14 +25,14 @@ public: static IrTypeFunction *get(Type *dt); /// - IrTypeFunction *isFunction() { return this; } + IrTypeFunction *isFunction() override { return this; } /// - IrFuncTy &getIrFuncTy() { return irFty; } + IrFuncTy &getIrFuncTy() override { return irFty; } protected: /// - IrTypeFunction(Type *dt, llvm::Type *lt, const IrFuncTy &irFty); + IrTypeFunction(Type *dt, llvm::Type *lt, IrFuncTy irFty); /// IrFuncTy irFty; }; @@ -44,14 +44,14 @@ public: static IrTypeDelegate *get(Type *dt); /// - IrTypeDelegate *isDelegate() { return this; } + IrTypeDelegate *isDelegate() override { return this; } /// - IrFuncTy &getIrFuncTy() { return irFty; } + IrFuncTy &getIrFuncTy() override { return irFty; } protected: /// - IrTypeDelegate(Type *dt, LLType *lt, const IrFuncTy &irFty); + IrTypeDelegate(Type *dt, LLType *lt, IrFuncTy irFty); /// IrFuncTy irFty; }; diff --git a/ir/irtypestruct.cpp b/ir/irtypestruct.cpp index 2b6d30f7c1..8fdab7df2a 100644 --- a/ir/irtypestruct.cpp +++ b/ir/irtypestruct.cpp @@ -30,7 +30,7 @@ IrTypeStruct::IrTypeStruct(StructDeclaration *sd) ////////////////////////////////////////////////////////////////////////////// IrTypeStruct *IrTypeStruct::get(StructDeclaration *sd) { - IrTypeStruct *t = new IrTypeStruct(sd); + auto t = new IrTypeStruct(sd); sd->type->ctype = t; IF_LOG Logger::println("Building struct type %s @ %s", sd->toPrettyChars(), @@ -38,8 +38,9 @@ IrTypeStruct *IrTypeStruct::get(StructDeclaration *sd) { LOG_SCOPE; // if it's a forward declaration, all bets are off, stick with the opaque - if (sd->sizeok != SIZEOKdone) + if (sd->sizeok != SIZEOKdone) { return t; + } t->packed = sd->alignment == 1; if (!t->packed) { diff --git a/ir/irtypestruct.h b/ir/irtypestruct.h index 2b321e4f1b..b5df2ec7c7 100644 --- a/ir/irtypestruct.h +++ b/ir/irtypestruct.h @@ -22,11 +22,11 @@ public: static IrTypeStruct *get(StructDeclaration *sd); /// - IrTypeStruct *isStruct() { return this; } + IrTypeStruct *isStruct() override { return this; } protected: /// - IrTypeStruct(StructDeclaration *sd); + explicit IrTypeStruct(StructDeclaration *sd); /// StructDeclaration this type represents. StructDeclaration *sd = nullptr;