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