Expr.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by Chris Lattner and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Expr class and subclasses.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/Expr.h"
  14. #include "clang/AST/StmtVisitor.h"
  15. #include "clang/Lex/IdentifierTable.h"
  16. using namespace clang;
  17. //===----------------------------------------------------------------------===//
  18. // Primary Expressions.
  19. //===----------------------------------------------------------------------===//
  20. StringLiteral::StringLiteral(const char *strData, unsigned byteLength,
  21. bool Wide, QualType t, SourceLocation firstLoc,
  22. SourceLocation lastLoc) :
  23. Expr(StringLiteralClass, t) {
  24. // OPTIMIZE: could allocate this appended to the StringLiteral.
  25. char *AStrData = new char[byteLength];
  26. memcpy(AStrData, strData, byteLength);
  27. StrData = AStrData;
  28. ByteLength = byteLength;
  29. IsWide = Wide;
  30. firstTokLoc = firstLoc;
  31. lastTokLoc = lastLoc;
  32. }
  33. StringLiteral::~StringLiteral() {
  34. delete[] StrData;
  35. }
  36. bool UnaryOperator::isPostfix(Opcode Op) {
  37. switch (Op) {
  38. case PostInc:
  39. case PostDec:
  40. return true;
  41. default:
  42. return false;
  43. }
  44. }
  45. /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
  46. /// corresponds to, e.g. "sizeof" or "[pre]++".
  47. const char *UnaryOperator::getOpcodeStr(Opcode Op) {
  48. switch (Op) {
  49. default: assert(0 && "Unknown unary operator");
  50. case PostInc: return "++";
  51. case PostDec: return "--";
  52. case PreInc: return "++";
  53. case PreDec: return "--";
  54. case AddrOf: return "&";
  55. case Deref: return "*";
  56. case Plus: return "+";
  57. case Minus: return "-";
  58. case Not: return "~";
  59. case LNot: return "!";
  60. case Real: return "__real";
  61. case Imag: return "__imag";
  62. case SizeOf: return "sizeof";
  63. case AlignOf: return "alignof";
  64. case Extension: return "__extension__";
  65. }
  66. }
  67. //===----------------------------------------------------------------------===//
  68. // Postfix Operators.
  69. //===----------------------------------------------------------------------===//
  70. CallExpr::CallExpr(Expr *fn, Expr **args, unsigned numargs, QualType t,
  71. SourceLocation rparenloc)
  72. : Expr(CallExprClass, t), Fn(fn), NumArgs(numargs) {
  73. Args = new Expr*[numargs];
  74. for (unsigned i = 0; i != numargs; ++i)
  75. Args[i] = args[i];
  76. RParenLoc = rparenloc;
  77. }
  78. /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
  79. /// corresponds to, e.g. "<<=".
  80. const char *BinaryOperator::getOpcodeStr(Opcode Op) {
  81. switch (Op) {
  82. default: assert(0 && "Unknown binary operator");
  83. case Mul: return "*";
  84. case Div: return "/";
  85. case Rem: return "%";
  86. case Add: return "+";
  87. case Sub: return "-";
  88. case Shl: return "<<";
  89. case Shr: return ">>";
  90. case LT: return "<";
  91. case GT: return ">";
  92. case LE: return "<=";
  93. case GE: return ">=";
  94. case EQ: return "==";
  95. case NE: return "!=";
  96. case And: return "&";
  97. case Xor: return "^";
  98. case Or: return "|";
  99. case LAnd: return "&&";
  100. case LOr: return "||";
  101. case Assign: return "=";
  102. case MulAssign: return "*=";
  103. case DivAssign: return "/=";
  104. case RemAssign: return "%=";
  105. case AddAssign: return "+=";
  106. case SubAssign: return "-=";
  107. case ShlAssign: return "<<=";
  108. case ShrAssign: return ">>=";
  109. case AndAssign: return "&=";
  110. case XorAssign: return "^=";
  111. case OrAssign: return "|=";
  112. case Comma: return ",";
  113. }
  114. }
  115. //===----------------------------------------------------------------------===//
  116. // Generic Expression Routines
  117. //===----------------------------------------------------------------------===//
  118. /// hasLocalSideEffect - Return true if this immediate expression has side
  119. /// effects, not counting any sub-expressions.
  120. bool Expr::hasLocalSideEffect() const {
  121. switch (getStmtClass()) {
  122. default:
  123. return false;
  124. case ParenExprClass:
  125. return cast<ParenExpr>(this)->getSubExpr()->hasLocalSideEffect();
  126. case UnaryOperatorClass: {
  127. const UnaryOperator *UO = cast<UnaryOperator>(this);
  128. switch (UO->getOpcode()) {
  129. default: return false;
  130. case UnaryOperator::PostInc:
  131. case UnaryOperator::PostDec:
  132. case UnaryOperator::PreInc:
  133. case UnaryOperator::PreDec:
  134. return true; // ++/--
  135. case UnaryOperator::Deref:
  136. // Dereferencing a volatile pointer is a side-effect.
  137. return getType().isVolatileQualified();
  138. case UnaryOperator::Real:
  139. case UnaryOperator::Imag:
  140. // accessing a piece of a volatile complex is a side-effect.
  141. return UO->getSubExpr()->getType().isVolatileQualified();
  142. case UnaryOperator::Extension:
  143. return UO->getSubExpr()->hasLocalSideEffect();
  144. }
  145. }
  146. case BinaryOperatorClass:
  147. return cast<BinaryOperator>(this)->isAssignmentOp();
  148. case MemberExprClass:
  149. case ArraySubscriptExprClass:
  150. // If the base pointer or element is to a volatile pointer/field, accessing
  151. // if is a side effect.
  152. return getType().isVolatileQualified();
  153. case CallExprClass:
  154. // TODO: check attributes for pure/const. "void foo() { strlen("bar"); }"
  155. // should warn.
  156. return true;
  157. case CastExprClass:
  158. // If this is a cast to void, check the operand. Otherwise, the result of
  159. // the cast is unused.
  160. if (getType()->isVoidType())
  161. return cast<CastExpr>(this)->getSubExpr()->hasLocalSideEffect();
  162. return false;
  163. }
  164. }
  165. /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or an
  166. /// incomplete type other than void. Nonarray expressions that can be lvalues:
  167. /// - name, where name must be a variable
  168. /// - e[i]
  169. /// - (e), where e must be an lvalue
  170. /// - e.name, where e must be an lvalue
  171. /// - e->name
  172. /// - *e, the type of e cannot be a function type
  173. /// - string-constant
  174. ///
  175. Expr::isLvalueResult Expr::isLvalue() {
  176. // first, check the type (C99 6.3.2.1)
  177. if (isa<FunctionType>(TR.getCanonicalType())) // from isObjectType()
  178. return LV_NotObjectType;
  179. if (TR->isIncompleteType() && TR->isVoidType())
  180. return LV_IncompleteVoidType;
  181. // the type looks fine, now check the expression
  182. switch (getStmtClass()) {
  183. case StringLiteralClass: // C99 6.5.1p4
  184. case ArraySubscriptExprClass: // C99 6.5.3p4 (e1[e2] == (*((e1)+(e2))))
  185. // For vectors, make sure base is an lvalue (i.e. not a function call).
  186. if (cast<ArraySubscriptExpr>(this)->getBase()->getType()->isVectorType())
  187. return cast<ArraySubscriptExpr>(this)->getBase()->isLvalue();
  188. return LV_Valid;
  189. case DeclRefExprClass: // C99 6.5.1p2
  190. if (isa<VarDecl>(cast<DeclRefExpr>(this)->getDecl()))
  191. return LV_Valid;
  192. break;
  193. case MemberExprClass: // C99 6.5.2.3p4
  194. const MemberExpr *m = cast<MemberExpr>(this);
  195. return m->isArrow() ? LV_Valid : m->getBase()->isLvalue();
  196. case UnaryOperatorClass: // C99 6.5.3p4
  197. if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Deref)
  198. return LV_Valid;
  199. break;
  200. case ParenExprClass: // C99 6.5.1p5
  201. return cast<ParenExpr>(this)->getSubExpr()->isLvalue();
  202. default:
  203. break;
  204. }
  205. return LV_InvalidExpression;
  206. }
  207. /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
  208. /// does not have an incomplete type, does not have a const-qualified type, and
  209. /// if it is a structure or union, does not have any member (including,
  210. /// recursively, any member or element of all contained aggregates or unions)
  211. /// with a const-qualified type.
  212. Expr::isModifiableLvalueResult Expr::isModifiableLvalue() {
  213. isLvalueResult lvalResult = isLvalue();
  214. switch (lvalResult) {
  215. case LV_Valid: break;
  216. case LV_NotObjectType: return MLV_NotObjectType;
  217. case LV_IncompleteVoidType: return MLV_IncompleteVoidType;
  218. case LV_InvalidExpression: return MLV_InvalidExpression;
  219. }
  220. if (TR.isConstQualified())
  221. return MLV_ConstQualified;
  222. if (TR->isArrayType())
  223. return MLV_ArrayType;
  224. if (TR->isIncompleteType())
  225. return MLV_IncompleteType;
  226. if (const RecordType *r = dyn_cast<RecordType>(TR.getCanonicalType())) {
  227. if (r->hasConstFields())
  228. return MLV_ConstQualified;
  229. }
  230. return MLV_Valid;
  231. }
  232. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  233. /// an integer constant expression. Note: With the introduction of VLA's in
  234. /// C99 the result of the sizeof operator is no longer always a constant
  235. /// expression. The generalization of the wording to include any subexpression
  236. /// that is not evaluated (C99 6.6p3) means that nonconstant subexpressions
  237. /// can appear as operands to other operators (e.g. &&, ||, ?:). For instance,
  238. /// "0 || f()" can be treated as a constant expression. In C90 this expression,
  239. /// occurring in a context requiring a constant, would have been a constraint
  240. /// violation. FIXME: This routine currently implements C90 semantics.
  241. /// To properly implement C99 semantics this routine will need to evaluate
  242. /// expressions involving operators previously mentioned.
  243. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  244. /// comma, etc
  245. ///
  246. /// FIXME: This should ext-warn on overflow during evaluation! ISO C does not
  247. /// permit this.
  248. bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, SourceLocation *Loc,
  249. bool isEvaluated) const {
  250. switch (getStmtClass()) {
  251. default:
  252. if (Loc) *Loc = getLocStart();
  253. return false;
  254. case ParenExprClass:
  255. return cast<ParenExpr>(this)->getSubExpr()->
  256. isIntegerConstantExpr(Result, Loc, isEvaluated);
  257. case IntegerLiteralClass:
  258. Result = cast<IntegerLiteral>(this)->getValue();
  259. break;
  260. case CharacterLiteralClass:
  261. // FIXME: This doesn't set the right width etc.
  262. Result.zextOrTrunc(32); // FIXME: NOT RIGHT IN GENERAL.
  263. Result = cast<CharacterLiteral>(this)->getValue();
  264. break;
  265. case DeclRefExprClass:
  266. if (const EnumConstantDecl *D =
  267. dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(this)->getDecl())) {
  268. Result = D->getInitVal();
  269. break;
  270. }
  271. if (Loc) *Loc = getLocStart();
  272. return false;
  273. case UnaryOperatorClass: {
  274. const UnaryOperator *Exp = cast<UnaryOperator>(this);
  275. // Get the operand value. If this is sizeof/alignof, do not evalute the
  276. // operand. This affects C99 6.6p3.
  277. if (Exp->isSizeOfAlignOfOp()) isEvaluated = false;
  278. if (!Exp->getSubExpr()->isIntegerConstantExpr(Result, Loc, isEvaluated))
  279. return false;
  280. switch (Exp->getOpcode()) {
  281. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  282. // See C99 6.6p3.
  283. default:
  284. if (Loc) *Loc = Exp->getOperatorLoc();
  285. return false;
  286. case UnaryOperator::Extension:
  287. return true;
  288. case UnaryOperator::SizeOf:
  289. case UnaryOperator::AlignOf:
  290. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  291. if (!Exp->getSubExpr()->getType()->isConstantSizeType(Loc))
  292. return false;
  293. // FIXME: Evaluate sizeof/alignof.
  294. Result.zextOrTrunc(32); // FIXME: NOT RIGHT IN GENERAL.
  295. Result = 1; // FIXME: Obviously bogus
  296. break;
  297. case UnaryOperator::LNot: {
  298. bool Val = Result != 0;
  299. Result.zextOrTrunc(32); // FIXME: NOT RIGHT IN GENERAL.
  300. Result = Val;
  301. break;
  302. }
  303. case UnaryOperator::Plus:
  304. // FIXME: Do usual unary promotions here!
  305. break;
  306. case UnaryOperator::Minus:
  307. // FIXME: Do usual unary promotions here!
  308. Result = -Result;
  309. break;
  310. case UnaryOperator::Not:
  311. // FIXME: Do usual unary promotions here!
  312. Result = ~Result;
  313. break;
  314. }
  315. break;
  316. }
  317. case SizeOfAlignOfTypeExprClass: {
  318. const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(this);
  319. // alignof always evaluates to a constant.
  320. if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType(Loc))
  321. return false;
  322. // FIXME: Evaluate sizeof/alignof.
  323. Result.zextOrTrunc(32); // FIXME: NOT RIGHT IN GENERAL.
  324. Result = 1; // FIXME: Obviously bogus
  325. break;
  326. }
  327. case BinaryOperatorClass: {
  328. const BinaryOperator *Exp = cast<BinaryOperator>(this);
  329. // The LHS of a constant expr is always evaluated and needed.
  330. if (!Exp->getLHS()->isIntegerConstantExpr(Result, Loc, isEvaluated))
  331. return false;
  332. llvm::APSInt RHS(Result);
  333. // The short-circuiting &&/|| operators don't necessarily evaluate their
  334. // RHS. Make sure to pass isEvaluated down correctly.
  335. if (Exp->isLogicalOp()) {
  336. bool RHSEval;
  337. if (Exp->getOpcode() == BinaryOperator::LAnd)
  338. RHSEval = Result != 0;
  339. else {
  340. assert(Exp->getOpcode() == BinaryOperator::LOr &&"Unexpected logical");
  341. RHSEval = Result == 0;
  342. }
  343. if (!Exp->getRHS()->isIntegerConstantExpr(RHS, Loc,
  344. isEvaluated & RHSEval))
  345. return false;
  346. } else {
  347. if (!Exp->getRHS()->isIntegerConstantExpr(RHS, Loc, isEvaluated))
  348. return false;
  349. }
  350. // FIXME: These should all do the standard promotions, etc.
  351. switch (Exp->getOpcode()) {
  352. default:
  353. if (Loc) *Loc = getLocStart();
  354. return false;
  355. case BinaryOperator::Mul:
  356. Result *= RHS;
  357. break;
  358. case BinaryOperator::Div:
  359. if (RHS == 0) {
  360. if (!isEvaluated) break;
  361. if (Loc) *Loc = getLocStart();
  362. return false;
  363. }
  364. Result /= RHS;
  365. break;
  366. case BinaryOperator::Rem:
  367. if (RHS == 0) {
  368. if (!isEvaluated) break;
  369. if (Loc) *Loc = getLocStart();
  370. return false;
  371. }
  372. Result %= RHS;
  373. break;
  374. case BinaryOperator::Add: Result += RHS; break;
  375. case BinaryOperator::Sub: Result -= RHS; break;
  376. case BinaryOperator::Shl:
  377. Result <<= RHS.getLimitedValue(Result.getBitWidth()-1);
  378. break;
  379. case BinaryOperator::Shr:
  380. Result >>= RHS.getLimitedValue(Result.getBitWidth()-1);
  381. break;
  382. case BinaryOperator::LT: Result = Result < RHS; break;
  383. case BinaryOperator::GT: Result = Result > RHS; break;
  384. case BinaryOperator::LE: Result = Result <= RHS; break;
  385. case BinaryOperator::GE: Result = Result >= RHS; break;
  386. case BinaryOperator::EQ: Result = Result == RHS; break;
  387. case BinaryOperator::NE: Result = Result != RHS; break;
  388. case BinaryOperator::And: Result &= RHS; break;
  389. case BinaryOperator::Xor: Result ^= RHS; break;
  390. case BinaryOperator::Or: Result |= RHS; break;
  391. case BinaryOperator::LAnd:
  392. Result = Result != 0 && RHS != 0;
  393. break;
  394. case BinaryOperator::LOr:
  395. Result = Result != 0 || RHS != 0;
  396. break;
  397. case BinaryOperator::Comma:
  398. // C99 6.6p3: "shall not contain assignment, ..., or comma operators,
  399. // *except* when they are contained within a subexpression that is not
  400. // evaluated". Note that Assignment can never happen due to constraints
  401. // on the LHS subexpr, so we don't need to check it here.
  402. if (isEvaluated) {
  403. if (Loc) *Loc = getLocStart();
  404. return false;
  405. }
  406. // The result of the constant expr is the RHS.
  407. Result = RHS;
  408. return true;
  409. }
  410. assert(!Exp->isAssignmentOp() && "LHS can't be a constant expr!");
  411. break;
  412. }
  413. case CastExprClass: {
  414. const CastExpr *Exp = cast<CastExpr>(this);
  415. // C99 6.6p6: shall only convert arithmetic types to integer types.
  416. if (!Exp->getSubExpr()->getType()->isArithmeticType() ||
  417. !Exp->getDestType()->isIntegerType()) {
  418. if (Loc) *Loc = Exp->getSubExpr()->getLocStart();
  419. return false;
  420. }
  421. // Handle simple integer->integer casts.
  422. if (Exp->getSubExpr()->getType()->isIntegerType()) {
  423. if (!Exp->getSubExpr()->isIntegerConstantExpr(Result, Loc, isEvaluated))
  424. return false;
  425. // FIXME: do the conversion on Result.
  426. break;
  427. }
  428. // Allow floating constants that are the immediate operands of casts or that
  429. // are parenthesized.
  430. const Expr *Operand = Exp->getSubExpr();
  431. while (const ParenExpr *PE = dyn_cast<ParenExpr>(Operand))
  432. Operand = PE->getSubExpr();
  433. if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(Operand)) {
  434. // FIXME: Evaluate this correctly!
  435. Result = (int)FL->getValue();
  436. break;
  437. }
  438. if (Loc) *Loc = Operand->getLocStart();
  439. return false;
  440. }
  441. case ConditionalOperatorClass: {
  442. const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
  443. if (!Exp->getCond()->isIntegerConstantExpr(Result, Loc, isEvaluated))
  444. return false;
  445. const Expr *TrueExp = Exp->getLHS();
  446. const Expr *FalseExp = Exp->getRHS();
  447. if (Result == 0) std::swap(TrueExp, FalseExp);
  448. // Evaluate the false one first, discard the result.
  449. if (!FalseExp->isIntegerConstantExpr(Result, Loc, false))
  450. return false;
  451. // Evalute the true one, capture the result.
  452. if (!TrueExp->isIntegerConstantExpr(Result, Loc, isEvaluated))
  453. return false;
  454. // FIXME: promotions on result.
  455. break;
  456. }
  457. }
  458. // Cases that are valid constant exprs fall through to here.
  459. Result.setIsUnsigned(getType()->isUnsignedIntegerType());
  460. return true;
  461. }
  462. /// isNullPointerConstant - C99 6.3.2.3p3 - Return true if this is either an
  463. /// integer constant expression with the value zero, or if this is one that is
  464. /// cast to void*.
  465. bool Expr::isNullPointerConstant() const {
  466. // Strip off a cast to void*, if it exists.
  467. if (const CastExpr *CE = dyn_cast<CastExpr>(this)) {
  468. // Check that it is a cast to void*.
  469. if (const PointerType *PT = dyn_cast<PointerType>(CE->getType())) {
  470. QualType Pointee = PT->getPointeeType();
  471. if (Pointee.getQualifiers() == 0 && Pointee->isVoidType() && // to void*
  472. CE->getSubExpr()->getType()->isIntegerType()) // from int.
  473. return CE->getSubExpr()->isNullPointerConstant();
  474. }
  475. } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
  476. // Accept ((void*)0) as a null pointer constant, as many other
  477. // implementations do.
  478. return PE->getSubExpr()->isNullPointerConstant();
  479. }
  480. // This expression must be an integer type.
  481. if (!getType()->isIntegerType())
  482. return false;
  483. // If we have an integer constant expression, we need to *evaluate* it and
  484. // test for the value 0.
  485. llvm::APSInt Val(32);
  486. return isIntegerConstantExpr(Val, 0, true) && Val == 0;
  487. }