r333324 - Fix typo + reflow comment; NFC
Author: gbiv Date: Fri May 25 16:40:59 2018 New Revision: 24 URL: http://llvm.org/viewvc/llvm-project?rev=24&view=rev Log: Fix typo + reflow comment; NFC Reflow brings said comment below 80 cols Modified: cfe/trunk/include/clang/AST/ASTContext.h Modified: cfe/trunk/include/clang/AST/ASTContext.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=24&r1=23&r2=24&view=diff == --- cfe/trunk/include/clang/AST/ASTContext.h (original) +++ cfe/trunk/include/clang/AST/ASTContext.h Fri May 25 16:40:59 2018 @@ -1123,7 +1123,7 @@ public: /// Return the uniqued reference to the type for an Objective-C /// gc-qualified type. /// - /// The retulting type has a union of the qualifiers from T and the gc + /// The resulting type has a union of the qualifiers from T and the gc /// attribute. QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const; @@ -1250,9 +1250,9 @@ public: /// Returns true iff we need copy/dispose helpers for the given type. bool BlockRequiresCopying(QualType Ty, const VarDecl *D); - /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set - /// to false in this case. If HasByrefExtendedLayout returns true, byref variable - /// has extended lifetime. + /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout + /// is set to false in this case. If HasByrefExtendedLayout returns true, + /// byref variable has extended lifetime. bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r333333 - Test commit; please ignore.
Author: gbiv Date: Fri May 25 19:29:14 2018 New Revision: 33 URL: http://llvm.org/viewvc/llvm-project?rev=33&view=rev Log: Test commit; please ignore. Modified: cfe/trunk/lib/Sema/SemaAttr.cpp Modified: cfe/trunk/lib/Sema/SemaAttr.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaAttr.cpp?rev=33&r1=32&r2=33&view=diff == --- cfe/trunk/lib/Sema/SemaAttr.cpp (original) +++ cfe/trunk/lib/Sema/SemaAttr.cpp Fri May 25 19:29:14 2018 @@ -330,7 +330,7 @@ void Sema::PragmaStack::Act(S Stack.erase(std::prev(I.base()), Stack.end()); } } else if (!Stack.empty()) { - // We don't have a label, just pop the last entry. + // We do not have a label, just pop the last entry. CurrentValue = Stack.back().Value; CurrentPragmaLocation = Stack.back().PragmaLocation; Stack.pop_back(); ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r333333 - Test commit; please ignore.
Thanks. :) On Fri, May 25, 2018, 7:56 PM Richard Smith wrote: > Congratulations? > > On Fri, 25 May 2018, 19:33 George Burgess IV via cfe-commits, < > cfe-commits@lists.llvm.org> wrote: > >> Author: gbiv >> Date: Fri May 25 19:29:14 2018 >> New Revision: 33 >> >> URL: http://llvm.org/viewvc/llvm-project?rev=33&view=rev >> Log: >> Test commit; please ignore. >> >> Modified: >> cfe/trunk/lib/Sema/SemaAttr.cpp >> >> Modified: cfe/trunk/lib/Sema/SemaAttr.cpp >> URL: >> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaAttr.cpp?rev=33&r1=32&r2=33&view=diff >> >> == >> --- cfe/trunk/lib/Sema/SemaAttr.cpp (original) >> +++ cfe/trunk/lib/Sema/SemaAttr.cpp Fri May 25 19:29:14 2018 >> @@ -330,7 +330,7 @@ void Sema::PragmaStack::Act(S >> Stack.erase(std::prev(I.base()), Stack.end()); >>} >> } else if (!Stack.empty()) { >> - // We don't have a label, just pop the last entry. >> + // We do not have a label, just pop the last entry. >>CurrentValue = Stack.back().Value; >>CurrentPragmaLocation = Stack.back().PragmaLocation; >>Stack.pop_back(); >> >> >> ___ >> cfe-commits mailing list >> cfe-commits@lists.llvm.org >> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits >> > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r315951 - Make __builtin_types_compatible_p more like GCC's
Author: gbiv Date: Mon Oct 16 15:58:37 2017 New Revision: 315951 URL: http://llvm.org/viewvc/llvm-project?rev=315951&view=rev Log: Make __builtin_types_compatible_p more like GCC's GCC ignore qualifiers on array types. Since we seem to have this function primarily for GCC compatibility, we should try to match that behavior. This also adds a few more test-cases __builtin_types_compatible_p, which were inspired by GCC's documentation on the builtin. Modified: cfe/trunk/lib/Sema/SemaExprCXX.cpp cfe/trunk/test/Parser/builtin_types_compatible.c Modified: cfe/trunk/lib/Sema/SemaExprCXX.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprCXX.cpp?rev=315951&r1=315950&r2=315951&view=diff == --- cfe/trunk/lib/Sema/SemaExprCXX.cpp (original) +++ cfe/trunk/lib/Sema/SemaExprCXX.cpp Mon Oct 16 15:58:37 2017 @@ -4824,9 +4824,13 @@ static bool EvaluateBinaryTypeTrait(Sema } case BTT_IsSame: return Self.Context.hasSameType(LhsT, RhsT); - case BTT_TypeCompatible: -return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(), - RhsT.getUnqualifiedType()); + case BTT_TypeCompatible: { +// GCC ignores cv-qualifiers on arrays for this builtin. +Qualifiers LhsQuals, RhsQuals; +QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); +QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); +return Self.Context.typesAreCompatible(Lhs, Rhs); + } case BTT_IsConvertible: case BTT_IsConvertibleTo: { // C++0x [meta.rel]p4: Modified: cfe/trunk/test/Parser/builtin_types_compatible.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/builtin_types_compatible.c?rev=315951&r1=315950&r2=315951&view=diff == --- cfe/trunk/test/Parser/builtin_types_compatible.c (original) +++ cfe/trunk/test/Parser/builtin_types_compatible.c Mon Oct 16 15:58:37 2017 @@ -41,3 +41,20 @@ static void test() } +enum E1 { E1Foo }; +enum E2 { E2Foo }; + +static void testGccCompatibility() { + _Static_assert(__builtin_types_compatible_p(const volatile int, int), ""); + _Static_assert(__builtin_types_compatible_p(int[5], int[]), ""); + _Static_assert(!__builtin_types_compatible_p(int[5], int[4]), ""); + _Static_assert(!__builtin_types_compatible_p(int *, int **), ""); + _Static_assert(!__builtin_types_compatible_p(const int *, int *), ""); + _Static_assert(!__builtin_types_compatible_p(enum E1, enum E2), ""); + + // GCC's __builtin_types_compatible_p ignores qualifiers on arrays. + _Static_assert(__builtin_types_compatible_p(const int[4], int[4]), ""); + _Static_assert(__builtin_types_compatible_p(int[4], const int[4]), ""); + _Static_assert(__builtin_types_compatible_p(const int[5][4], int[][4]), ""); + _Static_assert(!__builtin_types_compatible_p(const int(*)[], int(*)[]), ""); +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r315951 - Make __builtin_types_compatible_p more like GCC's
Yuck, sorry for the typos in the commit message. It should read: GCC ignores qualifiers on array types. Since we seem to have this function primarily for GCC compatibility, we should try to match that behavior. This also adds a few more test-cases for __builtin_types_compatible_p, which were inspired by GCC's documentation on the builtin. On Mon, Oct 16, 2017 at 3:58 PM, George Burgess IV via cfe-commits wrote: > Author: gbiv > Date: Mon Oct 16 15:58:37 2017 > New Revision: 315951 > > URL: http://llvm.org/viewvc/llvm-project?rev=315951&view=rev > Log: > Make __builtin_types_compatible_p more like GCC's > > GCC ignore qualifiers on array types. Since we seem to have this > function primarily for GCC compatibility, we should try to match that > behavior. > > This also adds a few more test-cases __builtin_types_compatible_p, > which were inspired by GCC's documentation on the builtin. > > Modified: > cfe/trunk/lib/Sema/SemaExprCXX.cpp > cfe/trunk/test/Parser/builtin_types_compatible.c > > Modified: cfe/trunk/lib/Sema/SemaExprCXX.cpp > URL: > http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprCXX.cpp?rev=315951&r1=315950&r2=315951&view=diff > == > --- cfe/trunk/lib/Sema/SemaExprCXX.cpp (original) > +++ cfe/trunk/lib/Sema/SemaExprCXX.cpp Mon Oct 16 15:58:37 2017 > @@ -4824,9 +4824,13 @@ static bool EvaluateBinaryTypeTrait(Sema >} >case BTT_IsSame: > return Self.Context.hasSameType(LhsT, RhsT); > - case BTT_TypeCompatible: > -return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(), > - RhsT.getUnqualifiedType()); > + case BTT_TypeCompatible: { > +// GCC ignores cv-qualifiers on arrays for this builtin. > +Qualifiers LhsQuals, RhsQuals; > +QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, > LhsQuals); > +QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, > RhsQuals); > +return Self.Context.typesAreCompatible(Lhs, Rhs); > + } >case BTT_IsConvertible: >case BTT_IsConvertibleTo: { > // C++0x [meta.rel]p4: > > Modified: cfe/trunk/test/Parser/builtin_types_compatible.c > URL: > http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/builtin_types_compatible.c?rev=315951&r1=315950&r2=315951&view=diff > == > --- cfe/trunk/test/Parser/builtin_types_compatible.c (original) > +++ cfe/trunk/test/Parser/builtin_types_compatible.c Mon Oct 16 15:58:37 2017 > @@ -41,3 +41,20 @@ static void test() > > } > > +enum E1 { E1Foo }; > +enum E2 { E2Foo }; > + > +static void testGccCompatibility() { > + _Static_assert(__builtin_types_compatible_p(const volatile int, int), ""); > + _Static_assert(__builtin_types_compatible_p(int[5], int[]), ""); > + _Static_assert(!__builtin_types_compatible_p(int[5], int[4]), ""); > + _Static_assert(!__builtin_types_compatible_p(int *, int **), ""); > + _Static_assert(!__builtin_types_compatible_p(const int *, int *), ""); > + _Static_assert(!__builtin_types_compatible_p(enum E1, enum E2), ""); > + > + // GCC's __builtin_types_compatible_p ignores qualifiers on arrays. > + _Static_assert(__builtin_types_compatible_p(const int[4], int[4]), ""); > + _Static_assert(__builtin_types_compatible_p(int[4], const int[4]), ""); > + _Static_assert(__builtin_types_compatible_p(const int[5][4], int[][4]), > ""); > + _Static_assert(!__builtin_types_compatible_p(const int(*)[], int(*)[]), > ""); > +} > > > ___ > cfe-commits mailing list > cfe-commits@lists.llvm.org > http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r337796 - Fix unused variable warnings; NFC
Author: gbiv Date: Mon Jul 23 19:10:53 2018 New Revision: 337796 URL: http://llvm.org/viewvc/llvm-project?rev=337796&view=rev Log: Fix unused variable warnings; NFC Looks like MTE was previously used for its SourceLoc, but we're now using a seperate SourceLocation here. Modified: cfe/trunk/lib/Sema/SemaInit.cpp Modified: cfe/trunk/lib/Sema/SemaInit.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=337796&r1=337795&r2=337796&view=diff == --- cfe/trunk/lib/Sema/SemaInit.cpp (original) +++ cfe/trunk/lib/Sema/SemaInit.cpp Mon Jul 23 19:10:53 2018 @@ -6774,7 +6774,7 @@ void Sema::checkInitializerLifetime(cons } case LK_MemInitializer: { - if (auto *MTE = dyn_cast(L)) { + if (isa(L)) { // Under C++ DR1696, if a mem-initializer (or a default member // initializer used by the absence of one) would lifetime-extend a // temporary, the program is ill-formed. @@ -6833,7 +6833,7 @@ void Sema::checkInitializerLifetime(cons } case LK_New: - if (auto *MTE = dyn_cast(L)) { + if (isa(L)) { Diag(DiagLoc, RK == RK_ReferenceBinding ? diag::warn_new_dangling_reference : diag::warn_new_dangling_initializer_list) ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r338962 - Use Optional instead of unique_ptr; NFC
Author: gbiv Date: Sat Aug 4 18:37:07 2018 New Revision: 338962 URL: http://llvm.org/viewvc/llvm-project?rev=338962&view=rev Log: Use Optional instead of unique_ptr; NFC Looks like the only reason we use a unique_ptr here is so that we can conditionally construct a LogicalErrorHandler. It's a small type, and Optional can do the same thing with 100% fewer heap allocations. Modified: cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp Modified: cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp?rev=338962&r1=338961&r2=338962&view=diff == --- cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp (original) +++ cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp Sat Aug 4 18:37:07 2018 @@ -2068,11 +2068,11 @@ AnalysisBasedWarnings::IssueWarnings(sem } // Install the logical handler for -Wtautological-overlap-compare - std::unique_ptr LEH; + llvm::Optional LEH; if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison, D->getLocStart())) { -LEH.reset(new LogicalErrorHandler(S)); -AC.getCFGBuildOptions().Observer = LEH.get(); +LEH.emplace(S); +AC.getCFGBuildOptions().Observer = &*LEH; } // Emit delayed diagnostics. ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r303962 - [docs] Point coroutine link to an actual document
Author: gbiv Date: Thu May 25 21:56:51 2017 New Revision: 303962 URL: http://llvm.org/viewvc/llvm-project?rev=303962&view=rev Log: [docs] Point coroutine link to an actual document Unsure if there's a better document, but what we had before led to a 404. :) Modified: cfe/trunk/www/cxx_status.html Modified: cfe/trunk/www/cxx_status.html URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/www/cxx_status.html?rev=303962&r1=303961&r2=303962&view=diff == --- cfe/trunk/www/cxx_status.html (original) +++ cfe/trunk/www/cxx_status.html Thu May 25 21:56:51 2017 @@ -831,7 +831,7 @@ and library features that are not part o [DRAFT TS] Coroutines - http://wg21.link/p0057r7";>P0057R7 + http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0057r7.pdf";>P0057R7 WIP ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r304996 - [Sema] Remove unused field from OverloadCandidate.
Author: gbiv Date: Thu Jun 8 13:19:25 2017 New Revision: 304996 URL: http://llvm.org/viewvc/llvm-project?rev=304996&view=rev Log: [Sema] Remove unused field from OverloadCandidate. The only use in-tree I can find for BuiltinTypes.ResultTy is a single store to it. We otherwise just recompute what it should be later on (and sometimes do things like argument conversions in the process of recomputing it). Since it's impossible to test if the value stored there is sane, and we don't use it anyway, we should probably just drop the field. I'll do a follow-up patch to rename BuiltinTypes.ParamTypes -> BuiltinParamTypes in a bit. Wanted to keep this patch relatively minimal. Thanks to Petr Kudryavtsev for bringing this up! Modified: cfe/trunk/include/clang/Sema/Overload.h cfe/trunk/include/clang/Sema/Sema.h cfe/trunk/lib/Sema/SemaOverload.cpp Modified: cfe/trunk/include/clang/Sema/Overload.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Overload.h?rev=304996&r1=304995&r2=304996&view=diff == --- cfe/trunk/include/clang/Sema/Overload.h (original) +++ cfe/trunk/include/clang/Sema/Overload.h Thu Jun 8 13:19:25 2017 @@ -633,10 +633,9 @@ namespace clang { /// Might be a UsingShadowDecl or a FunctionTemplateDecl. DeclAccessPair FoundDecl; -// BuiltinTypes - Provides the return and parameter types of a -// built-in overload candidate. Only valid when Function is NULL. +/// BuiltinTypes - Provides the parameter types of a built-in overload +/// candidate. Only valid when Function is NULL. struct { - QualType ResultTy; QualType ParamTypes[3]; } BuiltinTypes; Modified: cfe/trunk/include/clang/Sema/Sema.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=304996&r1=304995&r2=304996&view=diff == --- cfe/trunk/include/clang/Sema/Sema.h (original) +++ cfe/trunk/include/clang/Sema/Sema.h Thu Jun 8 13:19:25 2017 @@ -2727,8 +2727,7 @@ public: SourceLocation OpLoc, ArrayRef Args, OverloadCandidateSet& CandidateSet, SourceRange OpRange = SourceRange()); - void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, - ArrayRef Args, + void AddBuiltinCandidate(QualType *ParamTys, ArrayRef Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); Modified: cfe/trunk/lib/Sema/SemaOverload.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=304996&r1=304995&r2=304996&view=diff == --- cfe/trunk/lib/Sema/SemaOverload.cpp (original) +++ cfe/trunk/lib/Sema/SemaOverload.cpp Thu Jun 8 13:19:25 2017 @@ -7136,8 +7136,7 @@ void Sema::AddMemberOperatorCandidates(O /// operator. NumContextualBoolArguments is the number of arguments /// (at the beginning of the argument list) that will be contextually /// converted to bool. -void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, - ArrayRef Args, +void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator, unsigned NumContextualBoolArguments) { @@ -7151,7 +7150,6 @@ void Sema::AddBuiltinCandidate(QualType Candidate.Function = nullptr; Candidate.IsSurrogate = false; Candidate.IgnoreObjectArgument = false; - Candidate.BuiltinTypes.ResultTy = ResultTy; for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; @@ -7492,7 +7490,7 @@ static void AddBuiltinAssignmentOperator // T& operator=(T&, T) ParamTypes[0] = S.Context.getLValueReferenceType(T); ParamTypes[1] = T; - S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, + S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, /*IsAssignmentOperator=*/true); if (!S.Context.getCanonicalType(T).isVolatileQualified()) { @@ -7500,7 +7498,7 @@ static void AddBuiltinAssignmentOperator ParamTypes[0] = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); ParamTypes[1] = T; -S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, +S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, /*IsAssignmentOperator=*/true); } } @@ -7620,64 +7618,6 @@ class BuiltinOperatorOverloadBuilder { return S.Context.*ArithmeticTypes[index]; } - /// \brief Gets the canonical type
r305013 - [Sema] Refactor OverloadCandidate::BuiltinTypes. NFC.
Author: gbiv Date: Thu Jun 8 15:55:21 2017 New Revision: 305013 URL: http://llvm.org/viewvc/llvm-project?rev=305013&view=rev Log: [Sema] Refactor OverloadCandidate::BuiltinTypes. NFC. As promised in r304996. Modified: cfe/trunk/include/clang/Sema/Overload.h cfe/trunk/lib/Sema/SemaExprCXX.cpp cfe/trunk/lib/Sema/SemaOverload.cpp Modified: cfe/trunk/include/clang/Sema/Overload.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Overload.h?rev=305013&r1=305012&r2=305013&view=diff == --- cfe/trunk/include/clang/Sema/Overload.h (original) +++ cfe/trunk/include/clang/Sema/Overload.h Thu Jun 8 15:55:21 2017 @@ -633,11 +633,9 @@ namespace clang { /// Might be a UsingShadowDecl or a FunctionTemplateDecl. DeclAccessPair FoundDecl; -/// BuiltinTypes - Provides the parameter types of a built-in overload +/// BuiltinParamTypes - Provides the parameter types of a built-in overload /// candidate. Only valid when Function is NULL. -struct { - QualType ParamTypes[3]; -} BuiltinTypes; +QualType BuiltinParamTypes[3]; /// Surrogate - The conversion function for which this candidate /// is a surrogate, but only if IsSurrogate is true. Modified: cfe/trunk/lib/Sema/SemaExprCXX.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprCXX.cpp?rev=305013&r1=305012&r2=305013&view=diff == --- cfe/trunk/lib/Sema/SemaExprCXX.cpp (original) +++ cfe/trunk/lib/Sema/SemaExprCXX.cpp Thu Jun 8 15:55:21 2017 @@ -5281,16 +5281,16 @@ static bool FindConditionalOverload(Sema switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { case OR_Success: { // We found a match. Perform the conversions on the arguments and move on. - ExprResult LHSRes = -Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0], - Best->Conversions[0], Sema::AA_Converting); + ExprResult LHSRes = Self.PerformImplicitConversion( + LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], + Sema::AA_Converting); if (LHSRes.isInvalid()) break; LHS = LHSRes; - ExprResult RHSRes = -Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1], - Best->Conversions[1], Sema::AA_Converting); + ExprResult RHSRes = Self.PerformImplicitConversion( + RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], + Sema::AA_Converting); if (RHSRes.isInvalid()) break; RHS = RHSRes; Modified: cfe/trunk/lib/Sema/SemaOverload.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=305013&r1=305012&r2=305013&view=diff == --- cfe/trunk/lib/Sema/SemaOverload.cpp (original) +++ cfe/trunk/lib/Sema/SemaOverload.cpp Thu Jun 8 15:55:21 2017 @@ -7150,8 +7150,7 @@ void Sema::AddBuiltinCandidate(QualType Candidate.Function = nullptr; Candidate.IsSurrogate = false; Candidate.IgnoreObjectArgument = false; - for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) -Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; + std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); // Determine the implicit conversion sequences for each of the // arguments. @@ -10143,13 +10142,13 @@ static void NoteBuiltinOperatorCandidate std::string TypeStr("operator"); TypeStr += Opc; TypeStr += "("; - TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); + TypeStr += Cand->BuiltinParamTypes[0].getAsString(); if (Cand->Conversions.size() == 1) { TypeStr += ")"; S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; } else { TypeStr += ", "; -TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); +TypeStr += Cand->BuiltinParamTypes[1].getAsString(); TypeStr += ")"; S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; } @@ -10386,7 +10385,7 @@ static void CompleteNonViableCandidate(S } else { // Builtin operator. assert(ConvCount <= 3); -ParamTypes = Cand->BuiltinTypes.ParamTypes; +ParamTypes = Cand->BuiltinParamTypes; } // Fill in the rest of the conversions. @@ -11992,9 +11991,8 @@ Sema::CreateOverloadedUnaryOp(SourceLoca // We matched a built-in operator. Convert the arguments, then // break out so that we will build the appropriate built-in // operator node. - ExprResult InputRes = -PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], - Best->Conversions[0], AA_Passing); + ExprResult InputRes = PerformImplicitConversion( + Input, Best->Built
r305207 - [Sema] Use the right FoldingSet.
Author: gbiv Date: Mon Jun 12 12:44:30 2017 New Revision: 305207 URL: http://llvm.org/viewvc/llvm-project?rev=305207&view=rev Log: [Sema] Use the right FoldingSet. We were doing FindNodeOrInsertPos on SubstTemplateTypeParmPackTypes, so we should presumably be inserting into SubstTemplateTypeParmPackTypes. Looks like the FoldingSet API can be tweaked a bit so that we can catch things like this at compile-time. I'll look into that shortly. I'm unsure of how to test this; suggestions welcome. Thanks to Vladimir Voskresensky for bringing this up! Modified: cfe/trunk/lib/AST/ASTContext.cpp Modified: cfe/trunk/lib/AST/ASTContext.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTContext.cpp?rev=305207&r1=305206&r2=305207&view=diff == --- cfe/trunk/lib/AST/ASTContext.cpp (original) +++ cfe/trunk/lib/AST/ASTContext.cpp Mon Jun 12 12:44:30 2017 @@ -3565,7 +3565,7 @@ QualType ASTContext::getSubstTemplateTyp = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, ArgPack); Types.push_back(SubstParm); - SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); + SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); return QualType(SubstParm, 0); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305947 - [test] Make absolute line numbers relative; NFC
Author: gbiv Date: Wed Jun 21 14:59:05 2017 New Revision: 305947 URL: http://llvm.org/viewvc/llvm-project?rev=305947&view=rev Log: [test] Make absolute line numbers relative; NFC Done to remove noise from https://reviews.llvm.org/D32332 (and to make this test more resilient to changes in general). Modified: cfe/trunk/test/Sema/overloadable.c Modified: cfe/trunk/test/Sema/overloadable.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/overloadable.c?rev=305947&r1=305946&r2=305947&view=diff == --- cfe/trunk/test/Sema/overloadable.c (original) +++ cfe/trunk/test/Sema/overloadable.c Wed Jun 21 14:59:05 2017 @@ -106,8 +106,8 @@ void fn_type_conversions() { void foo(char *c) __attribute__((overloadable)); void (*ptr1)(void *) = &foo; void (*ptr2)(char *) = &foo; - void (*ambiguous)(int *) = &foo; // expected-error{{initializing 'void (*)(int *)' with an expression of incompatible type ''}} expected-note@105{{candidate function}} expected-note@106{{candidate function}} - void *vp_ambiguous = &foo; // expected-error{{initializing 'void *' with an expression of incompatible type ''}} expected-note@105{{candidate function}} expected-note@106{{candidate function}} + void (*ambiguous)(int *) = &foo; // expected-error{{initializing 'void (*)(int *)' with an expression of incompatible type ''}} expected-note@-4{{candidate function}} expected-note@-3{{candidate function}} + void *vp_ambiguous = &foo; // expected-error{{initializing 'void *' with an expression of incompatible type ''}} expected-note@-5{{candidate function}} expected-note@-4{{candidate function}} void (*specific1)(int *) = (void (*)(void *))&foo; // expected-warning{{incompatible function pointer types initializing 'void (*)(int *)' with an expression of type 'void (*)(void *)'}} void *specific2 = (void (*)(void *))&foo; @@ -117,8 +117,8 @@ void fn_type_conversions() { void disabled(char *c) __attribute__((overloadable, enable_if(1, "The function name lies."))); // To be clear, these should all point to the last overload of 'disabled' void (*dptr1)(char *c) = &disabled; - void (*dptr2)(void *c) = &disabled; // expected-warning{{incompatible pointer types initializing 'void (*)(void *)' with an expression of type ''}} expected-note@115{{candidate function made ineligible by enable_if}} expected-note@116{{candidate function made ineligible by enable_if}} expected-note@117{{candidate function has type mismatch at 1st parameter (expected 'void *' but has 'char *')}} - void (*dptr3)(int *c) = &disabled; // expected-warning{{incompatible pointer types initializing 'void (*)(int *)' with an expression of type ''}} expected-note@115{{candidate function made ineligible by enable_if}} expected-note@116{{candidate function made ineligible by enable_if}} expected-note@117{{candidate function has type mismatch at 1st parameter (expected 'int *' but has 'char *')}} + void (*dptr2)(void *c) = &disabled; // expected-warning{{incompatible pointer types initializing 'void (*)(void *)' with an expression of type ''}} expected-note@-5{{candidate function made ineligible by enable_if}} expected-note@-4{{candidate function made ineligible by enable_if}} expected-note@-3{{candidate function has type mismatch at 1st parameter (expected 'void *' but has 'char *')}} + void (*dptr3)(int *c) = &disabled; // expected-warning{{incompatible pointer types initializing 'void (*)(int *)' with an expression of type ''}} expected-note@-6{{candidate function made ineligible by enable_if}} expected-note@-5{{candidate function made ineligible by enable_if}} expected-note@-4{{candidate function has type mismatch at 1st parameter (expected 'int *' but has 'char *')}} void *specific_disabled = &disabled; } @@ -131,14 +131,14 @@ void incompatible_pointer_type_conversio void foo(char *c) __attribute__((overloadable)); void foo(short *c) __attribute__((overloadable)); foo(charbuf); - foo(ucharbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@131{{candidate function}} expected-note@132{{candidate function}} - foo(intbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@131{{candidate function}} expected-note@132{{candidate function}} + foo(ucharbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@-3{{candidate function}} expected-note@-2{{candidate function}} + foo(intbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@-4{{candidate function}} expected-note@-3{{candidate function}} void bar(unsigned char *c) __attribute__((overloadable)); void bar(signed char *c) __attribute__((overloadable)); - bar(charbuf); // expected-error{{call to 'bar' is ambiguous}} expected-note@137{{candidate function}} expected-note@138{{candidate function}} + bar(charbuf); // expected-error{{call to 'bar' is ambiguous}} expected-note@-2{{candidate function}} expected-not
r326416 - Remove redundant casts. NFC
Author: gbiv Date: Wed Feb 28 21:43:23 2018 New Revision: 326416 URL: http://llvm.org/viewvc/llvm-project?rev=326416&view=rev Log: Remove redundant casts. NFC So I wrote a clang-tidy check to lint out redundant `isa`, `cast`, and `dyn_cast`s for fun. This is a portion of what it found for clang; I plan to do similar cleanups in LLVM and other subprojects when I find time. Because of the volume of changes, I explicitly avoided making any change that wasn't highly local and obviously correct to me (e.g. we still have a number of foo(cast(baz)) that I didn't touch, since overloading is a thing and the cast did actually change the type -- just up the class hierarchy). I also tried to leave the types we were cast<>ing to somewhere nearby, in cases where it wasn't locally obvious what we were dealing with before. Modified: cfe/trunk/include/clang/AST/DeclCXX.h cfe/trunk/include/clang/AST/Expr.h cfe/trunk/include/clang/AST/ExprObjC.h cfe/trunk/lib/AST/ASTContext.cpp cfe/trunk/lib/AST/CXXInheritance.cpp cfe/trunk/lib/AST/Decl.cpp cfe/trunk/lib/AST/DeclCXX.cpp cfe/trunk/lib/AST/DeclPrinter.cpp cfe/trunk/lib/AST/Expr.cpp cfe/trunk/lib/AST/ExprConstant.cpp cfe/trunk/lib/AST/ItaniumMangle.cpp cfe/trunk/lib/AST/MicrosoftCXXABI.cpp cfe/trunk/lib/AST/MicrosoftMangle.cpp cfe/trunk/lib/AST/RecordLayoutBuilder.cpp cfe/trunk/lib/AST/TemplateBase.cpp cfe/trunk/lib/AST/Type.cpp cfe/trunk/lib/CodeGen/CGCoroutine.cpp cfe/trunk/lib/CodeGen/CGDebugInfo.cpp cfe/trunk/lib/CodeGen/CGObjCGNU.cpp cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp cfe/trunk/lib/CodeGen/CGRecordLayoutBuilder.cpp cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp cfe/trunk/lib/CodeGen/CodeGenFunction.cpp cfe/trunk/lib/CodeGen/CodeGenModule.cpp cfe/trunk/lib/CodeGen/CodeGenTypes.cpp cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp cfe/trunk/lib/Frontend/ASTUnit.cpp cfe/trunk/lib/Frontend/Rewrite/RewriteModernObjC.cpp cfe/trunk/lib/Frontend/Rewrite/RewriteObjC.cpp cfe/trunk/lib/Sema/SemaChecking.cpp cfe/trunk/lib/Sema/SemaCodeComplete.cpp cfe/trunk/lib/Sema/SemaDecl.cpp cfe/trunk/lib/Sema/SemaDeclAttr.cpp cfe/trunk/lib/Sema/SemaDeclCXX.cpp cfe/trunk/lib/Sema/SemaDeclObjC.cpp cfe/trunk/lib/Sema/SemaExceptionSpec.cpp cfe/trunk/lib/Sema/SemaExprCXX.cpp cfe/trunk/lib/Sema/SemaObjCProperty.cpp cfe/trunk/lib/Sema/SemaOpenMP.cpp cfe/trunk/lib/Sema/SemaTemplate.cpp cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp cfe/trunk/lib/Sema/SemaType.cpp cfe/trunk/lib/Serialization/ASTReaderDecl.cpp cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp cfe/trunk/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp cfe/trunk/lib/StaticAnalyzer/Core/MemRegion.cpp cfe/trunk/lib/StaticAnalyzer/Core/ProgramState.cpp cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp Modified: cfe/trunk/include/clang/AST/DeclCXX.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclCXX.h?rev=326416&r1=326415&r2=326416&view=diff == --- cfe/trunk/include/clang/AST/DeclCXX.h (original) +++ cfe/trunk/include/clang/AST/DeclCXX.h Wed Feb 28 21:43:23 2018 @@ -2062,8 +2062,7 @@ public: bool isVolatile() const { return getType()->castAs()->isVolatile(); } bool isVirtual() const { -CXXMethodDecl *CD = - cast(const_cast(this)->getCanonicalDecl()); +CXXMethodDecl *CD = const_cast(this)->getCanonicalDecl(); // Member function is virtual if it is marked explicitly so, or if it is // declared in __interface -- then it is automatically pure virtual. Modified: cfe/trunk/include/clang/AST/Expr.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Expr.h?rev=326416&r1=326415&r2=326416&view=diff == --- cfe/trunk/include/clang/AST/Expr.h (original) +++ cfe/trunk/include/clang/AST/Expr.h Wed Feb 28 21:43:23 2018 @@ -2169,19 +2169,19 @@ public: void setRHS(Expr *E) { SubExprs[RHS] = E; } Expr *getBase() { -return cast(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); +return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS(); } const Expr *getBase() const { -return cast(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); +return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS(); } Expr *getIdx() { -return cast(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); +return getRHS()->getType()->isIntegerType() ? getRHS() : getLHS(); } const Expr *getIdx() const { -return cast(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); +return getRHS()->getType()->isIntegerT
r326607 - Range-ify a for loop. NFC
Author: gbiv Date: Fri Mar 2 12:10:38 2018 New Revision: 326607 URL: http://llvm.org/viewvc/llvm-project?rev=326607&view=rev Log: Range-ify a for loop. NFC Modified: cfe/trunk/lib/CodeGen/CGBlocks.cpp Modified: cfe/trunk/lib/CodeGen/CGBlocks.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBlocks.cpp?rev=326607&r1=326606&r2=326607&view=diff == --- cfe/trunk/lib/CodeGen/CGBlocks.cpp (original) +++ cfe/trunk/lib/CodeGen/CGBlocks.cpp Fri Mar 2 12:10:38 2018 @@ -713,11 +713,8 @@ static void enterBlockScope(CodeGenFunct /// kind of cleanup object is a BlockDecl*. void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) { assert(E->getNumObjects() != 0); - ArrayRef cleanups = E->getObjects(); - for (ArrayRef::iterator - i = cleanups.begin(), e = cleanups.end(); i != e; ++i) { -enterBlockScope(*this, *i); - } + for (const ExprWithCleanups::CleanupObject &C : E->getObjects()) +enterBlockScope(*this, C); } /// Find the layout for the given block in a linked list and remove it. ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r326766 - [ExprConstant] Look through ExprWithCleanups for `allocsize`
Author: gbiv Date: Mon Mar 5 23:42:36 2018 New Revision: 326766 URL: http://llvm.org/viewvc/llvm-project?rev=326766&view=rev Log: [ExprConstant] Look through ExprWithCleanups for `allocsize` Modified: cfe/trunk/lib/AST/ExprConstant.cpp cfe/trunk/test/CodeGenCXX/alloc-size.cpp Modified: cfe/trunk/lib/AST/ExprConstant.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=326766&r1=326765&r2=326766&view=diff == --- cfe/trunk/lib/AST/ExprConstant.cpp (original) +++ cfe/trunk/lib/AST/ExprConstant.cpp Mon Mar 5 23:42:36 2018 @@ -133,7 +133,11 @@ namespace { E = E->IgnoreParens(); // If we're doing a variable assignment from e.g. malloc(N), there will -// probably be a cast of some kind. Ignore it. +// probably be a cast of some kind. In exotic cases, we might also see a +// top-level ExprWithCleanups. Ignore them either way. +if (const auto *EC = dyn_cast(E)) + E = EC->getSubExpr()->IgnoreParens(); + if (const auto *Cast = dyn_cast(E)) E = Cast->getSubExpr()->IgnoreParens(); Modified: cfe/trunk/test/CodeGenCXX/alloc-size.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/alloc-size.cpp?rev=326766&r1=326765&r2=326766&view=diff == --- cfe/trunk/test/CodeGenCXX/alloc-size.cpp (original) +++ cfe/trunk/test/CodeGenCXX/alloc-size.cpp Mon Mar 5 23:42:36 2018 @@ -88,3 +88,15 @@ int callMemberCalloc() { // CHECK: ret i32 32 return __builtin_object_size(C().my_calloc(16, 2), 0); } + +struct D { + ~D(); + void *my_malloc(int N) __attribute__((alloc_size(2))); +}; + +// CHECK-LABEL: define i32 @_Z20callExprWithCleanupsv +int callExprWithCleanups() { + int *const p = (int *)D().my_malloc(3); + // CHECK: ret i32 3 + return __builtin_object_size(p, 0); +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r326767 - Fix an unused variable warning; NFC
Author: gbiv Date: Mon Mar 5 23:45:11 2018 New Revision: 326767 URL: http://llvm.org/viewvc/llvm-project?rev=326767&view=rev Log: Fix an unused variable warning; NFC Modified: cfe/trunk/lib/Analysis/CFG.cpp Modified: cfe/trunk/lib/Analysis/CFG.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/CFG.cpp?rev=326767&r1=326766&r2=326767&view=diff == --- cfe/trunk/lib/Analysis/CFG.cpp (original) +++ cfe/trunk/lib/Analysis/CFG.cpp Mon Mar 5 23:45:11 2018 @@ -1165,6 +1165,7 @@ void CFGBuilder::consumeConstructionCont const ConstructionContextLayer *Layer, CXXConstructExpr *CE) { if (const ConstructionContextLayer *PreviouslyStoredLayer = ConstructionContextMap.lookup(CE)) { +(void)PreviouslyStoredLayer; // We might have visited this child when we were finding construction // contexts within its parents. assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) && ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r326844 - [CodeGen] Don't emit lifetime.end without lifetime.start
Author: gbiv Date: Tue Mar 6 15:07:00 2018 New Revision: 326844 URL: http://llvm.org/viewvc/llvm-project?rev=326844&view=rev Log: [CodeGen] Don't emit lifetime.end without lifetime.start EmitLifetimeStart returns a non-null `size` pointer if it actually emits a lifetime.start. Later in this function, we use `tempSize`'s nullness to determine whether or not we should emit a lifetime.end. Modified: cfe/trunk/lib/CodeGen/CGCall.cpp cfe/trunk/test/CodeGen/64bit-swiftcall.c Modified: cfe/trunk/lib/CodeGen/CGCall.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=326844&r1=326843&r2=326844&view=diff == --- cfe/trunk/lib/CodeGen/CGCall.cpp (original) +++ cfe/trunk/lib/CodeGen/CGCall.cpp Tue Mar 6 15:07:00 2018 @@ -4010,13 +4010,11 @@ RValue CodeGenFunction::EmitCall(const C auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType); auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType); -tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize); - // Materialize to a temporary. addr = CreateTempAlloca(RV.getScalarVal()->getType(), CharUnits::fromQuantity(std::max(layout->getAlignment(), scalarAlign))); -EmitLifetimeStart(scalarSize, addr.getPointer()); +tempSize = EmitLifetimeStart(scalarSize, addr.getPointer()); Builder.CreateStore(RV.getScalarVal(), addr); } Modified: cfe/trunk/test/CodeGen/64bit-swiftcall.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/64bit-swiftcall.c?rev=326844&r1=326843&r2=326844&view=diff == --- cfe/trunk/test/CodeGen/64bit-swiftcall.c (original) +++ cfe/trunk/test/CodeGen/64bit-swiftcall.c Tue Mar 6 15:07:00 2018 @@ -1032,3 +1032,12 @@ typedef union { TEST(union_hom_fp_partial2) // X86-64-LABEL: take_union_hom_fp_partial2(i64, float) // ARM64-LABEL: take_union_hom_fp_partial2(i64, float) + +// At one point, we emitted lifetime.ends without a matching lifetime.begin for +// CoerceAndExpanded args. Since we're not performing optimizations, neither +// intrinsic should be emitted. +// CHECK-LABEL: define void @no_lifetime_markers +void no_lifetime_markers() { + // CHECK-NOT: call void @llvm.lifetime. + take_int5(return_int5()); +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r326845 - Fix a typo from r326844; NFC
Author: gbiv Date: Tue Mar 6 15:09:01 2018 New Revision: 326845 URL: http://llvm.org/viewvc/llvm-project?rev=326845&view=rev Log: Fix a typo from r326844; NFC Modified: cfe/trunk/test/CodeGen/64bit-swiftcall.c Modified: cfe/trunk/test/CodeGen/64bit-swiftcall.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/64bit-swiftcall.c?rev=326845&r1=326844&r2=326845&view=diff == --- cfe/trunk/test/CodeGen/64bit-swiftcall.c (original) +++ cfe/trunk/test/CodeGen/64bit-swiftcall.c Tue Mar 6 15:09:01 2018 @@ -1033,7 +1033,7 @@ TEST(union_hom_fp_partial2) // X86-64-LABEL: take_union_hom_fp_partial2(i64, float) // ARM64-LABEL: take_union_hom_fp_partial2(i64, float) -// At one point, we emitted lifetime.ends without a matching lifetime.begin for +// At one point, we emitted lifetime.ends without a matching lifetime.start for // CoerceAndExpanded args. Since we're not performing optimizations, neither // intrinsic should be emitted. // CHECK-LABEL: define void @no_lifetime_markers ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r326872 - Reland r326766 (with a slightly modified test)
Author: gbiv Date: Tue Mar 6 20:52:34 2018 New Revision: 326872 URL: http://llvm.org/viewvc/llvm-project?rev=326872&view=rev Log: Reland r326766 (with a slightly modified test) The original revert was done in r326869, since reverting r326602 broke the test added by this. The new test should be less dependent on r326602. Modified: cfe/trunk/lib/AST/ExprConstant.cpp cfe/trunk/test/CodeGenCXX/alloc-size.cpp Modified: cfe/trunk/lib/AST/ExprConstant.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=326872&r1=326871&r2=326872&view=diff == --- cfe/trunk/lib/AST/ExprConstant.cpp (original) +++ cfe/trunk/lib/AST/ExprConstant.cpp Tue Mar 6 20:52:34 2018 @@ -133,7 +133,11 @@ namespace { E = E->IgnoreParens(); // If we're doing a variable assignment from e.g. malloc(N), there will -// probably be a cast of some kind. Ignore it. +// probably be a cast of some kind. In exotic cases, we might also see a +// top-level ExprWithCleanups. Ignore them either way. +if (const auto *EC = dyn_cast(E)) + E = EC->getSubExpr()->IgnoreParens(); + if (const auto *Cast = dyn_cast(E)) E = Cast->getSubExpr()->IgnoreParens(); Modified: cfe/trunk/test/CodeGenCXX/alloc-size.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/alloc-size.cpp?rev=326872&r1=326871&r2=326872&view=diff == --- cfe/trunk/test/CodeGenCXX/alloc-size.cpp (original) +++ cfe/trunk/test/CodeGenCXX/alloc-size.cpp Tue Mar 6 20:52:34 2018 @@ -70,3 +70,19 @@ int testIt() { __builtin_object_size(dependent_calloc2(), 0); } } // namespace templated_alloc_size + +// Be sure that an ExprWithCleanups doesn't deter us. +namespace alloc_size_with_cleanups { +struct Foo { + ~Foo(); +}; + +void *my_malloc(const Foo &, int N) __attribute__((alloc_size(2))); + +// CHECK-LABEL: define i32 lalala +int testIt() { + int *const p = (int *)my_malloc(Foo{}, 3); + // CHECK: ret i32 3 + return __builtin_object_size(p, 0); +} +} // namespace alloc_size_with_cleanups ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r326766 - [ExprConstant] Look through ExprWithCleanups for `allocsize`
Relanded in r326872. Thanks! On Tue, Mar 6, 2018 at 7:03 PM, Nico Weber wrote: > Apologies, I had to revert the change that touched alloc-size.cpp before > this change in r326862. After that revert, your new test here failed, and > since I didn't understand how to make it passed, I reverted your change > in 326869 too. It should hopefully be easy for you to reland it. > > On Tue, Mar 6, 2018 at 2:42 AM, George Burgess IV via cfe-commits < > cfe-commits@lists.llvm.org> wrote: > >> Author: gbiv >> Date: Mon Mar 5 23:42:36 2018 >> New Revision: 326766 >> >> URL: http://llvm.org/viewvc/llvm-project?rev=326766&view=rev >> Log: >> [ExprConstant] Look through ExprWithCleanups for `allocsize` >> >> Modified: >> cfe/trunk/lib/AST/ExprConstant.cpp >> cfe/trunk/test/CodeGenCXX/alloc-size.cpp >> >> Modified: cfe/trunk/lib/AST/ExprConstant.cpp >> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprCo >> nstant.cpp?rev=326766&r1=326765&r2=326766&view=diff >> >> == >> --- cfe/trunk/lib/AST/ExprConstant.cpp (original) >> +++ cfe/trunk/lib/AST/ExprConstant.cpp Mon Mar 5 23:42:36 2018 >> @@ -133,7 +133,11 @@ namespace { >> >> E = E->IgnoreParens(); >> // If we're doing a variable assignment from e.g. malloc(N), there >> will >> -// probably be a cast of some kind. Ignore it. >> +// probably be a cast of some kind. In exotic cases, we might also >> see a >> +// top-level ExprWithCleanups. Ignore them either way. >> +if (const auto *EC = dyn_cast(E)) >> + E = EC->getSubExpr()->IgnoreParens(); >> + >> if (const auto *Cast = dyn_cast(E)) >>E = Cast->getSubExpr()->IgnoreParens(); >> >> >> Modified: cfe/trunk/test/CodeGenCXX/alloc-size.cpp >> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCX >> X/alloc-size.cpp?rev=326766&r1=326765&r2=326766&view=diff >> >> == >> --- cfe/trunk/test/CodeGenCXX/alloc-size.cpp (original) >> +++ cfe/trunk/test/CodeGenCXX/alloc-size.cpp Mon Mar 5 23:42:36 2018 >> @@ -88,3 +88,15 @@ int callMemberCalloc() { >>// CHECK: ret i32 32 >>return __builtin_object_size(C().my_calloc(16, 2), 0); >> } >> + >> +struct D { >> + ~D(); >> + void *my_malloc(int N) __attribute__((alloc_size(2))); >> +}; >> + >> +// CHECK-LABEL: define i32 @_Z20callExprWithCleanupsv >> +int callExprWithCleanups() { >> + int *const p = (int *)D().my_malloc(3); >> + // CHECK: ret i32 3 >> + return __builtin_object_size(p, 0); >> +} >> >> >> ___ >> cfe-commits mailing list >> cfe-commits@lists.llvm.org >> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits >> > > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r326873 - Remove a placeholder
Author: gbiv Date: Tue Mar 6 21:02:27 2018 New Revision: 326873 URL: http://llvm.org/viewvc/llvm-project?rev=326873&view=rev Log: Remove a placeholder ...Running tests in the wrong directory will often make them seem to pass. Oops. :) Modified: cfe/trunk/test/CodeGenCXX/alloc-size.cpp Modified: cfe/trunk/test/CodeGenCXX/alloc-size.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/alloc-size.cpp?rev=326873&r1=326872&r2=326873&view=diff == --- cfe/trunk/test/CodeGenCXX/alloc-size.cpp (original) +++ cfe/trunk/test/CodeGenCXX/alloc-size.cpp Tue Mar 6 21:02:27 2018 @@ -79,7 +79,7 @@ struct Foo { void *my_malloc(const Foo &, int N) __attribute__((alloc_size(2))); -// CHECK-LABEL: define i32 lalala +// CHECK-LABEL: define i32 @_ZN24alloc_size_with_cleanups6testItEv int testIt() { int *const p = (int *)my_malloc(Foo{}, 3); // CHECK: ret i32 3 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r326968 - Fix a doc typo; NFC
Author: gbiv Date: Wed Mar 7 16:22:04 2018 New Revision: 326968 URL: http://llvm.org/viewvc/llvm-project?rev=326968&view=rev Log: Fix a doc typo; NFC Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=326968&r1=326967&r2=326968&view=diff == --- cfe/trunk/lib/CodeGen/CGExpr.cpp (original) +++ cfe/trunk/lib/CodeGen/CGExpr.cpp Wed Mar 7 16:22:04 2018 @@ -187,7 +187,7 @@ RValue CodeGenFunction::EmitAnyExpr(cons llvm_unreachable("bad evaluation kind"); } -/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will +/// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will /// always be accessible even if no aggregate location is provided. RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) { AggValueSlot AggSlot = AggValueSlot::ignored(); ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r326980 - Fix an unused variable warning; NFC
Author: gbiv Date: Wed Mar 7 18:15:12 2018 New Revision: 326980 URL: http://llvm.org/viewvc/llvm-project?rev=326980&view=rev Log: Fix an unused variable warning; NFC Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=326980&r1=326979&r2=326980&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Wed Mar 7 18:15:12 2018 @@ -2466,7 +2466,7 @@ void ExprEngine::VisitCommonDeclRefExpr( ProgramPoint::PostLValueKind); return; } - if (const auto* BD = dyn_cast(D)) { + if (isa(D)) { // FIXME: proper support for bound declarations. // For now, let's just prevent crashing. return; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r326988 - [CodeGen] Emit lifetime.ends in both EH and non-EH blocks
Author: gbiv Date: Wed Mar 7 21:32:30 2018 New Revision: 326988 URL: http://llvm.org/viewvc/llvm-project?rev=326988&view=rev Log: [CodeGen] Emit lifetime.ends in both EH and non-EH blocks Before this, we'd only emit lifetime.ends for these temps in non-exceptional paths. This potentially made our stack larger than it needed to be for any code that follows an EH cleanup. e.g. in ``` struct Foo { char cs[32]; }; void escape(void *); struct Bar { ~Bar() { char cs[64]; escape(cs); } }; Foo getFoo(); void baz() { Bar b; getFoo(); } ``` baz() would require 96 bytes of stack, since the temporary from getFoo() only had a lifetime.end on the non-exceptional path. This also makes us keep hold of the Value* returned by EmitLifetimeStart, so we don't have to remake it later. Added: cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp Modified: cfe/trunk/lib/CodeGen/CGCall.cpp Modified: cfe/trunk/lib/CodeGen/CGCall.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=326988&r1=326987&r2=326988&view=diff == --- cfe/trunk/lib/CodeGen/CGCall.cpp (original) +++ cfe/trunk/lib/CodeGen/CGCall.cpp Wed Mar 7 21:32:30 2018 @@ -3790,7 +3790,7 @@ RValue CodeGenFunction::EmitCall(const C // If the call returns a temporary with struct return, create a temporary // alloca to hold the result, unless one is given to us. Address SRetPtr = Address::invalid(); - size_t UnusedReturnSize = 0; + llvm::Value *UnusedReturnSizePtr = nullptr; if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) { if (!ReturnValue.isNull()) { SRetPtr = ReturnValue.getValue(); @@ -3799,8 +3799,7 @@ RValue CodeGenFunction::EmitCall(const C if (HaveInsertPoint() && ReturnValue.isUnused()) { uint64_t size = CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy)); -if (EmitLifetimeStart(size, SRetPtr.getPointer())) - UnusedReturnSize = size; +UnusedReturnSizePtr = EmitLifetimeStart(size, SRetPtr.getPointer()); } } if (IRFunctionArgs.hasSRetArg()) { @@ -4231,6 +4230,15 @@ RValue CodeGenFunction::EmitCall(const C CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex, llvm::Attribute::NoUnwind); } + + // If we made a temporary, be sure to clean up after ourselves. Note that we + // can't depend on being inside of an ExprWithCleanups, so we need to manually + // pop this cleanup later on. Being eager about this is OK, since this + // temporary is 'invisible' outside of the callee. + if (UnusedReturnSizePtr) +pushFullExprCleanup(NormalEHLifetimeMarker, SRetPtr, + UnusedReturnSizePtr); + llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest(); SmallVector BundleList = @@ -4284,9 +4292,8 @@ RValue CodeGenFunction::EmitCall(const C // insertion point; this allows the rest of IRGen to discard // unreachable code. if (CS.doesNotReturn()) { -if (UnusedReturnSize) - EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize), - SRetPtr.getPointer()); +if (UnusedReturnSizePtr) + PopCleanupBlock(); // Strip away the noreturn attribute to better diagnose unreachable UB. if (SanOpts.has(SanitizerKind::Unreachable)) { @@ -4355,9 +4362,8 @@ RValue CodeGenFunction::EmitCall(const C case ABIArgInfo::InAlloca: case ABIArgInfo::Indirect: { RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation()); - if (UnusedReturnSize) -EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize), -SRetPtr.getPointer()); + if (UnusedReturnSizePtr) +PopCleanupBlock(); return ret; } Added: cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp?rev=326988&view=auto == --- cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp (added) +++ cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp Wed Mar 7 21:32:30 2018 @@ -0,0 +1,189 @@ +// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu %s -o - -emit-llvm -O1 \ +// RUN: -fexceptions -fcxx-exceptions | FileCheck %s +// +// We should emit lifetime.ends for these temporaries in both the 'exception' +// and 'normal' paths in functions. +// +// -O1 is necessary to make lifetime markers appear. + +struct Large { + int cs[32]; +}; + +Large getLarge(); + +// Used to ensure we emit invokes. +struct NontrivialDtor { + int i; + ~NontrivialDtor(); +}; + +// CHECK-LABEL: define void @_Z33cleanupsAreEmittedWithoutTryCatchv +void cleanupsAreEmittedWithoutTryCatch() { +// CHECK: %[[CLEAN:[^ ]+]] = bitcast %struct.NontrivialDtor* %{{[^ ]+}} to i8* +// CHECK: call
r327192 - [CodeGen] Try to not call a dtor after lifetime.end
Author: gbiv Date: Fri Mar 9 17:11:17 2018 New Revision: 327192 URL: http://llvm.org/viewvc/llvm-project?rev=327192&view=rev Log: [CodeGen] Try to not call a dtor after lifetime.end If CodeGenFunction::EmitCall is: - asked to emit a call with an indirectly returned value, - given an invalid return value slot, and - told the return value of the function it's calling is unused then it'll make its own temporary, and add lifetime markers so that the temporary's lifetime ends immediately after the call. The early lifetime.end becomes problematic when we need to run a destructor on the result of the function. Instead of unconditionally saying that results of all calls are used here (which would be correct, but would also cause us to never emit lifetime markers for these temporaries), we just build our own temporary to pass in when a dtor has to be run. Modified: cfe/trunk/lib/CodeGen/CGExprAgg.cpp cfe/trunk/test/CodeGenObjC/arc.m Modified: cfe/trunk/lib/CodeGen/CGExprAgg.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprAgg.cpp?rev=327192&r1=327191&r2=327192&view=diff == --- cfe/trunk/lib/CodeGen/CGExprAgg.cpp (original) +++ cfe/trunk/lib/CodeGen/CGExprAgg.cpp Fri Mar 9 17:11:17 2018 @@ -37,23 +37,6 @@ class AggExprEmitter : public StmtVisito AggValueSlot Dest; bool IsResultUnused; - /// We want to use 'dest' as the return slot except under two - /// conditions: - /// - The destination slot requires garbage collection, so we - /// need to use the GC API. - /// - The destination slot is potentially aliased. - bool shouldUseDestForReturnSlot() const { -return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased()); - } - - ReturnValueSlot getReturnValueSlot() const { -if (!shouldUseDestForReturnSlot()) - return ReturnValueSlot(); - -return ReturnValueSlot(Dest.getAddress(), Dest.isVolatile(), - IsResultUnused); - } - AggValueSlot EnsureSlot(QualType T) { if (!Dest.isIgnored()) return Dest; return CGF.CreateAggTemp(T, "agg.tmp.ensured"); @@ -63,6 +46,15 @@ class AggExprEmitter : public StmtVisito Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured"); } + // Calls `Fn` with a valid return value slot, potentially creating a temporary + // to do so. If a temporary is created, an appropriate copy into `Dest` will + // be emitted. + // + // The given function should take a ReturnValueSlot, and return an RValue that + // points to said slot. + void withReturnValueSlot(const Expr *E, + llvm::function_ref Fn); + public: AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused) : CGF(cgf), Builder(CGF.Builder), Dest(Dest), @@ -242,34 +234,44 @@ bool AggExprEmitter::TypeRequiresGCollec return Record->hasObjectMember(); } -/// \brief Perform the final move to DestPtr if for some reason -/// getReturnValueSlot() didn't use it directly. -/// -/// The idea is that you do something like this: -/// RValue Result = EmitSomething(..., getReturnValueSlot()); -/// EmitMoveFromReturnSlot(E, Result); -/// -/// If nothing interferes, this will cause the result to be emitted -/// directly into the return value slot. Otherwise, a final move -/// will be performed. -void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) { - // Push destructor if the result is ignored and the type is a C struct that - // is non-trivial to destroy. - QualType Ty = E->getType(); - if (Dest.isIgnored() && - Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) -CGF.pushDestroy(Ty.isDestructedType(), src.getAggregateAddress(), Ty); - - if (shouldUseDestForReturnSlot()) { -// Logically, Dest.getAddr() should equal Src.getAggregateAddr(). -// The possibility of undef rvalues complicates that a lot, -// though, so we can't really assert. -return; +void AggExprEmitter::withReturnValueSlot( +const Expr *E, llvm::function_ref EmitCall) { + QualType RetTy = E->getType(); + bool RequiresDestruction = + Dest.isIgnored() && + RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct; + + // If it makes no observable difference, save a memcpy + temporary. + // + // We need to always provide our own temporary if destruction is required. + // Otherwise, EmitCall will emit its own, notice that it's "unused", and end + // its lifetime before we have the chance to emit a proper destructor call. + bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() || + (RequiresDestruction && !Dest.getAddress().isValid()); + + Address RetAddr = Address::invalid(); + if (!UseTemp) { +RetAddr = Dest.getAddress(); + } else { +RetAddr = CGF.CreateMemTemp(RetTy); +uint64_t Size = +CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy)); +if (llvm::Value *LifetimeSizePtr =
r327229 - [CodeGen] Eagerly emit lifetime.end markers for calls
Author: gbiv Date: Sat Mar 10 15:06:31 2018 New Revision: 327229 URL: http://llvm.org/viewvc/llvm-project?rev=327229&view=rev Log: [CodeGen] Eagerly emit lifetime.end markers for calls In C, we'll wait until the end of the scope to clean up aggregate temporaries used for returns from calls. This means in cases like: { // Assuming that `Bar` is large enough to warrant indirect returns struct Bar b = {}; b = foo(&b); b = foo(&b); b = foo(&b); b = foo(&b); } ...We'll allocate space for 5 Bars on the stack (`b`, and 4 temporaries). This becomes painful in things like large switch statements. If cleaning up sooner is trivial, we should do it. Added: cfe/trunk/test/CodeGen/aggregate-assign-call.c Modified: cfe/trunk/lib/CodeGen/CGExprAgg.cpp Modified: cfe/trunk/lib/CodeGen/CGExprAgg.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprAgg.cpp?rev=327229&r1=327228&r2=327229&view=diff == --- cfe/trunk/lib/CodeGen/CGExprAgg.cpp (original) +++ cfe/trunk/lib/CodeGen/CGExprAgg.cpp Sat Mar 10 15:06:31 2018 @@ -23,6 +23,7 @@ #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Intrinsics.h" +#include "llvm/IR/IntrinsicInst.h" using namespace clang; using namespace CodeGen; @@ -48,7 +49,7 @@ class AggExprEmitter : public StmtVisito // Calls `Fn` with a valid return value slot, potentially creating a temporary // to do so. If a temporary is created, an appropriate copy into `Dest` will - // be emitted. + // be emitted, as will lifetime markers. // // The given function should take a ReturnValueSlot, and return an RValue that // points to said slot. @@ -250,16 +251,28 @@ void AggExprEmitter::withReturnValueSlot (RequiresDestruction && !Dest.getAddress().isValid()); Address RetAddr = Address::invalid(); + + EHScopeStack::stable_iterator LifetimeEndBlock; + llvm::Value *LifetimeSizePtr = nullptr; + llvm::IntrinsicInst *LifetimeStartInst = nullptr; if (!UseTemp) { RetAddr = Dest.getAddress(); } else { RetAddr = CGF.CreateMemTemp(RetTy); uint64_t Size = CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy)); -if (llvm::Value *LifetimeSizePtr = -CGF.EmitLifetimeStart(Size, RetAddr.getPointer())) +LifetimeSizePtr = CGF.EmitLifetimeStart(Size, RetAddr.getPointer()); +if (LifetimeSizePtr) { + LifetimeStartInst = + cast(std::prev(Builder.GetInsertPoint())); + assert(LifetimeStartInst->getIntrinsicID() == + llvm::Intrinsic::lifetime_start && + "Last insertion wasn't a lifetime.start?"); + CGF.pushFullExprCleanup( NormalEHLifetimeMarker, RetAddr, LifetimeSizePtr); + LifetimeEndBlock = CGF.EHStack.stable_begin(); +} } RValue Src = @@ -268,9 +281,18 @@ void AggExprEmitter::withReturnValueSlot if (RequiresDestruction) CGF.pushDestroy(RetTy.isDestructedType(), Src.getAggregateAddress(), RetTy); - if (UseTemp) { -assert(Dest.getPointer() != Src.getAggregatePointer()); -EmitFinalDestCopy(E->getType(), Src); + if (!UseTemp) +return; + + assert(Dest.getPointer() != Src.getAggregatePointer()); + EmitFinalDestCopy(E->getType(), Src); + + if (!RequiresDestruction && LifetimeStartInst) { +// If there's no dtor to run, the copy was the last use of our temporary. +// Since we're not guaranteed to be in an ExprWithCleanups, clean up +// eagerly. +CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst); +CGF.EmitLifetimeEnd(LifetimeSizePtr, RetAddr.getPointer()); } } Added: cfe/trunk/test/CodeGen/aggregate-assign-call.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/aggregate-assign-call.c?rev=327229&view=auto == --- cfe/trunk/test/CodeGen/aggregate-assign-call.c (added) +++ cfe/trunk/test/CodeGen/aggregate-assign-call.c Sat Mar 10 15:06:31 2018 @@ -0,0 +1,101 @@ +// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O1 -S -emit-llvm -o - %s | FileCheck %s --check-prefix=O1 +// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O0 -S -emit-llvm -o - %s | FileCheck %s --check-prefix=O0 +// +// Ensure that we place appropriate lifetime markers around indirectly returned +// temporaries, and that the lifetime.ends appear in a timely manner. +// +// -O1 is used so lifetime markers actually get emitted. + +struct S { + int ns[40]; +}; + +struct S foo(void); + +// CHECK-LABEL: define dso_local void @bar +struct S bar() { + // O0-NOT: @llvm.lifetime.start + // O0-NOT: @llvm.lifetime.end + + struct S r; + // O1: call void @llvm.lifetime.start.p0i8({{[^,]*}}, i8* nonnull %[[R_TMP:[^)]+]]) + + // O1: call void @llvm.lifetime.start.p0i8({{[^,]*}}, i8* nonnull %[[TMP1:[^)]+]]) + // O1: call void @foo + r = foo(); + // O1: call void @llvm.life
r327945 - Properly construct `inline` members without initializers
Author: gbiv Date: Mon Mar 19 20:27:44 2018 New Revision: 327945 URL: http://llvm.org/viewvc/llvm-project?rev=327945&view=rev Log: Properly construct `inline` members without initializers Digging through commit logs, it appears the checks in this block predate `inline` class variables. With them, we fail to emit dynamic initializers for members that don't have an explicit initializer, and we won't go out of our way to instantiate the class denoted by `Var->getType()`. Fixes PR35599. Modified: cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp cfe/trunk/test/CodeGenCXX/cxx1z-inline-variables.cpp Modified: cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp?rev=327945&r1=327944&r2=327945&view=diff == --- cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp (original) +++ cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp Mon Mar 19 20:27:44 2018 @@ -4202,7 +4202,9 @@ void Sema::InstantiateVariableInitialize Var->setInvalidDecl(); } } else { -if (Var->isStaticDataMember()) { +// `inline` variables are a definition and declaration all in one; we won't +// pick up an initializer from anywhere else. +if (Var->isStaticDataMember() && !Var->isInline()) { if (!Var->isOutOfLine()) return; Modified: cfe/trunk/test/CodeGenCXX/cxx1z-inline-variables.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/cxx1z-inline-variables.cpp?rev=327945&r1=327944&r2=327945&view=diff == --- cfe/trunk/test/CodeGenCXX/cxx1z-inline-variables.cpp (original) +++ cfe/trunk/test/CodeGenCXX/cxx1z-inline-variables.cpp Mon Mar 19 20:27:44 2018 @@ -111,3 +111,29 @@ int e = d; // CHECK-NOT: __cxa_guard_acquire(i64* @_ZGV1b) // CHECK: call i32 @_Z1fv // CHECK-NOT: __cxa_guard_release(i64* @_ZGV1b) + +namespace PR35599 { +struct Marker1 {}; +struct Marker2 {}; + +template +struct Foo { + struct Bar { Bar(); }; + inline static Bar bar; +}; + +void run() { + // All we want here are ODR uses. Anything that requires that the type is + // complete is uninteresting. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-value" + Foo::bar; +#pragma clang diagnostic pop + static_cast(Foo::bar); +} + +// CHECK-LABEL: define {{.*}}global_var_init{{.*}}comdat +// CHECK: call void @_ZN7PR355993FooINS_7Marker1EE3BarC1Ev +// CHECK-LABEL: define {{.*}}global_var_init{{.*}}comdat +// CHECK: call void @_ZN7PR355993FooINS_7Marker2EE3BarC1Ev +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r355944 - Add a creduce script for clang crashes
Author: gbiv Date: Tue Mar 12 10:48:53 2019 New Revision: 355944 URL: http://llvm.org/viewvc/llvm-project?rev=355944&view=rev Log: Add a creduce script for clang crashes This CL adds a script that calls C-Reduce on an input file and given the clang crash script, which is used to generate an interestingness test for C-Reduce. Patch by Amy Huang! Differential Revision: https://reviews.llvm.org/D59118 Added: cfe/trunk/utils/creduce-clang-crash.py Added: cfe/trunk/utils/creduce-clang-crash.py URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/creduce-clang-crash.py?rev=355944&view=auto == --- cfe/trunk/utils/creduce-clang-crash.py (added) +++ cfe/trunk/utils/creduce-clang-crash.py Tue Mar 12 10:48:53 2019 @@ -0,0 +1,118 @@ +#!/usr/bin/env python +"""Calls C-Reduce to create a minimal reproducer for clang crashes. + +Requires C-Reduce and not (part of LLVM utils) to be installed. +""" + +from argparse import ArgumentParser +import os +import re +import stat +import sys +import subprocess +import pipes +from distutils.spawn import find_executable + +def create_test(build_script, llvm_not): + """ + Create an interestingness test from the crash output. + Return as a string. + """ + # Get clang call from build script + # Assumes the call is the last line of the script + with open(build_script) as f: +cmd = f.readlines()[-1].rstrip('\n\r') + + # Get crash output + p = subprocess.Popen(build_script, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + crash_output, _ = p.communicate() + + output = ['#!/bin/bash'] + output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not), + cmd)) + + # Add messages from crash output to the test + # If there is an Assertion failure, use that; otherwise use the + # last five stack trace functions + assertion_re = r'Assertion `([^\']+)\' failed' + assertion_match = re.search(assertion_re, crash_output) + if assertion_match: +msg = assertion_match.group(1) +output.append('grep %s t.log || exit 1' % pipes.quote(msg)) + else: +stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\(' +matches = re.findall(stacktrace_re, crash_output) +del matches[:-5] +output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches] + + return output + +def main(): + parser = ArgumentParser(description=__doc__) + parser.add_argument('build_script', type=str, nargs=1, + help='Name of the script that generates the crash.') + parser.add_argument('file_to_reduce', type=str, nargs=1, + help='Name of the file to be reduced.') + parser.add_argument('-o', '--output', dest='output', type=str, + help='Name of the output file for the reduction. Optional.') + parser.add_argument('--llvm-not', dest='llvm_not', type=str, + help="The path to the llvm-not executable. " + "Required if 'not' is not in PATH environment."); + parser.add_argument('--creduce', dest='creduce', type=str, + help="The path to the C-Reduce executable. " + "Required if 'creduce' is not in PATH environment."); + args = parser.parse_args() + + build_script = os.path.abspath(args.build_script[0]) + file_to_reduce = os.path.abspath(args.file_to_reduce[0]) + llvm_not = (find_executable(args.llvm_not) if args.llvm_not else + find_executable('not')) + creduce = (find_executable(args.creduce) if args.creduce else + find_executable('creduce')) + + if not os.path.isfile(build_script): +print(("ERROR: input file '%s' does not exist") % build_script) +return 1 + + if not os.path.isfile(file_to_reduce): +print(("ERROR: input file '%s' does not exist") % file_to_reduce) +return 1 + + if not llvm_not: +parser.print_help() +return 1 + + if not creduce: +parser.print_help() +return 1 + + # Write interestingness test to file + test_contents = create_test(build_script, llvm_not) + testname, _ = os.path.splitext(file_to_reduce) + testfile = testname + '.test.sh' + with open(testfile, 'w') as f: +f.write('\n'.join(test_contents)) + os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC) + + # Confirm that the interestingness test passes + try: +with open(os.devnull, 'w') as devnull: + subprocess.check_call(testfile, stdout=devnull) + except subprocess.CalledProcessError: +print("For some reason the interestingness test does not return zero") +return 1 + + # FIXME: try running clang preprocessor first + + try: +p = subprocess.Popen([creduce, testfile, file_to_reduce]) +p.communicate() + except KeyboardInterrupt: +# Hack to kill C-Reduce because it jumps into its own pgid +print('\n\nctrl-c detected, killed creduce') +p.kill() + +if __
r356636 - creduce-clang-crash.py: preprocess file + reduce commandline
Author: gbiv Date: Wed Mar 20 18:01:53 2019 New Revision: 356636 URL: http://llvm.org/viewvc/llvm-project?rev=356636&view=rev Log: creduce-clang-crash.py: preprocess file + reduce commandline This CL causes our creduce-clang-crash.py util to: - try to preprocess the file before reducing - try to remove some command line arguments - now require a llvm bin directory, since the generated crash script doesn't have an absolute path for clang It also marks it as executable, since I forgot to do that in the last commit. :) Patch by Amy Huang! Differential Revision: https://reviews.llvm.org/D59440 Modified: cfe/trunk/utils/creduce-clang-crash.py Modified: cfe/trunk/utils/creduce-clang-crash.py URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/creduce-clang-crash.py?rev=356636&r1=356635&r2=356636&view=diff == --- cfe/trunk/utils/creduce-clang-crash.py (original) +++ cfe/trunk/utils/creduce-clang-crash.py Wed Mar 20 18:01:53 2019 @@ -1,7 +1,5 @@ #!/usr/bin/env python """Calls C-Reduce to create a minimal reproducer for clang crashes. - -Requires C-Reduce and not (part of LLVM utils) to be installed. """ from argparse import ArgumentParser @@ -11,108 +9,232 @@ import stat import sys import subprocess import pipes +import shlex +import tempfile +import shutil from distutils.spawn import find_executable -def create_test(build_script, llvm_not): +verbose = False +llvm_bin = None +creduce_cmd = None +not_cmd = None + +def check_file(fname): + if not os.path.isfile(fname): +sys.exit("ERROR: %s does not exist" % (fname)) + return fname + +def check_cmd(cmd_name, cmd_dir, cmd_path=None): """ - Create an interestingness test from the crash output. - Return as a string. + Returns absolute path to cmd_path if it is given, + or absolute path to cmd_dir/cmd_name. """ - # Get clang call from build script - # Assumes the call is the last line of the script - with open(build_script) as f: -cmd = f.readlines()[-1].rstrip('\n\r') + if cmd_path: +cmd = find_executable(cmd_path) +if cmd: + return cmd +sys.exit("ERROR: executable %s not found" % (cmd_path)) + + cmd = find_executable(cmd_name, path=cmd_dir) + if cmd: +return cmd + sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir)) + +def quote_cmd(cmd): + return ' '.join(arg if arg.startswith('$') else pipes.quote(arg) + for arg in cmd) + +def get_crash_cmd(crash_script): + with open(crash_script) as f: +# Assume clang call is on the last line of the script +line = f.readlines()[-1] +cmd = shlex.split(line) + +# Overwrite the script's clang with the user's clang path +new_clang = check_cmd('clang', llvm_bin) +cmd[0] = pipes.quote(new_clang) +return cmd - # Get crash output - p = subprocess.Popen(build_script, +def has_expected_output(crash_cmd, expected_output): + p = subprocess.Popen(crash_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) crash_output, _ = p.communicate() + return all(msg in crash_output for msg in expected_output) - output = ['#!/bin/bash'] - output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not), - cmd)) - - # Add messages from crash output to the test - # If there is an Assertion failure, use that; otherwise use the - # last five stack trace functions +def get_expected_output(crash_cmd): + p = subprocess.Popen(crash_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + crash_output, _ = p.communicate() + + # If there is an assertion failure, use that; + # otherwise use the last five stack trace functions assertion_re = r'Assertion `([^\']+)\' failed' assertion_match = re.search(assertion_re, crash_output) if assertion_match: -msg = assertion_match.group(1) -output.append('grep %s t.log || exit 1' % pipes.quote(msg)) +return [assertion_match.group(1)] else: stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\(' matches = re.findall(stacktrace_re, crash_output) -del matches[:-5] -output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches] +return matches[-5:] + +def write_interestingness_test(testfile, crash_cmd, expected_output, + file_to_reduce): + filename = os.path.basename(file_to_reduce) + if filename not in crash_cmd: +sys.exit("ERROR: expected %s to be in the crash command" % filename) + + # Replace all instances of file_to_reduce with a command line variable + output = ['#!/bin/bash', +'if [ -z "$1" ] ; then', +' f=%s' % (pipes.quote(filename)), +'else', +' f="$1"', +'fi'] + cmd = ['$f' if s == filename else s for s in crash_cmd] + + output.append('%s --crash %s >& t.log || exit 1' % (pipes.qu
r357290 - Various fixes and additions to creduce-clang-crash.py
Author: gbiv Date: Fri Mar 29 10:50:43 2019 New Revision: 357290 URL: http://llvm.org/viewvc/llvm-project?rev=357290&view=rev Log: Various fixes and additions to creduce-clang-crash.py Some more additions to the script - mainly reducing the clang args after the creduce run by removing them one by one and seeing if the crash reproduces. Other things: - remove the --crash flag when "fatal error" occurs - fixed to read stack trace functions from the top - run creduce on a copy of the original file Patch by Amy Huang! Differential Revision: https://reviews.llvm.org/D59725 Modified: cfe/trunk/utils/creduce-clang-crash.py Modified: cfe/trunk/utils/creduce-clang-crash.py URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/creduce-clang-crash.py?rev=357290&r1=357289&r2=357290&view=diff == --- cfe/trunk/utils/creduce-clang-crash.py (original) +++ cfe/trunk/utils/creduce-clang-crash.py Fri Mar 29 10:50:43 2019 @@ -1,8 +1,14 @@ #!/usr/bin/env python """Calls C-Reduce to create a minimal reproducer for clang crashes. + +Output files: + *.reduced.sh -- crash reproducer with minimal arguments + *.reduced.cpp -- the reduced file + *.test.sh -- interestingness test for C-Reduce """ -from argparse import ArgumentParser +from __future__ import print_function +from argparse import ArgumentParser, RawTextHelpFormatter import os import re import stat @@ -15,10 +21,14 @@ import shutil from distutils.spawn import find_executable verbose = False -llvm_bin = None creduce_cmd = None +clang_cmd = None not_cmd = None +def verbose_print(*args, **kwargs): + if verbose: +print(*args, **kwargs) + def check_file(fname): if not os.path.isfile(fname): sys.exit("ERROR: %s does not exist" % (fname)) @@ -33,166 +43,339 @@ def check_cmd(cmd_name, cmd_dir, cmd_pat cmd = find_executable(cmd_path) if cmd: return cmd -sys.exit("ERROR: executable %s not found" % (cmd_path)) +sys.exit("ERROR: executable `%s` not found" % (cmd_path)) cmd = find_executable(cmd_name, path=cmd_dir) if cmd: return cmd - sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir)) -def quote_cmd(cmd): - return ' '.join(arg if arg.startswith('$') else pipes.quote(arg) - for arg in cmd) + if not cmd_dir: +cmd_dir = "$PATH" + sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir)) -def get_crash_cmd(crash_script): - with open(crash_script) as f: -# Assume clang call is on the last line of the script -line = f.readlines()[-1] -cmd = shlex.split(line) - -# Overwrite the script's clang with the user's clang path -new_clang = check_cmd('clang', llvm_bin) -cmd[0] = pipes.quote(new_clang) -return cmd +def quote_cmd(cmd): + return ' '.join(pipes.quote(arg) for arg in cmd) -def has_expected_output(crash_cmd, expected_output): - p = subprocess.Popen(crash_cmd, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) - crash_output, _ = p.communicate() - return all(msg in crash_output for msg in expected_output) - -def get_expected_output(crash_cmd): - p = subprocess.Popen(crash_cmd, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) - crash_output, _ = p.communicate() - - # If there is an assertion failure, use that; - # otherwise use the last five stack trace functions - assertion_re = r'Assertion `([^\']+)\' failed' - assertion_match = re.search(assertion_re, crash_output) - if assertion_match: -return [assertion_match.group(1)] - else: -stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\(' -matches = re.findall(stacktrace_re, crash_output) -return matches[-5:] - -def write_interestingness_test(testfile, crash_cmd, expected_output, - file_to_reduce): - filename = os.path.basename(file_to_reduce) - if filename not in crash_cmd: -sys.exit("ERROR: expected %s to be in the crash command" % filename) - - # Replace all instances of file_to_reduce with a command line variable - output = ['#!/bin/bash', -'if [ -z "$1" ] ; then', -' f=%s' % (pipes.quote(filename)), -'else', -' f="$1"', -'fi'] - cmd = ['$f' if s == filename else s for s in crash_cmd] - - output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd), - quote_cmd(cmd))) - - for msg in expected_output: -output.append('grep %s t.log || exit 1' % pipes.quote(msg)) - - with open(testfile, 'w') as f: -f.write('\n'.join(output)) - os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC) - -def check_interestingness(testfile, file_to_reduce): - testfile = os.path.abspath(testfile) - - # Check that the test considers the original file interesting - with open(os.devnull, 'w') as devnull: -returncode = subproc
[clang-tools-extra] r362672 - android: add a close-on-exec check on pipe2()
Author: gbiv Date: Wed Jun 5 22:21:39 2019 New Revision: 362672 URL: http://llvm.org/viewvc/llvm-project?rev=362672&view=rev Log: android: add a close-on-exec check on pipe2() On Android, pipe2() is better to set O_CLOEXEC flag to avoid file descriptor leakage. Patch by Jian Cai! Differential Revision: https://reviews.llvm.org/D62049 Added: clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.cpp clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.h clang-tools-extra/trunk/docs/clang-tidy/checks/android-cloexec-pipe2.rst clang-tools-extra/trunk/test/clang-tidy/android-cloexec-pipe2.cpp Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt clang-tools-extra/trunk/docs/ReleaseNotes.rst clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp?rev=362672&r1=362671&r2=362672&view=diff == --- clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp Wed Jun 5 22:21:39 2019 @@ -20,6 +20,7 @@ #include "CloexecInotifyInitCheck.h" #include "CloexecMemfdCreateCheck.h" #include "CloexecOpenCheck.h" +#include "CloexecPipe2Check.h" #include "CloexecSocketCheck.h" #include "ComparisonInTempFailureRetryCheck.h" @@ -49,6 +50,7 @@ public: CheckFactories.registerCheck( "android-cloexec-memfd-create"); CheckFactories.registerCheck("android-cloexec-open"); +CheckFactories.registerCheck("android-cloexec-pipe2"); CheckFactories.registerCheck("android-cloexec-socket"); CheckFactories.registerCheck( "android-comparison-in-temp-failure-retry"); Modified: clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt?rev=362672&r1=362671&r2=362672&view=diff == --- clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt (original) +++ clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt Wed Jun 5 22:21:39 2019 @@ -14,6 +14,7 @@ add_clang_library(clangTidyAndroidModule CloexecInotifyInitCheck.cpp CloexecMemfdCreateCheck.cpp CloexecOpenCheck.cpp + CloexecPipe2Check.cpp CloexecSocketCheck.cpp ComparisonInTempFailureRetryCheck.cpp Added: clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.cpp?rev=362672&view=auto == --- clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.cpp (added) +++ clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.cpp Wed Jun 5 22:21:39 2019 @@ -0,0 +1,33 @@ +//===--- CloexecPipe2Check.cpp - clang-tidy===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "CloexecPipe2Check.h" +#include "../utils/ASTUtils.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang { +namespace tidy { +namespace android { + +void CloexecPipe2Check::registerMatchers(MatchFinder *Finder) { + registerMatchersImpl(Finder, + functionDecl(returns(isInteger()), hasName("pipe2"), +hasParameter(0, hasType(pointsTo(isInteger(, +hasParameter(1, hasType(isInteger(); +} + +void CloexecPipe2Check::check(const MatchFinder::MatchResult &Result) { + insertMacroFlag(Result, /*MacroFlag=*/"O_CLOEXEC", /*ArgPos=*/1); +} + +} // namespace android +} // namespace tidy +} // namespace clang Added: clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.h URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.h?rev=362672&view=auto == --- clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.h (added) +++ clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.h Wed Jun 5 22:21:39 2019 @@ -0,0 +1,34 @@ +//===--- CloexecPipe2Check.h - clang-tidy*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license in
[clang-tools-extra] r362673 - android: add a close-on-exec check on pipe()
Author: gbiv Date: Wed Jun 5 22:21:45 2019 New Revision: 362673 URL: http://llvm.org/viewvc/llvm-project?rev=362673&view=rev Log: android: add a close-on-exec check on pipe() On Android, pipe() is better to be replaced by pipe2() with O_CLOEXEC flag to avoid file descriptor leakage. Patch by Jian Cai! Differential Revision: https://reviews.llvm.org/D61967 Added: clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.cpp clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.h clang-tools-extra/trunk/docs/clang-tidy/checks/android-cloexec-pipe.rst clang-tools-extra/trunk/test/clang-tidy/android-cloexec-pipe.cpp Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt clang-tools-extra/trunk/docs/ReleaseNotes.rst clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp?rev=362673&r1=362672&r2=362673&view=diff == --- clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp Wed Jun 5 22:21:45 2019 @@ -20,6 +20,7 @@ #include "CloexecInotifyInitCheck.h" #include "CloexecMemfdCreateCheck.h" #include "CloexecOpenCheck.h" +#include "CloexecPipeCheck.h" #include "CloexecPipe2Check.h" #include "CloexecSocketCheck.h" #include "ComparisonInTempFailureRetryCheck.h" @@ -50,6 +51,7 @@ public: CheckFactories.registerCheck( "android-cloexec-memfd-create"); CheckFactories.registerCheck("android-cloexec-open"); +CheckFactories.registerCheck("android-cloexec-pipe"); CheckFactories.registerCheck("android-cloexec-pipe2"); CheckFactories.registerCheck("android-cloexec-socket"); CheckFactories.registerCheck( Modified: clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt?rev=362673&r1=362672&r2=362673&view=diff == --- clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt (original) +++ clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt Wed Jun 5 22:21:45 2019 @@ -14,6 +14,7 @@ add_clang_library(clangTidyAndroidModule CloexecInotifyInitCheck.cpp CloexecMemfdCreateCheck.cpp CloexecOpenCheck.cpp + CloexecPipeCheck.cpp CloexecPipe2Check.cpp CloexecSocketCheck.cpp ComparisonInTempFailureRetryCheck.cpp Added: clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.cpp?rev=362673&view=auto == --- clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.cpp (added) +++ clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.cpp Wed Jun 5 22:21:45 2019 @@ -0,0 +1,37 @@ +//===--- CloexecPipeCheck.cpp - clang-tidy-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "CloexecPipeCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang { +namespace tidy { +namespace android { + +void CloexecPipeCheck::registerMatchers(MatchFinder *Finder) { + registerMatchersImpl(Finder, + functionDecl(returns(isInteger()), hasName("pipe"), +hasParameter(0, hasType(pointsTo(isInteger()); +} + +void CloexecPipeCheck::check(const MatchFinder::MatchResult &Result) { + std::string ReplacementText = + (Twine("pipe2(") + getSpellingArg(Result, 0) + ", O_CLOEXEC)").str(); + + replaceFunc( + Result, + "prefer pipe2() with O_CLOEXEC to avoid leaking file descriptors to child processes", + ReplacementText); +} + +} // namespace android +} // namespace tidy +} // namespace clang Added: clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.h URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.h?rev=362673&view=auto == --- clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.h (added) +++ clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.h Wed Jun 5 22:21:45 2019 @@ -0,0 +1,34 @@ +//===--- CloexecPipeCheck.h - clang-tidy-*- C++
r363346 - [Targets] Move soft-float-abi filtering to `initFeatureMap`
Author: gbiv Date: Thu Jun 13 17:35:17 2019 New Revision: 363346 URL: http://llvm.org/viewvc/llvm-project?rev=363346&view=rev Log: [Targets] Move soft-float-abi filtering to `initFeatureMap` ARM has a special target feature called soft-float-abi. This feature is special, since we get it passed to us explicitly in the frontend, but filter it out before it can land in any target feature strings in LLVM IR. __attribute__((target(""))) doesn't quite filter these features out properly, so today, we get warnings about soft-float-abi being an unknown feature from the backend. This CL has us filter soft-float-abi out at a slightly different point, so we don't end up passing these invalid features to the backend. Differential Revision: https://reviews.llvm.org/D61750 Added: cfe/trunk/test/CodeGen/arm-soft-float-abi-filtering.c Modified: cfe/trunk/lib/Basic/Targets/ARM.cpp cfe/trunk/lib/Basic/Targets/ARM.h Modified: cfe/trunk/lib/Basic/Targets/ARM.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/ARM.cpp?rev=363346&r1=363345&r2=363346&view=diff == --- cfe/trunk/lib/Basic/Targets/ARM.cpp (original) +++ cfe/trunk/lib/Basic/Targets/ARM.cpp Thu Jun 13 17:35:17 2019 @@ -323,6 +323,8 @@ ARMTargetInfo::ARMTargetInfo(const llvm: this->MCountName = Opts.EABIVersion == llvm::EABI::GNU ? "\01__gnu_mcount_nc" : "\01mcount"; + + SoftFloatABI = llvm::is_contained(Opts.FeaturesAsWritten, "+soft-float-abi"); } StringRef ARMTargetInfo::getABI() const { return ABI; } @@ -385,12 +387,21 @@ bool ARMTargetInfo::initFeatureMap( // Convert user-provided arm and thumb GNU target attributes to // [-|+]thumb-mode target features respectively. - std::vector UpdatedFeaturesVec(FeaturesVec); - for (auto &Feature : UpdatedFeaturesVec) { -if (Feature.compare("+arm") == 0) - Feature = "-thumb-mode"; -else if (Feature.compare("+thumb") == 0) - Feature = "+thumb-mode"; + std::vector UpdatedFeaturesVec; + for (const auto &Feature : FeaturesVec) { +// Skip soft-float-abi; it's something we only use to initialize a bit of +// class state, and is otherwise unrecognized. +if (Feature == "+soft-float-abi") + continue; + +StringRef FixedFeature; +if (Feature == "+arm") + FixedFeature = "-thumb-mode"; +else if (Feature == "+thumb") + FixedFeature = "+thumb-mode"; +else + FixedFeature = Feature; +UpdatedFeaturesVec.push_back(FixedFeature.str()); } return TargetInfo::initFeatureMap(Features, Diags, CPU, UpdatedFeaturesVec); @@ -405,7 +416,8 @@ bool ARMTargetInfo::handleTargetFeatures Crypto = 0; DSP = 0; Unaligned = 1; - SoftFloat = SoftFloatABI = false; + SoftFloat = false; + // Note that SoftFloatABI is initialized in our constructor. HWDiv = 0; DotProd = 0; HasFloat16 = true; @@ -415,8 +427,6 @@ bool ARMTargetInfo::handleTargetFeatures for (const auto &Feature : Features) { if (Feature == "+soft-float") { SoftFloat = true; -} else if (Feature == "+soft-float-abi") { - SoftFloatABI = true; } else if (Feature == "+vfp2sp" || Feature == "+vfp2d16sp" || Feature == "+vfp2" || Feature == "+vfp2d16") { FPU |= VFP2FPU; @@ -510,11 +520,6 @@ bool ARMTargetInfo::handleTargetFeatures else if (FPMath == FP_VFP) Features.push_back("-neonfp"); - // Remove front-end specific options which the backend handles differently. - auto Feature = llvm::find(Features, "+soft-float-abi"); - if (Feature != Features.end()) -Features.erase(Feature); - return true; } Modified: cfe/trunk/lib/Basic/Targets/ARM.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/ARM.h?rev=363346&r1=363345&r2=363346&view=diff == --- cfe/trunk/lib/Basic/Targets/ARM.h (original) +++ cfe/trunk/lib/Basic/Targets/ARM.h Thu Jun 13 17:35:17 2019 @@ -124,6 +124,12 @@ public: StringRef CPU, const std::vector &FeaturesVec) const override; + bool isValidFeatureName(StringRef Feature) const override { +// We pass soft-float-abi in as a -target-feature, but the backend figures +// this out through other means. +return Feature != "soft-float-abi"; + } + bool handleTargetFeatures(std::vector &Features, DiagnosticsEngine &Diags) override; Added: cfe/trunk/test/CodeGen/arm-soft-float-abi-filtering.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/arm-soft-float-abi-filtering.c?rev=363346&view=auto == --- cfe/trunk/test/CodeGen/arm-soft-float-abi-filtering.c (added) +++ cfe/trunk/test/CodeGen/arm-soft-float-abi-filtering.c Thu Jun 13 17:35:17 2019 @@ -0,0 +1,9 @@ +// REQUIRES: arm-registe
r366276 - Fix a typo in target features
Author: gbiv Date: Tue Jul 16 15:32:17 2019 New Revision: 366276 URL: http://llvm.org/viewvc/llvm-project?rev=366276&view=rev Log: Fix a typo in target features There was a slight typo in r364352 that ended up causing our backend to complain on some x86 Android builds. This CL fixes that. Differential Revision: https://reviews.llvm.org/D64781 Modified: cfe/trunk/lib/Driver/ToolChains/Arch/X86.cpp cfe/trunk/test/Driver/clang-translation.c Modified: cfe/trunk/lib/Driver/ToolChains/Arch/X86.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Arch/X86.cpp?rev=366276&r1=366275&r2=366276&view=diff == --- cfe/trunk/lib/Driver/ToolChains/Arch/X86.cpp (original) +++ cfe/trunk/lib/Driver/ToolChains/Arch/X86.cpp Tue Jul 16 15:32:17 2019 @@ -135,7 +135,7 @@ void x86::getX86TargetFeatures(const Dri if (ArchType == llvm::Triple::x86_64) { Features.push_back("+sse4.2"); Features.push_back("+popcnt"); - Features.push_back("+mcx16"); + Features.push_back("+cx16"); } else Features.push_back("+ssse3"); } Modified: cfe/trunk/test/Driver/clang-translation.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/clang-translation.c?rev=366276&r1=366275&r2=366276&view=diff == --- cfe/trunk/test/Driver/clang-translation.c (original) +++ cfe/trunk/test/Driver/clang-translation.c Tue Jul 16 15:32:17 2019 @@ -318,7 +318,7 @@ // ANDROID-X86_64: "-target-cpu" "x86-64" // ANDROID-X86_64: "-target-feature" "+sse4.2" // ANDROID-X86_64: "-target-feature" "+popcnt" -// ANDROID-X86_64: "-target-feature" "+mcx16" +// ANDROID-X86_64: "-target-feature" "+cx16" // RUN: %clang -target mips-linux-gnu -### -S %s 2>&1 | \ // RUN: FileCheck -check-prefix=MIPS %s ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r367067 - [Sema] add -Walloca to flag uses of `alloca`
Author: gbiv Date: Thu Jul 25 15:23:40 2019 New Revision: 367067 URL: http://llvm.org/viewvc/llvm-project?rev=367067&view=rev Log: [Sema] add -Walloca to flag uses of `alloca` This CL adds an optional warning to diagnose uses of the `__builtin_alloca` family of functions. The use of these functions is discouraged by many, so it seems like a good idea to allow clang to warn about it. Patch by Elaina Guan! Differential Revision: https://reviews.llvm.org/D64883 Added: cfe/trunk/test/Sema/warn-alloca.c Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td cfe/trunk/lib/Sema/SemaChecking.cpp Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=367067&r1=367066&r2=367067&view=diff == --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original) +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Thu Jul 25 15:23:40 2019 @@ -2779,6 +2779,11 @@ def err_no_accessor_for_property : Error def err_cannot_find_suitable_accessor : Error< "cannot find suitable %select{getter|setter}0 for property %1">; +def warn_alloca : Warning< + "use of function %0 is discouraged; there is no way to check for failure but " + "failure may still occur, resulting in a possibly exploitable security vulnerability">, + InGroup>, DefaultIgnore; + def warn_alloca_align_alignof : Warning< "second argument to __builtin_alloca_with_align is supposed to be in bits">, InGroup>; Modified: cfe/trunk/lib/Sema/SemaChecking.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=367067&r1=367066&r2=367067&view=diff == --- cfe/trunk/lib/Sema/SemaChecking.cpp (original) +++ cfe/trunk/lib/Sema/SemaChecking.cpp Thu Jul 25 15:23:40 2019 @@ -1179,6 +1179,10 @@ Sema::CheckBuiltinFunctionCall(FunctionD case Builtin::BI__builtin_alloca_with_align: if (SemaBuiltinAllocaWithAlign(TheCall)) return ExprError(); +LLVM_FALLTHROUGH; + case Builtin::BI__builtin_alloca: +Diag(TheCall->getBeginLoc(), diag::warn_alloca) +<< TheCall->getDirectCallee(); break; case Builtin::BI__assume: case Builtin::BI__builtin_assume: Added: cfe/trunk/test/Sema/warn-alloca.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-alloca.c?rev=367067&view=auto == --- cfe/trunk/test/Sema/warn-alloca.c (added) +++ cfe/trunk/test/Sema/warn-alloca.c Thu Jul 25 15:23:40 2019 @@ -0,0 +1,20 @@ +// RUN: %clang_cc1 -DSILENCE -fsyntax-only -verify -Wall %s +// RUN: %clang_cc1 -fsyntax-only -verify -Walloca %s + +#ifdef SILENCE + // expected-no-diagnostics +#endif + +void test1(int a) { + __builtin_alloca(a); +#ifndef SILENCE + // expected-warning@-2 {{use of function '__builtin_alloca' is discouraged; there is no way to check for failure but failure may still occur, resulting in a possibly exploitable security vulnerability}} +#endif +} + +void test2(int a) { + __builtin_alloca_with_align(a, 32); +#ifndef SILENCE + // expected-warning@-2 {{use of function '__builtin_alloca_with_align' is discouraged; there is no way to check for failure but failure may still occur, resulting in a possibly exploitable security vulnerability}} +#endif +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r367940 - [Sema] Add -Wpointer-compare
Author: gbiv Date: Mon Aug 5 15:15:40 2019 New Revision: 367940 URL: http://llvm.org/viewvc/llvm-project?rev=367940&view=rev Log: [Sema] Add -Wpointer-compare This patch adds a warning that diagnoses comparisons of pointers to '\0'. This is often indicative of a bug (e.g. the user might've forgotten to dereference the pointer). Patch by Elaina Guan! Differential Revision: https://reviews.llvm.org/D65595 Added: cfe/trunk/test/Sema/warn-nullchar-nullptr.c Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td cfe/trunk/include/clang/Sema/Sema.h cfe/trunk/lib/Sema/SemaExpr.cpp Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=367940&r1=367939&r2=367940&view=diff == --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original) +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Mon Aug 5 15:15:40 2019 @@ -3296,6 +3296,10 @@ def warn_impcast_bool_to_null_pointer : def warn_non_literal_null_pointer : Warning< "expression which evaluates to zero treated as a null pointer constant of " "type %0">, InGroup; +def warn_pointer_compare : Warning< +"comparing a pointer to a null character constant; did you mean " +"to compare to %select{NULL|(void *)0}0?">, +InGroup>; def warn_impcast_null_pointer_to_integer : Warning< "implicit conversion of %select{NULL|nullptr}0 constant to %1">, InGroup; Modified: cfe/trunk/include/clang/Sema/Sema.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=367940&r1=367939&r2=367940&view=diff == --- cfe/trunk/include/clang/Sema/Sema.h (original) +++ cfe/trunk/include/clang/Sema/Sema.h Mon Aug 5 15:15:40 2019 @@ -10022,6 +10022,7 @@ public: QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); + void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); Modified: cfe/trunk/lib/Sema/SemaExpr.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=367940&r1=367939&r2=367940&view=diff == --- cfe/trunk/lib/Sema/SemaExpr.cpp (original) +++ cfe/trunk/lib/Sema/SemaExpr.cpp Mon Aug 5 15:15:40 2019 @@ -10443,6 +10443,32 @@ static QualType checkArithmeticOrEnumera return S.Context.getLogicalOperationType(); } +void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { + if (!NullE.get()->getType()->isAnyPointerType()) +return; + int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; + if (!E.get()->getType()->isAnyPointerType() && + E.get()->isNullPointerConstant(Context, + Expr::NPC_ValueDependentIsNotNull) == +Expr::NPCK_ZeroExpression) { +if (const auto *CL = dyn_cast(E.get())) { + if (CL->getValue() == 0) +Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) +<< NullValue +<< FixItHint::CreateReplacement(E.get()->getExprLoc(), +NullValue ? "NULL" : "(void *)0"); +} else if (const auto *CE = dyn_cast(E.get())) { +TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); +QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); +if (T == Context.CharTy) + Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) + << NullValue + << FixItHint::CreateReplacement(E.get()->getExprLoc(), + NullValue ? "NULL" : "(void *)0"); + } + } +} + // C99 6.5.8, C++ [expr.rel] QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, @@ -10476,6 +10502,10 @@ QualType Sema::CheckCompareOperands(Expr } checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); + if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { +CheckPtrComparisonWithNullChar(LHS, RHS); +CheckPtrComparisonWithNullChar(RHS, LHS); + } // Handle vector comparisons separately. if (LHS.get()->getType()->isVectorType() || Added: cfe/trunk/test/Sema/warn-nullchar-nullptr.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-nullchar-nullptr.c?rev=367940&view=auto == --- cfe/trunk/test/Sema/warn-nullchar-nullptr.c (added) +++ cfe/trunk/test/Sema/warn-nullchar-nullptr.c Mon Aug 5 15:15:40 2019 @@ -0,0 +1,49 @@ +// RUN: %clang_cc1 -fsyntax-o
r367947 - [Sema] attempt to appease buildbots after r367940
Author: gbiv Date: Mon Aug 5 16:19:15 2019 New Revision: 367947 URL: http://llvm.org/viewvc/llvm-project?rev=367947&view=rev Log: [Sema] attempt to appease buildbots after r367940 A buildbot got angry about this new test, with error messages like: warn-nullchar-nullptr.c Line 16: use of undeclared identifier 'u' It looks like this `u'c'` syntax was introduced in C11; I'm guessing some bots may default to something before that. Let's see if explicitly specifying the standard version makes it happy... Modified: cfe/trunk/test/Sema/warn-nullchar-nullptr.c Modified: cfe/trunk/test/Sema/warn-nullchar-nullptr.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-nullchar-nullptr.c?rev=367947&r1=367946&r2=367947&view=diff == --- cfe/trunk/test/Sema/warn-nullchar-nullptr.c (original) +++ cfe/trunk/test/Sema/warn-nullchar-nullptr.c Mon Aug 5 16:19:15 2019 @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -fsyntax-only -verify -Wall %s +// RUN: %clang_cc1 -fsyntax-only -verify -Wall %s -std=c11 int test1(int *a) { return a == '\0'; // expected-warning {{comparing a pointer to a null character constant; did you mean to compare to (void *)0?}} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r364104 - clang-format a block; NFC
Author: gbiv Date: Fri Jun 21 13:49:47 2019 New Revision: 364104 URL: http://llvm.org/viewvc/llvm-project?rev=364104&view=rev Log: clang-format a block; NFC The indentation of the return here was off, and confusing as a result. Cleaned up a bit extra while I was in the area. Modified: cfe/trunk/lib/Sema/SemaExpr.cpp Modified: cfe/trunk/lib/Sema/SemaExpr.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=364104&r1=364103&r2=364104&view=diff == --- cfe/trunk/lib/Sema/SemaExpr.cpp (original) +++ cfe/trunk/lib/Sema/SemaExpr.cpp Fri Jun 21 13:49:47 2019 @@ -5794,28 +5794,29 @@ ExprResult Sema::BuildResolvedCallExpr(E // CheckBuiltinFunctionCall below just after creation of the call expression. const FunctionType *FuncT = nullptr; if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { - retry: + retry: if (const PointerType *PT = Fn->getType()->getAs()) { // C99 6.5.2.2p1 - "The expression that denotes the called function shall // have type pointer to function". FuncT = PT->getPointeeType()->getAs(); if (!FuncT) return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) - << Fn->getType() << Fn->getSourceRange()); + << Fn->getType() << Fn->getSourceRange()); } else if (const BlockPointerType *BPT = - Fn->getType()->getAs()) { + Fn->getType()->getAs()) { FuncT = BPT->getPointeeType()->castAs(); } else { // Handle calls to expressions of unknown-any type. if (Fn->getType() == Context.UnknownAnyTy) { ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); -if (rewrite.isInvalid()) return ExprError(); +if (rewrite.isInvalid()) + return ExprError(); Fn = rewrite.get(); goto retry; } -return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) - << Fn->getType() << Fn->getSourceRange()); + return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) + << Fn->getType() << Fn->getSourceRange()); } } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r361457 - Remove unnecessary const&s; NFC
Author: gbiv Date: Wed May 22 19:52:39 2019 New Revision: 361457 URL: http://llvm.org/viewvc/llvm-project?rev=361457&view=rev Log: Remove unnecessary const&s; NFC It's uncommon to rely on temporary lifetime extension when having a regular, non-`const&` value behaves identically. Since `Twine::str` and `buildFixMsgForStringFlag` both return regular `std::string`s, there's seemingly no point in having `const&` here. Modified: clang-tools-extra/trunk/clang-tidy/android/CloexecAcceptCheck.cpp clang-tools-extra/trunk/clang-tidy/android/CloexecCheck.cpp clang-tools-extra/trunk/clang-tidy/android/CloexecDupCheck.cpp Modified: clang-tools-extra/trunk/clang-tidy/android/CloexecAcceptCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecAcceptCheck.cpp?rev=361457&r1=361456&r2=361457&view=diff == --- clang-tools-extra/trunk/clang-tidy/android/CloexecAcceptCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/android/CloexecAcceptCheck.cpp Wed May 22 19:52:39 2019 @@ -29,7 +29,7 @@ void CloexecAcceptCheck::registerMatcher } void CloexecAcceptCheck::check(const MatchFinder::MatchResult &Result) { - const std::string &ReplacementText = + std::string ReplacementText = (Twine("accept4(") + getSpellingArg(Result, 0) + ", " + getSpellingArg(Result, 1) + ", " + getSpellingArg(Result, 2) + ", SOCK_CLOEXEC)") Modified: clang-tools-extra/trunk/clang-tidy/android/CloexecCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecCheck.cpp?rev=361457&r1=361456&r2=361457&view=diff == --- clang-tools-extra/trunk/clang-tidy/android/CloexecCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/android/CloexecCheck.cpp Wed May 22 19:52:39 2019 @@ -90,7 +90,7 @@ void CloexecCheck::insertStringFlag( if (!ModeStr || (ModeStr->getString().find(Mode) != StringRef::npos)) return; - const std::string &ReplacementText = buildFixMsgForStringFlag( + std::string ReplacementText = buildFixMsgForStringFlag( ModeArg, *Result.SourceManager, Result.Context->getLangOpts(), Mode); diag(ModeArg->getBeginLoc(), "use %0 mode '%1' to set O_CLOEXEC") Modified: clang-tools-extra/trunk/clang-tidy/android/CloexecDupCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecDupCheck.cpp?rev=361457&r1=361456&r2=361457&view=diff == --- clang-tools-extra/trunk/clang-tidy/android/CloexecDupCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/android/CloexecDupCheck.cpp Wed May 22 19:52:39 2019 @@ -23,7 +23,7 @@ void CloexecDupCheck::registerMatchers(M } void CloexecDupCheck::check(const MatchFinder::MatchResult &Result) { - const std::string &ReplacementText = + std::string ReplacementText = (Twine("fcntl(") + getSpellingArg(Result, 0) + ", F_DUPFD_CLOEXEC)") .str(); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r335927 - [Parse] Make -Wgcc-compat complain about for loop inits in C89
Author: gbiv Date: Thu Jun 28 14:36:00 2018 New Revision: 335927 URL: http://llvm.org/viewvc/llvm-project?rev=335927&view=rev Log: [Parse] Make -Wgcc-compat complain about for loop inits in C89 While clang allows declarations in for loop init statements in c89 and gnu89, gcc does not. So, we should probably warn if users care about gcc compatibility. Differential Revision: https://reviews.llvm.org/D47840 Added: cfe/trunk/test/Parser/gcc-for-loop-init-compatibility.c Modified: cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td cfe/trunk/lib/Parse/ParseStmt.cpp Modified: cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td?rev=335927&r1=335926&r2=335927&view=diff == --- cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td (original) +++ cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td Thu Jun 28 14:36:00 2018 @@ -173,6 +173,9 @@ def warn_attribute_on_function_definitio def warn_gcc_attribute_location : Warning< "GCC does not allow an attribute in this position on a function declaration">, InGroup; +def warn_gcc_variable_decl_in_for_loop : Warning< + "GCC does not allow variable declarations in for loop initializers before " + "C99">, InGroup; def warn_attribute_no_decl : Warning< "attribute %0 ignored, because it is not attached to a declaration">, InGroup; Modified: cfe/trunk/lib/Parse/ParseStmt.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseStmt.cpp?rev=335927&r1=335926&r2=335927&view=diff == --- cfe/trunk/lib/Parse/ParseStmt.cpp (original) +++ cfe/trunk/lib/Parse/ParseStmt.cpp Thu Jun 28 14:36:00 2018 @@ -1624,8 +1624,10 @@ StmtResult Parser::ParseForStatement(Sou ParenBraceBracketBalancer BalancerRAIIObj(*this); // Parse declaration, which eats the ';'. -if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode? +if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode? Diag(Tok, diag::ext_c99_variable_decl_in_for_loop); + Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop); +} // In C++0x, "for (T NS:a" might not be a typo for :: bool MightBeForRangeStmt = getLangOpts().CPlusPlus; Added: cfe/trunk/test/Parser/gcc-for-loop-init-compatibility.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/gcc-for-loop-init-compatibility.c?rev=335927&view=auto == --- cfe/trunk/test/Parser/gcc-for-loop-init-compatibility.c (added) +++ cfe/trunk/test/Parser/gcc-for-loop-init-compatibility.c Thu Jun 28 14:36:00 2018 @@ -0,0 +1,15 @@ +// RUN: %clang_cc1 -std=c89 -fsyntax-only -verify %s +// RUN: %clang_cc1 -std=gnu89 -fsyntax-only -verify %s +// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify %s -DC99 + +#ifdef C99 +// expected-no-diagnostics +#endif + +void foo() { +#ifndef C99 + // expected-warning@+2{{GCC does not allow variable declarations in for loop initializers before C99}} +#endif + for (int i = 0; i < 10; i++) +; +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 91c8c74 - [CodeGen] clarify a comment; NFC
Author: George Burgess IV Date: 2020-04-14T14:33:01-07:00 New Revision: 91c8c74180ced4b82da02f2544f3978f72003d37 URL: https://github.com/llvm/llvm-project/commit/91c8c74180ced4b82da02f2544f3978f72003d37 DIFF: https://github.com/llvm/llvm-project/commit/91c8c74180ced4b82da02f2544f3978f72003d37.diff LOG: [CodeGen] clarify a comment; NFC Prompted by discussion on https://reviews.llvm.org/D78148. Added: Modified: clang/lib/CodeGen/CodeGenModule.cpp Removed: diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 0f56dcb3e26c..39aa5c1c512f 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -2796,8 +2796,8 @@ bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { // PR9614. Avoid cases where the source code is lying to us. An available // externally function should have an equivalent function somewhere else, - // but a function that calls itself is clearly not equivalent to the real - // implementation. + // but a function that calls itself through asm label/`__builtin_` trickery is + // clearly not equivalent to the real implementation. // This happens in glibc's btowc and in some configure checks. return !isTriviallyRecursive(F); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 2dd17ff - [CodeGen] only add nobuiltin to inline builtins if we'll emit them
Author: George Burgess IV Date: 2020-04-15T11:05:22-07:00 New Revision: 2dd17ff08165e6118e70f00e22b2c36d2d4e0a9a URL: https://github.com/llvm/llvm-project/commit/2dd17ff08165e6118e70f00e22b2c36d2d4e0a9a DIFF: https://github.com/llvm/llvm-project/commit/2dd17ff08165e6118e70f00e22b2c36d2d4e0a9a.diff LOG: [CodeGen] only add nobuiltin to inline builtins if we'll emit them There are some inline builtin definitions that we can't emit (isTriviallyRecursive & callers go into why). Marking these nobuiltin is only useful if we actually emit the body, so don't mark these as such unless we _do_ plan on emitting that. This suboptimality was encountered in Linux (see some discussion on D71082, and https://github.com/ClangBuiltLinux/linux/issues/979). Differential Revision: https://reviews.llvm.org/D78162 Added: clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.c Modified: clang/lib/CodeGen/CodeGenModule.cpp Removed: diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 39aa5c1c512f..73a3212bcd47 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -1908,7 +1908,8 @@ void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, else if (const auto *SA = FD->getAttr()) F->setSection(SA->getName()); - if (FD->isInlineBuiltinDeclaration()) { + // If we plan on emitting this inline builtin, we can't treat it as a builtin. + if (FD->isInlineBuiltinDeclaration() && shouldEmitFunction(FD)) { F->addAttribute(llvm::AttributeList::FunctionIndex, llvm::Attribute::NoBuiltin); } diff --git a/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.c b/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.c new file mode 100644 index ..b4c1376c5bb3 --- /dev/null +++ b/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.c @@ -0,0 +1,25 @@ +// RUN: %clang_cc1 -triple x86_64-unknown-unknown -S -emit-llvm -o - %s | FileCheck %s +// +// Verifies that clang doesn't mark an inline builtin definition as `nobuiltin` +// if the builtin isn't emittable. + +typedef unsigned long size_t; + +// always_inline is used so clang will emit this body. Otherwise, we need >= +// -O1. +#define AVAILABLE_EXTERNALLY extern inline __attribute__((always_inline)) \ +__attribute__((gnu_inline)) + +AVAILABLE_EXTERNALLY void *memcpy(void *a, const void *b, size_t c) { + return __builtin_memcpy(a, b, c); +} + +// CHECK-LABEL: define void @foo +void foo(void *a, const void *b, size_t c) { + // Clang will always _emit_ this as memcpy. LLVM turns it into @llvm.memcpy + // later on if optimizations are enabled. + // CHECK: call i8* @memcpy + memcpy(a, b, c); +} + +// CHECK-NOT: nobuiltin ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 9490808 - [CodeGen] fix inline builtin-related breakage from D78162
Author: George Burgess IV Date: 2020-04-16T11:54:10-07:00 New Revision: 94908088a831141cfbdd15fc5837dccf30cfeeb6 URL: https://github.com/llvm/llvm-project/commit/94908088a831141cfbdd15fc5837dccf30cfeeb6 DIFF: https://github.com/llvm/llvm-project/commit/94908088a831141cfbdd15fc5837dccf30cfeeb6.diff LOG: [CodeGen] fix inline builtin-related breakage from D78162 In cases where we have multiple decls of an inline builtin, we may need to go hunting for the one with a definition when setting function attributes. An additional test-case was provided on https://github.com/ClangBuiltLinux/linux/issues/979 Added: clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.cpp Modified: clang/lib/CodeGen/CodeGenModule.cpp Removed: diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 1243ce50ec8d..ce28d741225e 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -1909,9 +1909,15 @@ void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, F->setSection(SA->getName()); // If we plan on emitting this inline builtin, we can't treat it as a builtin. - if (FD->isInlineBuiltinDeclaration() && shouldEmitFunction(FD)) { -F->addAttribute(llvm::AttributeList::FunctionIndex, -llvm::Attribute::NoBuiltin); + if (FD->isInlineBuiltinDeclaration()) { +const FunctionDecl *FDBody; +bool HasBody = FD->hasBody(FDBody); +(void)HasBody; +assert(HasBody && "Inline builtin declarations should always have an " + "available body!"); +if (shouldEmitFunction(FDBody)) + F->addAttribute(llvm::AttributeList::FunctionIndex, + llvm::Attribute::NoBuiltin); } if (FD->isReplaceableGlobalAllocationFunction()) { diff --git a/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.cpp b/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.cpp new file mode 100644 index ..d27aa9c53413 --- /dev/null +++ b/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.cpp @@ -0,0 +1,16 @@ +// RUN: %clang_cc1 -triple i686-linux-gnu -std=c++11 -S -emit-llvm -o - %s | FileCheck %s +// +// Regression test for the issue reported at +// https://reviews.llvm.org/D78162#1986104 + +typedef unsigned long size_t; + +extern "C" __inline__ __attribute__((__gnu_inline__)) void *memcpy(void *a, const void *b, unsigned c) { + return __builtin_memcpy(a, b, c); +} +void *memcpy(void *, const void *, unsigned); + +// CHECK-LABEL: define void @_Z1av +void a() { (void)memcpy; } + +// CHECK-NOT: nobuiltin ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r281277 - [Sema] Fix PR30346: relax __builtin_object_size checks.
WFM; I'll put together a patch that only allows this under -fno-strict-aliasing. I'm entirely unfamiliar with struct-path-tbaa, so Hal, do you see a reason why struct-path-tbaa wouldn't play nicely with flexible arrays at the end of types? Glancing at it, I don't think it should cause problems, but a more authoritative answer would really be appreciated. :) If it might cause issues now or in the future, I'm happy to be conservative here if -fno-strict-path-tbaa is given, too. On Tue, Sep 13, 2016 at 2:00 PM, Joerg Sonnenberger via cfe-commits < cfe-commits@lists.llvm.org> wrote: > On Tue, Sep 13, 2016 at 12:51:52PM -0700, Richard Smith wrote: > > On Tue, Sep 13, 2016 at 10:44 AM, Joerg Sonnenberger via cfe-commits < > > cfe-commits@lists.llvm.org> wrote: > > > > > IMO this should be restricted to code that explicitly disables C/C++ > > > aliasing rules. > > > > > > Do you mean -fno-strict-aliasing or -fno-struct-path-tbaa or something > else > > here? (I think we're not doing anyone any favours by making > _FORTIFY_SOURCE > > say that a pattern is OK in cases when LLVM will in fact optimize on the > > assumption that it's UB, but I don't recall how aggressive > > -fstruct-path-tbaa is for trailing array members.) > > The former immediately, the latter potentially as well. I can't think of > many use cases for this kind of idiom that don't involve type prunning > and socket code is notoriously bad in that regard by necessity. > > Joerg > ___ > cfe-commits mailing list > cfe-commits@lists.llvm.org > http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r281277 - [Sema] Fix PR30346: relax __builtin_object_size checks.
Noted; thanks for the correction. :) On Tue, Sep 20, 2016 at 3:04 AM, Joerg Sonnenberger via cfe-commits < cfe-commits@lists.llvm.org> wrote: > On Mon, Sep 19, 2016 at 09:21:33PM -0700, George Burgess IV wrote: > > I'm entirely unfamiliar with struct-path-tbaa, so Hal, do you see a > reason > > why struct-path-tbaa wouldn't play nicely with flexible arrays at the end > > of types? Glancing at it, I don't think it should cause problems, but a > > more authoritative answer would really be appreciated. :) If it might > cause > > issues now or in the future, I'm happy to be conservative here if > > -fno-strict-path-tbaa is given, too. > > Please don't call them flexible types. That's a misname. The standard > provides a clear mechanism for arrays with statically undefined size -- > which is providing no size at all. We do provide the same support for > array size of 1 for legacy compat. Any other size is basically abuse. > > Joerg > ___ > cfe-commits mailing list > cfe-commits@lists.llvm.org > http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r282124 - [Sema] Fix PR30481: crash on checking printf args.
Author: gbiv Date: Wed Sep 21 19:00:26 2016 New Revision: 282124 URL: http://llvm.org/viewvc/llvm-project?rev=282124&view=rev Log: [Sema] Fix PR30481: crash on checking printf args. We were falling through from one case to another in a switch statement. Oops. Modified: cfe/trunk/lib/Sema/SemaChecking.cpp cfe/trunk/test/Sema/format-strings.c Modified: cfe/trunk/lib/Sema/SemaChecking.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=282124&r1=282123&r2=282124&view=diff == --- cfe/trunk/lib/Sema/SemaChecking.cpp (original) +++ cfe/trunk/lib/Sema/SemaChecking.cpp Wed Sep 21 19:00:26 2016 @@ -4194,9 +4194,9 @@ checkFormatStringExpr(Sema &S, const Exp goto tryAgain; } } - - return SLCT_NotALiteral; } + +return SLCT_NotALiteral; } case Stmt::UnaryOperatorClass: { const UnaryOperator *UnaOp = cast(E); Modified: cfe/trunk/test/Sema/format-strings.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/format-strings.c?rev=282124&r1=282123&r2=282124&view=diff == --- cfe/trunk/test/Sema/format-strings.c (original) +++ cfe/trunk/test/Sema/format-strings.c Wed Sep 21 19:00:26 2016 @@ -687,3 +687,8 @@ void test_char_pointer_arithmetic(int b) printf(s7 + 3, ""); // expected-warning{{more '%' conversions than data arguments}} // expected-note@-2{{format string is defined here}} } + +void PR30481() { + // This caused crashes due to invalid casts. + printf(1 > 0); // expected-warning{{format string is not a string literal}} expected-warning{{incompatible integer to pointer conversion}} expected-note@format-strings.c:*{{passing argument to parameter here}} expected-note{{to avoid this}} +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D24999: [Sema] Only relax array-at-end-of-object checks in __builtin_object_size when -fno-strict-aliasing is given.
george.burgess.iv created this revision. george.burgess.iv added reviewers: joerg, rsmith. george.burgess.iv added a subscriber: cfe-commits. Mostly asking for a review to verify that you guys are happy with this approach. Given that Hal said struct-path-tbaa doesn't really deal with arrays (yet), I decided to ignore -fno-struct-path-tbaa. If that changes in the future, we can relax this when that flag is given, too. https://reviews.llvm.org/D24999 Files: include/clang/Basic/LangOptions.def lib/AST/ExprConstant.cpp lib/Frontend/CompilerInvocation.cpp test/CodeGen/object-size.c test/CodeGen/pass-object-size.c Index: test/CodeGen/pass-object-size.c === --- test/CodeGen/pass-object-size.c +++ test/CodeGen/pass-object-size.c @@ -1,4 +1,5 @@ -// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -O0 %s -o - 2>&1 | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -O0 %s -o - 2>&1 | FileCheck %s --check-prefixes STRICT,CHECK +// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -O0 %s -o - -relaxed-aliasing 2>&1 | FileCheck %s --check-prefixes NOSTRICT,CHECK typedef unsigned long size_t; @@ -59,8 +60,10 @@ // CHECK-LABEL: define void @test2 void test2(struct Foo *t) { - // CHECK: [[VAR:%[0-9]+]] = call i64 @llvm.objectsize - // CHECK: call i32 @ObjectSize1(i8* %{{.*}}, i64 [[VAR]]) + // NOSTRICT: [[VAR:%[0-9]+]] = call i64 @llvm.objectsize + // NOSTRICT: call i32 @ObjectSize1(i8* %{{.*}}, i64 [[VAR]]) + // + // STRICT: call i32 @ObjectSize1(i8* %{{.*}}, i64 36) gi = ObjectSize1(&t->t[1]); // CHECK: call i32 @ObjectSize3(i8* %{{.*}}, i64 36) gi = ObjectSize3(&t->t[1]); @@ -169,8 +172,10 @@ // CHECK: call i32 @_Z27NoViableOverloadObjectSize0PvU17pass_object_size0(i8* %{{.*}}, i64 %{{.*}}) gi = NoViableOverloadObjectSize0(&t[1].t[1]); - // CHECK: [[VAR:%[0-9]+]] = call i64 @llvm.objectsize - // CHECK: call i32 @_Z27NoViableOverloadObjectSize1PvU17pass_object_size1(i8* %{{.*}}, i64 [[VAR]]) + // NOSTRICT: [[VAR:%[0-9]+]] = call i64 @llvm.objectsize + // NOSTRICT: call i32 @_Z27NoViableOverloadObjectSize1PvU17pass_object_size1(i8* %{{.*}}, i64 [[VAR]]) + // + // STRICT: call i32 @_Z27NoViableOverloadObjectSize1PvU17pass_object_size1(i8* %{{.*}}, i64 36) gi = NoViableOverloadObjectSize1(&t[1].t[1]); // CHECK: call i32 @_Z27NoViableOverloadObjectSize2PvU17pass_object_size2(i8* %{{.*}}, i64 %{{.*}}) gi = NoViableOverloadObjectSize2(&t[1].t[1]); @@ -276,8 +281,10 @@ // CHECK-LABEL: define void @test8 void test8(struct Foo *t) { - // CHECK: [[VAR:%[0-9]+]] = call i64 @llvm.objectsize - // CHECK: call i32 @"\01Identity"(i8* %{{.*}}, i64 [[VAR]]) + // NOSTRICT: [[VAR:%[0-9]+]] = call i64 @llvm.objectsize + // NOSTRICT: call i32 @"\01Identity"(i8* %{{.*}}, i64 [[VAR]]) + // + // STRICT: call i32 @"\01Identity"(i8* %{{.*}}, i64 36) gi = AsmObjectSize1(&t[1].t[1]); // CHECK: call i32 @"\01Identity"(i8* %{{.*}}, i64 36) gi = AsmObjectSize3(&t[1].t[1]); Index: test/CodeGen/object-size.c === --- test/CodeGen/object-size.c +++ test/CodeGen/object-size.c @@ -1,4 +1,5 @@ -// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - 2>&1 | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefixes=STRICT,CHECK +// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - 2>&1 -relaxed-aliasing | FileCheck %s --check-prefixes=NOSTRICT,CHECK #define strcpy(dest, src) \ ((__builtin_object_size(dest, 0) != -1ULL) \ @@ -276,7 +277,8 @@ // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false) gi = __builtin_object_size(&p->t[5], 0); - // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false) + // NOSTRICT: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false) + // STRICT: store i32 20 gi = __builtin_object_size(&p->t[5], 1); // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 true) gi = __builtin_object_size(&p->t[5], 2); @@ -444,7 +446,8 @@ // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false) gi = __builtin_object_size(ss->snd, 0); - // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false) + // NOSTRICT: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false) + // STRICT: store i32 2 gi = __builtin_object_size(ss->snd, 1); // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 true) gi = __builtin_object_size(ss->snd, 2); @@ -505,7 +508,8 @@ // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false) gi = __builtin_object_size(ds1[9].snd, 1); - // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false) + // NOSTRICT: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false) + // STRICT: store i32 2 gi = __builtin_object_size(&ss[9].snd[0], 1); // CHECK: call i64 @llvm.objectsize.i64.p0i8
[clang] e12e02d - [clang] Evaluate strlen of strcpy argument for -Wfortify-source.
Author: Michael Benfield Date: 2021-07-28T20:52:57Z New Revision: e12e02df09a967f644cf28136a7361bce7a5bb91 URL: https://github.com/llvm/llvm-project/commit/e12e02df09a967f644cf28136a7361bce7a5bb91 DIFF: https://github.com/llvm/llvm-project/commit/e12e02df09a967f644cf28136a7361bce7a5bb91.diff LOG: [clang] Evaluate strlen of strcpy argument for -Wfortify-source. Also introduce Expr::tryEvaluateStrLen. Differential Revision: https://reviews.llvm.org/D104887 Added: Modified: clang/include/clang/AST/Expr.h clang/include/clang/Basic/DiagnosticSemaKinds.td clang/lib/AST/ExprConstant.cpp clang/lib/Sema/SemaChecking.cpp clang/test/Analysis/security-syntax-checks.m clang/test/Sema/warn-fortify-source.c Removed: diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h index 06164411cc2d4..991abef733637 100644 --- a/clang/include/clang/AST/Expr.h +++ b/clang/include/clang/AST/Expr.h @@ -740,6 +740,12 @@ class Expr : public ValueStmt { bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const; + /// If the current Expr is a pointer, this will try to statically + /// determine the strlen of the string pointed to. + /// Returns true if all of the above holds and we were able to figure out the + /// strlen, false otherwise. + bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const; + /// Enumeration used to describe the kind of Null pointer constant /// returned from \c isNullPointerConstant(). enum NullPointerConstantKind { diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 00b443b45f132..a777f08de8909 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -816,6 +816,11 @@ def warn_fortify_source_size_mismatch : Warning< "'%0' size argument is too large; destination buffer has size %1," " but size argument is %2">, InGroup; +def warn_fortify_strlen_overflow: Warning< + "'%0' will always overflow; destination buffer has size %1," + " but the source string has length %2 (including NUL byte)">, + InGroup; + def warn_fortify_source_format_overflow : Warning< "'%0' will always overflow; destination buffer has size %1," " but format string expands to at least %2">, diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 01c0168d61a40..f49a144879b3e 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -1826,6 +1826,8 @@ static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info); static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); +static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, + EvalInfo &Info); /// Evaluate an integer or fixed point expression into an APResult. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, @@ -11836,46 +11838,10 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, case Builtin::BI__builtin_wcslen: { // As an extension, we support __builtin_strlen() as a constant expression, // and support folding strlen() to a constant. -LValue String; -if (!EvaluatePointer(E->getArg(0), String, Info)) - return false; - -QualType CharTy = E->getArg(0)->getType()->getPointeeType(); - -// Fast path: if it's a string literal, search the string value. -if (const StringLiteral *S = dyn_cast_or_null( -String.getLValueBase().dyn_cast())) { - // The string literal may have embedded null characters. Find the first - // one and truncate there. - StringRef Str = S->getBytes(); - int64_t Off = String.Offset.getQuantity(); - if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && - S->getCharByteWidth() == 1 && - // FIXME: Add fast-path for wchar_t too. - Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { -Str = Str.substr(Off); - -StringRef::size_type Pos = Str.find(0); -if (Pos != StringRef::npos) - Str = Str.substr(0, Pos); - -return Success(Str.size(), E); - } - - // Fall through to slow path to issue appropriate diagnostic. -} - -// Slow path: scan the bytes of the string looking for the terminating 0. -for (uint64_t Strlen = 0; /**/; ++Strlen) { - APValue Char; - if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || - !Char.isInt()) -return false; - if (!Char.getInt()) -return Success(Strlen, E); - if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) -return false; -} +
r310299 - Mark static variables static; NFC.
Author: gbiv Date: Mon Aug 7 13:26:33 2017 New Revision: 310299 URL: http://llvm.org/viewvc/llvm-project?rev=310299&view=rev Log: Mark static variables static; NFC. Modified: cfe/trunk/lib/AST/Decl.cpp Modified: cfe/trunk/lib/AST/Decl.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310299&r1=310298&r2=310299&view=diff == --- cfe/trunk/lib/AST/Decl.cpp (original) +++ cfe/trunk/lib/AST/Decl.cpp Mon Aug 7 13:26:33 2017 @@ -99,8 +99,8 @@ TranslationUnitDecl::TranslationUnitDecl // and 'matcher' is a type only matters when looking for attributes // and settings from the immediate context. -const unsigned IgnoreExplicitVisibilityBit = 2; -const unsigned IgnoreAllVisibilityBit = 4; +const static unsigned IgnoreExplicitVisibilityBit = 2; +const static unsigned IgnoreAllVisibilityBit = 4; /// Kinds of LV computation. The linkage side of the computation is /// always the same, but different things can change how visibility is ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r310436 - [AST] Move visibility computations into a class; NFC
Author: gbiv Date: Tue Aug 8 21:02:49 2017 New Revision: 310436 URL: http://llvm.org/viewvc/llvm-project?rev=310436&view=rev Log: [AST] Move visibility computations into a class; NFC This is patch 1 in a 2 patch series that aims to fix PR29160. Its goal is to cache decl visibility/linkage for the duration of each visibility+linkage query. The simplest way I can see to do this is to put the visibility calculation code that needs to (transitively) access this cache into a class, which is what this patch does. Actual caching will come in patch 2. (Another way would be to keep the cache in ASTContext + manually invalidate it or something, but that felt way too subtle to me.) Caching visibility results across multiple queries seems a bit tricky, since the user can add visibility attributes ~whenever they want, and these attributes can apparently have far-reaching effects (e.g. class visibility extends to its members, ...). Because a cache that's dropped at the end of each top-level query seems to work nearly as well and doesn't require any eviction logic, I opted for that design. Added: cfe/trunk/lib/AST/Linkage.h Modified: cfe/trunk/lib/AST/Decl.cpp cfe/trunk/lib/AST/Type.cpp Modified: cfe/trunk/lib/AST/Decl.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310436&r1=310435&r2=310436&view=diff == --- cfe/trunk/lib/AST/Decl.cpp (original) +++ cfe/trunk/lib/AST/Decl.cpp Tue Aug 8 21:02:49 2017 @@ -12,6 +12,7 @@ //===--===// #include "clang/AST/Decl.h" +#include "Linkage.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTLambda.h" #include "clang/AST/ASTMutationListener.h" @@ -99,38 +100,6 @@ TranslationUnitDecl::TranslationUnitDecl // and 'matcher' is a type only matters when looking for attributes // and settings from the immediate context. -const static unsigned IgnoreExplicitVisibilityBit = 2; -const static unsigned IgnoreAllVisibilityBit = 4; - -/// Kinds of LV computation. The linkage side of the computation is -/// always the same, but different things can change how visibility is -/// computed. -enum LVComputationKind { - /// Do an LV computation for, ultimately, a type. - /// Visibility may be restricted by type visibility settings and - /// the visibility of template arguments. - LVForType = NamedDecl::VisibilityForType, - - /// Do an LV computation for, ultimately, a non-type declaration. - /// Visibility may be restricted by value visibility settings and - /// the visibility of template arguments. - LVForValue = NamedDecl::VisibilityForValue, - - /// Do an LV computation for, ultimately, a type that already has - /// some sort of explicit visibility. Visibility may only be - /// restricted by the visibility of template arguments. - LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit), - - /// Do an LV computation for, ultimately, a non-type declaration - /// that already has some sort of explicit visibility. Visibility - /// may only be restricted by the visibility of template arguments. - LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit), - - /// Do an LV computation when we only care about the linkage. - LVForLinkageOnly = - LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit -}; - /// Does this computation kind permit us to consider additional /// visibility settings from attributes and the like? static bool hasExplicitVisibilityAlready(LVComputationKind computation) { @@ -219,8 +188,8 @@ static Optional getVisibilit return None; } -static LinkageInfo -getLVForType(const Type &T, LVComputationKind computation) { +LinkageInfo LinkageComputer::getLVForType(const Type &T, + LVComputationKind computation) { if (computation == LVForLinkageOnly) return LinkageInfo(T.getLinkage(), DefaultVisibility, true); return T.getLinkageAndVisibility(); @@ -229,9 +198,8 @@ getLVForType(const Type &T, LVComputatio /// \brief Get the most restrictive linkage for the types in the given /// template parameter list. For visibility purposes, template /// parameters are part of the signature of a template. -static LinkageInfo -getLVForTemplateParameterList(const TemplateParameterList *Params, - LVComputationKind computation) { +LinkageInfo LinkageComputer::getLVForTemplateParameterList( +const TemplateParameterList *Params, LVComputationKind computation) { LinkageInfo LV; for (const NamedDecl *P : *Params) { // Template type parameters are the most common and never @@ -283,10 +251,6 @@ getLVForTemplateParameterList(const Temp return LV; } -/// getLVForDecl - Get the linkage and visibility for the given declaration. -static LinkageInfo getLVForDecl(const NamedDecl *D, -LVComputationKind computation); - static
r310437 - [AST] Cache intermediate visibility/linkage results
Author: gbiv Date: Tue Aug 8 21:12:17 2017 New Revision: 310437 URL: http://llvm.org/viewvc/llvm-project?rev=310437&view=rev Log: [AST] Cache intermediate visibility/linkage results This is a follow-up to r310436 with actual functional changes. Please see that commit message for a description of why a cache is appearing here. Suggestions for less-bad ways of testing this are appreciated. :) This fixes PR29160. Added: cfe/trunk/test/CodeGenCXX/pr29160.cpp Modified: cfe/trunk/lib/AST/Decl.cpp cfe/trunk/lib/AST/Linkage.h cfe/trunk/lib/AST/Type.cpp Modified: cfe/trunk/lib/AST/Decl.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310437&r1=310436&r2=310437&view=diff == --- cfe/trunk/lib/AST/Decl.cpp (original) +++ cfe/trunk/lib/AST/Decl.cpp Tue Aug 8 21:12:17 2017 @@ -192,7 +192,7 @@ LinkageInfo LinkageComputer::getLVForTyp LVComputationKind computation) { if (computation == LVForLinkageOnly) return LinkageInfo(T.getLinkage(), DefaultVisibility, true); - return T.getLinkageAndVisibility(); + return getTypeLinkageAndVisibility(&T); } /// \brief Get the most restrictive linkage for the types in the given @@ -224,7 +224,7 @@ LinkageInfo LinkageComputer::getLVForTem for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) { QualType type = NTTP->getExpansionType(i); if (!type->isDependentType()) - LV.merge(type->getLinkageAndVisibility()); + LV.merge(getTypeLinkageAndVisibility(type)); } continue; } @@ -291,7 +291,7 @@ LinkageComputer::getLVForTemplateArgumen continue; case TemplateArgument::NullPtr: - LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility()); + LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType())); continue; case TemplateArgument::Template: @@ -610,7 +610,7 @@ LinkageComputer::getLVForNamespaceScopeD PrevVar = PrevVar->getPreviousDecl()) { if (PrevVar->getStorageClass() == SC_PrivateExtern && Var->getStorageClass() == SC_None) -return PrevVar->getLinkageAndVisibility(); +return getDeclLinkageAndVisibility(PrevVar); // Explicitly declared static. if (PrevVar->getStorageClass() == SC_Static) return getInternalLinkageFor(Var); @@ -1358,11 +1358,15 @@ LinkageInfo LinkageComputer::getLVForDec if (computation == LVForLinkageOnly && D->hasCachedLinkage()) return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false); + if (llvm::Optional LI = lookup(D, computation)) +return *LI; + LinkageInfo LV = computeLVForDecl(D, computation); if (D->hasCachedLinkage()) assert(D->getCachedLinkage() == LV.getLinkage()); D->setCachedLinkage(LV.getLinkage()); + cache(D, computation, LV); #ifndef NDEBUG // In C (because of gnu inline) and in c++ with microsoft extensions an Modified: cfe/trunk/lib/AST/Linkage.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Linkage.h?rev=310437&r1=310436&r2=310437&view=diff == --- cfe/trunk/lib/AST/Linkage.h (original) +++ cfe/trunk/lib/AST/Linkage.h Tue Aug 8 21:12:17 2017 @@ -19,6 +19,7 @@ #include "clang/AST/DeclCXX.h" #include "clang/AST/Type.h" #include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/Optional.h" namespace clang { enum : unsigned { @@ -54,8 +55,50 @@ enum LVComputationKind { LVForLinkageOnly = LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit }; +} // namespace clang +namespace llvm { +template <> struct DenseMapInfo { + static inline clang::LVComputationKind getEmptyKey() { +return static_cast(-1); + } + static inline clang::LVComputationKind getTombstoneKey() { +return static_cast(-2); + } + static unsigned getHashValue(const clang::LVComputationKind &Val) { +return Val; + } + static bool isEqual(const clang::LVComputationKind &LHS, + const clang::LVComputationKind &RHS) { +return LHS == RHS; + } +}; +} // namespace llvm + +namespace clang { class LinkageComputer { + // We have a cache for repeated linkage/visibility computations. This saves us + // from exponential behavior in heavily templated code, such as: + // + // template struct {}; + // using A = int; + // using B = Foo; + // using C = Foo; + // using D = Foo; + using QueryType = std::pair; + llvm::SmallDenseMap CachedLinkageInfo; + llvm::Optional lookup(const NamedDecl *ND, + LVComputationKind Kind) const { +auto Iter = CachedLinkageInfo.find(std::make_pair(ND, Kind)); +if (Iter == CachedLinkageInfo.end()) + return None; +return Iter->second; + } + + void cache(const NamedDecl *ND, LVComputationKind Kind, LinkageInfo Info) { +CachedLinkageInfo[std::make_pair(ND, Kind
r310444 - Attempt to appease msc buildbot
Author: gbiv Date: Tue Aug 8 22:20:05 2017 New Revision: 310444 URL: http://llvm.org/viewvc/llvm-project?rev=310444&view=rev Log: Attempt to appease msc buildbot It was timing out on this test, but for reasons unrelated to the specific bug it was testing for. Randomly breaking in gdb with `clang -target i686-windows -fmsc-version=1700` reveals *many* frames from MicrosoftCXXNameMangler. So, it would seem that some caching is needed there, as well... Fingers crossed that specifying a triple is sufficient to work around this. Modified: cfe/trunk/test/CodeGenCXX/pr29160.cpp Modified: cfe/trunk/test/CodeGenCXX/pr29160.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/pr29160.cpp?rev=310444&r1=310443&r2=310444&view=diff == --- cfe/trunk/test/CodeGenCXX/pr29160.cpp (original) +++ cfe/trunk/test/CodeGenCXX/pr29160.cpp Tue Aug 8 22:20:05 2017 @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -std=c++11 %s -o /dev/null -S +// RUN: %clang_cc1 -std=c++11 -triple i686-linux %s -o /dev/null -S // // This test's failure mode is running ~forever. (For some value of "forever" // that's greater than 25 minutes on my machine) ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r310445 - Attempt #2 to appease buildbots
Author: gbiv Date: Tue Aug 8 23:07:08 2017 New Revision: 310445 URL: http://llvm.org/viewvc/llvm-project?rev=310445&view=rev Log: Attempt #2 to appease buildbots "error: unable to create target: 'No available targets are compatible with this triple.'" Modified: cfe/trunk/test/CodeGenCXX/pr29160.cpp Modified: cfe/trunk/test/CodeGenCXX/pr29160.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/pr29160.cpp?rev=310445&r1=310444&r2=310445&view=diff == --- cfe/trunk/test/CodeGenCXX/pr29160.cpp (original) +++ cfe/trunk/test/CodeGenCXX/pr29160.cpp Tue Aug 8 23:07:08 2017 @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -std=c++11 -triple i686-linux %s -o /dev/null -S +// RUN: %clang_cc1 -std=c++11 -triple i686-linux-gnu %s -o /dev/null -S -emit-llvm // // This test's failure mode is running ~forever. (For some value of "forever" // that's greater than 25 minutes on my machine) ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r310523 - Use unsigned instead of an enum for map keys
Author: gbiv Date: Wed Aug 9 14:20:41 2017 New Revision: 310523 URL: http://llvm.org/viewvc/llvm-project?rev=310523&view=rev Log: Use unsigned instead of an enum for map keys ubsan's enum sanitizer doesn't like the latter, and we had to have out-of-bounds values for DenseMapInfo's tombstone/empty keys. Modified: cfe/trunk/lib/AST/Linkage.h Modified: cfe/trunk/lib/AST/Linkage.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Linkage.h?rev=310523&r1=310522&r2=310523&view=diff == --- cfe/trunk/lib/AST/Linkage.h (original) +++ cfe/trunk/lib/AST/Linkage.h Wed Aug 9 14:20:41 2017 @@ -55,27 +55,7 @@ enum LVComputationKind { LVForLinkageOnly = LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit }; -} // namespace clang -namespace llvm { -template <> struct DenseMapInfo { - static inline clang::LVComputationKind getEmptyKey() { -return static_cast(-1); - } - static inline clang::LVComputationKind getTombstoneKey() { -return static_cast(-2); - } - static unsigned getHashValue(const clang::LVComputationKind &Val) { -return Val; - } - static bool isEqual(const clang::LVComputationKind &LHS, - const clang::LVComputationKind &RHS) { -return LHS == RHS; - } -}; -} // namespace llvm - -namespace clang { class LinkageComputer { // We have a cache for repeated linkage/visibility computations. This saves us // from exponential behavior in heavily templated code, such as: @@ -85,18 +65,27 @@ class LinkageComputer { // using B = Foo; // using C = Foo; // using D = Foo; - using QueryType = std::pair; + // + // Note that the unsigned is actually a LVComputationKind; ubsan's enum + // sanitizer doesn't like tombstone/empty markers outside of + // LVComputationKind's range. + using QueryType = std::pair; llvm::SmallDenseMap CachedLinkageInfo; + + static QueryType makeCacheKey(const NamedDecl *ND, LVComputationKind Kind) { +return std::make_pair(ND, static_cast(Kind)); + } + llvm::Optional lookup(const NamedDecl *ND, LVComputationKind Kind) const { -auto Iter = CachedLinkageInfo.find(std::make_pair(ND, Kind)); +auto Iter = CachedLinkageInfo.find(makeCacheKey(ND, Kind)); if (Iter == CachedLinkageInfo.end()) return None; return Iter->second; } void cache(const NamedDecl *ND, LVComputationKind Kind, LinkageInfo Info) { -CachedLinkageInfo[std::make_pair(ND, Kind)] = Info; +CachedLinkageInfo[makeCacheKey(ND, Kind)] = Info; } LinkageInfo getLVForTemplateArgumentList(ArrayRef Args, ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r310436 - [AST] Move visibility computations into a class; NFC
Sorry about that! Attempted fix is r310523. I'll keep an eye on the bot to make sure it turns green. On Wed, Aug 9, 2017 at 1:23 PM, Juergen Ributzka wrote: > This seems to cause UBSAN issues: > > runtime error: load of value 4294967295, which is not a valid value for type > 'clang::LVComputationKind' > > See ASAN+UBSAN bot on Green Dragon: > http://lab.llvm.org:8080/green/job/clang-stage2-cmake-RgSan_check/4065/console > > On Tue, Aug 8, 2017 at 9:02 PM, George Burgess IV via cfe-commits > wrote: >> >> Author: gbiv >> Date: Tue Aug 8 21:02:49 2017 >> New Revision: 310436 >> >> URL: http://llvm.org/viewvc/llvm-project?rev=310436&view=rev >> Log: >> [AST] Move visibility computations into a class; NFC >> >> This is patch 1 in a 2 patch series that aims to fix PR29160. Its goal >> is to cache decl visibility/linkage for the duration of each >> visibility+linkage query. >> >> The simplest way I can see to do this is to put the visibility >> calculation code that needs to (transitively) access this cache into a >> class, which is what this patch does. Actual caching will come in patch >> 2. (Another way would be to keep the cache in ASTContext + manually >> invalidate it or something, but that felt way too subtle to me.) >> >> Caching visibility results across multiple queries seems a bit tricky, >> since the user can add visibility attributes ~whenever they want, and >> these attributes can apparently have far-reaching effects (e.g. class >> visibility extends to its members, ...). Because a cache that's dropped >> at the end of each top-level query seems to work nearly as well and >> doesn't require any eviction logic, I opted for that design. >> >> Added: >> cfe/trunk/lib/AST/Linkage.h >> Modified: >> cfe/trunk/lib/AST/Decl.cpp >> cfe/trunk/lib/AST/Type.cpp >> >> Modified: cfe/trunk/lib/AST/Decl.cpp >> URL: >> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310436&r1=310435&r2=310436&view=diff >> >> == >> --- cfe/trunk/lib/AST/Decl.cpp (original) >> +++ cfe/trunk/lib/AST/Decl.cpp Tue Aug 8 21:02:49 2017 >> @@ -12,6 +12,7 @@ >> >> //===--===// >> >> #include "clang/AST/Decl.h" >> +#include "Linkage.h" >> #include "clang/AST/ASTContext.h" >> #include "clang/AST/ASTLambda.h" >> #include "clang/AST/ASTMutationListener.h" >> @@ -99,38 +100,6 @@ TranslationUnitDecl::TranslationUnitDecl >> // and 'matcher' is a type only matters when looking for attributes >> // and settings from the immediate context. >> >> -const static unsigned IgnoreExplicitVisibilityBit = 2; >> -const static unsigned IgnoreAllVisibilityBit = 4; >> - >> -/// Kinds of LV computation. The linkage side of the computation is >> -/// always the same, but different things can change how visibility is >> -/// computed. >> -enum LVComputationKind { >> - /// Do an LV computation for, ultimately, a type. >> - /// Visibility may be restricted by type visibility settings and >> - /// the visibility of template arguments. >> - LVForType = NamedDecl::VisibilityForType, >> - >> - /// Do an LV computation for, ultimately, a non-type declaration. >> - /// Visibility may be restricted by value visibility settings and >> - /// the visibility of template arguments. >> - LVForValue = NamedDecl::VisibilityForValue, >> - >> - /// Do an LV computation for, ultimately, a type that already has >> - /// some sort of explicit visibility. Visibility may only be >> - /// restricted by the visibility of template arguments. >> - LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit), >> - >> - /// Do an LV computation for, ultimately, a non-type declaration >> - /// that already has some sort of explicit visibility. Visibility >> - /// may only be restricted by the visibility of template arguments. >> - LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit), >> - >> - /// Do an LV computation when we only care about the linkage. >> - LVForLinkageOnly = >> - LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit >> -}; >> - >> /// Does this computation kind permit us to consider additional >> /// visibility settings from attributes and the like? >> static bool hasExplicitVisibilityAlready(
Re: r310436 - [AST] Move visibility computations into a class; NFC
Following up, http://green.lab.llvm.org/green/job/clang-stage2-cmake-RgSan_check/4070/console no longer shows ubsan failures. Looks like the attempt to fix Driver/openmp-offload.c is in r310580 (the linked build was r310538). The libc++ test failures all seem to be a result of -Werror clang emitting warnings as a result of r310403, which gave us more diagnostics about thread safety annotations. Glancing at it, seems legit. Working on a fix now. On Wed, Aug 9, 2017 at 2:22 PM, George Burgess IV wrote: > Sorry about that! > > Attempted fix is r310523. I'll keep an eye on the bot to make sure it > turns green. > > On Wed, Aug 9, 2017 at 1:23 PM, Juergen Ributzka wrote: >> This seems to cause UBSAN issues: >> >> runtime error: load of value 4294967295, which is not a valid value for type >> 'clang::LVComputationKind' >> >> See ASAN+UBSAN bot on Green Dragon: >> http://lab.llvm.org:8080/green/job/clang-stage2-cmake-RgSan_check/4065/console >> >> On Tue, Aug 8, 2017 at 9:02 PM, George Burgess IV via cfe-commits >> wrote: >>> >>> Author: gbiv >>> Date: Tue Aug 8 21:02:49 2017 >>> New Revision: 310436 >>> >>> URL: http://llvm.org/viewvc/llvm-project?rev=310436&view=rev >>> Log: >>> [AST] Move visibility computations into a class; NFC >>> >>> This is patch 1 in a 2 patch series that aims to fix PR29160. Its goal >>> is to cache decl visibility/linkage for the duration of each >>> visibility+linkage query. >>> >>> The simplest way I can see to do this is to put the visibility >>> calculation code that needs to (transitively) access this cache into a >>> class, which is what this patch does. Actual caching will come in patch >>> 2. (Another way would be to keep the cache in ASTContext + manually >>> invalidate it or something, but that felt way too subtle to me.) >>> >>> Caching visibility results across multiple queries seems a bit tricky, >>> since the user can add visibility attributes ~whenever they want, and >>> these attributes can apparently have far-reaching effects (e.g. class >>> visibility extends to its members, ...). Because a cache that's dropped >>> at the end of each top-level query seems to work nearly as well and >>> doesn't require any eviction logic, I opted for that design. >>> >>> Added: >>> cfe/trunk/lib/AST/Linkage.h >>> Modified: >>> cfe/trunk/lib/AST/Decl.cpp >>> cfe/trunk/lib/AST/Type.cpp >>> >>> Modified: cfe/trunk/lib/AST/Decl.cpp >>> URL: >>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310436&r1=310435&r2=310436&view=diff >>> >>> == >>> --- cfe/trunk/lib/AST/Decl.cpp (original) >>> +++ cfe/trunk/lib/AST/Decl.cpp Tue Aug 8 21:02:49 2017 >>> @@ -12,6 +12,7 @@ >>> >>> //===--===// >>> >>> #include "clang/AST/Decl.h" >>> +#include "Linkage.h" >>> #include "clang/AST/ASTContext.h" >>> #include "clang/AST/ASTLambda.h" >>> #include "clang/AST/ASTMutationListener.h" >>> @@ -99,38 +100,6 @@ TranslationUnitDecl::TranslationUnitDecl >>> // and 'matcher' is a type only matters when looking for attributes >>> // and settings from the immediate context. >>> >>> -const static unsigned IgnoreExplicitVisibilityBit = 2; >>> -const static unsigned IgnoreAllVisibilityBit = 4; >>> - >>> -/// Kinds of LV computation. The linkage side of the computation is >>> -/// always the same, but different things can change how visibility is >>> -/// computed. >>> -enum LVComputationKind { >>> - /// Do an LV computation for, ultimately, a type. >>> - /// Visibility may be restricted by type visibility settings and >>> - /// the visibility of template arguments. >>> - LVForType = NamedDecl::VisibilityForType, >>> - >>> - /// Do an LV computation for, ultimately, a non-type declaration. >>> - /// Visibility may be restricted by value visibility settings and >>> - /// the visibility of template arguments. >>> - LVForValue = NamedDecl::VisibilityForValue, >>> - >>> - /// Do an LV computation for, ultimately, a type that already has >>> - /// some sort of explicit visibility. Visibility may only be >>&
Re: r310403 - Thread Safety Analysis: warn on nonsensical attributes.
Hello! It looks like this is causing buildbot failures related to libc++'s lock_guard and scoped_lock: http://green.lab.llvm.org/green/job/clang-stage2-cmake-RgSan_check/4070/consoleFull Here's a reduced test-case (from libc++'s __mutex_base): struct __attribute__((capability("mutex"))) mutex { mutex(); ~mutex(); }; template struct __attribute__((scoped_lockable)) Foo { _Mutex &__m_; explicit Foo(_Mutex &__m) __attribute__((acquire_capability(__m))) : __m_(__m) {} ~Foo() __attribute__((release_capability())) {} }; int main() { ::mutex m; Foo f(m); } Built with `clang -Wthread-safety-attributes -Wthread-safety-attributes /tmp/tc.cpp -std=c++17 -c -o/dev/null`, I see the following warning: warning: 'release_capability' attribute requires type annotated with 'capability' attribute; type here is 'Foo<_Mutex> *' [-Wthread-safety-attributes] If I change ~Foo to release_capability(__m_), I get warnings about both 'm' being held at the end of main, and about releasing f.__m_, which was not held. Since the buildbot uses -Werror, ... Can you look into this, please? :) Thanks, George On Tue, Aug 8, 2017 at 12:44 PM, Josh Gao via cfe-commits wrote: > Author: jmgao > Date: Tue Aug 8 12:44:35 2017 > New Revision: 310403 > > URL: http://llvm.org/viewvc/llvm-project?rev=310403&view=rev > Log: > Thread Safety Analysis: warn on nonsensical attributes. > > Add warnings in cases where an implicit `this` argument is expected to > attributes because either `this` doesn't exist because the attribute is > on a free function, or because `this` is on a type that doesn't have a > corresponding capability/lockable/scoped_lockable attribute. > > Reviewers: delesley, aaron.ballman > > Differential Revision: https://reviews.llvm.org/D36237 > > Modified: > cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td > cfe/trunk/lib/Sema/SemaDeclAttr.cpp > cfe/trunk/test/Sema/attr-capabilities.c > cfe/trunk/test/SemaCXX/warn-thread-safety-parsing.cpp > > Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td > URL: > http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=310403&r1=310402&r2=310403&view=diff > == > --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original) > +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Aug 8 12:44:35 > 2017 > @@ -2932,6 +2932,16 @@ def warn_thread_attribute_decl_not_locka >"%0 attribute can only be applied in a context annotated " >"with 'capability(\"mutex\")' attribute">, >InGroup, DefaultIgnore; > +def warn_thread_attribute_noargs_not_lockable : Warning< > + "%0 attribute requires type annotated with 'capability' attribute; " > + "type here is %1">, > + InGroup, DefaultIgnore; > +def warn_thread_attribute_noargs_not_method : Warning< > + "%0 attribute without arguments can only be applied to a method of a > class">, > + InGroup, DefaultIgnore; > +def warn_thread_attribute_noargs_static_method : Warning< > + "%0 attribute without arguments cannot be applied to a static method">, > + InGroup, DefaultIgnore; > def warn_thread_attribute_decl_not_pointer : Warning< >"%0 only applies to pointer types; type here is %1">, >InGroup, DefaultIgnore; > > Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp > URL: > http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=310403&r1=310402&r2=310403&view=diff > == > --- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original) > +++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Tue Aug 8 12:44:35 2017 > @@ -480,7 +480,7 @@ static const RecordType *getRecordType(Q >return nullptr; > } > > -static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { > +template static bool checkRecordTypeForAttr(Sema &S, QualType > Ty) { >const RecordType *RT = getRecordType(Ty); > >if (!RT) > @@ -497,7 +497,7 @@ static bool checkRecordTypeForCapability > >// Check if the record itself has a capability. >RecordDecl *RD = RT->getDecl(); > - if (RD->hasAttr()) > + if (RD->hasAttr()) > return true; > >// Else check if any base classes have a capability. > @@ -505,14 +505,14 @@ static bool checkRecordTypeForCapability > CXXBasePaths BPaths(false, false); > if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) { >const auto *Type = BS->getType()->getAs(); > - return Type->getDecl()->hasAttr(); > + return Type->getDecl()->hasAttr(); > }, BPaths)) >return true; >} >return false; > } > > -static bool checkTypedefTypeForCapability(QualType Ty) { > +template static bool checkTypedefTypeForAttr(QualType Ty) { >const auto *TD = Ty->getAs(); >if (!TD) > return false; > @@ -521,19 +521,27 @@ static bool checkTypedefTypeForCapabilit >if (!TN) > return false; > > - return TN->
Re: r310436 - [AST] Move visibility computations into a class; NFC
Okay, apparently release_capability doesn't work how I assumed, so it looks like this may be a bug in r310403. Pinged that thread. On Thu, Aug 10, 2017 at 3:24 PM, George Burgess IV wrote: > Following up, > http://green.lab.llvm.org/green/job/clang-stage2-cmake-RgSan_check/4070/console > no longer shows ubsan failures. > > Looks like the attempt to fix Driver/openmp-offload.c is in r310580 > (the linked build was r310538). > > The libc++ test failures all seem to be a result of -Werror clang > emitting warnings as a result of r310403, which gave us more > diagnostics about thread safety annotations. Glancing at it, seems > legit. Working on a fix now. > > On Wed, Aug 9, 2017 at 2:22 PM, George Burgess IV > wrote: >> Sorry about that! >> >> Attempted fix is r310523. I'll keep an eye on the bot to make sure it >> turns green. >> >> On Wed, Aug 9, 2017 at 1:23 PM, Juergen Ributzka wrote: >>> This seems to cause UBSAN issues: >>> >>> runtime error: load of value 4294967295, which is not a valid value for type >>> 'clang::LVComputationKind' >>> >>> See ASAN+UBSAN bot on Green Dragon: >>> http://lab.llvm.org:8080/green/job/clang-stage2-cmake-RgSan_check/4065/console >>> >>> On Tue, Aug 8, 2017 at 9:02 PM, George Burgess IV via cfe-commits >>> wrote: >>>> >>>> Author: gbiv >>>> Date: Tue Aug 8 21:02:49 2017 >>>> New Revision: 310436 >>>> >>>> URL: http://llvm.org/viewvc/llvm-project?rev=310436&view=rev >>>> Log: >>>> [AST] Move visibility computations into a class; NFC >>>> >>>> This is patch 1 in a 2 patch series that aims to fix PR29160. Its goal >>>> is to cache decl visibility/linkage for the duration of each >>>> visibility+linkage query. >>>> >>>> The simplest way I can see to do this is to put the visibility >>>> calculation code that needs to (transitively) access this cache into a >>>> class, which is what this patch does. Actual caching will come in patch >>>> 2. (Another way would be to keep the cache in ASTContext + manually >>>> invalidate it or something, but that felt way too subtle to me.) >>>> >>>> Caching visibility results across multiple queries seems a bit tricky, >>>> since the user can add visibility attributes ~whenever they want, and >>>> these attributes can apparently have far-reaching effects (e.g. class >>>> visibility extends to its members, ...). Because a cache that's dropped >>>> at the end of each top-level query seems to work nearly as well and >>>> doesn't require any eviction logic, I opted for that design. >>>> >>>> Added: >>>> cfe/trunk/lib/AST/Linkage.h >>>> Modified: >>>> cfe/trunk/lib/AST/Decl.cpp >>>> cfe/trunk/lib/AST/Type.cpp >>>> >>>> Modified: cfe/trunk/lib/AST/Decl.cpp >>>> URL: >>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310436&r1=310435&r2=310436&view=diff >>>> >>>> == >>>> --- cfe/trunk/lib/AST/Decl.cpp (original) >>>> +++ cfe/trunk/lib/AST/Decl.cpp Tue Aug 8 21:02:49 2017 >>>> @@ -12,6 +12,7 @@ >>>> >>>> //===--===// >>>> >>>> #include "clang/AST/Decl.h" >>>> +#include "Linkage.h" >>>> #include "clang/AST/ASTContext.h" >>>> #include "clang/AST/ASTLambda.h" >>>> #include "clang/AST/ASTMutationListener.h" >>>> @@ -99,38 +100,6 @@ TranslationUnitDecl::TranslationUnitDecl >>>> // and 'matcher' is a type only matters when looking for attributes >>>> // and settings from the immediate context. >>>> >>>> -const static unsigned IgnoreExplicitVisibilityBit = 2; >>>> -const static unsigned IgnoreAllVisibilityBit = 4; >>>> - >>>> -/// Kinds of LV computation. The linkage side of the computation is >>>> -/// always the same, but different things can change how visibility is >>>> -/// computed. >>>> -enum LVComputationKind { >>>> - /// Do an LV computation for, ultimately, a type. >>>> - /// Visibility may be restricted by type visibility settings and >>>>
Re: r310403 - Thread Safety Analysis: warn on nonsensical attributes.
Sorry, I meant bin/clang -Wthread-safety-attributes -Wthread-safety-analysis /tmp/tc.cpp -std=c++17 -c -o/dev/null (had -Wthread-safety-attributes twice in the email) George On Thu, Aug 10, 2017 at 4:08 PM, George Burgess IV wrote: > Hello! > > It looks like this is causing buildbot failures related to libc++'s > lock_guard and scoped_lock: > http://green.lab.llvm.org/green/job/clang-stage2-cmake-RgSan_check/4070/consoleFull > > Here's a reduced test-case (from libc++'s __mutex_base): > > struct __attribute__((capability("mutex"))) mutex { > mutex(); > ~mutex(); > }; > > template struct __attribute__((scoped_lockable)) Foo { > _Mutex &__m_; > > explicit Foo(_Mutex &__m) __attribute__((acquire_capability(__m))) > : __m_(__m) {} > > ~Foo() __attribute__((release_capability())) {} > }; > > int main() { > ::mutex m; > Foo f(m); > } > > > Built with `clang -Wthread-safety-attributes > -Wthread-safety-attributes /tmp/tc.cpp -std=c++17 -c -o/dev/null`, I > see the following warning: > warning: 'release_capability' attribute requires type annotated with > 'capability' attribute; type here is 'Foo<_Mutex> *' > [-Wthread-safety-attributes] > > If I change ~Foo to release_capability(__m_), I get warnings about > both 'm' being held at the end of main, and about releasing f.__m_, > which was not held. > > Since the buildbot uses -Werror, ... > > Can you look into this, please? :) > > Thanks, > George > > On Tue, Aug 8, 2017 at 12:44 PM, Josh Gao via cfe-commits > wrote: >> Author: jmgao >> Date: Tue Aug 8 12:44:35 2017 >> New Revision: 310403 >> >> URL: http://llvm.org/viewvc/llvm-project?rev=310403&view=rev >> Log: >> Thread Safety Analysis: warn on nonsensical attributes. >> >> Add warnings in cases where an implicit `this` argument is expected to >> attributes because either `this` doesn't exist because the attribute is >> on a free function, or because `this` is on a type that doesn't have a >> corresponding capability/lockable/scoped_lockable attribute. >> >> Reviewers: delesley, aaron.ballman >> >> Differential Revision: https://reviews.llvm.org/D36237 >> >> Modified: >> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td >> cfe/trunk/lib/Sema/SemaDeclAttr.cpp >> cfe/trunk/test/Sema/attr-capabilities.c >> cfe/trunk/test/SemaCXX/warn-thread-safety-parsing.cpp >> >> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td >> URL: >> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=310403&r1=310402&r2=310403&view=diff >> == >> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original) >> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Aug 8 12:44:35 >> 2017 >> @@ -2932,6 +2932,16 @@ def warn_thread_attribute_decl_not_locka >>"%0 attribute can only be applied in a context annotated " >>"with 'capability(\"mutex\")' attribute">, >>InGroup, DefaultIgnore; >> +def warn_thread_attribute_noargs_not_lockable : Warning< >> + "%0 attribute requires type annotated with 'capability' attribute; " >> + "type here is %1">, >> + InGroup, DefaultIgnore; >> +def warn_thread_attribute_noargs_not_method : Warning< >> + "%0 attribute without arguments can only be applied to a method of a >> class">, >> + InGroup, DefaultIgnore; >> +def warn_thread_attribute_noargs_static_method : Warning< >> + "%0 attribute without arguments cannot be applied to a static method">, >> + InGroup, DefaultIgnore; >> def warn_thread_attribute_decl_not_pointer : Warning< >>"%0 only applies to pointer types; type here is %1">, >>InGroup, DefaultIgnore; >> >> Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp >> URL: >> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=310403&r1=310402&r2=310403&view=diff >> == >> --- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original) >> +++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Tue Aug 8 12:44:35 2017 >> @@ -480,7 +480,7 @@ static const RecordType *getRecordType(Q >>return nullptr; >> } >> >> -static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { >> +template static bool checkRecordTypeForAttr(Sema &S, QualType >> Ty) { >>const RecordType *RT = getRecordType(Ty); >> >>if (!RT) >> @@ -497,7 +497,7 @@ static bool checkRecordTypeForCapability >> >>// Check if the record itself has a capability. >>RecordDecl *RD = RT->getDecl(); >> - if (RD->hasAttr()) >> + if (RD->hasAttr()) >> return true; >> >>// Else check if any base classes have a capability. >> @@ -505,14 +505,14 @@ static bool checkRecordTypeForCapability >> CXXBasePaths BPaths(false, false); >> if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) { >>const auto *Type = BS->getType()->getAs(); >> - return Type->getDecl()->hasAttr(); >> + return Type->getDecl()->ha
r311051 - Fix typos in comments; NFC
Author: gbiv Date: Wed Aug 16 15:44:17 2017 New Revision: 311051 URL: http://llvm.org/viewvc/llvm-project?rev=311051&view=rev Log: Fix typos in comments; NFC Modified: cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h cfe/trunk/lib/Sema/SemaExpr.cpp Modified: cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h?rev=311051&r1=311050&r2=311051&view=diff == --- cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h (original) +++ cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h Wed Aug 16 15:44:17 2017 @@ -92,7 +92,7 @@ public: TheMacro = nullptr; } - /// getHasReadAnyTokensVal - This is used for the \#ifndef hande-shake at the + /// getHasReadAnyTokensVal - This is used for the \#ifndef handshake at the /// top of the file when reading preprocessor directives. Otherwise, reading /// the "ifndef x" would count as reading tokens. bool getHasReadAnyTokensVal() const { return ReadAnyTokens; } Modified: cfe/trunk/lib/Sema/SemaExpr.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=311051&r1=311050&r2=311051&view=diff == --- cfe/trunk/lib/Sema/SemaExpr.cpp (original) +++ cfe/trunk/lib/Sema/SemaExpr.cpp Wed Aug 16 15:44:17 2017 @@ -995,7 +995,7 @@ static QualType handleComplexFloatConver return ResultType; } -/// \brief Hande arithmetic conversion from integer to float. Helper function +/// \brief Handle arithmetic conversion from integer to float. Helper function /// of UsualArithmeticConversions() static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] 9d40fb8 - Allow to specify macro names for android-comparison-in-temp-failure-retry
Author: Florian Mayer Date: 2020-10-01T10:09:26-07:00 New Revision: 9d40fb808fd0fbd33eb3b50c20d7f402de5db91e URL: https://github.com/llvm/llvm-project/commit/9d40fb808fd0fbd33eb3b50c20d7f402de5db91e DIFF: https://github.com/llvm/llvm-project/commit/9d40fb808fd0fbd33eb3b50c20d7f402de5db91e.diff LOG: Allow to specify macro names for android-comparison-in-temp-failure-retry Some projects do not use the TEMP_FAILURE_RETRY macro but define their own one, as not to depend on glibc / Bionic details. By allowing the user to override the list of macros, these projects can also benefit from this check. Differential Revision: https://reviews.llvm.org/D83144 Added: clang-tools-extra/test/clang-tidy/checkers/android-comparison-in-temp-failure-retry-custom-macro.c Modified: clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.h clang-tools-extra/docs/clang-tidy/checks/android-comparison-in-temp-failure-retry.rst Removed: diff --git a/clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp b/clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp index 188d44da51d81..c7b9896c64f81 100644 --- a/clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp +++ b/clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp @@ -18,32 +18,17 @@ namespace clang { namespace tidy { namespace android { -namespace { -AST_MATCHER(BinaryOperator, isRHSATempFailureRetryArg) { - if (!Node.getBeginLoc().isMacroID()) -return false; - - const SourceManager &SM = Finder->getASTContext().getSourceManager(); - if (!SM.isMacroArgExpansion(Node.getRHS()->IgnoreParenCasts()->getBeginLoc())) -return false; - - const LangOptions &Opts = Finder->getASTContext().getLangOpts(); - SourceLocation LocStart = Node.getBeginLoc(); - while (LocStart.isMacroID()) { -SourceLocation Invocation = SM.getImmediateMacroCallerLoc(LocStart); -Token Tok; -if (!Lexer::getRawToken(SM.getSpellingLoc(Invocation), Tok, SM, Opts, -/*IgnoreWhiteSpace=*/true)) { - if (Tok.getKind() == tok::raw_identifier && - Tok.getRawIdentifier() == "TEMP_FAILURE_RETRY") -return true; -} +ComparisonInTempFailureRetryCheck::ComparisonInTempFailureRetryCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + RawRetryList(Options.get("RetryMacros", "TEMP_FAILURE_RETRY")) { + StringRef(RawRetryList).split(RetryMacros, ",", -1, false); +} -LocStart = Invocation; - } - return false; +void ComparisonInTempFailureRetryCheck::storeOptions( +ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "RetryMacros", RawRetryList); } -} // namespace void ComparisonInTempFailureRetryCheck::registerMatchers(MatchFinder *Finder) { // Both glibc's and Bionic's TEMP_FAILURE_RETRY macros structurally look like: @@ -63,15 +48,43 @@ void ComparisonInTempFailureRetryCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( binaryOperator(hasOperatorName("="), hasRHS(ignoringParenCasts( - binaryOperator(isComparisonOperator()).bind("binop"))), - isRHSATempFailureRetryArg()), + binaryOperator(isComparisonOperator()).bind("inner" + .bind("outer"), this); } void ComparisonInTempFailureRetryCheck::check( const MatchFinder::MatchResult &Result) { - const auto &BinOp = *Result.Nodes.getNodeAs("binop"); - diag(BinOp.getOperatorLoc(), "top-level comparison in TEMP_FAILURE_RETRY"); + StringRef RetryMacroName; + const auto &Node = *Result.Nodes.getNodeAs("outer"); + if (!Node.getBeginLoc().isMacroID()) +return; + + const SourceManager &SM = *Result.SourceManager; + if (!SM.isMacroArgExpansion(Node.getRHS()->IgnoreParenCasts()->getBeginLoc())) +return; + + const LangOptions &Opts = Result.Context->getLangOpts(); + SourceLocation LocStart = Node.getBeginLoc(); + while (LocStart.isMacroID()) { +SourceLocation Invocation = SM.getImmediateMacroCallerLoc(LocStart); +Token Tok; +if (!Lexer::getRawToken(SM.getSpellingLoc(Invocation), Tok, SM, Opts, +/*IgnoreWhiteSpace=*/true)) { + if (Tok.getKind() == tok::raw_identifier && + llvm::is_contained(RetryMacros, Tok.getRawIdentifier())) { +RetryMacroName = Tok.getRawIdentifier(); +break; + } +} + +LocStart = Invocation; + } + if (RetryMacroName.empty()) +return; + + const auto &Inner = *Result.Nodes.getNodeAs("inner"); + diag(Inner.getOperatorLoc(), "top-level comparison in %0") << RetryMacroName; // FIXME: FixIts would be nice, but potentially nontrivial when nested macros // happen, e.g. `TEMP_FAILURE_RET
[clang] 425a83a - [Sema] adds basic -Wfree-nonheap-object functionality
Author: Christopher Di Bella Date: 2020-10-28T16:18:23-07:00 New Revision: 425a83a5f069eb1a692145d2c92e6d3bfe564a62 URL: https://github.com/llvm/llvm-project/commit/425a83a5f069eb1a692145d2c92e6d3bfe564a62 DIFF: https://github.com/llvm/llvm-project/commit/425a83a5f069eb1a692145d2c92e6d3bfe564a62.diff LOG: [Sema] adds basic -Wfree-nonheap-object functionality Checks to make sure that stdlib's (std::)free is being appropriately used. Presently checks for the following misuses: - free(&stack_object) - free(stack_array) Differential Revision: https://reviews.llvm.org/D89988 Added: clang/test/Sema/warn-free-nonheap-object.c clang/test/Sema/warn-free-nonheap-object.cpp Modified: clang/include/clang/Basic/Builtins.def clang/include/clang/Basic/DiagnosticSemaKinds.td clang/include/clang/Sema/Sema.h clang/lib/AST/Decl.cpp clang/lib/Sema/SemaChecking.cpp Removed: diff --git a/clang/include/clang/Basic/Builtins.def b/clang/include/clang/Basic/Builtins.def index b2876ed6cbed..45ea7d9a3551 100644 --- a/clang/include/clang/Basic/Builtins.def +++ b/clang/include/clang/Basic/Builtins.def @@ -913,6 +913,7 @@ LIBBUILTIN(exit, "vi","fr","stdlib.h", ALL_LANGUAGES) LIBBUILTIN(_Exit, "vi", "fr","stdlib.h", ALL_LANGUAGES) LIBBUILTIN(malloc, "v*z", "f", "stdlib.h", ALL_LANGUAGES) LIBBUILTIN(realloc, "v*v*z", "f", "stdlib.h", ALL_LANGUAGES) +LIBBUILTIN(free,"vv*","f", "stdlib.h", ALL_LANGUAGES) LIBBUILTIN(strtod, "dcC*c**", "f", "stdlib.h", ALL_LANGUAGES) LIBBUILTIN(strtof, "fcC*c**", "f", "stdlib.h", ALL_LANGUAGES) LIBBUILTIN(strtold, "LdcC*c**", "f", "stdlib.h", ALL_LANGUAGES) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index e1d20fbcb433..97cacbe32e5a 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -7539,6 +7539,11 @@ def err_incomplete_object_call : Error< def warn_condition_is_assignment : Warning<"using the result of an " "assignment as a condition without parentheses">, InGroup; +def warn_free_nonheap_object + : Warning<"attempt to call %0 on non-heap object %1">, +InGroup>, +DefaultIgnore; // FIXME: add to -Wall after sufficient testing + // Completely identical except off by default. def warn_condition_is_idiomatic_assignment : Warning<"using the result " "of an assignment as a condition without parentheses">, diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 3c3190680acf..61ee743a7ab9 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -12400,6 +12400,8 @@ class Sema final { void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); + void CheckFreeArguments(const CallExpr *E); + void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp index 80bc22b61b70..b4f92d77dd5d 100644 --- a/clang/lib/AST/Decl.cpp +++ b/clang/lib/AST/Decl.cpp @@ -3959,6 +3959,9 @@ unsigned FunctionDecl::getMemoryFunctionKind() const { case Builtin::BIbzero: return Builtin::BIbzero; + case Builtin::BIfree: +return Builtin::BIfree; + default: if (isExternC()) { if (FnInfo->isStr("memset")) @@ -3987,6 +3990,9 @@ unsigned FunctionDecl::getMemoryFunctionKind() const { return Builtin::BIstrlen; else if (FnInfo->isStr("bzero")) return Builtin::BIbzero; +} else if (isInStdNamespace()) { + if (FnInfo->isStr("free")) +return Builtin::BIfree; } break; } diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index e87adf8ff302..3d5e2d70d8ca 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -4496,16 +4496,24 @@ bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); unsigned CMId = FDecl->getMemoryFunctionKind(); - if (CMId == 0) -return false; // Handle memory setting and copying functions. - if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) + switch (CMId) { + case 0: +return false; + case Builtin::BIstrlcpy: // fallthrough + case Builtin::BIstrlcat: CheckStrlcpycatArguments(TheCall, FnInfo); - else if (CMId == Builtin::BIstrncat) +break; + case Builtin::BIstrncat: CheckStrncatArguments(TheCall, FnInfo); - else +break; + case Builtin::BIfree: +CheckFreeArguments(TheCall); +break; + default: CheckMemaccessArguments(TheCall, CMId, FnInfo); + } return false; } @@ -10098,6 +10106
[clang] ba18bc4 - [Sema] adds -Wfree-nonheap-object member var checks
Author: Christopher Di Bella Date: 2020-11-02T11:03:28-08:00 New Revision: ba18bc4925d8cbd4a9354629617cbcafbbd48941 URL: https://github.com/llvm/llvm-project/commit/ba18bc4925d8cbd4a9354629617cbcafbbd48941 DIFF: https://github.com/llvm/llvm-project/commit/ba18bc4925d8cbd4a9354629617cbcafbbd48941.diff LOG: [Sema] adds -Wfree-nonheap-object member var checks Checks to make sure that stdlib's (std::)free is being appropriately used for member variables. Differential Revision: https://reviews.llvm.org/D90269 Added: Modified: clang/lib/Sema/SemaChecking.cpp clang/test/Sema/warn-free-nonheap-object.c clang/test/Sema/warn-free-nonheap-object.cpp Removed: diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 3d5e2d70d8ca..bad9b14c1fa2 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -10107,19 +10107,9 @@ void Sema::CheckStrncatArguments(const CallExpr *CE, } namespace { -void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, - const UnaryOperator *UnaryExpr) { - if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf) -return; - - const auto *Lvalue = dyn_cast(UnaryExpr->getSubExpr()); - if (Lvalue == nullptr) -return; - - const auto *Var = dyn_cast(Lvalue->getDecl()); - if (Var == nullptr) -return; - +void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, +const UnaryOperator *UnaryExpr, +const VarDecl *Var) { StorageClass Class = Var->getStorageClass(); if (Class == StorageClass::SC_Extern || Class == StorageClass::SC_PrivateExtern || @@ -10130,6 +10120,27 @@ void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, << CalleeName << Var; } +void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, +const UnaryOperator *UnaryExpr, const Decl *D) { + if (const auto *Field = dyn_cast(D)) +S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) +<< CalleeName << Field; +} + +void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, + const UnaryOperator *UnaryExpr) { + if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf) +return; + + if (const auto *Lvalue = dyn_cast(UnaryExpr->getSubExpr())) +if (const auto *Var = dyn_cast(Lvalue->getDecl())) + return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var); + + if (const auto *Lvalue = dyn_cast(UnaryExpr->getSubExpr())) +return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, + Lvalue->getMemberDecl()); +} + void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, const DeclRefExpr *Lvalue) { if (!Lvalue->getType()->isArrayType()) diff --git a/clang/test/Sema/warn-free-nonheap-object.c b/clang/test/Sema/warn-free-nonheap-object.c index e149e8349571..1618a559b431 100644 --- a/clang/test/Sema/warn-free-nonheap-object.c +++ b/clang/test/Sema/warn-free-nonheap-object.c @@ -4,6 +4,11 @@ typedef __SIZE_TYPE__ size_t; void *malloc(size_t); void free(void *); +struct S { + int I; + char *P; +}; + int GI; void test() { { @@ -31,4 +36,9 @@ void test() { free(A); // expected-warning {{attempt to call free on non-heap object 'A'}} free(&A); // expected-warning {{attempt to call free on non-heap object 'A'}} } + { +struct S s; +free(&s.I); // expected-warning {{attempt to call free on non-heap object 'I'}} +free(s.P); + } } diff --git a/clang/test/Sema/warn-free-nonheap-object.cpp b/clang/test/Sema/warn-free-nonheap-object.cpp index 0578d9e9cd66..9347709a23ca 100644 --- a/clang/test/Sema/warn-free-nonheap-object.cpp +++ b/clang/test/Sema/warn-free-nonheap-object.cpp @@ -13,10 +13,25 @@ int GI; struct S { operator char *() { return ptr; } + void CFree() { +::free(&ptr); // expected-warning {{attempt to call free on non-heap object 'ptr'}} +::free(&I); // expected-warning {{attempt to call free on non-heap object 'I'}} +::free(ptr); + } + + void CXXFree() { +std::free(&ptr); // expected-warning {{attempt to call std::free on non-heap object 'ptr'}} +std::free(&I); // expected-warning {{attempt to call std::free on non-heap object 'I'}} +std::free(ptr); + } + private: char *ptr = (char *)std::malloc(10); + static int I; }; +int S::I = 0; + void test1() { { free(&GI); // expected-warning {{attempt to call free on non-heap object 'GI'}} @@ -51,6 +66,10 @@ void test1() { free(s); free(&s); // expected-warning {{attempt to call free on non-heap object 's'}} } + { +S s; +s.CFree(); + } } void test2() { @@ -87,4 +106,8 @@ void test2(
[clang] cf49cae - [Clang] -Wunused-but-set-parameter and -Wunused-but-set-variable
Author: Michael Benfield Date: 2021-06-01T15:38:48-07:00 New Revision: cf49cae278b4e972cd2547d72f9ee7d9d69a3af4 URL: https://github.com/llvm/llvm-project/commit/cf49cae278b4e972cd2547d72f9ee7d9d69a3af4 DIFF: https://github.com/llvm/llvm-project/commit/cf49cae278b4e972cd2547d72f9ee7d9d69a3af4.diff LOG: [Clang] -Wunused-but-set-parameter and -Wunused-but-set-variable These are intended to mimic warnings available in gcc. Differential Revision: https://reviews.llvm.org/D100581 Added: clang/test/Sema/warn-unused-but-set-parameters.c clang/test/Sema/warn-unused-but-set-variables.c clang/test/SemaCXX/warn-unused-but-set-parameters-cpp.cpp clang/test/SemaCXX/warn-unused-but-set-variables-cpp.cpp Modified: clang/include/clang/Basic/DiagnosticGroups.td clang/include/clang/Basic/DiagnosticSemaKinds.td clang/include/clang/Sema/Sema.h clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaExpr.cpp clang/lib/Sema/SemaExprCXX.cpp clang/test/CXX/expr/expr.prim/expr.prim.lambda/p12.cpp clang/test/CodeGen/2007-10-30-Volatile.c clang/test/CodeGen/X86/x86_32-xsave.c clang/test/CodeGen/X86/x86_64-xsave.c clang/test/CodeGen/builtins-arm.c clang/test/CodeGen/builtins-riscv.c clang/test/FixIt/fixit.cpp clang/test/Misc/warning-wall.c clang/test/Sema/shift.c clang/test/Sema/vector-gcc-compat.c clang/test/Sema/vector-gcc-compat.cpp clang/test/SemaCXX/goto.cpp clang/test/SemaCXX/shift.cpp clang/test/SemaCXX/sizeless-1.cpp clang/test/SemaObjC/foreach.m Removed: diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index 8544607673c3e..b4be0fcfb454f 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -725,6 +725,7 @@ def UnusedMemberFunction : DiagGroup<"unused-member-function", def UnusedLabel : DiagGroup<"unused-label">; def UnusedLambdaCapture : DiagGroup<"unused-lambda-capture">; def UnusedParameter : DiagGroup<"unused-parameter">; +def UnusedButSetParameter : DiagGroup<"unused-but-set-parameter">; def UnusedResult : DiagGroup<"unused-result">; def PotentiallyEvaluatedExpression : DiagGroup<"potentially-evaluated-expression">; def UnevaluatedExpression : DiagGroup<"unevaluated-expression", @@ -734,6 +735,7 @@ def UnusedValue : DiagGroup<"unused-value", [UnusedComparison, UnusedResult, def UnusedConstVariable : DiagGroup<"unused-const-variable">; def UnusedVariable : DiagGroup<"unused-variable", [UnusedConstVariable]>; +def UnusedButSetVariable : DiagGroup<"unused-but-set-variable">; def UnusedLocalTypedef : DiagGroup<"unused-local-typedef">; def UnusedPropertyIvar : DiagGroup<"unused-property-ivar">; def UnusedGetterReturnValue : DiagGroup<"unused-getter-return-value">; @@ -875,7 +877,7 @@ def Unused : DiagGroup<"unused", // UnusedMemberFunction, (clean-up llvm before enabling) UnusedPrivateField, UnusedLambdaCapture, UnusedLocalTypedef, UnusedValue, UnusedVariable, -UnusedPropertyIvar]>, +UnusedButSetVariable, UnusedPropertyIvar]>, DiagCategory<"Unused Entity Issue">; // Format settings. @@ -927,6 +929,7 @@ def Extra : DiagGroup<"extra", [ MissingMethodReturnType, SignCompare, UnusedParameter, +UnusedButSetParameter, NullPointerArithmetic, EmptyInitStatement, StringConcatation, diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 80130c2584fe5..cc23fd789d31c 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -311,8 +311,12 @@ def note_riscv_repeated_interrupt_attribute : Note< "repeated RISC-V 'interrupt' attribute is here">; def warn_unused_parameter : Warning<"unused parameter %0">, InGroup, DefaultIgnore; +def warn_unused_but_set_parameter : Warning<"parameter %0 set but not used">, + InGroup, DefaultIgnore; def warn_unused_variable : Warning<"unused variable %0">, InGroup, DefaultIgnore; +def warn_unused_but_set_variable : Warning<"variable %0 set but not used">, + InGroup, DefaultIgnore; def warn_unused_local_typedef : Warning< "unused %select{typedef|type alias}0 %1">, InGroup, DefaultIgnore; diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 65469418936cb..347a909d99574 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -1518,6 +1518,11 @@ class Sema final { bool WarnedStackExhausted = false; + /// Increment when we find a reference; decrement when we find an ignored + /// assignment. Ultimately the value is 0 if every reference is an ignored + /// assign
[clang] 20f7b5f - [Clang] Test case for -Wunused-but-set-variable, warn for volatile.
Author: Michael Benfield Date: 2021-06-14T10:25:59-07:00 New Revision: 20f7b5f3f9c8ebbbe7bf6648c824b815385d4bf7 URL: https://github.com/llvm/llvm-project/commit/20f7b5f3f9c8ebbbe7bf6648c824b815385d4bf7 DIFF: https://github.com/llvm/llvm-project/commit/20f7b5f3f9c8ebbbe7bf6648c824b815385d4bf7.diff LOG: [Clang] Test case for -Wunused-but-set-variable, warn for volatile. Differential Revision: https://reviews.llvm.org/D103623 Added: Modified: clang/test/Sema/warn-unused-but-set-variables.c Removed: diff --git a/clang/test/Sema/warn-unused-but-set-variables.c b/clang/test/Sema/warn-unused-but-set-variables.c index 93595a251df0..a8d05243321f 100644 --- a/clang/test/Sema/warn-unused-but-set-variables.c +++ b/clang/test/Sema/warn-unused-but-set-variables.c @@ -23,6 +23,10 @@ int f0() { int a; w = (a = 0); + // Following gcc, warn for a volatile variable. + volatile int b; // expected-warning{{variable 'b' set but not used}} + b = 0; + int x; x = 0; return x; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] 2e75986 - bugprone-argument-comment: ignore mismatches from system headers
Author: George Burgess IV Date: 2021-08-03T19:56:27Z New Revision: 2e75986a21e543ac9f169a067542eec590339ac0 URL: https://github.com/llvm/llvm-project/commit/2e75986a21e543ac9f169a067542eec590339ac0 DIFF: https://github.com/llvm/llvm-project/commit/2e75986a21e543ac9f169a067542eec590339ac0.diff LOG: bugprone-argument-comment: ignore mismatches from system headers As of 2a3498e24f97d, we ignore parameter name mismatches for functions in the `std::` namespace, since those aren't standardized. It seems reasonable to extend this to all functions which are declared in system headers, since this lint can be a bit noisy otherwise (https://bugs.chromium.org/p/chromium/issues/detail?id=1191507). Differential Revision: https://reviews.llvm.org/D3 Added: clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/header-with-decl.h clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/system-header-with-decl.h Modified: clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment.cpp Removed: diff --git a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp index e50ebdba3b34..c36fb60b6d3d 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp @@ -20,10 +20,12 @@ namespace clang { namespace tidy { namespace bugprone { namespace { -AST_MATCHER(Decl, isFromStdNamespace) { +AST_MATCHER(Decl, isFromStdNamespaceOrSystemHeader) { if (const auto *D = Node.getDeclContext()->getEnclosingNamespaceContext()) -return D->isStdNamespace(); - return false; +if (D->isStdNamespace()) + return true; + return Node.getASTContext().getSourceManager().isInSystemHeader( + Node.getLocation()); } } // namespace @@ -66,13 +68,13 @@ void ArgumentCommentCheck::registerMatchers(MatchFinder *Finder) { // not specified by the standard, and standard library // implementations in practice have to use reserved names to // avoid conflicts with same-named macros. - unless(hasDeclaration(isFromStdNamespace( - .bind("expr"), - this); - Finder->addMatcher( - cxxConstructExpr(unless(hasDeclaration(isFromStdNamespace( + unless(hasDeclaration(isFromStdNamespaceOrSystemHeader( .bind("expr"), this); + Finder->addMatcher(cxxConstructExpr(unless(hasDeclaration( + isFromStdNamespaceOrSystemHeader( + .bind("expr"), + this); } static std::vector> diff --git a/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/header-with-decl.h b/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/header-with-decl.h new file mode 100644 index ..1e065b1edeb6 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/header-with-decl.h @@ -0,0 +1 @@ +void my_header_function(int arg); diff --git a/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/system-header-with-decl.h b/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/system-header-with-decl.h new file mode 100644 index ..4e3529a6f1ab --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/system-header-with-decl.h @@ -0,0 +1,3 @@ +#pragma clang system_header + +void my_system_header_function(int arg); diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment.cpp index 8a6fe097a55d..cb4eac84c691 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment.cpp @@ -1,4 +1,4 @@ -// RUN: %check_clang_tidy %s bugprone-argument-comment %t +// RUN: %check_clang_tidy %s bugprone-argument-comment %t -- -- -I %S/Inputs/bugprone-argument-comment // FIXME: clang-tidy should provide a -verify mode to make writing these checks // easier and more accurate. @@ -134,3 +134,20 @@ void test(int a, int b) { std::swap(a, /*num=*/b); } } // namespace ignore_std_functions + +namespace regular_header { +#include "header-with-decl.h" +void test() { + my_header_function(/*not_arg=*/1); +// CHECK-NOTES: [[@LINE-1]]:22: warning: argument name 'not_arg' in comment does not match parameter name 'arg' +// CHECK-NOTES: header-with-decl.h:1:29: note: 'arg' declared here +// CHECK-FIXES: my_header_function(/*not_arg=*/1); +} +} // namespace regular_header + +namespace system_header { +#include "system-heade
[clang-tools-extra] 9f13a03 - clang-tidy: don't use an absolute path in a test
Author: George Burgess IV Date: 2019-11-22T18:13:18-08:00 New Revision: 9f13a032b6d7f720caf6511d0c9b1b6b7d2bbc67 URL: https://github.com/llvm/llvm-project/commit/9f13a032b6d7f720caf6511d0c9b1b6b7d2bbc67 DIFF: https://github.com/llvm/llvm-project/commit/9f13a032b6d7f720caf6511d0c9b1b6b7d2bbc67.diff LOG: clang-tidy: don't use an absolute path in a test `run_clang_tidy` takes a regular expression to match against compile_commands.json entries. If we pass "%t/test.cpp" and "%t" expands to anything that includes chars that a regex treats specially, like '+', this test starts failing. Added: Modified: clang-tools-extra/test/clang-tidy/infrastructure/run-clang-tidy.cpp Removed: diff --git a/clang-tools-extra/test/clang-tidy/infrastructure/run-clang-tidy.cpp b/clang-tools-extra/test/clang-tidy/infrastructure/run-clang-tidy.cpp index 31c4d681ebc9..0d0e41e022ae 100644 --- a/clang-tools-extra/test/clang-tidy/infrastructure/run-clang-tidy.cpp +++ b/clang-tools-extra/test/clang-tidy/infrastructure/run-clang-tidy.cpp @@ -9,7 +9,7 @@ // RUN: echo "value: '0'" >> %t/.clang-tidy // RUN: cp "%s" "%t/test.cpp" // RUN: cd "%t" -// RUN: not %run_clang_tidy "%t/test.cpp" +// RUN: not %run_clang_tidy "test.cpp" int main() { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 380a645 - [ASTMatchers] work around a miscompile; "NFC"
Author: George Burgess IV Date: 2019-11-22T20:11:16-08:00 New Revision: 380a6452b2e98d9c34828503edf8032f6b4c82d3 URL: https://github.com/llvm/llvm-project/commit/380a6452b2e98d9c34828503edf8032f6b4c82d3 DIFF: https://github.com/llvm/llvm-project/commit/380a6452b2e98d9c34828503edf8032f6b4c82d3.diff LOG: [ASTMatchers] work around a miscompile; "NFC" I chatted with Reid offline, and we agreed that having a workaround here would be appropriate until PR43879 is resolved. The given transformation Works On My Machine(TM), and should hopefully hold more broadly, but my fingers are crossed nonetheless. :) Added: Modified: clang/lib/ASTMatchers/ASTMatchFinder.cpp Removed: diff --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp b/clang/lib/ASTMatchers/ASTMatchFinder.cpp index c51fd630e64b..8a103f3d89a3 100644 --- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp +++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp @@ -904,8 +904,9 @@ bool MatchASTVisitor::objcClassIsDerivedFrom( if (Base.matches(*ClassDecl, this, Builder)) return true; +// Not `return false` as a temporary workaround for PR43879. if (Directly) - return false; + break; } return false; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r329428 - [clang-tidy] Sort includes; NFC
Author: gbiv Date: Fri Apr 6 10:22:36 2018 New Revision: 329428 URL: http://llvm.org/viewvc/llvm-project?rev=329428&view=rev Log: [clang-tidy] Sort includes; NFC Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp?rev=329428&r1=329427&r2=329428&view=diff == --- clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp Fri Apr 6 10:22:36 2018 @@ -13,9 +13,9 @@ #include "CloexecAccept4Check.h" #include "CloexecAcceptCheck.h" #include "CloexecCreatCheck.h" +#include "CloexecDupCheck.h" #include "CloexecEpollCreate1Check.h" #include "CloexecEpollCreateCheck.h" -#include "CloexecDupCheck.h" #include "CloexecFopenCheck.h" #include "CloexecInotifyInit1Check.h" #include "CloexecInotifyInitCheck.h" ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r329652 - [AST] Attempt to fix buildbot warnings + appease MSVC; NFCI
Author: gbiv Date: Mon Apr 9 18:11:26 2018 New Revision: 329652 URL: http://llvm.org/viewvc/llvm-project?rev=329652&view=rev Log: [AST] Attempt to fix buildbot warnings + appease MSVC; NFCI GCC 4.8.4 on a bot was warning about `ArgPassingKind` not fitting in `ArgPassingRestrictions`, which appears to be incorrect, since `ArgPassingKind` only has three potential values: "warning: 'clang::RecordDecl::ArgPassingRestrictions' is too small to hold all values of 'enum clang::RecordDecl::ArgPassingKind'" Additionally, I remember hearing (though my knowledge may be outdated) that MSVC won't merge adjacent bitfields if their types are different. Try to fix both issues by turning these into `uint8_t`s. Modified: cfe/trunk/include/clang/AST/Decl.h Modified: cfe/trunk/include/clang/AST/Decl.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=329652&r1=329651&r2=329652&view=diff == --- cfe/trunk/include/clang/AST/Decl.h (original) +++ cfe/trunk/include/clang/AST/Decl.h Mon Apr 9 18:11:26 2018 @@ -3599,10 +3599,13 @@ private: /// Indicates whether this struct is destroyed in the callee. This flag is /// meaningless when Microsoft ABI is used since parameters are always /// destroyed in the callee. - bool ParamDestroyedInCallee : 1; + /// + /// Please note that MSVC won't merge adjacent bitfields if they don't have + /// the same type. + uint8_t ParamDestroyedInCallee : 1; /// Represents the way this type is passed to a function. - ArgPassingKind ArgPassingRestrictions : 2; + uint8_t ArgPassingRestrictions : 2; protected: RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, @@ -3691,15 +3694,15 @@ public: /// it must have at least one trivial, non-deleted copy or move constructor. /// FIXME: This should be set as part of completeDefinition. bool canPassInRegisters() const { -return ArgPassingRestrictions == APK_CanPassInRegs; +return getArgPassingRestrictions() == APK_CanPassInRegs; } ArgPassingKind getArgPassingRestrictions() const { -return ArgPassingRestrictions; +return static_cast(ArgPassingRestrictions); } void setArgPassingRestrictions(ArgPassingKind Kind) { -ArgPassingRestrictions = Kind; +ArgPassingRestrictions = static_cast(Kind); } bool isParamDestroyedInCallee() const { ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r329759 - [clang-tidy] Add a `android-comparison-in-temp-failure-retry` check
Author: gbiv Date: Tue Apr 10 14:22:22 2018 New Revision: 329759 URL: http://llvm.org/viewvc/llvm-project?rev=329759&view=rev Log: [clang-tidy] Add a `android-comparison-in-temp-failure-retry` check This check attempts to catch buggy uses of the `TEMP_FAILURE_RETRY` macro, which is provided by both Bionic and glibc. Differential Revision: https://reviews.llvm.org/D45059 Added: clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.h clang-tools-extra/trunk/docs/clang-tidy/checks/android-comparison-in-temp-failure-retry.rst clang-tools-extra/trunk/test/clang-tidy/android-comparison-in-temp-failure-retry.c Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt clang-tools-extra/trunk/docs/ReleaseNotes.rst clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp?rev=329759&r1=329758&r2=329759&view=diff == --- clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp Tue Apr 10 14:22:22 2018 @@ -22,6 +22,7 @@ #include "CloexecMemfdCreateCheck.h" #include "CloexecOpenCheck.h" #include "CloexecSocketCheck.h" +#include "ComparisonInTempFailureRetryCheck.h" using namespace clang::ast_matchers; @@ -50,6 +51,8 @@ public: "android-cloexec-memfd-create"); CheckFactories.registerCheck("android-cloexec-open"); CheckFactories.registerCheck("android-cloexec-socket"); +CheckFactories.registerCheck( +"android-comparison-in-temp-failure-retry"); } }; Modified: clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt?rev=329759&r1=329758&r2=329759&view=diff == --- clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt (original) +++ clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt Tue Apr 10 14:22:22 2018 @@ -15,6 +15,7 @@ add_clang_library(clangTidyAndroidModule CloexecMemfdCreateCheck.cpp CloexecOpenCheck.cpp CloexecSocketCheck.cpp + ComparisonInTempFailureRetryCheck.cpp LINK_LIBS clangAST Added: clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp?rev=329759&view=auto == --- clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp (added) +++ clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp Tue Apr 10 14:22:22 2018 @@ -0,0 +1,84 @@ +//===--- ComparisonInTempFailureRetryCheck.cpp - clang-tidy===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// + +#include "../utils/Matchers.h" +#include "ComparisonInTempFailureRetryCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang { +namespace tidy { +namespace android { + +namespace { +AST_MATCHER(BinaryOperator, isRHSATempFailureRetryArg) { + if (!Node.getLocStart().isMacroID()) +return false; + + const SourceManager &SM = Finder->getASTContext().getSourceManager(); + if (!SM.isMacroArgExpansion(Node.getRHS()->IgnoreParenCasts()->getLocStart())) +return false; + + const LangOptions &Opts = Finder->getASTContext().getLangOpts(); + SourceLocation LocStart = Node.getLocStart(); + while (LocStart.isMacroID()) { +SourceLocation Invocation = SM.getImmediateMacroCallerLoc(LocStart); +Token Tok; +if (!Lexer::getRawToken(SM.getSpellingLoc(Invocation), Tok, SM, Opts, +/*IgnoreWhiteSpace=*/true)) { + if (Tok.getKind() == tok::raw_identifier && + Tok.getRawIdentifier() == "TEMP_FAILURE_RETRY") +return true; +} + +LocStart = Invocation; + } + return false; +} +} // namespace + +void ComparisonInTempFailureRetryCheck::registerMatchers(MatchFinder *Finder) { + // Both glibc's and Bionic's TEMP_FAILURE_RETRY macros structurally look like: + // + // #define TEMP_FAILURE_RETRY(x) ({ \ + //typeof(x) y; \ + //do y = (x); \ + //while (y == -1 && errno == EI
r290149 - Add the alloc_size attribute to clang.
Author: gbiv Date: Mon Dec 19 19:05:42 2016 New Revision: 290149 URL: http://llvm.org/viewvc/llvm-project?rev=290149&view=rev Log: Add the alloc_size attribute to clang. This patch does three things: - Gives us the alloc_size attribute in clang, which lets us infer the number of bytes handed back to us by malloc/realloc/calloc/any user functions that act in a similar manner. - Teaches our constexpr evaluator that evaluating some `const` variables is OK sometimes. This is why we have a change in test/SemaCXX/constant-expression-cxx11.cpp and other seemingly unrelated tests. Richard Smith okay'ed this idea some time ago in person. - Uniques some Blocks in CodeGen, which was reviewed separately at D26410. Lack of uniquing only really shows up as a problem when combined with our new eagerness in the face of const. Differential Revision: https://reviews.llvm.org/D14274 Added: cfe/trunk/test/CodeGen/alloc-size.c cfe/trunk/test/CodeGenCXX/alloc-size.cpp cfe/trunk/test/Sema/alloc-size.c Modified: cfe/trunk/include/clang/Basic/Attr.td cfe/trunk/include/clang/Basic/AttrDocs.td cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td cfe/trunk/lib/AST/ExprConstant.cpp cfe/trunk/lib/CodeGen/CGBlocks.cpp cfe/trunk/lib/CodeGen/CGCall.cpp cfe/trunk/lib/CodeGen/CodeGenFunction.h cfe/trunk/lib/CodeGen/CodeGenModule.h cfe/trunk/lib/Sema/SemaDeclAttr.cpp cfe/trunk/test/CodeGenCXX/block-in-ctor-dtor.cpp cfe/trunk/test/CodeGenCXX/global-init.cpp cfe/trunk/test/CodeGenOpenCL/cl20-device-side-enqueue.cl cfe/trunk/test/SemaCXX/constant-expression-cxx11.cpp Modified: cfe/trunk/include/clang/Basic/Attr.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=290149&r1=290148&r2=290149&view=diff == --- cfe/trunk/include/clang/Basic/Attr.td (original) +++ cfe/trunk/include/clang/Basic/Attr.td Mon Dec 19 19:05:42 2016 @@ -780,6 +780,15 @@ def EmptyBases : InheritableAttr, Target let Documentation = [EmptyBasesDocs]; } +def AllocSize : InheritableAttr { + let Spellings = [GCC<"alloc_size">]; + let Subjects = SubjectList<[HasFunctionProto], WarnDiag, + "ExpectedFunctionWithProtoType">; + let Args = [IntArgument<"ElemSizeParam">, IntArgument<"NumElemsParam", 1>]; + let TemplateDependent = 1; + let Documentation = [AllocSizeDocs]; +} + def EnableIf : InheritableAttr { let Spellings = [GNU<"enable_if">]; let Subjects = SubjectList<[Function]>; Modified: cfe/trunk/include/clang/Basic/AttrDocs.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=290149&r1=290148&r2=290149&view=diff == --- cfe/trunk/include/clang/Basic/AttrDocs.td (original) +++ cfe/trunk/include/clang/Basic/AttrDocs.td Mon Dec 19 19:05:42 2016 @@ -206,6 +206,44 @@ to enforce the provided alignment assump }]; } +def AllocSizeDocs : Documentation { + let Category = DocCatFunction; + let Content = [{ +The ``alloc_size`` attribute can be placed on functions that return pointers in +order to hint to the compiler how many bytes of memory will be available at the +returned poiner. ``alloc_size`` takes one or two arguments. + +- ``alloc_size(N)`` implies that argument number N equals the number of + available bytes at the returned pointer. +- ``alloc_size(N, M)`` implies that the product of argument number N and + argument number M equals the number of available bytes at the returned + pointer. + +Argument numbers are 1-based. + +An example of how to use ``alloc_size`` + +.. code-block:: c + + void *my_malloc(int a) __attribute__((alloc_size(1))); + void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2))); + + int main() { +void *const p = my_malloc(100); +assert(__builtin_object_size(p, 0) == 100); +void *const a = my_calloc(20, 5); +assert(__builtin_object_size(a, 0) == 100); + } + +.. Note:: This attribute works differently in clang than it does in GCC. + Specifically, clang will only trace ``const`` pointers (as above); we give up + on pointers that are not marked as ``const``. In the vast majority of cases, + this is unimportant, because LLVM has support for the ``alloc_size`` + attribute. However, this may cause mildly unintuitive behavior when used with + other attributes, such as ``enable_if``. + }]; +} + def EnableIfDocs : Documentation { let Category = DocCatFunction; let Content = [{ Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=290149&r1=290148&r2=290149&view=diff == --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original) +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
r290297 - Add the alloc_size attribute to clang, attempt 2.
Author: gbiv Date: Wed Dec 21 20:50:20 2016 New Revision: 290297 URL: http://llvm.org/viewvc/llvm-project?rev=290297&view=rev Log: Add the alloc_size attribute to clang, attempt 2. This is a recommit of r290149, which was reverted in r290169 due to msan failures. msan was failing because we were calling `isMostDerivedAnUnsizedArray` on an invalid designator, which caused us to read uninitialized memory. To fix this, the logic of the caller of said function was simplified, and we now have a `!Invalid` assert in `isMostDerivedAnUnsizedArray`, so we can catch this particular bug more easily in the future. Fingers crossed that this patch sticks this time. :) Original commit message: This patch does three things: - Gives us the alloc_size attribute in clang, which lets us infer the number of bytes handed back to us by malloc/realloc/calloc/any user functions that act in a similar manner. - Teaches our constexpr evaluator that evaluating some `const` variables is OK sometimes. This is why we have a change in test/SemaCXX/constant-expression-cxx11.cpp and other seemingly unrelated tests. Richard Smith okay'ed this idea some time ago in person. - Uniques some Blocks in CodeGen, which was reviewed separately at D26410. Lack of uniquing only really shows up as a problem when combined with our new eagerness in the face of const. Added: cfe/trunk/test/CodeGen/alloc-size.c cfe/trunk/test/CodeGenCXX/alloc-size.cpp cfe/trunk/test/Sema/alloc-size.c Modified: cfe/trunk/include/clang/Basic/Attr.td cfe/trunk/include/clang/Basic/AttrDocs.td cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td cfe/trunk/lib/AST/ExprConstant.cpp cfe/trunk/lib/CodeGen/CGBlocks.cpp cfe/trunk/lib/CodeGen/CGCall.cpp cfe/trunk/lib/CodeGen/CodeGenFunction.h cfe/trunk/lib/CodeGen/CodeGenModule.h cfe/trunk/lib/Sema/SemaDeclAttr.cpp cfe/trunk/test/CodeGenCXX/block-in-ctor-dtor.cpp cfe/trunk/test/CodeGenCXX/global-init.cpp cfe/trunk/test/CodeGenOpenCL/cl20-device-side-enqueue.cl cfe/trunk/test/SemaCXX/constant-expression-cxx11.cpp Modified: cfe/trunk/include/clang/Basic/Attr.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=290297&r1=290296&r2=290297&view=diff == --- cfe/trunk/include/clang/Basic/Attr.td (original) +++ cfe/trunk/include/clang/Basic/Attr.td Wed Dec 21 20:50:20 2016 @@ -780,6 +780,15 @@ def EmptyBases : InheritableAttr, Target let Documentation = [EmptyBasesDocs]; } +def AllocSize : InheritableAttr { + let Spellings = [GCC<"alloc_size">]; + let Subjects = SubjectList<[HasFunctionProto], WarnDiag, + "ExpectedFunctionWithProtoType">; + let Args = [IntArgument<"ElemSizeParam">, IntArgument<"NumElemsParam", 1>]; + let TemplateDependent = 1; + let Documentation = [AllocSizeDocs]; +} + def EnableIf : InheritableAttr { let Spellings = [GNU<"enable_if">]; let Subjects = SubjectList<[Function]>; Modified: cfe/trunk/include/clang/Basic/AttrDocs.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=290297&r1=290296&r2=290297&view=diff == --- cfe/trunk/include/clang/Basic/AttrDocs.td (original) +++ cfe/trunk/include/clang/Basic/AttrDocs.td Wed Dec 21 20:50:20 2016 @@ -206,6 +206,44 @@ to enforce the provided alignment assump }]; } +def AllocSizeDocs : Documentation { + let Category = DocCatFunction; + let Content = [{ +The ``alloc_size`` attribute can be placed on functions that return pointers in +order to hint to the compiler how many bytes of memory will be available at the +returned poiner. ``alloc_size`` takes one or two arguments. + +- ``alloc_size(N)`` implies that argument number N equals the number of + available bytes at the returned pointer. +- ``alloc_size(N, M)`` implies that the product of argument number N and + argument number M equals the number of available bytes at the returned + pointer. + +Argument numbers are 1-based. + +An example of how to use ``alloc_size`` + +.. code-block:: c + + void *my_malloc(int a) __attribute__((alloc_size(1))); + void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2))); + + int main() { +void *const p = my_malloc(100); +assert(__builtin_object_size(p, 0) == 100); +void *const a = my_calloc(20, 5); +assert(__builtin_object_size(a, 0) == 100); + } + +.. Note:: This attribute works differently in clang than it does in GCC. + Specifically, clang will only trace ``const`` pointers (as above); we give up + on pointers that are not marked as ``const``. In the vast majority of cases, + this is unimportant, because LLVM has support for the ``alloc_size`` + attribute. However, this may cause mildly unintuitive behavior when used with + other attributes, such as ``enable_if``. + }]; +} + def EnableIfDocs : Documenta
r290353 - Make alloc_size only applicable to Functions.
Author: gbiv Date: Thu Dec 22 12:48:34 2016 New Revision: 290353 URL: http://llvm.org/viewvc/llvm-project?rev=290353&view=rev Log: Make alloc_size only applicable to Functions. I don't remember why I didn't make alloc_size only applicable to Functions a year ago, but I can't see any compelling reason not to do so now. Fixes PR31453. Modified: cfe/trunk/include/clang/Basic/Attr.td cfe/trunk/test/Sema/alloc-size.c Modified: cfe/trunk/include/clang/Basic/Attr.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=290353&r1=290352&r2=290353&view=diff == --- cfe/trunk/include/clang/Basic/Attr.td (original) +++ cfe/trunk/include/clang/Basic/Attr.td Thu Dec 22 12:48:34 2016 @@ -782,8 +782,7 @@ def EmptyBases : InheritableAttr, Target def AllocSize : InheritableAttr { let Spellings = [GCC<"alloc_size">]; - let Subjects = SubjectList<[HasFunctionProto], WarnDiag, - "ExpectedFunctionWithProtoType">; + let Subjects = SubjectList<[Function]>; let Args = [IntArgument<"ElemSizeParam">, IntArgument<"NumElemsParam", 1>]; let TemplateDependent = 1; let Documentation = [AllocSizeDocs]; Modified: cfe/trunk/test/Sema/alloc-size.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/alloc-size.c?rev=290353&r1=290352&r2=290353&view=diff == --- cfe/trunk/test/Sema/alloc-size.c (original) +++ cfe/trunk/test/Sema/alloc-size.c Thu Dec 22 12:48:34 2016 @@ -14,10 +14,12 @@ void *fail8(int a, int b) __attribute__( int fail9(int a) __attribute__((alloc_size(1))); //expected-warning{{'alloc_size' attribute only applies to return values that are pointers}} -int fail10 __attribute__((alloc_size(1))); //expected-warning{{'alloc_size' attribute only applies to non-K&R-style functions}} +int fail10 __attribute__((alloc_size(1))); //expected-warning{{'alloc_size' attribute only applies to functions}} void *fail11(void *a) __attribute__((alloc_size(1))); //expected-error{{'alloc_size' attribute argument may only refer to a function parameter of integer type}} void *fail12(int a) __attribute__((alloc_size("abc"))); //expected-error{{'alloc_size' attribute requires parameter 1 to be an integer constant}} void *fail12(int a) __attribute__((alloc_size(1, "abc"))); //expected-error{{'alloc_size' attribute requires parameter 2 to be an integer constant}} void *fail13(int a) __attribute__((alloc_size(1U<<31))); //expected-error{{integer constant expression evaluates to value 2147483648 that cannot be represented in a 32-bit signed integer type}} + +int (*PR31453)(int) __attribute__((alloc_size(1))); //expected-warning{{'alloc_size' attribute only applies to functions}} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r290356 - Fix warning introduced by r290297.
Author: gbiv Date: Thu Dec 22 13:00:31 2016 New Revision: 290356 URL: http://llvm.org/viewvc/llvm-project?rev=290356&view=rev Log: Fix warning introduced by r290297. Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=290356&r1=290355&r2=290356&view=diff == --- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original) +++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Thu Dec 22 13:00:31 2016 @@ -256,7 +256,7 @@ static bool checkPositiveIntArgument(Sem if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx)) return false; - if (UVal > std::numeric_limits::max()) { + if (UVal > (uint32_t)std::numeric_limits::max()) { llvm::APSInt I(32); // for toString I = UVal; S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r290169 - Revert r290149: Add the alloc_size attribute to clang.
Yes, this was reapplied in r290297 with fixes for the msan issue we caught; these asan unit test failures are news to me. Can you give me the command that you're using to run these tests, please? On Thu, Dec 22, 2016 at 11:10 AM, Dimitry Andric wrote: > On 20 Dec 2016, at 09:28, Chandler Carruth via cfe-commits < > cfe-commits@lists.llvm.org> wrote: > > Author: chandlerc > > Date: Tue Dec 20 02:28:19 2016 > > New Revision: 290169 > > > > URL: http://llvm.org/viewvc/llvm-project?rev=290169&view=rev > > Log: > > Revert r290149: Add the alloc_size attribute to clang. > > > > This commit fails MSan when running test/CodeGen/object-size.c in > > a confusing way. After some discussion with George, it isn't really > > clear what is going on here. We can make the MSan failure go away by > > testing for the invalid bit, but *why* things are invalid isn't clear. > > And yet, other code in the surrounding area is doing precisely this and > > testing for invalid. > > > > George is going to take a closer look at this to better understand the > > nature of the failure and recommit it, for now backing it out to clean > > up MSan builds. > > Hmm, was this reapplied later on? I'm still getting the following > AddressSanitizer failures on FreeBSD, and bisecting has pointed to r290149 > as the cause: > > FAIL: AddressSanitizer-Unit :: Asan-i386-inline-Test/AddressS > anitizer.ReallocFreedPointerTest (2124 of 30204) > TEST 'AddressSanitizer-Unit :: > Asan-i386-inline-Test/AddressSanitizer.ReallocFreedPointerTest' FAILED > > Note: Google Test filter = AddressSanitizer.ReallocFreedPointerTest > [==] Running 1 test from 1 test case. > [--] Global test environment set-up. > [--] 1 test from AddressSanitizer > [ RUN ] AddressSanitizer.ReallocFreedPointerTest > /share/dim/src/llvm/trunk/projects/compiler-rt/lib/asan/tests/asan_test.cc:377: > Failure > Death test: ptr = realloc(ptr, 77) > Result: failed to die. > Error msg: > [ DEATH ] > [ FAILED ] AddressSanitizer.ReallocFreedPointerTest (30 ms) > [--] 1 test from AddressSanitizer (30 ms total) > > [--] Global test environment tear-down > [==] 1 test from 1 test case ran. (31 ms total) > [ PASSED ] 0 tests. > [ FAILED ] 1 test, listed below: > [ FAILED ] AddressSanitizer.ReallocFreedPointerTest > > 1 FAILED TEST > YOU HAVE 24 DISABLED TESTS > > > > Testing: 0 . > FAIL: AddressSanitizer-Unit :: Asan-i386-with-calls-Test/Addr > essSanitizer.ReallocFreedPointerTest (2233 of 30204) > TEST 'AddressSanitizer-Unit :: > Asan-i386-with-calls-Test/AddressSanitizer.ReallocFreedPointerTest' > FAILED > Note: Google Test filter = AddressSanitizer.ReallocFreedPointerTest > [==] Running 1 test from 1 test case. > [--] Global test environment set-up. > [--] 1 test from AddressSanitizer > [ RUN ] AddressSanitizer.ReallocFreedPointerTest > /share/dim/src/llvm/trunk/projects/compiler-rt/lib/asan/tests/asan_test.cc:377: > Failure > Death test: ptr = realloc(ptr, 77) > Result: failed to die. > Error msg: > [ DEATH ] > [ FAILED ] AddressSanitizer.ReallocFreedPointerTest (24 ms) > [--] 1 test from AddressSanitizer (24 ms total) > > [--] Global test environment tear-down > [==] 1 test from 1 test case ran. (25 ms total) > [ PASSED ] 0 tests. > [ FAILED ] 1 test, listed below: > [ FAILED ] AddressSanitizer.ReallocFreedPointerTest > > 1 FAILED TEST > YOU HAVE 24 DISABLED TESTS > > > > Testing: 0 . > FAIL: AddressSanitizer-i386-freebsd :: TestCases/Posix/free_hook_realloc.cc > (2399 of 30204) > TEST 'AddressSanitizer-i386-freebsd :: > TestCases/Posix/free_hook_realloc.cc' FAILED > Script: > -- > /home/dim/obj/llvm-290338-trunk-freebsd12-i386-ninja-rel-1/./bin/clang > --driver-mode=g++ -fsanitize=address -mno-omit-leaf-frame-pointer > -fno-omit-frame-pointer -fno-optimize-sibling-calls -gline-tables-only -m32 > -O2 /share/dim/src/llvm/trunk/projects/compiler-rt/test/asan/Tes > tCases/Posix/free_hook_realloc.cc -o /home/dim/obj/llvm-290338-trun > k-freebsd12-i386-ninja-rel-1/projects/compiler-rt/test/asan/ > I386FreeBSDConfig/TestCases/Posix/Output/free_hook_realloc.cc.tmp > /home/dim/obj/llvm-290338-trunk-freebsd12-i386-ninja-rel-1/p > rojects/compiler-rt/test/asan/I386FreeBSDConfig/TestCases/ > Posix/Output/free_hook_realloc.cc.tmp 2>&1 | FileCheck > /share/dim/src/llvm/trunk/projects/compiler-rt/test/asan/Tes > tCases/Posix/free_hook_realloc.cc > -- > Exit Code: 2 > > Command Output (stderr): > -- > FileCheck error: '-' is empty. > FileCheck command line: FileCheck /share/dim/src/llvm/trunk/proj > ects/compiler-rt/test/asan/TestCases/Posix/free_hook_realloc.cc > > -- > > > Testing: 0 .. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90.. > Testing Time: 880.55s >
Re: r290169 - Revert r290149: Add the alloc_size attribute to clang.
Okay, I'm seeing this failure now if I tag my system's `realloc` declaration with `alloc_size`. (Which FreeBSD seems to do in their headers). Because all that clang does with `alloc_size` is use it to answer `__builtin_object_size` queries and lower it to LLVM's `allocsize` attribute, this is presumably a latent bug in LLVM's `allocsize` attribute. Let me mess around for a bit and see what I can dig up. :) On Thu, Dec 22, 2016 at 11:59 AM, Dimitry Andric wrote: > This is when running "ninja check-all", in a tree with llvm, clang and > compiler-rt checked out. The first program that shows a failure is > projects/compiler-rt/lib/asan/tests/default/Asan-i386-inline-Test: > > [==] Running 92 tests from 3 test cases. > [--] Global test environment set-up. > [--] 14 tests from AddressSanitizerInterface > ... > [ RUN ] AddressSanitizer.ReallocFreedPointerTest > /share/dim/src/llvm/trunk/projects/compiler-rt/lib/asan/tests/asan_test.cc:377: > Failure > Death test: ptr = realloc(ptr, 77) > Result: failed to die. > Error msg: > [ DEATH ] > [ FAILED ] AddressSanitizer.ReallocFreedPointerTest (48 ms) > > A similar failure shows when running projects/compiler-rt/lib/asan/ > tests/default/Asan-i386-with-calls-Test: > > [==] Running 92 tests from 3 test cases. > [--] Global test environment set-up. > [--] 14 tests from AddressSanitizerInterface > ... > [ RUN ] AddressSanitizer.ReallocFreedPointerTest > /share/dim/src/llvm/trunk/projects/compiler-rt/lib/asan/tests/asan_test.cc:377: > Failure > Death test: ptr = realloc(ptr, 77) > Result: failed to die. > Error msg: > [ DEATH ] > [ FAILED ] AddressSanitizer.ReallocFreedPointerTest (55 ms) > > Interestingly, the Asan-i386-inline-Noinst-Test and > Asan-i386-with-calls-Noinst-Test do not show this particular failure. > > The other test that fails is projects/compiler-rt/test/asan > /I386FreeBSDConfig/TestCases/Posix/Output/free_hook_realloc.cc.tmp, which > simply returns 1 without printing any output. Debugging the program shows > that it seems to be skipping completely over the realloc() call, and > jumping directly to the _exit(1), but this may be due to optimization. > > -Dimitry > > > On 22 Dec 2016, at 20:27, George Burgess IV > wrote: > > > > Yes, this was reapplied in r290297 with fixes for the msan issue we > caught; these asan unit test failures are news to me. Can you give me the > command that you're using to run these tests, please? > > > > On Thu, Dec 22, 2016 at 11:10 AM, Dimitry Andric > wrote: > > On 20 Dec 2016, at 09:28, Chandler Carruth via cfe-commits < > cfe-commits@lists.llvm.org> wrote: > > > Author: chandlerc > > > Date: Tue Dec 20 02:28:19 2016 > > > New Revision: 290169 > > > > > > URL: http://llvm.org/viewvc/llvm-project?rev=290169&view=rev > > > Log: > > > Revert r290149: Add the alloc_size attribute to clang. > > > > > > This commit fails MSan when running test/CodeGen/object-size.c in > > > a confusing way. After some discussion with George, it isn't really > > > clear what is going on here. We can make the MSan failure go away by > > > testing for the invalid bit, but *why* things are invalid isn't clear. > > > And yet, other code in the surrounding area is doing precisely this and > > > testing for invalid. > > > > > > George is going to take a closer look at this to better understand the > > > nature of the failure and recommit it, for now backing it out to clean > > > up MSan builds. > > > > Hmm, was this reapplied later on? I'm still getting the following > AddressSanitizer failures on FreeBSD, and bisecting has pointed to r290149 > as the cause: > > > > FAIL: AddressSanitizer-Unit :: Asan-i386-inline-Test/AddressS > anitizer.ReallocFreedPointerTest (2124 of 30204) > > TEST 'AddressSanitizer-Unit :: > Asan-i386-inline-Test/AddressSanitizer.ReallocFreedPointerTest' FAILED > > > Note: Google Test filter = AddressSanitizer.ReallocFreedPointerTest > > [==] Running 1 test from 1 test case. > > [--] Global test environment set-up. > > [--] 1 test from AddressSanitizer > > [ RUN ] AddressSanitizer.ReallocFreedPointerTest > > /share/dim/src/llvm/trunk/projects/compiler-rt/lib/asan/tests/asan_test.cc:377: > Failure > > Death test: ptr = realloc(ptr, 77) > > Result: failed to die. > > Error msg: > > [ DEATH ] > > [ FAILED ] AddressSanitizer.ReallocFreedPointerTest (30 ms) > > [--] 1 test from AddressSanitizer (30 ms total) > > > > [--] Global test environment tear-down > > [==] 1 test from 1 test case ran. (31 ms total) > > [ PASSED ] 0 tests. > > [ FAILED ] 1 test, listed below: > > [ FAILED ] AddressSanitizer.ReallocFreedPointerTest > > > > 1 FAILED TEST > > YOU HAVE 24 DISABLED TESTS > > > > > > > > Testing: 0 . > > FAIL: AddressSanitizer-Unit :: Asan-i386-with-calls-Test/Addr > essSanitizer.ReallocFreedPointerTest (2233 of 30204)
Re: r290169 - Revert r290149: Add the alloc_size attribute to clang.
It looks like the root of this is that we're treating calls to `allocsize` functions as AllocLike (e.g. any allocation function type except realloc) functions, which caused us to perform invalid optimizations. For example, in ReallocFreedPointerTest, EarlyCSE DCE'd the realloc because llvm::isInstructionTriviallyDead calls llvm::isAllocLikeFn, and isAllocLikeFn would return true if it saw the allocsize attribute. It really shouldn't do that. r290397 should fix this behavior by making allocsize alone insufficient to consider a function an allocation function. Thanks for your help! On Thu, Dec 22, 2016 at 1:10 PM, George Burgess IV < george.burgess...@gmail.com> wrote: > Okay, I'm seeing this failure now if I tag my system's `realloc` > declaration with `alloc_size`. (Which FreeBSD seems to do in their > headers). Because all that clang does with `alloc_size` is use it to answer > `__builtin_object_size` queries and lower it to LLVM's `allocsize` > attribute, this is presumably a latent bug in LLVM's `allocsize` attribute. > > Let me mess around for a bit and see what I can dig up. :) > > On Thu, Dec 22, 2016 at 11:59 AM, Dimitry Andric > wrote: > >> This is when running "ninja check-all", in a tree with llvm, clang and >> compiler-rt checked out. The first program that shows a failure is >> projects/compiler-rt/lib/asan/tests/default/Asan-i386-inline-Test: >> >> [==] Running 92 tests from 3 test cases. >> [--] Global test environment set-up. >> [--] 14 tests from AddressSanitizerInterface >> ... >> [ RUN ] AddressSanitizer.ReallocFreedPointerTest >> /share/dim/src/llvm/trunk/projects/compiler-rt/lib/asan/tests/asan_test.cc:377: >> Failure >> Death test: ptr = realloc(ptr, 77) >> Result: failed to die. >> Error msg: >> [ DEATH ] >> [ FAILED ] AddressSanitizer.ReallocFreedPointerTest (48 ms) >> >> A similar failure shows when running projects/compiler-rt/lib/asan/ >> tests/default/Asan-i386-with-calls-Test: >> >> [==] Running 92 tests from 3 test cases. >> [--] Global test environment set-up. >> [--] 14 tests from AddressSanitizerInterface >> ... >> [ RUN ] AddressSanitizer.ReallocFreedPointerTest >> /share/dim/src/llvm/trunk/projects/compiler-rt/lib/asan/tests/asan_test.cc:377: >> Failure >> Death test: ptr = realloc(ptr, 77) >> Result: failed to die. >> Error msg: >> [ DEATH ] >> [ FAILED ] AddressSanitizer.ReallocFreedPointerTest (55 ms) >> >> Interestingly, the Asan-i386-inline-Noinst-Test and >> Asan-i386-with-calls-Noinst-Test do not show this particular failure. >> >> The other test that fails is projects/compiler-rt/test/asan >> /I386FreeBSDConfig/TestCases/Posix/Output/free_hook_realloc.cc.tmp, >> which simply returns 1 without printing any output. Debugging the program >> shows that it seems to be skipping completely over the realloc() call, and >> jumping directly to the _exit(1), but this may be due to optimization. >> >> -Dimitry >> >> > On 22 Dec 2016, at 20:27, George Burgess IV < >> george.burgess...@gmail.com> wrote: >> > >> > Yes, this was reapplied in r290297 with fixes for the msan issue we >> caught; these asan unit test failures are news to me. Can you give me the >> command that you're using to run these tests, please? >> > >> > On Thu, Dec 22, 2016 at 11:10 AM, Dimitry Andric >> wrote: >> > On 20 Dec 2016, at 09:28, Chandler Carruth via cfe-commits < >> cfe-commits@lists.llvm.org> wrote: >> > > Author: chandlerc >> > > Date: Tue Dec 20 02:28:19 2016 >> > > New Revision: 290169 >> > > >> > > URL: http://llvm.org/viewvc/llvm-project?rev=290169&view=rev >> > > Log: >> > > Revert r290149: Add the alloc_size attribute to clang. >> > > >> > > This commit fails MSan when running test/CodeGen/object-size.c in >> > > a confusing way. After some discussion with George, it isn't really >> > > clear what is going on here. We can make the MSan failure go away by >> > > testing for the invalid bit, but *why* things are invalid isn't clear. >> > > And yet, other code in the surrounding area is doing precisely this >> and >> > > testing for invalid. >> > > >> > > George is going to take a closer look at this to better understand the >> > > nature of the failure and recommit it, for now backing it out to clean >> > > up MSan builds. >> > >> > Hmm, was this reapplied later on? I'm still getting the following >> AddressSanitizer failures on FreeBSD, and bisecting has pointed to r290149 >> as the cause: >> > >> > FAIL: AddressSanitizer-Unit :: Asan-i386-inline-Test/AddressS >> anitizer.ReallocFreedPointerTest (2124 of 30204) >> > TEST 'AddressSanitizer-Unit :: >> Asan-i386-inline-Test/AddressSanitizer.ReallocFreedPointerTest' FAILED >> >> > Note: Google Test filter = AddressSanitizer.ReallocFreedPointerTest >> > [==] Running 1 test from 1 test case. >> > [--] Global test environment set-up. >> > [--] 1 test from AddressSanitizer >> > [ RUN ] AddressSa
r290577 - Add a test for `const` folding introduced by r290297. NFC.
Author: gbiv Date: Mon Dec 26 22:01:22 2016 New Revision: 290577 URL: http://llvm.org/viewvc/llvm-project?rev=290577&view=rev Log: Add a test for `const` folding introduced by r290297. NFC. AFAICT, we didn't add a test targeted at the new "const can sometimes act as constexpr" behavior introduced by r290297. Modified: cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp Modified: cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp?rev=290577&r1=290576&r2=290577&view=diff == --- cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp (original) +++ cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp Mon Dec 26 22:01:22 2016 @@ -957,3 +957,20 @@ namespace PR27989 { } static_assert(f(0) == 1, ""); } + +namespace const_char { +template +constexpr int sum(const char (&Arr)[N]) { + static_assert(N >= M, ""); + int S = 0; + for (unsigned I = 0; I != M; ++I) +S += Arr[I]; + return S; +} + +// As an extension, we support evaluating some things that are `const` as though +// they were `constexpr`. +const char Cs[] = {'a', 'b', 'c'}; +const int N = 2; +static_assert(sum(Cs) == 'a' + 'b', ""); +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r290577 - Add a test for `const` folding introduced by r290297. NFC.
SG; working on a follow-up now. Thanks! On Mon, Dec 26, 2016 at 8:26 PM, Richard Smith wrote: > On 26 December 2016 at 20:01, George Burgess IV via cfe-commits < > cfe-commits@lists.llvm.org> wrote: > >> Author: gbiv >> Date: Mon Dec 26 22:01:22 2016 >> New Revision: 290577 >> >> URL: http://llvm.org/viewvc/llvm-project?rev=290577&view=rev >> Log: >> Add a test for `const` folding introduced by r290297. NFC. >> >> AFAICT, we didn't add a test targeted at the new "const can sometimes >> act as constexpr" behavior introduced by r290297. >> >> Modified: >> cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp >> >> Modified: cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp >> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/c >> onstant-expression-cxx1y.cpp?rev=290577&r1=290576&r2=290577&view=diff >> >> == >> --- cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp (original) >> +++ cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp Mon Dec 26 >> 22:01:22 2016 >> @@ -957,3 +957,20 @@ namespace PR27989 { >>} >>static_assert(f(0) == 1, ""); >> } >> + >> +namespace const_char { >> +template >> +constexpr int sum(const char (&Arr)[N]) { >> + static_assert(N >= M, ""); >> + int S = 0; >> + for (unsigned I = 0; I != M; ++I) >> +S += Arr[I]; >> + return S; >> +} >> + >> +// As an extension, we support evaluating some things that are `const` >> as though >> +// they were `constexpr`. >> +const char Cs[] = {'a', 'b', 'c'}; >> +const int N = 2; >> +static_assert(sum(Cs) == 'a' + 'b', ""); >> +} > > > Hold on, this test should fail. It's OK to extend the set of things we can > constant-fold, but formal constant expression checking still needs to be > strict. (You should produce a CCEDiag from within the constant expression > evaluator to mark things that are not core constant expressions but are > permitted as an extension.) > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r290584 - Emit CCEDiags when evaluating a const variable.
Author: gbiv Date: Mon Dec 26 23:33:20 2016 New Revision: 290584 URL: http://llvm.org/viewvc/llvm-project?rev=290584&view=rev Log: Emit CCEDiags when evaluating a const variable. This addresses post-review feedback from r290577. Modified: cfe/trunk/lib/AST/ExprConstant.cpp cfe/trunk/test/SemaCXX/constant-expression-cxx11.cpp cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp Modified: cfe/trunk/lib/AST/ExprConstant.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=290584&r1=290583&r2=290584&view=diff == --- cfe/trunk/lib/AST/ExprConstant.cpp (original) +++ cfe/trunk/lib/AST/ExprConstant.cpp Mon Dec 26 23:33:20 2016 @@ -2903,7 +2903,7 @@ static CompleteObject findCompleteObject // All the remaining cases only permit reading. Info.FFDiag(E, diag::note_constexpr_modify_global); return CompleteObject(); - } else if (VD->isConstexpr() || BaseType.isConstQualified()) { + } else if (VD->isConstexpr()) { // OK, we can read this variable. } else if (BaseType->isIntegralOrEnumerationType()) { // In OpenCL if a variable is in constant address space it is a const value. @@ -2928,6 +2928,9 @@ static CompleteObject findCompleteObject } else { Info.CCEDiag(E); } + } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { +Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; +// Keep evaluating to see what we can do. } else { // FIXME: Allow folding of values of any literal type in all languages. if (Info.checkingPotentialConstantExpression() && Modified: cfe/trunk/test/SemaCXX/constant-expression-cxx11.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/constant-expression-cxx11.cpp?rev=290584&r1=290583&r2=290584&view=diff == --- cfe/trunk/test/SemaCXX/constant-expression-cxx11.cpp (original) +++ cfe/trunk/test/SemaCXX/constant-expression-cxx11.cpp Mon Dec 26 23:33:20 2016 @@ -1195,7 +1195,7 @@ struct S { int j : f(0); // expected-error {{constant expression}} expected-note {{in call to 'f(0)'}} int k : g(0); // expected-error {{constant expression}} expected-note {{temporary created here}} expected-note {{in call to 'g(0)'}} int l : n3; // expected-error {{constant expression}} expected-note {{read of non-const variable}} - int m : t.n; // expected-warning{{width of bit-field 'm' (42 bits)}} + int m : t.n; // expected-warning{{width of bit-field 'm' (42 bits)}} expected-warning{{expression is not an integral constant expression}} expected-note{{read of non-constexpr variable 't' is not allowed}} }; } Modified: cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp?rev=290584&r1=290583&r2=290584&view=diff == --- cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp (original) +++ cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp Mon Dec 26 23:33:20 2016 @@ -959,18 +959,21 @@ namespace PR27989 { } namespace const_char { -template +template constexpr int sum(const char (&Arr)[N]) { - static_assert(N >= M, ""); int S = 0; - for (unsigned I = 0; I != M; ++I) -S += Arr[I]; + for (unsigned I = 0; I != N; ++I) +S += Arr[I]; // expected-note 2{{read of non-constexpr variable 'Cs' is not allowed}} return S; } // As an extension, we support evaluating some things that are `const` as though -// they were `constexpr`. -const char Cs[] = {'a', 'b', 'c'}; -const int N = 2; -static_assert(sum(Cs) == 'a' + 'b', ""); +// they were `constexpr` when folding, but it should not be allowed in normal +// constexpr evaluation. +const char Cs[] = {'a', 'b'}; +void foo() __attribute__((enable_if(sum(Cs) == 'a' + 'b', ""))); +void run() { foo(); } + +static_assert(sum(Cs) == 'a' + 'b', ""); // expected-error{{not an integral constant expression}} expected-note{{in call to 'sum(Cs)'}} +constexpr int S = sum(Cs); // expected-error{{must be initialized by a constant expression}} expected-note{{in call}} } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r290577 - Add a test for `const` folding introduced by r290297. NFC.
r290584 :) On Mon, Dec 26, 2016 at 8:30 PM, George Burgess IV < george.burgess...@gmail.com> wrote: > SG; working on a follow-up now. Thanks! > > On Mon, Dec 26, 2016 at 8:26 PM, Richard Smith > wrote: > >> On 26 December 2016 at 20:01, George Burgess IV via cfe-commits < >> cfe-commits@lists.llvm.org> wrote: >> >>> Author: gbiv >>> Date: Mon Dec 26 22:01:22 2016 >>> New Revision: 290577 >>> >>> URL: http://llvm.org/viewvc/llvm-project?rev=290577&view=rev >>> Log: >>> Add a test for `const` folding introduced by r290297. NFC. >>> >>> AFAICT, we didn't add a test targeted at the new "const can sometimes >>> act as constexpr" behavior introduced by r290297. >>> >>> Modified: >>> cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp >>> >>> Modified: cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp >>> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/c >>> onstant-expression-cxx1y.cpp?rev=290577&r1=290576&r2=290577&view=diff >>> >>> == >>> --- cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp (original) >>> +++ cfe/trunk/test/SemaCXX/constant-expression-cxx1y.cpp Mon Dec 26 >>> 22:01:22 2016 >>> @@ -957,3 +957,20 @@ namespace PR27989 { >>>} >>>static_assert(f(0) == 1, ""); >>> } >>> + >>> +namespace const_char { >>> +template >>> +constexpr int sum(const char (&Arr)[N]) { >>> + static_assert(N >= M, ""); >>> + int S = 0; >>> + for (unsigned I = 0; I != M; ++I) >>> +S += Arr[I]; >>> + return S; >>> +} >>> + >>> +// As an extension, we support evaluating some things that are `const` >>> as though >>> +// they were `constexpr`. >>> +const char Cs[] = {'a', 'b', 'c'}; >>> +const int N = 2; >>> +static_assert(sum(Cs) == 'a' + 'b', ""); >>> +} >> >> >> Hold on, this test should fail. It's OK to extend the set of things we >> can constant-fold, but formal constant expression checking still needs to >> be strict. (You should produce a CCEDiag from within the constant >> expression evaluator to mark things that are not core constant expressions >> but are permitted as an extension.) >> > > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r290661 - [CodeGen] Unique constant CompoundLiterals.
Author: gbiv Date: Wed Dec 28 01:27:40 2016 New Revision: 290661 URL: http://llvm.org/viewvc/llvm-project?rev=290661&view=rev Log: [CodeGen] Unique constant CompoundLiterals. Our newly aggressive constant folding logic makes it possible for CGExprConstant to see the same CompoundLiteralExpr more than once. So, emitting a new GlobalVariable every time we see a CompoundLiteral is no longer correct. We had a similar issue with BlockExprs that was caught while testing said aggressive folding, so I applied the same style of fix (see D26410) here. If we find yet another case where this needs to happen, we should probably refactor this so we don't have a third DenseMap+getter+setter. As a design note: getAddrOfConstantCompoundLiteralIfEmitted is really only intended to be called by ConstExprEmitter::EmitLValue. So, returning a GlobalVariable* instead of a ConstantAddress costs us effectively nothing, and saves us either a few bytes per entry in our map or a bit of code duplication. Modified: cfe/trunk/lib/CodeGen/CGExprConstant.cpp cfe/trunk/lib/CodeGen/CodeGenModule.h cfe/trunk/test/CodeGen/compound-literal.c Modified: cfe/trunk/lib/CodeGen/CGExprConstant.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprConstant.cpp?rev=290661&r1=290660&r2=290661&view=diff == --- cfe/trunk/lib/CodeGen/CGExprConstant.cpp (original) +++ cfe/trunk/lib/CodeGen/CGExprConstant.cpp Wed Dec 28 01:27:40 2016 @@ -1023,16 +1023,17 @@ public: switch (E->getStmtClass()) { default: break; case Expr::CompoundLiteralExprClass: { - // Note that due to the nature of compound literals, this is guaranteed - // to be the only use of the variable, so we just generate it here. CompoundLiteralExpr *CLE = cast(E); + CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType()); + if (llvm::GlobalVariable *Addr = + CGM.getAddrOfConstantCompoundLiteralIfEmitted(CLE)) +return ConstantAddress(Addr, Align); + llvm::Constant* C = CGM.EmitConstantExpr(CLE->getInitializer(), CLE->getType(), CGF); // FIXME: "Leaked" on failure. if (!C) return ConstantAddress::invalid(); - CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType()); - auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(), E->getType().isConstant(CGM.getContext()), llvm::GlobalValue::InternalLinkage, @@ -1040,6 +1041,7 @@ public: llvm::GlobalVariable::NotThreadLocal, CGM.getContext().getTargetAddressSpace(E->getType())); GV->setAlignment(Align.getQuantity()); + CGM.setAddrOfConstantCompoundLiteral(CLE, GV); return ConstantAddress(GV, Align); } case Expr::StringLiteralClass: @@ -1492,6 +1494,18 @@ CodeGenModule::EmitConstantValueForMemor return C; } +llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted( +const CompoundLiteralExpr *E) { + return EmittedCompoundLiterals.lookup(E); +} + +void CodeGenModule::setAddrOfConstantCompoundLiteral( +const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) { + bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second; + (void)Ok; + assert(Ok && "CLE has already been emitted!"); +} + ConstantAddress CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) { assert(E->isFileScope() && "not a file-scope compound literal expr"); Modified: cfe/trunk/lib/CodeGen/CodeGenModule.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.h?rev=290661&r1=290660&r2=290661&view=diff == --- cfe/trunk/lib/CodeGen/CodeGenModule.h (original) +++ cfe/trunk/lib/CodeGen/CodeGenModule.h Wed Dec 28 01:27:40 2016 @@ -455,6 +455,10 @@ private: bool isTriviallyRecursive(const FunctionDecl *F); bool shouldEmitFunction(GlobalDecl GD); + /// Map used to be sure we don't emit the same CompoundLiteral twice. + llvm::DenseMap + EmittedCompoundLiterals; + /// Map of the global blocks we've emitted, so that we don't have to re-emit /// them if the constexpr evaluator gets aggressive. llvm::DenseMap EmittedGlobalBlocks; @@ -824,6 +828,16 @@ public: /// compound literal expression. ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E); + /// If it's been emitted already, returns the GlobalVariable corresponding to + /// a compound literal. Otherwise, returns null. + llvm::GlobalVariable * + getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E); + + /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already + /// emitted. + void setAddrOfConstantCompoundLiteral(cons
r290916 - Re-add objectsize function/incomplete type checks.
Author: gbiv Date: Tue Jan 3 17:35:19 2017 New Revision: 290916 URL: http://llvm.org/viewvc/llvm-project?rev=290916&view=rev Log: Re-add objectsize function/incomplete type checks. I accidentally omitted these when refactoring this code. This caused problems when building parts of the test-suite on MacOS. Modified: cfe/trunk/lib/AST/ExprConstant.cpp cfe/trunk/test/CodeGen/object-size.c Modified: cfe/trunk/lib/AST/ExprConstant.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=290916&r1=290915&r2=290916&view=diff == --- cfe/trunk/lib/AST/ExprConstant.cpp (original) +++ cfe/trunk/lib/AST/ExprConstant.cpp Tue Jan 3 17:35:19 2017 @@ -7192,6 +7192,12 @@ static bool determineEndOffset(EvalInfo CharUnits &EndOffset) { bool DetermineForCompleteObject = refersToCompleteObject(LVal); + auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { +if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) + return false; +return HandleSizeof(Info, ExprLoc, Ty, Result); + }; + // We want to evaluate the size of the entire object. This is a valid fallback // for when Type=1 and the designator is invalid, because we're asked for an // upper-bound. @@ -7209,7 +7215,7 @@ static bool determineEndOffset(EvalInfo return false; QualType BaseTy = getObjectType(LVal.getLValueBase()); -return !BaseTy.isNull() && HandleSizeof(Info, ExprLoc, BaseTy, EndOffset); +return CheckedHandleSizeof(BaseTy, EndOffset); } // We want to evaluate the size of a subobject. @@ -7238,7 +7244,7 @@ static bool determineEndOffset(EvalInfo } CharUnits BytesPerElem; - if (!HandleSizeof(Info, ExprLoc, Designator.MostDerivedType, BytesPerElem)) + if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) return false; // According to the GCC documentation, we want the size of the subobject Modified: cfe/trunk/test/CodeGen/object-size.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/object-size.c?rev=290916&r1=290915&r2=290916&view=diff == --- cfe/trunk/test/CodeGen/object-size.c (original) +++ cfe/trunk/test/CodeGen/object-size.c Tue Jan 3 17:35:19 2017 @@ -536,3 +536,16 @@ void PR30346() { // CHECK: store i32 14 gi = __builtin_object_size(sa->sa_data, 3); } + +extern char incomplete_char_array[]; +// CHECK-LABEL: @incomplete_and_function_types +int incomplete_and_function_types() { + // CHECK: call i64 @llvm.objectsize.i64.p0i8 + gi = __builtin_object_size(incomplete_char_array, 0); + // CHECK: call i64 @llvm.objectsize.i64.p0i8 + gi = __builtin_object_size(incomplete_char_array, 1); + // CHECK: call i64 @llvm.objectsize.i64.p0i8 + gi = __builtin_object_size(incomplete_char_array, 2); + // CHECK: store i32 0 + gi = __builtin_object_size(incomplete_char_array, 3); +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r290991 - [Sema] Replace remove_if+erase with erase_if. NFC.
Author: gbiv Date: Wed Jan 4 13:16:29 2017 New Revision: 290991 URL: http://llvm.org/viewvc/llvm-project?rev=290991&view=rev Log: [Sema] Replace remove_if+erase with erase_if. NFC. Modified: cfe/trunk/lib/Sema/SemaCUDA.cpp cfe/trunk/lib/Sema/SemaOverload.cpp Modified: cfe/trunk/lib/Sema/SemaCUDA.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCUDA.cpp?rev=290991&r1=290990&r2=290991&view=diff == --- cfe/trunk/lib/Sema/SemaCUDA.cpp (original) +++ cfe/trunk/lib/Sema/SemaCUDA.cpp Wed Jan 4 13:16:29 2017 @@ -228,10 +228,8 @@ void Sema::EraseUnwantedCUDAMatches( [&](const Pair &M1, const Pair &M2) { return GetCFP(M1) < GetCFP(M2); })); // Erase all functions with lower priority. - Matches.erase( - llvm::remove_if( - Matches, [&](const Pair &Match) { return GetCFP(Match) < BestCFP; }), - Matches.end()); + llvm::erase_if(Matches, + [&](const Pair &Match) { return GetCFP(Match) < BestCFP; }); } /// When an implicitly-declared special member has to invoke more than one Modified: cfe/trunk/lib/Sema/SemaOverload.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=290991&r1=290990&r2=290991&view=diff == --- cfe/trunk/lib/Sema/SemaOverload.cpp (original) +++ cfe/trunk/lib/Sema/SemaOverload.cpp Wed Jan 4 13:16:29 2017 @@ -8958,9 +8958,7 @@ OverloadCandidateSet::BestViableFunction S.IdentifyCUDAPreference(Caller, Cand->Function) == Sema::CFP_WrongSide; }; - Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), - IsWrongSideCandidate), - Candidates.end()); + llvm::erase_if(Candidates, IsWrongSideCandidate); } } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r291020 - [Parse] Don't ignore attributes after a late-parsed attr.
Author: gbiv Date: Wed Jan 4 16:43:01 2017 New Revision: 291020 URL: http://llvm.org/viewvc/llvm-project?rev=291020&view=rev Log: [Parse] Don't ignore attributes after a late-parsed attr. Without this, we drop everything after the first late-parsed attribute in a single __attribute__. (Where "drop" means "stuff everything into LA->Toks.") Modified: cfe/trunk/lib/Parse/ParseDecl.cpp cfe/trunk/test/Sema/warn-thread-safety-analysis.c Modified: cfe/trunk/lib/Parse/ParseDecl.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseDecl.cpp?rev=291020&r1=291019&r2=291020&view=diff == --- cfe/trunk/lib/Parse/ParseDecl.cpp (original) +++ cfe/trunk/lib/Parse/ParseDecl.cpp Wed Jan 4 16:43:01 2017 @@ -177,8 +177,12 @@ void Parser::ParseGNUAttributes(ParsedAt if (!ClassStack.empty() && !LateAttrs->parseSoon()) getCurrentClass().LateParsedDeclarations.push_back(LA); - // consume everything up to and including the matching right parens - ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false); + // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it + // recursively consumes balanced parens. + LA->Toks.push_back(Tok); + ConsumeParen(); + // Consume everything up to and including the matching right parens. + ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true); Token Eof; Eof.startToken(); Modified: cfe/trunk/test/Sema/warn-thread-safety-analysis.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-thread-safety-analysis.c?rev=291020&r1=291019&r2=291020&view=diff == --- cfe/trunk/test/Sema/warn-thread-safety-analysis.c (original) +++ cfe/trunk/test/Sema/warn-thread-safety-analysis.c Wed Jan 4 16:43:01 2017 @@ -127,3 +127,7 @@ int main() { return 0; } + +// We had a problem where we'd skip all attributes that follow a late-parsed +// attribute in a single __attribute__. +void run() __attribute__((guarded_by(mu1), guarded_by(mu1))); // expected-warning 2{{only applies to fields and global variables}} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r291058 - [Sema] Mark undefined ctors as deleted. NFC.
Author: gbiv Date: Wed Jan 4 19:21:21 2017 New Revision: 291058 URL: http://llvm.org/viewvc/llvm-project?rev=291058&view=rev Log: [Sema] Mark undefined ctors as deleted. NFC. Looks like these functions exist just to prevent bad implicit conversions. Rather than waiting for the linker to complain about undefined references to them, we can mark them as deleted. Modified: cfe/trunk/include/clang/Sema/Ownership.h Modified: cfe/trunk/include/clang/Sema/Ownership.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Ownership.h?rev=291058&r1=291057&r2=291058&view=diff == --- cfe/trunk/include/clang/Sema/Ownership.h (original) +++ cfe/trunk/include/clang/Sema/Ownership.h Wed Jan 4 19:21:21 2017 @@ -153,8 +153,8 @@ namespace clang { ActionResult(const DiagnosticBuilder &) : Val(PtrTy()), Invalid(true) {} // These two overloads prevent void* -> bool conversions. -ActionResult(const void *); -ActionResult(volatile void *); +ActionResult(const void *) = delete; +ActionResult(volatile void *) = delete; bool isInvalid() const { return Invalid; } bool isUsable() const { return !Invalid && Val; } @@ -192,8 +192,8 @@ namespace clang { ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) { } // These two overloads prevent void* -> bool conversions. -ActionResult(const void *); -ActionResult(volatile void *); +ActionResult(const void *) = delete; +ActionResult(volatile void *) = delete; bool isInvalid() const { return PtrWithInvalid & 0x01; } bool isUsable() const { return PtrWithInvalid > 0x01; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r291264 - Clean up redundant isa before getAs. NFC.
Author: gbiv Date: Fri Jan 6 13:10:48 2017 New Revision: 291264 URL: http://llvm.org/viewvc/llvm-project?rev=291264&view=rev Log: Clean up redundant isa before getAs. NFC. Modified: cfe/trunk/lib/CodeGen/CGCall.cpp Modified: cfe/trunk/lib/CodeGen/CGCall.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=291264&r1=291263&r2=291264&view=diff == --- cfe/trunk/lib/CodeGen/CGCall.cpp (original) +++ cfe/trunk/lib/CodeGen/CGCall.cpp Fri Jan 6 13:10:48 2017 @@ -393,15 +393,13 @@ CodeGenTypes::arrangeFunctionDeclaration // When declaring a function without a prototype, always use a // non-variadic type. - if (isa(FTy)) { -CanQual noProto = FTy.getAs(); + if (CanQual noProto = FTy.getAs()) { return arrangeLLVMFunctionInfo( noProto->getReturnType(), /*instanceMethod=*/false, /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All); } - assert(isa(FTy)); - return arrangeFreeFunctionType(FTy.getAs(), FD); + return arrangeFreeFunctionType(FTy.castAs(), FD); } /// Arrange the argument and result information for the declaration or ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r291418 - Add the diagnose_if attribute to clang.
Author: gbiv Date: Sun Jan 8 22:12:14 2017 New Revision: 291418 URL: http://llvm.org/viewvc/llvm-project?rev=291418&view=rev Log: Add the diagnose_if attribute to clang. `diagnose_if` can be used to have clang emit either warnings or errors for function calls that meet user-specified conditions. For example: ``` constexpr int foo(int a) __attribute__((diagnose_if(a > 10, "configurations with a > 10 are " "expensive.", "warning"))); int f1 = foo(9); int f2 = foo(10); // warning: configuration with a > 10 are expensive. int f3 = foo(f2); ``` It currently only emits diagnostics in cases where the condition is guaranteed to always be true. So, the following code will emit no warnings: ``` constexpr int bar(int a) { foo(a); return 0; } constexpr int i = bar(10); ``` We hope to support optionally emitting diagnostics for cases like that (and emitting runtime checks) in the future. Release notes will appear shortly. :) Differential Revision: https://reviews.llvm.org/D27424 Added: cfe/trunk/test/Sema/diagnose_if.c cfe/trunk/test/SemaCXX/diagnose_if.cpp Modified: cfe/trunk/include/clang/AST/Expr.h cfe/trunk/include/clang/Basic/Attr.td cfe/trunk/include/clang/Basic/AttrDocs.td cfe/trunk/include/clang/Basic/DiagnosticCommonKinds.td cfe/trunk/include/clang/Basic/DiagnosticGroups.td cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td cfe/trunk/include/clang/Sema/Initialization.h cfe/trunk/include/clang/Sema/Overload.h cfe/trunk/include/clang/Sema/Sema.h cfe/trunk/lib/AST/ExprConstant.cpp cfe/trunk/lib/Sema/SemaDeclAttr.cpp cfe/trunk/lib/Sema/SemaExpr.cpp cfe/trunk/lib/Sema/SemaLookup.cpp cfe/trunk/lib/Sema/SemaOverload.cpp cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp Modified: cfe/trunk/include/clang/AST/Expr.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Expr.h?rev=291418&r1=291417&r2=291418&view=diff == --- cfe/trunk/include/clang/AST/Expr.h (original) +++ cfe/trunk/include/clang/AST/Expr.h Sun Jan 8 22:12:14 2017 @@ -651,7 +651,8 @@ public: /// constant. bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, -ArrayRef Args) const; +ArrayRef Args, +const Expr *This = nullptr) const; /// \brief If the current Expr is a pointer, this will try to statically /// determine the number of bytes available where the pointer is pointing. Modified: cfe/trunk/include/clang/Basic/Attr.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=291418&r1=291417&r2=291418&view=diff == --- cfe/trunk/include/clang/Basic/Attr.td (original) +++ cfe/trunk/include/clang/Basic/Attr.td Sun Jan 8 22:12:14 2017 @@ -140,12 +140,15 @@ class Argument : Argument; +class BoolArgument : Argument; class IdentifierArgument : Argument; class IntArgument : Argument; class StringArgument : Argument; class ExprArgument : Argument; -class FunctionArgument : Argument; +class FunctionArgument : Argument; class TypeArgument : Argument; class UnsignedArgument : Argument; class VariadicUnsignedArgument : Argument; @@ -1591,6 +1594,26 @@ def Unavailable : InheritableAttr { let Documentation = [Undocumented]; } +def DiagnoseIf : InheritableAttr { + let Spellings = [GNU<"diagnose_if">]; + let Subjects = SubjectList<[Function]>; + let Args = [ExprArgument<"Cond">, StringArgument<"Message">, + EnumArgument<"DiagnosticType", + "DiagnosticType", + ["error", "warning"], + ["DT_Error", "DT_Warning"]>, + BoolArgument<"ArgDependent", 0, /*fake*/ 1>, + FunctionArgument<"Parent", 0, /*fake*/ 1>]; + let DuplicatesAllowedWhileMerging = 1; + let LateParsed = 1; + let AdditionalMembers = [{ +bool isError() const { return diagnosticType == DT_Error; } +bool isWarning() const { return diagnosticType == DT_Warning; } + }]; + let TemplateDependent = 1; + let Documentation = [DiagnoseIfDocs]; +} + def ArcWeakrefUnavailable : InheritableAttr { let Spellings = [GNU<"objc_arc_weak_reference_unavailable">]; let Subjects = SubjectList<[ObjCInterface], ErrorDiag>; Modified: cfe/trunk/include/clang/Basic/AttrDocs.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=291418&r1=291417&r2=291418&view=diff == --- cfe/trunk/include/clang/Basic/AttrDocs.td (original) +++ cfe/trunk/include/clang/Basic/AttrDocs.td Sun Jan 8 22:12:14 2017 @@ -378,6 +378,65 @@ template instantiation, so the value for }]; } +def Diagnose
r291422 - Add release notes for `diagnose_if`
Author: gbiv Date: Sun Jan 8 23:58:18 2017 New Revision: 291422 URL: http://llvm.org/viewvc/llvm-project?rev=291422&view=rev Log: Add release notes for `diagnose_if` Bots seem happy with `diagnose_if` so far, so I'm optimistically adding release notes for it. Modified: cfe/trunk/docs/ReleaseNotes.rst Modified: cfe/trunk/docs/ReleaseNotes.rst URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=291422&r1=291421&r2=291422&view=diff == --- cfe/trunk/docs/ReleaseNotes.rst (original) +++ cfe/trunk/docs/ReleaseNotes.rst Sun Jan 8 23:58:18 2017 @@ -47,6 +47,10 @@ sections with improvements to Clang's su Major New Features -- +- The ``diagnose_if`` attribute has been added to clang. This attribute allows + clang to emit a warning or error if a function call meets one or more + user-specified conditions. + - ... Improvements to Clang's diagnostics ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r291058 - [Sema] Mark undefined ctors as deleted. NFC.
That's a good point, but I don't think they're a big issue: this code has apparently been this way since 2010, and I only hit this problem because I was blindly adding `const` to things and looking for what broke. :) If someone feels differently, I'm happy to swap this to use SFINAE magic. On Mon, Jan 9, 2017 at 8:34 AM, David Blaikie wrote: > Alternatively could make the bool ctor a template with some SFINAE to > restrict it to only parameters of type bool - thus blocking all conversions > there, if they're particularly problematic. > > On Wed, Jan 4, 2017 at 5:32 PM George Burgess IV via cfe-commits < > cfe-commits@lists.llvm.org> wrote: > >> Author: gbiv >> Date: Wed Jan 4 19:21:21 2017 >> New Revision: 291058 >> >> URL: http://llvm.org/viewvc/llvm-project?rev=291058&view=rev >> Log: >> [Sema] Mark undefined ctors as deleted. NFC. >> >> Looks like these functions exist just to prevent bad implicit >> conversions. Rather than waiting for the linker to complain about >> undefined references to them, we can mark them as deleted. >> >> Modified: >> cfe/trunk/include/clang/Sema/Ownership.h >> >> Modified: cfe/trunk/include/clang/Sema/Ownership.h >> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/ >> Sema/Ownership.h?rev=291058&r1=291057&r2=291058&view=diff >> >> == >> --- cfe/trunk/include/clang/Sema/Ownership.h (original) >> +++ cfe/trunk/include/clang/Sema/Ownership.h Wed Jan 4 19:21:21 2017 >> @@ -153,8 +153,8 @@ namespace clang { >> ActionResult(const DiagnosticBuilder &) : Val(PtrTy()), >> Invalid(true) {} >> >> // These two overloads prevent void* -> bool conversions. >> -ActionResult(const void *); >> -ActionResult(volatile void *); >> +ActionResult(const void *) = delete; >> +ActionResult(volatile void *) = delete; >> >> bool isInvalid() const { return Invalid; } >> bool isUsable() const { return !Invalid && Val; } >> @@ -192,8 +192,8 @@ namespace clang { >> ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) { } >> >> // These two overloads prevent void* -> bool conversions. >> -ActionResult(const void *); >> -ActionResult(volatile void *); >> +ActionResult(const void *) = delete; >> +ActionResult(volatile void *) = delete; >> >> bool isInvalid() const { return PtrWithInvalid & 0x01; } >> bool isUsable() const { return PtrWithInvalid > 0x01; } >> >> >> ___ >> cfe-commits mailing list >> cfe-commits@lists.llvm.org >> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits >> > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r291493 - Add a test for diagnose_if.
Author: gbiv Date: Mon Jan 9 16:43:16 2017 New Revision: 291493 URL: http://llvm.org/viewvc/llvm-project?rev=291493&view=rev Log: Add a test for diagnose_if. Forgot to add this file as a part of r291418. Added: cfe/trunk/test/SemaCXX/diagnose_if-ext.cpp Added: cfe/trunk/test/SemaCXX/diagnose_if-ext.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/diagnose_if-ext.cpp?rev=291493&view=auto == --- cfe/trunk/test/SemaCXX/diagnose_if-ext.cpp (added) +++ cfe/trunk/test/SemaCXX/diagnose_if-ext.cpp Mon Jan 9 16:43:16 2017 @@ -0,0 +1,8 @@ +// RUN: %clang_cc1 -Wpedantic -fsyntax-only %s -verify + +void foo() __attribute__((diagnose_if(1, "", "error"))); // expected-warning{{'diagnose_if' is a clang extension}} +void foo(int a) __attribute__((diagnose_if(a, "", "error"))); // expected-warning{{'diagnose_if' is a clang extension}} +// FIXME: When diagnose_if gets a CXX11 spelling, this should be enabled. +#if 0 +[[clang::diagnose_if(a, "", "error")]] void foo(double a); +#endif ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r279702 - Remove a pointless LLVM_CONSTEXPR. NFC.
Author: gbiv Date: Wed Aug 24 20:54:37 2016 New Revision: 279702 URL: http://llvm.org/viewvc/llvm-project?rev=279702&view=rev Log: Remove a pointless LLVM_CONSTEXPR. NFC. Modified: cfe/trunk/lib/AST/ASTContext.cpp Modified: cfe/trunk/lib/AST/ASTContext.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTContext.cpp?rev=279702&r1=279701&r2=279702&view=diff == --- cfe/trunk/lib/AST/ASTContext.cpp (original) +++ cfe/trunk/lib/AST/ASTContext.cpp Wed Aug 24 20:54:37 2016 @@ -653,7 +653,7 @@ ASTContext::getCanonicalTemplateTemplate assert(!TTP->getRequiresClause() && "Unexpected requires-clause on template template-parameter"); - LLVM_CONSTEXPR Expr *const CanonRequiresClause = nullptr; + Expr *const CanonRequiresClause = nullptr; TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r280269 - Fix a typo in a comment.
Author: gbiv Date: Wed Aug 31 13:14:15 2016 New Revision: 280269 URL: http://llvm.org/viewvc/llvm-project?rev=280269&view=rev Log: Fix a typo in a comment. Modified: cfe/trunk/include/clang/Sema/Sema.h Modified: cfe/trunk/include/clang/Sema/Sema.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=280269&r1=280268&r2=280269&view=diff == --- cfe/trunk/include/clang/Sema/Sema.h (original) +++ cfe/trunk/include/clang/Sema/Sema.h Wed Aug 31 13:14:15 2016 @@ -8711,8 +8711,8 @@ public: /// are not compatible, but we accept them as an extension. IncompatiblePointer, -/// IncompatiblePointer - The assignment is between two pointers types which -/// point to integers which have a different sign, but are otherwise +/// IncompatiblePointerSign - The assignment is between two pointers types +/// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D24113: Allow implicit conversions between incompatible pointer types in overload resolution in C.
george.burgess.iv created this revision. george.burgess.iv added a reviewer: rsmith. george.burgess.iv added a subscriber: cfe-commits. In C, we allow pointer conversions like: ``` void foo(int *a); long b; void runFoo() { foo(&b); } ``` ...But not when overloading: ``` int bar(char *a) __attribute__((overloadable)); int bar(struct{}) __attribute__((overloadable)); unsigned char d; void runBar() { bar(&d); } // error: no matching function for call to 'bar' ``` This patch makes it so `bar(&d)` isn't an error. A few notes: - We'll still emit a warning about the conversion, assuming the user hasn't opted out of said warnings. - Every such conversion is ranked as the worst possible thing. So, if there's any ambiguity at all (e.g. if bar had a `void(signed char*)` overload, as well), we'll still emit an error. - We consider conversions that drop qualifiers to be equally as bad as converting between incompatible pointer types. I'm happy to make conversions that only drop qualifiers preferred over incompatible pointer types, if that would be better. https://reviews.llvm.org/D24113 Files: include/clang/Basic/AttrDocs.td include/clang/Sema/Overload.h lib/Sema/SemaExprCXX.cpp lib/Sema/SemaOverload.cpp test/CodeGen/builtins-systemz-zvector-error.c test/CodeGen/overloadable.c test/Sema/overloadable.c test/Sema/pass-object-size.c test/SemaOpenCL/event_t_overload.cl Index: test/SemaOpenCL/event_t_overload.cl === --- test/SemaOpenCL/event_t_overload.cl +++ test/SemaOpenCL/event_t_overload.cl @@ -1,11 +1,11 @@ // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -void __attribute__((overloadable)) foo(event_t, __local char *); // expected-note {{candidate function not viable: no known conversion from '__global int *' to '__local char *' for 2nd argument}} -void __attribute__((overloadable)) foo(event_t, __local float *); // expected-note {{candidate function not viable: no known conversion from '__global int *' to '__local float *' for 2nd argument}} +void __attribute__((overloadable)) foo(event_t, __local char *); // expected-note {{candidate function}} +void __attribute__((overloadable)) foo(event_t, __local float *); // expected-note {{candidate function}} void kernel ker(__local char *src1, __local float *src2, __global int *src3) { event_t evt; foo(evt, src1); foo(0, src2); - foo(evt, src3); // expected-error {{no matching function for call to 'foo'}} + foo(evt, src3); // expected-error {{call to 'foo' is ambiguous}} } Index: test/Sema/pass-object-size.c === --- test/Sema/pass-object-size.c +++ test/Sema/pass-object-size.c @@ -52,5 +52,5 @@ int P; (&NotOverloaded)(&P); //expected-error{{cannot take address of function 'NotOverloaded' because parameter 1 has pass_object_size attribute}} - (&IsOverloaded)(&P); //expected-error{{no matching function}} expected-note@35{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@36{{candidate function not viable: no known conversion from 'int *' to 'char *' for 1st argument}} + (&IsOverloaded)(&P); //expected-warning{{incompatible pointer types passing 'int *' to parameter of type 'char *'}} expected-note@36{{passing argument to parameter 'p' here}} } Index: test/Sema/overloadable.c === --- test/Sema/overloadable.c +++ test/Sema/overloadable.c @@ -23,7 +23,7 @@ void test_funcptr(int (*f1)(int, double), int (*f2)(int, float)) { float *fp = accept_funcptr(f1); - accept_funcptr(f2); // expected-error{{no matching function for call to 'accept_funcptr'}} + accept_funcptr(f2); // expected-error{{call to 'accept_funcptr' is ambiguous}} } struct X { int x; float y; }; @@ -122,3 +122,32 @@ void *specific_disabled = &disabled; } + +void incompatible_pointer_type_conversions() { + char charbuf[1]; + unsigned char ucharbuf[1]; + int intbuf[1]; + + void foo(char *c) __attribute__((overloadable)); + void foo(short *c) __attribute__((overloadable)); + foo(charbuf); + foo(ucharbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@131{{candidate function}} expected-note@132{{candidate function}} + foo(intbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@131{{candidate function}} expected-note@132{{candidate function}} + + void bar(unsigned char *c) __attribute__((overloadable)); + void bar(signed char *c) __attribute__((overloadable)); + bar(charbuf); // expected-error{{call to 'bar' is ambiguous}} expected-note@137{{candidate function}} expected-note@138{{candidate function}} + bar(ucharbuf); + bar(intbuf); // expected-error{{call to 'bar' is ambiguous}} expected-note@137{{candidate function}} expected-note@138{{candidate function}} +} + +void dropping_qualifiers_is_incompatible() { + const char ccharbuf[1]; + vola
r280333 - Fix typos in comments.
Author: gbiv Date: Wed Aug 31 20:26:58 2016 New Revision: 280333 URL: http://llvm.org/viewvc/llvm-project?rev=280333&view=rev Log: Fix typos in comments. Modified: cfe/trunk/lib/Sema/SemaExprObjC.cpp Modified: cfe/trunk/lib/Sema/SemaExprObjC.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprObjC.cpp?rev=280333&r1=280332&r2=280333&view=diff == --- cfe/trunk/lib/Sema/SemaExprObjC.cpp (original) +++ cfe/trunk/lib/Sema/SemaExprObjC.cpp Wed Aug 31 20:26:58 2016 @@ -2645,7 +2645,7 @@ ExprResult Sema::BuildInstanceMessage(Ex CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/, true/*CheckTheOther*/, typeBound); if (!Methods.empty()) { -// We chose the first method as the initial condidate, then try to +// We choose the first method as the initial candidate, then try to // select a better one. Method = Methods[0]; @@ -2701,7 +2701,7 @@ ExprResult Sema::BuildInstanceMessage(Ex false/*InstanceFirst*/, true/*CheckTheOther*/); if (!Methods.empty()) { - // We chose the first method as the initial condidate, then try + // We choose the first method as the initial candidate, then try // to select a better one. Method = Methods[0]; @@ -2789,7 +2789,7 @@ ExprResult Sema::BuildInstanceMessage(Ex true/*InstanceFirst*/, false/*CheckTheOther*/); if (!Methods.empty()) { -// We chose the first method as the initial condidate, then try +// We choose the first method as the initial candidate, then try // to select a better one. Method = Methods[0]; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: [PATCH] D24152: Support the overloadable attribute with _Generic expressions
george.burgess.iv added a subscriber: george.burgess.iv. george.burgess.iv added a comment. Just a drive-by nit. Thanks for the patch! Comment at: lib/Sema/SemaOverload.cpp:12996 @@ +12995,3 @@ + // selection expression. + std::vector AssocExprs(GSE->getAssocExprs().vec()); + unsigned ResultIdx = GSE->getResultIndex(); Is there a reason this isn't a `SmallVector` instead? https://reviews.llvm.org/D24152 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: [PATCH] D24152: Support the overloadable attribute with _Generic expressions
george.burgess.iv added inline comments. Comment at: lib/Sema/SemaOverload.cpp:12996 @@ +12995,3 @@ + // selection expression. + std::vector AssocExprs(GSE->getAssocExprs().vec()); + unsigned ResultIdx = GSE->getResultIndex(); aaron.ballman wrote: > dblaikie wrote: > > george.burgess.iv wrote: > > > Is there a reason this isn't a `SmallVector` instead? > > Another note on this - we should generally prefer copy init over direct > > init (less power, less responsibility/easier to read): > > > > std::vector AssocExprs = GSE->getAssocExprs().vec(); > > > > (& as for George's question: since ArrayRef::vec returns std::vector, it's > > cheaper to store in a std::vector (by move) than to make a copy into a > > SmallVector) > Yeah, I originally used std::vector<> because of ArrayRef's interface. I am > happy to go either route, depending on preference, as I doubt this will wind > up on the hot path with any regularity. > as for George's question: since ArrayRef::vec returns std::vector, it's > cheaper to store in a std::vector (by move) than to make a copy into a > SmallVector I was thinking that we would end up using the `SmallVector(begin(), end())` ctor instead, so the vector temp wouldn't be needed. :) Regardless, it was just a nit, so I'm perfectly happy if it stays a `vector`. > I doubt this will wind up on the hot path with any regularity Agreed. https://reviews.llvm.org/D24152 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: [PATCH] D24113: Allow implicit conversions between incompatible pointer types in overload resolution in C.
george.burgess.iv marked 2 inline comments as done. Comment at: lib/Sema/SemaOverload.cpp:1813-1815 @@ -1795,5 +1812,5 @@ // and we don't know what conversions it may overlap with. - SCS.First = ICK_C_Only_Conversion; - SCS.Second = ICK_C_Only_Conversion; - SCS.Third = ICK_C_Only_Conversion; + SCS.First = ImplicitConv; + SCS.Second = ImplicitConv; + SCS.Third = ImplicitConv; return true; rsmith wrote: > Yuck, this violates our invariants: `First` should only ever be some kind of > lvalue conversion (it should in this case be an `ICK_Array_To_Pointer` or > `ICK_Function_To_Pointer` if the argument was an array or function, > respectively, and otherwise `ICK_Identity`). `Third` should only ever be > `ICK_Identity` or `ICK_Qualification`. It seems fine to always set `Third` to > `ICK_Identity` and model the qualification change as part of the second > "standard" conversion; this should still compare worse than any other > sequence by the rank test. > > Now I've noticed this, I'd like to see it fixed, but since this is > pre-existing I don't mind whether we fix this as part of this change or > separately. I'll fix this in a follow-up commit; thanks for pointing it out! https://reviews.llvm.org/D24113 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r280553 - [Sema] Relax overloading restrictions in C.
Author: gbiv Date: Fri Sep 2 17:59:57 2016 New Revision: 280553 URL: http://llvm.org/viewvc/llvm-project?rev=280553&view=rev Log: [Sema] Relax overloading restrictions in C. This patch allows us to perform incompatible pointer conversions when resolving overloads in C. So, the following code will no longer fail to compile (though it will still emit warnings, assuming the user hasn't opted out of them): ``` void foo(char *) __attribute__((overloadable)); void foo(int) __attribute__((overloadable)); void callFoo() { unsigned char bar[128]; foo(bar); // selects the char* overload. } ``` These conversions are ranked below all others, so: A. Any other viable conversion will win out B. If we had another incompatible pointer conversion in the example above (e.g. `void foo(int *)`), we would complain about an ambiguity. Differential Revision: https://reviews.llvm.org/D24113 Modified: cfe/trunk/include/clang/Basic/AttrDocs.td cfe/trunk/include/clang/Sema/Overload.h cfe/trunk/lib/Sema/SemaExprCXX.cpp cfe/trunk/lib/Sema/SemaOverload.cpp cfe/trunk/test/CodeGen/builtins-systemz-zvector-error.c cfe/trunk/test/CodeGen/overloadable.c cfe/trunk/test/Sema/overloadable.c cfe/trunk/test/Sema/pass-object-size.c cfe/trunk/test/SemaOpenCL/event_t_overload.cl Modified: cfe/trunk/include/clang/Basic/AttrDocs.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=280553&r1=280552&r2=280553&view=diff == --- cfe/trunk/include/clang/Basic/AttrDocs.td (original) +++ cfe/trunk/include/clang/Basic/AttrDocs.td Fri Sep 2 17:59:57 2016 @@ -470,6 +470,11 @@ semantics: * A conversion from type ``T`` to a value of type ``U`` is permitted if ``T`` and ``U`` are compatible types. This conversion is given "conversion" rank. +* A conversion from a pointer of type ``T*`` to a pointer of type ``U*``, where + ``T`` and ``U`` are incompatible, is allowed, but is ranked below all other + types of conversions. Please note: ``U`` lacking qualifiers that are present + on ``T`` is sufficient for ``T`` and ``U`` to be incompatible. + The declaration of ``overloadable`` functions is restricted to function declarations and definitions. Most importantly, if any function with a given name is given the ``overloadable`` attribute, then all function declarations Modified: cfe/trunk/include/clang/Sema/Overload.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Overload.h?rev=280553&r1=280552&r2=280553&view=diff == --- cfe/trunk/include/clang/Sema/Overload.h (original) +++ cfe/trunk/include/clang/Sema/Overload.h Fri Sep 2 17:59:57 2016 @@ -84,6 +84,8 @@ namespace clang { ICK_Writeback_Conversion, ///< Objective-C ARC writeback conversion ICK_Zero_Event_Conversion, ///< Zero constant to event (OpenCL1.2 6.12.10) ICK_C_Only_Conversion, ///< Conversions allowed in C, but not C++ +ICK_Incompatible_Pointer_Conversion, ///< C-only conversion between pointers + /// with incompatible types ICK_Num_Conversion_Kinds, ///< The number of conversion kinds }; @@ -97,8 +99,10 @@ namespace clang { ICR_Conversion, ///< Conversion ICR_Complex_Real_Conversion, ///< Complex <-> Real conversion ICR_Writeback_Conversion,///< ObjC ARC writeback conversion -ICR_C_Conversion ///< Conversion only allowed in the C standard. +ICR_C_Conversion,///< Conversion only allowed in the C standard. /// (e.g. void* to char*) +ICR_C_Conversion_Extension ///< Conversion not allowed by the C standard, + /// but that we accept as an extension anyway. }; ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind); Modified: cfe/trunk/lib/Sema/SemaExprCXX.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprCXX.cpp?rev=280553&r1=280552&r2=280553&view=diff == --- cfe/trunk/lib/Sema/SemaExprCXX.cpp (original) +++ cfe/trunk/lib/Sema/SemaExprCXX.cpp Fri Sep 2 17:59:57 2016 @@ -3705,6 +3705,7 @@ Sema::PerformImplicitConversion(Expr *Fr case ICK_Qualification: case ICK_Num_Conversion_Kinds: case ICK_C_Only_Conversion: + case ICK_Incompatible_Pointer_Conversion: llvm_unreachable("Improper second standard conversion"); } Modified: cfe/trunk/lib/Sema/SemaOverload.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=280553&r1=280552&r2=280553&view=diff == --- cfe/trunk/lib/Sema/SemaOverload.cpp (original) +++ cfe/trunk/lib/Sema/SemaOverload.cpp Fri Sep 2 17:59:57 2016 @@ -136,7