PPExpressions.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. // Complain about, and drop, any ud-suffix.
  190. if (Literal.hasUDSuffix())
  191. PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
  192. // long long is a C99 feature.
  193. if (!PP.getLangOpts().C99 && Literal.isLongLong)
  194. PP.Diag(PeekTok, PP.getLangOpts().CPlusPlus0x ?
  195. diag::warn_cxx98_compat_longlong : diag::ext_longlong);
  196. // Parse the integer literal into Result.
  197. if (Literal.GetIntegerValue(Result.Val)) {
  198. // Overflow parsing integer literal.
  199. if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
  200. Result.Val.setIsUnsigned(true);
  201. } else {
  202. // Set the signedness of the result to match whether there was a U suffix
  203. // or not.
  204. Result.Val.setIsUnsigned(Literal.isUnsigned);
  205. // Detect overflow based on whether the value is signed. If signed
  206. // and if the value is too large, emit a warning "integer constant is so
  207. // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
  208. // is 64-bits.
  209. if (!Literal.isUnsigned && Result.Val.isNegative()) {
  210. // Don't warn for a hex literal: 0x8000..0 shouldn't warn.
  211. if (ValueLive && Literal.getRadix() != 16)
  212. PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
  213. Result.Val.setIsUnsigned(true);
  214. }
  215. }
  216. // Consume the token.
  217. Result.setRange(PeekTok.getLocation());
  218. PP.LexNonComment(PeekTok);
  219. return false;
  220. }
  221. case tok::char_constant: // 'x'
  222. case tok::wide_char_constant: { // L'x'
  223. case tok::utf16_char_constant: // u'x'
  224. case tok::utf32_char_constant: // U'x'
  225. // Complain about, and drop, any ud-suffix.
  226. if (PeekTok.hasUDSuffix())
  227. PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
  228. SmallString<32> CharBuffer;
  229. bool CharInvalid = false;
  230. StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
  231. if (CharInvalid)
  232. return true;
  233. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
  234. PeekTok.getLocation(), PP, PeekTok.getKind());
  235. if (Literal.hadError())
  236. return true; // A diagnostic was already emitted.
  237. // Character literals are always int or wchar_t, expand to intmax_t.
  238. const TargetInfo &TI = PP.getTargetInfo();
  239. unsigned NumBits;
  240. if (Literal.isMultiChar())
  241. NumBits = TI.getIntWidth();
  242. else if (Literal.isWide())
  243. NumBits = TI.getWCharWidth();
  244. else if (Literal.isUTF16())
  245. NumBits = TI.getChar16Width();
  246. else if (Literal.isUTF32())
  247. NumBits = TI.getChar32Width();
  248. else
  249. NumBits = TI.getCharWidth();
  250. // Set the width.
  251. llvm::APSInt Val(NumBits);
  252. // Set the value.
  253. Val = Literal.getValue();
  254. // Set the signedness. UTF-16 and UTF-32 are always unsigned
  255. if (!Literal.isUTF16() && !Literal.isUTF32())
  256. Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
  257. if (Result.Val.getBitWidth() > Val.getBitWidth()) {
  258. Result.Val = Val.extend(Result.Val.getBitWidth());
  259. } else {
  260. assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
  261. "intmax_t smaller than char/wchar_t?");
  262. Result.Val = Val;
  263. }
  264. // Consume the token.
  265. Result.setRange(PeekTok.getLocation());
  266. PP.LexNonComment(PeekTok);
  267. return false;
  268. }
  269. case tok::l_paren: {
  270. SourceLocation Start = PeekTok.getLocation();
  271. PP.LexNonComment(PeekTok); // Eat the (.
  272. // Parse the value and if there are any binary operators involved, parse
  273. // them.
  274. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
  275. // If this is a silly value like (X), which doesn't need parens, check for
  276. // !(defined X).
  277. if (PeekTok.is(tok::r_paren)) {
  278. // Just use DT unmodified as our result.
  279. } else {
  280. // Otherwise, we have something like (x+y), and we consumed '(x'.
  281. if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
  282. return true;
  283. if (PeekTok.isNot(tok::r_paren)) {
  284. PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
  285. << Result.getRange();
  286. PP.Diag(Start, diag::note_matching) << "(";
  287. return true;
  288. }
  289. DT.State = DefinedTracker::Unknown;
  290. }
  291. Result.setRange(Start, PeekTok.getLocation());
  292. PP.LexNonComment(PeekTok); // Eat the ).
  293. return false;
  294. }
  295. case tok::plus: {
  296. SourceLocation Start = PeekTok.getLocation();
  297. // Unary plus doesn't modify the value.
  298. PP.LexNonComment(PeekTok);
  299. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
  300. Result.setBegin(Start);
  301. return false;
  302. }
  303. case tok::minus: {
  304. SourceLocation Loc = PeekTok.getLocation();
  305. PP.LexNonComment(PeekTok);
  306. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
  307. Result.setBegin(Loc);
  308. // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
  309. Result.Val = -Result.Val;
  310. // -MININT is the only thing that overflows. Unsigned never overflows.
  311. bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
  312. // If this operator is live and overflowed, report the issue.
  313. if (Overflow && ValueLive)
  314. PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
  315. DT.State = DefinedTracker::Unknown;
  316. return false;
  317. }
  318. case tok::tilde: {
  319. SourceLocation Start = PeekTok.getLocation();
  320. PP.LexNonComment(PeekTok);
  321. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
  322. Result.setBegin(Start);
  323. // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
  324. Result.Val = ~Result.Val;
  325. DT.State = DefinedTracker::Unknown;
  326. return false;
  327. }
  328. case tok::exclaim: {
  329. SourceLocation Start = PeekTok.getLocation();
  330. PP.LexNonComment(PeekTok);
  331. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
  332. Result.setBegin(Start);
  333. Result.Val = !Result.Val;
  334. // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
  335. Result.Val.setIsUnsigned(false);
  336. if (DT.State == DefinedTracker::DefinedMacro)
  337. DT.State = DefinedTracker::NotDefinedMacro;
  338. else if (DT.State == DefinedTracker::NotDefinedMacro)
  339. DT.State = DefinedTracker::DefinedMacro;
  340. return false;
  341. }
  342. // FIXME: Handle #assert
  343. }
  344. }
  345. /// getPrecedence - Return the precedence of the specified binary operator
  346. /// token. This returns:
  347. /// ~0 - Invalid token.
  348. /// 14 -> 3 - various operators.
  349. /// 0 - 'eod' or ')'
  350. static unsigned getPrecedence(tok::TokenKind Kind) {
  351. switch (Kind) {
  352. default: return ~0U;
  353. case tok::percent:
  354. case tok::slash:
  355. case tok::star: return 14;
  356. case tok::plus:
  357. case tok::minus: return 13;
  358. case tok::lessless:
  359. case tok::greatergreater: return 12;
  360. case tok::lessequal:
  361. case tok::less:
  362. case tok::greaterequal:
  363. case tok::greater: return 11;
  364. case tok::exclaimequal:
  365. case tok::equalequal: return 10;
  366. case tok::amp: return 9;
  367. case tok::caret: return 8;
  368. case tok::pipe: return 7;
  369. case tok::ampamp: return 6;
  370. case tok::pipepipe: return 5;
  371. case tok::question: return 4;
  372. case tok::comma: return 3;
  373. case tok::colon: return 2;
  374. case tok::r_paren: return 0;// Lowest priority, end of expr.
  375. case tok::eod: return 0;// Lowest priority, end of directive.
  376. }
  377. }
  378. /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
  379. /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
  380. ///
  381. /// If ValueLive is false, then this value is being evaluated in a context where
  382. /// the result is not used. As such, avoid diagnostics that relate to
  383. /// evaluation, such as division by zero warnings.
  384. static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
  385. Token &PeekTok, bool ValueLive,
  386. Preprocessor &PP) {
  387. unsigned PeekPrec = getPrecedence(PeekTok.getKind());
  388. // If this token isn't valid, report the error.
  389. if (PeekPrec == ~0U) {
  390. PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
  391. << LHS.getRange();
  392. return true;
  393. }
  394. while (1) {
  395. // If this token has a lower precedence than we are allowed to parse, return
  396. // it so that higher levels of the recursion can parse it.
  397. if (PeekPrec < MinPrec)
  398. return false;
  399. tok::TokenKind Operator = PeekTok.getKind();
  400. // If this is a short-circuiting operator, see if the RHS of the operator is
  401. // dead. Note that this cannot just clobber ValueLive. Consider
  402. // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
  403. // this example, the RHS of the && being dead does not make the rest of the
  404. // expr dead.
  405. bool RHSIsLive;
  406. if (Operator == tok::ampamp && LHS.Val == 0)
  407. RHSIsLive = false; // RHS of "0 && x" is dead.
  408. else if (Operator == tok::pipepipe && LHS.Val != 0)
  409. RHSIsLive = false; // RHS of "1 || x" is dead.
  410. else if (Operator == tok::question && LHS.Val == 0)
  411. RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
  412. else
  413. RHSIsLive = ValueLive;
  414. // Consume the operator, remembering the operator's location for reporting.
  415. SourceLocation OpLoc = PeekTok.getLocation();
  416. PP.LexNonComment(PeekTok);
  417. PPValue RHS(LHS.getBitWidth());
  418. // Parse the RHS of the operator.
  419. DefinedTracker DT;
  420. if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
  421. // Remember the precedence of this operator and get the precedence of the
  422. // operator immediately to the right of the RHS.
  423. unsigned ThisPrec = PeekPrec;
  424. PeekPrec = getPrecedence(PeekTok.getKind());
  425. // If this token isn't valid, report the error.
  426. if (PeekPrec == ~0U) {
  427. PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
  428. << RHS.getRange();
  429. return true;
  430. }
  431. // Decide whether to include the next binop in this subexpression. For
  432. // example, when parsing x+y*z and looking at '*', we want to recursively
  433. // handle y*z as a single subexpression. We do this because the precedence
  434. // of * is higher than that of +. The only strange case we have to handle
  435. // here is for the ?: operator, where the precedence is actually lower than
  436. // the LHS of the '?'. The grammar rule is:
  437. //
  438. // conditional-expression ::=
  439. // logical-OR-expression ? expression : conditional-expression
  440. // where 'expression' is actually comma-expression.
  441. unsigned RHSPrec;
  442. if (Operator == tok::question)
  443. // The RHS of "?" should be maximally consumed as an expression.
  444. RHSPrec = getPrecedence(tok::comma);
  445. else // All others should munch while higher precedence.
  446. RHSPrec = ThisPrec+1;
  447. if (PeekPrec >= RHSPrec) {
  448. if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
  449. return true;
  450. PeekPrec = getPrecedence(PeekTok.getKind());
  451. }
  452. assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
  453. // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
  454. // either operand is unsigned.
  455. llvm::APSInt Res(LHS.getBitWidth());
  456. switch (Operator) {
  457. case tok::question: // No UAC for x and y in "x ? y : z".
  458. case tok::lessless: // Shift amount doesn't UAC with shift value.
  459. case tok::greatergreater: // Shift amount doesn't UAC with shift value.
  460. case tok::comma: // Comma operands are not subject to UACs.
  461. case tok::pipepipe: // Logical || does not do UACs.
  462. case tok::ampamp: // Logical && does not do UACs.
  463. break; // No UAC
  464. default:
  465. Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
  466. // If this just promoted something from signed to unsigned, and if the
  467. // value was negative, warn about it.
  468. if (ValueLive && Res.isUnsigned()) {
  469. if (!LHS.isUnsigned() && LHS.Val.isNegative())
  470. PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive)
  471. << LHS.Val.toString(10, true) + " to " +
  472. LHS.Val.toString(10, false)
  473. << LHS.getRange() << RHS.getRange();
  474. if (!RHS.isUnsigned() && RHS.Val.isNegative())
  475. PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive)
  476. << RHS.Val.toString(10, true) + " to " +
  477. RHS.Val.toString(10, false)
  478. << LHS.getRange() << RHS.getRange();
  479. }
  480. LHS.Val.setIsUnsigned(Res.isUnsigned());
  481. RHS.Val.setIsUnsigned(Res.isUnsigned());
  482. }
  483. bool Overflow = false;
  484. switch (Operator) {
  485. default: llvm_unreachable("Unknown operator token!");
  486. case tok::percent:
  487. if (RHS.Val != 0)
  488. Res = LHS.Val % RHS.Val;
  489. else if (ValueLive) {
  490. PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
  491. << LHS.getRange() << RHS.getRange();
  492. return true;
  493. }
  494. break;
  495. case tok::slash:
  496. if (RHS.Val != 0) {
  497. if (LHS.Val.isSigned())
  498. Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
  499. else
  500. Res = LHS.Val / RHS.Val;
  501. } else if (ValueLive) {
  502. PP.Diag(OpLoc, diag::err_pp_division_by_zero)
  503. << LHS.getRange() << RHS.getRange();
  504. return true;
  505. }
  506. break;
  507. case tok::star:
  508. if (Res.isSigned())
  509. Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
  510. else
  511. Res = LHS.Val * RHS.Val;
  512. break;
  513. case tok::lessless: {
  514. // Determine whether overflow is about to happen.
  515. unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
  516. if (LHS.isUnsigned()) {
  517. Overflow = ShAmt >= LHS.Val.getBitWidth();
  518. if (Overflow)
  519. ShAmt = LHS.Val.getBitWidth()-1;
  520. Res = LHS.Val << ShAmt;
  521. } else {
  522. Res = llvm::APSInt(LHS.Val.sshl_ov(ShAmt, Overflow), false);
  523. }
  524. break;
  525. }
  526. case tok::greatergreater: {
  527. // Determine whether overflow is about to happen.
  528. unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
  529. if (ShAmt >= LHS.getBitWidth())
  530. Overflow = true, ShAmt = LHS.getBitWidth()-1;
  531. Res = LHS.Val >> ShAmt;
  532. break;
  533. }
  534. case tok::plus:
  535. if (LHS.isUnsigned())
  536. Res = LHS.Val + RHS.Val;
  537. else
  538. Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
  539. break;
  540. case tok::minus:
  541. if (LHS.isUnsigned())
  542. Res = LHS.Val - RHS.Val;
  543. else
  544. Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
  545. break;
  546. case tok::lessequal:
  547. Res = LHS.Val <= RHS.Val;
  548. Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
  549. break;
  550. case tok::less:
  551. Res = LHS.Val < RHS.Val;
  552. Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
  553. break;
  554. case tok::greaterequal:
  555. Res = LHS.Val >= RHS.Val;
  556. Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
  557. break;
  558. case tok::greater:
  559. Res = LHS.Val > RHS.Val;
  560. Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
  561. break;
  562. case tok::exclaimequal:
  563. Res = LHS.Val != RHS.Val;
  564. Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
  565. break;
  566. case tok::equalequal:
  567. Res = LHS.Val == RHS.Val;
  568. Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
  569. break;
  570. case tok::amp:
  571. Res = LHS.Val & RHS.Val;
  572. break;
  573. case tok::caret:
  574. Res = LHS.Val ^ RHS.Val;
  575. break;
  576. case tok::pipe:
  577. Res = LHS.Val | RHS.Val;
  578. break;
  579. case tok::ampamp:
  580. Res = (LHS.Val != 0 && RHS.Val != 0);
  581. Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
  582. break;
  583. case tok::pipepipe:
  584. Res = (LHS.Val != 0 || RHS.Val != 0);
  585. Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
  586. break;
  587. case tok::comma:
  588. // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
  589. // if not being evaluated.
  590. if (!PP.getLangOpts().C99 || ValueLive)
  591. PP.Diag(OpLoc, diag::ext_pp_comma_expr)
  592. << LHS.getRange() << RHS.getRange();
  593. Res = RHS.Val; // LHS = LHS,RHS -> RHS.
  594. break;
  595. case tok::question: {
  596. // Parse the : part of the expression.
  597. if (PeekTok.isNot(tok::colon)) {
  598. PP.Diag(PeekTok.getLocation(), diag::err_expected_colon)
  599. << LHS.getRange(), RHS.getRange();
  600. PP.Diag(OpLoc, diag::note_matching) << "?";
  601. return true;
  602. }
  603. // Consume the :.
  604. PP.LexNonComment(PeekTok);
  605. // Evaluate the value after the :.
  606. bool AfterColonLive = ValueLive && LHS.Val == 0;
  607. PPValue AfterColonVal(LHS.getBitWidth());
  608. DefinedTracker DT;
  609. if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
  610. return true;
  611. // Parse anything after the : with the same precedence as ?. We allow
  612. // things of equal precedence because ?: is right associative.
  613. if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
  614. PeekTok, AfterColonLive, PP))
  615. return true;
  616. // Now that we have the condition, the LHS and the RHS of the :, evaluate.
  617. Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
  618. RHS.setEnd(AfterColonVal.getRange().getEnd());
  619. // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
  620. // either operand is unsigned.
  621. Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
  622. // Figure out the precedence of the token after the : part.
  623. PeekPrec = getPrecedence(PeekTok.getKind());
  624. break;
  625. }
  626. case tok::colon:
  627. // Don't allow :'s to float around without being part of ?: exprs.
  628. PP.Diag(OpLoc, diag::err_pp_colon_without_question)
  629. << LHS.getRange() << RHS.getRange();
  630. return true;
  631. }
  632. // If this operator is live and overflowed, report the issue.
  633. if (Overflow && ValueLive)
  634. PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
  635. << LHS.getRange() << RHS.getRange();
  636. // Put the result back into 'LHS' for our next iteration.
  637. LHS.Val = Res;
  638. LHS.setEnd(RHS.getRange().getEnd());
  639. }
  640. }
  641. /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
  642. /// may occur after a #if or #elif directive. If the expression is equivalent
  643. /// to "!defined(X)" return X in IfNDefMacro.
  644. bool Preprocessor::
  645. EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
  646. // Save the current state of 'DisableMacroExpansion' and reset it to false. If
  647. // 'DisableMacroExpansion' is true, then we must be in a macro argument list
  648. // in which case a directive is undefined behavior. We want macros to be able
  649. // to recursively expand in order to get more gcc-list behavior, so we force
  650. // DisableMacroExpansion to false and restore it when we're done parsing the
  651. // expression.
  652. bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
  653. DisableMacroExpansion = false;
  654. // Peek ahead one token.
  655. Token Tok;
  656. LexNonComment(Tok);
  657. // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
  658. unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
  659. PPValue ResVal(BitWidth);
  660. DefinedTracker DT;
  661. if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
  662. // Parse error, skip the rest of the macro line.
  663. if (Tok.isNot(tok::eod))
  664. DiscardUntilEndOfDirective();
  665. // Restore 'DisableMacroExpansion'.
  666. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
  667. return false;
  668. }
  669. // If we are at the end of the expression after just parsing a value, there
  670. // must be no (unparenthesized) binary operators involved, so we can exit
  671. // directly.
  672. if (Tok.is(tok::eod)) {
  673. // If the expression we parsed was of the form !defined(macro), return the
  674. // macro in IfNDefMacro.
  675. if (DT.State == DefinedTracker::NotDefinedMacro)
  676. IfNDefMacro = DT.TheMacro;
  677. // Restore 'DisableMacroExpansion'.
  678. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
  679. return ResVal.Val != 0;
  680. }
  681. // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
  682. // operator and the stuff after it.
  683. if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
  684. Tok, true, *this)) {
  685. // Parse error, skip the rest of the macro line.
  686. if (Tok.isNot(tok::eod))
  687. DiscardUntilEndOfDirective();
  688. // Restore 'DisableMacroExpansion'.
  689. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
  690. return false;
  691. }
  692. // If we aren't at the tok::eod token, something bad happened, like an extra
  693. // ')' token.
  694. if (Tok.isNot(tok::eod)) {
  695. Diag(Tok, diag::err_pp_expected_eol);
  696. DiscardUntilEndOfDirective();
  697. }
  698. // Restore 'DisableMacroExpansion'.
  699. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
  700. return ResVal.Val != 0;
  701. }