PPExpressions.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. //===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Preprocessor::EvaluateDirectiveExpression method,
  11. // which parses and evaluates integer constant expressions for #if directives.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. //
  15. // FIXME: implement testing for #assert's.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "clang/Lex/Preprocessor.h"
  19. #include "clang/Lex/MacroInfo.h"
  20. #include "clang/Lex/LiteralSupport.h"
  21. #include "clang/Lex/CodeCompletionHandler.h"
  22. #include "clang/Basic/TargetInfo.h"
  23. #include "clang/Lex/LexDiagnostic.h"
  24. #include "llvm/ADT/APSInt.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. using namespace clang;
  27. namespace {
  28. /// PPValue - Represents the value of a subexpression of a preprocessor
  29. /// conditional and the source range covered by it.
  30. class PPValue {
  31. SourceRange Range;
  32. public:
  33. llvm::APSInt Val;
  34. // Default ctor - Construct an 'invalid' PPValue.
  35. PPValue(unsigned BitWidth) : Val(BitWidth) {}
  36. unsigned getBitWidth() const { return Val.getBitWidth(); }
  37. bool isUnsigned() const { return Val.isUnsigned(); }
  38. const SourceRange &getRange() const { return Range; }
  39. void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
  40. void setRange(SourceLocation B, SourceLocation E) {
  41. Range.setBegin(B); Range.setEnd(E);
  42. }
  43. void setBegin(SourceLocation L) { Range.setBegin(L); }
  44. void setEnd(SourceLocation L) { Range.setEnd(L); }
  45. };
  46. }
  47. static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
  48. Token &PeekTok, bool ValueLive,
  49. Preprocessor &PP);
  50. /// DefinedTracker - This struct is used while parsing expressions to keep track
  51. /// of whether !defined(X) has been seen.
  52. ///
  53. /// With this simple scheme, we handle the basic forms:
  54. /// !defined(X) and !defined X
  55. /// but we also trivially handle (silly) stuff like:
  56. /// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
  57. struct DefinedTracker {
  58. /// Each time a Value is evaluated, it returns information about whether the
  59. /// parsed value is of the form defined(X), !defined(X) or is something else.
  60. enum TrackerState {
  61. DefinedMacro, // defined(X)
  62. NotDefinedMacro, // !defined(X)
  63. Unknown // Something else.
  64. } State;
  65. /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
  66. /// indicates the macro that was checked.
  67. IdentifierInfo *TheMacro;
  68. };
  69. /// EvaluateDefined - Process a 'defined(sym)' expression.
  70. static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
  71. bool ValueLive, Preprocessor &PP) {
  72. IdentifierInfo *II;
  73. Result.setBegin(PeekTok.getLocation());
  74. // Get the next token, don't expand it.
  75. PP.LexUnexpandedNonComment(PeekTok);
  76. // Two options, it can either be a pp-identifier or a (.
  77. SourceLocation LParenLoc;
  78. if (PeekTok.is(tok::l_paren)) {
  79. // Found a paren, remember we saw it and skip it.
  80. LParenLoc = PeekTok.getLocation();
  81. PP.LexUnexpandedNonComment(PeekTok);
  82. }
  83. if (PeekTok.is(tok::code_completion)) {
  84. if (PP.getCodeCompletionHandler())
  85. PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
  86. PP.setCodeCompletionReached();
  87. PP.LexUnexpandedNonComment(PeekTok);
  88. }
  89. // If we don't have a pp-identifier now, this is an error.
  90. if ((II = PeekTok.getIdentifierInfo()) == 0) {
  91. PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
  92. return true;
  93. }
  94. // Otherwise, we got an identifier, is it defined to something?
  95. Result.Val = II->hasMacroDefinition();
  96. Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
  97. // If there is a macro, mark it used.
  98. if (Result.Val != 0 && ValueLive) {
  99. MacroInfo *Macro = PP.getMacroInfo(II);
  100. PP.markMacroAsUsed(Macro);
  101. }
  102. // Invoke the 'defined' callback.
  103. if (PPCallbacks *Callbacks = PP.getPPCallbacks())
  104. Callbacks->Defined(PeekTok);
  105. // If we are in parens, ensure we have a trailing ).
  106. if (LParenLoc.isValid()) {
  107. // Consume identifier.
  108. Result.setEnd(PeekTok.getLocation());
  109. PP.LexUnexpandedNonComment(PeekTok);
  110. if (PeekTok.isNot(tok::r_paren)) {
  111. PP.Diag(PeekTok.getLocation(), diag::err_pp_missing_rparen) << "defined";
  112. PP.Diag(LParenLoc, diag::note_matching) << "(";
  113. return true;
  114. }
  115. // Consume the ).
  116. Result.setEnd(PeekTok.getLocation());
  117. PP.LexNonComment(PeekTok);
  118. } else {
  119. // Consume identifier.
  120. Result.setEnd(PeekTok.getLocation());
  121. PP.LexNonComment(PeekTok);
  122. }
  123. // Success, remember that we saw defined(X).
  124. DT.State = DefinedTracker::DefinedMacro;
  125. DT.TheMacro = II;
  126. return false;
  127. }
  128. /// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
  129. /// return the computed value in Result. Return true if there was an error
  130. /// parsing. This function also returns information about the form of the
  131. /// expression in DT. See above for information on what DT means.
  132. ///
  133. /// If ValueLive is false, then this value is being evaluated in a context where
  134. /// the result is not used. As such, avoid diagnostics that relate to
  135. /// evaluation.
  136. static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
  137. bool ValueLive, Preprocessor &PP) {
  138. DT.State = DefinedTracker::Unknown;
  139. if (PeekTok.is(tok::code_completion)) {
  140. if (PP.getCodeCompletionHandler())
  141. PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
  142. PP.setCodeCompletionReached();
  143. PP.LexNonComment(PeekTok);
  144. }
  145. // If this token's spelling is a pp-identifier, check to see if it is
  146. // 'defined' or if it is a macro. Note that we check here because many
  147. // keywords are pp-identifiers, so we can't check the kind.
  148. if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
  149. // Handle "defined X" and "defined(X)".
  150. if (II->isStr("defined"))
  151. return(EvaluateDefined(Result, PeekTok, DT, ValueLive, PP));
  152. // If this identifier isn't 'defined' or one of the special
  153. // preprocessor keywords and it wasn't macro expanded, it turns
  154. // into a simple 0, unless it is the C++ keyword "true", in which case it
  155. // turns into "1".
  156. if (ValueLive)
  157. PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
  158. Result.Val = II->getTokenID() == tok::kw_true;
  159. Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
  160. Result.setRange(PeekTok.getLocation());
  161. PP.LexNonComment(PeekTok);
  162. return false;
  163. }
  164. switch (PeekTok.getKind()) {
  165. default: // Non-value token.
  166. PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
  167. return true;
  168. case tok::eod:
  169. case tok::r_paren:
  170. // If there is no expression, report and exit.
  171. PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
  172. return true;
  173. case tok::numeric_constant: {
  174. SmallString<64> IntegerBuffer;
  175. bool NumberInvalid = false;
  176. StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
  177. &NumberInvalid);
  178. if (NumberInvalid)
  179. return true; // a diagnostic was already reported
  180. NumericLiteralParser Literal(Spelling.begin(), Spelling.end(),
  181. PeekTok.getLocation(), PP);
  182. if (Literal.hadError)
  183. return true; // a diagnostic was already reported.
  184. if (Literal.isFloatingLiteral() || Literal.isImaginary) {
  185. PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
  186. return true;
  187. }
  188. assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
  189. // long long is a C99 feature.
  190. if (!PP.getLangOptions().C99 && Literal.isLongLong)
  191. PP.Diag(PeekTok, PP.getLangOptions().CPlusPlus0x ?
  192. diag::warn_cxx98_compat_longlong : diag::ext_longlong);
  193. // Parse the integer literal into Result.
  194. if (Literal.GetIntegerValue(Result.Val)) {
  195. // Overflow parsing integer literal.
  196. if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
  197. Result.Val.setIsUnsigned(true);
  198. } else {
  199. // Set the signedness of the result to match whether there was a U suffix
  200. // or not.
  201. Result.Val.setIsUnsigned(Literal.isUnsigned);
  202. // Detect overflow based on whether the value is signed. If signed
  203. // and if the value is too large, emit a warning "integer constant is so
  204. // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
  205. // is 64-bits.
  206. if (!Literal.isUnsigned && Result.Val.isNegative()) {
  207. // Don't warn for a hex literal: 0x8000..0 shouldn't warn.
  208. if (ValueLive && Literal.getRadix() != 16)
  209. PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
  210. Result.Val.setIsUnsigned(true);
  211. }
  212. }
  213. // Consume the token.
  214. Result.setRange(PeekTok.getLocation());
  215. PP.LexNonComment(PeekTok);
  216. return false;
  217. }
  218. case tok::char_constant: // 'x'
  219. case tok::wide_char_constant: { // L'x'
  220. case tok::utf16_char_constant: // u'x'
  221. case tok::utf32_char_constant: // U'x'
  222. SmallString<32> CharBuffer;
  223. bool CharInvalid = false;
  224. StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
  225. if (CharInvalid)
  226. return true;
  227. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
  228. PeekTok.getLocation(), PP, PeekTok.getKind());
  229. if (Literal.hadError())
  230. return true; // A diagnostic was already emitted.
  231. // Character literals are always int or wchar_t, expand to intmax_t.
  232. const TargetInfo &TI = PP.getTargetInfo();
  233. unsigned NumBits;
  234. if (Literal.isMultiChar())
  235. NumBits = TI.getIntWidth();
  236. else if (Literal.isWide())
  237. NumBits = TI.getWCharWidth();
  238. else if (Literal.isUTF16())
  239. NumBits = TI.getChar16Width();
  240. else if (Literal.isUTF32())
  241. NumBits = TI.getChar32Width();
  242. else
  243. NumBits = TI.getCharWidth();
  244. // Set the width.
  245. llvm::APSInt Val(NumBits);
  246. // Set the value.
  247. Val = Literal.getValue();
  248. // Set the signedness. UTF-16 and UTF-32 are always unsigned
  249. if (!Literal.isUTF16() && !Literal.isUTF32())
  250. Val.setIsUnsigned(!PP.getLangOptions().CharIsSigned);
  251. if (Result.Val.getBitWidth() > Val.getBitWidth()) {
  252. Result.Val = Val.extend(Result.Val.getBitWidth());
  253. } else {
  254. assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
  255. "intmax_t smaller than char/wchar_t?");
  256. Result.Val = Val;
  257. }
  258. // Consume the token.
  259. Result.setRange(PeekTok.getLocation());
  260. PP.LexNonComment(PeekTok);
  261. return false;
  262. }
  263. case tok::l_paren: {
  264. SourceLocation Start = PeekTok.getLocation();
  265. PP.LexNonComment(PeekTok); // Eat the (.
  266. // Parse the value and if there are any binary operators involved, parse
  267. // them.
  268. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
  269. // If this is a silly value like (X), which doesn't need parens, check for
  270. // !(defined X).
  271. if (PeekTok.is(tok::r_paren)) {
  272. // Just use DT unmodified as our result.
  273. } else {
  274. // Otherwise, we have something like (x+y), and we consumed '(x'.
  275. if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
  276. return true;
  277. if (PeekTok.isNot(tok::r_paren)) {
  278. PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
  279. << Result.getRange();
  280. PP.Diag(Start, diag::note_matching) << "(";
  281. return true;
  282. }
  283. DT.State = DefinedTracker::Unknown;
  284. }
  285. Result.setRange(Start, PeekTok.getLocation());
  286. PP.LexNonComment(PeekTok); // Eat the ).
  287. return false;
  288. }
  289. case tok::plus: {
  290. SourceLocation Start = PeekTok.getLocation();
  291. // Unary plus doesn't modify the value.
  292. PP.LexNonComment(PeekTok);
  293. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
  294. Result.setBegin(Start);
  295. return false;
  296. }
  297. case tok::minus: {
  298. SourceLocation Loc = PeekTok.getLocation();
  299. PP.LexNonComment(PeekTok);
  300. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
  301. Result.setBegin(Loc);
  302. // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
  303. Result.Val = -Result.Val;
  304. // -MININT is the only thing that overflows. Unsigned never overflows.
  305. bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
  306. // If this operator is live and overflowed, report the issue.
  307. if (Overflow && ValueLive)
  308. PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
  309. DT.State = DefinedTracker::Unknown;
  310. return false;
  311. }
  312. case tok::tilde: {
  313. SourceLocation Start = PeekTok.getLocation();
  314. PP.LexNonComment(PeekTok);
  315. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
  316. Result.setBegin(Start);
  317. // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
  318. Result.Val = ~Result.Val;
  319. DT.State = DefinedTracker::Unknown;
  320. return false;
  321. }
  322. case tok::exclaim: {
  323. SourceLocation Start = PeekTok.getLocation();
  324. PP.LexNonComment(PeekTok);
  325. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
  326. Result.setBegin(Start);
  327. Result.Val = !Result.Val;
  328. // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
  329. Result.Val.setIsUnsigned(false);
  330. if (DT.State == DefinedTracker::DefinedMacro)
  331. DT.State = DefinedTracker::NotDefinedMacro;
  332. else if (DT.State == DefinedTracker::NotDefinedMacro)
  333. DT.State = DefinedTracker::DefinedMacro;
  334. return false;
  335. }
  336. // FIXME: Handle #assert
  337. }
  338. }
  339. /// getPrecedence - Return the precedence of the specified binary operator
  340. /// token. This returns:
  341. /// ~0 - Invalid token.
  342. /// 14 -> 3 - various operators.
  343. /// 0 - 'eod' or ')'
  344. static unsigned getPrecedence(tok::TokenKind Kind) {
  345. switch (Kind) {
  346. default: return ~0U;
  347. case tok::percent:
  348. case tok::slash:
  349. case tok::star: return 14;
  350. case tok::plus:
  351. case tok::minus: return 13;
  352. case tok::lessless:
  353. case tok::greatergreater: return 12;
  354. case tok::lessequal:
  355. case tok::less:
  356. case tok::greaterequal:
  357. case tok::greater: return 11;
  358. case tok::exclaimequal:
  359. case tok::equalequal: return 10;
  360. case tok::amp: return 9;
  361. case tok::caret: return 8;
  362. case tok::pipe: return 7;
  363. case tok::ampamp: return 6;
  364. case tok::pipepipe: return 5;
  365. case tok::question: return 4;
  366. case tok::comma: return 3;
  367. case tok::colon: return 2;
  368. case tok::r_paren: return 0;// Lowest priority, end of expr.
  369. case tok::eod: return 0;// Lowest priority, end of directive.
  370. }
  371. }
  372. /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
  373. /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
  374. ///
  375. /// If ValueLive is false, then this value is being evaluated in a context where
  376. /// the result is not used. As such, avoid diagnostics that relate to
  377. /// evaluation, such as division by zero warnings.
  378. static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
  379. Token &PeekTok, bool ValueLive,
  380. Preprocessor &PP) {
  381. unsigned PeekPrec = getPrecedence(PeekTok.getKind());
  382. // If this token isn't valid, report the error.
  383. if (PeekPrec == ~0U) {
  384. PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
  385. << LHS.getRange();
  386. return true;
  387. }
  388. while (1) {
  389. // If this token has a lower precedence than we are allowed to parse, return
  390. // it so that higher levels of the recursion can parse it.
  391. if (PeekPrec < MinPrec)
  392. return false;
  393. tok::TokenKind Operator = PeekTok.getKind();
  394. // If this is a short-circuiting operator, see if the RHS of the operator is
  395. // dead. Note that this cannot just clobber ValueLive. Consider
  396. // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
  397. // this example, the RHS of the && being dead does not make the rest of the
  398. // expr dead.
  399. bool RHSIsLive;
  400. if (Operator == tok::ampamp && LHS.Val == 0)
  401. RHSIsLive = false; // RHS of "0 && x" is dead.
  402. else if (Operator == tok::pipepipe && LHS.Val != 0)
  403. RHSIsLive = false; // RHS of "1 || x" is dead.
  404. else if (Operator == tok::question && LHS.Val == 0)
  405. RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
  406. else
  407. RHSIsLive = ValueLive;
  408. // Consume the operator, remembering the operator's location for reporting.
  409. SourceLocation OpLoc = PeekTok.getLocation();
  410. PP.LexNonComment(PeekTok);
  411. PPValue RHS(LHS.getBitWidth());
  412. // Parse the RHS of the operator.
  413. DefinedTracker DT;
  414. if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
  415. // Remember the precedence of this operator and get the precedence of the
  416. // operator immediately to the right of the RHS.
  417. unsigned ThisPrec = PeekPrec;
  418. PeekPrec = getPrecedence(PeekTok.getKind());
  419. // If this token isn't valid, report the error.
  420. if (PeekPrec == ~0U) {
  421. PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
  422. << RHS.getRange();
  423. return true;
  424. }
  425. // Decide whether to include the next binop in this subexpression. For
  426. // example, when parsing x+y*z and looking at '*', we want to recursively
  427. // handle y*z as a single subexpression. We do this because the precedence
  428. // of * is higher than that of +. The only strange case we have to handle
  429. // here is for the ?: operator, where the precedence is actually lower than
  430. // the LHS of the '?'. The grammar rule is:
  431. //
  432. // conditional-expression ::=
  433. // logical-OR-expression ? expression : conditional-expression
  434. // where 'expression' is actually comma-expression.
  435. unsigned RHSPrec;
  436. if (Operator == tok::question)
  437. // The RHS of "?" should be maximally consumed as an expression.
  438. RHSPrec = getPrecedence(tok::comma);
  439. else // All others should munch while higher precedence.
  440. RHSPrec = ThisPrec+1;
  441. if (PeekPrec >= RHSPrec) {
  442. if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
  443. return true;
  444. PeekPrec = getPrecedence(PeekTok.getKind());
  445. }
  446. assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
  447. // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
  448. // either operand is unsigned.
  449. llvm::APSInt Res(LHS.getBitWidth());
  450. switch (Operator) {
  451. case tok::question: // No UAC for x and y in "x ? y : z".
  452. case tok::lessless: // Shift amount doesn't UAC with shift value.
  453. case tok::greatergreater: // Shift amount doesn't UAC with shift value.
  454. case tok::comma: // Comma operands are not subject to UACs.
  455. case tok::pipepipe: // Logical || does not do UACs.
  456. case tok::ampamp: // Logical && does not do UACs.
  457. break; // No UAC
  458. default:
  459. Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
  460. // If this just promoted something from signed to unsigned, and if the
  461. // value was negative, warn about it.
  462. if (ValueLive && Res.isUnsigned()) {
  463. if (!LHS.isUnsigned() && LHS.Val.isNegative())
  464. PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive)
  465. << LHS.Val.toString(10, true) + " to " +
  466. LHS.Val.toString(10, false)
  467. << LHS.getRange() << RHS.getRange();
  468. if (!RHS.isUnsigned() && RHS.Val.isNegative())
  469. PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive)
  470. << RHS.Val.toString(10, true) + " to " +
  471. RHS.Val.toString(10, false)
  472. << LHS.getRange() << RHS.getRange();
  473. }
  474. LHS.Val.setIsUnsigned(Res.isUnsigned());
  475. RHS.Val.setIsUnsigned(Res.isUnsigned());
  476. }
  477. bool Overflow = false;
  478. switch (Operator) {
  479. default: llvm_unreachable("Unknown operator token!");
  480. case tok::percent:
  481. if (RHS.Val != 0)
  482. Res = LHS.Val % RHS.Val;
  483. else if (ValueLive) {
  484. PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
  485. << LHS.getRange() << RHS.getRange();
  486. return true;
  487. }
  488. break;
  489. case tok::slash:
  490. if (RHS.Val != 0) {
  491. if (LHS.Val.isSigned())
  492. Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
  493. else
  494. Res = LHS.Val / RHS.Val;
  495. } else if (ValueLive) {
  496. PP.Diag(OpLoc, diag::err_pp_division_by_zero)
  497. << LHS.getRange() << RHS.getRange();
  498. return true;
  499. }
  500. break;
  501. case tok::star:
  502. if (Res.isSigned())
  503. Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
  504. else
  505. Res = LHS.Val * RHS.Val;
  506. break;
  507. case tok::lessless: {
  508. // Determine whether overflow is about to happen.
  509. unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
  510. if (LHS.isUnsigned()) {
  511. Overflow = ShAmt >= LHS.Val.getBitWidth();
  512. if (Overflow)
  513. ShAmt = LHS.Val.getBitWidth()-1;
  514. Res = LHS.Val << ShAmt;
  515. } else {
  516. Res = llvm::APSInt(LHS.Val.sshl_ov(ShAmt, Overflow), false);
  517. }
  518. break;
  519. }
  520. case tok::greatergreater: {
  521. // Determine whether overflow is about to happen.
  522. unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
  523. if (ShAmt >= LHS.getBitWidth())
  524. Overflow = true, ShAmt = LHS.getBitWidth()-1;
  525. Res = LHS.Val >> ShAmt;
  526. break;
  527. }
  528. case tok::plus:
  529. if (LHS.isUnsigned())
  530. Res = LHS.Val + RHS.Val;
  531. else
  532. Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
  533. break;
  534. case tok::minus:
  535. if (LHS.isUnsigned())
  536. Res = LHS.Val - RHS.Val;
  537. else
  538. Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
  539. break;
  540. case tok::lessequal:
  541. Res = LHS.Val <= RHS.Val;
  542. Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
  543. break;
  544. case tok::less:
  545. Res = LHS.Val < RHS.Val;
  546. Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
  547. break;
  548. case tok::greaterequal:
  549. Res = LHS.Val >= RHS.Val;
  550. Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
  551. break;
  552. case tok::greater:
  553. Res = LHS.Val > RHS.Val;
  554. Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
  555. break;
  556. case tok::exclaimequal:
  557. Res = LHS.Val != RHS.Val;
  558. Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
  559. break;
  560. case tok::equalequal:
  561. Res = LHS.Val == RHS.Val;
  562. Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
  563. break;
  564. case tok::amp:
  565. Res = LHS.Val & RHS.Val;
  566. break;
  567. case tok::caret:
  568. Res = LHS.Val ^ RHS.Val;
  569. break;
  570. case tok::pipe:
  571. Res = LHS.Val | RHS.Val;
  572. break;
  573. case tok::ampamp:
  574. Res = (LHS.Val != 0 && RHS.Val != 0);
  575. Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
  576. break;
  577. case tok::pipepipe:
  578. Res = (LHS.Val != 0 || RHS.Val != 0);
  579. Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
  580. break;
  581. case tok::comma:
  582. // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
  583. // if not being evaluated.
  584. if (!PP.getLangOptions().C99 || ValueLive)
  585. PP.Diag(OpLoc, diag::ext_pp_comma_expr)
  586. << LHS.getRange() << RHS.getRange();
  587. Res = RHS.Val; // LHS = LHS,RHS -> RHS.
  588. break;
  589. case tok::question: {
  590. // Parse the : part of the expression.
  591. if (PeekTok.isNot(tok::colon)) {
  592. PP.Diag(PeekTok.getLocation(), diag::err_expected_colon)
  593. << LHS.getRange(), RHS.getRange();
  594. PP.Diag(OpLoc, diag::note_matching) << "?";
  595. return true;
  596. }
  597. // Consume the :.
  598. PP.LexNonComment(PeekTok);
  599. // Evaluate the value after the :.
  600. bool AfterColonLive = ValueLive && LHS.Val == 0;
  601. PPValue AfterColonVal(LHS.getBitWidth());
  602. DefinedTracker DT;
  603. if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
  604. return true;
  605. // Parse anything after the : with the same precedence as ?. We allow
  606. // things of equal precedence because ?: is right associative.
  607. if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
  608. PeekTok, AfterColonLive, PP))
  609. return true;
  610. // Now that we have the condition, the LHS and the RHS of the :, evaluate.
  611. Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
  612. RHS.setEnd(AfterColonVal.getRange().getEnd());
  613. // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
  614. // either operand is unsigned.
  615. Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
  616. // Figure out the precedence of the token after the : part.
  617. PeekPrec = getPrecedence(PeekTok.getKind());
  618. break;
  619. }
  620. case tok::colon:
  621. // Don't allow :'s to float around without being part of ?: exprs.
  622. PP.Diag(OpLoc, diag::err_pp_colon_without_question)
  623. << LHS.getRange() << RHS.getRange();
  624. return true;
  625. }
  626. // If this operator is live and overflowed, report the issue.
  627. if (Overflow && ValueLive)
  628. PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
  629. << LHS.getRange() << RHS.getRange();
  630. // Put the result back into 'LHS' for our next iteration.
  631. LHS.Val = Res;
  632. LHS.setEnd(RHS.getRange().getEnd());
  633. }
  634. }
  635. /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
  636. /// may occur after a #if or #elif directive. If the expression is equivalent
  637. /// to "!defined(X)" return X in IfNDefMacro.
  638. bool Preprocessor::
  639. EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
  640. // Save the current state of 'DisableMacroExpansion' and reset it to false. If
  641. // 'DisableMacroExpansion' is true, then we must be in a macro argument list
  642. // in which case a directive is undefined behavior. We want macros to be able
  643. // to recursively expand in order to get more gcc-list behavior, so we force
  644. // DisableMacroExpansion to false and restore it when we're done parsing the
  645. // expression.
  646. bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
  647. DisableMacroExpansion = false;
  648. // Peek ahead one token.
  649. Token Tok;
  650. LexNonComment(Tok);
  651. // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
  652. unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
  653. PPValue ResVal(BitWidth);
  654. DefinedTracker DT;
  655. if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
  656. // Parse error, skip the rest of the macro line.
  657. if (Tok.isNot(tok::eod))
  658. DiscardUntilEndOfDirective();
  659. // Restore 'DisableMacroExpansion'.
  660. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
  661. return false;
  662. }
  663. // If we are at the end of the expression after just parsing a value, there
  664. // must be no (unparenthesized) binary operators involved, so we can exit
  665. // directly.
  666. if (Tok.is(tok::eod)) {
  667. // If the expression we parsed was of the form !defined(macro), return the
  668. // macro in IfNDefMacro.
  669. if (DT.State == DefinedTracker::NotDefinedMacro)
  670. IfNDefMacro = DT.TheMacro;
  671. // Restore 'DisableMacroExpansion'.
  672. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
  673. return ResVal.Val != 0;
  674. }
  675. // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
  676. // operator and the stuff after it.
  677. if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
  678. Tok, true, *this)) {
  679. // Parse error, skip the rest of the macro line.
  680. if (Tok.isNot(tok::eod))
  681. DiscardUntilEndOfDirective();
  682. // Restore 'DisableMacroExpansion'.
  683. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
  684. return false;
  685. }
  686. // If we aren't at the tok::eod token, something bad happened, like an extra
  687. // ')' token.
  688. if (Tok.isNot(tok::eod)) {
  689. Diag(Tok, diag::err_pp_expected_eol);
  690. DiscardUntilEndOfDirective();
  691. }
  692. // Restore 'DisableMacroExpansion'.
  693. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
  694. return ResVal.Val != 0;
  695. }