blob: ce5a8ce262f047ac0d1f98b5aabb45be595c1705 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- 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
14#include "clang/AST/Expr.h"
Chris Lattner2eadfb62007-07-15 23:32:58 +000015#include "clang/AST/ASTContext.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/StmtVisitor.h"
17#include "clang/Lex/IdentifierTable.h"
18using namespace clang;
19
20//===----------------------------------------------------------------------===//
21// Primary Expressions.
22//===----------------------------------------------------------------------===//
23
24StringLiteral::StringLiteral(const char *strData, unsigned byteLength,
25 bool Wide, QualType t, SourceLocation firstLoc,
26 SourceLocation lastLoc) :
27 Expr(StringLiteralClass, t) {
28 // OPTIMIZE: could allocate this appended to the StringLiteral.
29 char *AStrData = new char[byteLength];
30 memcpy(AStrData, strData, byteLength);
31 StrData = AStrData;
32 ByteLength = byteLength;
33 IsWide = Wide;
34 firstTokLoc = firstLoc;
35 lastTokLoc = lastLoc;
36}
37
38StringLiteral::~StringLiteral() {
39 delete[] StrData;
40}
41
42bool UnaryOperator::isPostfix(Opcode Op) {
43 switch (Op) {
44 case PostInc:
45 case PostDec:
46 return true;
47 default:
48 return false;
49 }
50}
51
52/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
53/// corresponds to, e.g. "sizeof" or "[pre]++".
54const char *UnaryOperator::getOpcodeStr(Opcode Op) {
55 switch (Op) {
56 default: assert(0 && "Unknown unary operator");
57 case PostInc: return "++";
58 case PostDec: return "--";
59 case PreInc: return "++";
60 case PreDec: return "--";
61 case AddrOf: return "&";
62 case Deref: return "*";
63 case Plus: return "+";
64 case Minus: return "-";
65 case Not: return "~";
66 case LNot: return "!";
67 case Real: return "__real";
68 case Imag: return "__imag";
69 case SizeOf: return "sizeof";
70 case AlignOf: return "alignof";
71 case Extension: return "__extension__";
72 }
73}
74
75//===----------------------------------------------------------------------===//
76// Postfix Operators.
77//===----------------------------------------------------------------------===//
78
79CallExpr::CallExpr(Expr *fn, Expr **args, unsigned numargs, QualType t,
80 SourceLocation rparenloc)
Ted Kremenek77ed8e42007-08-24 18:13:47 +000081 : Expr(CallExprClass, t), NumArgs(numargs) {
82 SubExprs = new Expr*[numargs+1];
83 SubExprs[FN] = fn;
Reid Spencer5f016e22007-07-11 17:01:13 +000084 for (unsigned i = 0; i != numargs; ++i)
Ted Kremenek77ed8e42007-08-24 18:13:47 +000085 SubExprs[i+ARGS_START] = args[i];
Reid Spencer5f016e22007-07-11 17:01:13 +000086 RParenLoc = rparenloc;
87}
88
Steve Naroff13b7c5f2007-08-08 22:15:55 +000089bool CallExpr::isBuiltinClassifyType(llvm::APSInt &Result) const {
90 // The following enum mimics gcc's internal "typeclass.h" file.
91 enum gcc_type_class {
92 no_type_class = -1,
93 void_type_class, integer_type_class, char_type_class,
94 enumeral_type_class, boolean_type_class,
95 pointer_type_class, reference_type_class, offset_type_class,
96 real_type_class, complex_type_class,
97 function_type_class, method_type_class,
98 record_type_class, union_type_class,
99 array_type_class, string_type_class,
100 lang_type_class
101 };
102 Result.setIsSigned(true);
103
104 // All simple function calls (e.g. func()) are implicitly cast to pointer to
105 // function. As a result, we try and obtain the DeclRefExpr from the
106 // ImplicitCastExpr.
107 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
108 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
109 return false;
110 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
111 if (!DRE)
112 return false;
113
114 // We have a DeclRefExpr.
115 if (strcmp(DRE->getDecl()->getName(), "__builtin_classify_type") == 0) {
116 // If no argument was supplied, default to "no_type_class". This isn't
117 // ideal, however it's what gcc does.
118 Result = static_cast<uint64_t>(no_type_class);
119 if (NumArgs >= 1) {
120 QualType argType = getArg(0)->getType();
121
122 if (argType->isVoidType())
123 Result = void_type_class;
124 else if (argType->isEnumeralType())
125 Result = enumeral_type_class;
126 else if (argType->isBooleanType())
127 Result = boolean_type_class;
128 else if (argType->isCharType())
129 Result = string_type_class; // gcc doesn't appear to use char_type_class
130 else if (argType->isIntegerType())
131 Result = integer_type_class;
132 else if (argType->isPointerType())
133 Result = pointer_type_class;
134 else if (argType->isReferenceType())
135 Result = reference_type_class;
136 else if (argType->isRealType())
137 Result = real_type_class;
138 else if (argType->isComplexType())
139 Result = complex_type_class;
140 else if (argType->isFunctionType())
141 Result = function_type_class;
142 else if (argType->isStructureType())
143 Result = record_type_class;
144 else if (argType->isUnionType())
145 Result = union_type_class;
146 else if (argType->isArrayType())
147 Result = array_type_class;
148 else if (argType->isUnionType())
149 Result = union_type_class;
150 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
151 assert(1 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
152 }
153 return true;
154 }
155 return false;
156}
157
Reid Spencer5f016e22007-07-11 17:01:13 +0000158/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
159/// corresponds to, e.g. "<<=".
160const char *BinaryOperator::getOpcodeStr(Opcode Op) {
161 switch (Op) {
162 default: assert(0 && "Unknown binary operator");
163 case Mul: return "*";
164 case Div: return "/";
165 case Rem: return "%";
166 case Add: return "+";
167 case Sub: return "-";
168 case Shl: return "<<";
169 case Shr: return ">>";
170 case LT: return "<";
171 case GT: return ">";
172 case LE: return "<=";
173 case GE: return ">=";
174 case EQ: return "==";
175 case NE: return "!=";
176 case And: return "&";
177 case Xor: return "^";
178 case Or: return "|";
179 case LAnd: return "&&";
180 case LOr: return "||";
181 case Assign: return "=";
182 case MulAssign: return "*=";
183 case DivAssign: return "/=";
184 case RemAssign: return "%=";
185 case AddAssign: return "+=";
186 case SubAssign: return "-=";
187 case ShlAssign: return "<<=";
188 case ShrAssign: return ">>=";
189 case AndAssign: return "&=";
190 case XorAssign: return "^=";
191 case OrAssign: return "|=";
192 case Comma: return ",";
193 }
194}
195
196
197//===----------------------------------------------------------------------===//
198// Generic Expression Routines
199//===----------------------------------------------------------------------===//
200
201/// hasLocalSideEffect - Return true if this immediate expression has side
202/// effects, not counting any sub-expressions.
203bool Expr::hasLocalSideEffect() const {
204 switch (getStmtClass()) {
205 default:
206 return false;
207 case ParenExprClass:
208 return cast<ParenExpr>(this)->getSubExpr()->hasLocalSideEffect();
209 case UnaryOperatorClass: {
210 const UnaryOperator *UO = cast<UnaryOperator>(this);
211
212 switch (UO->getOpcode()) {
213 default: return false;
214 case UnaryOperator::PostInc:
215 case UnaryOperator::PostDec:
216 case UnaryOperator::PreInc:
217 case UnaryOperator::PreDec:
218 return true; // ++/--
219
220 case UnaryOperator::Deref:
221 // Dereferencing a volatile pointer is a side-effect.
222 return getType().isVolatileQualified();
223 case UnaryOperator::Real:
224 case UnaryOperator::Imag:
225 // accessing a piece of a volatile complex is a side-effect.
226 return UO->getSubExpr()->getType().isVolatileQualified();
227
228 case UnaryOperator::Extension:
229 return UO->getSubExpr()->hasLocalSideEffect();
230 }
231 }
232 case BinaryOperatorClass:
233 return cast<BinaryOperator>(this)->isAssignmentOp();
234
235 case MemberExprClass:
236 case ArraySubscriptExprClass:
237 // If the base pointer or element is to a volatile pointer/field, accessing
238 // if is a side effect.
239 return getType().isVolatileQualified();
240
241 case CallExprClass:
242 // TODO: check attributes for pure/const. "void foo() { strlen("bar"); }"
243 // should warn.
244 return true;
245
246 case CastExprClass:
247 // If this is a cast to void, check the operand. Otherwise, the result of
248 // the cast is unused.
249 if (getType()->isVoidType())
250 return cast<CastExpr>(this)->getSubExpr()->hasLocalSideEffect();
251 return false;
252 }
253}
254
255/// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or an
256/// incomplete type other than void. Nonarray expressions that can be lvalues:
257/// - name, where name must be a variable
258/// - e[i]
259/// - (e), where e must be an lvalue
260/// - e.name, where e must be an lvalue
261/// - e->name
262/// - *e, the type of e cannot be a function type
263/// - string-constant
Bill Wendling08ad47c2007-07-17 03:52:31 +0000264/// - reference type [C++ [expr]]
Reid Spencer5f016e22007-07-11 17:01:13 +0000265///
Bill Wendlingca51c972007-07-16 07:07:56 +0000266Expr::isLvalueResult Expr::isLvalue() const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000267 // first, check the type (C99 6.3.2.1)
Chris Lattnercb4f9a62007-07-21 05:33:26 +0000268 if (TR->isFunctionType()) // from isObjectType()
Reid Spencer5f016e22007-07-11 17:01:13 +0000269 return LV_NotObjectType;
270
Steve Naroff731ec572007-07-21 13:32:03 +0000271 if (TR->isVoidType())
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 return LV_IncompleteVoidType;
Bill Wendling08ad47c2007-07-17 03:52:31 +0000273
Chris Lattnercb4f9a62007-07-21 05:33:26 +0000274 if (TR->isReferenceType()) // C++ [expr]
Bill Wendling08ad47c2007-07-17 03:52:31 +0000275 return LV_Valid;
276
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 // the type looks fine, now check the expression
278 switch (getStmtClass()) {
279 case StringLiteralClass: // C99 6.5.1p4
280 case ArraySubscriptExprClass: // C99 6.5.3p4 (e1[e2] == (*((e1)+(e2))))
281 // For vectors, make sure base is an lvalue (i.e. not a function call).
282 if (cast<ArraySubscriptExpr>(this)->getBase()->getType()->isVectorType())
283 return cast<ArraySubscriptExpr>(this)->getBase()->isLvalue();
284 return LV_Valid;
285 case DeclRefExprClass: // C99 6.5.1p2
286 if (isa<VarDecl>(cast<DeclRefExpr>(this)->getDecl()))
287 return LV_Valid;
288 break;
Anton Korobeynikovfdd75662007-07-12 15:26:50 +0000289 case MemberExprClass: { // C99 6.5.2.3p4
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 const MemberExpr *m = cast<MemberExpr>(this);
291 return m->isArrow() ? LV_Valid : m->getBase()->isLvalue();
Anton Korobeynikovfdd75662007-07-12 15:26:50 +0000292 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 case UnaryOperatorClass: // C99 6.5.3p4
294 if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Deref)
295 return LV_Valid;
296 break;
297 case ParenExprClass: // C99 6.5.1p5
298 return cast<ParenExpr>(this)->getSubExpr()->isLvalue();
Chris Lattner6481a572007-08-03 17:31:20 +0000299 case OCUVectorElementExprClass:
300 if (cast<OCUVectorElementExpr>(this)->containsDuplicateElements())
Steve Narofffec0b492007-07-30 03:29:09 +0000301 return LV_DuplicateVectorComponents;
302 return LV_Valid;
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 default:
304 break;
305 }
306 return LV_InvalidExpression;
307}
308
309/// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
310/// does not have an incomplete type, does not have a const-qualified type, and
311/// if it is a structure or union, does not have any member (including,
312/// recursively, any member or element of all contained aggregates or unions)
313/// with a const-qualified type.
Bill Wendlingca51c972007-07-16 07:07:56 +0000314Expr::isModifiableLvalueResult Expr::isModifiableLvalue() const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 isLvalueResult lvalResult = isLvalue();
316
317 switch (lvalResult) {
318 case LV_Valid: break;
319 case LV_NotObjectType: return MLV_NotObjectType;
320 case LV_IncompleteVoidType: return MLV_IncompleteVoidType;
Steve Narofffec0b492007-07-30 03:29:09 +0000321 case LV_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 case LV_InvalidExpression: return MLV_InvalidExpression;
323 }
324 if (TR.isConstQualified())
325 return MLV_ConstQualified;
326 if (TR->isArrayType())
327 return MLV_ArrayType;
328 if (TR->isIncompleteType())
329 return MLV_IncompleteType;
330
331 if (const RecordType *r = dyn_cast<RecordType>(TR.getCanonicalType())) {
332 if (r->hasConstFields())
333 return MLV_ConstQualified;
334 }
335 return MLV_Valid;
336}
337
338/// isIntegerConstantExpr - this recursive routine will test if an expression is
339/// an integer constant expression. Note: With the introduction of VLA's in
340/// C99 the result of the sizeof operator is no longer always a constant
341/// expression. The generalization of the wording to include any subexpression
342/// that is not evaluated (C99 6.6p3) means that nonconstant subexpressions
343/// can appear as operands to other operators (e.g. &&, ||, ?:). For instance,
344/// "0 || f()" can be treated as a constant expression. In C90 this expression,
345/// occurring in a context requiring a constant, would have been a constraint
346/// violation. FIXME: This routine currently implements C90 semantics.
347/// To properly implement C99 semantics this routine will need to evaluate
348/// expressions involving operators previously mentioned.
349
350/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
351/// comma, etc
352///
353/// FIXME: This should ext-warn on overflow during evaluation! ISO C does not
354/// permit this.
Chris Lattnerce0afc02007-07-18 05:21:20 +0000355///
356/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
357/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
358/// cast+dereference.
Chris Lattner590b6642007-07-15 23:26:56 +0000359bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
360 SourceLocation *Loc, bool isEvaluated) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 switch (getStmtClass()) {
362 default:
363 if (Loc) *Loc = getLocStart();
364 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 case ParenExprClass:
366 return cast<ParenExpr>(this)->getSubExpr()->
Chris Lattner590b6642007-07-15 23:26:56 +0000367 isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated);
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 case IntegerLiteralClass:
369 Result = cast<IntegerLiteral>(this)->getValue();
370 break;
Chris Lattner2eadfb62007-07-15 23:32:58 +0000371 case CharacterLiteralClass: {
372 const CharacterLiteral *CL = cast<CharacterLiteral>(this);
373 Result.zextOrTrunc(Ctx.getTypeSize(getType(), CL->getLoc()));
374 Result = CL->getValue();
Chris Lattnerf0fbcb32007-07-16 21:04:56 +0000375 Result.setIsUnsigned(!getType()->isSignedIntegerType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 break;
Chris Lattner2eadfb62007-07-15 23:32:58 +0000377 }
Steve Naroff7b658aa2007-08-02 04:09:23 +0000378 case TypesCompatibleExprClass: {
379 const TypesCompatibleExpr *TCE = cast<TypesCompatibleExpr>(this);
380 Result.zextOrTrunc(Ctx.getTypeSize(getType(), TCE->getLocStart()));
381 Result = TCE->typesAreCompatible();
Steve Naroff389cecc2007-08-02 00:13:27 +0000382 break;
Steve Naroff7b658aa2007-08-02 04:09:23 +0000383 }
Steve Naroff13b7c5f2007-08-08 22:15:55 +0000384 case CallExprClass: {
385 const CallExpr *CE = cast<CallExpr>(this);
386 Result.zextOrTrunc(Ctx.getTypeSize(getType(), CE->getLocStart()));
387 if (CE->isBuiltinClassifyType(Result))
388 break;
389 if (Loc) *Loc = getLocStart();
390 return false;
391 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 case DeclRefExprClass:
393 if (const EnumConstantDecl *D =
394 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(this)->getDecl())) {
395 Result = D->getInitVal();
396 break;
397 }
398 if (Loc) *Loc = getLocStart();
399 return false;
400 case UnaryOperatorClass: {
401 const UnaryOperator *Exp = cast<UnaryOperator>(this);
402
403 // Get the operand value. If this is sizeof/alignof, do not evalute the
404 // operand. This affects C99 6.6p3.
Chris Lattner602dafd2007-08-23 21:42:50 +0000405 if (!Exp->isSizeOfAlignOfOp() &&
406 !Exp->getSubExpr()->isIntegerConstantExpr(Result, Ctx, Loc,isEvaluated))
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 return false;
408
409 switch (Exp->getOpcode()) {
410 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
411 // See C99 6.6p3.
412 default:
413 if (Loc) *Loc = Exp->getOperatorLoc();
414 return false;
415 case UnaryOperator::Extension:
Chris Lattner76e773a2007-07-18 18:38:36 +0000416 return true; // FIXME: this is wrong.
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 case UnaryOperator::SizeOf:
418 case UnaryOperator::AlignOf:
419 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattner590b6642007-07-15 23:26:56 +0000420 if (!Exp->getSubExpr()->getType()->isConstantSizeType(Ctx, Loc))
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 return false;
422
Chris Lattner76e773a2007-07-18 18:38:36 +0000423 // Return the result in the right width.
424 Result.zextOrTrunc(Ctx.getTypeSize(getType(), Exp->getOperatorLoc()));
425
426 // Get information about the size or align.
427 if (Exp->getOpcode() == UnaryOperator::SizeOf)
428 Result = Ctx.getTypeSize(Exp->getSubExpr()->getType(),
429 Exp->getOperatorLoc());
430 else
431 Result = Ctx.getTypeAlign(Exp->getSubExpr()->getType(),
432 Exp->getOperatorLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 break;
434 case UnaryOperator::LNot: {
435 bool Val = Result != 0;
Chris Lattner76e773a2007-07-18 18:38:36 +0000436 Result.zextOrTrunc(Ctx.getTypeSize(getType(), Exp->getOperatorLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 Result = Val;
438 break;
439 }
440 case UnaryOperator::Plus:
Reid Spencer5f016e22007-07-11 17:01:13 +0000441 break;
442 case UnaryOperator::Minus:
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 Result = -Result;
444 break;
445 case UnaryOperator::Not:
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 Result = ~Result;
447 break;
448 }
449 break;
450 }
451 case SizeOfAlignOfTypeExprClass: {
452 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(this);
453 // alignof always evaluates to a constant.
Chris Lattner590b6642007-07-15 23:26:56 +0000454 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType(Ctx,Loc))
Reid Spencer5f016e22007-07-11 17:01:13 +0000455 return false;
456
Chris Lattner76e773a2007-07-18 18:38:36 +0000457 // Return the result in the right width.
458 Result.zextOrTrunc(Ctx.getTypeSize(getType(), Exp->getOperatorLoc()));
459
460 // Get information about the size or align.
461 if (Exp->isSizeOf())
462 Result = Ctx.getTypeSize(Exp->getArgumentType(), Exp->getOperatorLoc());
463 else
464 Result = Ctx.getTypeAlign(Exp->getArgumentType(), Exp->getOperatorLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 break;
466 }
467 case BinaryOperatorClass: {
468 const BinaryOperator *Exp = cast<BinaryOperator>(this);
469
470 // The LHS of a constant expr is always evaluated and needed.
Chris Lattner590b6642007-07-15 23:26:56 +0000471 if (!Exp->getLHS()->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 return false;
473
474 llvm::APSInt RHS(Result);
475
476 // The short-circuiting &&/|| operators don't necessarily evaluate their
477 // RHS. Make sure to pass isEvaluated down correctly.
478 if (Exp->isLogicalOp()) {
479 bool RHSEval;
480 if (Exp->getOpcode() == BinaryOperator::LAnd)
481 RHSEval = Result != 0;
482 else {
483 assert(Exp->getOpcode() == BinaryOperator::LOr &&"Unexpected logical");
484 RHSEval = Result == 0;
485 }
486
Chris Lattner590b6642007-07-15 23:26:56 +0000487 if (!Exp->getRHS()->isIntegerConstantExpr(RHS, Ctx, Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000488 isEvaluated & RHSEval))
489 return false;
490 } else {
Chris Lattner590b6642007-07-15 23:26:56 +0000491 if (!Exp->getRHS()->isIntegerConstantExpr(RHS, Ctx, Loc, isEvaluated))
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 return false;
493 }
494
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 switch (Exp->getOpcode()) {
496 default:
497 if (Loc) *Loc = getLocStart();
498 return false;
499 case BinaryOperator::Mul:
500 Result *= RHS;
501 break;
502 case BinaryOperator::Div:
503 if (RHS == 0) {
504 if (!isEvaluated) break;
505 if (Loc) *Loc = getLocStart();
506 return false;
507 }
508 Result /= RHS;
509 break;
510 case BinaryOperator::Rem:
511 if (RHS == 0) {
512 if (!isEvaluated) break;
513 if (Loc) *Loc = getLocStart();
514 return false;
515 }
516 Result %= RHS;
517 break;
518 case BinaryOperator::Add: Result += RHS; break;
519 case BinaryOperator::Sub: Result -= RHS; break;
520 case BinaryOperator::Shl:
521 Result <<= RHS.getLimitedValue(Result.getBitWidth()-1);
522 break;
523 case BinaryOperator::Shr:
524 Result >>= RHS.getLimitedValue(Result.getBitWidth()-1);
525 break;
526 case BinaryOperator::LT: Result = Result < RHS; break;
527 case BinaryOperator::GT: Result = Result > RHS; break;
528 case BinaryOperator::LE: Result = Result <= RHS; break;
529 case BinaryOperator::GE: Result = Result >= RHS; break;
530 case BinaryOperator::EQ: Result = Result == RHS; break;
531 case BinaryOperator::NE: Result = Result != RHS; break;
532 case BinaryOperator::And: Result &= RHS; break;
533 case BinaryOperator::Xor: Result ^= RHS; break;
534 case BinaryOperator::Or: Result |= RHS; break;
535 case BinaryOperator::LAnd:
536 Result = Result != 0 && RHS != 0;
537 break;
538 case BinaryOperator::LOr:
539 Result = Result != 0 || RHS != 0;
540 break;
541
542 case BinaryOperator::Comma:
543 // C99 6.6p3: "shall not contain assignment, ..., or comma operators,
544 // *except* when they are contained within a subexpression that is not
545 // evaluated". Note that Assignment can never happen due to constraints
546 // on the LHS subexpr, so we don't need to check it here.
547 if (isEvaluated) {
548 if (Loc) *Loc = getLocStart();
549 return false;
550 }
551
552 // The result of the constant expr is the RHS.
553 Result = RHS;
554 return true;
555 }
556
557 assert(!Exp->isAssignmentOp() && "LHS can't be a constant expr!");
558 break;
559 }
Chris Lattner26dc7b32007-07-15 23:54:50 +0000560 case ImplicitCastExprClass:
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 case CastExprClass: {
Chris Lattner26dc7b32007-07-15 23:54:50 +0000562 const Expr *SubExpr;
563 SourceLocation CastLoc;
564 if (const CastExpr *C = dyn_cast<CastExpr>(this)) {
565 SubExpr = C->getSubExpr();
566 CastLoc = C->getLParenLoc();
567 } else {
568 SubExpr = cast<ImplicitCastExpr>(this)->getSubExpr();
569 CastLoc = getLocStart();
570 }
571
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 // C99 6.6p6: shall only convert arithmetic types to integer types.
Chris Lattner26dc7b32007-07-15 23:54:50 +0000573 if (!SubExpr->getType()->isArithmeticType() ||
574 !getType()->isIntegerType()) {
575 if (Loc) *Loc = SubExpr->getLocStart();
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 return false;
577 }
578
579 // Handle simple integer->integer casts.
Chris Lattner26dc7b32007-07-15 23:54:50 +0000580 if (SubExpr->getType()->isIntegerType()) {
581 if (!SubExpr->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 return false;
Chris Lattner26dc7b32007-07-15 23:54:50 +0000583
584 // Figure out if this is a truncate, extend or noop cast.
585 unsigned DestWidth = Ctx.getTypeSize(getType(), CastLoc);
586
587 // If the input is signed, do a sign extend, noop, or truncate.
588 if (SubExpr->getType()->isSignedIntegerType())
589 Result.sextOrTrunc(DestWidth);
590 else // If the input is unsigned, do a zero extend, noop, or truncate.
591 Result.zextOrTrunc(DestWidth);
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 break;
593 }
594
595 // Allow floating constants that are the immediate operands of casts or that
596 // are parenthesized.
Chris Lattner26dc7b32007-07-15 23:54:50 +0000597 const Expr *Operand = SubExpr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 while (const ParenExpr *PE = dyn_cast<ParenExpr>(Operand))
599 Operand = PE->getSubExpr();
600
601 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(Operand)) {
602 // FIXME: Evaluate this correctly!
603 Result = (int)FL->getValue();
604 break;
605 }
606 if (Loc) *Loc = Operand->getLocStart();
607 return false;
608 }
609 case ConditionalOperatorClass: {
610 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
611
Chris Lattner590b6642007-07-15 23:26:56 +0000612 if (!Exp->getCond()->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
Reid Spencer5f016e22007-07-11 17:01:13 +0000613 return false;
614
615 const Expr *TrueExp = Exp->getLHS();
616 const Expr *FalseExp = Exp->getRHS();
617 if (Result == 0) std::swap(TrueExp, FalseExp);
618
619 // Evaluate the false one first, discard the result.
Chris Lattner590b6642007-07-15 23:26:56 +0000620 if (!FalseExp->isIntegerConstantExpr(Result, Ctx, Loc, false))
Reid Spencer5f016e22007-07-11 17:01:13 +0000621 return false;
622 // Evalute the true one, capture the result.
Chris Lattner590b6642007-07-15 23:26:56 +0000623 if (!TrueExp->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 break;
626 }
627 }
628
629 // Cases that are valid constant exprs fall through to here.
630 Result.setIsUnsigned(getType()->isUnsignedIntegerType());
631 return true;
632}
633
634
635/// isNullPointerConstant - C99 6.3.2.3p3 - Return true if this is either an
636/// integer constant expression with the value zero, or if this is one that is
637/// cast to void*.
Chris Lattner590b6642007-07-15 23:26:56 +0000638bool Expr::isNullPointerConstant(ASTContext &Ctx) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 // Strip off a cast to void*, if it exists.
640 if (const CastExpr *CE = dyn_cast<CastExpr>(this)) {
641 // Check that it is a cast to void*.
642 if (const PointerType *PT = dyn_cast<PointerType>(CE->getType())) {
643 QualType Pointee = PT->getPointeeType();
644 if (Pointee.getQualifiers() == 0 && Pointee->isVoidType() && // to void*
645 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Chris Lattner590b6642007-07-15 23:26:56 +0000646 return CE->getSubExpr()->isNullPointerConstant(Ctx);
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 }
648 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
649 // Accept ((void*)0) as a null pointer constant, as many other
650 // implementations do.
Chris Lattner590b6642007-07-15 23:26:56 +0000651 return PE->getSubExpr()->isNullPointerConstant(Ctx);
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 }
653
654 // This expression must be an integer type.
655 if (!getType()->isIntegerType())
656 return false;
657
658 // If we have an integer constant expression, we need to *evaluate* it and
659 // test for the value 0.
660 llvm::APSInt Val(32);
Chris Lattner590b6642007-07-15 23:26:56 +0000661 return isIntegerConstantExpr(Val, Ctx, 0, true) && Val == 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000662}
Steve Naroff31a45842007-07-28 23:10:27 +0000663
Chris Lattner6481a572007-08-03 17:31:20 +0000664unsigned OCUVectorElementExpr::getNumElements() const {
Chris Lattner4d0ac882007-08-03 16:00:20 +0000665 return strlen(Accessor.getName());
666}
667
668
Chris Lattnercb92a112007-08-02 21:47:28 +0000669/// getComponentType - Determine whether the components of this access are
670/// "point" "color" or "texture" elements.
Chris Lattner6481a572007-08-03 17:31:20 +0000671OCUVectorElementExpr::ElementType
672OCUVectorElementExpr::getElementType() const {
Steve Naroff31a45842007-07-28 23:10:27 +0000673 // derive the component type, no need to waste space.
674 const char *compStr = Accessor.getName();
Chris Lattnerb4878f42007-08-02 22:20:00 +0000675
Chris Lattner88dca042007-08-02 22:33:49 +0000676 if (OCUVectorType::getPointAccessorIdx(*compStr) != -1) return Point;
677 if (OCUVectorType::getColorAccessorIdx(*compStr) != -1) return Color;
Chris Lattnerb4878f42007-08-02 22:20:00 +0000678
Chris Lattner88dca042007-08-02 22:33:49 +0000679 assert(OCUVectorType::getTextureAccessorIdx(*compStr) != -1 &&
Chris Lattnerb4878f42007-08-02 22:20:00 +0000680 "getComponentType(): Illegal accessor");
681 return Texture;
Steve Naroff31a45842007-07-28 23:10:27 +0000682}
Steve Narofffec0b492007-07-30 03:29:09 +0000683
Chris Lattner6481a572007-08-03 17:31:20 +0000684/// containsDuplicateElements - Return true if any element access is
Chris Lattnercb92a112007-08-02 21:47:28 +0000685/// repeated.
Chris Lattner6481a572007-08-03 17:31:20 +0000686bool OCUVectorElementExpr::containsDuplicateElements() const {
Steve Narofffec0b492007-07-30 03:29:09 +0000687 const char *compStr = Accessor.getName();
688 unsigned length = strlen(compStr);
689
690 for (unsigned i = 0; i < length-1; i++) {
691 const char *s = compStr+i;
692 for (const char c = *s++; *s; s++)
693 if (c == *s)
694 return true;
695 }
696 return false;
697}
Chris Lattnerb8f849d2007-08-02 23:36:59 +0000698
699/// getEncodedElementAccess - We encode fields with two bits per component.
Chris Lattner6481a572007-08-03 17:31:20 +0000700unsigned OCUVectorElementExpr::getEncodedElementAccess() const {
Chris Lattnerb8f849d2007-08-02 23:36:59 +0000701 const char *compStr = Accessor.getName();
Chris Lattner6481a572007-08-03 17:31:20 +0000702 unsigned length = getNumElements();
Chris Lattnerb8f849d2007-08-02 23:36:59 +0000703
704 unsigned Result = 0;
705
706 while (length--) {
707 Result <<= 2;
708 int Idx = OCUVectorType::getAccessorIdx(compStr[length]);
709 assert(Idx != -1 && "Invalid accessor letter");
710 Result |= Idx;
711 }
712 return Result;
713}
714
Ted Kremenek77ed8e42007-08-24 18:13:47 +0000715//===----------------------------------------------------------------------===//
716// Child Iterators for iterating over subexpressions/substatements
717//===----------------------------------------------------------------------===//
718
719// DeclRefExpr
720Stmt::child_iterator DeclRefExpr::child_begin() { return NULL; }
721Stmt::child_iterator DeclRefExpr::child_end() { return NULL; }
722
723// PreDefinedExpr
724Stmt::child_iterator PreDefinedExpr::child_begin() { return NULL; }
725Stmt::child_iterator PreDefinedExpr::child_end() { return NULL; }
726
727// IntegerLiteral
728Stmt::child_iterator IntegerLiteral::child_begin() { return NULL; }
729Stmt::child_iterator IntegerLiteral::child_end() { return NULL; }
730
731// CharacterLiteral
732Stmt::child_iterator CharacterLiteral::child_begin() { return NULL; }
733Stmt::child_iterator CharacterLiteral::child_end() { return NULL; }
734
735// FloatingLiteral
736Stmt::child_iterator FloatingLiteral::child_begin() { return NULL; }
737Stmt::child_iterator FloatingLiteral::child_end() { return NULL; }
738
739// StringLiteral
740Stmt::child_iterator StringLiteral::child_begin() { return NULL; }
741Stmt::child_iterator StringLiteral::child_end() { return NULL; }
742
743// ParenExpr
744Stmt::child_iterator ParenExpr::child_begin() {
745 return reinterpret_cast<Stmt**>(&Val);
746}
747
748Stmt::child_iterator ParenExpr::child_end() {
749 return child_begin()+1;
750}
751
752// UnaryOperator
753Stmt::child_iterator UnaryOperator::child_begin() {
754 return reinterpret_cast<Stmt**>(&Val);
755}
756
757Stmt::child_iterator UnaryOperator::child_end() {
758 return child_begin()+1;
759}
760
761// SizeOfAlignOfTypeExpr
762Stmt::child_iterator SizeOfAlignOfTypeExpr::child_begin() {
763 return NULL;
764}
765
766Stmt::child_iterator SizeOfAlignOfTypeExpr::child_end() {
767 return NULL;
768}
769
770// ArraySubscriptExpr
771Stmt::child_iterator ArraySubscriptExpr::child_begin() {
772 return reinterpret_cast<Stmt**>(&SubExprs);
773}
774
775Stmt::child_iterator ArraySubscriptExpr::child_end() {
776 return child_begin()+END_EXPR;
777}
778
779// CallExpr
780Stmt::child_iterator CallExpr::child_begin() {
781 return reinterpret_cast<Stmt**>(&SubExprs);
782}
783
784Stmt::child_iterator CallExpr::child_end() {
785 return child_begin()+NumArgs+ARGS_START;
786}