SemaExpr.cpp revision cde3a2d585f80c567c3367ffcbcde0b1b041368f
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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 semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Designator.h"
26#include "clang/Parse/Scope.h"
27using namespace clang;
28
29/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
41  // See if the decl is deprecated.
42  if (D->getAttr<DeprecatedAttr>()) {
43    // Implementing deprecated stuff requires referencing deprecated
44    // stuff. Don't warn if we are implementing a deprecated
45    // construct.
46    bool isSilenced = false;
47
48    if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49      // If this reference happens *in* a deprecated function or method, don't
50      // warn.
51      isSilenced = ND->getAttr<DeprecatedAttr>();
52
53      // If this is an Objective-C method implementation, check to see if the
54      // method was deprecated on the declaration, not the definition.
55      if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56        // The semantic decl context of a ObjCMethodDecl is the
57        // ObjCImplementationDecl.
58        if (ObjCImplementationDecl *Impl
59              = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
61          MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
62                                                    MD->isInstanceMethod());
63          isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
64        }
65      }
66    }
67
68    if (!isSilenced)
69      Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70  }
71
72  // See if this is a deleted function.
73  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74    if (FD->isDeleted()) {
75      Diag(Loc, diag::err_deleted_function_use);
76      Diag(D->getLocation(), diag::note_unavailable_here) << true;
77      return true;
78    }
79  }
80
81  // See if the decl is unavailable
82  if (D->getAttr<UnavailableAttr>()) {
83    Diag(Loc, diag::warn_unavailable) << D->getDeclName();
84    Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85  }
86
87  return false;
88}
89
90SourceRange Sema::getExprRange(ExprTy *E) const {
91  Expr *Ex = (Expr *)E;
92  return Ex? Ex->getSourceRange() : SourceRange();
93}
94
95//===----------------------------------------------------------------------===//
96//  Standard Promotions and Conversions
97//===----------------------------------------------------------------------===//
98
99/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
100void Sema::DefaultFunctionArrayConversion(Expr *&E) {
101  QualType Ty = E->getType();
102  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
103
104  if (Ty->isFunctionType())
105    ImpCastExprToType(E, Context.getPointerType(Ty));
106  else if (Ty->isArrayType()) {
107    // In C90 mode, arrays only promote to pointers if the array expression is
108    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
109    // type 'array of type' is converted to an expression that has type 'pointer
110    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
111    // that has type 'array of type' ...".  The relevant change is "an lvalue"
112    // (C90) to "an expression" (C99).
113    //
114    // C++ 4.2p1:
115    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
116    // T" can be converted to an rvalue of type "pointer to T".
117    //
118    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
119        E->isLvalue(Context) == Expr::LV_Valid)
120      ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
121  }
122}
123
124/// UsualUnaryConversions - Performs various conversions that are common to most
125/// operators (C99 6.3). The conversions of array and function types are
126/// sometimes surpressed. For example, the array->pointer conversion doesn't
127/// apply if the array is an argument to the sizeof or address (&) operators.
128/// In these instances, this routine should *not* be called.
129Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
130  QualType Ty = Expr->getType();
131  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
132
133  if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
134    ImpCastExprToType(Expr, Context.IntTy);
135  else
136    DefaultFunctionArrayConversion(Expr);
137
138  return Expr;
139}
140
141/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
142/// do not have a prototype. Arguments that have type float are promoted to
143/// double. All other argument types are converted by UsualUnaryConversions().
144void Sema::DefaultArgumentPromotion(Expr *&Expr) {
145  QualType Ty = Expr->getType();
146  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
147
148  // If this is a 'float' (CVR qualified or typedef) promote to double.
149  if (const BuiltinType *BT = Ty->getAsBuiltinType())
150    if (BT->getKind() == BuiltinType::Float)
151      return ImpCastExprToType(Expr, Context.DoubleTy);
152
153  UsualUnaryConversions(Expr);
154}
155
156// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
157// will warn if the resulting type is not a POD type.
158void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
159  DefaultArgumentPromotion(Expr);
160
161  if (!Expr->getType()->isPODType()) {
162    Diag(Expr->getLocStart(),
163         diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
164    Expr->getType() << CT;
165  }
166}
167
168
169/// UsualArithmeticConversions - Performs various conversions that are common to
170/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
171/// routine returns the first non-arithmetic type found. The client is
172/// responsible for emitting appropriate error diagnostics.
173/// FIXME: verify the conversion rules for "complex int" are consistent with
174/// GCC.
175QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
176                                          bool isCompAssign) {
177  if (!isCompAssign) {
178    UsualUnaryConversions(lhsExpr);
179    UsualUnaryConversions(rhsExpr);
180  }
181
182  // For conversion purposes, we ignore any qualifiers.
183  // For example, "const float" and "float" are equivalent.
184  QualType lhs =
185    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
186  QualType rhs =
187    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
188
189  // If both types are identical, no conversion is needed.
190  if (lhs == rhs)
191    return lhs;
192
193  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
194  // The caller can deal with this (e.g. pointer + int).
195  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
196    return lhs;
197
198  QualType destType = UsualArithmeticConversionsType(lhs, rhs);
199  if (!isCompAssign) {
200    ImpCastExprToType(lhsExpr, destType);
201    ImpCastExprToType(rhsExpr, destType);
202  }
203  return destType;
204}
205
206QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
207  // Perform the usual unary conversions. We do this early so that
208  // integral promotions to "int" can allow us to exit early, in the
209  // lhs == rhs check. Also, for conversion purposes, we ignore any
210  // qualifiers.  For example, "const float" and "float" are
211  // equivalent.
212  if (lhs->isPromotableIntegerType())
213    lhs = Context.IntTy;
214  else
215    lhs = lhs.getUnqualifiedType();
216  if (rhs->isPromotableIntegerType())
217    rhs = Context.IntTy;
218  else
219    rhs = rhs.getUnqualifiedType();
220
221  // If both types are identical, no conversion is needed.
222  if (lhs == rhs)
223    return lhs;
224
225  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
226  // The caller can deal with this (e.g. pointer + int).
227  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
228    return lhs;
229
230  // At this point, we have two different arithmetic types.
231
232  // Handle complex types first (C99 6.3.1.8p1).
233  if (lhs->isComplexType() || rhs->isComplexType()) {
234    // if we have an integer operand, the result is the complex type.
235    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
236      // convert the rhs to the lhs complex type.
237      return lhs;
238    }
239    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
240      // convert the lhs to the rhs complex type.
241      return rhs;
242    }
243    // This handles complex/complex, complex/float, or float/complex.
244    // When both operands are complex, the shorter operand is converted to the
245    // type of the longer, and that is the type of the result. This corresponds
246    // to what is done when combining two real floating-point operands.
247    // The fun begins when size promotion occur across type domains.
248    // From H&S 6.3.4: When one operand is complex and the other is a real
249    // floating-point type, the less precise type is converted, within it's
250    // real or complex domain, to the precision of the other type. For example,
251    // when combining a "long double" with a "double _Complex", the
252    // "double _Complex" is promoted to "long double _Complex".
253    int result = Context.getFloatingTypeOrder(lhs, rhs);
254
255    if (result > 0) { // The left side is bigger, convert rhs.
256      rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
257    } else if (result < 0) { // The right side is bigger, convert lhs.
258      lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
259    }
260    // At this point, lhs and rhs have the same rank/size. Now, make sure the
261    // domains match. This is a requirement for our implementation, C99
262    // does not require this promotion.
263    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
264      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
265        return rhs;
266      } else { // handle "_Complex double, double".
267        return lhs;
268      }
269    }
270    return lhs; // The domain/size match exactly.
271  }
272  // Now handle "real" floating types (i.e. float, double, long double).
273  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
274    // if we have an integer operand, the result is the real floating type.
275    if (rhs->isIntegerType()) {
276      // convert rhs to the lhs floating point type.
277      return lhs;
278    }
279    if (rhs->isComplexIntegerType()) {
280      // convert rhs to the complex floating point type.
281      return Context.getComplexType(lhs);
282    }
283    if (lhs->isIntegerType()) {
284      // convert lhs to the rhs floating point type.
285      return rhs;
286    }
287    if (lhs->isComplexIntegerType()) {
288      // convert lhs to the complex floating point type.
289      return Context.getComplexType(rhs);
290    }
291    // We have two real floating types, float/complex combos were handled above.
292    // Convert the smaller operand to the bigger result.
293    int result = Context.getFloatingTypeOrder(lhs, rhs);
294    if (result > 0) // convert the rhs
295      return lhs;
296    assert(result < 0 && "illegal float comparison");
297    return rhs;   // convert the lhs
298  }
299  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
300    // Handle GCC complex int extension.
301    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
302    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
303
304    if (lhsComplexInt && rhsComplexInt) {
305      if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
306                                      rhsComplexInt->getElementType()) >= 0)
307        return lhs; // convert the rhs
308      return rhs;
309    } else if (lhsComplexInt && rhs->isIntegerType()) {
310      // convert the rhs to the lhs complex type.
311      return lhs;
312    } else if (rhsComplexInt && lhs->isIntegerType()) {
313      // convert the lhs to the rhs complex type.
314      return rhs;
315    }
316  }
317  // Finally, we have two differing integer types.
318  // The rules for this case are in C99 6.3.1.8
319  int compare = Context.getIntegerTypeOrder(lhs, rhs);
320  bool lhsSigned = lhs->isSignedIntegerType(),
321       rhsSigned = rhs->isSignedIntegerType();
322  QualType destType;
323  if (lhsSigned == rhsSigned) {
324    // Same signedness; use the higher-ranked type
325    destType = compare >= 0 ? lhs : rhs;
326  } else if (compare != (lhsSigned ? 1 : -1)) {
327    // The unsigned type has greater than or equal rank to the
328    // signed type, so use the unsigned type
329    destType = lhsSigned ? rhs : lhs;
330  } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
331    // The two types are different widths; if we are here, that
332    // means the signed type is larger than the unsigned type, so
333    // use the signed type.
334    destType = lhsSigned ? lhs : rhs;
335  } else {
336    // The signed type is higher-ranked than the unsigned type,
337    // but isn't actually any bigger (like unsigned int and long
338    // on most 32-bit systems).  Use the unsigned type corresponding
339    // to the signed type.
340    destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
341  }
342  return destType;
343}
344
345//===----------------------------------------------------------------------===//
346//  Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
351/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
353/// multiple tokens.  However, the common case is that StringToks points to one
354/// string.
355///
356Action::OwningExprResult
357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
358  assert(NumStringToks && "Must have at least one string!");
359
360  StringLiteralParser Literal(StringToks, NumStringToks, PP);
361  if (Literal.hadError)
362    return ExprError();
363
364  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
365  for (unsigned i = 0; i != NumStringToks; ++i)
366    StringTokLocs.push_back(StringToks[i].getLocation());
367
368  QualType StrTy = Context.CharTy;
369  if (Literal.AnyWide) StrTy = Context.getWCharType();
370  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
371
372  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
373  if (getLangOptions().CPlusPlus)
374    StrTy.addConst();
375
376  // Get an array type for the string, according to C99 6.4.5.  This includes
377  // the nul terminator character as well as the string length for pascal
378  // strings.
379  StrTy = Context.getConstantArrayType(StrTy,
380                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
381                                       ArrayType::Normal, 0);
382
383  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
384  return Owned(StringLiteral::Create(Context, Literal.GetString(),
385                                     Literal.GetStringLength(),
386                                     Literal.AnyWide, StrTy,
387                                     &StringTokLocs[0],
388                                     StringTokLocs.size()));
389}
390
391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
392/// CurBlock to VD should cause it to be snapshotted (as we do for auto
393/// variables defined outside the block) or false if this is not needed (e.g.
394/// for values inside the block or for globals).
395///
396/// FIXME: This will create BlockDeclRefExprs for global variables,
397/// function references, etc which is suboptimal :) and breaks
398/// things like "integer constant expression" tests.
399static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
400                                              ValueDecl *VD) {
401  // If the value is defined inside the block, we couldn't snapshot it even if
402  // we wanted to.
403  if (CurBlock->TheDecl == VD->getDeclContext())
404    return false;
405
406  // If this is an enum constant or function, it is constant, don't snapshot.
407  if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
408    return false;
409
410  // If this is a reference to an extern, static, or global variable, no need to
411  // snapshot it.
412  // FIXME: What about 'const' variables in C++?
413  if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
414    return Var->hasLocalStorage();
415
416  return true;
417}
418
419
420
421/// ActOnIdentifierExpr - The parser read an identifier in expression context,
422/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
423/// identifier is used in a function call context.
424/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
425/// class or namespace that the identifier must be a member of.
426Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
427                                                 IdentifierInfo &II,
428                                                 bool HasTrailingLParen,
429                                                 const CXXScopeSpec *SS,
430                                                 bool isAddressOfOperand) {
431  return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
432                                  isAddressOfOperand);
433}
434
435/// BuildDeclRefExpr - Build either a DeclRefExpr or a
436/// QualifiedDeclRefExpr based on whether or not SS is a
437/// nested-name-specifier.
438DeclRefExpr *
439Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
440                       bool TypeDependent, bool ValueDependent,
441                       const CXXScopeSpec *SS) {
442  if (SS && !SS->isEmpty()) {
443    llvm::SmallVector<NestedNameSpecifier, 16> Specs;
444    for (CXXScopeSpec::iterator Spec = SS->begin(), SpecEnd = SS->end();
445         Spec != SpecEnd; ++Spec)
446      Specs.push_back(NestedNameSpecifier::getFromOpaquePtr(*Spec));
447    return QualifiedDeclRefExpr::Create(Context, D, Ty, Loc, TypeDependent,
448                                        ValueDependent, SS->getRange(),
449                                        &Specs[0], Specs.size());
450  } else
451    return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
452}
453
454/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
455/// variable corresponding to the anonymous union or struct whose type
456/// is Record.
457static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
458  assert(Record->isAnonymousStructOrUnion() &&
459         "Record must be an anonymous struct or union!");
460
461  // FIXME: Once Decls are directly linked together, this will
462  // be an O(1) operation rather than a slow walk through DeclContext's
463  // vector (which itself will be eliminated). DeclGroups might make
464  // this even better.
465  DeclContext *Ctx = Record->getDeclContext();
466  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
467                               DEnd = Ctx->decls_end();
468       D != DEnd; ++D) {
469    if (*D == Record) {
470      // The object for the anonymous struct/union directly
471      // follows its type in the list of declarations.
472      ++D;
473      assert(D != DEnd && "Missing object for anonymous record");
474      assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
475      return *D;
476    }
477  }
478
479  assert(false && "Missing object for anonymous record");
480  return 0;
481}
482
483Sema::OwningExprResult
484Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
485                                               FieldDecl *Field,
486                                               Expr *BaseObjectExpr,
487                                               SourceLocation OpLoc) {
488  assert(Field->getDeclContext()->isRecord() &&
489         cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
490         && "Field must be stored inside an anonymous struct or union");
491
492  // Construct the sequence of field member references
493  // we'll have to perform to get to the field in the anonymous
494  // union/struct. The list of members is built from the field
495  // outward, so traverse it backwards to go from an object in
496  // the current context to the field we found.
497  llvm::SmallVector<FieldDecl *, 4> AnonFields;
498  AnonFields.push_back(Field);
499  VarDecl *BaseObject = 0;
500  DeclContext *Ctx = Field->getDeclContext();
501  do {
502    RecordDecl *Record = cast<RecordDecl>(Ctx);
503    Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
504    if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
505      AnonFields.push_back(AnonField);
506    else {
507      BaseObject = cast<VarDecl>(AnonObject);
508      break;
509    }
510    Ctx = Ctx->getParent();
511  } while (Ctx->isRecord() &&
512           cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
513
514  // Build the expression that refers to the base object, from
515  // which we will build a sequence of member references to each
516  // of the anonymous union objects and, eventually, the field we
517  // found via name lookup.
518  bool BaseObjectIsPointer = false;
519  unsigned ExtraQuals = 0;
520  if (BaseObject) {
521    // BaseObject is an anonymous struct/union variable (and is,
522    // therefore, not part of another non-anonymous record).
523    if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
524    BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
525                                               SourceLocation());
526    ExtraQuals
527      = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
528  } else if (BaseObjectExpr) {
529    // The caller provided the base object expression. Determine
530    // whether its a pointer and whether it adds any qualifiers to the
531    // anonymous struct/union fields we're looking into.
532    QualType ObjectType = BaseObjectExpr->getType();
533    if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
534      BaseObjectIsPointer = true;
535      ObjectType = ObjectPtr->getPointeeType();
536    }
537    ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
538  } else {
539    // We've found a member of an anonymous struct/union that is
540    // inside a non-anonymous struct/union, so in a well-formed
541    // program our base object expression is "this".
542    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
543      if (!MD->isStatic()) {
544        QualType AnonFieldType
545          = Context.getTagDeclType(
546                     cast<RecordDecl>(AnonFields.back()->getDeclContext()));
547        QualType ThisType = Context.getTagDeclType(MD->getParent());
548        if ((Context.getCanonicalType(AnonFieldType)
549               == Context.getCanonicalType(ThisType)) ||
550            IsDerivedFrom(ThisType, AnonFieldType)) {
551          // Our base object expression is "this".
552          BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
553                                                     MD->getThisType(Context));
554          BaseObjectIsPointer = true;
555        }
556      } else {
557        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
558          << Field->getDeclName());
559      }
560      ExtraQuals = MD->getTypeQualifiers();
561    }
562
563    if (!BaseObjectExpr)
564      return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
565        << Field->getDeclName());
566  }
567
568  // Build the implicit member references to the field of the
569  // anonymous struct/union.
570  Expr *Result = BaseObjectExpr;
571  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
572         FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
573       FI != FIEnd; ++FI) {
574    QualType MemberType = (*FI)->getType();
575    if (!(*FI)->isMutable()) {
576      unsigned combinedQualifiers
577        = MemberType.getCVRQualifiers() | ExtraQuals;
578      MemberType = MemberType.getQualifiedType(combinedQualifiers);
579    }
580    Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
581                                      OpLoc, MemberType);
582    BaseObjectIsPointer = false;
583    ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
584  }
585
586  return Owned(Result);
587}
588
589/// ActOnDeclarationNameExpr - The parser has read some kind of name
590/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
591/// performs lookup on that name and returns an expression that refers
592/// to that name. This routine isn't directly called from the parser,
593/// because the parser doesn't know about DeclarationName. Rather,
594/// this routine is called by ActOnIdentifierExpr,
595/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
596/// which form the DeclarationName from the corresponding syntactic
597/// forms.
598///
599/// HasTrailingLParen indicates whether this identifier is used in a
600/// function call context.  LookupCtx is only used for a C++
601/// qualified-id (foo::bar) to indicate the class or namespace that
602/// the identifier must be a member of.
603///
604/// isAddressOfOperand means that this expression is the direct operand
605/// of an address-of operator. This matters because this is the only
606/// situation where a qualified name referencing a non-static member may
607/// appear outside a member function of this class.
608Sema::OwningExprResult
609Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
610                               DeclarationName Name, bool HasTrailingLParen,
611                               const CXXScopeSpec *SS,
612                               bool isAddressOfOperand) {
613  // Could be enum-constant, value decl, instance variable, etc.
614  if (SS && SS->isInvalid())
615    return ExprError();
616
617  // C++ [temp.dep.expr]p3:
618  //   An id-expression is type-dependent if it contains:
619  //     -- a nested-name-specifier that contains a class-name that
620  //        names a dependent type.
621  if (SS && isDependentScopeSpecifier(*SS)) {
622    llvm::SmallVector<NestedNameSpecifier, 16> Specs;
623    for (CXXScopeSpec::iterator Spec = SS->begin(), SpecEnd = SS->end();
624         Spec != SpecEnd; ++Spec)
625      Specs.push_back(NestedNameSpecifier::getFromOpaquePtr(*Spec));
626    return Owned(UnresolvedDeclRefExpr::Create(Context, Name, Loc,
627                                               SS->getRange(), &Specs[0],
628                                               Specs.size()));
629  }
630
631  LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
632                                         false, true, Loc);
633
634  NamedDecl *D = 0;
635  if (Lookup.isAmbiguous()) {
636    DiagnoseAmbiguousLookup(Lookup, Name, Loc,
637                            SS && SS->isSet() ? SS->getRange()
638                                              : SourceRange());
639    return ExprError();
640  } else
641    D = Lookup.getAsDecl();
642
643  // If this reference is in an Objective-C method, then ivar lookup happens as
644  // well.
645  IdentifierInfo *II = Name.getAsIdentifierInfo();
646  if (II && getCurMethodDecl()) {
647    // There are two cases to handle here.  1) scoped lookup could have failed,
648    // in which case we should look for an ivar.  2) scoped lookup could have
649    // found a decl, but that decl is outside the current instance method (i.e.
650    // a global variable).  In these two cases, we do a lookup for an ivar with
651    // this name, if the lookup sucedes, we replace it our current decl.
652    if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
653      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
654      ObjCInterfaceDecl *ClassDeclared;
655      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
656        // Check if referencing a field with __attribute__((deprecated)).
657        if (DiagnoseUseOfDecl(IV, Loc))
658          return ExprError();
659        bool IsClsMethod = getCurMethodDecl()->isClassMethod();
660        // If a class method attemps to use a free standing ivar, this is
661        // an error.
662        if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
663           return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
664                           << IV->getDeclName());
665        // If a class method uses a global variable, even if an ivar with
666        // same name exists, use the global.
667        if (!IsClsMethod) {
668          if (IV->getAccessControl() == ObjCIvarDecl::Private &&
669              ClassDeclared != IFace)
670           Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
671          // FIXME: This should use a new expr for a direct reference, don't turn
672          // this into Self->ivar, just return a BareIVarExpr or something.
673          IdentifierInfo &II = Context.Idents.get("self");
674          OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
675          ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
676                                    Loc, static_cast<Expr*>(SelfExpr.release()),
677                                    true, true);
678          Context.setFieldDecl(IFace, IV, MRef);
679          return Owned(MRef);
680        }
681      }
682    }
683    else if (getCurMethodDecl()->isInstanceMethod()) {
684      // We should warn if a local variable hides an ivar.
685      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
686      ObjCInterfaceDecl *ClassDeclared;
687      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
688        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
689            IFace == ClassDeclared)
690          Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
691      }
692    }
693    // Needed to implement property "super.method" notation.
694    if (D == 0 && II->isStr("super")) {
695      QualType T;
696
697      if (getCurMethodDecl()->isInstanceMethod())
698        T = Context.getPointerType(Context.getObjCInterfaceType(
699                                   getCurMethodDecl()->getClassInterface()));
700      else
701        T = Context.getObjCClassType();
702      return Owned(new (Context) ObjCSuperExpr(Loc, T));
703    }
704  }
705
706  // Determine whether this name might be a candidate for
707  // argument-dependent lookup.
708  bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
709             HasTrailingLParen;
710
711  if (ADL && D == 0) {
712    // We've seen something of the form
713    //
714    //   identifier(
715    //
716    // and we did not find any entity by the name
717    // "identifier". However, this identifier is still subject to
718    // argument-dependent lookup, so keep track of the name.
719    return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
720                                                          Context.OverloadTy,
721                                                          Loc));
722  }
723
724  if (D == 0) {
725    // Otherwise, this could be an implicitly declared function reference (legal
726    // in C90, extension in C99).
727    if (HasTrailingLParen && II &&
728        !getLangOptions().CPlusPlus) // Not in C++.
729      D = ImplicitlyDefineFunction(Loc, *II, S);
730    else {
731      // If this name wasn't predeclared and if this is not a function call,
732      // diagnose the problem.
733      if (SS && !SS->isEmpty())
734        return ExprError(Diag(Loc, diag::err_typecheck_no_member)
735          << Name << SS->getRange());
736      else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
737               Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
738        return ExprError(Diag(Loc, diag::err_undeclared_use)
739          << Name.getAsString());
740      else
741        return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
742    }
743  }
744
745  // If this is an expression of the form &Class::member, don't build an
746  // implicit member ref, because we want a pointer to the member in general,
747  // not any specific instance's member.
748  if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
749    DeclContext *DC = computeDeclContext(*SS);
750    if (D && isa<CXXRecordDecl>(DC)) {
751      QualType DType;
752      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
753        DType = FD->getType().getNonReferenceType();
754      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
755        DType = Method->getType();
756      } else if (isa<OverloadedFunctionDecl>(D)) {
757        DType = Context.OverloadTy;
758      }
759      // Could be an inner type. That's diagnosed below, so ignore it here.
760      if (!DType.isNull()) {
761        // The pointer is type- and value-dependent if it points into something
762        // dependent.
763        bool Dependent = false;
764        for (; DC; DC = DC->getParent()) {
765          // FIXME: could stop early at namespace scope.
766          if (DC->isRecord()) {
767            CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
768            if (Context.getTypeDeclType(Record)->isDependentType()) {
769              Dependent = true;
770              break;
771            }
772          }
773        }
774        return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
775      }
776    }
777  }
778
779  // We may have found a field within an anonymous union or struct
780  // (C++ [class.union]).
781  if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
782    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
783      return BuildAnonymousStructUnionMemberReference(Loc, FD);
784
785  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
786    if (!MD->isStatic()) {
787      // C++ [class.mfct.nonstatic]p2:
788      //   [...] if name lookup (3.4.1) resolves the name in the
789      //   id-expression to a nonstatic nontype member of class X or of
790      //   a base class of X, the id-expression is transformed into a
791      //   class member access expression (5.2.5) using (*this) (9.3.2)
792      //   as the postfix-expression to the left of the '.' operator.
793      DeclContext *Ctx = 0;
794      QualType MemberType;
795      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
796        Ctx = FD->getDeclContext();
797        MemberType = FD->getType();
798
799        if (const ReferenceType *RefType = MemberType->getAsReferenceType())
800          MemberType = RefType->getPointeeType();
801        else if (!FD->isMutable()) {
802          unsigned combinedQualifiers
803            = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
804          MemberType = MemberType.getQualifiedType(combinedQualifiers);
805        }
806      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
807        if (!Method->isStatic()) {
808          Ctx = Method->getParent();
809          MemberType = Method->getType();
810        }
811      } else if (OverloadedFunctionDecl *Ovl
812                   = dyn_cast<OverloadedFunctionDecl>(D)) {
813        for (OverloadedFunctionDecl::function_iterator
814               Func = Ovl->function_begin(),
815               FuncEnd = Ovl->function_end();
816             Func != FuncEnd; ++Func) {
817          if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
818            if (!DMethod->isStatic()) {
819              Ctx = Ovl->getDeclContext();
820              MemberType = Context.OverloadTy;
821              break;
822            }
823        }
824      }
825
826      if (Ctx && Ctx->isRecord()) {
827        QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
828        QualType ThisType = Context.getTagDeclType(MD->getParent());
829        if ((Context.getCanonicalType(CtxType)
830               == Context.getCanonicalType(ThisType)) ||
831            IsDerivedFrom(ThisType, CtxType)) {
832          // Build the implicit member access expression.
833          Expr *This = new (Context) CXXThisExpr(SourceLocation(),
834                                                 MD->getThisType(Context));
835          return Owned(new (Context) MemberExpr(This, true, D,
836                                                SourceLocation(), MemberType));
837        }
838      }
839    }
840  }
841
842  if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
843    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
844      if (MD->isStatic())
845        // "invalid use of member 'x' in static member function"
846        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
847          << FD->getDeclName());
848    }
849
850    // Any other ways we could have found the field in a well-formed
851    // program would have been turned into implicit member expressions
852    // above.
853    return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
854      << FD->getDeclName());
855  }
856
857  if (isa<TypedefDecl>(D))
858    return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
859  if (isa<ObjCInterfaceDecl>(D))
860    return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
861  if (isa<NamespaceDecl>(D))
862    return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
863
864  // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
865  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
866    return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
867                                  false, false, SS));
868  else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
869    return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
870                                  false, false, SS));
871  ValueDecl *VD = cast<ValueDecl>(D);
872
873  // Check whether this declaration can be used. Note that we suppress
874  // this check when we're going to perform argument-dependent lookup
875  // on this function name, because this might not be the function
876  // that overload resolution actually selects.
877  if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
878    return ExprError();
879
880  if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
881    // Warn about constructs like:
882    //   if (void *X = foo()) { ... } else { X }.
883    // In the else block, the pointer is always false.
884    if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
885      Scope *CheckS = S;
886      while (CheckS) {
887        if (CheckS->isWithinElse() &&
888            CheckS->getControlParent()->isDeclScope(Var)) {
889          if (Var->getType()->isBooleanType())
890            ExprError(Diag(Loc, diag::warn_value_always_false)
891              << Var->getDeclName());
892          else
893            ExprError(Diag(Loc, diag::warn_value_always_zero)
894              << Var->getDeclName());
895          break;
896        }
897
898        // Move up one more control parent to check again.
899        CheckS = CheckS->getControlParent();
900        if (CheckS)
901          CheckS = CheckS->getParent();
902      }
903    }
904  } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
905    if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
906      // C99 DR 316 says that, if a function type comes from a
907      // function definition (without a prototype), that type is only
908      // used for checking compatibility. Therefore, when referencing
909      // the function, we pretend that we don't have the full function
910      // type.
911      QualType T = Func->getType();
912      QualType NoProtoType = T;
913      if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
914        NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
915      return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
916    }
917  }
918
919  // Only create DeclRefExpr's for valid Decl's.
920  if (VD->isInvalidDecl())
921    return ExprError();
922
923  // If the identifier reference is inside a block, and it refers to a value
924  // that is outside the block, create a BlockDeclRefExpr instead of a
925  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
926  // the block is formed.
927  //
928  // We do not do this for things like enum constants, global variables, etc,
929  // as they do not get snapshotted.
930  //
931  if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
932    // Blocks that have these can't be constant.
933    CurBlock->hasBlockDeclRefExprs = true;
934
935    QualType ExprTy = VD->getType().getNonReferenceType();
936    // The BlocksAttr indicates the variable is bound by-reference.
937    if (VD->getAttr<BlocksAttr>())
938      return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
939
940    // Variable will be bound by-copy, make it const within the closure.
941    ExprTy.addConst();
942    return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
943  }
944  // If this reference is not in a block or if the referenced variable is
945  // within the block, create a normal DeclRefExpr.
946
947  bool TypeDependent = false;
948  bool ValueDependent = false;
949  if (getLangOptions().CPlusPlus) {
950    // C++ [temp.dep.expr]p3:
951    //   An id-expression is type-dependent if it contains:
952    //     - an identifier that was declared with a dependent type,
953    if (VD->getType()->isDependentType())
954      TypeDependent = true;
955    //     - FIXME: a template-id that is dependent,
956    //     - a conversion-function-id that specifies a dependent type,
957    else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
958             Name.getCXXNameType()->isDependentType())
959      TypeDependent = true;
960    //     - a nested-name-specifier that contains a class-name that
961    //       names a dependent type.
962    else if (SS && !SS->isEmpty()) {
963      for (DeclContext *DC = computeDeclContext(*SS);
964           DC; DC = DC->getParent()) {
965        // FIXME: could stop early at namespace scope.
966        if (DC->isRecord()) {
967          CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
968          if (Context.getTypeDeclType(Record)->isDependentType()) {
969            TypeDependent = true;
970            break;
971          }
972        }
973      }
974    }
975
976    // C++ [temp.dep.constexpr]p2:
977    //
978    //   An identifier is value-dependent if it is:
979    //     - a name declared with a dependent type,
980    if (TypeDependent)
981      ValueDependent = true;
982    //     - the name of a non-type template parameter,
983    else if (isa<NonTypeTemplateParmDecl>(VD))
984      ValueDependent = true;
985    //    - a constant with integral or enumeration type and is
986    //      initialized with an expression that is value-dependent
987    //      (FIXME!).
988  }
989
990  return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
991                                TypeDependent, ValueDependent, SS));
992}
993
994Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
995                                                 tok::TokenKind Kind) {
996  PredefinedExpr::IdentType IT;
997
998  switch (Kind) {
999  default: assert(0 && "Unknown simple primary expr!");
1000  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1001  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1002  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
1003  }
1004
1005  // Pre-defined identifiers are of type char[x], where x is the length of the
1006  // string.
1007  unsigned Length;
1008  if (FunctionDecl *FD = getCurFunctionDecl())
1009    Length = FD->getIdentifier()->getLength();
1010  else if (ObjCMethodDecl *MD = getCurMethodDecl())
1011    Length = MD->getSynthesizedMethodSize();
1012  else {
1013    Diag(Loc, diag::ext_predef_outside_function);
1014    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1015    Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1016  }
1017
1018
1019  llvm::APInt LengthI(32, Length + 1);
1020  QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
1021  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1022  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1023}
1024
1025Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1026  llvm::SmallString<16> CharBuffer;
1027  CharBuffer.resize(Tok.getLength());
1028  const char *ThisTokBegin = &CharBuffer[0];
1029  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1030
1031  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1032                            Tok.getLocation(), PP);
1033  if (Literal.hadError())
1034    return ExprError();
1035
1036  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1037
1038  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1039                                              Literal.isWide(),
1040                                              type, Tok.getLocation()));
1041}
1042
1043Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1044  // Fast path for a single digit (which is quite common).  A single digit
1045  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1046  if (Tok.getLength() == 1) {
1047    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1048    unsigned IntSize = Context.Target.getIntWidth();
1049    return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1050                    Context.IntTy, Tok.getLocation()));
1051  }
1052
1053  llvm::SmallString<512> IntegerBuffer;
1054  // Add padding so that NumericLiteralParser can overread by one character.
1055  IntegerBuffer.resize(Tok.getLength()+1);
1056  const char *ThisTokBegin = &IntegerBuffer[0];
1057
1058  // Get the spelling of the token, which eliminates trigraphs, etc.
1059  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1060
1061  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1062                               Tok.getLocation(), PP);
1063  if (Literal.hadError)
1064    return ExprError();
1065
1066  Expr *Res;
1067
1068  if (Literal.isFloatingLiteral()) {
1069    QualType Ty;
1070    if (Literal.isFloat)
1071      Ty = Context.FloatTy;
1072    else if (!Literal.isLong)
1073      Ty = Context.DoubleTy;
1074    else
1075      Ty = Context.LongDoubleTy;
1076
1077    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1078
1079    // isExact will be set by GetFloatValue().
1080    bool isExact = false;
1081    Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1082                                        &isExact, Ty, Tok.getLocation());
1083
1084  } else if (!Literal.isIntegerLiteral()) {
1085    return ExprError();
1086  } else {
1087    QualType Ty;
1088
1089    // long long is a C99 feature.
1090    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1091        Literal.isLongLong)
1092      Diag(Tok.getLocation(), diag::ext_longlong);
1093
1094    // Get the value in the widest-possible width.
1095    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1096
1097    if (Literal.GetIntegerValue(ResultVal)) {
1098      // If this value didn't fit into uintmax_t, warn and force to ull.
1099      Diag(Tok.getLocation(), diag::warn_integer_too_large);
1100      Ty = Context.UnsignedLongLongTy;
1101      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1102             "long long is not intmax_t?");
1103    } else {
1104      // If this value fits into a ULL, try to figure out what else it fits into
1105      // according to the rules of C99 6.4.4.1p5.
1106
1107      // Octal, Hexadecimal, and integers with a U suffix are allowed to
1108      // be an unsigned int.
1109      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1110
1111      // Check from smallest to largest, picking the smallest type we can.
1112      unsigned Width = 0;
1113      if (!Literal.isLong && !Literal.isLongLong) {
1114        // Are int/unsigned possibilities?
1115        unsigned IntSize = Context.Target.getIntWidth();
1116
1117        // Does it fit in a unsigned int?
1118        if (ResultVal.isIntN(IntSize)) {
1119          // Does it fit in a signed int?
1120          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1121            Ty = Context.IntTy;
1122          else if (AllowUnsigned)
1123            Ty = Context.UnsignedIntTy;
1124          Width = IntSize;
1125        }
1126      }
1127
1128      // Are long/unsigned long possibilities?
1129      if (Ty.isNull() && !Literal.isLongLong) {
1130        unsigned LongSize = Context.Target.getLongWidth();
1131
1132        // Does it fit in a unsigned long?
1133        if (ResultVal.isIntN(LongSize)) {
1134          // Does it fit in a signed long?
1135          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1136            Ty = Context.LongTy;
1137          else if (AllowUnsigned)
1138            Ty = Context.UnsignedLongTy;
1139          Width = LongSize;
1140        }
1141      }
1142
1143      // Finally, check long long if needed.
1144      if (Ty.isNull()) {
1145        unsigned LongLongSize = Context.Target.getLongLongWidth();
1146
1147        // Does it fit in a unsigned long long?
1148        if (ResultVal.isIntN(LongLongSize)) {
1149          // Does it fit in a signed long long?
1150          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1151            Ty = Context.LongLongTy;
1152          else if (AllowUnsigned)
1153            Ty = Context.UnsignedLongLongTy;
1154          Width = LongLongSize;
1155        }
1156      }
1157
1158      // If we still couldn't decide a type, we probably have something that
1159      // does not fit in a signed long long, but has no U suffix.
1160      if (Ty.isNull()) {
1161        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1162        Ty = Context.UnsignedLongLongTy;
1163        Width = Context.Target.getLongLongWidth();
1164      }
1165
1166      if (ResultVal.getBitWidth() != Width)
1167        ResultVal.trunc(Width);
1168    }
1169    Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1170  }
1171
1172  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1173  if (Literal.isImaginary)
1174    Res = new (Context) ImaginaryLiteral(Res,
1175                                        Context.getComplexType(Res->getType()));
1176
1177  return Owned(Res);
1178}
1179
1180Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1181                                              SourceLocation R, ExprArg Val) {
1182  Expr *E = (Expr *)Val.release();
1183  assert((E != 0) && "ActOnParenExpr() missing expr");
1184  return Owned(new (Context) ParenExpr(L, R, E));
1185}
1186
1187/// The UsualUnaryConversions() function is *not* called by this routine.
1188/// See C99 6.3.2.1p[2-4] for more details.
1189bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1190                                     SourceLocation OpLoc,
1191                                     const SourceRange &ExprRange,
1192                                     bool isSizeof) {
1193  if (exprType->isDependentType())
1194    return false;
1195
1196  // C99 6.5.3.4p1:
1197  if (isa<FunctionType>(exprType)) {
1198    // alignof(function) is allowed.
1199    if (isSizeof)
1200      Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1201    return false;
1202  }
1203
1204  if (exprType->isVoidType()) {
1205    Diag(OpLoc, diag::ext_sizeof_void_type)
1206      << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1207    return false;
1208  }
1209
1210  return RequireCompleteType(OpLoc, exprType,
1211                                isSizeof ? diag::err_sizeof_incomplete_type :
1212                                           diag::err_alignof_incomplete_type,
1213                                ExprRange);
1214}
1215
1216bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1217                            const SourceRange &ExprRange) {
1218  E = E->IgnoreParens();
1219
1220  // alignof decl is always ok.
1221  if (isa<DeclRefExpr>(E))
1222    return false;
1223
1224  // Cannot know anything else if the expression is dependent.
1225  if (E->isTypeDependent())
1226    return false;
1227
1228  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1229    if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1230      if (FD->isBitField()) {
1231        Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1232        return true;
1233      }
1234      // Other fields are ok.
1235      return false;
1236    }
1237  }
1238  return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1239}
1240
1241/// \brief Build a sizeof or alignof expression given a type operand.
1242Action::OwningExprResult
1243Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1244                              bool isSizeOf, SourceRange R) {
1245  if (T.isNull())
1246    return ExprError();
1247
1248  if (!T->isDependentType() &&
1249      CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1250    return ExprError();
1251
1252  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1253  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1254                                               Context.getSizeType(), OpLoc,
1255                                               R.getEnd()));
1256}
1257
1258/// \brief Build a sizeof or alignof expression given an expression
1259/// operand.
1260Action::OwningExprResult
1261Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1262                              bool isSizeOf, SourceRange R) {
1263  // Verify that the operand is valid.
1264  bool isInvalid = false;
1265  if (E->isTypeDependent()) {
1266    // Delay type-checking for type-dependent expressions.
1267  } else if (!isSizeOf) {
1268    isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1269  } else if (E->isBitField()) {  // C99 6.5.3.4p1.
1270    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1271    isInvalid = true;
1272  } else {
1273    isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1274  }
1275
1276  if (isInvalid)
1277    return ExprError();
1278
1279  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1280  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1281                                               Context.getSizeType(), OpLoc,
1282                                               R.getEnd()));
1283}
1284
1285/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1286/// the same for @c alignof and @c __alignof
1287/// Note that the ArgRange is invalid if isType is false.
1288Action::OwningExprResult
1289Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1290                             void *TyOrEx, const SourceRange &ArgRange) {
1291  // If error parsing type, ignore.
1292  if (TyOrEx == 0) return ExprError();
1293
1294  if (isType) {
1295    QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1296    return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1297  }
1298
1299  // Get the end location.
1300  Expr *ArgEx = (Expr *)TyOrEx;
1301  Action::OwningExprResult Result
1302    = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1303
1304  if (Result.isInvalid())
1305    DeleteExpr(ArgEx);
1306
1307  return move(Result);
1308}
1309
1310QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
1311  if (V->isTypeDependent())
1312    return Context.DependentTy;
1313
1314  DefaultFunctionArrayConversion(V);
1315
1316  // These operators return the element type of a complex type.
1317  if (const ComplexType *CT = V->getType()->getAsComplexType())
1318    return CT->getElementType();
1319
1320  // Otherwise they pass through real integer and floating point types here.
1321  if (V->getType()->isArithmeticType())
1322    return V->getType();
1323
1324  // Reject anything else.
1325  Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1326    << (isReal ? "__real" : "__imag");
1327  return QualType();
1328}
1329
1330
1331
1332Action::OwningExprResult
1333Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1334                          tok::TokenKind Kind, ExprArg Input) {
1335  Expr *Arg = (Expr *)Input.get();
1336
1337  UnaryOperator::Opcode Opc;
1338  switch (Kind) {
1339  default: assert(0 && "Unknown unary op!");
1340  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
1341  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1342  }
1343
1344  if (getLangOptions().CPlusPlus &&
1345      (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1346    // Which overloaded operator?
1347    OverloadedOperatorKind OverOp =
1348      (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1349
1350    // C++ [over.inc]p1:
1351    //
1352    //     [...] If the function is a member function with one
1353    //     parameter (which shall be of type int) or a non-member
1354    //     function with two parameters (the second of which shall be
1355    //     of type int), it defines the postfix increment operator ++
1356    //     for objects of that type. When the postfix increment is
1357    //     called as a result of using the ++ operator, the int
1358    //     argument will have value zero.
1359    Expr *Args[2] = {
1360      Arg,
1361      new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1362                          /*isSigned=*/true), Context.IntTy, SourceLocation())
1363    };
1364
1365    // Build the candidate set for overloading
1366    OverloadCandidateSet CandidateSet;
1367    AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
1368
1369    // Perform overload resolution.
1370    OverloadCandidateSet::iterator Best;
1371    switch (BestViableFunction(CandidateSet, Best)) {
1372    case OR_Success: {
1373      // We found a built-in operator or an overloaded operator.
1374      FunctionDecl *FnDecl = Best->Function;
1375
1376      if (FnDecl) {
1377        // We matched an overloaded operator. Build a call to that
1378        // operator.
1379
1380        // Convert the arguments.
1381        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1382          if (PerformObjectArgumentInitialization(Arg, Method))
1383            return ExprError();
1384        } else {
1385          // Convert the arguments.
1386          if (PerformCopyInitialization(Arg,
1387                                        FnDecl->getParamDecl(0)->getType(),
1388                                        "passing"))
1389            return ExprError();
1390        }
1391
1392        // Determine the result type
1393        QualType ResultTy
1394          = FnDecl->getType()->getAsFunctionType()->getResultType();
1395        ResultTy = ResultTy.getNonReferenceType();
1396
1397        // Build the actual expression node.
1398        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1399                                                 SourceLocation());
1400        UsualUnaryConversions(FnExpr);
1401
1402        Input.release();
1403        return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1404                                                       Args, 2, ResultTy,
1405                                                       OpLoc));
1406      } else {
1407        // We matched a built-in operator. Convert the arguments, then
1408        // break out so that we will build the appropriate built-in
1409        // operator node.
1410        if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1411                                      "passing"))
1412          return ExprError();
1413
1414        break;
1415      }
1416    }
1417
1418    case OR_No_Viable_Function:
1419      // No viable function; fall through to handling this as a
1420      // built-in operator, which will produce an error message for us.
1421      break;
1422
1423    case OR_Ambiguous:
1424      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
1425          << UnaryOperator::getOpcodeStr(Opc)
1426          << Arg->getSourceRange();
1427      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1428      return ExprError();
1429
1430    case OR_Deleted:
1431      Diag(OpLoc, diag::err_ovl_deleted_oper)
1432        << Best->Function->isDeleted()
1433        << UnaryOperator::getOpcodeStr(Opc)
1434        << Arg->getSourceRange();
1435      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1436      return ExprError();
1437    }
1438
1439    // Either we found no viable overloaded operator or we matched a
1440    // built-in operator. In either case, fall through to trying to
1441    // build a built-in operation.
1442  }
1443
1444  QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1445                                                 Opc == UnaryOperator::PostInc);
1446  if (result.isNull())
1447    return ExprError();
1448  Input.release();
1449  return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
1450}
1451
1452Action::OwningExprResult
1453Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1454                              ExprArg Idx, SourceLocation RLoc) {
1455  Expr *LHSExp = static_cast<Expr*>(Base.get()),
1456       *RHSExp = static_cast<Expr*>(Idx.get());
1457
1458  if (getLangOptions().CPlusPlus &&
1459      (LHSExp->getType()->isRecordType() ||
1460       LHSExp->getType()->isEnumeralType() ||
1461       RHSExp->getType()->isRecordType() ||
1462       RHSExp->getType()->isEnumeralType())) {
1463    // Add the appropriate overloaded operators (C++ [over.match.oper])
1464    // to the candidate set.
1465    OverloadCandidateSet CandidateSet;
1466    Expr *Args[2] = { LHSExp, RHSExp };
1467    AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1468                          SourceRange(LLoc, RLoc));
1469
1470    // Perform overload resolution.
1471    OverloadCandidateSet::iterator Best;
1472    switch (BestViableFunction(CandidateSet, Best)) {
1473    case OR_Success: {
1474      // We found a built-in operator or an overloaded operator.
1475      FunctionDecl *FnDecl = Best->Function;
1476
1477      if (FnDecl) {
1478        // We matched an overloaded operator. Build a call to that
1479        // operator.
1480
1481        // Convert the arguments.
1482        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1483          if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1484              PerformCopyInitialization(RHSExp,
1485                                        FnDecl->getParamDecl(0)->getType(),
1486                                        "passing"))
1487            return ExprError();
1488        } else {
1489          // Convert the arguments.
1490          if (PerformCopyInitialization(LHSExp,
1491                                        FnDecl->getParamDecl(0)->getType(),
1492                                        "passing") ||
1493              PerformCopyInitialization(RHSExp,
1494                                        FnDecl->getParamDecl(1)->getType(),
1495                                        "passing"))
1496            return ExprError();
1497        }
1498
1499        // Determine the result type
1500        QualType ResultTy
1501          = FnDecl->getType()->getAsFunctionType()->getResultType();
1502        ResultTy = ResultTy.getNonReferenceType();
1503
1504        // Build the actual expression node.
1505        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1506                                                 SourceLocation());
1507        UsualUnaryConversions(FnExpr);
1508
1509        Base.release();
1510        Idx.release();
1511        return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1512                                                       FnExpr, Args, 2,
1513                                                       ResultTy, LLoc));
1514      } else {
1515        // We matched a built-in operator. Convert the arguments, then
1516        // break out so that we will build the appropriate built-in
1517        // operator node.
1518        if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1519                                      "passing") ||
1520            PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1521                                      "passing"))
1522          return ExprError();
1523
1524        break;
1525      }
1526    }
1527
1528    case OR_No_Viable_Function:
1529      // No viable function; fall through to handling this as a
1530      // built-in operator, which will produce an error message for us.
1531      break;
1532
1533    case OR_Ambiguous:
1534      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
1535          << "[]"
1536          << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1537      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1538      return ExprError();
1539
1540    case OR_Deleted:
1541      Diag(LLoc, diag::err_ovl_deleted_oper)
1542        << Best->Function->isDeleted()
1543        << "[]"
1544        << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1545      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1546      return ExprError();
1547    }
1548
1549    // Either we found no viable overloaded operator or we matched a
1550    // built-in operator. In either case, fall through to trying to
1551    // build a built-in operation.
1552  }
1553
1554  // Perform default conversions.
1555  DefaultFunctionArrayConversion(LHSExp);
1556  DefaultFunctionArrayConversion(RHSExp);
1557
1558  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1559
1560  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1561  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1562  // in the subscript position. As a result, we need to derive the array base
1563  // and index from the expression types.
1564  Expr *BaseExpr, *IndexExpr;
1565  QualType ResultType;
1566  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1567    BaseExpr = LHSExp;
1568    IndexExpr = RHSExp;
1569    ResultType = Context.DependentTy;
1570  } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
1571    BaseExpr = LHSExp;
1572    IndexExpr = RHSExp;
1573    // FIXME: need to deal with const...
1574    ResultType = PTy->getPointeeType();
1575  } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
1576     // Handle the uncommon case of "123[Ptr]".
1577    BaseExpr = RHSExp;
1578    IndexExpr = LHSExp;
1579    // FIXME: need to deal with const...
1580    ResultType = PTy->getPointeeType();
1581  } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1582    BaseExpr = LHSExp;    // vectors: V[123]
1583    IndexExpr = RHSExp;
1584
1585    // FIXME: need to deal with const...
1586    ResultType = VTy->getElementType();
1587  } else {
1588    return ExprError(Diag(LHSExp->getLocStart(),
1589      diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1590  }
1591  // C99 6.5.2.1p1
1592  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
1593    return ExprError(Diag(IndexExpr->getLocStart(),
1594      diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
1595
1596  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1597  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1598  // type. Note that Functions are not objects, and that (in C99 parlance)
1599  // incomplete types are not object types.
1600  if (ResultType->isFunctionType()) {
1601    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1602      << ResultType << BaseExpr->getSourceRange();
1603    return ExprError();
1604  }
1605  if (!ResultType->isDependentType() &&
1606      RequireCompleteType(BaseExpr->getLocStart(), ResultType,
1607                          diag::err_subscript_incomplete_type,
1608                          BaseExpr->getSourceRange()))
1609    return ExprError();
1610
1611  Base.release();
1612  Idx.release();
1613  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1614                                                ResultType, RLoc));
1615}
1616
1617QualType Sema::
1618CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
1619                        IdentifierInfo &CompName, SourceLocation CompLoc) {
1620  const ExtVectorType *vecType = baseType->getAsExtVectorType();
1621
1622  // The vector accessor can't exceed the number of elements.
1623  const char *compStr = CompName.getName();
1624
1625  // This flag determines whether or not the component is one of the four
1626  // special names that indicate a subset of exactly half the elements are
1627  // to be selected.
1628  bool HalvingSwizzle = false;
1629
1630  // This flag determines whether or not CompName has an 's' char prefix,
1631  // indicating that it is a string of hex values to be used as vector indices.
1632  bool HexSwizzle = *compStr == 's';
1633
1634  // Check that we've found one of the special components, or that the component
1635  // names must come from the same set.
1636  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1637      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1638    HalvingSwizzle = true;
1639  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1640    do
1641      compStr++;
1642    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1643  } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1644    do
1645      compStr++;
1646    while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1647  }
1648
1649  if (!HalvingSwizzle && *compStr) {
1650    // We didn't get to the end of the string. This means the component names
1651    // didn't come from the same set *or* we encountered an illegal name.
1652    Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1653      << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1654    return QualType();
1655  }
1656
1657  // Ensure no component accessor exceeds the width of the vector type it
1658  // operates on.
1659  if (!HalvingSwizzle) {
1660    compStr = CompName.getName();
1661
1662    if (HexSwizzle)
1663      compStr++;
1664
1665    while (*compStr) {
1666      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1667        Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1668          << baseType << SourceRange(CompLoc);
1669        return QualType();
1670      }
1671    }
1672  }
1673
1674  // If this is a halving swizzle, verify that the base type has an even
1675  // number of elements.
1676  if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1677    Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1678      << baseType << SourceRange(CompLoc);
1679    return QualType();
1680  }
1681
1682  // The component accessor looks fine - now we need to compute the actual type.
1683  // The vector type is implied by the component accessor. For example,
1684  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1685  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1686  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1687  unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1688                                     : CompName.getLength();
1689  if (HexSwizzle)
1690    CompSize--;
1691
1692  if (CompSize == 1)
1693    return vecType->getElementType();
1694
1695  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1696  // Now look up the TypeDefDecl from the vector type. Without this,
1697  // diagostics look bad. We want extended vector types to appear built-in.
1698  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1699    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1700      return Context.getTypedefType(ExtVectorDecls[i]);
1701  }
1702  return VT; // should never get here (a typedef type should always be found).
1703}
1704
1705static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1706                                                IdentifierInfo &Member,
1707                                                const Selector &Sel) {
1708
1709  if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
1710    return PD;
1711  if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
1712    return OMD;
1713
1714  for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1715       E = PDecl->protocol_end(); I != E; ++I) {
1716    if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel))
1717      return D;
1718  }
1719  return 0;
1720}
1721
1722static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1723                                IdentifierInfo &Member,
1724                                const Selector &Sel) {
1725  // Check protocols on qualified interfaces.
1726  Decl *GDecl = 0;
1727  for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1728       E = QIdTy->qual_end(); I != E; ++I) {
1729    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1730      GDecl = PD;
1731      break;
1732    }
1733    // Also must look for a getter name which uses property syntax.
1734    if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1735      GDecl = OMD;
1736      break;
1737    }
1738  }
1739  if (!GDecl) {
1740    for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1741         E = QIdTy->qual_end(); I != E; ++I) {
1742      // Search in the protocol-qualifier list of current protocol.
1743      GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel);
1744      if (GDecl)
1745        return GDecl;
1746    }
1747  }
1748  return GDecl;
1749}
1750
1751Action::OwningExprResult
1752Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1753                               tok::TokenKind OpKind, SourceLocation MemberLoc,
1754                               IdentifierInfo &Member,
1755                               DeclTy *ObjCImpDecl) {
1756  Expr *BaseExpr = static_cast<Expr *>(Base.release());
1757  assert(BaseExpr && "no record expression");
1758
1759  // Perform default conversions.
1760  DefaultFunctionArrayConversion(BaseExpr);
1761
1762  QualType BaseType = BaseExpr->getType();
1763  assert(!BaseType.isNull() && "no type for member expression");
1764
1765  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
1766  // must have pointer type, and the accessed type is the pointee.
1767  if (OpKind == tok::arrow) {
1768    if (const PointerType *PT = BaseType->getAsPointerType())
1769      BaseType = PT->getPointeeType();
1770    else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1771      return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1772                                            MemberLoc, Member));
1773    else
1774      return ExprError(Diag(MemberLoc,
1775                            diag::err_typecheck_member_reference_arrow)
1776        << BaseType << BaseExpr->getSourceRange());
1777  }
1778
1779  // Handle field access to simple records.  This also handles access to fields
1780  // of the ObjC 'id' struct.
1781  if (const RecordType *RTy = BaseType->getAsRecordType()) {
1782    RecordDecl *RDecl = RTy->getDecl();
1783    if (RequireCompleteType(OpLoc, BaseType,
1784                               diag::err_typecheck_incomplete_tag,
1785                               BaseExpr->getSourceRange()))
1786      return ExprError();
1787
1788    // The record definition is complete, now make sure the member is valid.
1789    // FIXME: Qualified name lookup for C++ is a bit more complicated
1790    // than this.
1791    LookupResult Result
1792      = LookupQualifiedName(RDecl, DeclarationName(&Member),
1793                            LookupMemberName, false);
1794
1795    NamedDecl *MemberDecl = 0;
1796    if (!Result)
1797      return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1798               << &Member << BaseExpr->getSourceRange());
1799    else if (Result.isAmbiguous()) {
1800      DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1801                              MemberLoc, BaseExpr->getSourceRange());
1802      return ExprError();
1803    } else
1804      MemberDecl = Result;
1805
1806    // If the decl being referenced had an error, return an error for this
1807    // sub-expr without emitting another error, in order to avoid cascading
1808    // error cases.
1809    if (MemberDecl->isInvalidDecl())
1810      return ExprError();
1811
1812    // Check the use of this field
1813    if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1814      return ExprError();
1815
1816    if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
1817      // We may have found a field within an anonymous union or struct
1818      // (C++ [class.union]).
1819      if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1820        return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1821                                                        BaseExpr, OpLoc);
1822
1823      // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1824      // FIXME: Handle address space modifiers
1825      QualType MemberType = FD->getType();
1826      if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1827        MemberType = Ref->getPointeeType();
1828      else {
1829        unsigned combinedQualifiers =
1830          MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
1831        if (FD->isMutable())
1832          combinedQualifiers &= ~QualType::Const;
1833        MemberType = MemberType.getQualifiedType(combinedQualifiers);
1834      }
1835
1836      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1837                                            MemberLoc, MemberType));
1838    } else if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
1839      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1840                                  Var, MemberLoc,
1841                                  Var->getType().getNonReferenceType()));
1842    else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
1843      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1844                                  MemberFn, MemberLoc, MemberFn->getType()));
1845    else if (OverloadedFunctionDecl *Ovl
1846             = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
1847      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
1848                                  MemberLoc, Context.OverloadTy));
1849    else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
1850      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1851                                            Enum, MemberLoc, Enum->getType()));
1852    else if (isa<TypeDecl>(MemberDecl))
1853      return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1854        << DeclarationName(&Member) << int(OpKind == tok::arrow));
1855
1856    // We found a declaration kind that we didn't expect. This is a
1857    // generic error message that tells the user that she can't refer
1858    // to this member with '.' or '->'.
1859    return ExprError(Diag(MemberLoc,
1860                          diag::err_typecheck_member_reference_unknown)
1861      << DeclarationName(&Member) << int(OpKind == tok::arrow));
1862  }
1863
1864  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1865  // (*Obj).ivar.
1866  if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1867    ObjCInterfaceDecl *ClassDeclared;
1868    if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
1869                                                             ClassDeclared)) {
1870      // If the decl being referenced had an error, return an error for this
1871      // sub-expr without emitting another error, in order to avoid cascading
1872      // error cases.
1873      if (IV->isInvalidDecl())
1874        return ExprError();
1875
1876      // Check whether we can reference this field.
1877      if (DiagnoseUseOfDecl(IV, MemberLoc))
1878        return ExprError();
1879      if (IV->getAccessControl() != ObjCIvarDecl::Public) {
1880        ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1881        if (ObjCMethodDecl *MD = getCurMethodDecl())
1882          ClassOfMethodDecl =  MD->getClassInterface();
1883        else if (ObjCImpDecl && getCurFunctionDecl()) {
1884          // Case of a c-function declared inside an objc implementation.
1885          // FIXME: For a c-style function nested inside an objc implementation
1886          // class, there is no implementation context available, so we pass down
1887          // the context as argument to this routine. Ideally, this context need
1888          // be passed down in the AST node and somehow calculated from the AST
1889          // for a function decl.
1890          Decl *ImplDecl = static_cast<Decl *>(ObjCImpDecl);
1891          if (ObjCImplementationDecl *IMPD =
1892              dyn_cast<ObjCImplementationDecl>(ImplDecl))
1893            ClassOfMethodDecl = IMPD->getClassInterface();
1894          else if (ObjCCategoryImplDecl* CatImplClass =
1895                      dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
1896            ClassOfMethodDecl = CatImplClass->getClassInterface();
1897        }
1898        if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1899          if (ClassDeclared != IFTy->getDecl() ||
1900              ClassOfMethodDecl != ClassDeclared)
1901            Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1902        }
1903        // @protected
1904        else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1905          Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1906      }
1907
1908      ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1909                                                 MemberLoc, BaseExpr,
1910                                                 OpKind == tok::arrow);
1911      Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1912      return Owned(MRef);
1913    }
1914    return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1915                       << IFTy->getDecl()->getDeclName() << &Member
1916                       << BaseExpr->getSourceRange());
1917  }
1918
1919  // Handle Objective-C property access, which is "Obj.property" where Obj is a
1920  // pointer to a (potentially qualified) interface type.
1921  const PointerType *PTy;
1922  const ObjCInterfaceType *IFTy;
1923  if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1924      (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1925    ObjCInterfaceDecl *IFace = IFTy->getDecl();
1926
1927    // Search for a declared property first.
1928    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
1929      // Check whether we can reference this property.
1930      if (DiagnoseUseOfDecl(PD, MemberLoc))
1931        return ExprError();
1932
1933      return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1934                                                     MemberLoc, BaseExpr));
1935    }
1936
1937    // Check protocols on qualified interfaces.
1938    for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1939         E = IFTy->qual_end(); I != E; ++I)
1940      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1941        // Check whether we can reference this property.
1942        if (DiagnoseUseOfDecl(PD, MemberLoc))
1943          return ExprError();
1944
1945        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1946                                                       MemberLoc, BaseExpr));
1947      }
1948
1949    // If that failed, look for an "implicit" property by seeing if the nullary
1950    // selector is implemented.
1951
1952    // FIXME: The logic for looking up nullary and unary selectors should be
1953    // shared with the code in ActOnInstanceMessage.
1954
1955    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1956    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1957
1958    // If this reference is in an @implementation, check for 'private' methods.
1959    if (!Getter)
1960      if (ObjCImplementationDecl *ImpDecl =
1961          ObjCImplementations[IFace->getIdentifier()])
1962        Getter = ImpDecl->getInstanceMethod(Sel);
1963
1964    // Look through local category implementations associated with the class.
1965    if (!Getter) {
1966      for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1967        if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1968          Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1969      }
1970    }
1971    if (Getter) {
1972      // Check if we can reference this property.
1973      if (DiagnoseUseOfDecl(Getter, MemberLoc))
1974        return ExprError();
1975    }
1976    // If we found a getter then this may be a valid dot-reference, we
1977    // will look for the matching setter, in case it is needed.
1978    Selector SetterSel =
1979      SelectorTable::constructSetterName(PP.getIdentifierTable(),
1980                                         PP.getSelectorTable(), &Member);
1981    ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1982    if (!Setter) {
1983      // If this reference is in an @implementation, also check for 'private'
1984      // methods.
1985      if (ObjCImplementationDecl *ImpDecl =
1986          ObjCImplementations[IFace->getIdentifier()])
1987        Setter = ImpDecl->getInstanceMethod(SetterSel);
1988    }
1989    // Look through local category implementations associated with the class.
1990    if (!Setter) {
1991      for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1992        if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1993          Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1994      }
1995    }
1996
1997    if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1998      return ExprError();
1999
2000    if (Getter || Setter) {
2001      QualType PType;
2002
2003      if (Getter)
2004        PType = Getter->getResultType();
2005      else {
2006        for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2007             E = Setter->param_end(); PI != E; ++PI)
2008          PType = (*PI)->getType();
2009      }
2010      // FIXME: we must check that the setter has property type.
2011      return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2012                                      Setter, MemberLoc, BaseExpr));
2013    }
2014    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2015      << &Member << BaseType);
2016  }
2017  // Handle properties on qualified "id" protocols.
2018  const ObjCQualifiedIdType *QIdTy;
2019  if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2020    // Check protocols on qualified interfaces.
2021    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2022    if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel)) {
2023      if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2024        // Check the use of this declaration
2025        if (DiagnoseUseOfDecl(PD, MemberLoc))
2026          return ExprError();
2027
2028        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2029                                                       MemberLoc, BaseExpr));
2030      }
2031      if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2032        // Check the use of this method.
2033        if (DiagnoseUseOfDecl(OMD, MemberLoc))
2034          return ExprError();
2035
2036        return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2037                                                   OMD->getResultType(),
2038                                                   OMD, OpLoc, MemberLoc,
2039                                                   NULL, 0));
2040      }
2041    }
2042
2043    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2044                       << &Member << BaseType);
2045  }
2046  // Handle properties on ObjC 'Class' types.
2047  if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2048    // Also must look for a getter name which uses property syntax.
2049    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2050    if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2051      ObjCInterfaceDecl *IFace = MD->getClassInterface();
2052      ObjCMethodDecl *Getter;
2053      // FIXME: need to also look locally in the implementation.
2054      if ((Getter = IFace->lookupClassMethod(Sel))) {
2055        // Check the use of this method.
2056        if (DiagnoseUseOfDecl(Getter, MemberLoc))
2057          return ExprError();
2058      }
2059      // If we found a getter then this may be a valid dot-reference, we
2060      // will look for the matching setter, in case it is needed.
2061      Selector SetterSel =
2062        SelectorTable::constructSetterName(PP.getIdentifierTable(),
2063                                           PP.getSelectorTable(), &Member);
2064      ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2065      if (!Setter) {
2066        // If this reference is in an @implementation, also check for 'private'
2067        // methods.
2068        if (ObjCImplementationDecl *ImpDecl =
2069            ObjCImplementations[IFace->getIdentifier()])
2070          Setter = ImpDecl->getInstanceMethod(SetterSel);
2071      }
2072      // Look through local category implementations associated with the class.
2073      if (!Setter) {
2074        for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2075          if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2076            Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel);
2077        }
2078      }
2079
2080      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2081        return ExprError();
2082
2083      if (Getter || Setter) {
2084        QualType PType;
2085
2086        if (Getter)
2087          PType = Getter->getResultType();
2088        else {
2089          for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2090               E = Setter->param_end(); PI != E; ++PI)
2091            PType = (*PI)->getType();
2092        }
2093        // FIXME: we must check that the setter has property type.
2094        return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2095                                        Setter, MemberLoc, BaseExpr));
2096      }
2097      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2098        << &Member << BaseType);
2099    }
2100  }
2101
2102  // Handle 'field access' to vectors, such as 'V.xx'.
2103  if (BaseType->isExtVectorType()) {
2104    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2105    if (ret.isNull())
2106      return ExprError();
2107    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
2108                                                    MemberLoc));
2109  }
2110
2111  return ExprError(Diag(MemberLoc,
2112                        diag::err_typecheck_member_reference_struct_union)
2113                     << BaseType << BaseExpr->getSourceRange());
2114}
2115
2116/// ConvertArgumentsForCall - Converts the arguments specified in
2117/// Args/NumArgs to the parameter types of the function FDecl with
2118/// function prototype Proto. Call is the call expression itself, and
2119/// Fn is the function expression. For a C++ member function, this
2120/// routine does not attempt to convert the object argument. Returns
2121/// true if the call is ill-formed.
2122bool
2123Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2124                              FunctionDecl *FDecl,
2125                              const FunctionProtoType *Proto,
2126                              Expr **Args, unsigned NumArgs,
2127                              SourceLocation RParenLoc) {
2128  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
2129  // assignment, to the types of the corresponding parameter, ...
2130  unsigned NumArgsInProto = Proto->getNumArgs();
2131  unsigned NumArgsToCheck = NumArgs;
2132  bool Invalid = false;
2133
2134  // If too few arguments are available (and we don't have default
2135  // arguments for the remaining parameters), don't make the call.
2136  if (NumArgs < NumArgsInProto) {
2137    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2138      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2139        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2140    // Use default arguments for missing arguments
2141    NumArgsToCheck = NumArgsInProto;
2142    Call->setNumArgs(Context, NumArgsInProto);
2143  }
2144
2145  // If too many are passed and not variadic, error on the extras and drop
2146  // them.
2147  if (NumArgs > NumArgsInProto) {
2148    if (!Proto->isVariadic()) {
2149      Diag(Args[NumArgsInProto]->getLocStart(),
2150           diag::err_typecheck_call_too_many_args)
2151        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2152        << SourceRange(Args[NumArgsInProto]->getLocStart(),
2153                       Args[NumArgs-1]->getLocEnd());
2154      // This deletes the extra arguments.
2155      Call->setNumArgs(Context, NumArgsInProto);
2156      Invalid = true;
2157    }
2158    NumArgsToCheck = NumArgsInProto;
2159  }
2160
2161  // Continue to check argument types (even if we have too few/many args).
2162  for (unsigned i = 0; i != NumArgsToCheck; i++) {
2163    QualType ProtoArgType = Proto->getArgType(i);
2164
2165    Expr *Arg;
2166    if (i < NumArgs) {
2167      Arg = Args[i];
2168
2169      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2170                              ProtoArgType,
2171                              diag::err_call_incomplete_argument,
2172                              Arg->getSourceRange()))
2173        return true;
2174
2175      // Pass the argument.
2176      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2177        return true;
2178    } else
2179      // We already type-checked the argument, so we know it works.
2180      Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
2181    QualType ArgType = Arg->getType();
2182
2183    Call->setArg(i, Arg);
2184  }
2185
2186  // If this is a variadic call, handle args passed through "...".
2187  if (Proto->isVariadic()) {
2188    VariadicCallType CallType = VariadicFunction;
2189    if (Fn->getType()->isBlockPointerType())
2190      CallType = VariadicBlock; // Block
2191    else if (isa<MemberExpr>(Fn))
2192      CallType = VariadicMethod;
2193
2194    // Promote the arguments (C99 6.5.2.2p7).
2195    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2196      Expr *Arg = Args[i];
2197      DefaultVariadicArgumentPromotion(Arg, CallType);
2198      Call->setArg(i, Arg);
2199    }
2200  }
2201
2202  return Invalid;
2203}
2204
2205/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2206/// This provides the location of the left/right parens and a list of comma
2207/// locations.
2208Action::OwningExprResult
2209Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2210                    MultiExprArg args,
2211                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2212  unsigned NumArgs = args.size();
2213  Expr *Fn = static_cast<Expr *>(fn.release());
2214  Expr **Args = reinterpret_cast<Expr**>(args.release());
2215  assert(Fn && "no function call expression");
2216  FunctionDecl *FDecl = NULL;
2217  DeclarationName UnqualifiedName;
2218
2219  if (getLangOptions().CPlusPlus) {
2220    // Determine whether this is a dependent call inside a C++ template,
2221    // in which case we won't do any semantic analysis now.
2222    // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2223    bool Dependent = false;
2224    if (Fn->isTypeDependent())
2225      Dependent = true;
2226    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2227      Dependent = true;
2228
2229    if (Dependent)
2230      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2231                                          Context.DependentTy, RParenLoc));
2232
2233    // Determine whether this is a call to an object (C++ [over.call.object]).
2234    if (Fn->getType()->isRecordType())
2235      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2236                                                CommaLocs, RParenLoc));
2237
2238    // Determine whether this is a call to a member function.
2239    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2240      if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2241          isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
2242        return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2243                                               CommaLocs, RParenLoc));
2244  }
2245
2246  // If we're directly calling a function, get the appropriate declaration.
2247  DeclRefExpr *DRExpr = NULL;
2248  Expr *FnExpr = Fn;
2249  bool ADL = true;
2250  while (true) {
2251    if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2252      FnExpr = IcExpr->getSubExpr();
2253    else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2254      // Parentheses around a function disable ADL
2255      // (C++0x [basic.lookup.argdep]p1).
2256      ADL = false;
2257      FnExpr = PExpr->getSubExpr();
2258    } else if (isa<UnaryOperator>(FnExpr) &&
2259               cast<UnaryOperator>(FnExpr)->getOpcode()
2260                 == UnaryOperator::AddrOf) {
2261      FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2262    } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2263      // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2264      ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2265      break;
2266    } else if (UnresolvedFunctionNameExpr *DepName
2267                 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2268      UnqualifiedName = DepName->getName();
2269      break;
2270    } else {
2271      // Any kind of name that does not refer to a declaration (or
2272      // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2273      ADL = false;
2274      break;
2275    }
2276  }
2277
2278  OverloadedFunctionDecl *Ovl = 0;
2279  if (DRExpr) {
2280    FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
2281    Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2282  }
2283
2284  if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2285    // We don't perform ADL for implicit declarations of builtins.
2286    if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
2287      ADL = false;
2288
2289    // We don't perform ADL in C.
2290    if (!getLangOptions().CPlusPlus)
2291      ADL = false;
2292
2293    if (Ovl || ADL) {
2294      FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2295                                      UnqualifiedName, LParenLoc, Args,
2296                                      NumArgs, CommaLocs, RParenLoc, ADL);
2297      if (!FDecl)
2298        return ExprError();
2299
2300      // Update Fn to refer to the actual function selected.
2301      Expr *NewFn = 0;
2302      if (QualifiedDeclRefExpr *QDRExpr
2303            = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
2304        NewFn = QualifiedDeclRefExpr::Create(Context, FDecl, FDecl->getType(),
2305                                             QDRExpr->getLocation(),
2306                                             false, false,
2307                                             QDRExpr->getQualifierRange(),
2308                                             QDRExpr->begin(),
2309                                             QDRExpr->size());
2310      else
2311        NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2312                                          Fn->getSourceRange().getBegin());
2313      Fn->Destroy(Context);
2314      Fn = NewFn;
2315    }
2316  }
2317
2318  // Promote the function operand.
2319  UsualUnaryConversions(Fn);
2320
2321  // Make the call expr early, before semantic checks.  This guarantees cleanup
2322  // of arguments and function on error.
2323  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2324                                                               Args, NumArgs,
2325                                                               Context.BoolTy,
2326                                                               RParenLoc));
2327
2328  const FunctionType *FuncT;
2329  if (!Fn->getType()->isBlockPointerType()) {
2330    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2331    // have type pointer to function".
2332    const PointerType *PT = Fn->getType()->getAsPointerType();
2333    if (PT == 0)
2334      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2335        << Fn->getType() << Fn->getSourceRange());
2336    FuncT = PT->getPointeeType()->getAsFunctionType();
2337  } else { // This is a block call.
2338    FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2339                getAsFunctionType();
2340  }
2341  if (FuncT == 0)
2342    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2343      << Fn->getType() << Fn->getSourceRange());
2344
2345  // Check for a valid return type
2346  if (!FuncT->getResultType()->isVoidType() &&
2347      RequireCompleteType(Fn->getSourceRange().getBegin(),
2348                          FuncT->getResultType(),
2349                          diag::err_call_incomplete_return,
2350                          TheCall->getSourceRange()))
2351    return ExprError();
2352
2353  // We know the result type of the call, set it.
2354  TheCall->setType(FuncT->getResultType().getNonReferenceType());
2355
2356  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
2357    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2358                                RParenLoc))
2359      return ExprError();
2360  } else {
2361    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
2362
2363    // Promote the arguments (C99 6.5.2.2p6).
2364    for (unsigned i = 0; i != NumArgs; i++) {
2365      Expr *Arg = Args[i];
2366      DefaultArgumentPromotion(Arg);
2367      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2368                              Arg->getType(),
2369                              diag::err_call_incomplete_argument,
2370                              Arg->getSourceRange()))
2371        return ExprError();
2372      TheCall->setArg(i, Arg);
2373    }
2374  }
2375
2376  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2377    if (!Method->isStatic())
2378      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2379        << Fn->getSourceRange());
2380
2381  // Do special checking on direct calls to functions.
2382  if (FDecl)
2383    return CheckFunctionCall(FDecl, TheCall.take());
2384
2385  return Owned(TheCall.take());
2386}
2387
2388Action::OwningExprResult
2389Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2390                           SourceLocation RParenLoc, ExprArg InitExpr) {
2391  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
2392  QualType literalType = QualType::getFromOpaquePtr(Ty);
2393  // FIXME: put back this assert when initializers are worked out.
2394  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
2395  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
2396
2397  if (literalType->isArrayType()) {
2398    if (literalType->isVariableArrayType())
2399      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2400        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
2401  } else if (RequireCompleteType(LParenLoc, literalType,
2402                                    diag::err_typecheck_decl_incomplete_type,
2403                SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
2404    return ExprError();
2405
2406  if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
2407                            DeclarationName(), /*FIXME:DirectInit=*/false))
2408    return ExprError();
2409
2410  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
2411  if (isFileScope) { // 6.5.2.5p3
2412    if (CheckForConstantInitializer(literalExpr, literalType))
2413      return ExprError();
2414  }
2415  InitExpr.release();
2416  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2417                                                 literalExpr, isFileScope));
2418}
2419
2420Action::OwningExprResult
2421Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2422                    SourceLocation RBraceLoc) {
2423  unsigned NumInit = initlist.size();
2424  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
2425
2426  // Semantic analysis for initializers is done by ActOnDeclarator() and
2427  // CheckInitializer() - it requires knowledge of the object being intialized.
2428
2429  InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
2430                                               RBraceLoc);
2431  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
2432  return Owned(E);
2433}
2434
2435/// CheckCastTypes - Check type constraints for casting between types.
2436bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
2437  UsualUnaryConversions(castExpr);
2438
2439  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2440  // type needs to be scalar.
2441  if (castType->isVoidType()) {
2442    // Cast to void allows any expr type.
2443  } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2444    // We can't check any more until template instantiation time.
2445  } else if (!castType->isScalarType() && !castType->isVectorType()) {
2446    if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2447        Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2448        (castType->isStructureType() || castType->isUnionType())) {
2449      // GCC struct/union extension: allow cast to self.
2450      // FIXME: Check that the cast destination type is complete.
2451      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2452        << castType << castExpr->getSourceRange();
2453    } else if (castType->isUnionType()) {
2454      // GCC cast to union extension
2455      RecordDecl *RD = castType->getAsRecordType()->getDecl();
2456      RecordDecl::field_iterator Field, FieldEnd;
2457      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2458           Field != FieldEnd; ++Field) {
2459        if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2460            Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2461          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2462            << castExpr->getSourceRange();
2463          break;
2464        }
2465      }
2466      if (Field == FieldEnd)
2467        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2468          << castExpr->getType() << castExpr->getSourceRange();
2469    } else {
2470      // Reject any other conversions to non-scalar types.
2471      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
2472        << castType << castExpr->getSourceRange();
2473    }
2474  } else if (!castExpr->getType()->isScalarType() &&
2475             !castExpr->getType()->isVectorType()) {
2476    return Diag(castExpr->getLocStart(),
2477                diag::err_typecheck_expect_scalar_operand)
2478      << castExpr->getType() << castExpr->getSourceRange();
2479  } else if (castExpr->getType()->isVectorType()) {
2480    if (CheckVectorCast(TyR, castExpr->getType(), castType))
2481      return true;
2482  } else if (castType->isVectorType()) {
2483    if (CheckVectorCast(TyR, castType, castExpr->getType()))
2484      return true;
2485  } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
2486    return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
2487  }
2488  return false;
2489}
2490
2491bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
2492  assert(VectorTy->isVectorType() && "Not a vector type!");
2493
2494  if (Ty->isVectorType() || Ty->isIntegerType()) {
2495    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
2496      return Diag(R.getBegin(),
2497                  Ty->isVectorType() ?
2498                  diag::err_invalid_conversion_between_vectors :
2499                  diag::err_invalid_conversion_between_vector_and_integer)
2500        << VectorTy << Ty << R;
2501  } else
2502    return Diag(R.getBegin(),
2503                diag::err_invalid_conversion_between_vector_and_scalar)
2504      << VectorTy << Ty << R;
2505
2506  return false;
2507}
2508
2509Action::OwningExprResult
2510Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2511                    SourceLocation RParenLoc, ExprArg Op) {
2512  assert((Ty != 0) && (Op.get() != 0) &&
2513         "ActOnCastExpr(): missing type or expr");
2514
2515  Expr *castExpr = static_cast<Expr*>(Op.release());
2516  QualType castType = QualType::getFromOpaquePtr(Ty);
2517
2518  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
2519    return ExprError();
2520  return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
2521                                            LParenLoc, RParenLoc));
2522}
2523
2524/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2525/// In that case, lhs = cond.
2526/// C99 6.5.15
2527QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2528                                        SourceLocation QuestionLoc) {
2529  UsualUnaryConversions(Cond);
2530  UsualUnaryConversions(LHS);
2531  UsualUnaryConversions(RHS);
2532  QualType CondTy = Cond->getType();
2533  QualType LHSTy = LHS->getType();
2534  QualType RHSTy = RHS->getType();
2535
2536  // first, check the condition.
2537  if (!Cond->isTypeDependent()) {
2538    if (!CondTy->isScalarType()) { // C99 6.5.15p2
2539      Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2540        << CondTy;
2541      return QualType();
2542    }
2543  }
2544
2545  // Now check the two expressions.
2546  if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
2547    return Context.DependentTy;
2548
2549  // If both operands have arithmetic type, do the usual arithmetic conversions
2550  // to find a common type: C99 6.5.15p3,5.
2551  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2552    UsualArithmeticConversions(LHS, RHS);
2553    return LHS->getType();
2554  }
2555
2556  // If both operands are the same structure or union type, the result is that
2557  // type.
2558  if (const RecordType *LHSRT = LHSTy->getAsRecordType()) {    // C99 6.5.15p3
2559    if (const RecordType *RHSRT = RHSTy->getAsRecordType())
2560      if (LHSRT->getDecl() == RHSRT->getDecl())
2561        // "If both the operands have structure or union type, the result has
2562        // that type."  This implies that CV qualifiers are dropped.
2563        return LHSTy.getUnqualifiedType();
2564    // FIXME: Type of conditional expression must be complete in C mode.
2565  }
2566
2567  // C99 6.5.15p5: "If both operands have void type, the result has void type."
2568  // The following || allows only one side to be void (a GCC-ism).
2569  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2570    if (!LHSTy->isVoidType())
2571      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2572        << RHS->getSourceRange();
2573    if (!RHSTy->isVoidType())
2574      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2575        << LHS->getSourceRange();
2576    ImpCastExprToType(LHS, Context.VoidTy);
2577    ImpCastExprToType(RHS, Context.VoidTy);
2578    return Context.VoidTy;
2579  }
2580  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2581  // the type of the other operand."
2582  if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2583       Context.isObjCObjectPointerType(LHSTy)) &&
2584      RHS->isNullPointerConstant(Context)) {
2585    ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2586    return LHSTy;
2587  }
2588  if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2589       Context.isObjCObjectPointerType(RHSTy)) &&
2590      LHS->isNullPointerConstant(Context)) {
2591    ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2592    return RHSTy;
2593  }
2594
2595  // Handle the case where both operands are pointers before we handle null
2596  // pointer constants in case both operands are null pointer constants.
2597  if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2598    if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
2599      // get the "pointed to" types
2600      QualType lhptee = LHSPT->getPointeeType();
2601      QualType rhptee = RHSPT->getPointeeType();
2602
2603      // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2604      if (lhptee->isVoidType() &&
2605          rhptee->isIncompleteOrObjectType()) {
2606        // Figure out necessary qualifiers (C99 6.5.15p6)
2607        QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
2608        QualType destType = Context.getPointerType(destPointee);
2609        ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2610        ImpCastExprToType(RHS, destType); // promote to void*
2611        return destType;
2612      }
2613      if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
2614        QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
2615        QualType destType = Context.getPointerType(destPointee);
2616        ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2617        ImpCastExprToType(RHS, destType); // promote to void*
2618        return destType;
2619      }
2620
2621      if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2622        // Two identical pointer types are always compatible.
2623        return LHSTy;
2624      }
2625
2626      QualType compositeType = LHSTy;
2627
2628      // If either type is an Objective-C object type then check
2629      // compatibility according to Objective-C.
2630      if (Context.isObjCObjectPointerType(LHSTy) ||
2631          Context.isObjCObjectPointerType(RHSTy)) {
2632        // If both operands are interfaces and either operand can be
2633        // assigned to the other, use that type as the composite
2634        // type. This allows
2635        //   xxx ? (A*) a : (B*) b
2636        // where B is a subclass of A.
2637        //
2638        // Additionally, as for assignment, if either type is 'id'
2639        // allow silent coercion. Finally, if the types are
2640        // incompatible then make sure to use 'id' as the composite
2641        // type so the result is acceptable for sending messages to.
2642
2643        // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2644        // It could return the composite type.
2645        const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2646        const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2647        if (LHSIface && RHSIface &&
2648            Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2649          compositeType = LHSTy;
2650        } else if (LHSIface && RHSIface &&
2651                   Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
2652          compositeType = RHSTy;
2653        } else if (Context.isObjCIdStructType(lhptee) ||
2654                   Context.isObjCIdStructType(rhptee)) {
2655          compositeType = Context.getObjCIdType();
2656        } else {
2657          Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2658               << LHSTy << RHSTy
2659               << LHS->getSourceRange() << RHS->getSourceRange();
2660          QualType incompatTy = Context.getObjCIdType();
2661          ImpCastExprToType(LHS, incompatTy);
2662          ImpCastExprToType(RHS, incompatTy);
2663          return incompatTy;
2664        }
2665      } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2666                                             rhptee.getUnqualifiedType())) {
2667        Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2668          << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2669        // In this situation, we assume void* type. No especially good
2670        // reason, but this is what gcc does, and we do have to pick
2671        // to get a consistent AST.
2672        QualType incompatTy = Context.getPointerType(Context.VoidTy);
2673        ImpCastExprToType(LHS, incompatTy);
2674        ImpCastExprToType(RHS, incompatTy);
2675        return incompatTy;
2676      }
2677      // The pointer types are compatible.
2678      // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2679      // differently qualified versions of compatible types, the result type is
2680      // a pointer to an appropriately qualified version of the *composite*
2681      // type.
2682      // FIXME: Need to calculate the composite type.
2683      // FIXME: Need to add qualifiers
2684      ImpCastExprToType(LHS, compositeType);
2685      ImpCastExprToType(RHS, compositeType);
2686      return compositeType;
2687    }
2688  }
2689
2690  // Selection between block pointer types is ok as long as they are the same.
2691  if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2692      Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2693    return LHSTy;
2694
2695  // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2696  // evaluates to "struct objc_object *" (and is handled above when comparing
2697  // id with statically typed objects).
2698  if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
2699    // GCC allows qualified id and any Objective-C type to devolve to
2700    // id. Currently localizing to here until clear this should be
2701    // part of ObjCQualifiedIdTypesAreCompatible.
2702    if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
2703        (LHSTy->isObjCQualifiedIdType() &&
2704         Context.isObjCObjectPointerType(RHSTy)) ||
2705        (RHSTy->isObjCQualifiedIdType() &&
2706         Context.isObjCObjectPointerType(LHSTy))) {
2707      // FIXME: This is not the correct composite type. This only
2708      // happens to work because id can more or less be used anywhere,
2709      // however this may change the type of method sends.
2710      // FIXME: gcc adds some type-checking of the arguments and emits
2711      // (confusing) incompatible comparison warnings in some
2712      // cases. Investigate.
2713      QualType compositeType = Context.getObjCIdType();
2714      ImpCastExprToType(LHS, compositeType);
2715      ImpCastExprToType(RHS, compositeType);
2716      return compositeType;
2717    }
2718  }
2719
2720  // Otherwise, the operands are not compatible.
2721  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2722    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2723  return QualType();
2724}
2725
2726/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
2727/// in the case of a the GNU conditional expr extension.
2728Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2729                                                  SourceLocation ColonLoc,
2730                                                  ExprArg Cond, ExprArg LHS,
2731                                                  ExprArg RHS) {
2732  Expr *CondExpr = (Expr *) Cond.get();
2733  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
2734
2735  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2736  // was the condition.
2737  bool isLHSNull = LHSExpr == 0;
2738  if (isLHSNull)
2739    LHSExpr = CondExpr;
2740
2741  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2742                                             RHSExpr, QuestionLoc);
2743  if (result.isNull())
2744    return ExprError();
2745
2746  Cond.release();
2747  LHS.release();
2748  RHS.release();
2749  return Owned(new (Context) ConditionalOperator(CondExpr,
2750                                                 isLHSNull ? 0 : LHSExpr,
2751                                                 RHSExpr, result));
2752}
2753
2754
2755// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2756// being closely modeled after the C99 spec:-). The odd characteristic of this
2757// routine is it effectively iqnores the qualifiers on the top level pointee.
2758// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2759// FIXME: add a couple examples in this comment.
2760Sema::AssignConvertType
2761Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2762  QualType lhptee, rhptee;
2763
2764  // get the "pointed to" type (ignoring qualifiers at the top level)
2765  lhptee = lhsType->getAsPointerType()->getPointeeType();
2766  rhptee = rhsType->getAsPointerType()->getPointeeType();
2767
2768  // make sure we operate on the canonical type
2769  lhptee = Context.getCanonicalType(lhptee);
2770  rhptee = Context.getCanonicalType(rhptee);
2771
2772  AssignConvertType ConvTy = Compatible;
2773
2774  // C99 6.5.16.1p1: This following citation is common to constraints
2775  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2776  // qualifiers of the type *pointed to* by the right;
2777  // FIXME: Handle ExtQualType
2778  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
2779    ConvTy = CompatiblePointerDiscardsQualifiers;
2780
2781  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2782  // incomplete type and the other is a pointer to a qualified or unqualified
2783  // version of void...
2784  if (lhptee->isVoidType()) {
2785    if (rhptee->isIncompleteOrObjectType())
2786      return ConvTy;
2787
2788    // As an extension, we allow cast to/from void* to function pointer.
2789    assert(rhptee->isFunctionType());
2790    return FunctionVoidPointer;
2791  }
2792
2793  if (rhptee->isVoidType()) {
2794    if (lhptee->isIncompleteOrObjectType())
2795      return ConvTy;
2796
2797    // As an extension, we allow cast to/from void* to function pointer.
2798    assert(lhptee->isFunctionType());
2799    return FunctionVoidPointer;
2800  }
2801  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2802  // unqualified versions of compatible types, ...
2803  lhptee = lhptee.getUnqualifiedType();
2804  rhptee = rhptee.getUnqualifiedType();
2805  if (!Context.typesAreCompatible(lhptee, rhptee)) {
2806    // Check if the pointee types are compatible ignoring the sign.
2807    // We explicitly check for char so that we catch "char" vs
2808    // "unsigned char" on systems where "char" is unsigned.
2809    if (lhptee->isCharType()) {
2810      lhptee = Context.UnsignedCharTy;
2811    } else if (lhptee->isSignedIntegerType()) {
2812      lhptee = Context.getCorrespondingUnsignedType(lhptee);
2813    }
2814    if (rhptee->isCharType()) {
2815      rhptee = Context.UnsignedCharTy;
2816    } else if (rhptee->isSignedIntegerType()) {
2817      rhptee = Context.getCorrespondingUnsignedType(rhptee);
2818    }
2819    if (lhptee == rhptee) {
2820      // Types are compatible ignoring the sign. Qualifier incompatibility
2821      // takes priority over sign incompatibility because the sign
2822      // warning can be disabled.
2823      if (ConvTy != Compatible)
2824        return ConvTy;
2825      return IncompatiblePointerSign;
2826    }
2827    // General pointer incompatibility takes priority over qualifiers.
2828    return IncompatiblePointer;
2829  }
2830  return ConvTy;
2831}
2832
2833/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2834/// block pointer types are compatible or whether a block and normal pointer
2835/// are compatible. It is more restrict than comparing two function pointer
2836// types.
2837Sema::AssignConvertType
2838Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2839                                          QualType rhsType) {
2840  QualType lhptee, rhptee;
2841
2842  // get the "pointed to" type (ignoring qualifiers at the top level)
2843  lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2844  rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2845
2846  // make sure we operate on the canonical type
2847  lhptee = Context.getCanonicalType(lhptee);
2848  rhptee = Context.getCanonicalType(rhptee);
2849
2850  AssignConvertType ConvTy = Compatible;
2851
2852  // For blocks we enforce that qualifiers are identical.
2853  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2854    ConvTy = CompatiblePointerDiscardsQualifiers;
2855
2856  if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2857    return IncompatibleBlockPointer;
2858  return ConvTy;
2859}
2860
2861/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2862/// has code to accommodate several GCC extensions when type checking
2863/// pointers. Here are some objectionable examples that GCC considers warnings:
2864///
2865///  int a, *pint;
2866///  short *pshort;
2867///  struct foo *pfoo;
2868///
2869///  pint = pshort; // warning: assignment from incompatible pointer type
2870///  a = pint; // warning: assignment makes integer from pointer without a cast
2871///  pint = a; // warning: assignment makes pointer from integer without a cast
2872///  pint = pfoo; // warning: assignment from incompatible pointer type
2873///
2874/// As a result, the code for dealing with pointers is more complex than the
2875/// C99 spec dictates.
2876///
2877Sema::AssignConvertType
2878Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
2879  // Get canonical types.  We're not formatting these types, just comparing
2880  // them.
2881  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2882  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
2883
2884  if (lhsType == rhsType)
2885    return Compatible; // Common case: fast path an exact match.
2886
2887  // If the left-hand side is a reference type, then we are in a
2888  // (rare!) case where we've allowed the use of references in C,
2889  // e.g., as a parameter type in a built-in function. In this case,
2890  // just make sure that the type referenced is compatible with the
2891  // right-hand side type. The caller is responsible for adjusting
2892  // lhsType so that the resulting expression does not have reference
2893  // type.
2894  if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2895    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
2896      return Compatible;
2897    return Incompatible;
2898  }
2899
2900  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2901    if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
2902      return Compatible;
2903    // Relax integer conversions like we do for pointers below.
2904    if (rhsType->isIntegerType())
2905      return IntToPointer;
2906    if (lhsType->isIntegerType())
2907      return PointerToInt;
2908    return IncompatibleObjCQualifiedId;
2909  }
2910
2911  if (lhsType->isVectorType() || rhsType->isVectorType()) {
2912    // For ExtVector, allow vector splats; float -> <n x float>
2913    if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2914      if (LV->getElementType() == rhsType)
2915        return Compatible;
2916
2917    // If we are allowing lax vector conversions, and LHS and RHS are both
2918    // vectors, the total size only needs to be the same. This is a bitcast;
2919    // no bits are changed but the result type is different.
2920    if (getLangOptions().LaxVectorConversions &&
2921        lhsType->isVectorType() && rhsType->isVectorType()) {
2922      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2923        return IncompatibleVectors;
2924    }
2925    return Incompatible;
2926  }
2927
2928  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
2929    return Compatible;
2930
2931  if (isa<PointerType>(lhsType)) {
2932    if (rhsType->isIntegerType())
2933      return IntToPointer;
2934
2935    if (isa<PointerType>(rhsType))
2936      return CheckPointerTypesForAssignment(lhsType, rhsType);
2937
2938    if (rhsType->getAsBlockPointerType()) {
2939      if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
2940        return Compatible;
2941
2942      // Treat block pointers as objects.
2943      if (getLangOptions().ObjC1 &&
2944          lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2945        return Compatible;
2946    }
2947    return Incompatible;
2948  }
2949
2950  if (isa<BlockPointerType>(lhsType)) {
2951    if (rhsType->isIntegerType())
2952      return IntToBlockPointer;
2953
2954    // Treat block pointers as objects.
2955    if (getLangOptions().ObjC1 &&
2956        rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2957      return Compatible;
2958
2959    if (rhsType->isBlockPointerType())
2960      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2961
2962    if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2963      if (RHSPT->getPointeeType()->isVoidType())
2964        return Compatible;
2965    }
2966    return Incompatible;
2967  }
2968
2969  if (isa<PointerType>(rhsType)) {
2970    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
2971    if (lhsType == Context.BoolTy)
2972      return Compatible;
2973
2974    if (lhsType->isIntegerType())
2975      return PointerToInt;
2976
2977    if (isa<PointerType>(lhsType))
2978      return CheckPointerTypesForAssignment(lhsType, rhsType);
2979
2980    if (isa<BlockPointerType>(lhsType) &&
2981        rhsType->getAsPointerType()->getPointeeType()->isVoidType())
2982      return Compatible;
2983    return Incompatible;
2984  }
2985
2986  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
2987    if (Context.typesAreCompatible(lhsType, rhsType))
2988      return Compatible;
2989  }
2990  return Incompatible;
2991}
2992
2993Sema::AssignConvertType
2994Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
2995  if (getLangOptions().CPlusPlus) {
2996    if (!lhsType->isRecordType()) {
2997      // C++ 5.17p3: If the left operand is not of class type, the
2998      // expression is implicitly converted (C++ 4) to the
2999      // cv-unqualified type of the left operand.
3000      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3001                                    "assigning"))
3002        return Incompatible;
3003      else
3004        return Compatible;
3005    }
3006
3007    // FIXME: Currently, we fall through and treat C++ classes like C
3008    // structures.
3009  }
3010
3011  // C99 6.5.16.1p1: the left operand is a pointer and the right is
3012  // a null pointer constant.
3013  if ((lhsType->isPointerType() ||
3014       lhsType->isObjCQualifiedIdType() ||
3015       lhsType->isBlockPointerType())
3016      && rExpr->isNullPointerConstant(Context)) {
3017    ImpCastExprToType(rExpr, lhsType);
3018    return Compatible;
3019  }
3020
3021  // This check seems unnatural, however it is necessary to ensure the proper
3022  // conversion of functions/arrays. If the conversion were done for all
3023  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
3024  // expressions that surpress this implicit conversion (&, sizeof).
3025  //
3026  // Suppress this for references: C++ 8.5.3p5.
3027  if (!lhsType->isReferenceType())
3028    DefaultFunctionArrayConversion(rExpr);
3029
3030  Sema::AssignConvertType result =
3031    CheckAssignmentConstraints(lhsType, rExpr->getType());
3032
3033  // C99 6.5.16.1p2: The value of the right operand is converted to the
3034  // type of the assignment expression.
3035  // CheckAssignmentConstraints allows the left-hand side to be a reference,
3036  // so that we can use references in built-in functions even in C.
3037  // The getNonReferenceType() call makes sure that the resulting expression
3038  // does not have reference type.
3039  if (rExpr->getType() != lhsType)
3040    ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
3041  return result;
3042}
3043
3044Sema::AssignConvertType
3045Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
3046  return CheckAssignmentConstraints(lhsType, rhsType);
3047}
3048
3049QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
3050  Diag(Loc, diag::err_typecheck_invalid_operands)
3051    << lex->getType() << rex->getType()
3052    << lex->getSourceRange() << rex->getSourceRange();
3053  return QualType();
3054}
3055
3056inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
3057                                                              Expr *&rex) {
3058  // For conversion purposes, we ignore any qualifiers.
3059  // For example, "const float" and "float" are equivalent.
3060  QualType lhsType =
3061    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3062  QualType rhsType =
3063    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
3064
3065  // If the vector types are identical, return.
3066  if (lhsType == rhsType)
3067    return lhsType;
3068
3069  // Handle the case of a vector & extvector type of the same size and element
3070  // type.  It would be nice if we only had one vector type someday.
3071  if (getLangOptions().LaxVectorConversions) {
3072    // FIXME: Should we warn here?
3073    if (const VectorType *LV = lhsType->getAsVectorType()) {
3074      if (const VectorType *RV = rhsType->getAsVectorType())
3075        if (LV->getElementType() == RV->getElementType() &&
3076            LV->getNumElements() == RV->getNumElements()) {
3077          return lhsType->isExtVectorType() ? lhsType : rhsType;
3078        }
3079    }
3080  }
3081
3082  // If the lhs is an extended vector and the rhs is a scalar of the same type
3083  // or a literal, promote the rhs to the vector type.
3084  if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
3085    QualType eltType = V->getElementType();
3086
3087    if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
3088        (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3089        (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
3090      ImpCastExprToType(rex, lhsType);
3091      return lhsType;
3092    }
3093  }
3094
3095  // If the rhs is an extended vector and the lhs is a scalar of the same type,
3096  // promote the lhs to the vector type.
3097  if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
3098    QualType eltType = V->getElementType();
3099
3100    if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
3101        (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3102        (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
3103      ImpCastExprToType(lex, rhsType);
3104      return rhsType;
3105    }
3106  }
3107
3108  // You cannot convert between vector values of different size.
3109  Diag(Loc, diag::err_typecheck_vector_not_convertable)
3110    << lex->getType() << rex->getType()
3111    << lex->getSourceRange() << rex->getSourceRange();
3112  return QualType();
3113}
3114
3115inline QualType Sema::CheckMultiplyDivideOperands(
3116  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3117{
3118  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3119    return CheckVectorOperands(Loc, lex, rex);
3120
3121  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3122
3123  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3124    return compType;
3125  return InvalidOperands(Loc, lex, rex);
3126}
3127
3128inline QualType Sema::CheckRemainderOperands(
3129  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3130{
3131  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3132    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3133      return CheckVectorOperands(Loc, lex, rex);
3134    return InvalidOperands(Loc, lex, rex);
3135  }
3136
3137  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3138
3139  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3140    return compType;
3141  return InvalidOperands(Loc, lex, rex);
3142}
3143
3144inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
3145  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3146{
3147  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3148    return CheckVectorOperands(Loc, lex, rex);
3149
3150  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3151
3152  // handle the common case first (both operands are arithmetic).
3153  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3154    return compType;
3155
3156  // Put any potential pointer into PExp
3157  Expr* PExp = lex, *IExp = rex;
3158  if (IExp->getType()->isPointerType())
3159    std::swap(PExp, IExp);
3160
3161  if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
3162    if (IExp->getType()->isIntegerType()) {
3163      // Check for arithmetic on pointers to incomplete types
3164      if (PTy->getPointeeType()->isVoidType()) {
3165        if (getLangOptions().CPlusPlus) {
3166          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3167            << lex->getSourceRange() << rex->getSourceRange();
3168          return QualType();
3169        }
3170
3171        // GNU extension: arithmetic on pointer to void
3172        Diag(Loc, diag::ext_gnu_void_ptr)
3173          << lex->getSourceRange() << rex->getSourceRange();
3174      } else if (PTy->getPointeeType()->isFunctionType()) {
3175        if (getLangOptions().CPlusPlus) {
3176          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3177            << lex->getType() << lex->getSourceRange();
3178          return QualType();
3179        }
3180
3181        // GNU extension: arithmetic on pointer to function
3182        Diag(Loc, diag::ext_gnu_ptr_func_arith)
3183          << lex->getType() << lex->getSourceRange();
3184      } else if (!PTy->isDependentType() &&
3185                 RequireCompleteType(Loc, PTy->getPointeeType(),
3186                                diag::err_typecheck_arithmetic_incomplete_type,
3187                                     lex->getSourceRange(), SourceRange(),
3188                                     lex->getType()))
3189        return QualType();
3190
3191      return PExp->getType();
3192    }
3193  }
3194
3195  return InvalidOperands(Loc, lex, rex);
3196}
3197
3198// C99 6.5.6
3199QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
3200                                        SourceLocation Loc, bool isCompAssign) {
3201  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3202    return CheckVectorOperands(Loc, lex, rex);
3203
3204  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3205
3206  // Enforce type constraints: C99 6.5.6p3.
3207
3208  // Handle the common case first (both operands are arithmetic).
3209  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3210    return compType;
3211
3212  // Either ptr - int   or   ptr - ptr.
3213  if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
3214    QualType lpointee = LHSPTy->getPointeeType();
3215
3216    // The LHS must be an completely-defined object type.
3217
3218    bool ComplainAboutVoid = false;
3219    Expr *ComplainAboutFunc = 0;
3220    if (lpointee->isVoidType()) {
3221      if (getLangOptions().CPlusPlus) {
3222        Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3223          << lex->getSourceRange() << rex->getSourceRange();
3224        return QualType();
3225      }
3226
3227      // GNU C extension: arithmetic on pointer to void
3228      ComplainAboutVoid = true;
3229    } else if (lpointee->isFunctionType()) {
3230      if (getLangOptions().CPlusPlus) {
3231        Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3232          << lex->getType() << lex->getSourceRange();
3233        return QualType();
3234      }
3235
3236      // GNU C extension: arithmetic on pointer to function
3237      ComplainAboutFunc = lex;
3238    } else if (!lpointee->isDependentType() &&
3239               RequireCompleteType(Loc, lpointee,
3240                                   diag::err_typecheck_sub_ptr_object,
3241                                   lex->getSourceRange(),
3242                                   SourceRange(),
3243                                   lex->getType()))
3244      return QualType();
3245
3246    // The result type of a pointer-int computation is the pointer type.
3247    if (rex->getType()->isIntegerType()) {
3248      if (ComplainAboutVoid)
3249        Diag(Loc, diag::ext_gnu_void_ptr)
3250          << lex->getSourceRange() << rex->getSourceRange();
3251      if (ComplainAboutFunc)
3252        Diag(Loc, diag::ext_gnu_ptr_func_arith)
3253          << ComplainAboutFunc->getType()
3254          << ComplainAboutFunc->getSourceRange();
3255
3256      return lex->getType();
3257    }
3258
3259    // Handle pointer-pointer subtractions.
3260    if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
3261      QualType rpointee = RHSPTy->getPointeeType();
3262
3263      // RHS must be a completely-type object type.
3264      // Handle the GNU void* extension.
3265      if (rpointee->isVoidType()) {
3266        if (getLangOptions().CPlusPlus) {
3267          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3268            << lex->getSourceRange() << rex->getSourceRange();
3269          return QualType();
3270        }
3271
3272        ComplainAboutVoid = true;
3273      } else if (rpointee->isFunctionType()) {
3274        if (getLangOptions().CPlusPlus) {
3275          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3276            << rex->getType() << rex->getSourceRange();
3277          return QualType();
3278        }
3279
3280        // GNU extension: arithmetic on pointer to function
3281        if (!ComplainAboutFunc)
3282          ComplainAboutFunc = rex;
3283      } else if (!rpointee->isDependentType() &&
3284                 RequireCompleteType(Loc, rpointee,
3285                                     diag::err_typecheck_sub_ptr_object,
3286                                     rex->getSourceRange(),
3287                                     SourceRange(),
3288                                     rex->getType()))
3289        return QualType();
3290
3291      // Pointee types must be compatible.
3292      if (!Context.typesAreCompatible(
3293              Context.getCanonicalType(lpointee).getUnqualifiedType(),
3294              Context.getCanonicalType(rpointee).getUnqualifiedType())) {
3295        Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
3296          << lex->getType() << rex->getType()
3297          << lex->getSourceRange() << rex->getSourceRange();
3298        return QualType();
3299      }
3300
3301      if (ComplainAboutVoid)
3302        Diag(Loc, diag::ext_gnu_void_ptr)
3303          << lex->getSourceRange() << rex->getSourceRange();
3304      if (ComplainAboutFunc)
3305        Diag(Loc, diag::ext_gnu_ptr_func_arith)
3306          << ComplainAboutFunc->getType()
3307          << ComplainAboutFunc->getSourceRange();
3308
3309      return Context.getPointerDiffType();
3310    }
3311  }
3312
3313  return InvalidOperands(Loc, lex, rex);
3314}
3315
3316// C99 6.5.7
3317QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
3318                                  bool isCompAssign) {
3319  // C99 6.5.7p2: Each of the operands shall have integer type.
3320  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
3321    return InvalidOperands(Loc, lex, rex);
3322
3323  // Shifts don't perform usual arithmetic conversions, they just do integer
3324  // promotions on each operand. C99 6.5.7p3
3325  if (!isCompAssign)
3326    UsualUnaryConversions(lex);
3327  UsualUnaryConversions(rex);
3328
3329  // "The type of the result is that of the promoted left operand."
3330  return lex->getType();
3331}
3332
3333// C99 6.5.8
3334QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
3335                                    bool isRelational) {
3336  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3337    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
3338
3339  // C99 6.5.8p3 / C99 6.5.9p4
3340  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3341    UsualArithmeticConversions(lex, rex);
3342  else {
3343    UsualUnaryConversions(lex);
3344    UsualUnaryConversions(rex);
3345  }
3346  QualType lType = lex->getType();
3347  QualType rType = rex->getType();
3348
3349  if (!lType->isFloatingType()) {
3350    // For non-floating point types, check for self-comparisons of the form
3351    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
3352    // often indicate logic errors in the program.
3353    // NOTE: Don't warn about comparisons of enum constants. These can arise
3354    //  from macro expansions, and are usually quite deliberate.
3355    Expr *LHSStripped = lex->IgnoreParens();
3356    Expr *RHSStripped = rex->IgnoreParens();
3357    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3358      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
3359        if (DRL->getDecl() == DRR->getDecl() &&
3360            !isa<EnumConstantDecl>(DRL->getDecl()))
3361          Diag(Loc, diag::warn_selfcomparison);
3362
3363    if (isa<CastExpr>(LHSStripped))
3364      LHSStripped = LHSStripped->IgnoreParenCasts();
3365    if (isa<CastExpr>(RHSStripped))
3366      RHSStripped = RHSStripped->IgnoreParenCasts();
3367
3368    // Warn about comparisons against a string constant (unless the other
3369    // operand is null), the user probably wants strcmp.
3370    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
3371        !RHSStripped->isNullPointerConstant(Context))
3372      Diag(Loc, diag::warn_stringcompare) << lex->getSourceRange();
3373    else if ((isa<StringLiteral>(RHSStripped) ||
3374              isa<ObjCEncodeExpr>(RHSStripped)) &&
3375             !LHSStripped->isNullPointerConstant(Context))
3376      Diag(Loc, diag::warn_stringcompare) << rex->getSourceRange();
3377  }
3378
3379  // The result of comparisons is 'bool' in C++, 'int' in C.
3380  QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
3381
3382  if (isRelational) {
3383    if (lType->isRealType() && rType->isRealType())
3384      return ResultTy;
3385  } else {
3386    // Check for comparisons of floating point operands using != and ==.
3387    if (lType->isFloatingType()) {
3388      assert(rType->isFloatingType());
3389      CheckFloatComparison(Loc,lex,rex);
3390    }
3391
3392    if (lType->isArithmeticType() && rType->isArithmeticType())
3393      return ResultTy;
3394  }
3395
3396  bool LHSIsNull = lex->isNullPointerConstant(Context);
3397  bool RHSIsNull = rex->isNullPointerConstant(Context);
3398
3399  // All of the following pointer related warnings are GCC extensions, except
3400  // when handling null pointer constants. One day, we can consider making them
3401  // errors (when -pedantic-errors is enabled).
3402  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
3403    QualType LCanPointeeTy =
3404      Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
3405    QualType RCanPointeeTy =
3406      Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
3407
3408    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
3409        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3410        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
3411                                    RCanPointeeTy.getUnqualifiedType()) &&
3412        !Context.areComparableObjCPointerTypes(lType, rType)) {
3413      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
3414        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3415    }
3416    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3417    return ResultTy;
3418  }
3419  // Handle block pointer types.
3420  if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3421    QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3422    QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3423
3424    if (!LHSIsNull && !RHSIsNull &&
3425        !Context.typesAreBlockCompatible(lpointee, rpointee)) {
3426      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3427        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3428    }
3429    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3430    return ResultTy;
3431  }
3432  // Allow block pointers to be compared with null pointer constants.
3433  if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3434      (lType->isPointerType() && rType->isBlockPointerType())) {
3435    if (!LHSIsNull && !RHSIsNull) {
3436      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3437        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3438    }
3439    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3440    return ResultTy;
3441  }
3442
3443  if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
3444    if (lType->isPointerType() || rType->isPointerType()) {
3445      const PointerType *LPT = lType->getAsPointerType();
3446      const PointerType *RPT = rType->getAsPointerType();
3447      bool LPtrToVoid = LPT ?
3448        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3449      bool RPtrToVoid = RPT ?
3450        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3451
3452      if (!LPtrToVoid && !RPtrToVoid &&
3453          !Context.typesAreCompatible(lType, rType)) {
3454        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
3455          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3456        ImpCastExprToType(rex, lType);
3457        return ResultTy;
3458      }
3459      ImpCastExprToType(rex, lType);
3460      return ResultTy;
3461    }
3462    if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3463      ImpCastExprToType(rex, lType);
3464      return ResultTy;
3465    } else {
3466      if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
3467        Diag(Loc, diag::warn_incompatible_qualified_id_operands)
3468          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3469        ImpCastExprToType(rex, lType);
3470        return ResultTy;
3471      }
3472    }
3473  }
3474  if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3475       rType->isIntegerType()) {
3476    if (!RHSIsNull)
3477      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3478        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3479    ImpCastExprToType(rex, lType); // promote the integer to pointer
3480    return ResultTy;
3481  }
3482  if (lType->isIntegerType() &&
3483      (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
3484    if (!LHSIsNull)
3485      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3486        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3487    ImpCastExprToType(lex, rType); // promote the integer to pointer
3488    return ResultTy;
3489  }
3490  // Handle block pointers.
3491  if (lType->isBlockPointerType() && rType->isIntegerType()) {
3492    if (!RHSIsNull)
3493      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3494        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3495    ImpCastExprToType(rex, lType); // promote the integer to pointer
3496    return ResultTy;
3497  }
3498  if (lType->isIntegerType() && rType->isBlockPointerType()) {
3499    if (!LHSIsNull)
3500      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3501        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3502    ImpCastExprToType(lex, rType); // promote the integer to pointer
3503    return ResultTy;
3504  }
3505  return InvalidOperands(Loc, lex, rex);
3506}
3507
3508/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3509/// operates on extended vector types.  Instead of producing an IntTy result,
3510/// like a scalar comparison, a vector comparison produces a vector of integer
3511/// types.
3512QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
3513                                          SourceLocation Loc,
3514                                          bool isRelational) {
3515  // Check to make sure we're operating on vectors of the same type and width,
3516  // Allowing one side to be a scalar of element type.
3517  QualType vType = CheckVectorOperands(Loc, lex, rex);
3518  if (vType.isNull())
3519    return vType;
3520
3521  QualType lType = lex->getType();
3522  QualType rType = rex->getType();
3523
3524  // For non-floating point types, check for self-comparisons of the form
3525  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
3526  // often indicate logic errors in the program.
3527  if (!lType->isFloatingType()) {
3528    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3529      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3530        if (DRL->getDecl() == DRR->getDecl())
3531          Diag(Loc, diag::warn_selfcomparison);
3532  }
3533
3534  // Check for comparisons of floating point operands using != and ==.
3535  if (!isRelational && lType->isFloatingType()) {
3536    assert (rType->isFloatingType());
3537    CheckFloatComparison(Loc,lex,rex);
3538  }
3539
3540  // Return the type for the comparison, which is the same as vector type for
3541  // integer vectors, or an integer type of identical size and number of
3542  // elements for floating point vectors.
3543  if (lType->isIntegerType())
3544    return lType;
3545
3546  const VectorType *VTy = lType->getAsVectorType();
3547  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
3548  if (TypeSize == Context.getTypeSize(Context.IntTy))
3549    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
3550  else if (TypeSize == Context.getTypeSize(Context.LongTy))
3551    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3552
3553  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3554         "Unhandled vector element size in vector compare");
3555  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3556}
3557
3558inline QualType Sema::CheckBitwiseOperands(
3559  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3560{
3561  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3562    return CheckVectorOperands(Loc, lex, rex);
3563
3564  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3565
3566  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3567    return compType;
3568  return InvalidOperands(Loc, lex, rex);
3569}
3570
3571inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
3572  Expr *&lex, Expr *&rex, SourceLocation Loc)
3573{
3574  UsualUnaryConversions(lex);
3575  UsualUnaryConversions(rex);
3576
3577  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
3578    return Context.IntTy;
3579  return InvalidOperands(Loc, lex, rex);
3580}
3581
3582/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3583/// is a read-only property; return true if so. A readonly property expression
3584/// depends on various declarations and thus must be treated specially.
3585///
3586static bool IsReadonlyProperty(Expr *E, Sema &S)
3587{
3588  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3589    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3590    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3591      QualType BaseType = PropExpr->getBase()->getType();
3592      if (const PointerType *PTy = BaseType->getAsPointerType())
3593        if (const ObjCInterfaceType *IFTy =
3594            PTy->getPointeeType()->getAsObjCInterfaceType())
3595          if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3596            if (S.isPropertyReadonly(PDecl, IFace))
3597              return true;
3598    }
3599  }
3600  return false;
3601}
3602
3603/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
3604/// emit an error and return true.  If so, return false.
3605static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
3606  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3607  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3608    IsLV = Expr::MLV_ReadonlyProperty;
3609  if (IsLV == Expr::MLV_Valid)
3610    return false;
3611
3612  unsigned Diag = 0;
3613  bool NeedType = false;
3614  switch (IsLV) { // C99 6.5.16p2
3615  default: assert(0 && "Unknown result from isModifiableLvalue!");
3616  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
3617  case Expr::MLV_ArrayType:
3618    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3619    NeedType = true;
3620    break;
3621  case Expr::MLV_NotObjectType:
3622    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3623    NeedType = true;
3624    break;
3625  case Expr::MLV_LValueCast:
3626    Diag = diag::err_typecheck_lvalue_casts_not_supported;
3627    break;
3628  case Expr::MLV_InvalidExpression:
3629    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3630    break;
3631  case Expr::MLV_IncompleteType:
3632  case Expr::MLV_IncompleteVoidType:
3633    return S.RequireCompleteType(Loc, E->getType(),
3634                      diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3635                                    E->getSourceRange());
3636  case Expr::MLV_DuplicateVectorComponents:
3637    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3638    break;
3639  case Expr::MLV_NotBlockQualified:
3640    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3641    break;
3642  case Expr::MLV_ReadonlyProperty:
3643    Diag = diag::error_readonly_property_assignment;
3644    break;
3645  case Expr::MLV_NoSetterProperty:
3646    Diag = diag::error_nosetter_property_assignment;
3647    break;
3648  }
3649
3650  if (NeedType)
3651    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
3652  else
3653    S.Diag(Loc, Diag) << E->getSourceRange();
3654  return true;
3655}
3656
3657
3658
3659// C99 6.5.16.1
3660QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3661                                       SourceLocation Loc,
3662                                       QualType CompoundType) {
3663  // Verify that LHS is a modifiable lvalue, and emit error if not.
3664  if (CheckForModifiableLvalue(LHS, Loc, *this))
3665    return QualType();
3666
3667  QualType LHSType = LHS->getType();
3668  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
3669
3670  AssignConvertType ConvTy;
3671  if (CompoundType.isNull()) {
3672    // Simple assignment "x = y".
3673    ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
3674    // Special case of NSObject attributes on c-style pointer types.
3675    if (ConvTy == IncompatiblePointer &&
3676        ((Context.isObjCNSObjectType(LHSType) &&
3677          Context.isObjCObjectPointerType(RHSType)) ||
3678         (Context.isObjCNSObjectType(RHSType) &&
3679          Context.isObjCObjectPointerType(LHSType))))
3680      ConvTy = Compatible;
3681
3682    // If the RHS is a unary plus or minus, check to see if they = and + are
3683    // right next to each other.  If so, the user may have typo'd "x =+ 4"
3684    // instead of "x += 4".
3685    Expr *RHSCheck = RHS;
3686    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3687      RHSCheck = ICE->getSubExpr();
3688    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3689      if ((UO->getOpcode() == UnaryOperator::Plus ||
3690           UO->getOpcode() == UnaryOperator::Minus) &&
3691          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
3692          // Only if the two operators are exactly adjacent.
3693          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3694          // And there is a space or other character before the subexpr of the
3695          // unary +/-.  We don't want to warn on "x=-1".
3696          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3697          UO->getSubExpr()->getLocStart().isFileID()) {
3698        Diag(Loc, diag::warn_not_compound_assign)
3699          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3700          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
3701      }
3702    }
3703  } else {
3704    // Compound assignment "x += y"
3705    ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
3706  }
3707
3708  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3709                               RHS, "assigning"))
3710    return QualType();
3711
3712  // C99 6.5.16p3: The type of an assignment expression is the type of the
3713  // left operand unless the left operand has qualified type, in which case
3714  // it is the unqualified version of the type of the left operand.
3715  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3716  // is converted to the type of the assignment expression (above).
3717  // C++ 5.17p1: the type of the assignment expression is that of its left
3718  // oprdu.
3719  return LHSType.getUnqualifiedType();
3720}
3721
3722// C99 6.5.17
3723QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3724  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
3725  DefaultFunctionArrayConversion(RHS);
3726
3727  // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
3728  // incomplete in C++).
3729
3730  return RHS->getType();
3731}
3732
3733/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3734/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
3735QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3736                                              bool isInc) {
3737  if (Op->isTypeDependent())
3738    return Context.DependentTy;
3739
3740  QualType ResType = Op->getType();
3741  assert(!ResType.isNull() && "no type for increment/decrement expression");
3742
3743  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3744    // Decrement of bool is not allowed.
3745    if (!isInc) {
3746      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3747      return QualType();
3748    }
3749    // Increment of bool sets it to true, but is deprecated.
3750    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3751  } else if (ResType->isRealType()) {
3752    // OK!
3753  } else if (const PointerType *PT = ResType->getAsPointerType()) {
3754    // C99 6.5.2.4p2, 6.5.6p2
3755    if (PT->getPointeeType()->isVoidType()) {
3756      if (getLangOptions().CPlusPlus) {
3757        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3758          << Op->getSourceRange();
3759        return QualType();
3760      }
3761
3762      // Pointer to void is a GNU extension in C.
3763      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3764    } else if (PT->getPointeeType()->isFunctionType()) {
3765      if (getLangOptions().CPlusPlus) {
3766        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3767          << Op->getType() << Op->getSourceRange();
3768        return QualType();
3769      }
3770
3771      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
3772        << ResType << Op->getSourceRange();
3773    } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
3774                               diag::err_typecheck_arithmetic_incomplete_type,
3775                                   Op->getSourceRange(), SourceRange(),
3776                                   ResType))
3777      return QualType();
3778  } else if (ResType->isComplexType()) {
3779    // C99 does not support ++/-- on complex types, we allow as an extension.
3780    Diag(OpLoc, diag::ext_integer_increment_complex)
3781      << ResType << Op->getSourceRange();
3782  } else {
3783    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
3784      << ResType << Op->getSourceRange();
3785    return QualType();
3786  }
3787  // At this point, we know we have a real, complex or pointer type.
3788  // Now make sure the operand is a modifiable lvalue.
3789  if (CheckForModifiableLvalue(Op, OpLoc, *this))
3790    return QualType();
3791  return ResType;
3792}
3793
3794/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
3795/// This routine allows us to typecheck complex/recursive expressions
3796/// where the declaration is needed for type checking. We only need to
3797/// handle cases when the expression references a function designator
3798/// or is an lvalue. Here are some examples:
3799///  - &(x) => x
3800///  - &*****f => f for f a function designator.
3801///  - &s.xx => s
3802///  - &s.zz[1].yy -> s, if zz is an array
3803///  - *(x + 1) -> x, if x is an array
3804///  - &"123"[2] -> 0
3805///  - & __real__ x -> x
3806static NamedDecl *getPrimaryDecl(Expr *E) {
3807  switch (E->getStmtClass()) {
3808  case Stmt::DeclRefExprClass:
3809  case Stmt::QualifiedDeclRefExprClass:
3810    return cast<DeclRefExpr>(E)->getDecl();
3811  case Stmt::MemberExprClass:
3812    // Fields cannot be declared with a 'register' storage class.
3813    // &X->f is always ok, even if X is declared register.
3814    if (cast<MemberExpr>(E)->isArrow())
3815      return 0;
3816    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
3817  case Stmt::ArraySubscriptExprClass: {
3818    // &X[4] and &4[X] refers to X if X is not a pointer.
3819
3820    NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
3821    ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
3822    if (!VD || VD->getType()->isPointerType())
3823      return 0;
3824    else
3825      return VD;
3826  }
3827  case Stmt::UnaryOperatorClass: {
3828    UnaryOperator *UO = cast<UnaryOperator>(E);
3829
3830    switch(UO->getOpcode()) {
3831    case UnaryOperator::Deref: {
3832      // *(X + 1) refers to X if X is not a pointer.
3833      if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3834        ValueDecl *VD = dyn_cast<ValueDecl>(D);
3835        if (!VD || VD->getType()->isPointerType())
3836          return 0;
3837        return VD;
3838      }
3839      return 0;
3840    }
3841    case UnaryOperator::Real:
3842    case UnaryOperator::Imag:
3843    case UnaryOperator::Extension:
3844      return getPrimaryDecl(UO->getSubExpr());
3845    default:
3846      return 0;
3847    }
3848  }
3849  case Stmt::BinaryOperatorClass: {
3850    BinaryOperator *BO = cast<BinaryOperator>(E);
3851
3852    // Handle cases involving pointer arithmetic. The result of an
3853    // Assign or AddAssign is not an lvalue so they can be ignored.
3854
3855    // (x + n) or (n + x) => x
3856    if (BO->getOpcode() == BinaryOperator::Add) {
3857      if (BO->getLHS()->getType()->isPointerType()) {
3858        return getPrimaryDecl(BO->getLHS());
3859      } else if (BO->getRHS()->getType()->isPointerType()) {
3860        return getPrimaryDecl(BO->getRHS());
3861      }
3862    }
3863
3864    return 0;
3865  }
3866  case Stmt::ParenExprClass:
3867    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
3868  case Stmt::ImplicitCastExprClass:
3869    // &X[4] when X is an array, has an implicit cast from array to pointer.
3870    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
3871  default:
3872    return 0;
3873  }
3874}
3875
3876/// CheckAddressOfOperand - The operand of & must be either a function
3877/// designator or an lvalue designating an object. If it is an lvalue, the
3878/// object cannot be declared with storage class register or be a bit field.
3879/// Note: The usual conversions are *not* applied to the operand of the &
3880/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
3881/// In C++, the operand might be an overloaded function name, in which case
3882/// we allow the '&' but retain the overloaded-function type.
3883QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
3884  if (op->isTypeDependent())
3885    return Context.DependentTy;
3886
3887  if (getLangOptions().C99) {
3888    // Implement C99-only parts of addressof rules.
3889    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3890      if (uOp->getOpcode() == UnaryOperator::Deref)
3891        // Per C99 6.5.3.2, the address of a deref always returns a valid result
3892        // (assuming the deref expression is valid).
3893        return uOp->getSubExpr()->getType();
3894    }
3895    // Technically, there should be a check for array subscript
3896    // expressions here, but the result of one is always an lvalue anyway.
3897  }
3898  NamedDecl *dcl = getPrimaryDecl(op);
3899  Expr::isLvalueResult lval = op->isLvalue(Context);
3900
3901  if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
3902    if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3903      // FIXME: emit more specific diag...
3904      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3905        << op->getSourceRange();
3906      return QualType();
3907    }
3908  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
3909    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3910      if (Field->isBitField()) {
3911        Diag(OpLoc, diag::err_typecheck_address_of)
3912          << "bit-field" << op->getSourceRange();
3913        return QualType();
3914      }
3915    }
3916  // Check for Apple extension for accessing vector components.
3917  } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3918           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
3919    Diag(OpLoc, diag::err_typecheck_address_of)
3920      << "vector element" << op->getSourceRange();
3921    return QualType();
3922  } else if (dcl) { // C99 6.5.3.2p1
3923    // We have an lvalue with a decl. Make sure the decl is not declared
3924    // with the register storage-class specifier.
3925    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3926      if (vd->getStorageClass() == VarDecl::Register) {
3927        Diag(OpLoc, diag::err_typecheck_address_of)
3928          << "register variable" << op->getSourceRange();
3929        return QualType();
3930      }
3931    } else if (isa<OverloadedFunctionDecl>(dcl)) {
3932      return Context.OverloadTy;
3933    } else if (isa<FieldDecl>(dcl)) {
3934      // Okay: we can take the address of a field.
3935      // Could be a pointer to member, though, if there is an explicit
3936      // scope qualifier for the class.
3937      if (isa<QualifiedDeclRefExpr>(op)) {
3938        DeclContext *Ctx = dcl->getDeclContext();
3939        if (Ctx && Ctx->isRecord())
3940          return Context.getMemberPointerType(op->getType(),
3941                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3942      }
3943    } else if (isa<FunctionDecl>(dcl)) {
3944      // Okay: we can take the address of a function.
3945      // As above.
3946      if (isa<QualifiedDeclRefExpr>(op)) {
3947        DeclContext *Ctx = dcl->getDeclContext();
3948        if (Ctx && Ctx->isRecord())
3949          return Context.getMemberPointerType(op->getType(),
3950                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3951      }
3952    }
3953    else
3954      assert(0 && "Unknown/unexpected decl type");
3955  }
3956
3957  // If the operand has type "type", the result has type "pointer to type".
3958  return Context.getPointerType(op->getType());
3959}
3960
3961QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3962  if (Op->isTypeDependent())
3963    return Context.DependentTy;
3964
3965  UsualUnaryConversions(Op);
3966  QualType Ty = Op->getType();
3967
3968  // Note that per both C89 and C99, this is always legal, even if ptype is an
3969  // incomplete type or void.  It would be possible to warn about dereferencing
3970  // a void pointer, but it's completely well-defined, and such a warning is
3971  // unlikely to catch any mistakes.
3972  if (const PointerType *PT = Ty->getAsPointerType())
3973    return PT->getPointeeType();
3974
3975  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
3976    << Ty << Op->getSourceRange();
3977  return QualType();
3978}
3979
3980static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3981  tok::TokenKind Kind) {
3982  BinaryOperator::Opcode Opc;
3983  switch (Kind) {
3984  default: assert(0 && "Unknown binop!");
3985  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
3986  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
3987  case tok::star:                 Opc = BinaryOperator::Mul; break;
3988  case tok::slash:                Opc = BinaryOperator::Div; break;
3989  case tok::percent:              Opc = BinaryOperator::Rem; break;
3990  case tok::plus:                 Opc = BinaryOperator::Add; break;
3991  case tok::minus:                Opc = BinaryOperator::Sub; break;
3992  case tok::lessless:             Opc = BinaryOperator::Shl; break;
3993  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
3994  case tok::lessequal:            Opc = BinaryOperator::LE; break;
3995  case tok::less:                 Opc = BinaryOperator::LT; break;
3996  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
3997  case tok::greater:              Opc = BinaryOperator::GT; break;
3998  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
3999  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
4000  case tok::amp:                  Opc = BinaryOperator::And; break;
4001  case tok::caret:                Opc = BinaryOperator::Xor; break;
4002  case tok::pipe:                 Opc = BinaryOperator::Or; break;
4003  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
4004  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
4005  case tok::equal:                Opc = BinaryOperator::Assign; break;
4006  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
4007  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
4008  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
4009  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
4010  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
4011  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
4012  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
4013  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
4014  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
4015  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
4016  case tok::comma:                Opc = BinaryOperator::Comma; break;
4017  }
4018  return Opc;
4019}
4020
4021static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4022  tok::TokenKind Kind) {
4023  UnaryOperator::Opcode Opc;
4024  switch (Kind) {
4025  default: assert(0 && "Unknown unary op!");
4026  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
4027  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
4028  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
4029  case tok::star:         Opc = UnaryOperator::Deref; break;
4030  case tok::plus:         Opc = UnaryOperator::Plus; break;
4031  case tok::minus:        Opc = UnaryOperator::Minus; break;
4032  case tok::tilde:        Opc = UnaryOperator::Not; break;
4033  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
4034  case tok::kw___real:    Opc = UnaryOperator::Real; break;
4035  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
4036  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4037  }
4038  return Opc;
4039}
4040
4041/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4042/// operator @p Opc at location @c TokLoc. This routine only supports
4043/// built-in operations; ActOnBinOp handles overloaded operators.
4044Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4045                                                  unsigned Op,
4046                                                  Expr *lhs, Expr *rhs) {
4047  QualType ResultTy;  // Result type of the binary operator.
4048  QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
4049  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
4050
4051  switch (Opc) {
4052  case BinaryOperator::Assign:
4053    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4054    break;
4055  case BinaryOperator::PtrMemD:
4056  case BinaryOperator::PtrMemI:
4057    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4058                                            Opc == BinaryOperator::PtrMemI);
4059    break;
4060  case BinaryOperator::Mul:
4061  case BinaryOperator::Div:
4062    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4063    break;
4064  case BinaryOperator::Rem:
4065    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4066    break;
4067  case BinaryOperator::Add:
4068    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4069    break;
4070  case BinaryOperator::Sub:
4071    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4072    break;
4073  case BinaryOperator::Shl:
4074  case BinaryOperator::Shr:
4075    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4076    break;
4077  case BinaryOperator::LE:
4078  case BinaryOperator::LT:
4079  case BinaryOperator::GE:
4080  case BinaryOperator::GT:
4081    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
4082    break;
4083  case BinaryOperator::EQ:
4084  case BinaryOperator::NE:
4085    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
4086    break;
4087  case BinaryOperator::And:
4088  case BinaryOperator::Xor:
4089  case BinaryOperator::Or:
4090    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4091    break;
4092  case BinaryOperator::LAnd:
4093  case BinaryOperator::LOr:
4094    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4095    break;
4096  case BinaryOperator::MulAssign:
4097  case BinaryOperator::DivAssign:
4098    CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4099    if (!CompTy.isNull())
4100      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4101    break;
4102  case BinaryOperator::RemAssign:
4103    CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4104    if (!CompTy.isNull())
4105      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4106    break;
4107  case BinaryOperator::AddAssign:
4108    CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
4109    if (!CompTy.isNull())
4110      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4111    break;
4112  case BinaryOperator::SubAssign:
4113    CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
4114    if (!CompTy.isNull())
4115      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4116    break;
4117  case BinaryOperator::ShlAssign:
4118  case BinaryOperator::ShrAssign:
4119    CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4120    if (!CompTy.isNull())
4121      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4122    break;
4123  case BinaryOperator::AndAssign:
4124  case BinaryOperator::XorAssign:
4125  case BinaryOperator::OrAssign:
4126    CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4127    if (!CompTy.isNull())
4128      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4129    break;
4130  case BinaryOperator::Comma:
4131    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4132    break;
4133  }
4134  if (ResultTy.isNull())
4135    return ExprError();
4136  if (CompTy.isNull())
4137    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4138  else
4139    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
4140                                                      CompTy, OpLoc));
4141}
4142
4143// Binary Operators.  'Tok' is the token for the operator.
4144Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4145                                          tok::TokenKind Kind,
4146                                          ExprArg LHS, ExprArg RHS) {
4147  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
4148  Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
4149
4150  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4151  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
4152
4153  if (getLangOptions().CPlusPlus &&
4154      (lhs->getType()->isOverloadableType() ||
4155       rhs->getType()->isOverloadableType())) {
4156    // Find all of the overloaded operators visible from this
4157    // point. We perform both an operator-name lookup from the local
4158    // scope and an argument-dependent lookup based on the types of
4159    // the arguments.
4160    FunctionSet Functions;
4161    OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4162    if (OverOp != OO_None) {
4163      LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4164                                   Functions);
4165      Expr *Args[2] = { lhs, rhs };
4166      DeclarationName OpName
4167        = Context.DeclarationNames.getCXXOperatorName(OverOp);
4168      ArgumentDependentLookup(OpName, Args, 2, Functions);
4169    }
4170
4171    // Build the (potentially-overloaded, potentially-dependent)
4172    // binary operation.
4173    return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
4174  }
4175
4176  // Build a built-in binary operation.
4177  return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
4178}
4179
4180Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4181                                                    unsigned OpcIn,
4182                                                    ExprArg InputArg) {
4183  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4184
4185  // FIXME: Input is modified below, but InputArg is not updated
4186  // appropriately.
4187  Expr *Input = (Expr *)InputArg.get();
4188  QualType resultType;
4189  switch (Opc) {
4190  case UnaryOperator::PostInc:
4191  case UnaryOperator::PostDec:
4192  case UnaryOperator::OffsetOf:
4193    assert(false && "Invalid unary operator");
4194    break;
4195
4196  case UnaryOperator::PreInc:
4197  case UnaryOperator::PreDec:
4198    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4199                                                Opc == UnaryOperator::PreInc);
4200    break;
4201  case UnaryOperator::AddrOf:
4202    resultType = CheckAddressOfOperand(Input, OpLoc);
4203    break;
4204  case UnaryOperator::Deref:
4205    DefaultFunctionArrayConversion(Input);
4206    resultType = CheckIndirectionOperand(Input, OpLoc);
4207    break;
4208  case UnaryOperator::Plus:
4209  case UnaryOperator::Minus:
4210    UsualUnaryConversions(Input);
4211    resultType = Input->getType();
4212    if (resultType->isDependentType())
4213      break;
4214    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4215      break;
4216    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4217             resultType->isEnumeralType())
4218      break;
4219    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4220             Opc == UnaryOperator::Plus &&
4221             resultType->isPointerType())
4222      break;
4223
4224    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4225      << resultType << Input->getSourceRange());
4226  case UnaryOperator::Not: // bitwise complement
4227    UsualUnaryConversions(Input);
4228    resultType = Input->getType();
4229    if (resultType->isDependentType())
4230      break;
4231    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4232    if (resultType->isComplexType() || resultType->isComplexIntegerType())
4233      // C99 does not support '~' for complex conjugation.
4234      Diag(OpLoc, diag::ext_integer_complement_complex)
4235        << resultType << Input->getSourceRange();
4236    else if (!resultType->isIntegerType())
4237      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4238        << resultType << Input->getSourceRange());
4239    break;
4240  case UnaryOperator::LNot: // logical negation
4241    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4242    DefaultFunctionArrayConversion(Input);
4243    resultType = Input->getType();
4244    if (resultType->isDependentType())
4245      break;
4246    if (!resultType->isScalarType()) // C99 6.5.3.3p1
4247      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4248        << resultType << Input->getSourceRange());
4249    // LNot always has type int. C99 6.5.3.3p5.
4250    // In C++, it's bool. C++ 5.3.1p8
4251    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
4252    break;
4253  case UnaryOperator::Real:
4254  case UnaryOperator::Imag:
4255    resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
4256    break;
4257  case UnaryOperator::Extension:
4258    resultType = Input->getType();
4259    break;
4260  }
4261  if (resultType.isNull())
4262    return ExprError();
4263
4264  InputArg.release();
4265  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
4266}
4267
4268// Unary Operators.  'Tok' is the token for the operator.
4269Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4270                                            tok::TokenKind Op, ExprArg input) {
4271  Expr *Input = (Expr*)input.get();
4272  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4273
4274  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4275    // Find all of the overloaded operators visible from this
4276    // point. We perform both an operator-name lookup from the local
4277    // scope and an argument-dependent lookup based on the types of
4278    // the arguments.
4279    FunctionSet Functions;
4280    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4281    if (OverOp != OO_None) {
4282      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4283                                   Functions);
4284      DeclarationName OpName
4285        = Context.DeclarationNames.getCXXOperatorName(OverOp);
4286      ArgumentDependentLookup(OpName, &Input, 1, Functions);
4287    }
4288
4289    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4290  }
4291
4292  return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4293}
4294
4295/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4296Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4297                                            SourceLocation LabLoc,
4298                                            IdentifierInfo *LabelII) {
4299  // Look up the record for this label identifier.
4300  LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
4301                                     LabelMap[LabelII];
4302
4303  // If we haven't seen this label yet, create a forward reference. It
4304  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
4305  if (LabelDecl == 0)
4306    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
4307
4308  // Create the AST node.  The address of a label always has type 'void*'.
4309  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4310                                       Context.getPointerType(Context.VoidTy)));
4311}
4312
4313Sema::OwningExprResult
4314Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4315                    SourceLocation RPLoc) { // "({..})"
4316  Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
4317  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4318  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4319
4320  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4321  if (isFileScope) {
4322    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
4323  }
4324
4325  // FIXME: there are a variety of strange constraints to enforce here, for
4326  // example, it is not possible to goto into a stmt expression apparently.
4327  // More semantic analysis is needed.
4328
4329  // FIXME: the last statement in the compount stmt has its value used.  We
4330  // should not warn about it being unused.
4331
4332  // If there are sub stmts in the compound stmt, take the type of the last one
4333  // as the type of the stmtexpr.
4334  QualType Ty = Context.VoidTy;
4335
4336  if (!Compound->body_empty()) {
4337    Stmt *LastStmt = Compound->body_back();
4338    // If LastStmt is a label, skip down through into the body.
4339    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4340      LastStmt = Label->getSubStmt();
4341
4342    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
4343      Ty = LastExpr->getType();
4344  }
4345
4346  // FIXME: Check that expression type is complete/non-abstract; statement
4347  // expressions are not lvalues.
4348
4349  substmt.release();
4350  return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
4351}
4352
4353Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4354                                                  SourceLocation BuiltinLoc,
4355                                                  SourceLocation TypeLoc,
4356                                                  TypeTy *argty,
4357                                                  OffsetOfComponent *CompPtr,
4358                                                  unsigned NumComponents,
4359                                                  SourceLocation RPLoc) {
4360  // FIXME: This function leaks all expressions in the offset components on
4361  // error.
4362  QualType ArgTy = QualType::getFromOpaquePtr(argty);
4363  assert(!ArgTy.isNull() && "Missing type argument!");
4364
4365  bool Dependent = ArgTy->isDependentType();
4366
4367  // We must have at least one component that refers to the type, and the first
4368  // one is known to be a field designator.  Verify that the ArgTy represents
4369  // a struct/union/class.
4370  if (!Dependent && !ArgTy->isRecordType())
4371    return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
4372
4373  // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4374  // with an incomplete type would be illegal.
4375
4376  // Otherwise, create a null pointer as the base, and iteratively process
4377  // the offsetof designators.
4378  QualType ArgTyPtr = Context.getPointerType(ArgTy);
4379  Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
4380  Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
4381                                    ArgTy, SourceLocation());
4382
4383  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4384  // GCC extension, diagnose them.
4385  // FIXME: This diagnostic isn't actually visible because the location is in
4386  // a system header!
4387  if (NumComponents != 1)
4388    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4389      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
4390
4391  if (!Dependent) {
4392    // FIXME: Dependent case loses a lot of information here. And probably
4393    // leaks like a sieve.
4394    for (unsigned i = 0; i != NumComponents; ++i) {
4395      const OffsetOfComponent &OC = CompPtr[i];
4396      if (OC.isBrackets) {
4397        // Offset of an array sub-field.  TODO: Should we allow vector elements?
4398        const ArrayType *AT = Context.getAsArrayType(Res->getType());
4399        if (!AT) {
4400          Res->Destroy(Context);
4401          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4402            << Res->getType());
4403        }
4404
4405        // FIXME: C++: Verify that operator[] isn't overloaded.
4406
4407        // Promote the array so it looks more like a normal array subscript
4408        // expression.
4409        DefaultFunctionArrayConversion(Res);
4410
4411        // C99 6.5.2.1p1
4412        Expr *Idx = static_cast<Expr*>(OC.U.E);
4413        // FIXME: Leaks Res
4414        if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
4415          return ExprError(Diag(Idx->getLocStart(),
4416                                diag::err_typecheck_subscript)
4417            << Idx->getSourceRange());
4418
4419        Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4420                                               OC.LocEnd);
4421        continue;
4422      }
4423
4424      const RecordType *RC = Res->getType()->getAsRecordType();
4425      if (!RC) {
4426        Res->Destroy(Context);
4427        return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4428          << Res->getType());
4429      }
4430
4431      // Get the decl corresponding to this.
4432      RecordDecl *RD = RC->getDecl();
4433      FieldDecl *MemberDecl
4434        = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4435                                                          LookupMemberName)
4436                                        .getAsDecl());
4437      // FIXME: Leaks Res
4438      if (!MemberDecl)
4439        return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4440         << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
4441
4442      // FIXME: C++: Verify that MemberDecl isn't a static field.
4443      // FIXME: Verify that MemberDecl isn't a bitfield.
4444      // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4445      // matter here.
4446      Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4447                                   MemberDecl->getType().getNonReferenceType());
4448    }
4449  }
4450
4451  return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4452                                           Context.getSizeType(), BuiltinLoc));
4453}
4454
4455
4456Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4457                                                      TypeTy *arg1,TypeTy *arg2,
4458                                                      SourceLocation RPLoc) {
4459  QualType argT1 = QualType::getFromOpaquePtr(arg1);
4460  QualType argT2 = QualType::getFromOpaquePtr(arg2);
4461
4462  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4463
4464  return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4465                                                 argT1, argT2, RPLoc));
4466}
4467
4468Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4469                                             ExprArg cond,
4470                                             ExprArg expr1, ExprArg expr2,
4471                                             SourceLocation RPLoc) {
4472  Expr *CondExpr = static_cast<Expr*>(cond.get());
4473  Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4474  Expr *RHSExpr = static_cast<Expr*>(expr2.get());
4475
4476  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4477
4478  QualType resType;
4479  if (CondExpr->isValueDependent()) {
4480    resType = Context.DependentTy;
4481  } else {
4482    // The conditional expression is required to be a constant expression.
4483    llvm::APSInt condEval(32);
4484    SourceLocation ExpLoc;
4485    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4486      return ExprError(Diag(ExpLoc,
4487                       diag::err_typecheck_choose_expr_requires_constant)
4488        << CondExpr->getSourceRange());
4489
4490    // If the condition is > zero, then the AST type is the same as the LSHExpr.
4491    resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4492  }
4493
4494  cond.release(); expr1.release(); expr2.release();
4495  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4496                                        resType, RPLoc));
4497}
4498
4499//===----------------------------------------------------------------------===//
4500// Clang Extensions.
4501//===----------------------------------------------------------------------===//
4502
4503/// ActOnBlockStart - This callback is invoked when a block literal is started.
4504void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
4505  // Analyze block parameters.
4506  BlockSemaInfo *BSI = new BlockSemaInfo();
4507
4508  // Add BSI to CurBlock.
4509  BSI->PrevBlockInfo = CurBlock;
4510  CurBlock = BSI;
4511
4512  BSI->ReturnType = 0;
4513  BSI->TheScope = BlockScope;
4514  BSI->hasBlockDeclRefExprs = false;
4515
4516  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
4517  PushDeclContext(BlockScope, BSI->TheDecl);
4518}
4519
4520void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4521  assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4522
4523  if (ParamInfo.getNumTypeObjects() == 0
4524      || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4525    QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4526
4527    // The type is entirely optional as well, if none, use DependentTy.
4528    if (T.isNull())
4529      T = Context.DependentTy;
4530
4531    // The parameter list is optional, if there was none, assume ().
4532    if (!T->isFunctionType())
4533      T = Context.getFunctionType(T, NULL, 0, 0, 0);
4534
4535    CurBlock->hasPrototype = true;
4536    CurBlock->isVariadic = false;
4537    Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4538      .getTypePtr();
4539
4540    if (!RetTy->isDependentType())
4541      CurBlock->ReturnType = RetTy;
4542    return;
4543  }
4544
4545  // Analyze arguments to block.
4546  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4547         "Not a function declarator!");
4548  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4549
4550  CurBlock->hasPrototype = FTI.hasPrototype;
4551  CurBlock->isVariadic = true;
4552
4553  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4554  // no arguments, not a function that takes a single void argument.
4555  if (FTI.hasPrototype &&
4556      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4557      (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4558        ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4559    // empty arg list, don't push any params.
4560    CurBlock->isVariadic = false;
4561  } else if (FTI.hasPrototype) {
4562    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
4563      CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4564    CurBlock->isVariadic = FTI.isVariadic;
4565    QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4566
4567    Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4568      .getTypePtr();
4569
4570    if (!RetTy->isDependentType())
4571      CurBlock->ReturnType = RetTy;
4572  }
4573  CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
4574                                        CurBlock->Params.size());
4575
4576  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4577       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4578    // If this has an identifier, add it to the scope stack.
4579    if ((*AI)->getIdentifier())
4580      PushOnScopeChains(*AI, CurBlock->TheScope);
4581}
4582
4583/// ActOnBlockError - If there is an error parsing a block, this callback
4584/// is invoked to pop the information about the block from the action impl.
4585void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4586  // Ensure that CurBlock is deleted.
4587  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4588
4589  // Pop off CurBlock, handle nested blocks.
4590  CurBlock = CurBlock->PrevBlockInfo;
4591
4592  // FIXME: Delete the ParmVarDecl objects as well???
4593
4594}
4595
4596/// ActOnBlockStmtExpr - This is called when the body of a block statement
4597/// literal was successfully completed.  ^(int x){...}
4598Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4599                                                StmtArg body, Scope *CurScope) {
4600  // Ensure that CurBlock is deleted.
4601  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4602
4603  PopDeclContext();
4604
4605  // Pop off CurBlock, handle nested blocks.
4606  CurBlock = CurBlock->PrevBlockInfo;
4607
4608  QualType RetTy = Context.VoidTy;
4609  if (BSI->ReturnType)
4610    RetTy = QualType(BSI->ReturnType, 0);
4611
4612  llvm::SmallVector<QualType, 8> ArgTypes;
4613  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4614    ArgTypes.push_back(BSI->Params[i]->getType());
4615
4616  QualType BlockTy;
4617  if (!BSI->hasPrototype)
4618    BlockTy = Context.getFunctionNoProtoType(RetTy);
4619  else
4620    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
4621                                      BSI->isVariadic, 0);
4622
4623  // FIXME: Check that return/parameter types are complete/non-abstract
4624
4625  BlockTy = Context.getBlockPointerType(BlockTy);
4626
4627  BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release()));
4628  return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4629                                       BSI->hasBlockDeclRefExprs));
4630}
4631
4632Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4633                                        ExprArg expr, TypeTy *type,
4634                                        SourceLocation RPLoc) {
4635  QualType T = QualType::getFromOpaquePtr(type);
4636
4637  InitBuiltinVaListType();
4638
4639  // Get the va_list type
4640  QualType VaListType = Context.getBuiltinVaListType();
4641  // Deal with implicit array decay; for example, on x86-64,
4642  // va_list is an array, but it's supposed to decay to
4643  // a pointer for va_arg.
4644  if (VaListType->isArrayType())
4645    VaListType = Context.getArrayDecayedType(VaListType);
4646  // Make sure the input expression also decays appropriately.
4647  Expr *E = static_cast<Expr*>(expr.get());
4648  UsualUnaryConversions(E);
4649
4650  if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
4651    return ExprError(Diag(E->getLocStart(),
4652                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
4653      << E->getType() << E->getSourceRange());
4654
4655  // FIXME: Check that type is complete/non-abstract
4656  // FIXME: Warn if a non-POD type is passed in.
4657
4658  expr.release();
4659  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
4660                                       RPLoc));
4661}
4662
4663Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4664  // The type of __null will be int or long, depending on the size of
4665  // pointers on the target.
4666  QualType Ty;
4667  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4668    Ty = Context.IntTy;
4669  else
4670    Ty = Context.LongTy;
4671
4672  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
4673}
4674
4675bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4676                                    SourceLocation Loc,
4677                                    QualType DstType, QualType SrcType,
4678                                    Expr *SrcExpr, const char *Flavor) {
4679  // Decode the result (notice that AST's are still created for extensions).
4680  bool isInvalid = false;
4681  unsigned DiagKind;
4682  switch (ConvTy) {
4683  default: assert(0 && "Unknown conversion type");
4684  case Compatible: return false;
4685  case PointerToInt:
4686    DiagKind = diag::ext_typecheck_convert_pointer_int;
4687    break;
4688  case IntToPointer:
4689    DiagKind = diag::ext_typecheck_convert_int_pointer;
4690    break;
4691  case IncompatiblePointer:
4692    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4693    break;
4694  case IncompatiblePointerSign:
4695    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
4696    break;
4697  case FunctionVoidPointer:
4698    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4699    break;
4700  case CompatiblePointerDiscardsQualifiers:
4701    // If the qualifiers lost were because we were applying the
4702    // (deprecated) C++ conversion from a string literal to a char*
4703    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
4704    // Ideally, this check would be performed in
4705    // CheckPointerTypesForAssignment. However, that would require a
4706    // bit of refactoring (so that the second argument is an
4707    // expression, rather than a type), which should be done as part
4708    // of a larger effort to fix CheckPointerTypesForAssignment for
4709    // C++ semantics.
4710    if (getLangOptions().CPlusPlus &&
4711        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4712      return false;
4713    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4714    break;
4715  case IntToBlockPointer:
4716    DiagKind = diag::err_int_to_block_pointer;
4717    break;
4718  case IncompatibleBlockPointer:
4719    DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
4720    break;
4721  case IncompatibleObjCQualifiedId:
4722    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4723    // it can give a more specific diagnostic.
4724    DiagKind = diag::warn_incompatible_qualified_id;
4725    break;
4726  case IncompatibleVectors:
4727    DiagKind = diag::warn_incompatible_vectors;
4728    break;
4729  case Incompatible:
4730    DiagKind = diag::err_typecheck_convert_incompatible;
4731    isInvalid = true;
4732    break;
4733  }
4734
4735  Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4736    << SrcExpr->getSourceRange();
4737  return isInvalid;
4738}
4739
4740bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4741{
4742  Expr::EvalResult EvalResult;
4743
4744  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4745      EvalResult.HasSideEffects) {
4746    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4747
4748    if (EvalResult.Diag) {
4749      // We only show the note if it's not the usual "invalid subexpression"
4750      // or if it's actually in a subexpression.
4751      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4752          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4753        Diag(EvalResult.DiagLoc, EvalResult.Diag);
4754    }
4755
4756    return true;
4757  }
4758
4759  if (EvalResult.Diag) {
4760    Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4761      E->getSourceRange();
4762
4763    // Print the reason it's not a constant.
4764    if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4765      Diag(EvalResult.DiagLoc, EvalResult.Diag);
4766  }
4767
4768  if (Result)
4769    *Result = EvalResult.Val.getInt();
4770  return false;
4771}
4772