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