diff options
Diffstat (limited to 'clang/lib')
37 files changed, 298 insertions, 243 deletions
diff --git a/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp b/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp index 3288585..d474605 100644 --- a/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp +++ b/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp @@ -137,21 +137,21 @@ int32_t ByteCodeEmitter::getOffset(LabelTy Label) { template <typename T> static void emit(Program &P, std::vector<std::byte> &Code, const T &Val, bool &Success) { + size_t ValPos = Code.size(); size_t Size; if constexpr (std::is_pointer_v<T>) - Size = sizeof(uint32_t); + Size = align(sizeof(uint32_t)); else - Size = sizeof(T); + Size = align(sizeof(T)); - if (Code.size() + Size > std::numeric_limits<unsigned>::max()) { + if (ValPos + Size > std::numeric_limits<unsigned>::max()) { Success = false; return; } // Access must be aligned! - size_t ValPos = align(Code.size()); - Size = align(Size); + assert(aligned(ValPos)); assert(aligned(ValPos + Size)); Code.resize(ValPos + Size); @@ -168,17 +168,16 @@ static void emit(Program &P, std::vector<std::byte> &Code, const T &Val, template <typename T> static void emitSerialized(std::vector<std::byte> &Code, const T &Val, bool &Success) { - size_t Size = Val.bytesToSerialize(); + size_t ValPos = Code.size(); + size_t Size = align(Val.bytesToSerialize()); - if (Code.size() + Size > std::numeric_limits<unsigned>::max()) { + if (ValPos + Size > std::numeric_limits<unsigned>::max()) { Success = false; return; } // Access must be aligned! - assert(aligned(Code.size())); - size_t ValPos = Code.size(); - Size = align(Size); + assert(aligned(ValPos)); assert(aligned(ValPos + Size)); Code.resize(ValPos + Size); diff --git a/clang/lib/AST/ByteCode/Compiler.cpp b/clang/lib/AST/ByteCode/Compiler.cpp index 8b9e5e0..6e451ac 100644 --- a/clang/lib/AST/ByteCode/Compiler.cpp +++ b/clang/lib/AST/ByteCode/Compiler.cpp @@ -331,6 +331,8 @@ bool Compiler<Emitter>::VisitCastExpr(const CastExpr *CE) { } case CK_FloatingToIntegral: { + if (!CE->getType()->isIntegralOrEnumerationType()) + return false; if (!this->visit(SubExpr)) return false; PrimType ToT = classifyPrim(CE); @@ -1369,10 +1371,15 @@ bool Compiler<Emitter>::VisitVectorBinOp(const BinaryOperator *E) { // BitAdd/BitOr/BitXor/Shl/Shr doesn't support bool type, we need perform the // integer promotion. bool NeedIntPromot = ElemT == PT_Bool && (E->isBitwiseOp() || E->isShiftOp()); - QualType PromotTy = - Ctx.getASTContext().getPromotedIntegerType(Ctx.getASTContext().BoolTy); - PrimType PromotT = classifyPrim(PromotTy); - PrimType OpT = NeedIntPromot ? PromotT : ElemT; + QualType PromotTy; + PrimType PromotT = PT_Bool; + PrimType OpT = ElemT; + if (NeedIntPromot) { + PromotTy = + Ctx.getASTContext().getPromotedIntegerType(Ctx.getASTContext().BoolTy); + PromotT = classifyPrim(PromotTy); + OpT = PromotT; + } auto getElem = [=](unsigned Offset, PrimType ElemT, unsigned Index) { if (!this->emitGetLocal(PT_Ptr, Offset, E)) diff --git a/clang/lib/AST/ByteCode/Context.cpp b/clang/lib/AST/ByteCode/Context.cpp index aaeb52e..7215e1dd 100644 --- a/clang/lib/AST/ByteCode/Context.cpp +++ b/clang/lib/AST/ByteCode/Context.cpp @@ -15,6 +15,7 @@ #include "InterpStack.h" #include "PrimType.h" #include "Program.h" +#include "clang/AST/ASTLambda.h" #include "clang/AST/Expr.h" #include "clang/Basic/TargetInfo.h" diff --git a/clang/lib/AST/ByteCode/Context.h b/clang/lib/AST/ByteCode/Context.h index 62ef529..1c084ac 100644 --- a/clang/lib/AST/ByteCode/Context.h +++ b/clang/lib/AST/ByteCode/Context.h @@ -17,9 +17,9 @@ #define LLVM_CLANG_AST_INTERP_CONTEXT_H #include "InterpStack.h" +#include "clang/AST/ASTContext.h" namespace clang { -class ASTContext; class LangOptions; class FunctionDecl; class VarDecl; diff --git a/clang/lib/AST/ByteCode/Descriptor.cpp b/clang/lib/AST/ByteCode/Descriptor.cpp index 5b9f445..7403e90 100644 --- a/clang/lib/AST/ByteCode/Descriptor.cpp +++ b/clang/lib/AST/ByteCode/Descriptor.cpp @@ -21,14 +21,31 @@ using namespace clang; using namespace clang::interp; +template <typename T> static constexpr bool needsCtor() { + if constexpr (std::is_same_v<T, Integral<8, true>> || + std::is_same_v<T, Integral<8, false>> || + std::is_same_v<T, Integral<16, true>> || + std::is_same_v<T, Integral<16, false>> || + std::is_same_v<T, Integral<32, true>> || + std::is_same_v<T, Integral<32, false>> || + std::is_same_v<T, Integral<64, true>> || + std::is_same_v<T, Integral<64, false>> || + std::is_same_v<T, Boolean>) + return false; + + return true; +} + template <typename T> static void ctorTy(Block *, std::byte *Ptr, bool, bool, bool, bool, bool, const Descriptor *) { + static_assert(needsCtor<T>()); new (Ptr) T(); } template <typename T> static void dtorTy(Block *, std::byte *Ptr, const Descriptor *) { + static_assert(needsCtor<T>()); reinterpret_cast<T *>(Ptr)->~T(); } @@ -45,9 +62,11 @@ static void ctorArrayTy(Block *, std::byte *Ptr, bool, bool, bool, bool, bool, const Descriptor *D) { new (Ptr) InitMapPtr(std::nullopt); - Ptr += sizeof(InitMapPtr); - for (unsigned I = 0, NE = D->getNumElems(); I < NE; ++I) { - new (&reinterpret_cast<T *>(Ptr)[I]) T(); + if constexpr (needsCtor<T>()) { + Ptr += sizeof(InitMapPtr); + for (unsigned I = 0, NE = D->getNumElems(); I < NE; ++I) { + new (&reinterpret_cast<T *>(Ptr)[I]) T(); + } } } @@ -57,9 +76,12 @@ static void dtorArrayTy(Block *, std::byte *Ptr, const Descriptor *D) { if (IMP) IMP = std::nullopt; - Ptr += sizeof(InitMapPtr); - for (unsigned I = 0, NE = D->getNumElems(); I < NE; ++I) { - reinterpret_cast<T *>(Ptr)[I].~T(); + + if constexpr (needsCtor<T>()) { + Ptr += sizeof(InitMapPtr); + for (unsigned I = 0, NE = D->getNumElems(); I < NE; ++I) { + reinterpret_cast<T *>(Ptr)[I].~T(); + } } } @@ -74,10 +96,14 @@ static void moveArrayTy(Block *, std::byte *Src, std::byte *Dst, } Src += sizeof(InitMapPtr); Dst += sizeof(InitMapPtr); - for (unsigned I = 0, NE = D->getNumElems(); I < NE; ++I) { - auto *SrcPtr = &reinterpret_cast<T *>(Src)[I]; - auto *DstPtr = &reinterpret_cast<T *>(Dst)[I]; - new (DstPtr) T(std::move(*SrcPtr)); + if constexpr (!needsCtor<T>()) { + std::memcpy(Dst, Src, D->getNumElems() * D->getElemSize()); + } else { + for (unsigned I = 0, NE = D->getNumElems(); I < NE; ++I) { + auto *SrcPtr = &reinterpret_cast<T *>(Src)[I]; + auto *DstPtr = &reinterpret_cast<T *>(Dst)[I]; + new (DstPtr) T(std::move(*SrcPtr)); + } } } diff --git a/clang/lib/AST/ByteCode/Function.cpp b/clang/lib/AST/ByteCode/Function.cpp index 0e639df3..a513be5 100644 --- a/clang/lib/AST/ByteCode/Function.cpp +++ b/clang/lib/AST/ByteCode/Function.cpp @@ -8,6 +8,7 @@ #include "Function.h" #include "Program.h" +#include "clang/AST/ASTLambda.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" diff --git a/clang/lib/AST/ByteCode/Function.h b/clang/lib/AST/ByteCode/Function.h index de88f3d..64bffc4 100644 --- a/clang/lib/AST/ByteCode/Function.h +++ b/clang/lib/AST/ByteCode/Function.h @@ -17,9 +17,9 @@ #include "Descriptor.h" #include "Source.h" -#include "clang/AST/ASTLambda.h" #include "clang/AST/Attr.h" #include "clang/AST/Decl.h" +#include "clang/AST/DeclCXX.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/Support/raw_ostream.h" diff --git a/clang/lib/AST/ByteCode/InterpState.cpp b/clang/lib/AST/ByteCode/InterpState.cpp index 3010847..a06b125 100644 --- a/clang/lib/AST/ByteCode/InterpState.cpp +++ b/clang/lib/AST/ByteCode/InterpState.cpp @@ -11,6 +11,8 @@ #include "InterpStack.h" #include "Program.h" #include "State.h" +#include "clang/AST/DeclCXX.h" +#include "clang/AST/DeclTemplate.h" using namespace clang; using namespace clang::interp; @@ -77,27 +79,27 @@ void InterpState::deallocate(Block *B) { const Descriptor *Desc = B->getDescriptor(); assert(Desc); + // The block might have a pointer saved in a field in its data + // that points to the block itself. We call the dtor first, + // which will destroy all the data but leave InlineDescriptors + // intact. If the block THEN still has pointers, we create a + // DeadBlock for it. + if (B->IsInitialized) + B->invokeDtor(); + if (B->hasPointers()) { size_t Size = B->getSize(); - // Allocate a new block, transferring over pointers. char *Memory = reinterpret_cast<char *>(std::malloc(sizeof(DeadBlock) + Size)); auto *D = new (Memory) DeadBlock(DeadBlocks, B); - std::memset(D->B.rawData(), 0, D->B.getSize()); - - // Move data and metadata from the old block to the new (dead)block. - if (B->IsInitialized && Desc->MoveFn) { - Desc->MoveFn(B, B->data(), D->data(), Desc); - if (Desc->getMetadataSize() > 0) - std::memcpy(D->rawData(), B->rawData(), Desc->getMetadataSize()); - } + // Since the block doesn't hold any actual data anymore, we can just + // memcpy() everything over. + std::memcpy(D->rawData(), B->rawData(), Desc->getAllocSize()); D->B.IsInitialized = B->IsInitialized; // We moved the contents over to the DeadBlock. B->IsInitialized = false; - } else if (B->IsInitialized) { - B->invokeDtor(); } } diff --git a/clang/lib/AST/ByteCode/PrimType.h b/clang/lib/AST/ByteCode/PrimType.h index 38c29b9..724da93 100644 --- a/clang/lib/AST/ByteCode/PrimType.h +++ b/clang/lib/AST/ByteCode/PrimType.h @@ -13,7 +13,6 @@ #ifndef LLVM_CLANG_AST_INTERP_TYPE_H #define LLVM_CLANG_AST_INTERP_TYPE_H -#include "clang/Basic/UnsignedOrNone.h" #include "llvm/Support/raw_ostream.h" #include <climits> #include <cstddef> diff --git a/clang/lib/AST/ByteCode/Program.cpp b/clang/lib/AST/ByteCode/Program.cpp index 2421ec4..4daa4ab 100644 --- a/clang/lib/AST/ByteCode/Program.cpp +++ b/clang/lib/AST/ByteCode/Program.cpp @@ -13,6 +13,7 @@ #include "PrimType.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" +#include "clang/AST/DeclTemplate.h" using namespace clang; using namespace clang::interp; diff --git a/clang/lib/AST/MicrosoftMangle.cpp b/clang/lib/AST/MicrosoftMangle.cpp index bc47e05..e6ea0ad 100644 --- a/clang/lib/AST/MicrosoftMangle.cpp +++ b/clang/lib/AST/MicrosoftMangle.cpp @@ -1298,8 +1298,7 @@ void MicrosoftCXXNameMangler::mangleUnqualifiedName(GlobalDecl GD, Name += "<unnamed-type-"; Name += TND->getName(); } else if (isa<EnumDecl>(TD) && - cast<EnumDecl>(TD)->enumerator_begin() != - cast<EnumDecl>(TD)->enumerator_end()) { + !cast<EnumDecl>(TD)->enumerators().empty()) { // Anonymous non-empty enums mangle in the first enumerator. auto *ED = cast<EnumDecl>(TD); Name += "<unnamed-enum-"; diff --git a/clang/lib/CIR/CodeGen/CIRGenDecl.cpp b/clang/lib/CIR/CodeGen/CIRGenDecl.cpp index 9cdbebe..78d375c 100644 --- a/clang/lib/CIR/CodeGen/CIRGenDecl.cpp +++ b/clang/lib/CIR/CodeGen/CIRGenDecl.cpp @@ -158,7 +158,7 @@ void CIRGenFunction::emitAutoVarInit( // out of it while trying to build the expression, mark it as such. mlir::Value val = lv.getAddress().getPointer(); assert(val && "Should have an address"); - auto allocaOp = dyn_cast_or_null<cir::AllocaOp>(val.getDefiningOp()); + auto allocaOp = val.getDefiningOp<cir::AllocaOp>(); assert(allocaOp && "Address should come straight out of the alloca"); if (!allocaOp.use_empty()) @@ -412,7 +412,8 @@ void CIRGenFunction::emitStaticVarDecl(const VarDecl &d, // TODO(cir): we should have a way to represent global ops as values without // having to emit a get global op. Sometimes these emissions are not used. mlir::Value addr = builder.createGetGlobal(globalOp); - auto getAddrOp = mlir::cast<cir::GetGlobalOp>(addr.getDefiningOp()); + auto getAddrOp = addr.getDefiningOp<cir::GetGlobalOp>(); + assert(getAddrOp && "expected cir::GetGlobalOp"); CharUnits alignment = getContext().getDeclAlign(&d); diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp index 761d8d3..cd37a2b 100644 --- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp +++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp @@ -303,8 +303,7 @@ void CIRGenFunction::emitStoreOfScalar(mlir::Value value, Address addr, // Update the alloca with more info on initialization. assert(addr.getPointer() && "expected pointer to exist"); - auto srcAlloca = - dyn_cast_or_null<cir::AllocaOp>(addr.getPointer().getDefiningOp()); + auto srcAlloca = addr.getDefiningOp<cir::AllocaOp>(); if (currVarDecl && srcAlloca) { const VarDecl *vd = currVarDecl; assert(vd && "VarDecl expected"); @@ -635,10 +634,8 @@ LValue CIRGenFunction::emitUnaryOpLValue(const UnaryOperator *e) { // Tag 'load' with deref attribute. // FIXME: This misses some derefence cases and has problematic interactions // with other operators. - if (auto loadOp = - dyn_cast<cir::LoadOp>(addr.getPointer().getDefiningOp())) { + if (auto loadOp = addr.getDefiningOp<cir::LoadOp>()) loadOp.setIsDerefAttr(mlir::UnitAttr::get(&getMLIRContext())); - } LValue lv = makeAddrLValue(addr, t, baseInfo); assert(!cir::MissingFeatures::addressSpace()); @@ -2006,9 +2003,9 @@ cir::AllocaOp CIRGenFunction::createTempAlloca(mlir::Type ty, const Twine &name, mlir::Value arraySize, bool insertIntoFnEntryBlock) { - return cast<cir::AllocaOp>(emitAlloca(name.str(), ty, loc, CharUnits(), - insertIntoFnEntryBlock, arraySize) - .getDefiningOp()); + return mlir::cast<cir::AllocaOp>(emitAlloca(name.str(), ty, loc, CharUnits(), + insertIntoFnEntryBlock, arraySize) + .getDefiningOp()); } /// This creates an alloca and inserts it into the provided insertion point @@ -2018,7 +2015,7 @@ cir::AllocaOp CIRGenFunction::createTempAlloca(mlir::Type ty, mlir::OpBuilder::InsertPoint ip, mlir::Value arraySize) { assert(ip.isSet() && "Insertion point is not set"); - return cast<cir::AllocaOp>( + return mlir::cast<cir::AllocaOp>( emitAlloca(name.str(), ty, loc, CharUnits(), ip, arraySize) .getDefiningOp()); } diff --git a/clang/lib/CIR/CodeGen/CIRGenFunction.cpp b/clang/lib/CIR/CodeGen/CIRGenFunction.cpp index 3ed1e30..f8e7347 100644 --- a/clang/lib/CIR/CodeGen/CIRGenFunction.cpp +++ b/clang/lib/CIR/CodeGen/CIRGenFunction.cpp @@ -219,7 +219,9 @@ void CIRGenFunction::declare(mlir::Value addrVal, const Decl *var, QualType ty, assert(isa<NamedDecl>(var) && "Needs a named decl"); assert(!cir::MissingFeatures::cgfSymbolTable()); - auto allocaOp = cast<cir::AllocaOp>(addrVal.getDefiningOp()); + auto allocaOp = addrVal.getDefiningOp<cir::AllocaOp>(); + assert(allocaOp && "expected cir::AllocaOp"); + if (isParam) allocaOp.setInitAttr(mlir::UnitAttr::get(&getMLIRContext())); if (ty->isReferenceType() || ty.isConstQualified()) diff --git a/clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp b/clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp index 8b01d41a..ecf31a7 100644 --- a/clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp +++ b/clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp @@ -501,11 +501,7 @@ void CIRRecordLowering::accumulateFields() { fieldEnd = recordDecl->field_end(); field != fieldEnd;) { if (field->isBitField()) { - RecordDecl::field_iterator start = field; - // Iterate to gather the list of bitfields. - for (++field; field != fieldEnd && field->isBitField(); ++field) - ; - field = accumulateBitFields(start, field); + field = accumulateBitFields(field, fieldEnd); assert((field == fieldEnd || !field->isBitField()) && "Failed to accumulate all the bitfields"); } else if (!field->isZeroSize(astContext)) { diff --git a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp index 263ff15..d3fcac1 100644 --- a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp +++ b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp @@ -606,7 +606,7 @@ static Value tryFoldCastChain(cir::CastOp op) { if (!isIntOrBoolCast(op)) break; head = op; - op = dyn_cast_or_null<cir::CastOp>(head.getSrc().getDefiningOp()); + op = head.getSrc().getDefiningOp<cir::CastOp>(); } if (head == tail) @@ -1802,7 +1802,7 @@ OpFoldResult cir::UnaryOp::fold(FoldAdaptor adaptor) { } if (isBoolNot(*this)) - if (auto previous = dyn_cast_or_null<UnaryOp>(getInput().getDefiningOp())) + if (auto previous = getInput().getDefiningOp<cir::UnaryOp>()) if (isBoolNot(previous)) return previous.getInput(); @@ -2184,8 +2184,7 @@ LogicalResult cir::ComplexRealOp::verify() { } OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) { - if (auto complexCreateOp = - dyn_cast_or_null<cir::ComplexCreateOp>(getOperand().getDefiningOp())) + if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>()) return complexCreateOp.getOperand(0); auto complex = @@ -2206,8 +2205,7 @@ LogicalResult cir::ComplexImagOp::verify() { } OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) { - if (auto complexCreateOp = - dyn_cast_or_null<cir::ComplexCreateOp>(getOperand().getDefiningOp())) + if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>()) return complexCreateOp.getOperand(1); auto complex = diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp index 895872b..dc6e1b7 100644 --- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp +++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp @@ -821,8 +821,7 @@ mlir::LogicalResult CIRToLLVMPtrStrideOpLowering::matchAndRewrite( // before it. To achieve that, look at unary minus, which already got // lowered to "sub 0, x". const auto sub = dyn_cast<mlir::LLVM::SubOp>(indexOp); - auto unary = dyn_cast_if_present<cir::UnaryOp>( - ptrStrideOp.getStride().getDefiningOp()); + auto unary = ptrStrideOp.getStride().getDefiningOp<cir::UnaryOp>(); bool rewriteSub = unary && unary.getKind() == cir::UnaryOpKind::Minus && sub; if (rewriteSub) @@ -2378,15 +2377,14 @@ mlir::LogicalResult CIRToLLVMVecSplatOpLowering::matchAndRewrite( mlir::Value poison = rewriter.create<mlir::LLVM::PoisonOp>(loc, llvmTy); mlir::Value elementValue = adaptor.getValue(); - if (mlir::isa<mlir::LLVM::PoisonOp>(elementValue.getDefiningOp())) { + if (elementValue.getDefiningOp<mlir::LLVM::PoisonOp>()) { // If the splat value is poison, then we can just use poison value // for the entire vector. rewriter.replaceOp(op, poison); return mlir::success(); } - if (auto constValue = - dyn_cast<mlir::LLVM::ConstantOp>(elementValue.getDefiningOp())) { + if (auto constValue = elementValue.getDefiningOp<mlir::LLVM::ConstantOp>()) { if (auto intAttr = dyn_cast<mlir::IntegerAttr>(constValue.getValue())) { mlir::DenseIntElementsAttr denseVec = mlir::DenseIntElementsAttr::get( mlir::cast<mlir::ShapedType>(llvmTy), intAttr.getValue()); diff --git a/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp b/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp index 7772a56..b51991bf 100644 --- a/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp +++ b/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp @@ -117,7 +117,7 @@ IntegerLiteralSeparatorFixer::process(const Environment &Env, } if (Style.isCpp()) { // Hex alpha digits a-f/A-F must be at the end of the string literal. - StringRef Suffixes = "_himnsuyd"; + static constexpr StringRef Suffixes("_himnsuyd"); if (const auto Pos = Text.find_first_of(IsBase16 ? Suffixes.drop_back() : Suffixes); Pos != StringRef::npos) { diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index d28d2fd..4801d27 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -1939,7 +1939,7 @@ private: Contexts.back().IsExpression = true; next(); if (CurrentToken) - CurrentToken->SpacesRequiredBefore = true; + CurrentToken->SpacesRequiredBefore = 1; parseLine(); break; default: @@ -2639,8 +2639,8 @@ private: if (PreviousNotConst->is(TT_TemplateCloser)) { return PreviousNotConst && PreviousNotConst->MatchingParen && PreviousNotConst->MatchingParen->Previous && - PreviousNotConst->MatchingParen->Previous->isNot(tok::period) && - PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template); + !PreviousNotConst->MatchingParen->Previous->isOneOf( + tok::period, tok::kw_template); } if ((PreviousNotConst->is(tok::r_paren) && @@ -3369,7 +3369,7 @@ private: Current->isOneOf(Keywords.kw_in, Keywords.kw_as)) { return prec::Relational; } - if (Current->is(TT_BinaryOperator) || Current->is(tok::comma)) + if (Current->isOneOf(TT_BinaryOperator, tok::comma)) return Current->getPrecedence(); if (Current->isOneOf(tok::period, tok::arrow) && Current->isNot(TT_TrailingReturnArrow)) { @@ -4314,8 +4314,8 @@ unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, if (Left.is(tok::coloncolon)) return Style.PenaltyBreakScopeResolution; - if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || - Right.is(tok::kw_operator)) { + if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName, + tok::kw_operator)) { if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt) return 3; if (Left.is(TT_StartOfName)) @@ -4757,7 +4757,7 @@ bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line, if (Previous) { if (Previous->endsSequence(tok::kw_operator)) return Style.PointerAlignment != FormatStyle::PAS_Left; - if (Previous->is(tok::kw_const) || Previous->is(tok::kw_volatile)) { + if (Previous->isOneOf(tok::kw_const, tok::kw_volatile)) { return (Style.PointerAlignment != FormatStyle::PAS_Left) || (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After) || @@ -4931,8 +4931,7 @@ bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line, } if (Left.is(TT_TemplateCloser) && Left.MatchingParen && Left.MatchingParen->Previous && - (Left.MatchingParen->Previous->is(tok::period) || - Left.MatchingParen->Previous->is(tok::coloncolon))) { + Left.MatchingParen->Previous->isOneOf(tok::period, tok::coloncolon)) { // Java call to generic function with explicit type: // A.<B<C<...>>>DoSomething(); // A::<B<C<...>>>DoSomething(); // With a Java 8 method reference. @@ -5207,8 +5206,7 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, // (e.g. as "const x of y" in a for loop), or after a destructuring // operation (const [x, y] of z, const {a, b} of c). (Left.is(Keywords.kw_of) && BeforeLeft && - (BeforeLeft->is(tok::identifier) || - BeforeLeft->isOneOf(tok::r_square, tok::r_brace)))) && + BeforeLeft->isOneOf(tok::identifier, tok::r_square, tok::r_brace))) && (!BeforeLeft || BeforeLeft->isNot(tok::period))) { return true; } @@ -5516,7 +5514,7 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, return false; } if (Style.isJava() && Right.is(tok::coloncolon) && - (Left.is(tok::identifier) || Left.is(tok::kw_this))) { + Left.isOneOf(tok::identifier, tok::kw_this)) { return false; } if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) { @@ -5587,8 +5585,8 @@ static bool IsFunctionArgument(const FormatToken &Tok) { } static bool -isItAnEmptyLambdaAllowed(const FormatToken &Tok, - FormatStyle::ShortLambdaStyle ShortLambdaOption) { +isEmptyLambdaAllowed(const FormatToken &Tok, + FormatStyle::ShortLambdaStyle ShortLambdaOption) { return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None; } @@ -5808,8 +5806,8 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, } if (Right.is(tok::comment)) { - return Left.isNot(BK_BracedInit) && Left.isNot(TT_CtorInitializerColon) && - (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline); + return !Left.isOneOf(BK_BracedInit, TT_CtorInitializerColon) && + Right.NewlinesBefore > 0 && Right.HasUnescapedNewline; } if (Left.isTrailingComment()) return true; @@ -5977,7 +5975,7 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, // Put multiple Java annotation on a new line. if ((Style.isJava() || Style.isJavaScript()) && Left.is(TT_LeadingJavaAnnotation) && - Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) && + !Right.isOneOf(TT_LeadingJavaAnnotation, tok::l_paren) && (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) { return true; } @@ -6043,7 +6041,7 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, ((LBrace->is(tok::l_brace) && (LBrace->is(TT_DictLiteral) || (LBrace->Next && LBrace->Next->is(tok::r_brace)))) || - LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) { + LBrace->isOneOf(TT_ArrayInitializerLSquare, tok::less))) { // If Left.ParameterCount is 0, then this submessage entry is not the // first in its parent submessage, and we want to break before this entry. // If Left.ParameterCount is greater than 0, then its parent submessage @@ -6257,9 +6255,9 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, } if (Left.is(tok::question) && Right.is(tok::colon)) return false; - if (Right.is(TT_ConditionalExpr) || Right.is(tok::question)) + if (Right.isOneOf(TT_ConditionalExpr, tok::question)) return Style.BreakBeforeTernaryOperators; - if (Left.is(TT_ConditionalExpr) || Left.is(tok::question)) + if (Left.isOneOf(TT_ConditionalExpr, tok::question)) return !Style.BreakBeforeTernaryOperators; if (Left.is(TT_InheritanceColon)) return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon; @@ -6302,7 +6300,7 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, // submessage: { ... } // submessage: < ... > // repeated: [ ... ] - if (((Right.is(tok::l_brace) || Right.is(tok::less)) && + if ((Right.isOneOf(tok::l_brace, tok::less) && Right.is(TT_DictLiteral)) || Right.is(TT_ArrayInitializerLSquare)) { return false; @@ -6352,10 +6350,8 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, Right.getPrecedence() != prec::Assignment)) { return true; } - if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) || - Left.is(tok::kw_operator)) { + if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator, tok::kw_operator)) return false; - } if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) && Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) { return false; @@ -6440,9 +6436,9 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine; if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) { if (isAllmanLambdaBrace(Left)) - return !isItAnEmptyLambdaAllowed(Left, ShortLambdaOption); + return !isEmptyLambdaAllowed(Left, ShortLambdaOption); if (isAllmanLambdaBrace(Right)) - return !isItAnEmptyLambdaAllowed(Right, ShortLambdaOption); + return !isEmptyLambdaAllowed(Right, ShortLambdaOption); } if (Right.is(tok::kw_noexcept) && Right.is(TT_TrailingAnnotation)) { diff --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp index 5711f45..a407825 100644 --- a/clang/lib/Frontend/ASTUnit.cpp +++ b/clang/lib/Frontend/ASTUnit.cpp @@ -831,11 +831,10 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( AST->CaptureDiagnostics = CaptureDiagnostics; AST->DiagOpts = DiagOpts; AST->Diagnostics = Diags; - AST->FileMgr = new FileManager(FileSystemOpts, VFS); + AST->FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOpts, VFS); AST->UserFilesAreVolatile = UserFilesAreVolatile; - AST->SourceMgr = new SourceManager(AST->getDiagnostics(), - AST->getFileManager(), - UserFilesAreVolatile); + AST->SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>( + AST->getDiagnostics(), AST->getFileManager(), UserFilesAreVolatile); AST->ModCache = createCrossProcessModuleCache(); AST->HSOpts = std::make_unique<HeaderSearchOptions>(HSOpts); AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.getFormats().front()); @@ -858,20 +857,20 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( Preprocessor &PP = *AST->PP; if (ToLoad >= LoadASTOnly) - AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(), - PP.getIdentifierTable(), PP.getSelectorTable(), - PP.getBuiltinInfo(), - AST->getTranslationUnitKind()); + AST->Ctx = llvm::makeIntrusiveRefCnt<ASTContext>( + *AST->LangOpts, AST->getSourceManager(), PP.getIdentifierTable(), + PP.getSelectorTable(), PP.getBuiltinInfo(), + AST->getTranslationUnitKind()); DisableValidationForModuleKind disableValid = DisableValidationForModuleKind::None; if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION")) disableValid = DisableValidationForModuleKind::All; - AST->Reader = new ASTReader(PP, *AST->ModCache, AST->Ctx.get(), - PCHContainerRdr, *AST->CodeGenOpts, {}, - /*isysroot=*/"", - /*DisableValidationKind=*/disableValid, - AllowASTWithCompilerErrors); + AST->Reader = llvm::makeIntrusiveRefCnt<ASTReader>( + PP, *AST->ModCache, AST->Ctx.get(), PCHContainerRdr, *AST->CodeGenOpts, + ArrayRef<std::shared_ptr<ModuleFileExtension>>(), + /*isysroot=*/"", + /*DisableValidationKind=*/disableValid, AllowASTWithCompilerErrors); unsigned Counter = 0; AST->Reader->setListener(std::make_unique<ASTInfoCollector>( @@ -1191,9 +1190,11 @@ bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, // changed above in AddImplicitPreamble. If VFS is nullptr, rely on // createFileManager to create one. if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS) - Clang->setFileManager(&*FileMgr); - else - FileMgr = Clang->createFileManager(std::move(VFS)); + Clang->setFileManager(FileMgr); + else { + Clang->createFileManager(std::move(VFS)); + FileMgr = Clang->getFileManagerPtr(); + } // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> @@ -1226,15 +1227,15 @@ bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, ResetForParse(); - SourceMgr = new SourceManager(getDiagnostics(), *FileMgr, - UserFilesAreVolatile); + SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>( + getDiagnostics(), *FileMgr, +UserFilesAreVolatile); if (!OverrideMainBuffer) { checkAndRemoveNonDriverDiags(StoredDiagnostics); TopLevelDeclsInPreamble.clear(); } // Create the source manager. - Clang->setSourceManager(&getSourceManager()); + Clang->setSourceManager(getSourceManagerPtr()); // If the main file has been overridden due to the use of a preamble, // make that override happen and introduce the preamble. @@ -1499,13 +1500,13 @@ void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) { TheSema = CI.takeSema(); Consumer = CI.takeASTConsumer(); if (CI.hasASTContext()) - Ctx = &CI.getASTContext(); + Ctx = CI.getASTContextPtr(); if (CI.hasPreprocessor()) PP = CI.getPreprocessorPtr(); CI.setSourceManager(nullptr); CI.setFileManager(nullptr); if (CI.hasTarget()) - Target = &CI.getTarget(); + Target = CI.getTargetPtr(); Reader = CI.getASTReader(); HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure(); if (Invocation != CI.getInvocationPtr()) { @@ -1555,10 +1556,11 @@ ASTUnit::create(std::shared_ptr<CompilerInvocation> CI, AST->Diagnostics = Diags; AST->FileSystemOpts = CI->getFileSystemOpts(); AST->Invocation = std::move(CI); - AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); + AST->FileMgr = + llvm::makeIntrusiveRefCnt<FileManager>(AST->FileSystemOpts, VFS); AST->UserFilesAreVolatile = UserFilesAreVolatile; - AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr, - UserFilesAreVolatile); + AST->SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>( + AST->getDiagnostics(), *AST->FileMgr, UserFilesAreVolatile); AST->ModCache = createCrossProcessModuleCache(); return AST; @@ -1646,10 +1648,10 @@ ASTUnit *ASTUnit::LoadFromCompilerInvocationAction( AST->Reader = nullptr; // Create a file manager object to provide access to and cache the filesystem. - Clang->setFileManager(&AST->getFileManager()); + Clang->setFileManager(AST->getFileManagerPtr()); // Create the source manager. - Clang->setSourceManager(&AST->getSourceManager()); + Clang->setSourceManager(AST->getSourceManagerPtr()); FrontendAction *Act = Action; @@ -1743,8 +1745,9 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation( std::shared_ptr<CompilerInvocation> CI, std::shared_ptr<PCHContainerOperations> PCHContainerOps, std::shared_ptr<DiagnosticOptions> DiagOpts, - IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr, - bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics, + IntrusiveRefCntPtr<DiagnosticsEngine> Diags, + IntrusiveRefCntPtr<FileManager> FileMgr, bool OnlyLocalDecls, + CaptureDiagsKind CaptureDiagnostics, unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind, bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) { @@ -1849,7 +1852,8 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromCommandLine( AST->FileSystemOpts = CI->getFileSystemOpts(); AST->CodeGenOpts = std::make_unique<CodeGenOptions>(CI->getCodeGenOpts()); VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS); - AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); + AST->FileMgr = + llvm::makeIntrusiveRefCnt<FileManager>(AST->FileSystemOpts, VFS); AST->StorePreamblesInMemory = StorePreamblesInMemory; AST->PreambleStoragePath = PreambleStoragePath; AST->ModCache = createCrossProcessModuleCache(); @@ -2210,7 +2214,8 @@ void ASTUnit::CodeComplete( CodeCompleteConsumer &Consumer, std::shared_ptr<PCHContainerOperations> PCHContainerOps, llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diag, LangOptions &LangOpts, - SourceManager &SourceMgr, FileManager &FileMgr, + llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr, + llvm::IntrusiveRefCntPtr<FileManager> FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers, std::unique_ptr<SyntaxOnlyAction> Act) { @@ -2265,7 +2270,7 @@ void ASTUnit::CodeComplete( Clang->getDiagnostics(), &StoredDiagnostics, nullptr); ProcessWarningOptions(*Diag, Inv.getDiagnosticOpts(), - FileMgr.getVirtualFileSystem()); + FileMgr->getVirtualFileSystem()); // Create the target instance. if (!Clang->createTarget()) { @@ -2282,8 +2287,8 @@ void ASTUnit::CodeComplete( "IR inputs not support here!"); // Use the source and file managers that we were given. - Clang->setFileManager(&FileMgr); - Clang->setSourceManager(&SourceMgr); + Clang->setFileManager(FileMgr); + Clang->setSourceManager(SourceMgr); // Remap files. PreprocessorOpts.clearRemappedFiles(); @@ -2301,7 +2306,7 @@ void ASTUnit::CodeComplete( auto getUniqueID = [&FileMgr](StringRef Filename) -> std::optional<llvm::sys::fs::UniqueID> { - if (auto Status = FileMgr.getVirtualFileSystem().status(Filename)) + if (auto Status = FileMgr->getVirtualFileSystem().status(Filename)) return Status->getUniqueID(); return std::nullopt; }; @@ -2322,7 +2327,7 @@ void ASTUnit::CodeComplete( std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; if (Preamble && Line > 1 && hasSameUniqueID(File, OriginalSourceFile)) { OverrideMainBuffer = getMainBufferWithPrecompiledPreamble( - PCHContainerOps, Inv, FileMgr.getVirtualFileSystemPtr(), false, + PCHContainerOps, Inv, FileMgr->getVirtualFileSystemPtr(), false, Line - 1); } @@ -2333,7 +2338,7 @@ void ASTUnit::CodeComplete( "No preamble was built, but OverrideMainBuffer is not null"); IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = - FileMgr.getVirtualFileSystemPtr(); + FileMgr->getVirtualFileSystemPtr(); Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS, OverrideMainBuffer.get()); // FIXME: there is no way to update VFS if it was changed by diff --git a/clang/lib/Frontend/ChainedIncludesSource.cpp b/clang/lib/Frontend/ChainedIncludesSource.cpp index 88b1076..013814a 100644 --- a/clang/lib/Frontend/ChainedIncludesSource.cpp +++ b/clang/lib/Frontend/ChainedIncludesSource.cpp @@ -53,17 +53,17 @@ private: }; } // end anonymous namespace -static ASTReader * +static llvm::IntrusiveRefCntPtr<ASTReader> createASTReader(CompilerInstance &CI, StringRef pchFile, SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> &MemBufs, SmallVectorImpl<std::string> &bufNames, ASTDeserializationListener *deserialListener = nullptr) { Preprocessor &PP = CI.getPreprocessor(); - std::unique_ptr<ASTReader> Reader; - Reader.reset(new ASTReader( + auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>( PP, CI.getModuleCache(), &CI.getASTContext(), CI.getPCHContainerReader(), - CI.getCodeGenOpts(), /*Extensions=*/{}, - /*isysroot=*/"", DisableValidationForModuleKind::PCH)); + CI.getCodeGenOpts(), + /*Extensions=*/ArrayRef<std::shared_ptr<ModuleFileExtension>>(), + /*isysroot=*/"", DisableValidationForModuleKind::PCH); for (unsigned ti = 0; ti < bufNames.size(); ++ti) { StringRef sr(bufNames[ti]); Reader->addInMemoryBuffer(sr, std::move(MemBufs[ti])); @@ -74,7 +74,7 @@ createASTReader(CompilerInstance &CI, StringRef pchFile, case ASTReader::Success: // Set the predefines buffer as suggested by the PCH reader. PP.setPredefines(Reader->getSuggestedPredefines()); - return Reader.release(); + return Reader; case ASTReader::Failure: case ASTReader::Missing: @@ -87,8 +87,9 @@ createASTReader(CompilerInstance &CI, StringRef pchFile, return nullptr; } -IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource( - CompilerInstance &CI, IntrusiveRefCntPtr<ExternalSemaSource> &Reader) { +IntrusiveRefCntPtr<ExternalSemaSource> +clang::createChainedIncludesSource(CompilerInstance &CI, + IntrusiveRefCntPtr<ASTReader> &OutReader) { std::vector<std::string> &includes = CI.getPreprocessorOpts().ChainedIncludes; assert(!includes.empty() && "No '-chain-include' in options!"); @@ -186,12 +187,12 @@ IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource( assert(!SerialBufs.empty()); std::string pchName = includes.back() + ".pch-final"; serialBufNames.push_back(pchName); - Reader = createASTReader(CI, pchName, SerialBufs, serialBufNames); - if (!Reader) + OutReader = createASTReader(CI, pchName, SerialBufs, serialBufNames); + if (!OutReader) return nullptr; auto ChainedSrc = llvm::makeIntrusiveRefCnt<ChainedIncludesSource>(std::move(CIs)); return llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>( - ChainedSrc.get(), Reader.get()); + std::move(ChainedSrc), OutReader); } diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp index ed6a651..d64290f 100644 --- a/clang/lib/Frontend/CompilerInstance.cpp +++ b/clang/lib/Frontend/CompilerInstance.cpp @@ -166,20 +166,23 @@ CompilerInstance::getVirtualFileSystemPtr() const { return getFileManager().getVirtualFileSystemPtr(); } -void CompilerInstance::setFileManager(FileManager *Value) { - FileMgr = Value; +void CompilerInstance::setFileManager( + llvm::IntrusiveRefCntPtr<FileManager> Value) { + FileMgr = std::move(Value); } -void CompilerInstance::setSourceManager(SourceManager *Value) { - SourceMgr = Value; +void CompilerInstance::setSourceManager( + llvm::IntrusiveRefCntPtr<SourceManager> Value) { + SourceMgr = std::move(Value); } void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) { PP = std::move(Value); } -void CompilerInstance::setASTContext(ASTContext *Value) { - Context = Value; +void CompilerInstance::setASTContext( + llvm::IntrusiveRefCntPtr<ASTContext> Value) { + Context = std::move(Value); if (Context && Consumer) getASTConsumer().Initialize(getASTContext()); @@ -387,14 +390,16 @@ FileManager *CompilerInstance::createFileManager( if (getFrontendOpts().ShowStats) VFS = llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS)); - FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS)); + FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(getFileSystemOpts(), + std::move(VFS)); return FileMgr.get(); } // Source Manager void CompilerInstance::createSourceManager(FileManager &FileMgr) { - SourceMgr = new SourceManager(getDiagnostics(), FileMgr); + SourceMgr = + llvm::makeIntrusiveRefCnt<SourceManager>(getDiagnostics(), FileMgr); } // Initialize the remapping of files to alternative contents, e.g., @@ -554,11 +559,11 @@ std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) { void CompilerInstance::createASTContext() { Preprocessor &PP = getPreprocessor(); - auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(), - PP.getIdentifierTable(), PP.getSelectorTable(), - PP.getBuiltinInfo(), PP.TUKind); + auto Context = llvm::makeIntrusiveRefCnt<ASTContext>( + getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(), + PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind); Context->InitBuiltinTypes(getTarget(), getAuxTarget()); - setASTContext(Context); + setASTContext(std::move(Context)); } // ExternalASTSource @@ -638,17 +643,17 @@ IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource( const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); - IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader( + auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>( PP, ModCache, &Context, PCHContainerRdr, CodeGenOpts, Extensions, Sysroot.empty() ? "" : Sysroot.data(), DisableValidation, AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false, HSOpts.ModulesValidateSystemHeaders, HSOpts.ModulesForceValidateUserHeaders, - HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex)); + HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex); // We need the external source to be set up before we read the AST, because // eagerly-deserialized declarations may use it. - Context.setExternalSource(Reader.get()); + Context.setExternalSource(Reader); Reader->setDeserializationListener( static_cast<ASTDeserializationListener *>(DeserializationListener), @@ -755,7 +760,7 @@ void CompilerInstance::createSema(TranslationUnitKind TUKind, // Attach the external sema source if there is any. if (ExternalSemaSrc) { - TheSema->addExternalSource(ExternalSemaSrc.get()); + TheSema->addExternalSource(ExternalSemaSrc); ExternalSemaSrc->InitializeSema(*TheSema); } @@ -1221,7 +1226,7 @@ std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl( if (ThreadSafeConfig) { Instance.createFileManager(ThreadSafeConfig->getVFS()); } else if (FrontendOpts.ModulesShareFileManager) { - Instance.setFileManager(&getFileManager()); + Instance.setFileManager(getFileManagerPtr()); } else { Instance.createFileManager(getVirtualFileSystemPtr()); } @@ -1750,17 +1755,18 @@ void CompilerInstance::createASTReader() { if (timerGroup) ReadTimer = std::make_unique<llvm::Timer>("reading_modules", "Reading modules", *timerGroup); - TheASTReader = new ASTReader( + TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>( getPreprocessor(), getModuleCache(), &getASTContext(), getPCHContainerReader(), getCodeGenOpts(), getFrontendOpts().ModuleFileExtensions, Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHOrModuleValidation, /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors, - /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders, - HSOpts.ModulesForceValidateUserHeaders, - HSOpts.ValidateASTInputFilesContent, - getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer)); + /*AllowConfigurationMismatch=*/false, + +HSOpts.ModulesValidateSystemHeaders, + +HSOpts.ModulesForceValidateUserHeaders, + +HSOpts.ValidateASTInputFilesContent, + +getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer)); if (hasASTConsumer()) { TheASTReader->setDeserializationListener( getASTConsumer().GetASTDeserializationListener()); diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp index 87cc2fc..2d69f8c 100644 --- a/clang/lib/Frontend/FrontendAction.cpp +++ b/clang/lib/Frontend/FrontendAction.cpp @@ -845,7 +845,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // Set the shared objects, these are reset when we finish processing the // file, otherwise the CompilerInstance will happily destroy them. - CI.setFileManager(&AST->getFileManager()); + CI.setFileManager(AST->getFileManagerPtr()); CI.createSourceManager(CI.getFileManager()); CI.getSourceManager().initializeForReplay(AST->getSourceManager()); @@ -912,13 +912,13 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // Set the shared objects, these are reset when we finish processing the // file, otherwise the CompilerInstance will happily destroy them. - CI.setFileManager(&AST->getFileManager()); - CI.setSourceManager(&AST->getSourceManager()); + CI.setFileManager(AST->getFileManagerPtr()); + CI.setSourceManager(AST->getSourceManagerPtr()); CI.setPreprocessor(AST->getPreprocessorPtr()); Preprocessor &PP = CI.getPreprocessor(); PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(), PP.getLangOpts()); - CI.setASTContext(&AST->getASTContext()); + CI.setASTContext(AST->getASTContextPtr()); setCurrentInput(Input, std::move(AST)); @@ -1172,11 +1172,12 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) { // Convert headers to PCH and chain them. - IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader; + IntrusiveRefCntPtr<ExternalSemaSource> source; + IntrusiveRefCntPtr<ASTReader> FinalReader; source = createChainedIncludesSource(CI, FinalReader); if (!source) return false; - CI.setASTReader(static_cast<ASTReader *>(FinalReader.get())); + CI.setASTReader(FinalReader); CI.getASTContext().setExternalSource(source); } else if (CI.getLangOpts().Modules || !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) { @@ -1252,23 +1253,21 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // provides the layouts from that file. if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() && CI.hasASTContext() && !CI.getASTContext().getExternalSource()) { - IntrusiveRefCntPtr<ExternalASTSource> - Override(new LayoutOverrideSource( - CI.getFrontendOpts().OverrideRecordLayoutsFile)); + auto Override = llvm::makeIntrusiveRefCnt<LayoutOverrideSource>( + CI.getFrontendOpts().OverrideRecordLayoutsFile); CI.getASTContext().setExternalSource(Override); } // Setup HLSL External Sema Source if (CI.getLangOpts().HLSL && CI.hasASTContext()) { - IntrusiveRefCntPtr<ExternalSemaSource> HLSLSema( - new HLSLExternalSemaSource()); - if (auto *SemaSource = dyn_cast_if_present<ExternalSemaSource>( - CI.getASTContext().getExternalSource())) { - IntrusiveRefCntPtr<ExternalSemaSource> MultiSema( - new MultiplexExternalSemaSource(SemaSource, HLSLSema.get())); - CI.getASTContext().setExternalSource(MultiSema); + auto HLSLSema = llvm::makeIntrusiveRefCnt<HLSLExternalSemaSource>(); + if (auto SemaSource = dyn_cast_if_present<ExternalSemaSource>( + CI.getASTContext().getExternalSourcePtr())) { + auto MultiSema = llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>( + std::move(SemaSource), std::move(HLSLSema)); + CI.getASTContext().setExternalSource(std::move(MultiSema)); } else - CI.getASTContext().setExternalSource(HLSLSema); + CI.getASTContext().setExternalSource(std::move(HLSLSema)); } FailureCleanup.release(); diff --git a/clang/lib/Frontend/PrecompiledPreamble.cpp b/clang/lib/Frontend/PrecompiledPreamble.cpp index 7fc1d87..03f70b7 100644 --- a/clang/lib/Frontend/PrecompiledPreamble.cpp +++ b/clang/lib/Frontend/PrecompiledPreamble.cpp @@ -483,11 +483,12 @@ llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build( VFS); // Create a file manager object to provide access to and cache the filesystem. - Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS)); + Clang->setFileManager( + llvm::makeIntrusiveRefCnt<FileManager>(Clang->getFileSystemOpts(), VFS)); // Create the source manager. - Clang->setSourceManager( - new SourceManager(*Diagnostics, Clang->getFileManager())); + Clang->setSourceManager(llvm::makeIntrusiveRefCnt<SourceManager>( + *Diagnostics, Clang->getFileManager())); auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>(); Clang->addDependencyCollector(PreambleDepCollector); diff --git a/clang/lib/Interpreter/CodeCompletion.cpp b/clang/lib/Interpreter/CodeCompletion.cpp index ecdf489..dc7030c 100644 --- a/clang/lib/Interpreter/CodeCompletion.cpp +++ b/clang/lib/Interpreter/CodeCompletion.cpp @@ -238,11 +238,9 @@ public: // compiler instance before the super `ExecuteAction` triggers parsing void IncrementalSyntaxOnlyAction::ExecuteAction() { CompilerInstance &CI = getCompilerInstance(); - ExternalSource *myExternalSource = - new ExternalSource(CI.getASTContext(), CI.getFileManager(), - ParentCI->getASTContext(), ParentCI->getFileManager()); - llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> astContextExternalSource( - myExternalSource); + auto astContextExternalSource = llvm::makeIntrusiveRefCnt<ExternalSource>( + CI.getASTContext(), CI.getFileManager(), ParentCI->getASTContext(), + ParentCI->getFileManager()); CI.getASTContext().setExternalSource(astContextExternalSource); CI.getASTContext().getTranslationUnitDecl()->setHasExternalVisibleStorage( true); @@ -381,8 +379,8 @@ void ReplCodeCompleter::codeComplete(CompilerInstance *InterpCI, AU->CodeComplete(CodeCompletionFileName, 1, Col, RemappedFiles, false, false, false, consumer, std::make_shared<clang::PCHContainerOperations>(), diag, - InterpCI->getLangOpts(), AU->getSourceManager(), - AU->getFileManager(), sd, tb, std::move(Act)); + InterpCI->getLangOpts(), AU->getSourceManagerPtr(), + AU->getFileManagerPtr(), sd, tb, std::move(Act)); } } // namespace clang diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp b/clang/lib/Sema/AnalysisBasedWarnings.cpp index 35ad0b5..fdb6302 100644 --- a/clang/lib/Sema/AnalysisBasedWarnings.cpp +++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp @@ -581,7 +581,7 @@ static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) { // mark them as live. for (const auto *B : *cfg) { if (!live[B->getBlockID()]) { - if (B->pred_begin() == B->pred_end()) { + if (B->preds().empty()) { const Stmt *Term = B->getTerminatorStmt(); if (isa_and_nonnull<CXXTryStmt>(Term)) // When not adding EH edges from calls, catch clauses diff --git a/clang/lib/Sema/MultiplexExternalSemaSource.cpp b/clang/lib/Sema/MultiplexExternalSemaSource.cpp index fbfb242..1f040c8 100644 --- a/clang/lib/Sema/MultiplexExternalSemaSource.cpp +++ b/clang/lib/Sema/MultiplexExternalSemaSource.cpp @@ -20,26 +20,19 @@ char MultiplexExternalSemaSource::ID; /// given element to it. /// MultiplexExternalSemaSource::MultiplexExternalSemaSource( - ExternalSemaSource *S1, ExternalSemaSource *S2) { - S1->Retain(); - S2->Retain(); - Sources.push_back(S1); - Sources.push_back(S2); -} - -// pin the vtable here. -MultiplexExternalSemaSource::~MultiplexExternalSemaSource() { - for (auto *S : Sources) - S->Release(); + llvm::IntrusiveRefCntPtr<ExternalSemaSource> S1, + llvm::IntrusiveRefCntPtr<ExternalSemaSource> S2) { + Sources.push_back(std::move(S1)); + Sources.push_back(std::move(S2)); } /// Appends new source to the source list. /// ///\param[in] source - An ExternalSemaSource. /// -void MultiplexExternalSemaSource::AddSource(ExternalSemaSource *Source) { - Source->Retain(); - Sources.push_back(Source); +void MultiplexExternalSemaSource::AddSource( + llvm::IntrusiveRefCntPtr<ExternalSemaSource> Source) { + Sources.push_back(std::move(Source)); } //===----------------------------------------------------------------------===// @@ -92,7 +85,7 @@ CXXBaseSpecifier *MultiplexExternalSemaSource::GetExternalCXXBaseSpecifiers( CXXCtorInitializer ** MultiplexExternalSemaSource::GetExternalCXXCtorInitializers(uint64_t Offset) { - for (auto *S : Sources) + for (auto &S : Sources) if (auto *R = S->GetExternalCXXCtorInitializers(Offset)) return R; return nullptr; @@ -371,6 +364,6 @@ bool MultiplexExternalSemaSource::MaybeDiagnoseMissingCompleteType( void MultiplexExternalSemaSource::AssignedLambdaNumbering( CXXRecordDecl *Lambda) { - for (auto *Source : Sources) + for (auto &Source : Sources) Source->AssignedLambdaNumbering(Lambda); } diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp index 43a7f9e..924becf 100644 --- a/clang/lib/Sema/Sema.cpp +++ b/clang/lib/Sema/Sema.cpp @@ -656,18 +656,19 @@ ASTMutationListener *Sema::getASTMutationListener() const { return getASTConsumer().GetASTMutationListener(); } -void Sema::addExternalSource(ExternalSemaSource *E) { +void Sema::addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E) { assert(E && "Cannot use with NULL ptr"); if (!ExternalSource) { - ExternalSource = E; + ExternalSource = std::move(E); return; } - if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource)) - Ex->AddSource(E); + if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource.get())) + Ex->AddSource(std::move(E)); else - ExternalSource = new MultiplexExternalSemaSource(ExternalSource.get(), E); + ExternalSource = llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>( + ExternalSource, std::move(E)); } void Sema::PrintStats() const { diff --git a/clang/lib/Sema/SemaAMDGPU.cpp b/clang/lib/Sema/SemaAMDGPU.cpp index 8580de2..a5fbd70 100644 --- a/clang/lib/Sema/SemaAMDGPU.cpp +++ b/clang/lib/Sema/SemaAMDGPU.cpp @@ -93,6 +93,12 @@ bool SemaAMDGPU::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, case AMDGPU::BI__builtin_amdgcn_cvt_scale_pk8_f32_fp8: case AMDGPU::BI__builtin_amdgcn_cvt_scale_pk8_f32_bf8: case AMDGPU::BI__builtin_amdgcn_cvt_scale_pk8_f32_fp4: + case AMDGPU::BI__builtin_amdgcn_cvt_scale_pk16_f16_fp6: + case AMDGPU::BI__builtin_amdgcn_cvt_scale_pk16_bf16_fp6: + case AMDGPU::BI__builtin_amdgcn_cvt_scale_pk16_f16_bf6: + case AMDGPU::BI__builtin_amdgcn_cvt_scale_pk16_bf16_bf6: + case AMDGPU::BI__builtin_amdgcn_cvt_scale_pk16_f32_fp6: + case AMDGPU::BI__builtin_amdgcn_cvt_scale_pk16_f32_bf6: return SemaRef.BuiltinConstantArgRange(TheCall, 2, 0, 7); } default: diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 20fdf2d..3eaf2eb 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -5255,8 +5255,8 @@ Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, if (getLangOpts().CPlusPlus && DS.getStorageClassSpec() != DeclSpec::SCS_typedef) if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) - if (Enum->enumerator_begin() == Enum->enumerator_end() && - !Enum->getIdentifier() && !Enum->isInvalidDecl()) + if (Enum->enumerators().empty() && !Enum->getIdentifier() && + !Enum->isInvalidDecl()) DeclaresAnything = false; if (!DS.isMissingDeclaratorOk()) { @@ -14724,7 +14724,6 @@ void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { type->isIntegralOrEnumerationType()) { // In C++98, in-class initialization for a static data member must // be an integer constant expression. - // SourceLocation Loc; if (!Init->isIntegerConstantExpr(Context)) { Diag(Init->getExprLoc(), diag::ext_in_class_initializer_non_constant) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 45c7178..e4c2543 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -6523,8 +6523,7 @@ ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier // language modes. if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn); - ULE && ULE->hasExplicitTemplateArgs() && - ULE->decls_begin() == ULE->decls_end()) { + ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) { DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id) << ULE->getName(); } diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp index 1c6f292..7b9c638 100644 --- a/clang/lib/Sema/SemaInit.cpp +++ b/clang/lib/Sema/SemaInit.cpp @@ -4836,7 +4836,7 @@ static void TryReferenceListInitialization(Sema &S, } // Update the initializer if we've resolved an overloaded function. - if (Sequence.step_begin() != Sequence.step_end()) + if (!Sequence.steps().empty()) Sequence.RewrapReferenceInitList(cv1T1, InitList); } // Perform address space compatibility check. diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp index 8bde18f..dc73ded 100644 --- a/clang/lib/Sema/SemaLookup.cpp +++ b/clang/lib/Sema/SemaLookup.cpp @@ -3130,7 +3130,7 @@ addAssociatedClassesAndNamespaces(AssociatedLookup &Result, CollectEnclosingNamespace(Result.Namespaces, BaseCtx); // Make sure we visit the bases of this base class. - if (BaseDecl->bases_begin() != BaseDecl->bases_end()) + if (!BaseDecl->bases().empty()) Bases.push_back(BaseDecl); } } diff --git a/clang/lib/Sema/SemaTemplateVariadic.cpp b/clang/lib/Sema/SemaTemplateVariadic.cpp index 572dbf2..b0a673d 100644 --- a/clang/lib/Sema/SemaTemplateVariadic.cpp +++ b/clang/lib/Sema/SemaTemplateVariadic.cpp @@ -1387,7 +1387,8 @@ static void CheckFoldOperand(Sema &S, Expr *E) { S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand) << E->getSourceRange() << FixItHint::CreateInsertion(E->getBeginLoc(), "(") - << FixItHint::CreateInsertion(E->getEndLoc(), ")"); + << FixItHint::CreateInsertion(S.getLocForEndOfToken(E->getEndLoc()), + ")"); } } diff --git a/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp b/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp index 5d392af..7bc34f6 100644 --- a/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp +++ b/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp @@ -43,8 +43,8 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) { if (Bodies.count(D->getName()) != 0) return; - SourceManager &SM = CI.getSourceManager(); - FileID mainFileID = SM.getMainFileID(); + llvm::IntrusiveRefCntPtr<SourceManager> SM = CI.getSourceManagerPtr(); + FileID mainFileID = SM->getMainFileID(); llvm::StringRef modelPath = CI.getAnalyzerOpts().ModelPath; @@ -80,14 +80,14 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) { new ForwardingDiagnosticConsumer(CI.getDiagnosticClient()), /*ShouldOwnClient=*/true); - Instance.getDiagnostics().setSourceManager(&SM); + Instance.getDiagnostics().setSourceManager(SM.get()); // The instance wants to take ownership, however DisableFree frontend option // is set to true to avoid double free issues - Instance.setFileManager(&CI.getFileManager()); - Instance.setSourceManager(&SM); + Instance.setFileManager(CI.getFileManagerPtr()); + Instance.setSourceManager(SM); Instance.setPreprocessor(CI.getPreprocessorPtr()); - Instance.setASTContext(&CI.getASTContext()); + Instance.setASTContext(CI.getASTContextPtr()); Instance.getPreprocessor().InitializeForModelFile(); @@ -108,5 +108,5 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) { // the main file id is changed to the model file during parsing and it needs // to be reset to the former main file id after parsing of the model file // is done. - SM.setMainFileID(mainFileID); + SM->setMainFileID(mainFileID); } diff --git a/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp b/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp index 2b5a293..e11319e 100644 --- a/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp +++ b/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp @@ -74,13 +74,24 @@ void skipComments(Lexer &Lex, Token &Tok) { return; } -// Returns the offset after header guard directives and any comments -// before/after header guards (e.g. #ifndef/#define pair, #pragma once). If no -// header guard is present in the code, this will return the offset after -// skipping all comments from the start of the code. -unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName, - StringRef Code, - const IncludeStyle &Style) { +bool checkAndConsumeModuleDecl(const SourceManager &SM, Lexer &Lex, + Token &Tok) { + bool Matched = Tok.is(tok::raw_identifier) && + Tok.getRawIdentifier() == "module" && + !Lex.LexFromRawLexer(Tok) && Tok.is(tok::semi) && + !Lex.LexFromRawLexer(Tok); + return Matched; +} + +// Determines the minimum offset into the file where we want to insert header +// includes. This will be put (when available): +// - after `#pragma once` +// - after header guards (`#ifdef` and `#define`) +// - after opening global module (`module;`) +// - after any comments at the start of the file or immediately following one of +// the above constructs +unsigned getMinHeaderInsertionOffset(StringRef FileName, StringRef Code, + const IncludeStyle &Style) { // \p Consume returns location after header guard or 0 if no header guard is // found. auto ConsumeHeaderGuardAndComment = @@ -95,7 +106,17 @@ unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName, return std::max(InitialOffset, Consume(SM, Lex, Tok)); }); }; - return std::max( + + auto ModuleDecl = ConsumeHeaderGuardAndComment( + [](const SourceManager &SM, Lexer &Lex, Token Tok) -> unsigned { + if (checkAndConsumeModuleDecl(SM, Lex, Tok)) { + skipComments(Lex, Tok); + return SM.getFileOffset(Tok.getLocation()); + } + return 0; + }); + + auto HeaderAndPPOffset = std::max( // #ifndef/#define ConsumeHeaderGuardAndComment( [](const SourceManager &SM, Lexer &Lex, Token Tok) -> unsigned { @@ -115,6 +136,7 @@ unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName, return SM.getFileOffset(Tok.getLocation()); return 0; })); + return std::max(HeaderAndPPOffset, ModuleDecl); } // Check if a sequence of tokens is like @@ -280,8 +302,7 @@ const llvm::Regex HeaderIncludes::IncludeRegex(IncludeRegexPattern); HeaderIncludes::HeaderIncludes(StringRef FileName, StringRef Code, const IncludeStyle &Style) : FileName(FileName), Code(Code), FirstIncludeOffset(-1), - MinInsertOffset( - getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style)), + MinInsertOffset(getMinHeaderInsertionOffset(FileName, Code, Style)), MaxInsertOffset(MinInsertOffset + getMaxHeaderInsertionOffset( FileName, Code.drop_front(MinInsertOffset), Style)), diff --git a/clang/lib/Tooling/Tooling.cpp b/clang/lib/Tooling/Tooling.cpp index ecafe26..45dfdf4 100644 --- a/clang/lib/Tooling/Tooling.cpp +++ b/clang/lib/Tooling/Tooling.cpp @@ -212,8 +212,8 @@ bool runToolOnCodeWithArgs( SmallString<16> FileNameStorage; StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage); - llvm::IntrusiveRefCntPtr<FileManager> Files( - new FileManager(FileSystemOptions(), VFS)); + llvm::IntrusiveRefCntPtr<FileManager> Files = + llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(), VFS); ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster(); ToolInvocation Invocation( getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef), @@ -479,7 +479,8 @@ ClangTool::ClangTool(const CompilationDatabase &Compilations, InMemoryFileSystem( llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>()), Files(Files ? Files - : new FileManager(FileSystemOptions(), OverlayFileSystem)) { + : llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(), + OverlayFileSystem)) { OverlayFileSystem->pushOverlay(InMemoryFileSystem); appendArgumentsAdjuster(getClangStripOutputAdjuster()); appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster()); @@ -701,8 +702,9 @@ std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs( auto InMemoryFileSystem = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>(); OverlayFileSystem->pushOverlay(InMemoryFileSystem); - llvm::IntrusiveRefCntPtr<FileManager> Files( - new FileManager(FileSystemOptions(), OverlayFileSystem)); + llvm::IntrusiveRefCntPtr<FileManager> Files = + llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(), + OverlayFileSystem); ToolInvocation Invocation( getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileName), FileName), |