31#include "llvm/ADT/APSInt.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/ScopeExit.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/SaveAndRestore.h"
48 IdentifierInfo *II =
nullptr;
54 PPValue(
unsigned BitWidth) : Val(BitWidth) {}
59 void setIdentifier(IdentifierInfo *II) { this->II = II; }
61 unsigned getBitWidth()
const {
return Val.getBitWidth(); }
62 bool isUnsigned()
const {
return Val.isUnsigned(); }
64 SourceRange
getRange()
const {
return Range; }
66 void setRange(SourceLocation L) { Range.
setBegin(L); Range.setEnd(L); }
67 void setRange(SourceLocation B, SourceLocation E) {
68 Range.setBegin(B); Range.setEnd(E);
70 void setBegin(SourceLocation L) { Range.setBegin(L); }
71 void setEnd(SourceLocation L) { Range.setEnd(L); }
77 Token &PeekTok,
bool ValueLive,
78 bool &IncludedUndefinedIds,
106 Result.setBegin(beginLoc);
113 if (PeekTok.
is(tok::l_paren)) {
119 if (PeekTok.
is(tok::code_completion)) {
134 Result.Val.setIsUnsigned(
false);
139 (II->
getName() ==
"INFINITY" || II->
getName() ==
"NAN") ?
true :
false);
142 if (
Result.Val != 0 && ValueLive)
146 Token macroToken(PeekTok);
154 if (PeekTok.
isNot(tok::r_paren)) {
156 <<
"'defined'" << tok::r_paren;
157 PP.
Diag(LParenLoc, diag::note_matching) << tok::l_paren;
188 bool IsFunctionTypeMacro =
208 if (IsFunctionTypeMacro)
209 PP.
Diag(beginLoc, diag::warn_defined_in_function_type_macro);
211 PP.
Diag(beginLoc, diag::warn_defined_in_object_type_macro);
216 Callbacks->Defined(macroToken,
Macro,
238 Result.setIdentifier(
nullptr);
240 if (PeekTok.
is(tok::code_completion)) {
257 if (II->
isStr(
"defined"))
265 unsigned DiagID = II->
getName() ==
"true"
266 ? diag::warn_pp_undef_true_identifier
267 : diag::warn_pp_undef_identifier;
268 PP.
Diag(PeekTok, DiagID) << II;
273 const std::vector<std::string> UndefPrefixes =
275 const StringRef IdentifierName = II->
getName();
276 if (llvm::any_of(UndefPrefixes,
277 [&IdentifierName](
const std::string &Prefix) {
278 return IdentifierName.starts_with(Prefix);
280 PP.
Diag(PeekTok, diag::warn_pp_undef_prefix)
285 Result.Val.setIsUnsigned(
false);
293 PP.
Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
298 PP.
Diag(PeekTok, diag::err_pp_expected_value_in_expr);
300 case tok::numeric_constant: {
302 bool NumberInvalid =
false;
303 StringRef Spelling = PP.
getSpelling(PeekTok, IntegerBuffer,
311 if (Literal.hadError)
314 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
315 PP.
Diag(PeekTok, diag::err_pp_illegal_floating_literal);
318 assert(Literal.isIntegerLiteral() &&
"Unknown ppnumber");
321 if (Literal.hasUDSuffix())
322 PP.
Diag(PeekTok, diag::err_pp_invalid_udl) << 1;
329 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
331 PP.
Diag(PeekTok, diag::ext_c99_longlong);
335 if (Literal.isSizeT) {
337 PP.
DiagCompat(PeekTok, diag_compat::size_t_suffix);
339 PP.
Diag(PeekTok, diag::err_cxx23_size_t_suffix);
345 if (Literal.isBitInt)
346 PP.
Diag(PeekTok, PP.
getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
348 ? diag::warn_c23_compat_bitint_suffix
349 : diag::ext_c23_bitint_suffix);
352 if (Literal.GetIntegerValue(
Result.Val)) {
354 PP.
Diag(PeekTok, diag::err_integer_literal_too_large) << 1;
355 Result.Val.setIsUnsigned(
true);
359 Result.Val.setIsUnsigned(Literal.isUnsigned);
365 if (!Literal.isUnsigned &&
Result.Val.isNegative()) {
368 if (ValueLive && Literal.getRadix() == 10)
369 PP.
Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed);
370 Result.Val.setIsUnsigned(
true);
379 case tok::char_constant:
380 case tok::wide_char_constant:
381 case tok::utf8_char_constant:
382 case tok::utf16_char_constant:
383 case tok::utf32_char_constant: {
386 PP.
Diag(PeekTok, diag::err_pp_invalid_udl) << 0;
389 bool CharInvalid =
false;
390 StringRef ThisTok = PP.
getSpelling(PeekTok, CharBuffer, &CharInvalid);
396 if (Literal.hadError())
402 if (Literal.isMultiChar())
404 else if (Literal.isWide())
406 else if (Literal.isUTF16())
408 else if (Literal.isUTF32())
414 llvm::APSInt Val(NumBits);
416 Val = Literal.getValue();
419 if (Literal.isWide())
421 else if (Literal.isUTF16() || Literal.isUTF32())
422 Val.setIsUnsigned(
true);
423 else if (Literal.isUTF8()) {
428 Val.setIsUnsigned(
true);
432 if (
Result.Val.getBitWidth() > Val.getBitWidth()) {
435 assert(
Result.Val.getBitWidth() == Val.getBitWidth() &&
436 "intmax_t smaller than char/wchar_t?");
437 Result.Val = std::move(Val);
454 if (PeekTok.
is(tok::r_paren)) {
462 if (PeekTok.
isNot(tok::r_paren)) {
465 PP.
Diag(Start, diag::note_matching) << tok::l_paren;
471 Result.setIdentifier(
nullptr);
481 Result.setIdentifier(
nullptr);
489 Result.setIdentifier(
nullptr);
495 bool Overflow = !
Result.isUnsigned() &&
Result.Val.isMinSignedValue();
498 if (Overflow && ValueLive)
499 PP.
Diag(Loc, diag::warn_pp_expr_overflow) <<
Result.getRange();
510 Result.setIdentifier(
nullptr);
525 Result.Val.setIsUnsigned(
false);
526 Result.setIdentifier(
nullptr);
537 Result.Val.setIsUnsigned(
false);
557 case tok::star:
return 14;
559 case tok::minus:
return 13;
561 case tok::greatergreater:
return 12;
564 case tok::greaterequal:
565 case tok::greater:
return 11;
566 case tok::exclaimequal:
567 case tok::equalequal:
return 10;
568 case tok::amp:
return 9;
569 case tok::caret:
return 8;
570 case tok::pipe:
return 7;
571 case tok::ampamp:
return 6;
572 case tok::pipepipe:
return 5;
573 case tok::question:
return 4;
574 case tok::comma:
return 3;
575 case tok::colon:
return 2;
576 case tok::r_paren:
return 0;
577 case tok::eod:
return 0;
583 if (
Tok.is(tok::l_paren) && LHS.getIdentifier())
584 PP.
Diag(LHS.getRange().getBegin(), diag::err_pp_expr_bad_token_lparen)
585 << LHS.getIdentifier();
587 PP.
Diag(
Tok.getLocation(), diag::err_pp_expr_bad_token_binop)
598 Token &PeekTok,
bool ValueLive,
599 bool &IncludedUndefinedIds,
603 IncludedUndefinedIds) {
610 if (PeekTok.
isNot(tok::eod))
617 if (PeekPrec == ~0
U) {
625 if (PeekPrec < MinPrec)
636 if (Operator == tok::ampamp && LHS.Val == 0)
638 else if (Operator == tok::pipepipe && LHS.Val != 0)
640 else if (Operator == tok::question && LHS.Val == 0)
643 RHSIsLive = ValueLive;
649 PPValue RHS(LHS.getBitWidth());
652 if (
EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP))
return true;
657 unsigned ThisPrec = PeekPrec;
661 if (PeekPrec == ~0
U) {
677 if (Operator == tok::question)
681 RHSPrec = ThisPrec+1;
683 if (PeekPrec >= RHSPrec) {
685 IncludedUndefinedIds, PP))
689 assert(PeekPrec <= ThisPrec &&
"Recursion didn't work!");
693 llvm::APSInt Res(LHS.getBitWidth());
697 case tok::greatergreater:
703 Res.setIsUnsigned(LHS.isUnsigned() || RHS.isUnsigned());
706 if (ValueLive && Res.isUnsigned()) {
707 if (!LHS.isUnsigned() && LHS.Val.isNegative())
708 PP.
Diag(OpLoc, diag::warn_pp_convert_to_positive) << 0
709 <<
toString(LHS.Val, 10,
true) +
" to " +
711 << LHS.getRange() << RHS.getRange();
712 if (!RHS.isUnsigned() && RHS.Val.isNegative())
713 PP.
Diag(OpLoc, diag::warn_pp_convert_to_positive) << 1
714 <<
toString(RHS.Val, 10,
true) +
" to " +
716 << LHS.getRange() << RHS.getRange();
718 LHS.Val.setIsUnsigned(Res.isUnsigned());
719 RHS.Val.setIsUnsigned(Res.isUnsigned());
722 bool Overflow =
false;
724 default: llvm_unreachable(
"Unknown operator token!");
727 Res = LHS.Val % RHS.Val;
728 else if (ValueLive) {
729 PP.
Diag(OpLoc, diag::err_pp_remainder_by_zero)
730 << LHS.getRange() << RHS.getRange();
736 if (LHS.Val.isSigned())
737 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow),
false);
739 Res = LHS.Val / RHS.Val;
740 }
else if (ValueLive) {
741 PP.
Diag(OpLoc, diag::err_pp_division_by_zero)
742 << LHS.getRange() << RHS.getRange();
749 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow),
false);
751 Res = LHS.Val * RHS.Val;
753 case tok::lessless: {
755 if (LHS.isUnsigned())
756 Res = LHS.Val.ushl_ov(RHS.Val, Overflow);
758 Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow),
false);
761 case tok::greatergreater: {
763 unsigned ShAmt =
static_cast<unsigned>(RHS.Val.getLimitedValue());
764 if (ShAmt >= LHS.getBitWidth()) {
766 ShAmt = LHS.getBitWidth()-1;
768 Res = LHS.Val >> ShAmt;
772 if (LHS.isUnsigned())
773 Res = LHS.Val + RHS.Val;
775 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow),
false);
778 if (LHS.isUnsigned())
779 Res = LHS.Val - RHS.Val;
781 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow),
false);
784 Res = LHS.Val <= RHS.Val;
785 Res.setIsUnsigned(
false);
788 Res = LHS.Val < RHS.Val;
789 Res.setIsUnsigned(
false);
791 case tok::greaterequal:
792 Res = LHS.Val >= RHS.Val;
793 Res.setIsUnsigned(
false);
796 Res = LHS.Val > RHS.Val;
797 Res.setIsUnsigned(
false);
799 case tok::exclaimequal:
800 Res = LHS.Val != RHS.Val;
801 Res.setIsUnsigned(
false);
803 case tok::equalequal:
804 Res = LHS.Val == RHS.Val;
805 Res.setIsUnsigned(
false);
808 Res = LHS.Val & RHS.Val;
811 Res = LHS.Val ^ RHS.Val;
814 Res = LHS.Val | RHS.Val;
817 Res = (LHS.Val != 0 && RHS.Val != 0);
818 Res.setIsUnsigned(
false);
821 Res = (LHS.Val != 0 || RHS.Val != 0);
822 Res.setIsUnsigned(
false);
828 PP.
Diag(OpLoc, diag::ext_pp_comma_expr)
829 << LHS.getRange() << RHS.getRange();
832 case tok::question: {
834 if (PeekTok.
isNot(tok::colon)) {
836 << tok::colon << LHS.getRange() << RHS.getRange();
837 PP.
Diag(OpLoc, diag::note_matching) << tok::question;
844 bool AfterColonLive = ValueLive && LHS.Val == 0;
845 PPValue AfterColonVal(LHS.getBitWidth());
847 if (
EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
853 PeekTok, AfterColonLive,
854 IncludedUndefinedIds, PP))
858 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
859 RHS.setEnd(AfterColonVal.getRange().getEnd());
863 Res.setIsUnsigned(RHS.isUnsigned() || AfterColonVal.isUnsigned());
871 PP.
Diag(OpLoc, diag::err_pp_colon_without_question)
872 << LHS.getRange() << RHS.getRange();
877 if (Overflow && ValueLive)
878 PP.
Diag(OpLoc, diag::warn_pp_expr_overflow)
879 << LHS.getRange() << RHS.getRange();
883 LHS.setEnd(RHS.getRange().getEnd());
884 RHS.setIdentifier(
nullptr);
891Preprocessor::DirectiveEvalResult
892Preprocessor::EvaluateDirectiveExpression(
IdentifierInfo *&IfNDefMacro,
895 SaveAndRestore PPDir(ParsingIfOrElifDirective,
true);
902 llvm::scope_exit RestoreMacroExpansion(
903 [
this, Old = DisableMacroExpansion] { DisableMacroExpansion = Old; });
904 DisableMacroExpansion =
false;
912 PPValue ResVal(BitWidth);
914 SourceLocation ExprStartLoc = SourceMgr.getExpansionLoc(
Tok.
getLocation());
923 return {std::nullopt,
934 if (
Tok.
is(tok::eod)) {
940 bool IsNonZero = ResVal.Val != 0;
941 SourceRange ValRange = ResVal.getRange();
954 return {std::nullopt,
964 Diag(
Tok, diag::err_pp_expected_eol);
971 bool IsNonZero = ResVal.Val != 0;
972 SourceRange ValRange = ResVal.getRange();
976Preprocessor::DirectiveEvalResult
977Preprocessor::EvaluateDirectiveExpression(
IdentifierInfo *&IfNDefMacro,
980 bool EvaluatedDefined;
981 return EvaluateDirectiveExpression(IfNDefMacro,
Tok, EvaluatedDefined,
985static std::optional<CXXStandardLibraryVersionInfo>
992 const Token &RevisionDateTok =
Macro->getReplacementToken(0);
996 llvm::StringRef RevisionDate =
1001 if (!RevisionDate.consumeInteger(10,
Value))
1009 if (!CXXStandardLibraryVersion)
1012 if (!CXXStandardLibraryVersion)
1013 return std::nullopt;
1015 if (CXXStandardLibraryVersion->Lib ==
1017 return CXXStandardLibraryVersion->Version;
1018 return std::nullopt;
1022 CXXStandardLibraryVersion = {
1029 assert(FixedVersion >= 2000'00'00 && FixedVersion <= 2100'00'00 &&
1030 "invalid value for __GLIBCXX__");
1034 return *Ver < FixedVersion;
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
static uint32_t getBitWidth(const Expr *E)
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the PPCallbacks interface.
static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, bool ValueLive, Preprocessor &PP)
EvaluateValue - Evaluate the token PeekTok (and any others needed) and return the computed value in R...
static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS, Token &Tok)
static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, Token &PeekTok, bool ValueLive, bool &IncludedUndefinedIds, Preprocessor &PP)
EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is PeekTok,...
static std::optional< CXXStandardLibraryVersionInfo > getCXXStandardLibraryVersion(Preprocessor &PP, IdentifierInfo *MacroName, CXXStandardLibraryVersionInfo::Library Lib)
static unsigned getPrecedence(tok::TokenKind Kind)
getPrecedence - Return the precedence of the specified binary operator token.
static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT, bool ValueLive, Preprocessor &PP)
EvaluateDefined - Process a 'defined(sym)' expression.
static StringRef getIdentifier(const Token &Tok)
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the clang::TokenKind enum and support functions.
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
void setBegin(SourceLocation b)
virtual void CodeCompleteMacroName(bool IsDefinition)
Callback invoked when performing code completion in a context where the name of a macro is expected.
virtual void CodeCompletePreprocessorExpression()
Callback invoked when performing code completion in a preprocessor expression, such as the condition ...
std::vector< std::string > UndefPrefixes
The list of prefixes from -Wundef-prefix=... used to generate warnings for undefined macros.
Concrete class used by the front-end to report problems and issues.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
One of these records is kept for each identifier that is lexed.
bool isCPlusPlusOperatorKeyword() const
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
A description of the current definition of a macro.
Encapsulates the data about a macro definition (e.g.
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
This interface provides a way to observe the actions of the preprocessor as it does its thing.
bool SingleFileParseMode
When enabled, preprocessor is in a mode for parsing a single file only.
bool SingleModuleParseMode
When enabled, preprocessor is in a mode for parsing a single module only.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void setStdLibCxxVersion(std::uint64_t Version)
PPCallbacks * getPPCallbacks() const
SourceRange DiscardUntilEndOfDirective(SmallVectorImpl< Token > *DiscardedToks=nullptr)
Read and discard all tokens remaining on the current line until the tok::eod token is found.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
DiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagID) const
void markMacroAsUsed(MacroInfo *MI)
A macro is used, update information about macros that need unused warnings.
void setCodeCompletionReached()
Note that we hit the code-completion point.
void LexNonComment(Token &Result)
Lex a token.
SourceManager & getSourceManager() const
MacroDefinition getMacroDefinition(const IdentifierInfo *II)
bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, bool *ShadowFlag=nullptr)
std::optional< std::uint64_t > getStdLibCxxVersion()
const TargetInfo & getTargetInfo() const
void LexUnexpandedNonComment(Token &Result)
Like LexNonComment, but this disables macro expansion of identifier tokens.
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
void emitMacroExpansionWarnings(const Token &Identifier, bool IsIfnDef=false) const
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
CodeCompletionHandler * getCodeCompletionHandler() const
Retrieve the current code-completion handler.
const PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
const LangOptions & getLangOpts() const
DiagnosticsEngine & getDiagnostics() const
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
A trivial tuple used to represent a source range.
bool isFunctionMacroExpansion() const
const ExpansionInfo & getExpansion() const
Exposes information about the current target.
unsigned getChar32Width() const
getChar32Width/Align - Return the size of 'char32_t' for this target, in bits.
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
unsigned getChar16Width() const
getChar16Width/Align - Return the size of 'char16_t' for this target, in bits.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
IntType getWCharType() const
unsigned getWCharWidth() const
getWCharWidth/Align - Return the size of 'wchar_t' for this target, in bits.
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
unsigned getCharWidth() const
Token - This structure provides full information about a lexed token.
IdentifierInfo * getIdentifierInfo() const
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
tok::TokenKind getKind() const
bool isNot(tok::TokenKind K) const
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
bool hasUDSuffix() const
Return true if this token is a string or character literal which has a ud-suffix.
Defines the clang::TargetInfo interface.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Top level wrappers for InstallAPI frontend operations.
DefinedTracker - This struct is used while parsing expressions to keep track of whether !...
TrackerState
Each time a Value is evaluated, it returns information about whether the parsed value is of the form ...
bool IncludedUndefinedIds
IdentifierInfo * TheMacro
TheMacro - When the state is DefinedMacro or NotDefinedMacro, this indicates the macro that was check...
enum DefinedTracker::TrackerState State