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