SemaExpr.cpp revision 751ec9be961888f14342fb63b39bf8727f0dee49
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 "clang/Sema/SemaInternal.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/RecursiveASTVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/ParsedTemplate.h"
39#include "clang/Sema/Template.h"
40using namespace clang;
41using namespace sema;
42
43
44/// \brief Determine whether the use of this declaration is valid, and
45/// emit any corresponding diagnostics.
46///
47/// This routine diagnoses various problems with referencing
48/// declarations that can occur when using a declaration. For example,
49/// it might warn if a deprecated or unavailable declaration is being
50/// used, or produce an error (and return true) if a C++0x deleted
51/// function is being used.
52///
53/// If IgnoreDeprecated is set to true, this should not warn about deprecated
54/// decls.
55///
56/// \returns true if there was an error (this declaration cannot be
57/// referenced), false otherwise.
58///
59bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
60                             const ObjCInterfaceDecl *UnknownObjCClass) {
61  if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
62    // If there were any diagnostics suppressed by template argument deduction,
63    // emit them now.
64    llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
65      Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
66    if (Pos != SuppressedDiagnostics.end()) {
67      llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
68      for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
69        Diag(Suppressed[I].first, Suppressed[I].second);
70
71      // Clear out the list of suppressed diagnostics, so that we don't emit
72      // them again for this specialization. However, we don't obsolete this
73      // entry from the table, because we want to avoid ever emitting these
74      // diagnostics again.
75      Suppressed.clear();
76    }
77  }
78
79  // See if this is an auto-typed variable whose initializer we are parsing.
80  if (ParsingInitForAutoVars.count(D)) {
81    Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
82      << D->getDeclName();
83    return true;
84  }
85
86  // See if this is a deleted function.
87  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
88    if (FD->isDeleted()) {
89      Diag(Loc, diag::err_deleted_function_use);
90      Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
91      return true;
92    }
93  }
94
95  // See if this declaration is unavailable or deprecated.
96  std::string Message;
97  switch (D->getAvailability(&Message)) {
98  case AR_Available:
99  case AR_NotYetIntroduced:
100    break;
101
102  case AR_Deprecated:
103    EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
104    break;
105
106  case AR_Unavailable:
107    if (Message.empty()) {
108      if (!UnknownObjCClass)
109        Diag(Loc, diag::err_unavailable) << D->getDeclName();
110      else
111        Diag(Loc, diag::warn_unavailable_fwdclass_message)
112             << D->getDeclName();
113    }
114    else
115      Diag(Loc, diag::err_unavailable_message)
116        << D->getDeclName() << Message;
117    Diag(D->getLocation(), diag::note_unavailable_here)
118      << isa<FunctionDecl>(D) << false;
119    break;
120  }
121
122  // Warn if this is used but marked unused.
123  if (D->hasAttr<UnusedAttr>())
124    Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
125
126  return false;
127}
128
129/// \brief Retrieve the message suffix that should be added to a
130/// diagnostic complaining about the given function being deleted or
131/// unavailable.
132std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
133  // FIXME: C++0x implicitly-deleted special member functions could be
134  // detected here so that we could improve diagnostics to say, e.g.,
135  // "base class 'A' had a deleted copy constructor".
136  if (FD->isDeleted())
137    return std::string();
138
139  std::string Message;
140  if (FD->getAvailability(&Message))
141    return ": " + Message;
142
143  return std::string();
144}
145
146/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
147/// (and other functions in future), which have been declared with sentinel
148/// attribute. It warns if call does not have the sentinel argument.
149///
150void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
151                                 Expr **Args, unsigned NumArgs) {
152  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
153  if (!attr)
154    return;
155
156  // FIXME: In C++0x, if any of the arguments are parameter pack
157  // expansions, we can't check for the sentinel now.
158  int sentinelPos = attr->getSentinel();
159  int nullPos = attr->getNullPos();
160
161  // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
162  // base class. Then we won't be needing two versions of the same code.
163  unsigned int i = 0;
164  bool warnNotEnoughArgs = false;
165  int isMethod = 0;
166  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
167    // skip over named parameters.
168    ObjCMethodDecl::param_iterator P, E = MD->param_end();
169    for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
170      if (nullPos)
171        --nullPos;
172      else
173        ++i;
174    }
175    warnNotEnoughArgs = (P != E || i >= NumArgs);
176    isMethod = 1;
177  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
178    // skip over named parameters.
179    ObjCMethodDecl::param_iterator P, E = FD->param_end();
180    for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
181      if (nullPos)
182        --nullPos;
183      else
184        ++i;
185    }
186    warnNotEnoughArgs = (P != E || i >= NumArgs);
187  } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
188    // block or function pointer call.
189    QualType Ty = V->getType();
190    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
191      const FunctionType *FT = Ty->isFunctionPointerType()
192      ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
193      : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
194      if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
195        unsigned NumArgsInProto = Proto->getNumArgs();
196        unsigned k;
197        for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
198          if (nullPos)
199            --nullPos;
200          else
201            ++i;
202        }
203        warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
204      }
205      if (Ty->isBlockPointerType())
206        isMethod = 2;
207    } else
208      return;
209  } else
210    return;
211
212  if (warnNotEnoughArgs) {
213    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
214    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
215    return;
216  }
217  int sentinel = i;
218  while (sentinelPos > 0 && i < NumArgs-1) {
219    --sentinelPos;
220    ++i;
221  }
222  if (sentinelPos > 0) {
223    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
224    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
225    return;
226  }
227  while (i < NumArgs-1) {
228    ++i;
229    ++sentinel;
230  }
231  Expr *sentinelExpr = Args[sentinel];
232  if (!sentinelExpr) return;
233  if (sentinelExpr->isTypeDependent()) return;
234  if (sentinelExpr->isValueDependent()) return;
235
236  // nullptr_t is always treated as null.
237  if (sentinelExpr->getType()->isNullPtrType()) return;
238
239  if (sentinelExpr->getType()->isAnyPointerType() &&
240      sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
241                                            Expr::NPC_ValueDependentIsNull))
242    return;
243
244  // Unfortunately, __null has type 'int'.
245  if (isa<GNUNullExpr>(sentinelExpr)) return;
246
247  Diag(Loc, diag::warn_missing_sentinel) << isMethod;
248  Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
249}
250
251SourceRange Sema::getExprRange(ExprTy *E) const {
252  Expr *Ex = (Expr *)E;
253  return Ex? Ex->getSourceRange() : SourceRange();
254}
255
256//===----------------------------------------------------------------------===//
257//  Standard Promotions and Conversions
258//===----------------------------------------------------------------------===//
259
260/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
261ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
262  QualType Ty = E->getType();
263  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
264
265  if (Ty->isFunctionType())
266    E = ImpCastExprToType(E, Context.getPointerType(Ty),
267                          CK_FunctionToPointerDecay).take();
268  else if (Ty->isArrayType()) {
269    // In C90 mode, arrays only promote to pointers if the array expression is
270    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
271    // type 'array of type' is converted to an expression that has type 'pointer
272    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
273    // that has type 'array of type' ...".  The relevant change is "an lvalue"
274    // (C90) to "an expression" (C99).
275    //
276    // C++ 4.2p1:
277    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
278    // T" can be converted to an rvalue of type "pointer to T".
279    //
280    if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
281      E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
282                            CK_ArrayToPointerDecay).take();
283  }
284  return Owned(E);
285}
286
287static void CheckForNullPointerDereference(Sema &S, Expr *E) {
288  // Check to see if we are dereferencing a null pointer.  If so,
289  // and if not volatile-qualified, this is undefined behavior that the
290  // optimizer will delete, so warn about it.  People sometimes try to use this
291  // to get a deterministic trap and are surprised by clang's behavior.  This
292  // only handles the pattern "*null", which is a very syntactic check.
293  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
294    if (UO->getOpcode() == UO_Deref &&
295        UO->getSubExpr()->IgnoreParenCasts()->
296          isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
297        !UO->getType().isVolatileQualified()) {
298    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
299                          S.PDiag(diag::warn_indirection_through_null)
300                            << UO->getSubExpr()->getSourceRange());
301    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
302                        S.PDiag(diag::note_indirection_through_null));
303  }
304}
305
306ExprResult Sema::DefaultLvalueConversion(Expr *E) {
307  // C++ [conv.lval]p1:
308  //   A glvalue of a non-function, non-array type T can be
309  //   converted to a prvalue.
310  if (!E->isGLValue()) return Owned(E);
311
312  QualType T = E->getType();
313  assert(!T.isNull() && "r-value conversion on typeless expression?");
314
315  // Create a load out of an ObjCProperty l-value, if necessary.
316  if (E->getObjectKind() == OK_ObjCProperty) {
317    ExprResult Res = ConvertPropertyForRValue(E);
318    if (Res.isInvalid())
319      return Owned(E);
320    E = Res.take();
321    if (!E->isGLValue())
322      return Owned(E);
323  }
324
325  // We don't want to throw lvalue-to-rvalue casts on top of
326  // expressions of certain types in C++.
327  if (getLangOptions().CPlusPlus &&
328      (E->getType() == Context.OverloadTy ||
329       T->isDependentType() ||
330       T->isRecordType()))
331    return Owned(E);
332
333  // The C standard is actually really unclear on this point, and
334  // DR106 tells us what the result should be but not why.  It's
335  // generally best to say that void types just doesn't undergo
336  // lvalue-to-rvalue at all.  Note that expressions of unqualified
337  // 'void' type are never l-values, but qualified void can be.
338  if (T->isVoidType())
339    return Owned(E);
340
341  CheckForNullPointerDereference(*this, E);
342
343  // C++ [conv.lval]p1:
344  //   [...] If T is a non-class type, the type of the prvalue is the
345  //   cv-unqualified version of T. Otherwise, the type of the
346  //   rvalue is T.
347  //
348  // C99 6.3.2.1p2:
349  //   If the lvalue has qualified type, the value has the unqualified
350  //   version of the type of the lvalue; otherwise, the value has the
351  //   type of the lvalue.
352  if (T.hasQualifiers())
353    T = T.getUnqualifiedType();
354
355  CheckArrayAccess(E);
356
357  return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
358                                        E, 0, VK_RValue));
359}
360
361ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
362  ExprResult Res = DefaultFunctionArrayConversion(E);
363  if (Res.isInvalid())
364    return ExprError();
365  Res = DefaultLvalueConversion(Res.take());
366  if (Res.isInvalid())
367    return ExprError();
368  return move(Res);
369}
370
371
372/// UsualUnaryConversions - Performs various conversions that are common to most
373/// operators (C99 6.3). The conversions of array and function types are
374/// sometimes suppressed. For example, the array->pointer conversion doesn't
375/// apply if the array is an argument to the sizeof or address (&) operators.
376/// In these instances, this routine should *not* be called.
377ExprResult Sema::UsualUnaryConversions(Expr *E) {
378  // First, convert to an r-value.
379  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
380  if (Res.isInvalid())
381    return Owned(E);
382  E = Res.take();
383
384  QualType Ty = E->getType();
385  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
386
387  // Try to perform integral promotions if the object has a theoretically
388  // promotable type.
389  if (Ty->isIntegralOrUnscopedEnumerationType()) {
390    // C99 6.3.1.1p2:
391    //
392    //   The following may be used in an expression wherever an int or
393    //   unsigned int may be used:
394    //     - an object or expression with an integer type whose integer
395    //       conversion rank is less than or equal to the rank of int
396    //       and unsigned int.
397    //     - A bit-field of type _Bool, int, signed int, or unsigned int.
398    //
399    //   If an int can represent all values of the original type, the
400    //   value is converted to an int; otherwise, it is converted to an
401    //   unsigned int. These are called the integer promotions. All
402    //   other types are unchanged by the integer promotions.
403
404    QualType PTy = Context.isPromotableBitField(E);
405    if (!PTy.isNull()) {
406      E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
407      return Owned(E);
408    }
409    if (Ty->isPromotableIntegerType()) {
410      QualType PT = Context.getPromotedIntegerType(Ty);
411      E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
412      return Owned(E);
413    }
414  }
415  return Owned(E);
416}
417
418/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
419/// do not have a prototype. Arguments that have type float are promoted to
420/// double. All other argument types are converted by UsualUnaryConversions().
421ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
422  QualType Ty = E->getType();
423  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
424
425  ExprResult Res = UsualUnaryConversions(E);
426  if (Res.isInvalid())
427    return Owned(E);
428  E = Res.take();
429
430  // If this is a 'float' (CVR qualified or typedef) promote to double.
431  if (Ty->isSpecificBuiltinType(BuiltinType::Float))
432    E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
433
434  return Owned(E);
435}
436
437/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
438/// will warn if the resulting type is not a POD type, and rejects ObjC
439/// interfaces passed by value.
440ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
441                                                  FunctionDecl *FDecl) {
442  ExprResult ExprRes = CheckPlaceholderExpr(E);
443  if (ExprRes.isInvalid())
444    return ExprError();
445
446  ExprRes = DefaultArgumentPromotion(E);
447  if (ExprRes.isInvalid())
448    return ExprError();
449  E = ExprRes.take();
450
451  // __builtin_va_start takes the second argument as a "varargs" argument, but
452  // it doesn't actually do anything with it.  It doesn't need to be non-pod
453  // etc.
454  if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
455    return Owned(E);
456
457  // Don't allow one to pass an Objective-C interface to a vararg.
458  if (E->getType()->isObjCObjectType() &&
459    DiagRuntimeBehavior(E->getLocStart(), 0,
460                        PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
461                          << E->getType() << CT))
462    return ExprError();
463
464  if (!E->getType().isPODType(Context)) {
465    // C++0x [expr.call]p7:
466    //   Passing a potentially-evaluated argument of class type (Clause 9)
467    //   having a non-trivial copy constructor, a non-trivial move constructor,
468    //   or a non-trivial destructor, with no corresponding parameter,
469    //   is conditionally-supported with implementation-defined semantics.
470    bool TrivialEnough = false;
471    if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType())  {
472      if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
473        if (Record->hasTrivialCopyConstructor() &&
474            Record->hasTrivialMoveConstructor() &&
475            Record->hasTrivialDestructor())
476          TrivialEnough = true;
477      }
478    }
479
480    if (!TrivialEnough &&
481        getLangOptions().ObjCAutoRefCount &&
482        E->getType()->isObjCLifetimeType())
483      TrivialEnough = true;
484
485    if (TrivialEnough) {
486      // Nothing to diagnose. This is okay.
487    } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
488                          PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
489                            << getLangOptions().CPlusPlus0x << E->getType()
490                            << CT)) {
491      // Turn this into a trap.
492      CXXScopeSpec SS;
493      UnqualifiedId Name;
494      Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
495                         E->getLocStart());
496      ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
497      if (TrapFn.isInvalid())
498        return ExprError();
499
500      ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
501                                      MultiExprArg(), E->getLocEnd());
502      if (Call.isInvalid())
503        return ExprError();
504
505      ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
506                                    Call.get(), E);
507      if (Comma.isInvalid())
508        return ExprError();
509
510      E = Comma.get();
511    }
512  }
513
514  return Owned(E);
515}
516
517/// UsualArithmeticConversions - Performs various conversions that are common to
518/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
519/// routine returns the first non-arithmetic type found. The client is
520/// responsible for emitting appropriate error diagnostics.
521/// FIXME: verify the conversion rules for "complex int" are consistent with
522/// GCC.
523QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
524                                          bool isCompAssign) {
525  if (!isCompAssign) {
526    lhsExpr = UsualUnaryConversions(lhsExpr.take());
527    if (lhsExpr.isInvalid())
528      return QualType();
529  }
530
531  rhsExpr = UsualUnaryConversions(rhsExpr.take());
532  if (rhsExpr.isInvalid())
533    return QualType();
534
535  // For conversion purposes, we ignore any qualifiers.
536  // For example, "const float" and "float" are equivalent.
537  QualType lhs =
538    Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
539  QualType rhs =
540    Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
541
542  // If both types are identical, no conversion is needed.
543  if (lhs == rhs)
544    return lhs;
545
546  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
547  // The caller can deal with this (e.g. pointer + int).
548  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
549    return lhs;
550
551  // Apply unary and bitfield promotions to the LHS's type.
552  QualType lhs_unpromoted = lhs;
553  if (lhs->isPromotableIntegerType())
554    lhs = Context.getPromotedIntegerType(lhs);
555  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
556  if (!LHSBitfieldPromoteTy.isNull())
557    lhs = LHSBitfieldPromoteTy;
558  if (lhs != lhs_unpromoted && !isCompAssign)
559    lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
560
561  // If both types are identical, no conversion is needed.
562  if (lhs == rhs)
563    return lhs;
564
565  // At this point, we have two different arithmetic types.
566
567  // Handle complex types first (C99 6.3.1.8p1).
568  bool LHSComplexFloat = lhs->isComplexType();
569  bool RHSComplexFloat = rhs->isComplexType();
570  if (LHSComplexFloat || RHSComplexFloat) {
571    // if we have an integer operand, the result is the complex type.
572
573    if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
574      if (rhs->isIntegerType()) {
575        QualType fp = cast<ComplexType>(lhs)->getElementType();
576        rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
577        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
578      } else {
579        assert(rhs->isComplexIntegerType());
580        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
581      }
582      return lhs;
583    }
584
585    if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
586      if (!isCompAssign) {
587        // int -> float -> _Complex float
588        if (lhs->isIntegerType()) {
589          QualType fp = cast<ComplexType>(rhs)->getElementType();
590          lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
591          lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
592        } else {
593          assert(lhs->isComplexIntegerType());
594          lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
595        }
596      }
597      return rhs;
598    }
599
600    // This handles complex/complex, complex/float, or float/complex.
601    // When both operands are complex, the shorter operand is converted to the
602    // type of the longer, and that is the type of the result. This corresponds
603    // to what is done when combining two real floating-point operands.
604    // The fun begins when size promotion occur across type domains.
605    // From H&S 6.3.4: When one operand is complex and the other is a real
606    // floating-point type, the less precise type is converted, within it's
607    // real or complex domain, to the precision of the other type. For example,
608    // when combining a "long double" with a "double _Complex", the
609    // "double _Complex" is promoted to "long double _Complex".
610    int order = Context.getFloatingTypeOrder(lhs, rhs);
611
612    // If both are complex, just cast to the more precise type.
613    if (LHSComplexFloat && RHSComplexFloat) {
614      if (order > 0) {
615        // _Complex float -> _Complex double
616        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
617        return lhs;
618
619      } else if (order < 0) {
620        // _Complex float -> _Complex double
621        if (!isCompAssign)
622          lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
623        return rhs;
624      }
625      return lhs;
626    }
627
628    // If just the LHS is complex, the RHS needs to be converted,
629    // and the LHS might need to be promoted.
630    if (LHSComplexFloat) {
631      if (order > 0) { // LHS is wider
632        // float -> _Complex double
633        QualType fp = cast<ComplexType>(lhs)->getElementType();
634        rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
635        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
636        return lhs;
637      }
638
639      // RHS is at least as wide.  Find its corresponding complex type.
640      QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
641
642      // double -> _Complex double
643      rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
644
645      // _Complex float -> _Complex double
646      if (!isCompAssign && order < 0)
647        lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
648
649      return result;
650    }
651
652    // Just the RHS is complex, so the LHS needs to be converted
653    // and the RHS might need to be promoted.
654    assert(RHSComplexFloat);
655
656    if (order < 0) { // RHS is wider
657      // float -> _Complex double
658      if (!isCompAssign) {
659        QualType fp = cast<ComplexType>(rhs)->getElementType();
660        lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
661        lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
662      }
663      return rhs;
664    }
665
666    // LHS is at least as wide.  Find its corresponding complex type.
667    QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
668
669    // double -> _Complex double
670    if (!isCompAssign)
671      lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
672
673    // _Complex float -> _Complex double
674    if (order > 0)
675      rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
676
677    return result;
678  }
679
680  // Now handle "real" floating types (i.e. float, double, long double).
681  bool LHSFloat = lhs->isRealFloatingType();
682  bool RHSFloat = rhs->isRealFloatingType();
683  if (LHSFloat || RHSFloat) {
684    // If we have two real floating types, convert the smaller operand
685    // to the bigger result.
686    if (LHSFloat && RHSFloat) {
687      int order = Context.getFloatingTypeOrder(lhs, rhs);
688      if (order > 0) {
689        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
690        return lhs;
691      }
692
693      assert(order < 0 && "illegal float comparison");
694      if (!isCompAssign)
695        lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
696      return rhs;
697    }
698
699    // If we have an integer operand, the result is the real floating type.
700    if (LHSFloat) {
701      if (rhs->isIntegerType()) {
702        // Convert rhs to the lhs floating point type.
703        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
704        return lhs;
705      }
706
707      // Convert both sides to the appropriate complex float.
708      assert(rhs->isComplexIntegerType());
709      QualType result = Context.getComplexType(lhs);
710
711      // _Complex int -> _Complex float
712      rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
713
714      // float -> _Complex float
715      if (!isCompAssign)
716        lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
717
718      return result;
719    }
720
721    assert(RHSFloat);
722    if (lhs->isIntegerType()) {
723      // Convert lhs to the rhs floating point type.
724      if (!isCompAssign)
725        lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
726      return rhs;
727    }
728
729    // Convert both sides to the appropriate complex float.
730    assert(lhs->isComplexIntegerType());
731    QualType result = Context.getComplexType(rhs);
732
733    // _Complex int -> _Complex float
734    if (!isCompAssign)
735      lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
736
737    // float -> _Complex float
738    rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
739
740    return result;
741  }
742
743  // Handle GCC complex int extension.
744  // FIXME: if the operands are (int, _Complex long), we currently
745  // don't promote the complex.  Also, signedness?
746  const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
747  const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
748  if (lhsComplexInt && rhsComplexInt) {
749    int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
750                                            rhsComplexInt->getElementType());
751    assert(order && "inequal types with equal element ordering");
752    if (order > 0) {
753      // _Complex int -> _Complex long
754      rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
755      return lhs;
756    }
757
758    if (!isCompAssign)
759      lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
760    return rhs;
761  } else if (lhsComplexInt) {
762    // int -> _Complex int
763    rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
764    return lhs;
765  } else if (rhsComplexInt) {
766    // int -> _Complex int
767    if (!isCompAssign)
768      lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
769    return rhs;
770  }
771
772  // Finally, we have two differing integer types.
773  // The rules for this case are in C99 6.3.1.8
774  int compare = Context.getIntegerTypeOrder(lhs, rhs);
775  bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
776       rhsSigned = rhs->hasSignedIntegerRepresentation();
777  if (lhsSigned == rhsSigned) {
778    // Same signedness; use the higher-ranked type
779    if (compare >= 0) {
780      rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
781      return lhs;
782    } else if (!isCompAssign)
783      lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
784    return rhs;
785  } else if (compare != (lhsSigned ? 1 : -1)) {
786    // The unsigned type has greater than or equal rank to the
787    // signed type, so use the unsigned type
788    if (rhsSigned) {
789      rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
790      return lhs;
791    } else if (!isCompAssign)
792      lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
793    return rhs;
794  } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
795    // The two types are different widths; if we are here, that
796    // means the signed type is larger than the unsigned type, so
797    // use the signed type.
798    if (lhsSigned) {
799      rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
800      return lhs;
801    } else if (!isCompAssign)
802      lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
803    return rhs;
804  } else {
805    // The signed type is higher-ranked than the unsigned type,
806    // but isn't actually any bigger (like unsigned int and long
807    // on most 32-bit systems).  Use the unsigned type corresponding
808    // to the signed type.
809    QualType result =
810      Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
811    rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
812    if (!isCompAssign)
813      lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
814    return result;
815  }
816}
817
818//===----------------------------------------------------------------------===//
819//  Semantic Analysis for various Expression Types
820//===----------------------------------------------------------------------===//
821
822
823ExprResult
824Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
825                                SourceLocation DefaultLoc,
826                                SourceLocation RParenLoc,
827                                Expr *ControllingExpr,
828                                MultiTypeArg types,
829                                MultiExprArg exprs) {
830  unsigned NumAssocs = types.size();
831  assert(NumAssocs == exprs.size());
832
833  ParsedType *ParsedTypes = types.release();
834  Expr **Exprs = exprs.release();
835
836  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
837  for (unsigned i = 0; i < NumAssocs; ++i) {
838    if (ParsedTypes[i])
839      (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
840    else
841      Types[i] = 0;
842  }
843
844  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
845                                             ControllingExpr, Types, Exprs,
846                                             NumAssocs);
847  delete [] Types;
848  return ER;
849}
850
851ExprResult
852Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
853                                 SourceLocation DefaultLoc,
854                                 SourceLocation RParenLoc,
855                                 Expr *ControllingExpr,
856                                 TypeSourceInfo **Types,
857                                 Expr **Exprs,
858                                 unsigned NumAssocs) {
859  bool TypeErrorFound = false,
860       IsResultDependent = ControllingExpr->isTypeDependent(),
861       ContainsUnexpandedParameterPack
862         = ControllingExpr->containsUnexpandedParameterPack();
863
864  for (unsigned i = 0; i < NumAssocs; ++i) {
865    if (Exprs[i]->containsUnexpandedParameterPack())
866      ContainsUnexpandedParameterPack = true;
867
868    if (Types[i]) {
869      if (Types[i]->getType()->containsUnexpandedParameterPack())
870        ContainsUnexpandedParameterPack = true;
871
872      if (Types[i]->getType()->isDependentType()) {
873        IsResultDependent = true;
874      } else {
875        // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
876        // complete object type other than a variably modified type."
877        unsigned D = 0;
878        if (Types[i]->getType()->isIncompleteType())
879          D = diag::err_assoc_type_incomplete;
880        else if (!Types[i]->getType()->isObjectType())
881          D = diag::err_assoc_type_nonobject;
882        else if (Types[i]->getType()->isVariablyModifiedType())
883          D = diag::err_assoc_type_variably_modified;
884
885        if (D != 0) {
886          Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
887            << Types[i]->getTypeLoc().getSourceRange()
888            << Types[i]->getType();
889          TypeErrorFound = true;
890        }
891
892        // C1X 6.5.1.1p2 "No two generic associations in the same generic
893        // selection shall specify compatible types."
894        for (unsigned j = i+1; j < NumAssocs; ++j)
895          if (Types[j] && !Types[j]->getType()->isDependentType() &&
896              Context.typesAreCompatible(Types[i]->getType(),
897                                         Types[j]->getType())) {
898            Diag(Types[j]->getTypeLoc().getBeginLoc(),
899                 diag::err_assoc_compatible_types)
900              << Types[j]->getTypeLoc().getSourceRange()
901              << Types[j]->getType()
902              << Types[i]->getType();
903            Diag(Types[i]->getTypeLoc().getBeginLoc(),
904                 diag::note_compat_assoc)
905              << Types[i]->getTypeLoc().getSourceRange()
906              << Types[i]->getType();
907            TypeErrorFound = true;
908          }
909      }
910    }
911  }
912  if (TypeErrorFound)
913    return ExprError();
914
915  // If we determined that the generic selection is result-dependent, don't
916  // try to compute the result expression.
917  if (IsResultDependent)
918    return Owned(new (Context) GenericSelectionExpr(
919                   Context, KeyLoc, ControllingExpr,
920                   Types, Exprs, NumAssocs, DefaultLoc,
921                   RParenLoc, ContainsUnexpandedParameterPack));
922
923  llvm::SmallVector<unsigned, 1> CompatIndices;
924  unsigned DefaultIndex = -1U;
925  for (unsigned i = 0; i < NumAssocs; ++i) {
926    if (!Types[i])
927      DefaultIndex = i;
928    else if (Context.typesAreCompatible(ControllingExpr->getType(),
929                                        Types[i]->getType()))
930      CompatIndices.push_back(i);
931  }
932
933  // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
934  // type compatible with at most one of the types named in its generic
935  // association list."
936  if (CompatIndices.size() > 1) {
937    // We strip parens here because the controlling expression is typically
938    // parenthesized in macro definitions.
939    ControllingExpr = ControllingExpr->IgnoreParens();
940    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
941      << ControllingExpr->getSourceRange() << ControllingExpr->getType()
942      << (unsigned) CompatIndices.size();
943    for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
944         E = CompatIndices.end(); I != E; ++I) {
945      Diag(Types[*I]->getTypeLoc().getBeginLoc(),
946           diag::note_compat_assoc)
947        << Types[*I]->getTypeLoc().getSourceRange()
948        << Types[*I]->getType();
949    }
950    return ExprError();
951  }
952
953  // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
954  // its controlling expression shall have type compatible with exactly one of
955  // the types named in its generic association list."
956  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
957    // We strip parens here because the controlling expression is typically
958    // parenthesized in macro definitions.
959    ControllingExpr = ControllingExpr->IgnoreParens();
960    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
961      << ControllingExpr->getSourceRange() << ControllingExpr->getType();
962    return ExprError();
963  }
964
965  // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
966  // type name that is compatible with the type of the controlling expression,
967  // then the result expression of the generic selection is the expression
968  // in that generic association. Otherwise, the result expression of the
969  // generic selection is the expression in the default generic association."
970  unsigned ResultIndex =
971    CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
972
973  return Owned(new (Context) GenericSelectionExpr(
974                 Context, KeyLoc, ControllingExpr,
975                 Types, Exprs, NumAssocs, DefaultLoc,
976                 RParenLoc, ContainsUnexpandedParameterPack,
977                 ResultIndex));
978}
979
980/// ActOnStringLiteral - The specified tokens were lexed as pasted string
981/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
982/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
983/// multiple tokens.  However, the common case is that StringToks points to one
984/// string.
985///
986ExprResult
987Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
988  assert(NumStringToks && "Must have at least one string!");
989
990  StringLiteralParser Literal(StringToks, NumStringToks, PP);
991  if (Literal.hadError)
992    return ExprError();
993
994  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
995  for (unsigned i = 0; i != NumStringToks; ++i)
996    StringTokLocs.push_back(StringToks[i].getLocation());
997
998  QualType StrTy = Context.CharTy;
999  if (Literal.AnyWide)
1000    StrTy = Context.getWCharType();
1001  else if (Literal.Pascal)
1002    StrTy = Context.UnsignedCharTy;
1003
1004  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1005  if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
1006    StrTy.addConst();
1007
1008  // Get an array type for the string, according to C99 6.4.5.  This includes
1009  // the nul terminator character as well as the string length for pascal
1010  // strings.
1011  StrTy = Context.getConstantArrayType(StrTy,
1012                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
1013                                       ArrayType::Normal, 0);
1014
1015  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1016  return Owned(StringLiteral::Create(Context, Literal.GetString(),
1017                                     Literal.GetStringLength(),
1018                                     Literal.AnyWide, Literal.Pascal, StrTy,
1019                                     &StringTokLocs[0],
1020                                     StringTokLocs.size()));
1021}
1022
1023enum CaptureResult {
1024  /// No capture is required.
1025  CR_NoCapture,
1026
1027  /// A capture is required.
1028  CR_Capture,
1029
1030  /// A by-ref capture is required.
1031  CR_CaptureByRef,
1032
1033  /// An error occurred when trying to capture the given variable.
1034  CR_Error
1035};
1036
1037/// Diagnose an uncapturable value reference.
1038///
1039/// \param var - the variable referenced
1040/// \param DC - the context which we couldn't capture through
1041static CaptureResult
1042diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
1043                                   VarDecl *var, DeclContext *DC) {
1044  switch (S.ExprEvalContexts.back().Context) {
1045  case Sema::Unevaluated:
1046    // The argument will never be evaluated, so don't complain.
1047    return CR_NoCapture;
1048
1049  case Sema::PotentiallyEvaluated:
1050  case Sema::PotentiallyEvaluatedIfUsed:
1051    break;
1052
1053  case Sema::PotentiallyPotentiallyEvaluated:
1054    // FIXME: delay these!
1055    break;
1056  }
1057
1058  // Don't diagnose about capture if we're not actually in code right
1059  // now; in general, there are more appropriate places that will
1060  // diagnose this.
1061  if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1062
1063  // Certain madnesses can happen with parameter declarations, which
1064  // we want to ignore.
1065  if (isa<ParmVarDecl>(var)) {
1066    // - If the parameter still belongs to the translation unit, then
1067    //   we're actually just using one parameter in the declaration of
1068    //   the next.  This is useful in e.g. VLAs.
1069    if (isa<TranslationUnitDecl>(var->getDeclContext()))
1070      return CR_NoCapture;
1071
1072    // - This particular madness can happen in ill-formed default
1073    //   arguments; claim it's okay and let downstream code handle it.
1074    if (S.CurContext == var->getDeclContext()->getParent())
1075      return CR_NoCapture;
1076  }
1077
1078  DeclarationName functionName;
1079  if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1080    functionName = fn->getDeclName();
1081  // FIXME: variable from enclosing block that we couldn't capture from!
1082
1083  S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1084    << var->getIdentifier() << functionName;
1085  S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1086    << var->getIdentifier();
1087
1088  return CR_Error;
1089}
1090
1091/// There is a well-formed capture at a particular scope level;
1092/// propagate it through all the nested blocks.
1093static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1094                                      const BlockDecl::Capture &capture) {
1095  VarDecl *var = capture.getVariable();
1096
1097  // Update all the inner blocks with the capture information.
1098  for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1099         i != e; ++i) {
1100    BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1101    innerBlock->Captures.push_back(
1102      BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1103                         /*nested*/ true, capture.getCopyExpr()));
1104    innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1105  }
1106
1107  return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1108}
1109
1110/// shouldCaptureValueReference - Determine if a reference to the
1111/// given value in the current context requires a variable capture.
1112///
1113/// This also keeps the captures set in the BlockScopeInfo records
1114/// up-to-date.
1115static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
1116                                                 ValueDecl *value) {
1117  // Only variables ever require capture.
1118  VarDecl *var = dyn_cast<VarDecl>(value);
1119  if (!var) return CR_NoCapture;
1120
1121  // Fast path: variables from the current context never require capture.
1122  DeclContext *DC = S.CurContext;
1123  if (var->getDeclContext() == DC) return CR_NoCapture;
1124
1125  // Only variables with local storage require capture.
1126  // FIXME: What about 'const' variables in C++?
1127  if (!var->hasLocalStorage()) return CR_NoCapture;
1128
1129  // Otherwise, we need to capture.
1130
1131  unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
1132  do {
1133    // Only blocks (and eventually C++0x closures) can capture; other
1134    // scopes don't work.
1135    if (!isa<BlockDecl>(DC))
1136      return diagnoseUncapturableValueReference(S, loc, var, DC);
1137
1138    BlockScopeInfo *blockScope =
1139      cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1140    assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1141
1142    // Check whether we've already captured it in this block.  If so,
1143    // we're done.
1144    if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1145      return propagateCapture(S, functionScopesIndex,
1146                              blockScope->Captures[indexPlus1 - 1]);
1147
1148    functionScopesIndex--;
1149    DC = cast<BlockDecl>(DC)->getDeclContext();
1150  } while (var->getDeclContext() != DC);
1151
1152  // Okay, we descended all the way to the block that defines the variable.
1153  // Actually try to capture it.
1154  QualType type = var->getType();
1155
1156  // Prohibit variably-modified types.
1157  if (type->isVariablyModifiedType()) {
1158    S.Diag(loc, diag::err_ref_vm_type);
1159    S.Diag(var->getLocation(), diag::note_declared_at);
1160    return CR_Error;
1161  }
1162
1163  // Prohibit arrays, even in __block variables, but not references to
1164  // them.
1165  if (type->isArrayType()) {
1166    S.Diag(loc, diag::err_ref_array_type);
1167    S.Diag(var->getLocation(), diag::note_declared_at);
1168    return CR_Error;
1169  }
1170
1171  S.MarkDeclarationReferenced(loc, var);
1172
1173  // The BlocksAttr indicates the variable is bound by-reference.
1174  bool byRef = var->hasAttr<BlocksAttr>();
1175
1176  // Build a copy expression.
1177  Expr *copyExpr = 0;
1178  const RecordType *rtype;
1179  if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1180      (rtype = type->getAs<RecordType>())) {
1181
1182    // The capture logic needs the destructor, so make sure we mark it.
1183    // Usually this is unnecessary because most local variables have
1184    // their destructors marked at declaration time, but parameters are
1185    // an exception because it's technically only the call site that
1186    // actually requires the destructor.
1187    if (isa<ParmVarDecl>(var))
1188      S.FinalizeVarWithDestructor(var, rtype);
1189
1190    // According to the blocks spec, the capture of a variable from
1191    // the stack requires a const copy constructor.  This is not true
1192    // of the copy/move done to move a __block variable to the heap.
1193    type.addConst();
1194
1195    Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1196    ExprResult result =
1197      S.PerformCopyInitialization(
1198                      InitializedEntity::InitializeBlock(var->getLocation(),
1199                                                         type, false),
1200                                  loc, S.Owned(declRef));
1201
1202    // Build a full-expression copy expression if initialization
1203    // succeeded and used a non-trivial constructor.  Recover from
1204    // errors by pretending that the copy isn't necessary.
1205    if (!result.isInvalid() &&
1206        !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1207      result = S.MaybeCreateExprWithCleanups(result);
1208      copyExpr = result.take();
1209    }
1210  }
1211
1212  // We're currently at the declarer; go back to the closure.
1213  functionScopesIndex++;
1214  BlockScopeInfo *blockScope =
1215    cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1216
1217  // Build a valid capture in this scope.
1218  blockScope->Captures.push_back(
1219                 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1220  blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1221
1222  // Propagate that to inner captures if necessary.
1223  return propagateCapture(S, functionScopesIndex,
1224                          blockScope->Captures.back());
1225}
1226
1227static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1228                                        const DeclarationNameInfo &NameInfo,
1229                                        bool byRef) {
1230  assert(isa<VarDecl>(vd) && "capturing non-variable");
1231
1232  VarDecl *var = cast<VarDecl>(vd);
1233  assert(var->hasLocalStorage() && "capturing non-local");
1234  assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1235
1236  QualType exprType = var->getType().getNonReferenceType();
1237
1238  BlockDeclRefExpr *BDRE;
1239  if (!byRef) {
1240    // The variable will be bound by copy; make it const within the
1241    // closure, but record that this was done in the expression.
1242    bool constAdded = !exprType.isConstQualified();
1243    exprType.addConst();
1244
1245    BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1246                                            NameInfo.getLoc(), false,
1247                                            constAdded);
1248  } else {
1249    BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1250                                            NameInfo.getLoc(), true);
1251  }
1252
1253  return S.Owned(BDRE);
1254}
1255
1256ExprResult
1257Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1258                       SourceLocation Loc,
1259                       const CXXScopeSpec *SS) {
1260  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1261  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1262}
1263
1264/// BuildDeclRefExpr - Build an expression that references a
1265/// declaration that does not require a closure capture.
1266ExprResult
1267Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1268                       const DeclarationNameInfo &NameInfo,
1269                       const CXXScopeSpec *SS) {
1270  MarkDeclarationReferenced(NameInfo.getLoc(), D);
1271
1272  Expr *E = DeclRefExpr::Create(Context,
1273                                SS? SS->getWithLocInContext(Context)
1274                                  : NestedNameSpecifierLoc(),
1275                                D, NameInfo, Ty, VK);
1276
1277  // Just in case we're building an illegal pointer-to-member.
1278  if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1279    E->setObjectKind(OK_BitField);
1280
1281  return Owned(E);
1282}
1283
1284static ExprResult
1285BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1286                        const CXXScopeSpec &SS, FieldDecl *Field,
1287                        DeclAccessPair FoundDecl,
1288                        const DeclarationNameInfo &MemberNameInfo);
1289
1290ExprResult
1291Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1292                                               SourceLocation loc,
1293                                               IndirectFieldDecl *indirectField,
1294                                               Expr *baseObjectExpr,
1295                                               SourceLocation opLoc) {
1296  // First, build the expression that refers to the base object.
1297
1298  bool baseObjectIsPointer = false;
1299  Qualifiers baseQuals;
1300
1301  // Case 1:  the base of the indirect field is not a field.
1302  VarDecl *baseVariable = indirectField->getVarDecl();
1303  CXXScopeSpec EmptySS;
1304  if (baseVariable) {
1305    assert(baseVariable->getType()->isRecordType());
1306
1307    // In principle we could have a member access expression that
1308    // accesses an anonymous struct/union that's a static member of
1309    // the base object's class.  However, under the current standard,
1310    // static data members cannot be anonymous structs or unions.
1311    // Supporting this is as easy as building a MemberExpr here.
1312    assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1313
1314    DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1315
1316    ExprResult result =
1317      BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
1318    if (result.isInvalid()) return ExprError();
1319
1320    baseObjectExpr = result.take();
1321    baseObjectIsPointer = false;
1322    baseQuals = baseObjectExpr->getType().getQualifiers();
1323
1324  // Case 2: the base of the indirect field is a field and the user
1325  // wrote a member expression.
1326  } else if (baseObjectExpr) {
1327    // The caller provided the base object expression. Determine
1328    // whether its a pointer and whether it adds any qualifiers to the
1329    // anonymous struct/union fields we're looking into.
1330    QualType objectType = baseObjectExpr->getType();
1331
1332    if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1333      baseObjectIsPointer = true;
1334      objectType = ptr->getPointeeType();
1335    } else {
1336      baseObjectIsPointer = false;
1337    }
1338    baseQuals = objectType.getQualifiers();
1339
1340  // Case 3: the base of the indirect field is a field and we should
1341  // build an implicit member access.
1342  } else {
1343    // We've found a member of an anonymous struct/union that is
1344    // inside a non-anonymous struct/union, so in a well-formed
1345    // program our base object expression is "this".
1346    QualType ThisTy = getAndCaptureCurrentThisType();
1347    if (ThisTy.isNull()) {
1348      Diag(loc, diag::err_invalid_member_use_in_static_method)
1349        << indirectField->getDeclName();
1350      return ExprError();
1351    }
1352
1353    // Our base object expression is "this".
1354    baseObjectExpr =
1355      new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
1356    baseObjectIsPointer = true;
1357    baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
1358  }
1359
1360  // Build the implicit member references to the field of the
1361  // anonymous struct/union.
1362  Expr *result = baseObjectExpr;
1363  IndirectFieldDecl::chain_iterator
1364    FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
1365
1366  // Build the first member access in the chain with full information.
1367  if (!baseVariable) {
1368    FieldDecl *field = cast<FieldDecl>(*FI);
1369
1370    // FIXME: use the real found-decl info!
1371    DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1372
1373    // Make a nameInfo that properly uses the anonymous name.
1374    DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1375
1376    result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
1377                                     EmptySS, field, foundDecl,
1378                                     memberNameInfo).take();
1379    baseObjectIsPointer = false;
1380
1381    // FIXME: check qualified member access
1382  }
1383
1384  // In all cases, we should now skip the first declaration in the chain.
1385  ++FI;
1386
1387  while (FI != FEnd) {
1388    FieldDecl *field = cast<FieldDecl>(*FI++);
1389
1390    // FIXME: these are somewhat meaningless
1391    DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1392    DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1393
1394    result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
1395                                     (FI == FEnd? SS : EmptySS), field,
1396                                     foundDecl, memberNameInfo)
1397      .take();
1398  }
1399
1400  return Owned(result);
1401}
1402
1403/// Decomposes the given name into a DeclarationNameInfo, its location, and
1404/// possibly a list of template arguments.
1405///
1406/// If this produces template arguments, it is permitted to call
1407/// DecomposeTemplateName.
1408///
1409/// This actually loses a lot of source location information for
1410/// non-standard name kinds; we should consider preserving that in
1411/// some way.
1412static void DecomposeUnqualifiedId(Sema &SemaRef,
1413                                   const UnqualifiedId &Id,
1414                                   TemplateArgumentListInfo &Buffer,
1415                                   DeclarationNameInfo &NameInfo,
1416                             const TemplateArgumentListInfo *&TemplateArgs) {
1417  if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1418    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1419    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1420
1421    ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1422                                       Id.TemplateId->getTemplateArgs(),
1423                                       Id.TemplateId->NumArgs);
1424    SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1425    TemplateArgsPtr.release();
1426
1427    TemplateName TName = Id.TemplateId->Template.get();
1428    SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1429    NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
1430    TemplateArgs = &Buffer;
1431  } else {
1432    NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
1433    TemplateArgs = 0;
1434  }
1435}
1436
1437/// Determines if the given class is provably not derived from all of
1438/// the prospective base classes.
1439static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1440                                     CXXRecordDecl *Record,
1441                            const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
1442  if (Bases.count(Record->getCanonicalDecl()))
1443    return false;
1444
1445  RecordDecl *RD = Record->getDefinition();
1446  if (!RD) return false;
1447  Record = cast<CXXRecordDecl>(RD);
1448
1449  for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1450         E = Record->bases_end(); I != E; ++I) {
1451    CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1452    CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1453    if (!BaseRT) return false;
1454
1455    CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
1456    if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1457      return false;
1458  }
1459
1460  return true;
1461}
1462
1463enum IMAKind {
1464  /// The reference is definitely not an instance member access.
1465  IMA_Static,
1466
1467  /// The reference may be an implicit instance member access.
1468  IMA_Mixed,
1469
1470  /// The reference may be to an instance member, but it is invalid if
1471  /// so, because the context is not an instance method.
1472  IMA_Mixed_StaticContext,
1473
1474  /// The reference may be to an instance member, but it is invalid if
1475  /// so, because the context is from an unrelated class.
1476  IMA_Mixed_Unrelated,
1477
1478  /// The reference is definitely an implicit instance member access.
1479  IMA_Instance,
1480
1481  /// The reference may be to an unresolved using declaration.
1482  IMA_Unresolved,
1483
1484  /// The reference may be to an unresolved using declaration and the
1485  /// context is not an instance method.
1486  IMA_Unresolved_StaticContext,
1487
1488  /// All possible referrents are instance members and the current
1489  /// context is not an instance method.
1490  IMA_Error_StaticContext,
1491
1492  /// All possible referrents are instance members of an unrelated
1493  /// class.
1494  IMA_Error_Unrelated
1495};
1496
1497/// The given lookup names class member(s) and is not being used for
1498/// an address-of-member expression.  Classify the type of access
1499/// according to whether it's possible that this reference names an
1500/// instance member.  This is best-effort; it is okay to
1501/// conservatively answer "yes", in which case some errors will simply
1502/// not be caught until template-instantiation.
1503static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1504                                            Scope *CurScope,
1505                                            const LookupResult &R) {
1506  assert(!R.empty() && (*R.begin())->isCXXClassMember());
1507
1508  DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
1509
1510  bool isStaticContext =
1511    (!isa<CXXMethodDecl>(DC) ||
1512     cast<CXXMethodDecl>(DC)->isStatic());
1513
1514  // C++0x [expr.prim]p4:
1515  //   Otherwise, if a member-declarator declares a non-static data member
1516  // of a class X, the expression this is a prvalue of type "pointer to X"
1517  // within the optional brace-or-equal-initializer.
1518  if (CurScope->getFlags() & Scope::ThisScope)
1519    isStaticContext = false;
1520
1521  if (R.isUnresolvableResult())
1522    return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1523
1524  // Collect all the declaring classes of instance members we find.
1525  bool hasNonInstance = false;
1526  bool hasField = false;
1527  llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1528  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1529    NamedDecl *D = *I;
1530
1531    if (D->isCXXInstanceMember()) {
1532      if (dyn_cast<FieldDecl>(D))
1533        hasField = true;
1534
1535      CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
1536      Classes.insert(R->getCanonicalDecl());
1537    }
1538    else
1539      hasNonInstance = true;
1540  }
1541
1542  // If we didn't find any instance members, it can't be an implicit
1543  // member reference.
1544  if (Classes.empty())
1545    return IMA_Static;
1546
1547  // If the current context is not an instance method, it can't be
1548  // an implicit member reference.
1549  if (isStaticContext) {
1550    if (hasNonInstance)
1551        return IMA_Mixed_StaticContext;
1552
1553    if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1554      // C++0x [expr.prim.general]p10:
1555      //   An id-expression that denotes a non-static data member or non-static
1556      //   member function of a class can only be used:
1557      //   (...)
1558      //   - if that id-expression denotes a non-static data member and it
1559      //     appears in an unevaluated operand.
1560      const Sema::ExpressionEvaluationContextRecord& record
1561        = SemaRef.ExprEvalContexts.back();
1562      bool isUnevaluatedExpression = (record.Context == Sema::Unevaluated);
1563      if (isUnevaluatedExpression)
1564        return IMA_Mixed_StaticContext;
1565    }
1566
1567    return IMA_Error_StaticContext;
1568  }
1569
1570  CXXRecordDecl *contextClass;
1571  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
1572    contextClass = MD->getParent()->getCanonicalDecl();
1573  else
1574    contextClass = cast<CXXRecordDecl>(DC);
1575
1576  // [class.mfct.non-static]p3:
1577  // ...is used in the body of a non-static member function of class X,
1578  // if name lookup (3.4.1) resolves the name in the id-expression to a
1579  // non-static non-type member of some class C [...]
1580  // ...if C is not X or a base class of X, the class member access expression
1581  // is ill-formed.
1582  if (R.getNamingClass() &&
1583      contextClass != R.getNamingClass()->getCanonicalDecl() &&
1584      contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1585    return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1586
1587  // If we can prove that the current context is unrelated to all the
1588  // declaring classes, it can't be an implicit member reference (in
1589  // which case it's an error if any of those members are selected).
1590  if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
1591    return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1592
1593  return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1594}
1595
1596/// Diagnose a reference to a field with no object available.
1597static void DiagnoseInstanceReference(Sema &SemaRef,
1598                                      const CXXScopeSpec &SS,
1599                                      NamedDecl *rep,
1600                                      const DeclarationNameInfo &nameInfo) {
1601  SourceLocation Loc = nameInfo.getLoc();
1602  SourceRange Range(Loc);
1603  if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1604
1605  if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
1606    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1607      if (MD->isStatic()) {
1608        // "invalid use of member 'x' in static member function"
1609        SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1610          << Range << nameInfo.getName();
1611        return;
1612      }
1613    }
1614
1615    SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1616      << nameInfo.getName() << Range;
1617    return;
1618  }
1619
1620  SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
1621}
1622
1623/// Diagnose an empty lookup.
1624///
1625/// \return false if new lookup candidates were found
1626bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1627                               CorrectTypoContext CTC) {
1628  DeclarationName Name = R.getLookupName();
1629
1630  unsigned diagnostic = diag::err_undeclared_var_use;
1631  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1632  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1633      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1634      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1635    diagnostic = diag::err_undeclared_use;
1636    diagnostic_suggest = diag::err_undeclared_use_suggest;
1637  }
1638
1639  // If the original lookup was an unqualified lookup, fake an
1640  // unqualified lookup.  This is useful when (for example) the
1641  // original lookup would not have found something because it was a
1642  // dependent name.
1643  for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1644       DC; DC = DC->getParent()) {
1645    if (isa<CXXRecordDecl>(DC)) {
1646      LookupQualifiedName(R, DC);
1647
1648      if (!R.empty()) {
1649        // Don't give errors about ambiguities in this lookup.
1650        R.suppressDiagnostics();
1651
1652        CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1653        bool isInstance = CurMethod &&
1654                          CurMethod->isInstance() &&
1655                          DC == CurMethod->getParent();
1656
1657        // Give a code modification hint to insert 'this->'.
1658        // TODO: fixit for inserting 'Base<T>::' in the other cases.
1659        // Actually quite difficult!
1660        if (isInstance) {
1661          UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1662              CallsUndergoingInstantiation.back()->getCallee());
1663          CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
1664              CurMethod->getInstantiatedFromMemberFunction());
1665          if (DepMethod) {
1666            Diag(R.getNameLoc(), diagnostic) << Name
1667              << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1668            QualType DepThisType = DepMethod->getThisType(Context);
1669            CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1670                                       R.getNameLoc(), DepThisType, false);
1671            TemplateArgumentListInfo TList;
1672            if (ULE->hasExplicitTemplateArgs())
1673              ULE->copyTemplateArgumentsInto(TList);
1674
1675            CXXScopeSpec SS;
1676            SS.Adopt(ULE->getQualifierLoc());
1677            CXXDependentScopeMemberExpr *DepExpr =
1678                CXXDependentScopeMemberExpr::Create(
1679                    Context, DepThis, DepThisType, true, SourceLocation(),
1680                    SS.getWithLocInContext(Context), NULL,
1681                    R.getLookupNameInfo(), &TList);
1682            CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1683          } else {
1684            // FIXME: we should be able to handle this case too. It is correct
1685            // to add this-> here. This is a workaround for PR7947.
1686            Diag(R.getNameLoc(), diagnostic) << Name;
1687          }
1688        } else {
1689          Diag(R.getNameLoc(), diagnostic) << Name;
1690        }
1691
1692        // Do we really want to note all of these?
1693        for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1694          Diag((*I)->getLocation(), diag::note_dependent_var_use);
1695
1696        // Tell the callee to try to recover.
1697        return false;
1698      }
1699
1700      R.clear();
1701    }
1702  }
1703
1704  // We didn't find anything, so try to correct for a typo.
1705  DeclarationName Corrected;
1706  if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
1707    if (!R.empty()) {
1708      if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1709        if (SS.isEmpty())
1710          Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1711            << FixItHint::CreateReplacement(R.getNameLoc(),
1712                                            R.getLookupName().getAsString());
1713        else
1714          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1715            << Name << computeDeclContext(SS, false) << R.getLookupName()
1716            << SS.getRange()
1717            << FixItHint::CreateReplacement(R.getNameLoc(),
1718                                            R.getLookupName().getAsString());
1719        if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1720          Diag(ND->getLocation(), diag::note_previous_decl)
1721            << ND->getDeclName();
1722
1723        // Tell the callee to try to recover.
1724        return false;
1725      }
1726
1727      if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1728        // FIXME: If we ended up with a typo for a type name or
1729        // Objective-C class name, we're in trouble because the parser
1730        // is in the wrong place to recover. Suggest the typo
1731        // correction, but don't make it a fix-it since we're not going
1732        // to recover well anyway.
1733        if (SS.isEmpty())
1734          Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1735        else
1736          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1737            << Name << computeDeclContext(SS, false) << R.getLookupName()
1738            << SS.getRange();
1739
1740        // Don't try to recover; it won't work.
1741        return true;
1742      }
1743    } else {
1744      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1745      // because we aren't able to recover.
1746      if (SS.isEmpty())
1747        Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
1748      else
1749        Diag(R.getNameLoc(), diag::err_no_member_suggest)
1750        << Name << computeDeclContext(SS, false) << Corrected
1751        << SS.getRange();
1752      return true;
1753    }
1754    R.clear();
1755  }
1756
1757  // Emit a special diagnostic for failed member lookups.
1758  // FIXME: computing the declaration context might fail here (?)
1759  if (!SS.isEmpty()) {
1760    Diag(R.getNameLoc(), diag::err_no_member)
1761      << Name << computeDeclContext(SS, false)
1762      << SS.getRange();
1763    return true;
1764  }
1765
1766  // Give up, we can't recover.
1767  Diag(R.getNameLoc(), diagnostic) << Name;
1768  return true;
1769}
1770
1771ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1772  ObjCMethodDecl *CurMeth = getCurMethodDecl();
1773  ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1774  if (!IDecl)
1775    return 0;
1776  ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1777  if (!ClassImpDecl)
1778    return 0;
1779  ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
1780  if (!property)
1781    return 0;
1782  if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1783    if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1784        PIDecl->getPropertyIvarDecl())
1785      return 0;
1786  return property;
1787}
1788
1789bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1790  ObjCMethodDecl *CurMeth = getCurMethodDecl();
1791  ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1792  if (!IDecl)
1793    return false;
1794  ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1795  if (!ClassImpDecl)
1796    return false;
1797  if (ObjCPropertyImplDecl *PIDecl
1798                = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1799    if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1800        PIDecl->getPropertyIvarDecl())
1801      return false;
1802
1803  return true;
1804}
1805
1806ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1807                                              IdentifierInfo *II,
1808                                              SourceLocation NameLoc) {
1809  ObjCMethodDecl *CurMeth = getCurMethodDecl();
1810  bool LookForIvars;
1811  if (Lookup.empty())
1812    LookForIvars = true;
1813  else if (CurMeth->isClassMethod())
1814    LookForIvars = false;
1815  else
1816    LookForIvars = (Lookup.isSingleResult() &&
1817                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1818                    (Lookup.getAsSingle<VarDecl>() != 0));
1819  if (!LookForIvars)
1820    return 0;
1821
1822  ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1823  if (!IDecl)
1824    return 0;
1825  ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1826  if (!ClassImpDecl)
1827    return 0;
1828  bool DynamicImplSeen = false;
1829  ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
1830  if (!property)
1831    return 0;
1832  if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
1833    DynamicImplSeen =
1834      (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1835    // property implementation has a designated ivar. No need to assume a new
1836    // one.
1837    if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1838      return 0;
1839  }
1840  if (!DynamicImplSeen) {
1841    QualType PropType = Context.getCanonicalType(property->getType());
1842    ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
1843                                              NameLoc, NameLoc,
1844                                              II, PropType, /*Dinfo=*/0,
1845                                              ObjCIvarDecl::Private,
1846                                              (Expr *)0, true);
1847    ClassImpDecl->addDecl(Ivar);
1848    IDecl->makeDeclVisibleInContext(Ivar, false);
1849    property->setPropertyIvarDecl(Ivar);
1850    return Ivar;
1851  }
1852  return 0;
1853}
1854
1855ExprResult Sema::ActOnIdExpression(Scope *S,
1856                                   CXXScopeSpec &SS,
1857                                   UnqualifiedId &Id,
1858                                   bool HasTrailingLParen,
1859                                   bool isAddressOfOperand) {
1860  assert(!(isAddressOfOperand && HasTrailingLParen) &&
1861         "cannot be direct & operand and have a trailing lparen");
1862
1863  if (SS.isInvalid())
1864    return ExprError();
1865
1866  TemplateArgumentListInfo TemplateArgsBuffer;
1867
1868  // Decompose the UnqualifiedId into the following data.
1869  DeclarationNameInfo NameInfo;
1870  const TemplateArgumentListInfo *TemplateArgs;
1871  DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1872
1873  DeclarationName Name = NameInfo.getName();
1874  IdentifierInfo *II = Name.getAsIdentifierInfo();
1875  SourceLocation NameLoc = NameInfo.getLoc();
1876
1877  // C++ [temp.dep.expr]p3:
1878  //   An id-expression is type-dependent if it contains:
1879  //     -- an identifier that was declared with a dependent type,
1880  //        (note: handled after lookup)
1881  //     -- a template-id that is dependent,
1882  //        (note: handled in BuildTemplateIdExpr)
1883  //     -- a conversion-function-id that specifies a dependent type,
1884  //     -- a nested-name-specifier that contains a class-name that
1885  //        names a dependent type.
1886  // Determine whether this is a member of an unknown specialization;
1887  // we need to handle these differently.
1888  bool DependentID = false;
1889  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1890      Name.getCXXNameType()->isDependentType()) {
1891    DependentID = true;
1892  } else if (SS.isSet()) {
1893    if (DeclContext *DC = computeDeclContext(SS, false)) {
1894      if (RequireCompleteDeclContext(SS, DC))
1895        return ExprError();
1896    } else {
1897      DependentID = true;
1898    }
1899  }
1900
1901  if (DependentID)
1902    return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1903                                      TemplateArgs);
1904
1905  bool IvarLookupFollowUp = false;
1906  // Perform the required lookup.
1907  LookupResult R(*this, NameInfo, LookupOrdinaryName);
1908  if (TemplateArgs) {
1909    // Lookup the template name again to correctly establish the context in
1910    // which it was found. This is really unfortunate as we already did the
1911    // lookup to determine that it was a template name in the first place. If
1912    // this becomes a performance hit, we can work harder to preserve those
1913    // results until we get here but it's likely not worth it.
1914    bool MemberOfUnknownSpecialization;
1915    LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1916                       MemberOfUnknownSpecialization);
1917
1918    if (MemberOfUnknownSpecialization ||
1919        (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1920      return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1921                                        TemplateArgs);
1922  } else {
1923    IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1924    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1925
1926    // If the result might be in a dependent base class, this is a dependent
1927    // id-expression.
1928    if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1929      return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1930                                        TemplateArgs);
1931
1932    // If this reference is in an Objective-C method, then we need to do
1933    // some special Objective-C lookup, too.
1934    if (IvarLookupFollowUp) {
1935      ExprResult E(LookupInObjCMethod(R, S, II, true));
1936      if (E.isInvalid())
1937        return ExprError();
1938
1939      if (Expr *Ex = E.takeAs<Expr>())
1940        return Owned(Ex);
1941
1942      // Synthesize ivars lazily.
1943      if (getLangOptions().ObjCDefaultSynthProperties &&
1944          getLangOptions().ObjCNonFragileABI2) {
1945        if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
1946          if (const ObjCPropertyDecl *Property =
1947                canSynthesizeProvisionalIvar(II)) {
1948            Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1949            Diag(Property->getLocation(), diag::note_property_declare);
1950          }
1951          return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1952                                   isAddressOfOperand);
1953        }
1954      }
1955      // for further use, this must be set to false if in class method.
1956      IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
1957    }
1958  }
1959
1960  if (R.isAmbiguous())
1961    return ExprError();
1962
1963  // Determine whether this name might be a candidate for
1964  // argument-dependent lookup.
1965  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1966
1967  if (R.empty() && !ADL) {
1968    // Otherwise, this could be an implicitly declared function reference (legal
1969    // in C90, extension in C99, forbidden in C++).
1970    if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1971      NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1972      if (D) R.addDecl(D);
1973    }
1974
1975    // If this name wasn't predeclared and if this is not a function
1976    // call, diagnose the problem.
1977    if (R.empty()) {
1978      if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1979        return ExprError();
1980
1981      assert(!R.empty() &&
1982             "DiagnoseEmptyLookup returned false but added no results");
1983
1984      // If we found an Objective-C instance variable, let
1985      // LookupInObjCMethod build the appropriate expression to
1986      // reference the ivar.
1987      if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1988        R.clear();
1989        ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1990        assert(E.isInvalid() || E.get());
1991        return move(E);
1992      }
1993    }
1994  }
1995
1996  // This is guaranteed from this point on.
1997  assert(!R.empty() || ADL);
1998
1999  // Check whether this might be a C++ implicit instance member access.
2000  // C++ [class.mfct.non-static]p3:
2001  //   When an id-expression that is not part of a class member access
2002  //   syntax and not used to form a pointer to member is used in the
2003  //   body of a non-static member function of class X, if name lookup
2004  //   resolves the name in the id-expression to a non-static non-type
2005  //   member of some class C, the id-expression is transformed into a
2006  //   class member access expression using (*this) as the
2007  //   postfix-expression to the left of the . operator.
2008  //
2009  // But we don't actually need to do this for '&' operands if R
2010  // resolved to a function or overloaded function set, because the
2011  // expression is ill-formed if it actually works out to be a
2012  // non-static member function:
2013  //
2014  // C++ [expr.ref]p4:
2015  //   Otherwise, if E1.E2 refers to a non-static member function. . .
2016  //   [t]he expression can be used only as the left-hand operand of a
2017  //   member function call.
2018  //
2019  // There are other safeguards against such uses, but it's important
2020  // to get this right here so that we don't end up making a
2021  // spuriously dependent expression if we're inside a dependent
2022  // instance method.
2023  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2024    bool MightBeImplicitMember;
2025    if (!isAddressOfOperand)
2026      MightBeImplicitMember = true;
2027    else if (!SS.isEmpty())
2028      MightBeImplicitMember = false;
2029    else if (R.isOverloadedResult())
2030      MightBeImplicitMember = false;
2031    else if (R.isUnresolvableResult())
2032      MightBeImplicitMember = true;
2033    else
2034      MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2035                              isa<IndirectFieldDecl>(R.getFoundDecl());
2036
2037    if (MightBeImplicitMember)
2038      return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
2039  }
2040
2041  if (TemplateArgs)
2042    return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
2043
2044  return BuildDeclarationNameExpr(SS, R, ADL);
2045}
2046
2047/// Builds an expression which might be an implicit member expression.
2048ExprResult
2049Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2050                                      LookupResult &R,
2051                                const TemplateArgumentListInfo *TemplateArgs) {
2052  switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
2053  case IMA_Instance:
2054    return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
2055
2056  case IMA_Mixed:
2057  case IMA_Mixed_Unrelated:
2058  case IMA_Unresolved:
2059    return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
2060
2061  case IMA_Static:
2062  case IMA_Mixed_StaticContext:
2063  case IMA_Unresolved_StaticContext:
2064    if (TemplateArgs)
2065      return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2066    return BuildDeclarationNameExpr(SS, R, false);
2067
2068  case IMA_Error_StaticContext:
2069  case IMA_Error_Unrelated:
2070    DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2071                              R.getLookupNameInfo());
2072    return ExprError();
2073  }
2074
2075  llvm_unreachable("unexpected instance member access kind");
2076  return ExprError();
2077}
2078
2079/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2080/// declaration name, generally during template instantiation.
2081/// There's a large number of things which don't need to be done along
2082/// this path.
2083ExprResult
2084Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2085                                        const DeclarationNameInfo &NameInfo) {
2086  DeclContext *DC;
2087  if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
2088    return BuildDependentDeclRefExpr(SS, NameInfo, 0);
2089
2090  if (RequireCompleteDeclContext(SS, DC))
2091    return ExprError();
2092
2093  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2094  LookupQualifiedName(R, DC);
2095
2096  if (R.isAmbiguous())
2097    return ExprError();
2098
2099  if (R.empty()) {
2100    Diag(NameInfo.getLoc(), diag::err_no_member)
2101      << NameInfo.getName() << DC << SS.getRange();
2102    return ExprError();
2103  }
2104
2105  return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2106}
2107
2108/// LookupInObjCMethod - The parser has read a name in, and Sema has
2109/// detected that we're currently inside an ObjC method.  Perform some
2110/// additional lookup.
2111///
2112/// Ideally, most of this would be done by lookup, but there's
2113/// actually quite a lot of extra work involved.
2114///
2115/// Returns a null sentinel to indicate trivial success.
2116ExprResult
2117Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2118                         IdentifierInfo *II, bool AllowBuiltinCreation) {
2119  SourceLocation Loc = Lookup.getNameLoc();
2120  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2121
2122  // There are two cases to handle here.  1) scoped lookup could have failed,
2123  // in which case we should look for an ivar.  2) scoped lookup could have
2124  // found a decl, but that decl is outside the current instance method (i.e.
2125  // a global variable).  In these two cases, we do a lookup for an ivar with
2126  // this name, if the lookup sucedes, we replace it our current decl.
2127
2128  // If we're in a class method, we don't normally want to look for
2129  // ivars.  But if we don't find anything else, and there's an
2130  // ivar, that's an error.
2131  bool IsClassMethod = CurMethod->isClassMethod();
2132
2133  bool LookForIvars;
2134  if (Lookup.empty())
2135    LookForIvars = true;
2136  else if (IsClassMethod)
2137    LookForIvars = false;
2138  else
2139    LookForIvars = (Lookup.isSingleResult() &&
2140                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2141  ObjCInterfaceDecl *IFace = 0;
2142  if (LookForIvars) {
2143    IFace = CurMethod->getClassInterface();
2144    ObjCInterfaceDecl *ClassDeclared;
2145    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2146      // Diagnose using an ivar in a class method.
2147      if (IsClassMethod)
2148        return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2149                         << IV->getDeclName());
2150
2151      // If we're referencing an invalid decl, just return this as a silent
2152      // error node.  The error diagnostic was already emitted on the decl.
2153      if (IV->isInvalidDecl())
2154        return ExprError();
2155
2156      // Check if referencing a field with __attribute__((deprecated)).
2157      if (DiagnoseUseOfDecl(IV, Loc))
2158        return ExprError();
2159
2160      // Diagnose the use of an ivar outside of the declaring class.
2161      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2162          ClassDeclared != IFace)
2163        Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2164
2165      // FIXME: This should use a new expr for a direct reference, don't
2166      // turn this into Self->ivar, just return a BareIVarExpr or something.
2167      IdentifierInfo &II = Context.Idents.get("self");
2168      UnqualifiedId SelfName;
2169      SelfName.setIdentifier(&II, SourceLocation());
2170      CXXScopeSpec SelfScopeSpec;
2171      ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
2172                                              SelfName, false, false);
2173      if (SelfExpr.isInvalid())
2174        return ExprError();
2175
2176      SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2177      if (SelfExpr.isInvalid())
2178        return ExprError();
2179
2180      MarkDeclarationReferenced(Loc, IV);
2181      Expr *base = SelfExpr.take();
2182      base = base->IgnoreParenImpCasts();
2183      if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2184        const NamedDecl *ND = DE->getDecl();
2185        if (!isa<ImplicitParamDecl>(ND)) {
2186          // relax the rule such that it is allowed to have a shadow 'self'
2187          // where stand-alone ivar can be found in this 'self' object.
2188          // This is to match gcc's behavior.
2189          ObjCInterfaceDecl *selfIFace = 0;
2190          if (const ObjCObjectPointerType *OPT =
2191              base->getType()->getAsObjCInterfacePointerType())
2192            selfIFace = OPT->getInterfaceDecl();
2193          if (!selfIFace ||
2194              !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
2195            Diag(Loc, diag::error_implicit_ivar_access)
2196            << IV->getDeclName();
2197            Diag(ND->getLocation(), diag::note_declared_at);
2198            return ExprError();
2199          }
2200        }
2201      }
2202      return Owned(new (Context)
2203                   ObjCIvarRefExpr(IV, IV->getType(), Loc,
2204                                   SelfExpr.take(), true, true));
2205    }
2206  } else if (CurMethod->isInstanceMethod()) {
2207    // We should warn if a local variable hides an ivar.
2208    ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2209    ObjCInterfaceDecl *ClassDeclared;
2210    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2211      if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2212          IFace == ClassDeclared)
2213        Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2214    }
2215  }
2216
2217  if (Lookup.empty() && II && AllowBuiltinCreation) {
2218    // FIXME. Consolidate this with similar code in LookupName.
2219    if (unsigned BuiltinID = II->getBuiltinID()) {
2220      if (!(getLangOptions().CPlusPlus &&
2221            Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2222        NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2223                                           S, Lookup.isForRedeclaration(),
2224                                           Lookup.getNameLoc());
2225        if (D) Lookup.addDecl(D);
2226      }
2227    }
2228  }
2229  // Sentinel value saying that we didn't do anything special.
2230  return Owned((Expr*) 0);
2231}
2232
2233/// \brief Cast a base object to a member's actual type.
2234///
2235/// Logically this happens in three phases:
2236///
2237/// * First we cast from the base type to the naming class.
2238///   The naming class is the class into which we were looking
2239///   when we found the member;  it's the qualifier type if a
2240///   qualifier was provided, and otherwise it's the base type.
2241///
2242/// * Next we cast from the naming class to the declaring class.
2243///   If the member we found was brought into a class's scope by
2244///   a using declaration, this is that class;  otherwise it's
2245///   the class declaring the member.
2246///
2247/// * Finally we cast from the declaring class to the "true"
2248///   declaring class of the member.  This conversion does not
2249///   obey access control.
2250ExprResult
2251Sema::PerformObjectMemberConversion(Expr *From,
2252                                    NestedNameSpecifier *Qualifier,
2253                                    NamedDecl *FoundDecl,
2254                                    NamedDecl *Member) {
2255  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2256  if (!RD)
2257    return Owned(From);
2258
2259  QualType DestRecordType;
2260  QualType DestType;
2261  QualType FromRecordType;
2262  QualType FromType = From->getType();
2263  bool PointerConversions = false;
2264  if (isa<FieldDecl>(Member)) {
2265    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2266
2267    if (FromType->getAs<PointerType>()) {
2268      DestType = Context.getPointerType(DestRecordType);
2269      FromRecordType = FromType->getPointeeType();
2270      PointerConversions = true;
2271    } else {
2272      DestType = DestRecordType;
2273      FromRecordType = FromType;
2274    }
2275  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2276    if (Method->isStatic())
2277      return Owned(From);
2278
2279    DestType = Method->getThisType(Context);
2280    DestRecordType = DestType->getPointeeType();
2281
2282    if (FromType->getAs<PointerType>()) {
2283      FromRecordType = FromType->getPointeeType();
2284      PointerConversions = true;
2285    } else {
2286      FromRecordType = FromType;
2287      DestType = DestRecordType;
2288    }
2289  } else {
2290    // No conversion necessary.
2291    return Owned(From);
2292  }
2293
2294  if (DestType->isDependentType() || FromType->isDependentType())
2295    return Owned(From);
2296
2297  // If the unqualified types are the same, no conversion is necessary.
2298  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2299    return Owned(From);
2300
2301  SourceRange FromRange = From->getSourceRange();
2302  SourceLocation FromLoc = FromRange.getBegin();
2303
2304  ExprValueKind VK = CastCategory(From);
2305
2306  // C++ [class.member.lookup]p8:
2307  //   [...] Ambiguities can often be resolved by qualifying a name with its
2308  //   class name.
2309  //
2310  // If the member was a qualified name and the qualified referred to a
2311  // specific base subobject type, we'll cast to that intermediate type
2312  // first and then to the object in which the member is declared. That allows
2313  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2314  //
2315  //   class Base { public: int x; };
2316  //   class Derived1 : public Base { };
2317  //   class Derived2 : public Base { };
2318  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2319  //
2320  //   void VeryDerived::f() {
2321  //     x = 17; // error: ambiguous base subobjects
2322  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2323  //   }
2324  if (Qualifier) {
2325    QualType QType = QualType(Qualifier->getAsType(), 0);
2326    assert(!QType.isNull() && "lookup done with dependent qualifier?");
2327    assert(QType->isRecordType() && "lookup done with non-record type");
2328
2329    QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2330
2331    // In C++98, the qualifier type doesn't actually have to be a base
2332    // type of the object type, in which case we just ignore it.
2333    // Otherwise build the appropriate casts.
2334    if (IsDerivedFrom(FromRecordType, QRecordType)) {
2335      CXXCastPath BasePath;
2336      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2337                                       FromLoc, FromRange, &BasePath))
2338        return ExprError();
2339
2340      if (PointerConversions)
2341        QType = Context.getPointerType(QType);
2342      From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2343                               VK, &BasePath).take();
2344
2345      FromType = QType;
2346      FromRecordType = QRecordType;
2347
2348      // If the qualifier type was the same as the destination type,
2349      // we're done.
2350      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2351        return Owned(From);
2352    }
2353  }
2354
2355  bool IgnoreAccess = false;
2356
2357  // If we actually found the member through a using declaration, cast
2358  // down to the using declaration's type.
2359  //
2360  // Pointer equality is fine here because only one declaration of a
2361  // class ever has member declarations.
2362  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2363    assert(isa<UsingShadowDecl>(FoundDecl));
2364    QualType URecordType = Context.getTypeDeclType(
2365                           cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2366
2367    // We only need to do this if the naming-class to declaring-class
2368    // conversion is non-trivial.
2369    if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2370      assert(IsDerivedFrom(FromRecordType, URecordType));
2371      CXXCastPath BasePath;
2372      if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2373                                       FromLoc, FromRange, &BasePath))
2374        return ExprError();
2375
2376      QualType UType = URecordType;
2377      if (PointerConversions)
2378        UType = Context.getPointerType(UType);
2379      From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2380                               VK, &BasePath).take();
2381      FromType = UType;
2382      FromRecordType = URecordType;
2383    }
2384
2385    // We don't do access control for the conversion from the
2386    // declaring class to the true declaring class.
2387    IgnoreAccess = true;
2388  }
2389
2390  CXXCastPath BasePath;
2391  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2392                                   FromLoc, FromRange, &BasePath,
2393                                   IgnoreAccess))
2394    return ExprError();
2395
2396  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2397                           VK, &BasePath);
2398}
2399
2400/// \brief Build a MemberExpr AST node.
2401static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
2402                                   const CXXScopeSpec &SS, ValueDecl *Member,
2403                                   DeclAccessPair FoundDecl,
2404                                   const DeclarationNameInfo &MemberNameInfo,
2405                                   QualType Ty,
2406                                   ExprValueKind VK, ExprObjectKind OK,
2407                          const TemplateArgumentListInfo *TemplateArgs = 0) {
2408  return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
2409                            Member, FoundDecl, MemberNameInfo,
2410                            TemplateArgs, Ty, VK, OK);
2411}
2412
2413static ExprResult
2414BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2415                        const CXXScopeSpec &SS, FieldDecl *Field,
2416                        DeclAccessPair FoundDecl,
2417                        const DeclarationNameInfo &MemberNameInfo) {
2418  // x.a is an l-value if 'a' has a reference type. Otherwise:
2419  // x.a is an l-value/x-value/pr-value if the base is (and note
2420  //   that *x is always an l-value), except that if the base isn't
2421  //   an ordinary object then we must have an rvalue.
2422  ExprValueKind VK = VK_LValue;
2423  ExprObjectKind OK = OK_Ordinary;
2424  if (!IsArrow) {
2425    if (BaseExpr->getObjectKind() == OK_Ordinary)
2426      VK = BaseExpr->getValueKind();
2427    else
2428      VK = VK_RValue;
2429  }
2430  if (VK != VK_RValue && Field->isBitField())
2431    OK = OK_BitField;
2432
2433  // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2434  QualType MemberType = Field->getType();
2435  if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2436    MemberType = Ref->getPointeeType();
2437    VK = VK_LValue;
2438  } else {
2439    QualType BaseType = BaseExpr->getType();
2440    if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2441
2442    Qualifiers BaseQuals = BaseType.getQualifiers();
2443
2444    // GC attributes are never picked up by members.
2445    BaseQuals.removeObjCGCAttr();
2446
2447    // CVR attributes from the base are picked up by members,
2448    // except that 'mutable' members don't pick up 'const'.
2449    if (Field->isMutable()) BaseQuals.removeConst();
2450
2451    Qualifiers MemberQuals
2452      = S.Context.getCanonicalType(MemberType).getQualifiers();
2453
2454    // TR 18037 does not allow fields to be declared with address spaces.
2455    assert(!MemberQuals.hasAddressSpace());
2456
2457    Qualifiers Combined = BaseQuals + MemberQuals;
2458    if (Combined != MemberQuals)
2459      MemberType = S.Context.getQualifiedType(MemberType, Combined);
2460  }
2461
2462  S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2463  ExprResult Base =
2464    S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2465                                    FoundDecl, Field);
2466  if (Base.isInvalid())
2467    return ExprError();
2468  return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
2469                                 Field, FoundDecl, MemberNameInfo,
2470                                 MemberType, VK, OK));
2471}
2472
2473/// Builds an implicit member access expression.  The current context
2474/// is known to be an instance method, and the given unqualified lookup
2475/// set is known to contain only instance members, at least one of which
2476/// is from an appropriate type.
2477ExprResult
2478Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2479                              LookupResult &R,
2480                              const TemplateArgumentListInfo *TemplateArgs,
2481                              bool IsKnownInstance) {
2482  assert(!R.empty() && !R.isAmbiguous());
2483
2484  SourceLocation loc = R.getNameLoc();
2485
2486  // We may have found a field within an anonymous union or struct
2487  // (C++ [class.union]).
2488  // FIXME: template-ids inside anonymous structs?
2489  if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2490    return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
2491
2492  // If this is known to be an instance access, go ahead and build an
2493  // implicit 'this' expression now.
2494  // 'this' expression now.
2495  QualType ThisTy = getAndCaptureCurrentThisType();
2496  assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
2497
2498  Expr *baseExpr = 0; // null signifies implicit access
2499  if (IsKnownInstance) {
2500    SourceLocation Loc = R.getNameLoc();
2501    if (SS.getRange().isValid())
2502      Loc = SS.getRange().getBegin();
2503    baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
2504  }
2505
2506  return BuildMemberReferenceExpr(baseExpr, ThisTy,
2507                                  /*OpLoc*/ SourceLocation(),
2508                                  /*IsArrow*/ true,
2509                                  SS,
2510                                  /*FirstQualifierInScope*/ 0,
2511                                  R, TemplateArgs);
2512}
2513
2514bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2515                                      const LookupResult &R,
2516                                      bool HasTrailingLParen) {
2517  // Only when used directly as the postfix-expression of a call.
2518  if (!HasTrailingLParen)
2519    return false;
2520
2521  // Never if a scope specifier was provided.
2522  if (SS.isSet())
2523    return false;
2524
2525  // Only in C++ or ObjC++.
2526  if (!getLangOptions().CPlusPlus)
2527    return false;
2528
2529  // Turn off ADL when we find certain kinds of declarations during
2530  // normal lookup:
2531  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2532    NamedDecl *D = *I;
2533
2534    // C++0x [basic.lookup.argdep]p3:
2535    //     -- a declaration of a class member
2536    // Since using decls preserve this property, we check this on the
2537    // original decl.
2538    if (D->isCXXClassMember())
2539      return false;
2540
2541    // C++0x [basic.lookup.argdep]p3:
2542    //     -- a block-scope function declaration that is not a
2543    //        using-declaration
2544    // NOTE: we also trigger this for function templates (in fact, we
2545    // don't check the decl type at all, since all other decl types
2546    // turn off ADL anyway).
2547    if (isa<UsingShadowDecl>(D))
2548      D = cast<UsingShadowDecl>(D)->getTargetDecl();
2549    else if (D->getDeclContext()->isFunctionOrMethod())
2550      return false;
2551
2552    // C++0x [basic.lookup.argdep]p3:
2553    //     -- a declaration that is neither a function or a function
2554    //        template
2555    // And also for builtin functions.
2556    if (isa<FunctionDecl>(D)) {
2557      FunctionDecl *FDecl = cast<FunctionDecl>(D);
2558
2559      // But also builtin functions.
2560      if (FDecl->getBuiltinID() && FDecl->isImplicit())
2561        return false;
2562    } else if (!isa<FunctionTemplateDecl>(D))
2563      return false;
2564  }
2565
2566  return true;
2567}
2568
2569
2570/// Diagnoses obvious problems with the use of the given declaration
2571/// as an expression.  This is only actually called for lookups that
2572/// were not overloaded, and it doesn't promise that the declaration
2573/// will in fact be used.
2574static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2575  if (isa<TypedefNameDecl>(D)) {
2576    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2577    return true;
2578  }
2579
2580  if (isa<ObjCInterfaceDecl>(D)) {
2581    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2582    return true;
2583  }
2584
2585  if (isa<NamespaceDecl>(D)) {
2586    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2587    return true;
2588  }
2589
2590  return false;
2591}
2592
2593ExprResult
2594Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2595                               LookupResult &R,
2596                               bool NeedsADL) {
2597  // If this is a single, fully-resolved result and we don't need ADL,
2598  // just build an ordinary singleton decl ref.
2599  if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2600    return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2601                                    R.getFoundDecl());
2602
2603  // We only need to check the declaration if there's exactly one
2604  // result, because in the overloaded case the results can only be
2605  // functions and function templates.
2606  if (R.isSingleResult() &&
2607      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2608    return ExprError();
2609
2610  // Otherwise, just build an unresolved lookup expression.  Suppress
2611  // any lookup-related diagnostics; we'll hash these out later, when
2612  // we've picked a target.
2613  R.suppressDiagnostics();
2614
2615  UnresolvedLookupExpr *ULE
2616    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2617                                   SS.getWithLocInContext(Context),
2618                                   R.getLookupNameInfo(),
2619                                   NeedsADL, R.isOverloadedResult(),
2620                                   R.begin(), R.end());
2621
2622  return Owned(ULE);
2623}
2624
2625/// \brief Complete semantic analysis for a reference to the given declaration.
2626ExprResult
2627Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2628                               const DeclarationNameInfo &NameInfo,
2629                               NamedDecl *D) {
2630  assert(D && "Cannot refer to a NULL declaration");
2631  assert(!isa<FunctionTemplateDecl>(D) &&
2632         "Cannot refer unambiguously to a function template");
2633
2634  SourceLocation Loc = NameInfo.getLoc();
2635  if (CheckDeclInExpr(*this, Loc, D))
2636    return ExprError();
2637
2638  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2639    // Specifically diagnose references to class templates that are missing
2640    // a template argument list.
2641    Diag(Loc, diag::err_template_decl_ref)
2642      << Template << SS.getRange();
2643    Diag(Template->getLocation(), diag::note_template_decl_here);
2644    return ExprError();
2645  }
2646
2647  // Make sure that we're referring to a value.
2648  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2649  if (!VD) {
2650    Diag(Loc, diag::err_ref_non_value)
2651      << D << SS.getRange();
2652    Diag(D->getLocation(), diag::note_declared_at);
2653    return ExprError();
2654  }
2655
2656  // Check whether this declaration can be used. Note that we suppress
2657  // this check when we're going to perform argument-dependent lookup
2658  // on this function name, because this might not be the function
2659  // that overload resolution actually selects.
2660  if (DiagnoseUseOfDecl(VD, Loc))
2661    return ExprError();
2662
2663  // Only create DeclRefExpr's for valid Decl's.
2664  if (VD->isInvalidDecl())
2665    return ExprError();
2666
2667  // Handle members of anonymous structs and unions.  If we got here,
2668  // and the reference is to a class member indirect field, then this
2669  // must be the subject of a pointer-to-member expression.
2670  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2671    if (!indirectField->isCXXClassMember())
2672      return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2673                                                      indirectField);
2674
2675  // If the identifier reference is inside a block, and it refers to a value
2676  // that is outside the block, create a BlockDeclRefExpr instead of a
2677  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
2678  // the block is formed.
2679  //
2680  // We do not do this for things like enum constants, global variables, etc,
2681  // as they do not get snapshotted.
2682  //
2683  switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
2684  case CR_Error:
2685    return ExprError();
2686
2687  case CR_Capture:
2688    assert(!SS.isSet() && "referenced local variable with scope specifier?");
2689    return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2690
2691  case CR_CaptureByRef:
2692    assert(!SS.isSet() && "referenced local variable with scope specifier?");
2693    return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
2694
2695  case CR_NoCapture: {
2696    // If this reference is not in a block or if the referenced
2697    // variable is within the block, create a normal DeclRefExpr.
2698
2699    QualType type = VD->getType();
2700    ExprValueKind valueKind = VK_RValue;
2701
2702    switch (D->getKind()) {
2703    // Ignore all the non-ValueDecl kinds.
2704#define ABSTRACT_DECL(kind)
2705#define VALUE(type, base)
2706#define DECL(type, base) \
2707    case Decl::type:
2708#include "clang/AST/DeclNodes.inc"
2709      llvm_unreachable("invalid value decl kind");
2710      return ExprError();
2711
2712    // These shouldn't make it here.
2713    case Decl::ObjCAtDefsField:
2714    case Decl::ObjCIvar:
2715      llvm_unreachable("forming non-member reference to ivar?");
2716      return ExprError();
2717
2718    // Enum constants are always r-values and never references.
2719    // Unresolved using declarations are dependent.
2720    case Decl::EnumConstant:
2721    case Decl::UnresolvedUsingValue:
2722      valueKind = VK_RValue;
2723      break;
2724
2725    // Fields and indirect fields that got here must be for
2726    // pointer-to-member expressions; we just call them l-values for
2727    // internal consistency, because this subexpression doesn't really
2728    // exist in the high-level semantics.
2729    case Decl::Field:
2730    case Decl::IndirectField:
2731      assert(getLangOptions().CPlusPlus &&
2732             "building reference to field in C?");
2733
2734      // These can't have reference type in well-formed programs, but
2735      // for internal consistency we do this anyway.
2736      type = type.getNonReferenceType();
2737      valueKind = VK_LValue;
2738      break;
2739
2740    // Non-type template parameters are either l-values or r-values
2741    // depending on the type.
2742    case Decl::NonTypeTemplateParm: {
2743      if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2744        type = reftype->getPointeeType();
2745        valueKind = VK_LValue; // even if the parameter is an r-value reference
2746        break;
2747      }
2748
2749      // For non-references, we need to strip qualifiers just in case
2750      // the template parameter was declared as 'const int' or whatever.
2751      valueKind = VK_RValue;
2752      type = type.getUnqualifiedType();
2753      break;
2754    }
2755
2756    case Decl::Var:
2757      // In C, "extern void blah;" is valid and is an r-value.
2758      if (!getLangOptions().CPlusPlus &&
2759          !type.hasQualifiers() &&
2760          type->isVoidType()) {
2761        valueKind = VK_RValue;
2762        break;
2763      }
2764      // fallthrough
2765
2766    case Decl::ImplicitParam:
2767    case Decl::ParmVar:
2768      // These are always l-values.
2769      valueKind = VK_LValue;
2770      type = type.getNonReferenceType();
2771      break;
2772
2773    case Decl::Function: {
2774      const FunctionType *fty = type->castAs<FunctionType>();
2775
2776      // If we're referring to a function with an __unknown_anytype
2777      // result type, make the entire expression __unknown_anytype.
2778      if (fty->getResultType() == Context.UnknownAnyTy) {
2779        type = Context.UnknownAnyTy;
2780        valueKind = VK_RValue;
2781        break;
2782      }
2783
2784      // Functions are l-values in C++.
2785      if (getLangOptions().CPlusPlus) {
2786        valueKind = VK_LValue;
2787        break;
2788      }
2789
2790      // C99 DR 316 says that, if a function type comes from a
2791      // function definition (without a prototype), that type is only
2792      // used for checking compatibility. Therefore, when referencing
2793      // the function, we pretend that we don't have the full function
2794      // type.
2795      if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2796          isa<FunctionProtoType>(fty))
2797        type = Context.getFunctionNoProtoType(fty->getResultType(),
2798                                              fty->getExtInfo());
2799
2800      // Functions are r-values in C.
2801      valueKind = VK_RValue;
2802      break;
2803    }
2804
2805    case Decl::CXXMethod:
2806      // If we're referring to a method with an __unknown_anytype
2807      // result type, make the entire expression __unknown_anytype.
2808      // This should only be possible with a type written directly.
2809      if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2810        if (proto->getResultType() == Context.UnknownAnyTy) {
2811          type = Context.UnknownAnyTy;
2812          valueKind = VK_RValue;
2813          break;
2814        }
2815
2816      // C++ methods are l-values if static, r-values if non-static.
2817      if (cast<CXXMethodDecl>(VD)->isStatic()) {
2818        valueKind = VK_LValue;
2819        break;
2820      }
2821      // fallthrough
2822
2823    case Decl::CXXConversion:
2824    case Decl::CXXDestructor:
2825    case Decl::CXXConstructor:
2826      valueKind = VK_RValue;
2827      break;
2828    }
2829
2830    return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2831  }
2832
2833  }
2834
2835  llvm_unreachable("unknown capture result");
2836  return ExprError();
2837}
2838
2839ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2840  PredefinedExpr::IdentType IT;
2841
2842  switch (Kind) {
2843  default: assert(0 && "Unknown simple primary expr!");
2844  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2845  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2846  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2847  }
2848
2849  // Pre-defined identifiers are of type char[x], where x is the length of the
2850  // string.
2851
2852  Decl *currentDecl = getCurFunctionOrMethodDecl();
2853  if (!currentDecl && getCurBlock())
2854    currentDecl = getCurBlock()->TheDecl;
2855  if (!currentDecl) {
2856    Diag(Loc, diag::ext_predef_outside_function);
2857    currentDecl = Context.getTranslationUnitDecl();
2858  }
2859
2860  QualType ResTy;
2861  if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2862    ResTy = Context.DependentTy;
2863  } else {
2864    unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2865
2866    llvm::APInt LengthI(32, Length + 1);
2867    ResTy = Context.CharTy.withConst();
2868    ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2869  }
2870  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2871}
2872
2873ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
2874  llvm::SmallString<16> CharBuffer;
2875  bool Invalid = false;
2876  llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2877  if (Invalid)
2878    return ExprError();
2879
2880  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2881                            PP);
2882  if (Literal.hadError())
2883    return ExprError();
2884
2885  QualType Ty;
2886  if (!getLangOptions().CPlusPlus)
2887    Ty = Context.IntTy;   // 'x' and L'x' -> int in C.
2888  else if (Literal.isWide())
2889    Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
2890  else if (Literal.isMultiChar())
2891    Ty = Context.IntTy;   // 'wxyz' -> int in C++.
2892  else
2893    Ty = Context.CharTy;  // 'x' -> char in C++
2894
2895  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2896                                              Literal.isWide(),
2897                                              Ty, Tok.getLocation()));
2898}
2899
2900ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
2901  // Fast path for a single digit (which is quite common).  A single digit
2902  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2903  if (Tok.getLength() == 1) {
2904    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2905    unsigned IntSize = Context.Target.getIntWidth();
2906    return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
2907                    Context.IntTy, Tok.getLocation()));
2908  }
2909
2910  llvm::SmallString<512> IntegerBuffer;
2911  // Add padding so that NumericLiteralParser can overread by one character.
2912  IntegerBuffer.resize(Tok.getLength()+1);
2913  const char *ThisTokBegin = &IntegerBuffer[0];
2914
2915  // Get the spelling of the token, which eliminates trigraphs, etc.
2916  bool Invalid = false;
2917  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2918  if (Invalid)
2919    return ExprError();
2920
2921  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2922                               Tok.getLocation(), PP);
2923  if (Literal.hadError)
2924    return ExprError();
2925
2926  Expr *Res;
2927
2928  if (Literal.isFloatingLiteral()) {
2929    QualType Ty;
2930    if (Literal.isFloat)
2931      Ty = Context.FloatTy;
2932    else if (!Literal.isLong)
2933      Ty = Context.DoubleTy;
2934    else
2935      Ty = Context.LongDoubleTy;
2936
2937    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2938
2939    using llvm::APFloat;
2940    APFloat Val(Format);
2941
2942    APFloat::opStatus result = Literal.GetFloatValue(Val);
2943
2944    // Overflow is always an error, but underflow is only an error if
2945    // we underflowed to zero (APFloat reports denormals as underflow).
2946    if ((result & APFloat::opOverflow) ||
2947        ((result & APFloat::opUnderflow) && Val.isZero())) {
2948      unsigned diagnostic;
2949      llvm::SmallString<20> buffer;
2950      if (result & APFloat::opOverflow) {
2951        diagnostic = diag::warn_float_overflow;
2952        APFloat::getLargest(Format).toString(buffer);
2953      } else {
2954        diagnostic = diag::warn_float_underflow;
2955        APFloat::getSmallest(Format).toString(buffer);
2956      }
2957
2958      Diag(Tok.getLocation(), diagnostic)
2959        << Ty
2960        << llvm::StringRef(buffer.data(), buffer.size());
2961    }
2962
2963    bool isExact = (result == APFloat::opOK);
2964    Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
2965
2966    if (Ty == Context.DoubleTy) {
2967      if (getLangOptions().SinglePrecisionConstants) {
2968        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2969      } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2970        Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2971        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2972      }
2973    }
2974  } else if (!Literal.isIntegerLiteral()) {
2975    return ExprError();
2976  } else {
2977    QualType Ty;
2978
2979    // long long is a C99 feature.
2980    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
2981        Literal.isLongLong)
2982      Diag(Tok.getLocation(), diag::ext_longlong);
2983
2984    // Get the value in the widest-possible width.
2985    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
2986
2987    if (Literal.GetIntegerValue(ResultVal)) {
2988      // If this value didn't fit into uintmax_t, warn and force to ull.
2989      Diag(Tok.getLocation(), diag::warn_integer_too_large);
2990      Ty = Context.UnsignedLongLongTy;
2991      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2992             "long long is not intmax_t?");
2993    } else {
2994      // If this value fits into a ULL, try to figure out what else it fits into
2995      // according to the rules of C99 6.4.4.1p5.
2996
2997      // Octal, Hexadecimal, and integers with a U suffix are allowed to
2998      // be an unsigned int.
2999      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3000
3001      // Check from smallest to largest, picking the smallest type we can.
3002      unsigned Width = 0;
3003      if (!Literal.isLong && !Literal.isLongLong) {
3004        // Are int/unsigned possibilities?
3005        unsigned IntSize = Context.Target.getIntWidth();
3006
3007        // Does it fit in a unsigned int?
3008        if (ResultVal.isIntN(IntSize)) {
3009          // Does it fit in a signed int?
3010          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3011            Ty = Context.IntTy;
3012          else if (AllowUnsigned)
3013            Ty = Context.UnsignedIntTy;
3014          Width = IntSize;
3015        }
3016      }
3017
3018      // Are long/unsigned long possibilities?
3019      if (Ty.isNull() && !Literal.isLongLong) {
3020        unsigned LongSize = Context.Target.getLongWidth();
3021
3022        // Does it fit in a unsigned long?
3023        if (ResultVal.isIntN(LongSize)) {
3024          // Does it fit in a signed long?
3025          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3026            Ty = Context.LongTy;
3027          else if (AllowUnsigned)
3028            Ty = Context.UnsignedLongTy;
3029          Width = LongSize;
3030        }
3031      }
3032
3033      // Finally, check long long if needed.
3034      if (Ty.isNull()) {
3035        unsigned LongLongSize = Context.Target.getLongLongWidth();
3036
3037        // Does it fit in a unsigned long long?
3038        if (ResultVal.isIntN(LongLongSize)) {
3039          // Does it fit in a signed long long?
3040          // To be compatible with MSVC, hex integer literals ending with the
3041          // LL or i64 suffix are always signed in Microsoft mode.
3042          if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3043              (getLangOptions().Microsoft && Literal.isLongLong)))
3044            Ty = Context.LongLongTy;
3045          else if (AllowUnsigned)
3046            Ty = Context.UnsignedLongLongTy;
3047          Width = LongLongSize;
3048        }
3049      }
3050
3051      // If we still couldn't decide a type, we probably have something that
3052      // does not fit in a signed long long, but has no U suffix.
3053      if (Ty.isNull()) {
3054        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3055        Ty = Context.UnsignedLongLongTy;
3056        Width = Context.Target.getLongLongWidth();
3057      }
3058
3059      if (ResultVal.getBitWidth() != Width)
3060        ResultVal = ResultVal.trunc(Width);
3061    }
3062    Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3063  }
3064
3065  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3066  if (Literal.isImaginary)
3067    Res = new (Context) ImaginaryLiteral(Res,
3068                                        Context.getComplexType(Res->getType()));
3069
3070  return Owned(Res);
3071}
3072
3073ExprResult Sema::ActOnParenExpr(SourceLocation L,
3074                                              SourceLocation R, Expr *E) {
3075  assert((E != 0) && "ActOnParenExpr() missing expr");
3076  return Owned(new (Context) ParenExpr(L, R, E));
3077}
3078
3079static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3080                                         SourceLocation Loc,
3081                                         SourceRange ArgRange) {
3082  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3083  // scalar or vector data type argument..."
3084  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3085  // type (C99 6.2.5p18) or void.
3086  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3087    S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3088      << T << ArgRange;
3089    return true;
3090  }
3091
3092  assert((T->isVoidType() || !T->isIncompleteType()) &&
3093         "Scalar types should always be complete");
3094  return false;
3095}
3096
3097static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3098                                           SourceLocation Loc,
3099                                           SourceRange ArgRange,
3100                                           UnaryExprOrTypeTrait TraitKind) {
3101  // C99 6.5.3.4p1:
3102  if (T->isFunctionType()) {
3103    // alignof(function) is allowed as an extension.
3104    if (TraitKind == UETT_SizeOf)
3105      S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
3106    return false;
3107  }
3108
3109  // Allow sizeof(void)/alignof(void) as an extension.
3110  if (T->isVoidType()) {
3111    S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
3112    return false;
3113  }
3114
3115  return true;
3116}
3117
3118static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3119                                             SourceLocation Loc,
3120                                             SourceRange ArgRange,
3121                                             UnaryExprOrTypeTrait TraitKind) {
3122  // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
3123  if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
3124    S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3125      << T << (TraitKind == UETT_SizeOf)
3126      << ArgRange;
3127    return true;
3128  }
3129
3130  return false;
3131}
3132
3133/// \brief Check the constrains on expression operands to unary type expression
3134/// and type traits.
3135///
3136/// Completes any types necessary and validates the constraints on the operand
3137/// expression. The logic mostly mirrors the type-based overload, but may modify
3138/// the expression as it completes the type for that expression through template
3139/// instantiation, etc.
3140bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
3141                                            UnaryExprOrTypeTrait ExprKind) {
3142  QualType ExprTy = Op->getType();
3143
3144  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3145  //   the result is the size of the referenced type."
3146  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3147  //   result shall be the alignment of the referenced type."
3148  if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3149    ExprTy = Ref->getPointeeType();
3150
3151  if (ExprKind == UETT_VecStep)
3152    return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3153                                        Op->getSourceRange());
3154
3155  // Whitelist some types as extensions
3156  if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3157                                      Op->getSourceRange(), ExprKind))
3158    return false;
3159
3160  if (RequireCompleteExprType(Op,
3161                              PDiag(diag::err_sizeof_alignof_incomplete_type)
3162                              << ExprKind << Op->getSourceRange(),
3163                              std::make_pair(SourceLocation(), PDiag(0))))
3164    return true;
3165
3166  // Completeing the expression's type may have changed it.
3167  ExprTy = Op->getType();
3168  if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3169    ExprTy = Ref->getPointeeType();
3170
3171  if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
3172                                       Op->getSourceRange(), ExprKind))
3173    return true;
3174
3175  if (ExprKind == UETT_SizeOf) {
3176    if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
3177      if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3178        QualType OType = PVD->getOriginalType();
3179        QualType Type = PVD->getType();
3180        if (Type->isPointerType() && OType->isArrayType()) {
3181          Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
3182            << Type << OType;
3183          Diag(PVD->getLocation(), diag::note_declared_at);
3184        }
3185      }
3186    }
3187  }
3188
3189  return false;
3190}
3191
3192/// \brief Check the constraints on operands to unary expression and type
3193/// traits.
3194///
3195/// This will complete any types necessary, and validate the various constraints
3196/// on those operands.
3197///
3198/// The UsualUnaryConversions() function is *not* called by this routine.
3199/// C99 6.3.2.1p[2-4] all state:
3200///   Except when it is the operand of the sizeof operator ...
3201///
3202/// C++ [expr.sizeof]p4
3203///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3204///   standard conversions are not applied to the operand of sizeof.
3205///
3206/// This policy is followed for all of the unary trait expressions.
3207bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3208                                            SourceLocation OpLoc,
3209                                            SourceRange ExprRange,
3210                                            UnaryExprOrTypeTrait ExprKind) {
3211  if (exprType->isDependentType())
3212    return false;
3213
3214  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3215  //   the result is the size of the referenced type."
3216  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3217  //   result shall be the alignment of the referenced type."
3218  if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3219    exprType = Ref->getPointeeType();
3220
3221  if (ExprKind == UETT_VecStep)
3222    return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
3223
3224  // Whitelist some types as extensions
3225  if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
3226                                      ExprKind))
3227    return false;
3228
3229  if (RequireCompleteType(OpLoc, exprType,
3230                          PDiag(diag::err_sizeof_alignof_incomplete_type)
3231                          << ExprKind << ExprRange))
3232    return true;
3233
3234  if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
3235                                       ExprKind))
3236    return true;
3237
3238  return false;
3239}
3240
3241static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3242  E = E->IgnoreParens();
3243
3244  // alignof decl is always ok.
3245  if (isa<DeclRefExpr>(E))
3246    return false;
3247
3248  // Cannot know anything else if the expression is dependent.
3249  if (E->isTypeDependent())
3250    return false;
3251
3252  if (E->getBitField()) {
3253    S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3254       << 1 << E->getSourceRange();
3255    return true;
3256  }
3257
3258  // Alignment of a field access is always okay, so long as it isn't a
3259  // bit-field.
3260  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3261    if (isa<FieldDecl>(ME->getMemberDecl()))
3262      return false;
3263
3264  return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3265}
3266
3267bool Sema::CheckVecStepExpr(Expr *E) {
3268  E = E->IgnoreParens();
3269
3270  // Cannot know anything else if the expression is dependent.
3271  if (E->isTypeDependent())
3272    return false;
3273
3274  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3275}
3276
3277/// \brief Build a sizeof or alignof expression given a type operand.
3278ExprResult
3279Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3280                                     SourceLocation OpLoc,
3281                                     UnaryExprOrTypeTrait ExprKind,
3282                                     SourceRange R) {
3283  if (!TInfo)
3284    return ExprError();
3285
3286  QualType T = TInfo->getType();
3287
3288  if (!T->isDependentType() &&
3289      CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3290    return ExprError();
3291
3292  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3293  return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3294                                                      Context.getSizeType(),
3295                                                      OpLoc, R.getEnd()));
3296}
3297
3298/// \brief Build a sizeof or alignof expression given an expression
3299/// operand.
3300ExprResult
3301Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3302                                     UnaryExprOrTypeTrait ExprKind) {
3303  // Verify that the operand is valid.
3304  bool isInvalid = false;
3305  if (E->isTypeDependent()) {
3306    // Delay type-checking for type-dependent expressions.
3307  } else if (ExprKind == UETT_AlignOf) {
3308    isInvalid = CheckAlignOfExpr(*this, E);
3309  } else if (ExprKind == UETT_VecStep) {
3310    isInvalid = CheckVecStepExpr(E);
3311  } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3312    Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3313    isInvalid = true;
3314  } else if (E->getType()->isPlaceholderType()) {
3315    ExprResult PE = CheckPlaceholderExpr(E);
3316    if (PE.isInvalid()) return ExprError();
3317    return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind);
3318  } else {
3319    isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3320  }
3321
3322  if (isInvalid)
3323    return ExprError();
3324
3325  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3326  return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3327      ExprKind, E, Context.getSizeType(), OpLoc,
3328      E->getSourceRange().getEnd()));
3329}
3330
3331/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3332/// expr and the same for @c alignof and @c __alignof
3333/// Note that the ArgRange is invalid if isType is false.
3334ExprResult
3335Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3336                                    UnaryExprOrTypeTrait ExprKind, bool isType,
3337                                    void *TyOrEx, const SourceRange &ArgRange) {
3338  // If error parsing type, ignore.
3339  if (TyOrEx == 0) return ExprError();
3340
3341  if (isType) {
3342    TypeSourceInfo *TInfo;
3343    (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3344    return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3345  }
3346
3347  Expr *ArgEx = (Expr *)TyOrEx;
3348  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3349  return move(Result);
3350}
3351
3352static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3353                                     bool isReal) {
3354  if (V.get()->isTypeDependent())
3355    return S.Context.DependentTy;
3356
3357  // _Real and _Imag are only l-values for normal l-values.
3358  if (V.get()->getObjectKind() != OK_Ordinary) {
3359    V = S.DefaultLvalueConversion(V.take());
3360    if (V.isInvalid())
3361      return QualType();
3362  }
3363
3364  // These operators return the element type of a complex type.
3365  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3366    return CT->getElementType();
3367
3368  // Otherwise they pass through real integer and floating point types here.
3369  if (V.get()->getType()->isArithmeticType())
3370    return V.get()->getType();
3371
3372  // Test for placeholders.
3373  ExprResult PR = S.CheckPlaceholderExpr(V.get());
3374  if (PR.isInvalid()) return QualType();
3375  if (PR.get() != V.get()) {
3376    V = move(PR);
3377    return CheckRealImagOperand(S, V, Loc, isReal);
3378  }
3379
3380  // Reject anything else.
3381  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3382    << (isReal ? "__real" : "__imag");
3383  return QualType();
3384}
3385
3386
3387
3388ExprResult
3389Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3390                          tok::TokenKind Kind, Expr *Input) {
3391  UnaryOperatorKind Opc;
3392  switch (Kind) {
3393  default: assert(0 && "Unknown unary op!");
3394  case tok::plusplus:   Opc = UO_PostInc; break;
3395  case tok::minusminus: Opc = UO_PostDec; break;
3396  }
3397
3398  return BuildUnaryOp(S, OpLoc, Opc, Input);
3399}
3400
3401/// Expressions of certain arbitrary types are forbidden by C from
3402/// having l-value type.  These are:
3403///   - 'void', but not qualified void
3404///   - function types
3405///
3406/// The exact rule here is C99 6.3.2.1:
3407///   An lvalue is an expression with an object type or an incomplete
3408///   type other than void.
3409static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3410  return ((T->isVoidType() && !T.hasQualifiers()) ||
3411          T->isFunctionType());
3412}
3413
3414ExprResult
3415Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3416                              Expr *Idx, SourceLocation RLoc) {
3417  // Since this might be a postfix expression, get rid of ParenListExprs.
3418  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3419  if (Result.isInvalid()) return ExprError();
3420  Base = Result.take();
3421
3422  Expr *LHSExp = Base, *RHSExp = Idx;
3423
3424  if (getLangOptions().CPlusPlus &&
3425      (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3426    return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3427                                                  Context.DependentTy,
3428                                                  VK_LValue, OK_Ordinary,
3429                                                  RLoc));
3430  }
3431
3432  if (getLangOptions().CPlusPlus &&
3433      (LHSExp->getType()->isRecordType() ||
3434       LHSExp->getType()->isEnumeralType() ||
3435       RHSExp->getType()->isRecordType() ||
3436       RHSExp->getType()->isEnumeralType())) {
3437    return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3438  }
3439
3440  return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3441}
3442
3443
3444ExprResult
3445Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3446                                     Expr *Idx, SourceLocation RLoc) {
3447  Expr *LHSExp = Base;
3448  Expr *RHSExp = Idx;
3449
3450  // Perform default conversions.
3451  if (!LHSExp->getType()->getAs<VectorType>()) {
3452    ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3453    if (Result.isInvalid())
3454      return ExprError();
3455    LHSExp = Result.take();
3456  }
3457  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3458  if (Result.isInvalid())
3459    return ExprError();
3460  RHSExp = Result.take();
3461
3462  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3463  ExprValueKind VK = VK_LValue;
3464  ExprObjectKind OK = OK_Ordinary;
3465
3466  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3467  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3468  // in the subscript position. As a result, we need to derive the array base
3469  // and index from the expression types.
3470  Expr *BaseExpr, *IndexExpr;
3471  QualType ResultType;
3472  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3473    BaseExpr = LHSExp;
3474    IndexExpr = RHSExp;
3475    ResultType = Context.DependentTy;
3476  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3477    BaseExpr = LHSExp;
3478    IndexExpr = RHSExp;
3479    ResultType = PTy->getPointeeType();
3480  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3481     // Handle the uncommon case of "123[Ptr]".
3482    BaseExpr = RHSExp;
3483    IndexExpr = LHSExp;
3484    ResultType = PTy->getPointeeType();
3485  } else if (const ObjCObjectPointerType *PTy =
3486               LHSTy->getAs<ObjCObjectPointerType>()) {
3487    BaseExpr = LHSExp;
3488    IndexExpr = RHSExp;
3489    ResultType = PTy->getPointeeType();
3490  } else if (const ObjCObjectPointerType *PTy =
3491               RHSTy->getAs<ObjCObjectPointerType>()) {
3492     // Handle the uncommon case of "123[Ptr]".
3493    BaseExpr = RHSExp;
3494    IndexExpr = LHSExp;
3495    ResultType = PTy->getPointeeType();
3496  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3497    BaseExpr = LHSExp;    // vectors: V[123]
3498    IndexExpr = RHSExp;
3499    VK = LHSExp->getValueKind();
3500    if (VK != VK_RValue)
3501      OK = OK_VectorComponent;
3502
3503    // FIXME: need to deal with const...
3504    ResultType = VTy->getElementType();
3505  } else if (LHSTy->isArrayType()) {
3506    // If we see an array that wasn't promoted by
3507    // DefaultFunctionArrayLvalueConversion, it must be an array that
3508    // wasn't promoted because of the C90 rule that doesn't
3509    // allow promoting non-lvalue arrays.  Warn, then
3510    // force the promotion here.
3511    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3512        LHSExp->getSourceRange();
3513    LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3514                               CK_ArrayToPointerDecay).take();
3515    LHSTy = LHSExp->getType();
3516
3517    BaseExpr = LHSExp;
3518    IndexExpr = RHSExp;
3519    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3520  } else if (RHSTy->isArrayType()) {
3521    // Same as previous, except for 123[f().a] case
3522    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3523        RHSExp->getSourceRange();
3524    RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3525                               CK_ArrayToPointerDecay).take();
3526    RHSTy = RHSExp->getType();
3527
3528    BaseExpr = RHSExp;
3529    IndexExpr = LHSExp;
3530    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3531  } else {
3532    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3533       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3534  }
3535  // C99 6.5.2.1p1
3536  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3537    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3538                     << IndexExpr->getSourceRange());
3539
3540  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3541       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3542         && !IndexExpr->isTypeDependent())
3543    Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3544
3545  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3546  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3547  // type. Note that Functions are not objects, and that (in C99 parlance)
3548  // incomplete types are not object types.
3549  if (ResultType->isFunctionType()) {
3550    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3551      << ResultType << BaseExpr->getSourceRange();
3552    return ExprError();
3553  }
3554
3555  if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3556    // GNU extension: subscripting on pointer to void
3557    Diag(LLoc, diag::ext_gnu_void_ptr)
3558      << BaseExpr->getSourceRange();
3559
3560    // C forbids expressions of unqualified void type from being l-values.
3561    // See IsCForbiddenLValueType.
3562    if (!ResultType.hasQualifiers()) VK = VK_RValue;
3563  } else if (!ResultType->isDependentType() &&
3564      RequireCompleteType(LLoc, ResultType,
3565                          PDiag(diag::err_subscript_incomplete_type)
3566                            << BaseExpr->getSourceRange()))
3567    return ExprError();
3568
3569  // Diagnose bad cases where we step over interface counts.
3570  if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
3571    Diag(LLoc, diag::err_subscript_nonfragile_interface)
3572      << ResultType << BaseExpr->getSourceRange();
3573    return ExprError();
3574  }
3575
3576  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3577         !IsCForbiddenLValueType(Context, ResultType));
3578
3579  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3580                                                ResultType, VK, OK, RLoc));
3581}
3582
3583/// Check an ext-vector component access expression.
3584///
3585/// VK should be set in advance to the value kind of the base
3586/// expression.
3587static QualType
3588CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3589                        SourceLocation OpLoc, const IdentifierInfo *CompName,
3590                        SourceLocation CompLoc) {
3591  // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3592  // see FIXME there.
3593  //
3594  // FIXME: This logic can be greatly simplified by splitting it along
3595  // halving/not halving and reworking the component checking.
3596  const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
3597
3598  // The vector accessor can't exceed the number of elements.
3599  const char *compStr = CompName->getNameStart();
3600
3601  // This flag determines whether or not the component is one of the four
3602  // special names that indicate a subset of exactly half the elements are
3603  // to be selected.
3604  bool HalvingSwizzle = false;
3605
3606  // This flag determines whether or not CompName has an 's' char prefix,
3607  // indicating that it is a string of hex values to be used as vector indices.
3608  bool HexSwizzle = *compStr == 's' || *compStr == 'S';
3609
3610  bool HasRepeated = false;
3611  bool HasIndex[16] = {};
3612
3613  int Idx;
3614
3615  // Check that we've found one of the special components, or that the component
3616  // names must come from the same set.
3617  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
3618      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3619    HalvingSwizzle = true;
3620  } else if (!HexSwizzle &&
3621             (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3622    do {
3623      if (HasIndex[Idx]) HasRepeated = true;
3624      HasIndex[Idx] = true;
3625      compStr++;
3626    } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3627  } else {
3628    if (HexSwizzle) compStr++;
3629    while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3630      if (HasIndex[Idx]) HasRepeated = true;
3631      HasIndex[Idx] = true;
3632      compStr++;
3633    }
3634  }
3635
3636  if (!HalvingSwizzle && *compStr) {
3637    // We didn't get to the end of the string. This means the component names
3638    // didn't come from the same set *or* we encountered an illegal name.
3639    S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
3640      << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
3641    return QualType();
3642  }
3643
3644  // Ensure no component accessor exceeds the width of the vector type it
3645  // operates on.
3646  if (!HalvingSwizzle) {
3647    compStr = CompName->getNameStart();
3648
3649    if (HexSwizzle)
3650      compStr++;
3651
3652    while (*compStr) {
3653      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
3654        S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
3655          << baseType << SourceRange(CompLoc);
3656        return QualType();
3657      }
3658    }
3659  }
3660
3661  // The component accessor looks fine - now we need to compute the actual type.
3662  // The vector type is implied by the component accessor. For example,
3663  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
3664  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
3665  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
3666  unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
3667                                     : CompName->getLength();
3668  if (HexSwizzle)
3669    CompSize--;
3670
3671  if (CompSize == 1)
3672    return vecType->getElementType();
3673
3674  if (HasRepeated) VK = VK_RValue;
3675
3676  QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
3677  // Now look up the TypeDefDecl from the vector type. Without this,
3678  // diagostics look bad. We want extended vector types to appear built-in.
3679  for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3680    if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3681      return S.Context.getTypedefType(S.ExtVectorDecls[i]);
3682  }
3683  return VT; // should never get here (a typedef type should always be found).
3684}
3685
3686static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
3687                                                IdentifierInfo *Member,
3688                                                const Selector &Sel,
3689                                                ASTContext &Context) {
3690  if (Member)
3691    if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3692      return PD;
3693  if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
3694    return OMD;
3695
3696  for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3697       E = PDecl->protocol_end(); I != E; ++I) {
3698    if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3699                                                           Context))
3700      return D;
3701  }
3702  return 0;
3703}
3704
3705static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3706                                      IdentifierInfo *Member,
3707                                      const Selector &Sel,
3708                                      ASTContext &Context) {
3709  // Check protocols on qualified interfaces.
3710  Decl *GDecl = 0;
3711  for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3712       E = QIdTy->qual_end(); I != E; ++I) {
3713    if (Member)
3714      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3715        GDecl = PD;
3716        break;
3717      }
3718    // Also must look for a getter or setter name which uses property syntax.
3719    if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
3720      GDecl = OMD;
3721      break;
3722    }
3723  }
3724  if (!GDecl) {
3725    for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3726         E = QIdTy->qual_end(); I != E; ++I) {
3727      // Search in the protocol-qualifier list of current protocol.
3728      GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3729                                                       Context);
3730      if (GDecl)
3731        return GDecl;
3732    }
3733  }
3734  return GDecl;
3735}
3736
3737ExprResult
3738Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
3739                               bool IsArrow, SourceLocation OpLoc,
3740                               const CXXScopeSpec &SS,
3741                               NamedDecl *FirstQualifierInScope,
3742                               const DeclarationNameInfo &NameInfo,
3743                               const TemplateArgumentListInfo *TemplateArgs) {
3744  // Even in dependent contexts, try to diagnose base expressions with
3745  // obviously wrong types, e.g.:
3746  //
3747  // T* t;
3748  // t.f;
3749  //
3750  // In Obj-C++, however, the above expression is valid, since it could be
3751  // accessing the 'f' property if T is an Obj-C interface. The extra check
3752  // allows this, while still reporting an error if T is a struct pointer.
3753  if (!IsArrow) {
3754    const PointerType *PT = BaseType->getAs<PointerType>();
3755    if (PT && (!getLangOptions().ObjC1 ||
3756               PT->getPointeeType()->isRecordType())) {
3757      assert(BaseExpr && "cannot happen with implicit member accesses");
3758      Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
3759        << BaseType << BaseExpr->getSourceRange();
3760      return ExprError();
3761    }
3762  }
3763
3764  assert(BaseType->isDependentType() ||
3765         NameInfo.getName().isDependentName() ||
3766         isDependentScopeSpecifier(SS));
3767
3768  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
3769  // must have pointer type, and the accessed type is the pointee.
3770  return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
3771                                                   IsArrow, OpLoc,
3772                                               SS.getWithLocInContext(Context),
3773                                                   FirstQualifierInScope,
3774                                                   NameInfo, TemplateArgs));
3775}
3776
3777/// We know that the given qualified member reference points only to
3778/// declarations which do not belong to the static type of the base
3779/// expression.  Diagnose the problem.
3780static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3781                                             Expr *BaseExpr,
3782                                             QualType BaseType,
3783                                             const CXXScopeSpec &SS,
3784                                             NamedDecl *rep,
3785                                       const DeclarationNameInfo &nameInfo) {
3786  // If this is an implicit member access, use a different set of
3787  // diagnostics.
3788  if (!BaseExpr)
3789    return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
3790
3791  SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3792    << SS.getRange() << rep << BaseType;
3793}
3794
3795// Check whether the declarations we found through a nested-name
3796// specifier in a member expression are actually members of the base
3797// type.  The restriction here is:
3798//
3799//   C++ [expr.ref]p2:
3800//     ... In these cases, the id-expression shall name a
3801//     member of the class or of one of its base classes.
3802//
3803// So it's perfectly legitimate for the nested-name specifier to name
3804// an unrelated class, and for us to find an overload set including
3805// decls from classes which are not superclasses, as long as the decl
3806// we actually pick through overload resolution is from a superclass.
3807bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3808                                         QualType BaseType,
3809                                         const CXXScopeSpec &SS,
3810                                         const LookupResult &R) {
3811  const RecordType *BaseRT = BaseType->getAs<RecordType>();
3812  if (!BaseRT) {
3813    // We can't check this yet because the base type is still
3814    // dependent.
3815    assert(BaseType->isDependentType());
3816    return false;
3817  }
3818  CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
3819
3820  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3821    // If this is an implicit member reference and we find a
3822    // non-instance member, it's not an error.
3823    if (!BaseExpr && !(*I)->isCXXInstanceMember())
3824      return false;
3825
3826    // Note that we use the DC of the decl, not the underlying decl.
3827    DeclContext *DC = (*I)->getDeclContext();
3828    while (DC->isTransparentContext())
3829      DC = DC->getParent();
3830
3831    if (!DC->isRecord())
3832      continue;
3833
3834    llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
3835    MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
3836
3837    if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3838      return false;
3839  }
3840
3841  DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3842                                   R.getRepresentativeDecl(),
3843                                   R.getLookupNameInfo());
3844  return true;
3845}
3846
3847static bool
3848LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3849                         SourceRange BaseRange, const RecordType *RTy,
3850                         SourceLocation OpLoc, CXXScopeSpec &SS,
3851                         bool HasTemplateArgs) {
3852  RecordDecl *RDecl = RTy->getDecl();
3853  if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
3854                              SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
3855                                    << BaseRange))
3856    return true;
3857
3858  if (HasTemplateArgs) {
3859    // LookupTemplateName doesn't expect these both to exist simultaneously.
3860    QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3861
3862    bool MOUS;
3863    SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3864    return false;
3865  }
3866
3867  DeclContext *DC = RDecl;
3868  if (SS.isSet()) {
3869    // If the member name was a qualified-id, look into the
3870    // nested-name-specifier.
3871    DC = SemaRef.computeDeclContext(SS, false);
3872
3873    if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
3874      SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3875        << SS.getRange() << DC;
3876      return true;
3877    }
3878
3879    assert(DC && "Cannot handle non-computable dependent contexts in lookup");
3880
3881    if (!isa<TypeDecl>(DC)) {
3882      SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3883        << DC << SS.getRange();
3884      return true;
3885    }
3886  }
3887
3888  // The record definition is complete, now look up the member.
3889  SemaRef.LookupQualifiedName(R, DC);
3890
3891  if (!R.empty())
3892    return false;
3893
3894  // We didn't find anything with the given name, so try to correct
3895  // for typos.
3896  DeclarationName Name = R.getLookupName();
3897  if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
3898      !R.empty() &&
3899      (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3900    SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3901      << Name << DC << R.getLookupName() << SS.getRange()
3902      << FixItHint::CreateReplacement(R.getNameLoc(),
3903                                      R.getLookupName().getAsString());
3904    if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3905      SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3906        << ND->getDeclName();
3907    return false;
3908  } else {
3909    R.clear();
3910    R.setLookupName(Name);
3911  }
3912
3913  return false;
3914}
3915
3916ExprResult
3917Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3918                               SourceLocation OpLoc, bool IsArrow,
3919                               CXXScopeSpec &SS,
3920                               NamedDecl *FirstQualifierInScope,
3921                               const DeclarationNameInfo &NameInfo,
3922                               const TemplateArgumentListInfo *TemplateArgs) {
3923  if (BaseType->isDependentType() ||
3924      (SS.isSet() && isDependentScopeSpecifier(SS)))
3925    return ActOnDependentMemberExpr(Base, BaseType,
3926                                    IsArrow, OpLoc,
3927                                    SS, FirstQualifierInScope,
3928                                    NameInfo, TemplateArgs);
3929
3930  LookupResult R(*this, NameInfo, LookupMemberName);
3931
3932  // Implicit member accesses.
3933  if (!Base) {
3934    QualType RecordTy = BaseType;
3935    if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3936    if (LookupMemberExprInRecord(*this, R, SourceRange(),
3937                                 RecordTy->getAs<RecordType>(),
3938                                 OpLoc, SS, TemplateArgs != 0))
3939      return ExprError();
3940
3941  // Explicit member accesses.
3942  } else {
3943    ExprResult BaseResult = Owned(Base);
3944    ExprResult Result =
3945      LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
3946                       SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
3947
3948    if (BaseResult.isInvalid())
3949      return ExprError();
3950    Base = BaseResult.take();
3951
3952    if (Result.isInvalid()) {
3953      Owned(Base);
3954      return ExprError();
3955    }
3956
3957    if (Result.get())
3958      return move(Result);
3959
3960    // LookupMemberExpr can modify Base, and thus change BaseType
3961    BaseType = Base->getType();
3962  }
3963
3964  return BuildMemberReferenceExpr(Base, BaseType,
3965                                  OpLoc, IsArrow, SS, FirstQualifierInScope,
3966                                  R, TemplateArgs);
3967}
3968
3969ExprResult
3970Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
3971                               SourceLocation OpLoc, bool IsArrow,
3972                               const CXXScopeSpec &SS,
3973                               NamedDecl *FirstQualifierInScope,
3974                               LookupResult &R,
3975                         const TemplateArgumentListInfo *TemplateArgs,
3976                               bool SuppressQualifierCheck) {
3977  QualType BaseType = BaseExprType;
3978  if (IsArrow) {
3979    assert(BaseType->isPointerType());
3980    BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3981  }
3982  R.setBaseObjectType(BaseType);
3983
3984  const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3985  DeclarationName MemberName = MemberNameInfo.getName();
3986  SourceLocation MemberLoc = MemberNameInfo.getLoc();
3987
3988  if (R.isAmbiguous())
3989    return ExprError();
3990
3991  if (R.empty()) {
3992    // Rederive where we looked up.
3993    DeclContext *DC = (SS.isSet()
3994                       ? computeDeclContext(SS, false)
3995                       : BaseType->getAs<RecordType>()->getDecl());
3996
3997    Diag(R.getNameLoc(), diag::err_no_member)
3998      << MemberName << DC
3999      << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
4000    return ExprError();
4001  }
4002
4003  // Diagnose lookups that find only declarations from a non-base
4004  // type.  This is possible for either qualified lookups (which may
4005  // have been qualified with an unrelated type) or implicit member
4006  // expressions (which were found with unqualified lookup and thus
4007  // may have come from an enclosing scope).  Note that it's okay for
4008  // lookup to find declarations from a non-base type as long as those
4009  // aren't the ones picked by overload resolution.
4010  if ((SS.isSet() || !BaseExpr ||
4011       (isa<CXXThisExpr>(BaseExpr) &&
4012        cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
4013      !SuppressQualifierCheck &&
4014      CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
4015    return ExprError();
4016
4017  // Construct an unresolved result if we in fact got an unresolved
4018  // result.
4019  if (R.isOverloadedResult() || R.isUnresolvableResult()) {
4020    // Suppress any lookup-related diagnostics; we'll do these when we
4021    // pick a member.
4022    R.suppressDiagnostics();
4023
4024    UnresolvedMemberExpr *MemExpr
4025      = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
4026                                     BaseExpr, BaseExprType,
4027                                     IsArrow, OpLoc,
4028                                     SS.getWithLocInContext(Context),
4029                                     MemberNameInfo,
4030                                     TemplateArgs, R.begin(), R.end());
4031
4032    return Owned(MemExpr);
4033  }
4034
4035  assert(R.isSingleResult());
4036  DeclAccessPair FoundDecl = R.begin().getPair();
4037  NamedDecl *MemberDecl = R.getFoundDecl();
4038
4039  // FIXME: diagnose the presence of template arguments now.
4040
4041  // If the decl being referenced had an error, return an error for this
4042  // sub-expr without emitting another error, in order to avoid cascading
4043  // error cases.
4044  if (MemberDecl->isInvalidDecl())
4045    return ExprError();
4046
4047  // Handle the implicit-member-access case.
4048  if (!BaseExpr) {
4049    // If this is not an instance member, convert to a non-member access.
4050    if (!MemberDecl->isCXXInstanceMember())
4051      return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
4052
4053    SourceLocation Loc = R.getNameLoc();
4054    if (SS.getRange().isValid())
4055      Loc = SS.getRange().getBegin();
4056    BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
4057  }
4058
4059  bool ShouldCheckUse = true;
4060  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
4061    // Don't diagnose the use of a virtual member function unless it's
4062    // explicitly qualified.
4063    if (MD->isVirtual() && !SS.isSet())
4064      ShouldCheckUse = false;
4065  }
4066
4067  // Check the use of this member.
4068  if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
4069    Owned(BaseExpr);
4070    return ExprError();
4071  }
4072
4073  // Perform a property load on the base regardless of whether we
4074  // actually need it for the declaration.
4075  if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
4076    ExprResult Result = ConvertPropertyForRValue(BaseExpr);
4077    if (Result.isInvalid())
4078      return ExprError();
4079    BaseExpr = Result.take();
4080  }
4081
4082  if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
4083    return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
4084                                   SS, FD, FoundDecl, MemberNameInfo);
4085
4086  if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
4087    // We may have found a field within an anonymous union or struct
4088    // (C++ [class.union]).
4089    return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
4090                                                    BaseExpr, OpLoc);
4091
4092  if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
4093    MarkDeclarationReferenced(MemberLoc, Var);
4094    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
4095                                 Var, FoundDecl, MemberNameInfo,
4096                                 Var->getType().getNonReferenceType(),
4097                                 VK_LValue, OK_Ordinary));
4098  }
4099
4100  if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
4101    ExprValueKind valueKind;
4102    QualType type;
4103    if (MemberFn->isInstance()) {
4104      valueKind = VK_RValue;
4105      type = Context.BoundMemberTy;
4106    } else {
4107      valueKind = VK_LValue;
4108      type = MemberFn->getType();
4109    }
4110
4111    MarkDeclarationReferenced(MemberLoc, MemberDecl);
4112    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
4113                                 MemberFn, FoundDecl, MemberNameInfo,
4114                                 type, valueKind, OK_Ordinary));
4115  }
4116  assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
4117
4118  if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
4119    MarkDeclarationReferenced(MemberLoc, MemberDecl);
4120    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
4121                                 Enum, FoundDecl, MemberNameInfo,
4122                                 Enum->getType(), VK_RValue, OK_Ordinary));
4123  }
4124
4125  Owned(BaseExpr);
4126
4127  // We found something that we didn't expect. Complain.
4128  if (isa<TypeDecl>(MemberDecl))
4129    Diag(MemberLoc, diag::err_typecheck_member_reference_type)
4130      << MemberName << BaseType << int(IsArrow);
4131  else
4132    Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
4133      << MemberName << BaseType << int(IsArrow);
4134
4135  Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
4136    << MemberName;
4137  R.suppressDiagnostics();
4138  return ExprError();
4139}
4140
4141/// Given that normal member access failed on the given expression,
4142/// and given that the expression's type involves builtin-id or
4143/// builtin-Class, decide whether substituting in the redefinition
4144/// types would be profitable.  The redefinition type is whatever
4145/// this translation unit tried to typedef to id/Class;  we store
4146/// it to the side and then re-use it in places like this.
4147static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
4148  const ObjCObjectPointerType *opty
4149    = base.get()->getType()->getAs<ObjCObjectPointerType>();
4150  if (!opty) return false;
4151
4152  const ObjCObjectType *ty = opty->getObjectType();
4153
4154  QualType redef;
4155  if (ty->isObjCId()) {
4156    redef = S.Context.ObjCIdRedefinitionType;
4157  } else if (ty->isObjCClass()) {
4158    redef = S.Context.ObjCClassRedefinitionType;
4159  } else {
4160    return false;
4161  }
4162
4163  // Do the substitution as long as the redefinition type isn't just a
4164  // possibly-qualified pointer to builtin-id or builtin-Class again.
4165  opty = redef->getAs<ObjCObjectPointerType>();
4166  if (opty && !opty->getObjectType()->getInterface() != 0)
4167    return false;
4168
4169  base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
4170  return true;
4171}
4172
4173/// Look up the given member of the given non-type-dependent
4174/// expression.  This can return in one of two ways:
4175///  * If it returns a sentinel null-but-valid result, the caller will
4176///    assume that lookup was performed and the results written into
4177///    the provided structure.  It will take over from there.
4178///  * Otherwise, the returned expression will be produced in place of
4179///    an ordinary member expression.
4180///
4181/// The ObjCImpDecl bit is a gross hack that will need to be properly
4182/// fixed for ObjC++.
4183ExprResult
4184Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
4185                       bool &IsArrow, SourceLocation OpLoc,
4186                       CXXScopeSpec &SS,
4187                       Decl *ObjCImpDecl, bool HasTemplateArgs) {
4188  assert(BaseExpr.get() && "no base expression");
4189
4190  // Perform default conversions.
4191  BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4192
4193  if (IsArrow) {
4194    BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4195    if (BaseExpr.isInvalid())
4196      return ExprError();
4197  }
4198
4199  QualType BaseType = BaseExpr.get()->getType();
4200  assert(!BaseType->isDependentType());
4201
4202  DeclarationName MemberName = R.getLookupName();
4203  SourceLocation MemberLoc = R.getNameLoc();
4204
4205  // For later type-checking purposes, turn arrow accesses into dot
4206  // accesses.  The only access type we support that doesn't follow
4207  // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4208  // and those never use arrows, so this is unaffected.
4209  if (IsArrow) {
4210    if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4211      BaseType = Ptr->getPointeeType();
4212    else if (const ObjCObjectPointerType *Ptr
4213               = BaseType->getAs<ObjCObjectPointerType>())
4214      BaseType = Ptr->getPointeeType();
4215    else if (BaseType->isRecordType()) {
4216      // Recover from arrow accesses to records, e.g.:
4217      //   struct MyRecord foo;
4218      //   foo->bar
4219      // This is actually well-formed in C++ if MyRecord has an
4220      // overloaded operator->, but that should have been dealt with
4221      // by now.
4222      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4223        << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
4224        << FixItHint::CreateReplacement(OpLoc, ".");
4225      IsArrow = false;
4226    } else if (BaseType == Context.BoundMemberTy) {
4227      goto fail;
4228    } else {
4229      Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
4230        << BaseType << BaseExpr.get()->getSourceRange();
4231      return ExprError();
4232    }
4233  }
4234
4235  // Handle field access to simple records.
4236  if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
4237    if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
4238                                 RTy, OpLoc, SS, HasTemplateArgs))
4239      return ExprError();
4240
4241    // Returning valid-but-null is how we indicate to the caller that
4242    // the lookup result was filled in.
4243    return Owned((Expr*) 0);
4244  }
4245
4246  // Handle ivar access to Objective-C objects.
4247  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
4248    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4249
4250    // There are three cases for the base type:
4251    //   - builtin id (qualified or unqualified)
4252    //   - builtin Class (qualified or unqualified)
4253    //   - an interface
4254    ObjCInterfaceDecl *IDecl = OTy->getInterface();
4255    if (!IDecl) {
4256      if (getLangOptions().ObjCAutoRefCount &&
4257          (OTy->isObjCId() || OTy->isObjCClass()))
4258        goto fail;
4259      // There's an implicit 'isa' ivar on all objects.
4260      // But we only actually find it this way on objects of type 'id',
4261      // apparently.
4262      if (OTy->isObjCId() && Member->isStr("isa"))
4263        return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
4264                                               Context.getObjCClassType()));
4265
4266      if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4267        return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4268                                ObjCImpDecl, HasTemplateArgs);
4269      goto fail;
4270    }
4271
4272    ObjCInterfaceDecl *ClassDeclared;
4273    ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4274
4275    if (!IV) {
4276      // Attempt to correct for typos in ivar names.
4277      LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4278                       LookupMemberName);
4279      if (CorrectTypo(Res, 0, 0, IDecl, false,
4280                      IsArrow ? CTC_ObjCIvarLookup
4281                              : CTC_ObjCPropertyLookup) &&
4282          (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4283        Diag(R.getNameLoc(),
4284             diag::err_typecheck_member_reference_ivar_suggest)
4285          << IDecl->getDeclName() << MemberName << IV->getDeclName()
4286          << FixItHint::CreateReplacement(R.getNameLoc(),
4287                                          IV->getNameAsString());
4288        Diag(IV->getLocation(), diag::note_previous_decl)
4289          << IV->getDeclName();
4290      } else {
4291        Res.clear();
4292        Res.setLookupName(Member);
4293
4294        Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4295          << IDecl->getDeclName() << MemberName
4296          << BaseExpr.get()->getSourceRange();
4297        return ExprError();
4298      }
4299    }
4300
4301    // If the decl being referenced had an error, return an error for this
4302    // sub-expr without emitting another error, in order to avoid cascading
4303    // error cases.
4304    if (IV->isInvalidDecl())
4305      return ExprError();
4306
4307    // Check whether we can reference this field.
4308    if (DiagnoseUseOfDecl(IV, MemberLoc))
4309      return ExprError();
4310    if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4311        IV->getAccessControl() != ObjCIvarDecl::Package) {
4312      ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4313      if (ObjCMethodDecl *MD = getCurMethodDecl())
4314        ClassOfMethodDecl =  MD->getClassInterface();
4315      else if (ObjCImpDecl && getCurFunctionDecl()) {
4316        // Case of a c-function declared inside an objc implementation.
4317        // FIXME: For a c-style function nested inside an objc implementation
4318        // class, there is no implementation context available, so we pass
4319        // down the context as argument to this routine. Ideally, this context
4320        // need be passed down in the AST node and somehow calculated from the
4321        // AST for a function decl.
4322        if (ObjCImplementationDecl *IMPD =
4323              dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4324          ClassOfMethodDecl = IMPD->getClassInterface();
4325        else if (ObjCCategoryImplDecl* CatImplClass =
4326                   dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4327          ClassOfMethodDecl = CatImplClass->getClassInterface();
4328      }
4329
4330      if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4331        if (ClassDeclared != IDecl ||
4332            ClassOfMethodDecl != ClassDeclared)
4333          Diag(MemberLoc, diag::error_private_ivar_access)
4334            << IV->getDeclName();
4335      } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4336        // @protected
4337        Diag(MemberLoc, diag::error_protected_ivar_access)
4338          << IV->getDeclName();
4339    }
4340    if (getLangOptions().ObjCAutoRefCount) {
4341      Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
4342      if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
4343        if (UO->getOpcode() == UO_Deref)
4344          BaseExp = UO->getSubExpr()->IgnoreParenCasts();
4345
4346      if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
4347        if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4348          Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
4349    }
4350
4351    return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
4352                                               MemberLoc, BaseExpr.take(),
4353                                               IsArrow));
4354  }
4355
4356  // Objective-C property access.
4357  const ObjCObjectPointerType *OPT;
4358  if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4359    // This actually uses the base as an r-value.
4360    BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4361    if (BaseExpr.isInvalid())
4362      return ExprError();
4363
4364    assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
4365
4366    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4367
4368    const ObjCObjectType *OT = OPT->getObjectType();
4369
4370    // id, with and without qualifiers.
4371    if (OT->isObjCId()) {
4372      // Check protocols on qualified interfaces.
4373      Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4374      if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4375        if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4376          // Check the use of this declaration
4377          if (DiagnoseUseOfDecl(PD, MemberLoc))
4378            return ExprError();
4379
4380          QualType T = PD->getType();
4381          if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
4382            T = getMessageSendResultType(BaseType, Getter, false, false);
4383
4384          return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
4385                                                         VK_LValue,
4386                                                         OK_ObjCProperty,
4387                                                         MemberLoc,
4388                                                         BaseExpr.take()));
4389        }
4390
4391        if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4392          // Check the use of this method.
4393          if (DiagnoseUseOfDecl(OMD, MemberLoc))
4394            return ExprError();
4395          Selector SetterSel =
4396            SelectorTable::constructSetterName(PP.getIdentifierTable(),
4397                                               PP.getSelectorTable(), Member);
4398          ObjCMethodDecl *SMD = 0;
4399          if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4400                                                     SetterSel, Context))
4401            SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4402          QualType PType = getMessageSendResultType(BaseType, OMD, false,
4403                                                    false);
4404
4405          ExprValueKind VK = VK_LValue;
4406          if (!getLangOptions().CPlusPlus &&
4407              IsCForbiddenLValueType(Context, PType))
4408            VK = VK_RValue;
4409          ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4410
4411          return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4412                                                         VK, OK,
4413                                                         MemberLoc, BaseExpr.take()));
4414        }
4415      }
4416      // Use of id.member can only be for a property reference. Do not
4417      // use the 'id' redefinition in this case.
4418      if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4419        return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4420                                ObjCImpDecl, HasTemplateArgs);
4421
4422      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4423                         << MemberName << BaseType);
4424    }
4425
4426    // 'Class', unqualified only.
4427    if (OT->isObjCClass()) {
4428      // Only works in a method declaration (??!).
4429      ObjCMethodDecl *MD = getCurMethodDecl();
4430      if (!MD) {
4431        if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4432          return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4433                                  ObjCImpDecl, HasTemplateArgs);
4434
4435        goto fail;
4436      }
4437
4438      // Also must look for a getter name which uses property syntax.
4439      Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4440      ObjCInterfaceDecl *IFace = MD->getClassInterface();
4441      ObjCMethodDecl *Getter;
4442      if ((Getter = IFace->lookupClassMethod(Sel))) {
4443        // Check the use of this method.
4444        if (DiagnoseUseOfDecl(Getter, MemberLoc))
4445          return ExprError();
4446      } else
4447        Getter = IFace->lookupPrivateMethod(Sel, false);
4448      // If we found a getter then this may be a valid dot-reference, we
4449      // will look for the matching setter, in case it is needed.
4450      Selector SetterSel =
4451        SelectorTable::constructSetterName(PP.getIdentifierTable(),
4452                                           PP.getSelectorTable(), Member);
4453      ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4454      if (!Setter) {
4455        // If this reference is in an @implementation, also check for 'private'
4456        // methods.
4457        Setter = IFace->lookupPrivateMethod(SetterSel, false);
4458      }
4459      // Look through local category implementations associated with the class.
4460      if (!Setter)
4461        Setter = IFace->getCategoryClassMethod(SetterSel);
4462
4463      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4464        return ExprError();
4465
4466      if (Getter || Setter) {
4467        QualType PType;
4468
4469        ExprValueKind VK = VK_LValue;
4470        if (Getter) {
4471          PType = getMessageSendResultType(QualType(OT, 0), Getter, true,
4472                                           false);
4473          if (!getLangOptions().CPlusPlus &&
4474              IsCForbiddenLValueType(Context, PType))
4475            VK = VK_RValue;
4476        } else {
4477          // Get the expression type from Setter's incoming parameter.
4478          PType = (*(Setter->param_end() -1))->getType();
4479        }
4480        ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4481
4482        // FIXME: we must check that the setter has property type.
4483        return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4484                                                       PType, VK, OK,
4485                                                       MemberLoc, BaseExpr.take()));
4486      }
4487
4488      if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4489        return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4490                                ObjCImpDecl, HasTemplateArgs);
4491
4492      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4493                         << MemberName << BaseType);
4494    }
4495
4496    // Normal property access.
4497    return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
4498                                     SourceLocation(), QualType(), false);
4499  }
4500
4501  // Handle 'field access' to vectors, such as 'V.xx'.
4502  if (BaseType->isExtVectorType()) {
4503    // FIXME: this expr should store IsArrow.
4504    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4505    ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
4506    QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4507                                           Member, MemberLoc);
4508    if (ret.isNull())
4509      return ExprError();
4510
4511    return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
4512                                                    *Member, MemberLoc));
4513  }
4514
4515  // Adjust builtin-sel to the appropriate redefinition type if that's
4516  // not just a pointer to builtin-sel again.
4517  if (IsArrow &&
4518      BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4519      !Context.ObjCSelRedefinitionType->isObjCSelType()) {
4520    BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4521                                 CK_BitCast);
4522    return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4523                            ObjCImpDecl, HasTemplateArgs);
4524  }
4525
4526  // Failure cases.
4527 fail:
4528
4529  // Recover from dot accesses to pointers, e.g.:
4530  //   type *foo;
4531  //   foo.bar
4532  // This is actually well-formed in two cases:
4533  //   - 'type' is an Objective C type
4534  //   - 'bar' is a pseudo-destructor name which happens to refer to
4535  //     the appropriate pointer type
4536  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4537    if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4538        MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
4539      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4540        << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
4541          << FixItHint::CreateReplacement(OpLoc, "->");
4542
4543      // Recurse as an -> access.
4544      IsArrow = true;
4545      return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4546                              ObjCImpDecl, HasTemplateArgs);
4547    }
4548  }
4549
4550  // If the user is trying to apply -> or . to a function name, it's probably
4551  // because they forgot parentheses to call that function.
4552  QualType ZeroArgCallTy;
4553  UnresolvedSet<4> Overloads;
4554  if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
4555    if (ZeroArgCallTy.isNull()) {
4556      Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4557          << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
4558      UnresolvedSet<2> PlausibleOverloads;
4559      for (OverloadExpr::decls_iterator It = Overloads.begin(),
4560           DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
4561        const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
4562        QualType OverloadResultTy = OverloadDecl->getResultType();
4563        if ((!IsArrow && OverloadResultTy->isRecordType()) ||
4564            (IsArrow && OverloadResultTy->isPointerType() &&
4565             OverloadResultTy->getPointeeType()->isRecordType()))
4566          PlausibleOverloads.addDecl(It.getDecl());
4567      }
4568      NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
4569      return ExprError();
4570    }
4571    if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
4572        (IsArrow && ZeroArgCallTy->isPointerType() &&
4573         ZeroArgCallTy->getPointeeType()->isRecordType())) {
4574      // At this point, we know BaseExpr looks like it's potentially callable
4575      // with 0 arguments, and that it returns something of a reasonable type,
4576      // so we can emit a fixit and carry on pretending that BaseExpr was
4577      // actually a CallExpr.
4578      SourceLocation ParenInsertionLoc =
4579          PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4580      Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4581          << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
4582          << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4583      // FIXME: Try this before emitting the fixit, and suppress diagnostics
4584      // while doing so.
4585      ExprResult NewBase =
4586          ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
4587                        MultiExprArg(*this, 0, 0),
4588                        ParenInsertionLoc.getFileLocWithOffset(1));
4589      if (NewBase.isInvalid())
4590        return ExprError();
4591      BaseExpr = NewBase;
4592      BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4593      return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4594                              ObjCImpDecl, HasTemplateArgs);
4595    }
4596  }
4597
4598  Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4599    << BaseType << BaseExpr.get()->getSourceRange();
4600
4601  return ExprError();
4602}
4603
4604/// The main callback when the parser finds something like
4605///   expression . [nested-name-specifier] identifier
4606///   expression -> [nested-name-specifier] identifier
4607/// where 'identifier' encompasses a fairly broad spectrum of
4608/// possibilities, including destructor and operator references.
4609///
4610/// \param OpKind either tok::arrow or tok::period
4611/// \param HasTrailingLParen whether the next token is '(', which
4612///   is used to diagnose mis-uses of special members that can
4613///   only be called
4614/// \param ObjCImpDecl the current ObjC @implementation decl;
4615///   this is an ugly hack around the fact that ObjC @implementations
4616///   aren't properly put in the context chain
4617ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
4618                                       SourceLocation OpLoc,
4619                                       tok::TokenKind OpKind,
4620                                       CXXScopeSpec &SS,
4621                                       UnqualifiedId &Id,
4622                                       Decl *ObjCImpDecl,
4623                                       bool HasTrailingLParen) {
4624  if (SS.isSet() && SS.isInvalid())
4625    return ExprError();
4626
4627  // Warn about the explicit constructor calls Microsoft extension.
4628  if (getLangOptions().Microsoft &&
4629      Id.getKind() == UnqualifiedId::IK_ConstructorName)
4630    Diag(Id.getSourceRange().getBegin(),
4631         diag::ext_ms_explicit_constructor_call);
4632
4633  TemplateArgumentListInfo TemplateArgsBuffer;
4634
4635  // Decompose the name into its component parts.
4636  DeclarationNameInfo NameInfo;
4637  const TemplateArgumentListInfo *TemplateArgs;
4638  DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
4639                         NameInfo, TemplateArgs);
4640
4641  DeclarationName Name = NameInfo.getName();
4642  bool IsArrow = (OpKind == tok::arrow);
4643
4644  NamedDecl *FirstQualifierInScope
4645    = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4646                       static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4647
4648  // This is a postfix expression, so get rid of ParenListExprs.
4649  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
4650  if (Result.isInvalid()) return ExprError();
4651  Base = Result.take();
4652
4653  if (Base->getType()->isDependentType() || Name.isDependentName() ||
4654      isDependentScopeSpecifier(SS)) {
4655    Result = ActOnDependentMemberExpr(Base, Base->getType(),
4656                                      IsArrow, OpLoc,
4657                                      SS, FirstQualifierInScope,
4658                                      NameInfo, TemplateArgs);
4659  } else {
4660    LookupResult R(*this, NameInfo, LookupMemberName);
4661    ExprResult BaseResult = Owned(Base);
4662    Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
4663                              SS, ObjCImpDecl, TemplateArgs != 0);
4664    if (BaseResult.isInvalid())
4665      return ExprError();
4666    Base = BaseResult.take();
4667
4668    if (Result.isInvalid()) {
4669      Owned(Base);
4670      return ExprError();
4671    }
4672
4673    if (Result.get()) {
4674      // The only way a reference to a destructor can be used is to
4675      // immediately call it, which falls into this case.  If the
4676      // next token is not a '(', produce a diagnostic and build the
4677      // call now.
4678      if (!HasTrailingLParen &&
4679          Id.getKind() == UnqualifiedId::IK_DestructorName)
4680        return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
4681
4682      return move(Result);
4683    }
4684
4685    Result = BuildMemberReferenceExpr(Base, Base->getType(),
4686                                      OpLoc, IsArrow, SS, FirstQualifierInScope,
4687                                      R, TemplateArgs);
4688  }
4689
4690  return move(Result);
4691}
4692
4693ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4694                                        FunctionDecl *FD,
4695                                        ParmVarDecl *Param) {
4696  if (Param->hasUnparsedDefaultArg()) {
4697    Diag(CallLoc,
4698         diag::err_use_of_default_argument_to_function_declared_later) <<
4699      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4700    Diag(UnparsedDefaultArgLocs[Param],
4701         diag::note_default_argument_declared_here);
4702    return ExprError();
4703  }
4704
4705  if (Param->hasUninstantiatedDefaultArg()) {
4706    Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4707
4708    // Instantiate the expression.
4709    MultiLevelTemplateArgumentList ArgList
4710      = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
4711
4712    std::pair<const TemplateArgument *, unsigned> Innermost
4713      = ArgList.getInnermost();
4714    InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4715                               Innermost.second);
4716
4717    ExprResult Result;
4718    {
4719      // C++ [dcl.fct.default]p5:
4720      //   The names in the [default argument] expression are bound, and
4721      //   the semantic constraints are checked, at the point where the
4722      //   default argument expression appears.
4723      ContextRAII SavedContext(*this, FD);
4724      Result = SubstExpr(UninstExpr, ArgList);
4725    }
4726    if (Result.isInvalid())
4727      return ExprError();
4728
4729    // Check the expression as an initializer for the parameter.
4730    InitializedEntity Entity
4731      = InitializedEntity::InitializeParameter(Context, Param);
4732    InitializationKind Kind
4733      = InitializationKind::CreateCopy(Param->getLocation(),
4734             /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4735    Expr *ResultE = Result.takeAs<Expr>();
4736
4737    InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4738    Result = InitSeq.Perform(*this, Entity, Kind,
4739                             MultiExprArg(*this, &ResultE, 1));
4740    if (Result.isInvalid())
4741      return ExprError();
4742
4743    // Build the default argument expression.
4744    return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4745                                           Result.takeAs<Expr>()));
4746  }
4747
4748  // If the default expression creates temporaries, we need to
4749  // push them to the current stack of expression temporaries so they'll
4750  // be properly destroyed.
4751  // FIXME: We should really be rebuilding the default argument with new
4752  // bound temporaries; see the comment in PR5810.
4753  for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4754    CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4755    MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4756                    const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4757    ExprTemporaries.push_back(Temporary);
4758    ExprNeedsCleanups = true;
4759  }
4760
4761  // We already type-checked the argument, so we know it works.
4762  // Just mark all of the declarations in this potentially-evaluated expression
4763  // as being "referenced".
4764  MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
4765  return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
4766}
4767
4768/// ConvertArgumentsForCall - Converts the arguments specified in
4769/// Args/NumArgs to the parameter types of the function FDecl with
4770/// function prototype Proto. Call is the call expression itself, and
4771/// Fn is the function expression. For a C++ member function, this
4772/// routine does not attempt to convert the object argument. Returns
4773/// true if the call is ill-formed.
4774bool
4775Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4776                              FunctionDecl *FDecl,
4777                              const FunctionProtoType *Proto,
4778                              Expr **Args, unsigned NumArgs,
4779                              SourceLocation RParenLoc) {
4780  // Bail out early if calling a builtin with custom typechecking.
4781  // We don't need to do this in the
4782  if (FDecl)
4783    if (unsigned ID = FDecl->getBuiltinID())
4784      if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4785        return false;
4786
4787  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4788  // assignment, to the types of the corresponding parameter, ...
4789  unsigned NumArgsInProto = Proto->getNumArgs();
4790  bool Invalid = false;
4791
4792  // If too few arguments are available (and we don't have default
4793  // arguments for the remaining parameters), don't make the call.
4794  if (NumArgs < NumArgsInProto) {
4795    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4796      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4797        << Fn->getType()->isBlockPointerType()
4798        << NumArgsInProto << NumArgs << Fn->getSourceRange();
4799    Call->setNumArgs(Context, NumArgsInProto);
4800  }
4801
4802  // If too many are passed and not variadic, error on the extras and drop
4803  // them.
4804  if (NumArgs > NumArgsInProto) {
4805    if (!Proto->isVariadic()) {
4806      Diag(Args[NumArgsInProto]->getLocStart(),
4807           diag::err_typecheck_call_too_many_args)
4808        << Fn->getType()->isBlockPointerType()
4809        << NumArgsInProto << NumArgs << Fn->getSourceRange()
4810        << SourceRange(Args[NumArgsInProto]->getLocStart(),
4811                       Args[NumArgs-1]->getLocEnd());
4812
4813      // Emit the location of the prototype.
4814      if (FDecl && !FDecl->getBuiltinID())
4815        Diag(FDecl->getLocStart(),
4816             diag::note_typecheck_call_too_many_args)
4817             << FDecl;
4818
4819      // This deletes the extra arguments.
4820      Call->setNumArgs(Context, NumArgsInProto);
4821      return true;
4822    }
4823  }
4824  llvm::SmallVector<Expr *, 8> AllArgs;
4825  VariadicCallType CallType =
4826    Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4827  if (Fn->getType()->isBlockPointerType())
4828    CallType = VariadicBlock; // Block
4829  else if (isa<MemberExpr>(Fn))
4830    CallType = VariadicMethod;
4831  Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
4832                                   Proto, 0, Args, NumArgs, AllArgs, CallType);
4833  if (Invalid)
4834    return true;
4835  unsigned TotalNumArgs = AllArgs.size();
4836  for (unsigned i = 0; i < TotalNumArgs; ++i)
4837    Call->setArg(i, AllArgs[i]);
4838
4839  return false;
4840}
4841
4842bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4843                                  FunctionDecl *FDecl,
4844                                  const FunctionProtoType *Proto,
4845                                  unsigned FirstProtoArg,
4846                                  Expr **Args, unsigned NumArgs,
4847                                  llvm::SmallVector<Expr *, 8> &AllArgs,
4848                                  VariadicCallType CallType) {
4849  unsigned NumArgsInProto = Proto->getNumArgs();
4850  unsigned NumArgsToCheck = NumArgs;
4851  bool Invalid = false;
4852  if (NumArgs != NumArgsInProto)
4853    // Use default arguments for missing arguments
4854    NumArgsToCheck = NumArgsInProto;
4855  unsigned ArgIx = 0;
4856  // Continue to check argument types (even if we have too few/many args).
4857  for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4858    QualType ProtoArgType = Proto->getArgType(i);
4859
4860    Expr *Arg;
4861    if (ArgIx < NumArgs) {
4862      Arg = Args[ArgIx++];
4863
4864      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4865                              ProtoArgType,
4866                              PDiag(diag::err_call_incomplete_argument)
4867                              << Arg->getSourceRange()))
4868        return true;
4869
4870      // Pass the argument
4871      ParmVarDecl *Param = 0;
4872      if (FDecl && i < FDecl->getNumParams())
4873        Param = FDecl->getParamDecl(i);
4874
4875      InitializedEntity Entity =
4876        Param? InitializedEntity::InitializeParameter(Context, Param)
4877             : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4878                                                      Proto->isArgConsumed(i));
4879      ExprResult ArgE = PerformCopyInitialization(Entity,
4880                                                  SourceLocation(),
4881                                                  Owned(Arg));
4882      if (ArgE.isInvalid())
4883        return true;
4884
4885      Arg = ArgE.takeAs<Expr>();
4886    } else {
4887      ParmVarDecl *Param = FDecl->getParamDecl(i);
4888
4889      ExprResult ArgExpr =
4890        BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4891      if (ArgExpr.isInvalid())
4892        return true;
4893
4894      Arg = ArgExpr.takeAs<Expr>();
4895    }
4896    AllArgs.push_back(Arg);
4897  }
4898
4899  // If this is a variadic call, handle args passed through "...".
4900  if (CallType != VariadicDoesNotApply) {
4901
4902    // Assume that extern "C" functions with variadic arguments that
4903    // return __unknown_anytype aren't *really* variadic.
4904    if (Proto->getResultType() == Context.UnknownAnyTy &&
4905        FDecl && FDecl->isExternC()) {
4906      for (unsigned i = ArgIx; i != NumArgs; ++i) {
4907        ExprResult arg;
4908        if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4909          arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4910        else
4911          arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4912        Invalid |= arg.isInvalid();
4913        AllArgs.push_back(arg.take());
4914      }
4915
4916    // Otherwise do argument promotion, (C99 6.5.2.2p7).
4917    } else {
4918      for (unsigned i = ArgIx; i != NumArgs; ++i) {
4919        ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4920        Invalid |= Arg.isInvalid();
4921        AllArgs.push_back(Arg.take());
4922      }
4923    }
4924  }
4925  return Invalid;
4926}
4927
4928/// Given a function expression of unknown-any type, try to rebuild it
4929/// to have a function type.
4930static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4931
4932/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4933/// This provides the location of the left/right parens and a list of comma
4934/// locations.
4935ExprResult
4936Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4937                    MultiExprArg args, SourceLocation RParenLoc,
4938                    Expr *ExecConfig) {
4939  unsigned NumArgs = args.size();
4940
4941  // Since this might be a postfix expression, get rid of ParenListExprs.
4942  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4943  if (Result.isInvalid()) return ExprError();
4944  Fn = Result.take();
4945
4946  Expr **Args = args.release();
4947
4948  if (getLangOptions().CPlusPlus) {
4949    // If this is a pseudo-destructor expression, build the call immediately.
4950    if (isa<CXXPseudoDestructorExpr>(Fn)) {
4951      if (NumArgs > 0) {
4952        // Pseudo-destructor calls should not have any arguments.
4953        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4954          << FixItHint::CreateRemoval(
4955                                    SourceRange(Args[0]->getLocStart(),
4956                                                Args[NumArgs-1]->getLocEnd()));
4957
4958        NumArgs = 0;
4959      }
4960
4961      return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
4962                                          VK_RValue, RParenLoc));
4963    }
4964
4965    // Determine whether this is a dependent call inside a C++ template,
4966    // in which case we won't do any semantic analysis now.
4967    // FIXME: Will need to cache the results of name lookup (including ADL) in
4968    // Fn.
4969    bool Dependent = false;
4970    if (Fn->isTypeDependent())
4971      Dependent = true;
4972    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4973      Dependent = true;
4974
4975    if (Dependent) {
4976      if (ExecConfig) {
4977        return Owned(new (Context) CUDAKernelCallExpr(
4978            Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4979            Context.DependentTy, VK_RValue, RParenLoc));
4980      } else {
4981        return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4982                                            Context.DependentTy, VK_RValue,
4983                                            RParenLoc));
4984      }
4985    }
4986
4987    // Determine whether this is a call to an object (C++ [over.call.object]).
4988    if (Fn->getType()->isRecordType())
4989      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
4990                                                RParenLoc));
4991
4992    if (Fn->getType() == Context.UnknownAnyTy) {
4993      ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4994      if (result.isInvalid()) return ExprError();
4995      Fn = result.take();
4996    }
4997
4998    if (Fn->getType() == Context.BoundMemberTy) {
4999      return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
5000                                       RParenLoc);
5001    }
5002  }
5003
5004  // Check for overloaded calls.  This can happen even in C due to extensions.
5005  if (Fn->getType() == Context.OverloadTy) {
5006    OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5007
5008    // We aren't supposed to apply this logic if there's an '&' involved.
5009    if (!find.IsAddressOfOperand) {
5010      OverloadExpr *ovl = find.Expression;
5011      if (isa<UnresolvedLookupExpr>(ovl)) {
5012        UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
5013        return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
5014                                       RParenLoc, ExecConfig);
5015      } else {
5016        return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
5017                                         RParenLoc);
5018      }
5019    }
5020  }
5021
5022  // If we're directly calling a function, get the appropriate declaration.
5023
5024  Expr *NakedFn = Fn->IgnoreParens();
5025
5026  NamedDecl *NDecl = 0;
5027  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
5028    if (UnOp->getOpcode() == UO_AddrOf)
5029      NakedFn = UnOp->getSubExpr()->IgnoreParens();
5030
5031  if (isa<DeclRefExpr>(NakedFn))
5032    NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5033  else if (isa<MemberExpr>(NakedFn))
5034    NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5035
5036  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
5037                               ExecConfig);
5038}
5039
5040ExprResult
5041Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5042                              MultiExprArg execConfig, SourceLocation GGGLoc) {
5043  FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
5044  if (!ConfigDecl)
5045    return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
5046                          << "cudaConfigureCall");
5047  QualType ConfigQTy = ConfigDecl->getType();
5048
5049  DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
5050      ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
5051
5052  return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
5053}
5054
5055/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5056///
5057/// __builtin_astype( value, dst type )
5058///
5059ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
5060                                 SourceLocation BuiltinLoc,
5061                                 SourceLocation RParenLoc) {
5062  ExprValueKind VK = VK_RValue;
5063  ExprObjectKind OK = OK_Ordinary;
5064  QualType DstTy = GetTypeFromParser(destty);
5065  QualType SrcTy = expr->getType();
5066  if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5067    return ExprError(Diag(BuiltinLoc,
5068                          diag::err_invalid_astype_of_different_size)
5069                     << DstTy
5070                     << SrcTy
5071                     << expr->getSourceRange());
5072  return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
5073}
5074
5075/// BuildResolvedCallExpr - Build a call to a resolved expression,
5076/// i.e. an expression not of \p OverloadTy.  The expression should
5077/// unary-convert to an expression of function-pointer or
5078/// block-pointer type.
5079///
5080/// \param NDecl the declaration being called, if available
5081ExprResult
5082Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5083                            SourceLocation LParenLoc,
5084                            Expr **Args, unsigned NumArgs,
5085                            SourceLocation RParenLoc,
5086                            Expr *Config) {
5087  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5088
5089  // Promote the function operand.
5090  ExprResult Result = UsualUnaryConversions(Fn);
5091  if (Result.isInvalid())
5092    return ExprError();
5093  Fn = Result.take();
5094
5095  // Make the call expr early, before semantic checks.  This guarantees cleanup
5096  // of arguments and function on error.
5097  CallExpr *TheCall;
5098  if (Config) {
5099    TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5100                                               cast<CallExpr>(Config),
5101                                               Args, NumArgs,
5102                                               Context.BoolTy,
5103                                               VK_RValue,
5104                                               RParenLoc);
5105  } else {
5106    TheCall = new (Context) CallExpr(Context, Fn,
5107                                     Args, NumArgs,
5108                                     Context.BoolTy,
5109                                     VK_RValue,
5110                                     RParenLoc);
5111  }
5112
5113  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5114
5115  // Bail out early if calling a builtin with custom typechecking.
5116  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5117    return CheckBuiltinFunctionCall(BuiltinID, TheCall);
5118
5119 retry:
5120  const FunctionType *FuncT;
5121  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5122    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5123    // have type pointer to function".
5124    FuncT = PT->getPointeeType()->getAs<FunctionType>();
5125    if (FuncT == 0)
5126      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5127                         << Fn->getType() << Fn->getSourceRange());
5128  } else if (const BlockPointerType *BPT =
5129               Fn->getType()->getAs<BlockPointerType>()) {
5130    FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5131  } else {
5132    // Handle calls to expressions of unknown-any type.
5133    if (Fn->getType() == Context.UnknownAnyTy) {
5134      ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5135      if (rewrite.isInvalid()) return ExprError();
5136      Fn = rewrite.take();
5137      TheCall->setCallee(Fn);
5138      goto retry;
5139    }
5140
5141    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5142      << Fn->getType() << Fn->getSourceRange());
5143  }
5144
5145  if (getLangOptions().CUDA) {
5146    if (Config) {
5147      // CUDA: Kernel calls must be to global functions
5148      if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5149        return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5150            << FDecl->getName() << Fn->getSourceRange());
5151
5152      // CUDA: Kernel function must have 'void' return type
5153      if (!FuncT->getResultType()->isVoidType())
5154        return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5155            << Fn->getType() << Fn->getSourceRange());
5156    }
5157  }
5158
5159  // Check for a valid return type
5160  if (CheckCallReturnType(FuncT->getResultType(),
5161                          Fn->getSourceRange().getBegin(), TheCall,
5162                          FDecl))
5163    return ExprError();
5164
5165  // We know the result type of the call, set it.
5166  TheCall->setType(FuncT->getCallResultType(Context));
5167  TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
5168
5169  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
5170    if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
5171                                RParenLoc))
5172      return ExprError();
5173  } else {
5174    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5175
5176    if (FDecl) {
5177      // Check if we have too few/too many template arguments, based
5178      // on our knowledge of the function definition.
5179      const FunctionDecl *Def = 0;
5180      if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
5181        const FunctionProtoType *Proto
5182          = Def->getType()->getAs<FunctionProtoType>();
5183        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
5184          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5185            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
5186      }
5187
5188      // If the function we're calling isn't a function prototype, but we have
5189      // a function prototype from a prior declaratiom, use that prototype.
5190      if (!FDecl->hasPrototype())
5191        Proto = FDecl->getType()->getAs<FunctionProtoType>();
5192    }
5193
5194    // Promote the arguments (C99 6.5.2.2p6).
5195    for (unsigned i = 0; i != NumArgs; i++) {
5196      Expr *Arg = Args[i];
5197
5198      if (Proto && i < Proto->getNumArgs()) {
5199        InitializedEntity Entity
5200          = InitializedEntity::InitializeParameter(Context,
5201                                                   Proto->getArgType(i),
5202                                                   Proto->isArgConsumed(i));
5203        ExprResult ArgE = PerformCopyInitialization(Entity,
5204                                                    SourceLocation(),
5205                                                    Owned(Arg));
5206        if (ArgE.isInvalid())
5207          return true;
5208
5209        Arg = ArgE.takeAs<Expr>();
5210
5211      } else {
5212        ExprResult ArgE = DefaultArgumentPromotion(Arg);
5213
5214        if (ArgE.isInvalid())
5215          return true;
5216
5217        Arg = ArgE.takeAs<Expr>();
5218      }
5219
5220      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5221                              Arg->getType(),
5222                              PDiag(diag::err_call_incomplete_argument)
5223                                << Arg->getSourceRange()))
5224        return ExprError();
5225
5226      TheCall->setArg(i, Arg);
5227    }
5228  }
5229
5230  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5231    if (!Method->isStatic())
5232      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5233        << Fn->getSourceRange());
5234
5235  // Check for sentinels
5236  if (NDecl)
5237    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
5238
5239  // Do special checking on direct calls to functions.
5240  if (FDecl) {
5241    if (CheckFunctionCall(FDecl, TheCall))
5242      return ExprError();
5243
5244    if (BuiltinID)
5245      return CheckBuiltinFunctionCall(BuiltinID, TheCall);
5246  } else if (NDecl) {
5247    if (CheckBlockCall(NDecl, TheCall))
5248      return ExprError();
5249  }
5250
5251  return MaybeBindToTemporary(TheCall);
5252}
5253
5254ExprResult
5255Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5256                           SourceLocation RParenLoc, Expr *InitExpr) {
5257  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
5258  // FIXME: put back this assert when initializers are worked out.
5259  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
5260
5261  TypeSourceInfo *TInfo;
5262  QualType literalType = GetTypeFromParser(Ty, &TInfo);
5263  if (!TInfo)
5264    TInfo = Context.getTrivialTypeSourceInfo(literalType);
5265
5266  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5267}
5268
5269ExprResult
5270Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5271                               SourceLocation RParenLoc, Expr *literalExpr) {
5272  QualType literalType = TInfo->getType();
5273
5274  if (literalType->isArrayType()) {
5275    if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5276             PDiag(diag::err_illegal_decl_array_incomplete_type)
5277               << SourceRange(LParenLoc,
5278                              literalExpr->getSourceRange().getEnd())))
5279      return ExprError();
5280    if (literalType->isVariableArrayType())
5281      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5282        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
5283  } else if (!literalType->isDependentType() &&
5284             RequireCompleteType(LParenLoc, literalType,
5285                      PDiag(diag::err_typecheck_decl_incomplete_type)
5286                        << SourceRange(LParenLoc,
5287                                       literalExpr->getSourceRange().getEnd())))
5288    return ExprError();
5289
5290  InitializedEntity Entity
5291    = InitializedEntity::InitializeTemporary(literalType);
5292  InitializationKind Kind
5293    = InitializationKind::CreateCStyleCast(LParenLoc,
5294                                           SourceRange(LParenLoc, RParenLoc));
5295  InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
5296  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5297                                       MultiExprArg(*this, &literalExpr, 1),
5298                                            &literalType);
5299  if (Result.isInvalid())
5300    return ExprError();
5301  literalExpr = Result.get();
5302
5303  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
5304  if (isFileScope) { // 6.5.2.5p3
5305    if (CheckForConstantInitializer(literalExpr, literalType))
5306      return ExprError();
5307  }
5308
5309  // In C, compound literals are l-values for some reason.
5310  ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5311
5312  return MaybeBindToTemporary(
5313           new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5314                                             VK, literalExpr, isFileScope));
5315}
5316
5317ExprResult
5318Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
5319                    SourceLocation RBraceLoc) {
5320  unsigned NumInit = initlist.size();
5321  Expr **InitList = initlist.release();
5322
5323  // Semantic analysis for initializers is done by ActOnDeclarator() and
5324  // CheckInitializer() - it requires knowledge of the object being intialized.
5325
5326  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5327                                               NumInit, RBraceLoc);
5328  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5329  return Owned(E);
5330}
5331
5332/// Prepares for a scalar cast, performing all the necessary stages
5333/// except the final cast and returning the kind required.
5334static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
5335  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5336  // Also, callers should have filtered out the invalid cases with
5337  // pointers.  Everything else should be possible.
5338
5339  QualType SrcTy = Src.get()->getType();
5340  if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
5341    return CK_NoOp;
5342
5343  switch (SrcTy->getScalarTypeKind()) {
5344  case Type::STK_MemberPointer:
5345    llvm_unreachable("member pointer type in C");
5346
5347  case Type::STK_Pointer:
5348    switch (DestTy->getScalarTypeKind()) {
5349    case Type::STK_Pointer:
5350      return DestTy->isObjCObjectPointerType() ?
5351                CK_AnyPointerToObjCPointerCast :
5352                CK_BitCast;
5353    case Type::STK_Bool:
5354      return CK_PointerToBoolean;
5355    case Type::STK_Integral:
5356      return CK_PointerToIntegral;
5357    case Type::STK_Floating:
5358    case Type::STK_FloatingComplex:
5359    case Type::STK_IntegralComplex:
5360    case Type::STK_MemberPointer:
5361      llvm_unreachable("illegal cast from pointer");
5362    }
5363    break;
5364
5365  case Type::STK_Bool: // casting from bool is like casting from an integer
5366  case Type::STK_Integral:
5367    switch (DestTy->getScalarTypeKind()) {
5368    case Type::STK_Pointer:
5369      if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
5370        return CK_NullToPointer;
5371      return CK_IntegralToPointer;
5372    case Type::STK_Bool:
5373      return CK_IntegralToBoolean;
5374    case Type::STK_Integral:
5375      return CK_IntegralCast;
5376    case Type::STK_Floating:
5377      return CK_IntegralToFloating;
5378    case Type::STK_IntegralComplex:
5379      Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5380                                CK_IntegralCast);
5381      return CK_IntegralRealToComplex;
5382    case Type::STK_FloatingComplex:
5383      Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5384                                CK_IntegralToFloating);
5385      return CK_FloatingRealToComplex;
5386    case Type::STK_MemberPointer:
5387      llvm_unreachable("member pointer type in C");
5388    }
5389    break;
5390
5391  case Type::STK_Floating:
5392    switch (DestTy->getScalarTypeKind()) {
5393    case Type::STK_Floating:
5394      return CK_FloatingCast;
5395    case Type::STK_Bool:
5396      return CK_FloatingToBoolean;
5397    case Type::STK_Integral:
5398      return CK_FloatingToIntegral;
5399    case Type::STK_FloatingComplex:
5400      Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5401                                CK_FloatingCast);
5402      return CK_FloatingRealToComplex;
5403    case Type::STK_IntegralComplex:
5404      Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5405                                CK_FloatingToIntegral);
5406      return CK_IntegralRealToComplex;
5407    case Type::STK_Pointer:
5408      llvm_unreachable("valid float->pointer cast?");
5409    case Type::STK_MemberPointer:
5410      llvm_unreachable("member pointer type in C");
5411    }
5412    break;
5413
5414  case Type::STK_FloatingComplex:
5415    switch (DestTy->getScalarTypeKind()) {
5416    case Type::STK_FloatingComplex:
5417      return CK_FloatingComplexCast;
5418    case Type::STK_IntegralComplex:
5419      return CK_FloatingComplexToIntegralComplex;
5420    case Type::STK_Floating: {
5421      QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
5422      if (S.Context.hasSameType(ET, DestTy))
5423        return CK_FloatingComplexToReal;
5424      Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
5425      return CK_FloatingCast;
5426    }
5427    case Type::STK_Bool:
5428      return CK_FloatingComplexToBoolean;
5429    case Type::STK_Integral:
5430      Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5431                                CK_FloatingComplexToReal);
5432      return CK_FloatingToIntegral;
5433    case Type::STK_Pointer:
5434      llvm_unreachable("valid complex float->pointer cast?");
5435    case Type::STK_MemberPointer:
5436      llvm_unreachable("member pointer type in C");
5437    }
5438    break;
5439
5440  case Type::STK_IntegralComplex:
5441    switch (DestTy->getScalarTypeKind()) {
5442    case Type::STK_FloatingComplex:
5443      return CK_IntegralComplexToFloatingComplex;
5444    case Type::STK_IntegralComplex:
5445      return CK_IntegralComplexCast;
5446    case Type::STK_Integral: {
5447      QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
5448      if (S.Context.hasSameType(ET, DestTy))
5449        return CK_IntegralComplexToReal;
5450      Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
5451      return CK_IntegralCast;
5452    }
5453    case Type::STK_Bool:
5454      return CK_IntegralComplexToBoolean;
5455    case Type::STK_Floating:
5456      Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5457                                CK_IntegralComplexToReal);
5458      return CK_IntegralToFloating;
5459    case Type::STK_Pointer:
5460      llvm_unreachable("valid complex int->pointer cast?");
5461    case Type::STK_MemberPointer:
5462      llvm_unreachable("member pointer type in C");
5463    }
5464    break;
5465  }
5466
5467  llvm_unreachable("Unhandled scalar cast");
5468  return CK_BitCast;
5469}
5470
5471/// CheckCastTypes - Check type constraints for casting between types.
5472ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
5473                                QualType castType, Expr *castExpr,
5474                                CastKind& Kind, ExprValueKind &VK,
5475                                CXXCastPath &BasePath, bool FunctionalStyle) {
5476  if (castExpr->getType() == Context.UnknownAnyTy)
5477    return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5478
5479  if (getLangOptions().CPlusPlus)
5480    return CXXCheckCStyleCast(SourceRange(CastStartLoc,
5481                                          castExpr->getLocEnd()),
5482                              castType, VK, castExpr, Kind, BasePath,
5483                              FunctionalStyle);
5484
5485  assert(!castExpr->getType()->isPlaceholderType());
5486
5487  // We only support r-value casts in C.
5488  VK = VK_RValue;
5489
5490  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5491  // type needs to be scalar.
5492  if (castType->isVoidType()) {
5493    // We don't necessarily do lvalue-to-rvalue conversions on this.
5494    ExprResult castExprRes = IgnoredValueConversions(castExpr);
5495    if (castExprRes.isInvalid())
5496      return ExprError();
5497    castExpr = castExprRes.take();
5498
5499    // Cast to void allows any expr type.
5500    Kind = CK_ToVoid;
5501    return Owned(castExpr);
5502  }
5503
5504  ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5505  if (castExprRes.isInvalid())
5506    return ExprError();
5507  castExpr = castExprRes.take();
5508
5509  if (RequireCompleteType(TyR.getBegin(), castType,
5510                          diag::err_typecheck_cast_to_incomplete))
5511    return ExprError();
5512
5513  if (!castType->isScalarType() && !castType->isVectorType()) {
5514    if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
5515        (castType->isStructureType() || castType->isUnionType())) {
5516      // GCC struct/union extension: allow cast to self.
5517      // FIXME: Check that the cast destination type is complete.
5518      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5519        << castType << castExpr->getSourceRange();
5520      Kind = CK_NoOp;
5521      return Owned(castExpr);
5522    }
5523
5524    if (castType->isUnionType()) {
5525      // GCC cast to union extension
5526      RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
5527      RecordDecl::field_iterator Field, FieldEnd;
5528      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
5529           Field != FieldEnd; ++Field) {
5530        if (Context.hasSameUnqualifiedType(Field->getType(),
5531                                           castExpr->getType()) &&
5532            !Field->isUnnamedBitfield()) {
5533          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5534            << castExpr->getSourceRange();
5535          break;
5536        }
5537      }
5538      if (Field == FieldEnd) {
5539        Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5540          << castExpr->getType() << castExpr->getSourceRange();
5541        return ExprError();
5542      }
5543      Kind = CK_ToUnion;
5544      return Owned(castExpr);
5545    }
5546
5547    // Reject any other conversions to non-scalar types.
5548    Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5549      << castType << castExpr->getSourceRange();
5550    return ExprError();
5551  }
5552
5553  // The type we're casting to is known to be a scalar or vector.
5554
5555  // Require the operand to be a scalar or vector.
5556  if (!castExpr->getType()->isScalarType() &&
5557      !castExpr->getType()->isVectorType()) {
5558    Diag(castExpr->getLocStart(),
5559                diag::err_typecheck_expect_scalar_operand)
5560      << castExpr->getType() << castExpr->getSourceRange();
5561    return ExprError();
5562  }
5563
5564  if (castType->isExtVectorType())
5565    return CheckExtVectorCast(TyR, castType, castExpr, Kind);
5566
5567  if (castType->isVectorType()) {
5568    if (castType->getAs<VectorType>()->getVectorKind() ==
5569        VectorType::AltiVecVector &&
5570          (castExpr->getType()->isIntegerType() ||
5571           castExpr->getType()->isFloatingType())) {
5572      Kind = CK_VectorSplat;
5573      return Owned(castExpr);
5574    } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5575      return ExprError();
5576    } else
5577      return Owned(castExpr);
5578  }
5579  if (castExpr->getType()->isVectorType()) {
5580    if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5581      return ExprError();
5582    else
5583      return Owned(castExpr);
5584  }
5585
5586  // The source and target types are both scalars, i.e.
5587  //   - arithmetic types (fundamental, enum, and complex)
5588  //   - all kinds of pointers
5589  // Note that member pointers were filtered out with C++, above.
5590
5591  if (isa<ObjCSelectorExpr>(castExpr)) {
5592    Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5593    return ExprError();
5594  }
5595
5596  // If either type is a pointer, the other type has to be either an
5597  // integer or a pointer.
5598  QualType castExprType = castExpr->getType();
5599  if (!castType->isArithmeticType()) {
5600    if (!castExprType->isIntegralType(Context) &&
5601        castExprType->isArithmeticType()) {
5602      Diag(castExpr->getLocStart(),
5603           diag::err_cast_pointer_from_non_pointer_int)
5604        << castExprType << castExpr->getSourceRange();
5605      return ExprError();
5606    }
5607  } else if (!castExpr->getType()->isArithmeticType()) {
5608    if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5609      Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
5610        << castType << castExpr->getSourceRange();
5611      return ExprError();
5612    }
5613  }
5614
5615  if (getLangOptions().ObjCAutoRefCount) {
5616    // Diagnose problems with Objective-C casts involving lifetime qualifiers.
5617    CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
5618                           castType, castExpr, CCK_CStyleCast);
5619
5620    if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
5621      if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
5622        Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
5623        Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
5624        if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
5625            ExprPtr->getPointeeType()->isObjCLifetimeType() &&
5626            !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
5627          Diag(castExpr->getLocStart(),
5628               diag::err_typecheck_incompatible_lifetime)
5629            << castExprType << castType << AA_Casting
5630            << castExpr->getSourceRange();
5631
5632          return ExprError();
5633        }
5634      }
5635    }
5636  }
5637
5638  castExprRes = Owned(castExpr);
5639  Kind = PrepareScalarCast(*this, castExprRes, castType);
5640  if (castExprRes.isInvalid())
5641    return ExprError();
5642  castExpr = castExprRes.take();
5643
5644  if (Kind == CK_BitCast)
5645    CheckCastAlign(castExpr, castType, TyR);
5646
5647  return Owned(castExpr);
5648}
5649
5650bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5651                           CastKind &Kind) {
5652  assert(VectorTy->isVectorType() && "Not a vector type!");
5653
5654  if (Ty->isVectorType() || Ty->isIntegerType()) {
5655    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
5656      return Diag(R.getBegin(),
5657                  Ty->isVectorType() ?
5658                  diag::err_invalid_conversion_between_vectors :
5659                  diag::err_invalid_conversion_between_vector_and_integer)
5660        << VectorTy << Ty << R;
5661  } else
5662    return Diag(R.getBegin(),
5663                diag::err_invalid_conversion_between_vector_and_scalar)
5664      << VectorTy << Ty << R;
5665
5666  Kind = CK_BitCast;
5667  return false;
5668}
5669
5670ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5671                                    Expr *CastExpr, CastKind &Kind) {
5672  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5673
5674  QualType SrcTy = CastExpr->getType();
5675
5676  // If SrcTy is a VectorType, the total size must match to explicitly cast to
5677  // an ExtVectorType.
5678  if (SrcTy->isVectorType()) {
5679    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5680      Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5681        << DestTy << SrcTy << R;
5682      return ExprError();
5683    }
5684    Kind = CK_BitCast;
5685    return Owned(CastExpr);
5686  }
5687
5688  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5689  // conversion will take place first from scalar to elt type, and then
5690  // splat from elt type to vector.
5691  if (SrcTy->isPointerType())
5692    return Diag(R.getBegin(),
5693                diag::err_invalid_conversion_between_vector_and_scalar)
5694      << DestTy << SrcTy << R;
5695
5696  QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5697  ExprResult CastExprRes = Owned(CastExpr);
5698  CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5699  if (CastExprRes.isInvalid())
5700    return ExprError();
5701  CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
5702
5703  Kind = CK_VectorSplat;
5704  return Owned(CastExpr);
5705}
5706
5707ExprResult
5708Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
5709                    SourceLocation RParenLoc, Expr *castExpr) {
5710  assert((Ty != 0) && (castExpr != 0) &&
5711         "ActOnCastExpr(): missing type or expr");
5712
5713  TypeSourceInfo *castTInfo;
5714  QualType castType = GetTypeFromParser(Ty, &castTInfo);
5715  if (!castTInfo)
5716    castTInfo = Context.getTrivialTypeSourceInfo(castType);
5717
5718  // If the Expr being casted is a ParenListExpr, handle it specially.
5719  if (isa<ParenListExpr>(castExpr))
5720    return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
5721                                    castTInfo);
5722
5723  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
5724}
5725
5726ExprResult
5727Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
5728                          SourceLocation RParenLoc, Expr *castExpr) {
5729  CastKind Kind = CK_Invalid;
5730  ExprValueKind VK = VK_RValue;
5731  CXXCastPath BasePath;
5732  ExprResult CastResult =
5733    CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
5734                   castExpr, Kind, VK, BasePath);
5735  if (CastResult.isInvalid())
5736    return ExprError();
5737  castExpr = CastResult.take();
5738
5739  return Owned(CStyleCastExpr::Create(Context,
5740                                      Ty->getType().getNonLValueExprType(Context),
5741                                      VK, Kind, castExpr, &BasePath, Ty,
5742                                      LParenLoc, RParenLoc));
5743}
5744
5745/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5746/// of comma binary operators.
5747ExprResult
5748Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
5749  ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5750  if (!E)
5751    return Owned(expr);
5752
5753  ExprResult Result(E->getExpr(0));
5754
5755  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5756    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5757                        E->getExpr(i));
5758
5759  if (Result.isInvalid()) return ExprError();
5760
5761  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5762}
5763
5764ExprResult
5765Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
5766                               SourceLocation RParenLoc, Expr *Op,
5767                               TypeSourceInfo *TInfo) {
5768  ParenListExpr *PE = cast<ParenListExpr>(Op);
5769  QualType Ty = TInfo->getType();
5770  bool isVectorLiteral = false;
5771
5772  // Check for an altivec or OpenCL literal,
5773  // i.e. all the elements are integer constants.
5774  if (getLangOptions().AltiVec && Ty->isVectorType()) {
5775    if (PE->getNumExprs() == 0) {
5776      Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5777      return ExprError();
5778    }
5779    if (PE->getNumExprs() == 1) {
5780      if (!PE->getExpr(0)->getType()->isVectorType())
5781        isVectorLiteral = true;
5782    }
5783    else
5784      isVectorLiteral = true;
5785  }
5786
5787  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5788  // then handle it as such.
5789  if (isVectorLiteral) {
5790    llvm::SmallVector<Expr *, 8> initExprs;
5791    // '(...)' form of vector initialization in AltiVec: the number of
5792    // initializers must be one or must match the size of the vector.
5793    // If a single value is specified in the initializer then it will be
5794    // replicated to all the components of the vector
5795    if (Ty->getAs<VectorType>()->getVectorKind() ==
5796        VectorType::AltiVecVector) {
5797      unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5798      // The number of initializers must be one or must match the size of the
5799      // vector. If a single value is specified in the initializer then it will
5800      // be replicated to all the components of the vector
5801      if (PE->getNumExprs() == 1) {
5802        QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5803        ExprResult Literal = Owned(PE->getExpr(0));
5804        Literal = ImpCastExprToType(Literal.take(), ElemTy,
5805                                    PrepareScalarCast(*this, Literal, ElemTy));
5806        return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5807      }
5808      else if (PE->getNumExprs() < numElems) {
5809        Diag(PE->getExprLoc(),
5810             diag::err_incorrect_number_of_vector_initializers);
5811        return ExprError();
5812      }
5813      else
5814        for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5815          initExprs.push_back(PE->getExpr(i));
5816    }
5817    else
5818      for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5819        initExprs.push_back(PE->getExpr(i));
5820
5821    // FIXME: This means that pretty-printing the final AST will produce curly
5822    // braces instead of the original commas.
5823    InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5824                                                 &initExprs[0],
5825                                                 initExprs.size(), RParenLoc);
5826    E->setType(Ty);
5827    return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
5828  } else {
5829    // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5830    // sequence of BinOp comma operators.
5831    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
5832    if (Result.isInvalid()) return ExprError();
5833    return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
5834  }
5835}
5836
5837ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
5838                                                  SourceLocation R,
5839                                                  MultiExprArg Val,
5840                                                  ParsedType TypeOfCast) {
5841  unsigned nexprs = Val.size();
5842  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
5843  assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5844  Expr *expr;
5845  if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5846    expr = new (Context) ParenExpr(L, R, exprs[0]);
5847  else
5848    expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
5849  return Owned(expr);
5850}
5851
5852/// \brief Emit a specialized diagnostic when one expression is a null pointer
5853/// constant and the other is not a pointer.
5854bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5855                                      SourceLocation QuestionLoc) {
5856  Expr *NullExpr = LHS;
5857  Expr *NonPointerExpr = RHS;
5858  Expr::NullPointerConstantKind NullKind =
5859      NullExpr->isNullPointerConstant(Context,
5860                                      Expr::NPC_ValueDependentIsNotNull);
5861
5862  if (NullKind == Expr::NPCK_NotNull) {
5863    NullExpr = RHS;
5864    NonPointerExpr = LHS;
5865    NullKind =
5866        NullExpr->isNullPointerConstant(Context,
5867                                        Expr::NPC_ValueDependentIsNotNull);
5868  }
5869
5870  if (NullKind == Expr::NPCK_NotNull)
5871    return false;
5872
5873  if (NullKind == Expr::NPCK_ZeroInteger) {
5874    // In this case, check to make sure that we got here from a "NULL"
5875    // string in the source code.
5876    NullExpr = NullExpr->IgnoreParenImpCasts();
5877    SourceLocation loc = NullExpr->getExprLoc();
5878    if (!findMacroSpelling(loc, "NULL"))
5879      return false;
5880  }
5881
5882  int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5883  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5884      << NonPointerExpr->getType() << DiagType
5885      << NonPointerExpr->getSourceRange();
5886  return true;
5887}
5888
5889/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5890/// In that case, lhs = cond.
5891/// C99 6.5.15
5892QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
5893                                        ExprValueKind &VK, ExprObjectKind &OK,
5894                                        SourceLocation QuestionLoc) {
5895
5896  ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
5897  if (!lhsResult.isUsable()) return QualType();
5898  LHS = move(lhsResult);
5899
5900  ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
5901  if (!rhsResult.isUsable()) return QualType();
5902  RHS = move(rhsResult);
5903
5904  // C++ is sufficiently different to merit its own checker.
5905  if (getLangOptions().CPlusPlus)
5906    return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5907
5908  VK = VK_RValue;
5909  OK = OK_Ordinary;
5910
5911  Cond = UsualUnaryConversions(Cond.take());
5912  if (Cond.isInvalid())
5913    return QualType();
5914  LHS = UsualUnaryConversions(LHS.take());
5915  if (LHS.isInvalid())
5916    return QualType();
5917  RHS = UsualUnaryConversions(RHS.take());
5918  if (RHS.isInvalid())
5919    return QualType();
5920
5921  QualType CondTy = Cond.get()->getType();
5922  QualType LHSTy = LHS.get()->getType();
5923  QualType RHSTy = RHS.get()->getType();
5924
5925  // first, check the condition.
5926  if (!CondTy->isScalarType()) { // C99 6.5.15p2
5927    // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5928    // Throw an error if its not either.
5929    if (getLangOptions().OpenCL) {
5930      if (!CondTy->isVectorType()) {
5931        Diag(Cond.get()->getLocStart(),
5932             diag::err_typecheck_cond_expect_scalar_or_vector)
5933          << CondTy;
5934        return QualType();
5935      }
5936    }
5937    else {
5938      Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5939        << CondTy;
5940      return QualType();
5941    }
5942  }
5943
5944  // Now check the two expressions.
5945  if (LHSTy->isVectorType() || RHSTy->isVectorType())
5946    return CheckVectorOperands(QuestionLoc, LHS, RHS);
5947
5948  // OpenCL: If the condition is a vector, and both operands are scalar,
5949  // attempt to implicity convert them to the vector type to act like the
5950  // built in select.
5951  if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5952    // Both operands should be of scalar type.
5953    if (!LHSTy->isScalarType()) {
5954      Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5955        << CondTy;
5956      return QualType();
5957    }
5958    if (!RHSTy->isScalarType()) {
5959      Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5960        << CondTy;
5961      return QualType();
5962    }
5963    // Implicity convert these scalars to the type of the condition.
5964    LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5965    RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5966  }
5967
5968  // If both operands have arithmetic type, do the usual arithmetic conversions
5969  // to find a common type: C99 6.5.15p3,5.
5970  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5971    UsualArithmeticConversions(LHS, RHS);
5972    if (LHS.isInvalid() || RHS.isInvalid())
5973      return QualType();
5974    return LHS.get()->getType();
5975  }
5976
5977  // If both operands are the same structure or union type, the result is that
5978  // type.
5979  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5980    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5981      if (LHSRT->getDecl() == RHSRT->getDecl())
5982        // "If both the operands have structure or union type, the result has
5983        // that type."  This implies that CV qualifiers are dropped.
5984        return LHSTy.getUnqualifiedType();
5985    // FIXME: Type of conditional expression must be complete in C mode.
5986  }
5987
5988  // C99 6.5.15p5: "If both operands have void type, the result has void type."
5989  // The following || allows only one side to be void (a GCC-ism).
5990  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5991    if (!LHSTy->isVoidType())
5992      Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5993        << RHS.get()->getSourceRange();
5994    if (!RHSTy->isVoidType())
5995      Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5996        << LHS.get()->getSourceRange();
5997    LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5998    RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
5999    return Context.VoidTy;
6000  }
6001  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6002  // the type of the other operand."
6003  if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
6004      RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6005    // promote the null to a pointer.
6006    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
6007    return LHSTy;
6008  }
6009  if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
6010      LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6011    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
6012    return RHSTy;
6013  }
6014
6015  // All objective-c pointer type analysis is done here.
6016  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6017                                                        QuestionLoc);
6018  if (LHS.isInvalid() || RHS.isInvalid())
6019    return QualType();
6020  if (!compositeType.isNull())
6021    return compositeType;
6022
6023
6024  // Handle block pointer types.
6025  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
6026    if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6027      if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6028        QualType destType = Context.getPointerType(Context.VoidTy);
6029        LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
6030        RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
6031        return destType;
6032      }
6033      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6034      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6035      return QualType();
6036    }
6037    // We have 2 block pointer types.
6038    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6039      // Two identical block pointer types are always compatible.
6040      return LHSTy;
6041    }
6042    // The block pointer types aren't identical, continue checking.
6043    QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
6044    QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
6045
6046    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6047                                    rhptee.getUnqualifiedType())) {
6048      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
6049      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6050      // In this situation, we assume void* type. No especially good
6051      // reason, but this is what gcc does, and we do have to pick
6052      // to get a consistent AST.
6053      QualType incompatTy = Context.getPointerType(Context.VoidTy);
6054      LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6055      RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
6056      return incompatTy;
6057    }
6058    // The block pointer types are compatible.
6059    LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6060    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
6061    return LHSTy;
6062  }
6063
6064  // Check constraints for C object pointers types (C99 6.5.15p3,6).
6065  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6066    // get the "pointed to" types
6067    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6068    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6069
6070    // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6071    if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6072      // Figure out necessary qualifiers (C99 6.5.15p6)
6073      QualType destPointee
6074        = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6075      QualType destType = Context.getPointerType(destPointee);
6076      // Add qualifiers if necessary.
6077      LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
6078      // Promote to void*.
6079      RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
6080      return destType;
6081    }
6082    if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6083      QualType destPointee
6084        = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6085      QualType destType = Context.getPointerType(destPointee);
6086      // Add qualifiers if necessary.
6087      RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
6088      // Promote to void*.
6089      LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
6090      return destType;
6091    }
6092
6093    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6094      // Two identical pointer types are always compatible.
6095      return LHSTy;
6096    }
6097    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6098                                    rhptee.getUnqualifiedType())) {
6099      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
6100        << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6101      // In this situation, we assume void* type. No especially good
6102      // reason, but this is what gcc does, and we do have to pick
6103      // to get a consistent AST.
6104      QualType incompatTy = Context.getPointerType(Context.VoidTy);
6105      LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6106      RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
6107      return incompatTy;
6108    }
6109    // The pointer types are compatible.
6110    // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
6111    // differently qualified versions of compatible types, the result type is
6112    // a pointer to an appropriately qualified version of the *composite*
6113    // type.
6114    // FIXME: Need to calculate the composite type.
6115    // FIXME: Need to add qualifiers
6116    LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6117    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
6118    return LHSTy;
6119  }
6120
6121  // GCC compatibility: soften pointer/integer mismatch.  Note that
6122  // null pointers have been filtered out by this point.
6123  if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
6124    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
6125      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6126    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
6127    return RHSTy;
6128  }
6129  if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
6130    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
6131      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6132    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
6133    return LHSTy;
6134  }
6135
6136  // Emit a better diagnostic if one of the expressions is a null pointer
6137  // constant and the other is not a pointer type. In this case, the user most
6138  // likely forgot to take the address of the other expression.
6139  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6140    return QualType();
6141
6142  // Otherwise, the operands are not compatible.
6143  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6144    << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6145  return QualType();
6146}
6147
6148/// FindCompositeObjCPointerType - Helper method to find composite type of
6149/// two objective-c pointer types of the two input expressions.
6150QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6151                                        SourceLocation QuestionLoc) {
6152  QualType LHSTy = LHS.get()->getType();
6153  QualType RHSTy = RHS.get()->getType();
6154
6155  // Handle things like Class and struct objc_class*.  Here we case the result
6156  // to the pseudo-builtin, because that will be implicitly cast back to the
6157  // redefinition type if an attempt is made to access its fields.
6158  if (LHSTy->isObjCClassType() &&
6159      (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
6160    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
6161    return LHSTy;
6162  }
6163  if (RHSTy->isObjCClassType() &&
6164      (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
6165    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
6166    return RHSTy;
6167  }
6168  // And the same for struct objc_object* / id
6169  if (LHSTy->isObjCIdType() &&
6170      (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
6171    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
6172    return LHSTy;
6173  }
6174  if (RHSTy->isObjCIdType() &&
6175      (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
6176    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
6177    return RHSTy;
6178  }
6179  // And the same for struct objc_selector* / SEL
6180  if (Context.isObjCSelType(LHSTy) &&
6181      (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
6182    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
6183    return LHSTy;
6184  }
6185  if (Context.isObjCSelType(RHSTy) &&
6186      (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
6187    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
6188    return RHSTy;
6189  }
6190  // Check constraints for Objective-C object pointers types.
6191  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6192
6193    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6194      // Two identical object pointer types are always compatible.
6195      return LHSTy;
6196    }
6197    const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6198    const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6199    QualType compositeType = LHSTy;
6200
6201    // If both operands are interfaces and either operand can be
6202    // assigned to the other, use that type as the composite
6203    // type. This allows
6204    //   xxx ? (A*) a : (B*) b
6205    // where B is a subclass of A.
6206    //
6207    // Additionally, as for assignment, if either type is 'id'
6208    // allow silent coercion. Finally, if the types are
6209    // incompatible then make sure to use 'id' as the composite
6210    // type so the result is acceptable for sending messages to.
6211
6212    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6213    // It could return the composite type.
6214    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6215      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6216    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6217      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6218    } else if ((LHSTy->isObjCQualifiedIdType() ||
6219                RHSTy->isObjCQualifiedIdType()) &&
6220               Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6221      // Need to handle "id<xx>" explicitly.
6222      // GCC allows qualified id and any Objective-C type to devolve to
6223      // id. Currently localizing to here until clear this should be
6224      // part of ObjCQualifiedIdTypesAreCompatible.
6225      compositeType = Context.getObjCIdType();
6226    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6227      compositeType = Context.getObjCIdType();
6228    } else if (!(compositeType =
6229                 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6230      ;
6231    else {
6232      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6233      << LHSTy << RHSTy
6234      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6235      QualType incompatTy = Context.getObjCIdType();
6236      LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6237      RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
6238      return incompatTy;
6239    }
6240    // The object pointer types are compatible.
6241    LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6242    RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
6243    return compositeType;
6244  }
6245  // Check Objective-C object pointer types and 'void *'
6246  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6247    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6248    QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6249    QualType destPointee
6250    = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6251    QualType destType = Context.getPointerType(destPointee);
6252    // Add qualifiers if necessary.
6253    LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
6254    // Promote to void*.
6255    RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
6256    return destType;
6257  }
6258  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6259    QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6260    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6261    QualType destPointee
6262    = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6263    QualType destType = Context.getPointerType(destPointee);
6264    // Add qualifiers if necessary.
6265    RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
6266    // Promote to void*.
6267    LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
6268    return destType;
6269  }
6270  return QualType();
6271}
6272
6273/// SuggestParentheses - Emit a note with a fixit hint that wraps
6274/// ParenRange in parentheses.
6275static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6276                               const PartialDiagnostic &Note,
6277                               SourceRange ParenRange) {
6278  SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6279  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6280      EndLoc.isValid()) {
6281    Self.Diag(Loc, Note)
6282      << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6283      << FixItHint::CreateInsertion(EndLoc, ")");
6284  } else {
6285    // We can't display the parentheses, so just show the bare note.
6286    Self.Diag(Loc, Note) << ParenRange;
6287  }
6288}
6289
6290static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6291  return Opc >= BO_Mul && Opc <= BO_Shr;
6292}
6293
6294/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6295/// expression, either using a built-in or overloaded operator,
6296/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
6297static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6298                                   Expr **RHS) {
6299  E = E->IgnoreParenImpCasts();
6300  E = E->IgnoreConversionOperator();
6301  E = E->IgnoreParenImpCasts();
6302
6303  // Built-in binary operator.
6304  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6305    if (IsArithmeticOp(OP->getOpcode())) {
6306      *Opcode = OP->getOpcode();
6307      *RHS = OP->getRHS();
6308      return true;
6309    }
6310  }
6311
6312  // Overloaded operator.
6313  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6314    if (Call->getNumArgs() != 2)
6315      return false;
6316
6317    // Make sure this is really a binary operator that is safe to pass into
6318    // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6319    OverloadedOperatorKind OO = Call->getOperator();
6320    if (OO < OO_Plus || OO > OO_Arrow)
6321      return false;
6322
6323    BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6324    if (IsArithmeticOp(OpKind)) {
6325      *Opcode = OpKind;
6326      *RHS = Call->getArg(1);
6327      return true;
6328    }
6329  }
6330
6331  return false;
6332}
6333
6334static bool IsLogicOp(BinaryOperatorKind Opc) {
6335  return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6336}
6337
6338/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6339/// or is a logical expression such as (x==y) which has int type, but is
6340/// commonly interpreted as boolean.
6341static bool ExprLooksBoolean(Expr *E) {
6342  E = E->IgnoreParenImpCasts();
6343
6344  if (E->getType()->isBooleanType())
6345    return true;
6346  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6347    return IsLogicOp(OP->getOpcode());
6348  if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6349    return OP->getOpcode() == UO_LNot;
6350
6351  return false;
6352}
6353
6354/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6355/// and binary operator are mixed in a way that suggests the programmer assumed
6356/// the conditional operator has higher precedence, for example:
6357/// "int x = a + someBinaryCondition ? 1 : 2".
6358static void DiagnoseConditionalPrecedence(Sema &Self,
6359                                          SourceLocation OpLoc,
6360                                          Expr *Condition,
6361                                          Expr *LHS,
6362                                          Expr *RHS) {
6363  BinaryOperatorKind CondOpcode;
6364  Expr *CondRHS;
6365
6366  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6367    return;
6368  if (!ExprLooksBoolean(CondRHS))
6369    return;
6370
6371  // The condition is an arithmetic binary expression, with a right-
6372  // hand side that looks boolean, so warn.
6373
6374  Self.Diag(OpLoc, diag::warn_precedence_conditional)
6375      << Condition->getSourceRange()
6376      << BinaryOperator::getOpcodeStr(CondOpcode);
6377
6378  SuggestParentheses(Self, OpLoc,
6379    Self.PDiag(diag::note_precedence_conditional_silence)
6380      << BinaryOperator::getOpcodeStr(CondOpcode),
6381    SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6382
6383  SuggestParentheses(Self, OpLoc,
6384    Self.PDiag(diag::note_precedence_conditional_first),
6385    SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
6386}
6387
6388/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6389/// in the case of a the GNU conditional expr extension.
6390ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6391                                    SourceLocation ColonLoc,
6392                                    Expr *CondExpr, Expr *LHSExpr,
6393                                    Expr *RHSExpr) {
6394  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6395  // was the condition.
6396  OpaqueValueExpr *opaqueValue = 0;
6397  Expr *commonExpr = 0;
6398  if (LHSExpr == 0) {
6399    commonExpr = CondExpr;
6400
6401    // We usually want to apply unary conversions *before* saving, except
6402    // in the special case of a C++ l-value conditional.
6403    if (!(getLangOptions().CPlusPlus
6404          && !commonExpr->isTypeDependent()
6405          && commonExpr->getValueKind() == RHSExpr->getValueKind()
6406          && commonExpr->isGLValue()
6407          && commonExpr->isOrdinaryOrBitFieldObject()
6408          && RHSExpr->isOrdinaryOrBitFieldObject()
6409          && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6410      ExprResult commonRes = UsualUnaryConversions(commonExpr);
6411      if (commonRes.isInvalid())
6412        return ExprError();
6413      commonExpr = commonRes.take();
6414    }
6415
6416    opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6417                                                commonExpr->getType(),
6418                                                commonExpr->getValueKind(),
6419                                                commonExpr->getObjectKind());
6420    LHSExpr = CondExpr = opaqueValue;
6421  }
6422
6423  ExprValueKind VK = VK_RValue;
6424  ExprObjectKind OK = OK_Ordinary;
6425  ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6426  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6427                                             VK, OK, QuestionLoc);
6428  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6429      RHS.isInvalid())
6430    return ExprError();
6431
6432  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6433                                RHS.get());
6434
6435  if (!commonExpr)
6436    return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6437                                                   LHS.take(), ColonLoc,
6438                                                   RHS.take(), result, VK, OK));
6439
6440  return Owned(new (Context)
6441    BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6442                              RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
6443}
6444
6445// checkPointerTypesForAssignment - This is a very tricky routine (despite
6446// being closely modeled after the C99 spec:-). The odd characteristic of this
6447// routine is it effectively iqnores the qualifiers on the top level pointee.
6448// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6449// FIXME: add a couple examples in this comment.
6450static Sema::AssignConvertType
6451checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6452  assert(lhsType.isCanonical() && "LHS not canonicalized!");
6453  assert(rhsType.isCanonical() && "RHS not canonicalized!");
6454
6455  // get the "pointed to" type (ignoring qualifiers at the top level)
6456  const Type *lhptee, *rhptee;
6457  Qualifiers lhq, rhq;
6458  llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6459  llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
6460
6461  Sema::AssignConvertType ConvTy = Sema::Compatible;
6462
6463  // C99 6.5.16.1p1: This following citation is common to constraints
6464  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6465  // qualifiers of the type *pointed to* by the right;
6466  Qualifiers lq;
6467
6468  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6469  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6470      lhq.compatiblyIncludesObjCLifetime(rhq)) {
6471    // Ignore lifetime for further calculation.
6472    lhq.removeObjCLifetime();
6473    rhq.removeObjCLifetime();
6474  }
6475
6476  if (!lhq.compatiblyIncludes(rhq)) {
6477    // Treat address-space mismatches as fatal.  TODO: address subspaces
6478    if (lhq.getAddressSpace() != rhq.getAddressSpace())
6479      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6480
6481    // It's okay to add or remove GC or lifetime qualifiers when converting to
6482    // and from void*.
6483    else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
6484                        .compatiblyIncludes(
6485                                rhq.withoutObjCGCAttr().withoutObjCGLifetime())
6486             && (lhptee->isVoidType() || rhptee->isVoidType()))
6487      ; // keep old
6488
6489    // Treat lifetime mismatches as fatal.
6490    else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6491      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6492
6493    // For GCC compatibility, other qualifier mismatches are treated
6494    // as still compatible in C.
6495    else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6496  }
6497
6498  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6499  // incomplete type and the other is a pointer to a qualified or unqualified
6500  // version of void...
6501  if (lhptee->isVoidType()) {
6502    if (rhptee->isIncompleteOrObjectType())
6503      return ConvTy;
6504
6505    // As an extension, we allow cast to/from void* to function pointer.
6506    assert(rhptee->isFunctionType());
6507    return Sema::FunctionVoidPointer;
6508  }
6509
6510  if (rhptee->isVoidType()) {
6511    if (lhptee->isIncompleteOrObjectType())
6512      return ConvTy;
6513
6514    // As an extension, we allow cast to/from void* to function pointer.
6515    assert(lhptee->isFunctionType());
6516    return Sema::FunctionVoidPointer;
6517  }
6518
6519  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6520  // unqualified versions of compatible types, ...
6521  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6522  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6523    // Check if the pointee types are compatible ignoring the sign.
6524    // We explicitly check for char so that we catch "char" vs
6525    // "unsigned char" on systems where "char" is unsigned.
6526    if (lhptee->isCharType())
6527      ltrans = S.Context.UnsignedCharTy;
6528    else if (lhptee->hasSignedIntegerRepresentation())
6529      ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6530
6531    if (rhptee->isCharType())
6532      rtrans = S.Context.UnsignedCharTy;
6533    else if (rhptee->hasSignedIntegerRepresentation())
6534      rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6535
6536    if (ltrans == rtrans) {
6537      // Types are compatible ignoring the sign. Qualifier incompatibility
6538      // takes priority over sign incompatibility because the sign
6539      // warning can be disabled.
6540      if (ConvTy != Sema::Compatible)
6541        return ConvTy;
6542
6543      return Sema::IncompatiblePointerSign;
6544    }
6545
6546    // If we are a multi-level pointer, it's possible that our issue is simply
6547    // one of qualification - e.g. char ** -> const char ** is not allowed. If
6548    // the eventual target type is the same and the pointers have the same
6549    // level of indirection, this must be the issue.
6550    if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6551      do {
6552        lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6553        rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6554      } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6555
6556      if (lhptee == rhptee)
6557        return Sema::IncompatibleNestedPointerQualifiers;
6558    }
6559
6560    // General pointer incompatibility takes priority over qualifiers.
6561    return Sema::IncompatiblePointer;
6562  }
6563  return ConvTy;
6564}
6565
6566/// checkBlockPointerTypesForAssignment - This routine determines whether two
6567/// block pointer types are compatible or whether a block and normal pointer
6568/// are compatible. It is more restrict than comparing two function pointer
6569// types.
6570static Sema::AssignConvertType
6571checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6572                                    QualType rhsType) {
6573  assert(lhsType.isCanonical() && "LHS not canonicalized!");
6574  assert(rhsType.isCanonical() && "RHS not canonicalized!");
6575
6576  QualType lhptee, rhptee;
6577
6578  // get the "pointed to" type (ignoring qualifiers at the top level)
6579  lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6580  rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
6581
6582  // In C++, the types have to match exactly.
6583  if (S.getLangOptions().CPlusPlus)
6584    return Sema::IncompatibleBlockPointer;
6585
6586  Sema::AssignConvertType ConvTy = Sema::Compatible;
6587
6588  // For blocks we enforce that qualifiers are identical.
6589  if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6590    ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6591
6592  if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6593    return Sema::IncompatibleBlockPointer;
6594
6595  return ConvTy;
6596}
6597
6598/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6599/// for assignment compatibility.
6600static Sema::AssignConvertType
6601checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6602  assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6603  assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6604
6605  if (lhsType->isObjCBuiltinType()) {
6606    // Class is not compatible with ObjC object pointers.
6607    if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6608        !rhsType->isObjCQualifiedClassType())
6609      return Sema::IncompatiblePointer;
6610    return Sema::Compatible;
6611  }
6612  if (rhsType->isObjCBuiltinType()) {
6613    // Class is not compatible with ObjC object pointers.
6614    if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6615        !lhsType->isObjCQualifiedClassType())
6616      return Sema::IncompatiblePointer;
6617    return Sema::Compatible;
6618  }
6619  QualType lhptee =
6620  lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
6621  QualType rhptee =
6622  rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
6623
6624  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6625    return Sema::CompatiblePointerDiscardsQualifiers;
6626
6627  if (S.Context.typesAreCompatible(lhsType, rhsType))
6628    return Sema::Compatible;
6629  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
6630    return Sema::IncompatibleObjCQualifiedId;
6631  return Sema::IncompatiblePointer;
6632}
6633
6634Sema::AssignConvertType
6635Sema::CheckAssignmentConstraints(SourceLocation Loc,
6636                                 QualType lhsType, QualType rhsType) {
6637  // Fake up an opaque expression.  We don't actually care about what
6638  // cast operations are required, so if CheckAssignmentConstraints
6639  // adds casts to this they'll be wasted, but fortunately that doesn't
6640  // usually happen on valid code.
6641  OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
6642  ExprResult rhsPtr = &rhs;
6643  CastKind K = CK_Invalid;
6644
6645  return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6646}
6647
6648/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6649/// has code to accommodate several GCC extensions when type checking
6650/// pointers. Here are some objectionable examples that GCC considers warnings:
6651///
6652///  int a, *pint;
6653///  short *pshort;
6654///  struct foo *pfoo;
6655///
6656///  pint = pshort; // warning: assignment from incompatible pointer type
6657///  a = pint; // warning: assignment makes integer from pointer without a cast
6658///  pint = a; // warning: assignment makes pointer from integer without a cast
6659///  pint = pfoo; // warning: assignment from incompatible pointer type
6660///
6661/// As a result, the code for dealing with pointers is more complex than the
6662/// C99 spec dictates.
6663///
6664/// Sets 'Kind' for any result kind except Incompatible.
6665Sema::AssignConvertType
6666Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
6667                                 CastKind &Kind) {
6668  QualType rhsType = rhs.get()->getType();
6669
6670  // Get canonical types.  We're not formatting these types, just comparing
6671  // them.
6672  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6673  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
6674
6675  // Common case: no conversion required.
6676  if (lhsType == rhsType) {
6677    Kind = CK_NoOp;
6678    return Compatible;
6679  }
6680
6681  // If the left-hand side is a reference type, then we are in a
6682  // (rare!) case where we've allowed the use of references in C,
6683  // e.g., as a parameter type in a built-in function. In this case,
6684  // just make sure that the type referenced is compatible with the
6685  // right-hand side type. The caller is responsible for adjusting
6686  // lhsType so that the resulting expression does not have reference
6687  // type.
6688  if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
6689    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6690      Kind = CK_LValueBitCast;
6691      return Compatible;
6692    }
6693    return Incompatible;
6694  }
6695
6696  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6697  // to the same ExtVector type.
6698  if (lhsType->isExtVectorType()) {
6699    if (rhsType->isExtVectorType())
6700      return Incompatible;
6701    if (rhsType->isArithmeticType()) {
6702      // CK_VectorSplat does T -> vector T, so first cast to the
6703      // element type.
6704      QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6705      if (elType != rhsType) {
6706        Kind = PrepareScalarCast(*this, rhs, elType);
6707        rhs = ImpCastExprToType(rhs.take(), elType, Kind);
6708      }
6709      Kind = CK_VectorSplat;
6710      return Compatible;
6711    }
6712  }
6713
6714  // Conversions to or from vector type.
6715  if (lhsType->isVectorType() || rhsType->isVectorType()) {
6716    if (lhsType->isVectorType() && rhsType->isVectorType()) {
6717      // Allow assignments of an AltiVec vector type to an equivalent GCC
6718      // vector type and vice versa
6719      if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6720        Kind = CK_BitCast;
6721        return Compatible;
6722      }
6723
6724      // If we are allowing lax vector conversions, and LHS and RHS are both
6725      // vectors, the total size only needs to be the same. This is a bitcast;
6726      // no bits are changed but the result type is different.
6727      if (getLangOptions().LaxVectorConversions &&
6728          (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
6729        Kind = CK_BitCast;
6730        return IncompatibleVectors;
6731      }
6732    }
6733    return Incompatible;
6734  }
6735
6736  // Arithmetic conversions.
6737  if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
6738      !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
6739    Kind = PrepareScalarCast(*this, rhs, lhsType);
6740    return Compatible;
6741  }
6742
6743  // Conversions to normal pointers.
6744  if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6745    // U* -> T*
6746    if (isa<PointerType>(rhsType)) {
6747      Kind = CK_BitCast;
6748      return checkPointerTypesForAssignment(*this, lhsType, rhsType);
6749    }
6750
6751    // int -> T*
6752    if (rhsType->isIntegerType()) {
6753      Kind = CK_IntegralToPointer; // FIXME: null?
6754      return IntToPointer;
6755    }
6756
6757    // C pointers are not compatible with ObjC object pointers,
6758    // with two exceptions:
6759    if (isa<ObjCObjectPointerType>(rhsType)) {
6760      //  - conversions to void*
6761      if (lhsPointer->getPointeeType()->isVoidType()) {
6762        Kind = CK_AnyPointerToObjCPointerCast;
6763        return Compatible;
6764      }
6765
6766      //  - conversions from 'Class' to the redefinition type
6767      if (rhsType->isObjCClassType() &&
6768          Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
6769        Kind = CK_BitCast;
6770        return Compatible;
6771      }
6772
6773      Kind = CK_BitCast;
6774      return IncompatiblePointer;
6775    }
6776
6777    // U^ -> void*
6778    if (rhsType->getAs<BlockPointerType>()) {
6779      if (lhsPointer->getPointeeType()->isVoidType()) {
6780        Kind = CK_BitCast;
6781        return Compatible;
6782      }
6783    }
6784
6785    return Incompatible;
6786  }
6787
6788  // Conversions to block pointers.
6789  if (isa<BlockPointerType>(lhsType)) {
6790    // U^ -> T^
6791    if (rhsType->isBlockPointerType()) {
6792      Kind = CK_AnyPointerToBlockPointerCast;
6793      return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
6794    }
6795
6796    // int or null -> T^
6797    if (rhsType->isIntegerType()) {
6798      Kind = CK_IntegralToPointer; // FIXME: null
6799      return IntToBlockPointer;
6800    }
6801
6802    // id -> T^
6803    if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6804      Kind = CK_AnyPointerToBlockPointerCast;
6805      return Compatible;
6806    }
6807
6808    // void* -> T^
6809    if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
6810      if (RHSPT->getPointeeType()->isVoidType()) {
6811        Kind = CK_AnyPointerToBlockPointerCast;
6812        return Compatible;
6813      }
6814
6815    return Incompatible;
6816  }
6817
6818  // Conversions to Objective-C pointers.
6819  if (isa<ObjCObjectPointerType>(lhsType)) {
6820    // A* -> B*
6821    if (rhsType->isObjCObjectPointerType()) {
6822      Kind = CK_BitCast;
6823      return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
6824    }
6825
6826    // int or null -> A*
6827    if (rhsType->isIntegerType()) {
6828      Kind = CK_IntegralToPointer; // FIXME: null
6829      return IntToPointer;
6830    }
6831
6832    // In general, C pointers are not compatible with ObjC object pointers,
6833    // with two exceptions:
6834    if (isa<PointerType>(rhsType)) {
6835      //  - conversions from 'void*'
6836      if (rhsType->isVoidPointerType()) {
6837        Kind = CK_AnyPointerToObjCPointerCast;
6838        return Compatible;
6839      }
6840
6841      //  - conversions to 'Class' from its redefinition type
6842      if (lhsType->isObjCClassType() &&
6843          Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6844        Kind = CK_BitCast;
6845        return Compatible;
6846      }
6847
6848      Kind = CK_AnyPointerToObjCPointerCast;
6849      return IncompatiblePointer;
6850    }
6851
6852    // T^ -> A*
6853    if (rhsType->isBlockPointerType()) {
6854      Kind = CK_AnyPointerToObjCPointerCast;
6855      return Compatible;
6856    }
6857
6858    return Incompatible;
6859  }
6860
6861  // Conversions from pointers that are not covered by the above.
6862  if (isa<PointerType>(rhsType)) {
6863    // T* -> _Bool
6864    if (lhsType == Context.BoolTy) {
6865      Kind = CK_PointerToBoolean;
6866      return Compatible;
6867    }
6868
6869    // T* -> int
6870    if (lhsType->isIntegerType()) {
6871      Kind = CK_PointerToIntegral;
6872      return PointerToInt;
6873    }
6874
6875    return Incompatible;
6876  }
6877
6878  // Conversions from Objective-C pointers that are not covered by the above.
6879  if (isa<ObjCObjectPointerType>(rhsType)) {
6880    // T* -> _Bool
6881    if (lhsType == Context.BoolTy) {
6882      Kind = CK_PointerToBoolean;
6883      return Compatible;
6884    }
6885
6886    // T* -> int
6887    if (lhsType->isIntegerType()) {
6888      Kind = CK_PointerToIntegral;
6889      return PointerToInt;
6890    }
6891
6892    return Incompatible;
6893  }
6894
6895  // struct A -> struct B
6896  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
6897    if (Context.typesAreCompatible(lhsType, rhsType)) {
6898      Kind = CK_NoOp;
6899      return Compatible;
6900    }
6901  }
6902
6903  return Incompatible;
6904}
6905
6906/// \brief Constructs a transparent union from an expression that is
6907/// used to initialize the transparent union.
6908static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
6909                                      QualType UnionType, FieldDecl *Field) {
6910  // Build an initializer list that designates the appropriate member
6911  // of the transparent union.
6912  Expr *E = EResult.take();
6913  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6914                                                   &E, 1,
6915                                                   SourceLocation());
6916  Initializer->setType(UnionType);
6917  Initializer->setInitializedFieldInUnion(Field);
6918
6919  // Build a compound literal constructing a value of the transparent
6920  // union type from this initializer list.
6921  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6922  EResult = S.Owned(
6923    new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6924                                VK_RValue, Initializer, false));
6925}
6926
6927Sema::AssignConvertType
6928Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6929  QualType FromType = rExpr.get()->getType();
6930
6931  // If the ArgType is a Union type, we want to handle a potential
6932  // transparent_union GCC extension.
6933  const RecordType *UT = ArgType->getAsUnionType();
6934  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6935    return Incompatible;
6936
6937  // The field to initialize within the transparent union.
6938  RecordDecl *UD = UT->getDecl();
6939  FieldDecl *InitField = 0;
6940  // It's compatible if the expression matches any of the fields.
6941  for (RecordDecl::field_iterator it = UD->field_begin(),
6942         itend = UD->field_end();
6943       it != itend; ++it) {
6944    if (it->getType()->isPointerType()) {
6945      // If the transparent union contains a pointer type, we allow:
6946      // 1) void pointer
6947      // 2) null pointer constant
6948      if (FromType->isPointerType())
6949        if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
6950          rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
6951          InitField = *it;
6952          break;
6953        }
6954
6955      if (rExpr.get()->isNullPointerConstant(Context,
6956                                       Expr::NPC_ValueDependentIsNull)) {
6957        rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
6958        InitField = *it;
6959        break;
6960      }
6961    }
6962
6963    CastKind Kind = CK_Invalid;
6964    if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
6965          == Compatible) {
6966      rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
6967      InitField = *it;
6968      break;
6969    }
6970  }
6971
6972  if (!InitField)
6973    return Incompatible;
6974
6975  ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
6976  return Compatible;
6977}
6978
6979Sema::AssignConvertType
6980Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
6981  if (getLangOptions().CPlusPlus) {
6982    if (!lhsType->isRecordType()) {
6983      // C++ 5.17p3: If the left operand is not of class type, the
6984      // expression is implicitly converted (C++ 4) to the
6985      // cv-unqualified type of the left operand.
6986      ExprResult Res = PerformImplicitConversion(rExpr.get(),
6987                                                 lhsType.getUnqualifiedType(),
6988                                                 AA_Assigning);
6989      if (Res.isInvalid())
6990        return Incompatible;
6991      rExpr = move(Res);
6992      return Compatible;
6993    }
6994
6995    // FIXME: Currently, we fall through and treat C++ classes like C
6996    // structures.
6997  }
6998
6999  // C99 6.5.16.1p1: the left operand is a pointer and the right is
7000  // a null pointer constant.
7001  if ((lhsType->isPointerType() ||
7002       lhsType->isObjCObjectPointerType() ||
7003       lhsType->isBlockPointerType())
7004      && rExpr.get()->isNullPointerConstant(Context,
7005                                      Expr::NPC_ValueDependentIsNull)) {
7006    rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
7007    return Compatible;
7008  }
7009
7010  // This check seems unnatural, however it is necessary to ensure the proper
7011  // conversion of functions/arrays. If the conversion were done for all
7012  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7013  // expressions that suppress this implicit conversion (&, sizeof).
7014  //
7015  // Suppress this for references: C++ 8.5.3p5.
7016  if (!lhsType->isReferenceType()) {
7017    rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
7018    if (rExpr.isInvalid())
7019      return Incompatible;
7020  }
7021
7022  CastKind Kind = CK_Invalid;
7023  Sema::AssignConvertType result =
7024    CheckAssignmentConstraints(lhsType, rExpr, Kind);
7025
7026  // C99 6.5.16.1p2: The value of the right operand is converted to the
7027  // type of the assignment expression.
7028  // CheckAssignmentConstraints allows the left-hand side to be a reference,
7029  // so that we can use references in built-in functions even in C.
7030  // The getNonReferenceType() call makes sure that the resulting expression
7031  // does not have reference type.
7032  if (result != Incompatible && rExpr.get()->getType() != lhsType)
7033    rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
7034  return result;
7035}
7036
7037QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
7038  Diag(Loc, diag::err_typecheck_invalid_operands)
7039    << lex.get()->getType() << rex.get()->getType()
7040    << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7041  return QualType();
7042}
7043
7044QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
7045  // For conversion purposes, we ignore any qualifiers.
7046  // For example, "const float" and "float" are equivalent.
7047  QualType lhsType =
7048    Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
7049  QualType rhsType =
7050    Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
7051
7052  // If the vector types are identical, return.
7053  if (lhsType == rhsType)
7054    return lhsType;
7055
7056  // Handle the case of a vector & extvector type of the same size and element
7057  // type.  It would be nice if we only had one vector type someday.
7058  if (getLangOptions().LaxVectorConversions) {
7059    if (const VectorType *LV = lhsType->getAs<VectorType>()) {
7060      if (const VectorType *RV = rhsType->getAs<VectorType>()) {
7061        if (LV->getElementType() == RV->getElementType() &&
7062            LV->getNumElements() == RV->getNumElements()) {
7063          if (lhsType->isExtVectorType()) {
7064            rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
7065            return lhsType;
7066          }
7067
7068          lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
7069          return rhsType;
7070        } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
7071          // If we are allowing lax vector conversions, and LHS and RHS are both
7072          // vectors, the total size only needs to be the same. This is a
7073          // bitcast; no bits are changed but the result type is different.
7074          rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
7075          return lhsType;
7076        }
7077      }
7078    }
7079  }
7080
7081  // Handle the case of equivalent AltiVec and GCC vector types
7082  if (lhsType->isVectorType() && rhsType->isVectorType() &&
7083      Context.areCompatibleVectorTypes(lhsType, rhsType)) {
7084    lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
7085    return rhsType;
7086  }
7087
7088  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
7089  // swap back (so that we don't reverse the inputs to a subtract, for instance.
7090  bool swapped = false;
7091  if (rhsType->isExtVectorType()) {
7092    swapped = true;
7093    std::swap(rex, lex);
7094    std::swap(rhsType, lhsType);
7095  }
7096
7097  // Handle the case of an ext vector and scalar.
7098  if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
7099    QualType EltTy = LV->getElementType();
7100    if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
7101      int order = Context.getIntegerTypeOrder(EltTy, rhsType);
7102      if (order > 0)
7103        rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
7104      if (order >= 0) {
7105        rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
7106        if (swapped) std::swap(rex, lex);
7107        return lhsType;
7108      }
7109    }
7110    if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
7111        rhsType->isRealFloatingType()) {
7112      int order = Context.getFloatingTypeOrder(EltTy, rhsType);
7113      if (order > 0)
7114        rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
7115      if (order >= 0) {
7116        rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
7117        if (swapped) std::swap(rex, lex);
7118        return lhsType;
7119      }
7120    }
7121  }
7122
7123  // Vectors of different size or scalar and non-ext-vector are errors.
7124  Diag(Loc, diag::err_typecheck_vector_not_convertable)
7125    << lex.get()->getType() << rex.get()->getType()
7126    << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7127  return QualType();
7128}
7129
7130QualType Sema::CheckMultiplyDivideOperands(
7131  ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
7132  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
7133    return CheckVectorOperands(Loc, lex, rex);
7134
7135  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
7136  if (lex.isInvalid() || rex.isInvalid())
7137    return QualType();
7138
7139  if (!lex.get()->getType()->isArithmeticType() ||
7140      !rex.get()->getType()->isArithmeticType())
7141    return InvalidOperands(Loc, lex, rex);
7142
7143  // Check for division by zero.
7144  if (isDiv &&
7145      rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7146    DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
7147                                     << rex.get()->getSourceRange());
7148
7149  return compType;
7150}
7151
7152QualType Sema::CheckRemainderOperands(
7153  ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7154  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7155    if (lex.get()->getType()->hasIntegerRepresentation() &&
7156        rex.get()->getType()->hasIntegerRepresentation())
7157      return CheckVectorOperands(Loc, lex, rex);
7158    return InvalidOperands(Loc, lex, rex);
7159  }
7160
7161  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
7162  if (lex.isInvalid() || rex.isInvalid())
7163    return QualType();
7164
7165  if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
7166    return InvalidOperands(Loc, lex, rex);
7167
7168  // Check for remainder by zero.
7169  if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7170    DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
7171                                 << rex.get()->getSourceRange());
7172
7173  return compType;
7174}
7175
7176QualType Sema::CheckAdditionOperands( // C99 6.5.6
7177  ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
7178  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7179    QualType compType = CheckVectorOperands(Loc, lex, rex);
7180    if (CompLHSTy) *CompLHSTy = compType;
7181    return compType;
7182  }
7183
7184  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
7185  if (lex.isInvalid() || rex.isInvalid())
7186    return QualType();
7187
7188  // handle the common case first (both operands are arithmetic).
7189  if (lex.get()->getType()->isArithmeticType() &&
7190      rex.get()->getType()->isArithmeticType()) {
7191    if (CompLHSTy) *CompLHSTy = compType;
7192    return compType;
7193  }
7194
7195  // Put any potential pointer into PExp
7196  Expr* PExp = lex.get(), *IExp = rex.get();
7197  if (IExp->getType()->isAnyPointerType())
7198    std::swap(PExp, IExp);
7199
7200  if (PExp->getType()->isAnyPointerType()) {
7201
7202    if (IExp->getType()->isIntegerType()) {
7203      QualType PointeeTy = PExp->getType()->getPointeeType();
7204
7205      // Check for arithmetic on pointers to incomplete types.
7206      if (PointeeTy->isVoidType()) {
7207        if (getLangOptions().CPlusPlus) {
7208          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
7209            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7210          return QualType();
7211        }
7212
7213        // GNU extension: arithmetic on pointer to void
7214        Diag(Loc, diag::ext_gnu_void_ptr)
7215          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7216      } else if (PointeeTy->isFunctionType()) {
7217        if (getLangOptions().CPlusPlus) {
7218          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
7219            << lex.get()->getType() << lex.get()->getSourceRange();
7220          return QualType();
7221        }
7222
7223        // GNU extension: arithmetic on pointer to function
7224        Diag(Loc, diag::ext_gnu_ptr_func_arith)
7225          << lex.get()->getType() << lex.get()->getSourceRange();
7226      } else {
7227        // Check if we require a complete type.
7228        if (((PExp->getType()->isPointerType() &&
7229              !PExp->getType()->isDependentType()) ||
7230              PExp->getType()->isObjCObjectPointerType()) &&
7231             RequireCompleteType(Loc, PointeeTy,
7232                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
7233                             << PExp->getSourceRange()
7234                             << PExp->getType()))
7235          return QualType();
7236      }
7237      // Diagnose bad cases where we step over interface counts.
7238      if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
7239        Diag(Loc, diag::err_arithmetic_nonfragile_interface)
7240          << PointeeTy << PExp->getSourceRange();
7241        return QualType();
7242      }
7243
7244      if (CompLHSTy) {
7245        QualType LHSTy = Context.isPromotableBitField(lex.get());
7246        if (LHSTy.isNull()) {
7247          LHSTy = lex.get()->getType();
7248          if (LHSTy->isPromotableIntegerType())
7249            LHSTy = Context.getPromotedIntegerType(LHSTy);
7250        }
7251        *CompLHSTy = LHSTy;
7252      }
7253      return PExp->getType();
7254    }
7255  }
7256
7257  return InvalidOperands(Loc, lex, rex);
7258}
7259
7260// C99 6.5.6
7261QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
7262                                        SourceLocation Loc, QualType* CompLHSTy) {
7263  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7264    QualType compType = CheckVectorOperands(Loc, lex, rex);
7265    if (CompLHSTy) *CompLHSTy = compType;
7266    return compType;
7267  }
7268
7269  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
7270  if (lex.isInvalid() || rex.isInvalid())
7271    return QualType();
7272
7273  // Enforce type constraints: C99 6.5.6p3.
7274
7275  // Handle the common case first (both operands are arithmetic).
7276  if (lex.get()->getType()->isArithmeticType() &&
7277      rex.get()->getType()->isArithmeticType()) {
7278    if (CompLHSTy) *CompLHSTy = compType;
7279    return compType;
7280  }
7281
7282  // Either ptr - int   or   ptr - ptr.
7283  if (lex.get()->getType()->isAnyPointerType()) {
7284    QualType lpointee = lex.get()->getType()->getPointeeType();
7285
7286    // The LHS must be an completely-defined object type.
7287
7288    bool ComplainAboutVoid = false;
7289    Expr *ComplainAboutFunc = 0;
7290    if (lpointee->isVoidType()) {
7291      if (getLangOptions().CPlusPlus) {
7292        Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
7293          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7294        return QualType();
7295      }
7296
7297      // GNU C extension: arithmetic on pointer to void
7298      ComplainAboutVoid = true;
7299    } else if (lpointee->isFunctionType()) {
7300      if (getLangOptions().CPlusPlus) {
7301        Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
7302          << lex.get()->getType() << lex.get()->getSourceRange();
7303        return QualType();
7304      }
7305
7306      // GNU C extension: arithmetic on pointer to function
7307      ComplainAboutFunc = lex.get();
7308    } else if (!lpointee->isDependentType() &&
7309               RequireCompleteType(Loc, lpointee,
7310                                   PDiag(diag::err_typecheck_sub_ptr_object)
7311                                     << lex.get()->getSourceRange()
7312                                     << lex.get()->getType()))
7313      return QualType();
7314
7315    // Diagnose bad cases where we step over interface counts.
7316    if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
7317      Diag(Loc, diag::err_arithmetic_nonfragile_interface)
7318        << lpointee << lex.get()->getSourceRange();
7319      return QualType();
7320    }
7321
7322    // The result type of a pointer-int computation is the pointer type.
7323    if (rex.get()->getType()->isIntegerType()) {
7324      if (ComplainAboutVoid)
7325        Diag(Loc, diag::ext_gnu_void_ptr)
7326          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7327      if (ComplainAboutFunc)
7328        Diag(Loc, diag::ext_gnu_ptr_func_arith)
7329          << ComplainAboutFunc->getType()
7330          << ComplainAboutFunc->getSourceRange();
7331
7332      if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7333      return lex.get()->getType();
7334    }
7335
7336    // Handle pointer-pointer subtractions.
7337    if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
7338      QualType rpointee = RHSPTy->getPointeeType();
7339
7340      // RHS must be a completely-type object type.
7341      // Handle the GNU void* extension.
7342      if (rpointee->isVoidType()) {
7343        if (getLangOptions().CPlusPlus) {
7344          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
7345            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7346          return QualType();
7347        }
7348
7349        ComplainAboutVoid = true;
7350      } else if (rpointee->isFunctionType()) {
7351        if (getLangOptions().CPlusPlus) {
7352          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
7353            << rex.get()->getType() << rex.get()->getSourceRange();
7354          return QualType();
7355        }
7356
7357        // GNU extension: arithmetic on pointer to function
7358        if (!ComplainAboutFunc)
7359          ComplainAboutFunc = rex.get();
7360      } else if (!rpointee->isDependentType() &&
7361                 RequireCompleteType(Loc, rpointee,
7362                                     PDiag(diag::err_typecheck_sub_ptr_object)
7363                                       << rex.get()->getSourceRange()
7364                                       << rex.get()->getType()))
7365        return QualType();
7366
7367      if (getLangOptions().CPlusPlus) {
7368        // Pointee types must be the same: C++ [expr.add]
7369        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7370          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7371            << lex.get()->getType() << rex.get()->getType()
7372            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7373          return QualType();
7374        }
7375      } else {
7376        // Pointee types must be compatible C99 6.5.6p3
7377        if (!Context.typesAreCompatible(
7378                Context.getCanonicalType(lpointee).getUnqualifiedType(),
7379                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7380          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7381            << lex.get()->getType() << rex.get()->getType()
7382            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7383          return QualType();
7384        }
7385      }
7386
7387      if (ComplainAboutVoid)
7388        Diag(Loc, diag::ext_gnu_void_ptr)
7389          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7390      if (ComplainAboutFunc)
7391        Diag(Loc, diag::ext_gnu_ptr_func_arith)
7392          << ComplainAboutFunc->getType()
7393          << ComplainAboutFunc->getSourceRange();
7394
7395      if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7396      return Context.getPointerDiffType();
7397    }
7398  }
7399
7400  return InvalidOperands(Loc, lex, rex);
7401}
7402
7403static bool isScopedEnumerationType(QualType T) {
7404  if (const EnumType *ET = dyn_cast<EnumType>(T))
7405    return ET->getDecl()->isScoped();
7406  return false;
7407}
7408
7409static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
7410                                   SourceLocation Loc, unsigned Opc,
7411                                   QualType LHSTy) {
7412  llvm::APSInt Right;
7413  // Check right/shifter operand
7414  if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
7415    return;
7416
7417  if (Right.isNegative()) {
7418    S.DiagRuntimeBehavior(Loc, rex.get(),
7419                          S.PDiag(diag::warn_shift_negative)
7420                            << rex.get()->getSourceRange());
7421    return;
7422  }
7423  llvm::APInt LeftBits(Right.getBitWidth(),
7424                       S.Context.getTypeSize(lex.get()->getType()));
7425  if (Right.uge(LeftBits)) {
7426    S.DiagRuntimeBehavior(Loc, rex.get(),
7427                          S.PDiag(diag::warn_shift_gt_typewidth)
7428                            << rex.get()->getSourceRange());
7429    return;
7430  }
7431  if (Opc != BO_Shl)
7432    return;
7433
7434  // When left shifting an ICE which is signed, we can check for overflow which
7435  // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7436  // integers have defined behavior modulo one more than the maximum value
7437  // representable in the result type, so never warn for those.
7438  llvm::APSInt Left;
7439  if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
7440      LHSTy->hasUnsignedIntegerRepresentation())
7441    return;
7442  llvm::APInt ResultBits =
7443      static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7444  if (LeftBits.uge(ResultBits))
7445    return;
7446  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7447  Result = Result.shl(Right);
7448
7449  // Print the bit representation of the signed integer as an unsigned
7450  // hexadecimal number.
7451  llvm::SmallString<40> HexResult;
7452  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7453
7454  // If we are only missing a sign bit, this is less likely to result in actual
7455  // bugs -- if the result is cast back to an unsigned type, it will have the
7456  // expected value. Thus we place this behind a different warning that can be
7457  // turned off separately if needed.
7458  if (LeftBits == ResultBits - 1) {
7459    S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7460        << HexResult.str() << LHSTy
7461        << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7462    return;
7463  }
7464
7465  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7466    << HexResult.str() << Result.getMinSignedBits() << LHSTy
7467    << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7468}
7469
7470// C99 6.5.7
7471QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
7472                                  unsigned Opc, bool isCompAssign) {
7473  // C99 6.5.7p2: Each of the operands shall have integer type.
7474  if (!lex.get()->getType()->hasIntegerRepresentation() ||
7475      !rex.get()->getType()->hasIntegerRepresentation())
7476    return InvalidOperands(Loc, lex, rex);
7477
7478  // C++0x: Don't allow scoped enums. FIXME: Use something better than
7479  // hasIntegerRepresentation() above instead of this.
7480  if (isScopedEnumerationType(lex.get()->getType()) ||
7481      isScopedEnumerationType(rex.get()->getType())) {
7482    return InvalidOperands(Loc, lex, rex);
7483  }
7484
7485  // Vector shifts promote their scalar inputs to vector type.
7486  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
7487    return CheckVectorOperands(Loc, lex, rex);
7488
7489  // Shifts don't perform usual arithmetic conversions, they just do integer
7490  // promotions on each operand. C99 6.5.7p3
7491
7492  // For the LHS, do usual unary conversions, but then reset them away
7493  // if this is a compound assignment.
7494  ExprResult old_lex = lex;
7495  lex = UsualUnaryConversions(lex.take());
7496  if (lex.isInvalid())
7497    return QualType();
7498  QualType LHSTy = lex.get()->getType();
7499  if (isCompAssign) lex = old_lex;
7500
7501  // The RHS is simpler.
7502  rex = UsualUnaryConversions(rex.take());
7503  if (rex.isInvalid())
7504    return QualType();
7505
7506  // Sanity-check shift operands
7507  DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
7508
7509  // "The type of the result is that of the promoted left operand."
7510  return LHSTy;
7511}
7512
7513static bool IsWithinTemplateSpecialization(Decl *D) {
7514  if (DeclContext *DC = D->getDeclContext()) {
7515    if (isa<ClassTemplateSpecializationDecl>(DC))
7516      return true;
7517    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7518      return FD->isFunctionTemplateSpecialization();
7519  }
7520  return false;
7521}
7522
7523// C99 6.5.8, C++ [expr.rel]
7524QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
7525                                    unsigned OpaqueOpc, bool isRelational) {
7526  BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7527
7528  // Handle vector comparisons separately.
7529  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
7530    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
7531
7532  QualType lType = lex.get()->getType();
7533  QualType rType = rex.get()->getType();
7534
7535  Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7536  Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
7537  QualType LHSStrippedType = LHSStripped->getType();
7538  QualType RHSStrippedType = RHSStripped->getType();
7539
7540
7541
7542  // Two different enums will raise a warning when compared.
7543  if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7544    if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7545      if (LHSEnumType->getDecl()->getIdentifier() &&
7546          RHSEnumType->getDecl()->getIdentifier() &&
7547          !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7548        Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7549          << LHSStrippedType << RHSStrippedType
7550          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7551      }
7552    }
7553  }
7554
7555  if (!lType->hasFloatingRepresentation() &&
7556      !(lType->isBlockPointerType() && isRelational) &&
7557      !lex.get()->getLocStart().isMacroID() &&
7558      !rex.get()->getLocStart().isMacroID()) {
7559    // For non-floating point types, check for self-comparisons of the form
7560    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7561    // often indicate logic errors in the program.
7562    //
7563    // NOTE: Don't warn about comparison expressions resulting from macro
7564    // expansion. Also don't warn about comparisons which are only self
7565    // comparisons within a template specialization. The warnings should catch
7566    // obvious cases in the definition of the template anyways. The idea is to
7567    // warn when the typed comparison operator will always evaluate to the same
7568    // result.
7569    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
7570      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
7571        if (DRL->getDecl() == DRR->getDecl() &&
7572            !IsWithinTemplateSpecialization(DRL->getDecl())) {
7573          DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7574                              << 0 // self-
7575                              << (Opc == BO_EQ
7576                                  || Opc == BO_LE
7577                                  || Opc == BO_GE));
7578        } else if (lType->isArrayType() && rType->isArrayType() &&
7579                   !DRL->getDecl()->getType()->isReferenceType() &&
7580                   !DRR->getDecl()->getType()->isReferenceType()) {
7581            // what is it always going to eval to?
7582            char always_evals_to;
7583            switch(Opc) {
7584            case BO_EQ: // e.g. array1 == array2
7585              always_evals_to = 0; // false
7586              break;
7587            case BO_NE: // e.g. array1 != array2
7588              always_evals_to = 1; // true
7589              break;
7590            default:
7591              // best we can say is 'a constant'
7592              always_evals_to = 2; // e.g. array1 <= array2
7593              break;
7594            }
7595            DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7596                                << 1 // array
7597                                << always_evals_to);
7598        }
7599      }
7600    }
7601
7602    if (isa<CastExpr>(LHSStripped))
7603      LHSStripped = LHSStripped->IgnoreParenCasts();
7604    if (isa<CastExpr>(RHSStripped))
7605      RHSStripped = RHSStripped->IgnoreParenCasts();
7606
7607    // Warn about comparisons against a string constant (unless the other
7608    // operand is null), the user probably wants strcmp.
7609    Expr *literalString = 0;
7610    Expr *literalStringStripped = 0;
7611    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7612        !RHSStripped->isNullPointerConstant(Context,
7613                                            Expr::NPC_ValueDependentIsNull)) {
7614      literalString = lex.get();
7615      literalStringStripped = LHSStripped;
7616    } else if ((isa<StringLiteral>(RHSStripped) ||
7617                isa<ObjCEncodeExpr>(RHSStripped)) &&
7618               !LHSStripped->isNullPointerConstant(Context,
7619                                            Expr::NPC_ValueDependentIsNull)) {
7620      literalString = rex.get();
7621      literalStringStripped = RHSStripped;
7622    }
7623
7624    if (literalString) {
7625      std::string resultComparison;
7626      switch (Opc) {
7627      case BO_LT: resultComparison = ") < 0"; break;
7628      case BO_GT: resultComparison = ") > 0"; break;
7629      case BO_LE: resultComparison = ") <= 0"; break;
7630      case BO_GE: resultComparison = ") >= 0"; break;
7631      case BO_EQ: resultComparison = ") == 0"; break;
7632      case BO_NE: resultComparison = ") != 0"; break;
7633      default: assert(false && "Invalid comparison operator");
7634      }
7635
7636      DiagRuntimeBehavior(Loc, 0,
7637        PDiag(diag::warn_stringcompare)
7638          << isa<ObjCEncodeExpr>(literalStringStripped)
7639          << literalString->getSourceRange());
7640    }
7641  }
7642
7643  // C99 6.5.8p3 / C99 6.5.9p4
7644  if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
7645    UsualArithmeticConversions(lex, rex);
7646    if (lex.isInvalid() || rex.isInvalid())
7647      return QualType();
7648  }
7649  else {
7650    lex = UsualUnaryConversions(lex.take());
7651    if (lex.isInvalid())
7652      return QualType();
7653
7654    rex = UsualUnaryConversions(rex.take());
7655    if (rex.isInvalid())
7656      return QualType();
7657  }
7658
7659  lType = lex.get()->getType();
7660  rType = rex.get()->getType();
7661
7662  // The result of comparisons is 'bool' in C++, 'int' in C.
7663  QualType ResultTy = Context.getLogicalOperationType();
7664
7665  if (isRelational) {
7666    if (lType->isRealType() && rType->isRealType())
7667      return ResultTy;
7668  } else {
7669    // Check for comparisons of floating point operands using != and ==.
7670    if (lType->hasFloatingRepresentation())
7671      CheckFloatComparison(Loc, lex.get(), rex.get());
7672
7673    if (lType->isArithmeticType() && rType->isArithmeticType())
7674      return ResultTy;
7675  }
7676
7677  bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
7678                                              Expr::NPC_ValueDependentIsNull);
7679  bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
7680                                              Expr::NPC_ValueDependentIsNull);
7681
7682  // All of the following pointer-related warnings are GCC extensions, except
7683  // when handling null pointer constants.
7684  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
7685    QualType LCanPointeeTy =
7686      Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
7687    QualType RCanPointeeTy =
7688      Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
7689
7690    if (getLangOptions().CPlusPlus) {
7691      if (LCanPointeeTy == RCanPointeeTy)
7692        return ResultTy;
7693      if (!isRelational &&
7694          (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7695        // Valid unless comparison between non-null pointer and function pointer
7696        // This is a gcc extension compatibility comparison.
7697        // In a SFINAE context, we treat this as a hard error to maintain
7698        // conformance with the C++ standard.
7699        if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7700            && !LHSIsNull && !RHSIsNull) {
7701          Diag(Loc,
7702               isSFINAEContext()?
7703                   diag::err_typecheck_comparison_of_fptr_to_void
7704                 : diag::ext_typecheck_comparison_of_fptr_to_void)
7705            << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7706
7707          if (isSFINAEContext())
7708            return QualType();
7709
7710          rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7711          return ResultTy;
7712        }
7713      }
7714
7715      // C++ [expr.rel]p2:
7716      //   [...] Pointer conversions (4.10) and qualification
7717      //   conversions (4.4) are performed on pointer operands (or on
7718      //   a pointer operand and a null pointer constant) to bring
7719      //   them to their composite pointer type. [...]
7720      //
7721      // C++ [expr.eq]p1 uses the same notion for (in)equality
7722      // comparisons of pointers.
7723      bool NonStandardCompositeType = false;
7724      QualType T = FindCompositePointerType(Loc, lex, rex,
7725                              isSFINAEContext()? 0 : &NonStandardCompositeType);
7726      if (T.isNull()) {
7727        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
7728          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7729        return QualType();
7730      } else if (NonStandardCompositeType) {
7731        Diag(Loc,
7732             diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7733          << lType << rType << T
7734          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7735      }
7736
7737      lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7738      rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
7739      return ResultTy;
7740    }
7741    // C99 6.5.9p2 and C99 6.5.8p2
7742    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7743                                   RCanPointeeTy.getUnqualifiedType())) {
7744      // Valid unless a relational comparison of function pointers
7745      if (isRelational && LCanPointeeTy->isFunctionType()) {
7746        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7747          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7748      }
7749    } else if (!isRelational &&
7750               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7751      // Valid unless comparison between non-null pointer and function pointer
7752      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7753          && !LHSIsNull && !RHSIsNull) {
7754        Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
7755          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7756      }
7757    } else {
7758      // Invalid
7759      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7760        << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7761    }
7762    if (LCanPointeeTy != RCanPointeeTy) {
7763      if (LHSIsNull && !RHSIsNull)
7764        lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
7765      else
7766        rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7767    }
7768    return ResultTy;
7769  }
7770
7771  if (getLangOptions().CPlusPlus) {
7772    // Comparison of nullptr_t with itself.
7773    if (lType->isNullPtrType() && rType->isNullPtrType())
7774      return ResultTy;
7775
7776    // Comparison of pointers with null pointer constants and equality
7777    // comparisons of member pointers to null pointer constants.
7778    if (RHSIsNull &&
7779        ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
7780         (!isRelational &&
7781          (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
7782      rex = ImpCastExprToType(rex.take(), lType,
7783                        lType->isMemberPointerType()
7784                          ? CK_NullToMemberPointer
7785                          : CK_NullToPointer);
7786      return ResultTy;
7787    }
7788    if (LHSIsNull &&
7789        ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
7790         (!isRelational &&
7791          (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
7792      lex = ImpCastExprToType(lex.take(), rType,
7793                        rType->isMemberPointerType()
7794                          ? CK_NullToMemberPointer
7795                          : CK_NullToPointer);
7796      return ResultTy;
7797    }
7798
7799    // Comparison of member pointers.
7800    if (!isRelational &&
7801        lType->isMemberPointerType() && rType->isMemberPointerType()) {
7802      // C++ [expr.eq]p2:
7803      //   In addition, pointers to members can be compared, or a pointer to
7804      //   member and a null pointer constant. Pointer to member conversions
7805      //   (4.11) and qualification conversions (4.4) are performed to bring
7806      //   them to a common type. If one operand is a null pointer constant,
7807      //   the common type is the type of the other operand. Otherwise, the
7808      //   common type is a pointer to member type similar (4.4) to the type
7809      //   of one of the operands, with a cv-qualification signature (4.4)
7810      //   that is the union of the cv-qualification signatures of the operand
7811      //   types.
7812      bool NonStandardCompositeType = false;
7813      QualType T = FindCompositePointerType(Loc, lex, rex,
7814                              isSFINAEContext()? 0 : &NonStandardCompositeType);
7815      if (T.isNull()) {
7816        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
7817          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7818        return QualType();
7819      } else if (NonStandardCompositeType) {
7820        Diag(Loc,
7821             diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7822          << lType << rType << T
7823          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7824      }
7825
7826      lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7827      rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
7828      return ResultTy;
7829    }
7830
7831    // Handle scoped enumeration types specifically, since they don't promote
7832    // to integers.
7833    if (lex.get()->getType()->isEnumeralType() &&
7834        Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
7835      return ResultTy;
7836  }
7837
7838  // Handle block pointer types.
7839  if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
7840    QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7841    QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
7842
7843    if (!LHSIsNull && !RHSIsNull &&
7844        !Context.typesAreCompatible(lpointee, rpointee)) {
7845      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7846        << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7847    }
7848    rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7849    return ResultTy;
7850  }
7851
7852  // Allow block pointers to be compared with null pointer constants.
7853  if (!isRelational
7854      && ((lType->isBlockPointerType() && rType->isPointerType())
7855          || (lType->isPointerType() && rType->isBlockPointerType()))) {
7856    if (!LHSIsNull && !RHSIsNull) {
7857      if (!((rType->isPointerType() && rType->castAs<PointerType>()
7858             ->getPointeeType()->isVoidType())
7859            || (lType->isPointerType() && lType->castAs<PointerType>()
7860                ->getPointeeType()->isVoidType())))
7861        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7862          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7863    }
7864    if (LHSIsNull && !RHSIsNull)
7865      lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
7866    else
7867      rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7868    return ResultTy;
7869  }
7870
7871  if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7872    const PointerType *LPT = lType->getAs<PointerType>();
7873    const PointerType *RPT = rType->getAs<PointerType>();
7874    if (LPT || RPT) {
7875      bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7876      bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7877
7878      if (!LPtrToVoid && !RPtrToVoid &&
7879          !Context.typesAreCompatible(lType, rType)) {
7880        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7881          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7882      }
7883      if (LHSIsNull && !RHSIsNull)
7884        lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
7885      else
7886        rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7887      return ResultTy;
7888    }
7889    if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
7890      if (!Context.areComparableObjCPointerTypes(lType, rType))
7891        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7892          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7893      if (LHSIsNull && !RHSIsNull)
7894        lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
7895      else
7896        rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7897      return ResultTy;
7898    }
7899  }
7900  if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7901      (lType->isIntegerType() && rType->isAnyPointerType())) {
7902    unsigned DiagID = 0;
7903    bool isError = false;
7904    if ((LHSIsNull && lType->isIntegerType()) ||
7905        (RHSIsNull && rType->isIntegerType())) {
7906      if (isRelational && !getLangOptions().CPlusPlus)
7907        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7908    } else if (isRelational && !getLangOptions().CPlusPlus)
7909      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7910    else if (getLangOptions().CPlusPlus) {
7911      DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7912      isError = true;
7913    } else
7914      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7915
7916    if (DiagID) {
7917      Diag(Loc, DiagID)
7918        << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7919      if (isError)
7920        return QualType();
7921    }
7922
7923    if (lType->isIntegerType())
7924      lex = ImpCastExprToType(lex.take(), rType,
7925                        LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7926    else
7927      rex = ImpCastExprToType(rex.take(), lType,
7928                        RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7929    return ResultTy;
7930  }
7931
7932  // Handle block pointers.
7933  if (!isRelational && RHSIsNull
7934      && lType->isBlockPointerType() && rType->isIntegerType()) {
7935    rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
7936    return ResultTy;
7937  }
7938  if (!isRelational && LHSIsNull
7939      && lType->isIntegerType() && rType->isBlockPointerType()) {
7940    lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
7941    return ResultTy;
7942  }
7943
7944  return InvalidOperands(Loc, lex, rex);
7945}
7946
7947/// CheckVectorCompareOperands - vector comparisons are a clang extension that
7948/// operates on extended vector types.  Instead of producing an IntTy result,
7949/// like a scalar comparison, a vector comparison produces a vector of integer
7950/// types.
7951QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
7952                                          SourceLocation Loc,
7953                                          bool isRelational) {
7954  // Check to make sure we're operating on vectors of the same type and width,
7955  // Allowing one side to be a scalar of element type.
7956  QualType vType = CheckVectorOperands(Loc, lex, rex);
7957  if (vType.isNull())
7958    return vType;
7959
7960  QualType lType = lex.get()->getType();
7961  QualType rType = rex.get()->getType();
7962
7963  // If AltiVec, the comparison results in a numeric type, i.e.
7964  // bool for C++, int for C
7965  if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7966    return Context.getLogicalOperationType();
7967
7968  // For non-floating point types, check for self-comparisons of the form
7969  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7970  // often indicate logic errors in the program.
7971  if (!lType->hasFloatingRepresentation()) {
7972    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7973      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
7974        if (DRL->getDecl() == DRR->getDecl())
7975          DiagRuntimeBehavior(Loc, 0,
7976                              PDiag(diag::warn_comparison_always)
7977                                << 0 // self-
7978                                << 2 // "a constant"
7979                              );
7980  }
7981
7982  // Check for comparisons of floating point operands using != and ==.
7983  if (!isRelational && lType->hasFloatingRepresentation()) {
7984    assert (rType->hasFloatingRepresentation());
7985    CheckFloatComparison(Loc, lex.get(), rex.get());
7986  }
7987
7988  // Return the type for the comparison, which is the same as vector type for
7989  // integer vectors, or an integer type of identical size and number of
7990  // elements for floating point vectors.
7991  if (lType->hasIntegerRepresentation())
7992    return lType;
7993
7994  const VectorType *VTy = lType->getAs<VectorType>();
7995  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7996  if (TypeSize == Context.getTypeSize(Context.IntTy))
7997    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7998  if (TypeSize == Context.getTypeSize(Context.LongTy))
7999    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8000
8001  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8002         "Unhandled vector element size in vector compare");
8003  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8004}
8005
8006inline QualType Sema::CheckBitwiseOperands(
8007  ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
8008  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
8009    if (lex.get()->getType()->hasIntegerRepresentation() &&
8010        rex.get()->getType()->hasIntegerRepresentation())
8011      return CheckVectorOperands(Loc, lex, rex);
8012
8013    return InvalidOperands(Loc, lex, rex);
8014  }
8015
8016  ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
8017  QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
8018  if (lexResult.isInvalid() || rexResult.isInvalid())
8019    return QualType();
8020  lex = lexResult.take();
8021  rex = rexResult.take();
8022
8023  if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
8024      rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
8025    return compType;
8026  return InvalidOperands(Loc, lex, rex);
8027}
8028
8029inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8030  ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
8031
8032  // Diagnose cases where the user write a logical and/or but probably meant a
8033  // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8034  // is a constant.
8035  if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
8036      rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
8037      // Don't warn in macros.
8038      !Loc.isMacroID()) {
8039    // If the RHS can be constant folded, and if it constant folds to something
8040    // that isn't 0 or 1 (which indicate a potential logical operation that
8041    // happened to fold to true/false) then warn.
8042    // Parens on the RHS are ignored.
8043    Expr::EvalResult Result;
8044    if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
8045      if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
8046          (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
8047        Diag(Loc, diag::warn_logical_instead_of_bitwise)
8048          << rex.get()->getSourceRange()
8049          << (Opc == BO_LAnd ? "&&" : "||")
8050          << (Opc == BO_LAnd ? "&" : "|");
8051    }
8052  }
8053
8054  if (!Context.getLangOptions().CPlusPlus) {
8055    lex = UsualUnaryConversions(lex.take());
8056    if (lex.isInvalid())
8057      return QualType();
8058
8059    rex = UsualUnaryConversions(rex.take());
8060    if (rex.isInvalid())
8061      return QualType();
8062
8063    if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
8064      return InvalidOperands(Loc, lex, rex);
8065
8066    return Context.IntTy;
8067  }
8068
8069  // The following is safe because we only use this method for
8070  // non-overloadable operands.
8071
8072  // C++ [expr.log.and]p1
8073  // C++ [expr.log.or]p1
8074  // The operands are both contextually converted to type bool.
8075  ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
8076  if (lexRes.isInvalid())
8077    return InvalidOperands(Loc, lex, rex);
8078  lex = move(lexRes);
8079
8080  ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
8081  if (rexRes.isInvalid())
8082    return InvalidOperands(Loc, lex, rex);
8083  rex = move(rexRes);
8084
8085  // C++ [expr.log.and]p2
8086  // C++ [expr.log.or]p2
8087  // The result is a bool.
8088  return Context.BoolTy;
8089}
8090
8091/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
8092/// is a read-only property; return true if so. A readonly property expression
8093/// depends on various declarations and thus must be treated specially.
8094///
8095static bool IsReadonlyProperty(Expr *E, Sema &S) {
8096  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8097    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
8098    if (PropExpr->isImplicitProperty()) return false;
8099
8100    ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8101    QualType BaseType = PropExpr->isSuperReceiver() ?
8102                            PropExpr->getSuperReceiverType() :
8103                            PropExpr->getBase()->getType();
8104
8105    if (const ObjCObjectPointerType *OPT =
8106          BaseType->getAsObjCInterfacePointerType())
8107      if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
8108        if (S.isPropertyReadonly(PDecl, IFace))
8109          return true;
8110  }
8111  return false;
8112}
8113
8114static bool IsConstProperty(Expr *E, Sema &S) {
8115  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8116    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
8117    if (PropExpr->isImplicitProperty()) return false;
8118
8119    ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8120    QualType T = PDecl->getType();
8121    if (T->isReferenceType())
8122      T = T->getAs<ReferenceType>()->getPointeeType();
8123    CanQualType CT = S.Context.getCanonicalType(T);
8124    return CT.isConstQualified();
8125  }
8126  return false;
8127}
8128
8129static bool IsReadonlyMessage(Expr *E, Sema &S) {
8130  if (E->getStmtClass() != Expr::MemberExprClass)
8131    return false;
8132  const MemberExpr *ME = cast<MemberExpr>(E);
8133  NamedDecl *Member = ME->getMemberDecl();
8134  if (isa<FieldDecl>(Member)) {
8135    Expr *Base = ME->getBase()->IgnoreParenImpCasts();
8136    if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
8137      return false;
8138    return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
8139  }
8140  return false;
8141}
8142
8143/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8144/// emit an error and return true.  If so, return false.
8145static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8146  SourceLocation OrigLoc = Loc;
8147  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8148                                                              &Loc);
8149  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
8150    IsLV = Expr::MLV_ReadonlyProperty;
8151  else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
8152    IsLV = Expr::MLV_Valid;
8153  else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8154    IsLV = Expr::MLV_InvalidMessageExpression;
8155  if (IsLV == Expr::MLV_Valid)
8156    return false;
8157
8158  unsigned Diag = 0;
8159  bool NeedType = false;
8160  switch (IsLV) { // C99 6.5.16p2
8161  case Expr::MLV_ConstQualified:
8162    Diag = diag::err_typecheck_assign_const;
8163
8164    // In ARC, use some specialized diagnostics for the times when we
8165    // infer const.
8166    if (S.getLangOptions().ObjCAutoRefCount) {
8167      DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8168      if (declRef && isa<VarDecl>(declRef->getDecl())) {
8169        VarDecl *var = cast<VarDecl>(declRef->getDecl());
8170
8171        // If the variable wasn't written with 'const', there are some
8172        // cases where we infer const anyway:
8173        //  - self
8174        //  - fast enumeration variables
8175        if (!var->getTypeSourceInfo() ||
8176            !var->getTypeSourceInfo()->getType().isConstQualified()) {
8177          ObjCMethodDecl *method = S.getCurMethodDecl();
8178          if (method && var == method->getSelfDecl())
8179            Diag = diag::err_typecheck_arr_assign_self;
8180          else if (var->getType().getObjCLifetime()
8181                     == Qualifiers::OCL_ExplicitNone)
8182            Diag = diag::err_typecheck_arr_assign_enumeration;
8183          SourceRange Assign;
8184          if (Loc != OrigLoc)
8185            Assign = SourceRange(OrigLoc, OrigLoc);
8186          S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8187          // We need to preserve the AST regardless, so migration tool
8188          // can do its job.
8189          return false;
8190        }
8191      }
8192    }
8193
8194    break;
8195  case Expr::MLV_ArrayType:
8196    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8197    NeedType = true;
8198    break;
8199  case Expr::MLV_NotObjectType:
8200    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8201    NeedType = true;
8202    break;
8203  case Expr::MLV_LValueCast:
8204    Diag = diag::err_typecheck_lvalue_casts_not_supported;
8205    break;
8206  case Expr::MLV_Valid:
8207    llvm_unreachable("did not take early return for MLV_Valid");
8208  case Expr::MLV_InvalidExpression:
8209  case Expr::MLV_MemberFunction:
8210  case Expr::MLV_ClassTemporary:
8211    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8212    break;
8213  case Expr::MLV_IncompleteType:
8214  case Expr::MLV_IncompleteVoidType:
8215    return S.RequireCompleteType(Loc, E->getType(),
8216              S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
8217                  << E->getSourceRange());
8218  case Expr::MLV_DuplicateVectorComponents:
8219    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8220    break;
8221  case Expr::MLV_NotBlockQualified:
8222    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8223    break;
8224  case Expr::MLV_ReadonlyProperty:
8225    Diag = diag::error_readonly_property_assignment;
8226    break;
8227  case Expr::MLV_NoSetterProperty:
8228    Diag = diag::error_nosetter_property_assignment;
8229    break;
8230  case Expr::MLV_InvalidMessageExpression:
8231    Diag = diag::error_readonly_message_assignment;
8232    break;
8233  case Expr::MLV_SubObjCPropertySetting:
8234    Diag = diag::error_no_subobject_property_setting;
8235    break;
8236  }
8237
8238  SourceRange Assign;
8239  if (Loc != OrigLoc)
8240    Assign = SourceRange(OrigLoc, OrigLoc);
8241  if (NeedType)
8242    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8243  else
8244    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8245  return true;
8246}
8247
8248
8249
8250// C99 6.5.16.1
8251QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
8252                                       SourceLocation Loc,
8253                                       QualType CompoundType) {
8254  // Verify that LHS is a modifiable lvalue, and emit error if not.
8255  if (CheckForModifiableLvalue(LHS, Loc, *this))
8256    return QualType();
8257
8258  QualType LHSType = LHS->getType();
8259  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
8260  AssignConvertType ConvTy;
8261  if (CompoundType.isNull()) {
8262    QualType LHSTy(LHSType);
8263    // Simple assignment "x = y".
8264    if (LHS->getObjectKind() == OK_ObjCProperty) {
8265      ExprResult LHSResult = Owned(LHS);
8266      ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
8267      if (LHSResult.isInvalid())
8268        return QualType();
8269      LHS = LHSResult.take();
8270    }
8271    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8272    if (RHS.isInvalid())
8273      return QualType();
8274    // Special case of NSObject attributes on c-style pointer types.
8275    if (ConvTy == IncompatiblePointer &&
8276        ((Context.isObjCNSObjectType(LHSType) &&
8277          RHSType->isObjCObjectPointerType()) ||
8278         (Context.isObjCNSObjectType(RHSType) &&
8279          LHSType->isObjCObjectPointerType())))
8280      ConvTy = Compatible;
8281
8282    if (ConvTy == Compatible &&
8283        getLangOptions().ObjCNonFragileABI &&
8284        LHSType->isObjCObjectType())
8285      Diag(Loc, diag::err_assignment_requires_nonfragile_object)
8286        << LHSType;
8287
8288    // If the RHS is a unary plus or minus, check to see if they = and + are
8289    // right next to each other.  If so, the user may have typo'd "x =+ 4"
8290    // instead of "x += 4".
8291    Expr *RHSCheck = RHS.get();
8292    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8293      RHSCheck = ICE->getSubExpr();
8294    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8295      if ((UO->getOpcode() == UO_Plus ||
8296           UO->getOpcode() == UO_Minus) &&
8297          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8298          // Only if the two operators are exactly adjacent.
8299          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
8300          // And there is a space or other character before the subexpr of the
8301          // unary +/-.  We don't want to warn on "x=-1".
8302          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8303          UO->getSubExpr()->getLocStart().isFileID()) {
8304        Diag(Loc, diag::warn_not_compound_assign)
8305          << (UO->getOpcode() == UO_Plus ? "+" : "-")
8306          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8307      }
8308    }
8309
8310    if (ConvTy == Compatible) {
8311      if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
8312        checkRetainCycles(LHS, RHS.get());
8313      else
8314        checkUnsafeAssigns(Loc, LHSType, RHS.get());
8315    }
8316  } else {
8317    // Compound assignment "x += y"
8318    ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8319  }
8320
8321  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8322                               RHS.get(), AA_Assigning))
8323    return QualType();
8324
8325  CheckForNullPointerDereference(*this, LHS);
8326  // Check for trivial buffer overflows.
8327  CheckArrayAccess(LHS->IgnoreParenCasts());
8328
8329  // C99 6.5.16p3: The type of an assignment expression is the type of the
8330  // left operand unless the left operand has qualified type, in which case
8331  // it is the unqualified version of the type of the left operand.
8332  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8333  // is converted to the type of the assignment expression (above).
8334  // C++ 5.17p1: the type of the assignment expression is that of its left
8335  // operand.
8336  return (getLangOptions().CPlusPlus
8337          ? LHSType : LHSType.getUnqualifiedType());
8338}
8339
8340// C99 6.5.17
8341static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8342                                   SourceLocation Loc) {
8343  S.DiagnoseUnusedExprResult(LHS.get());
8344
8345  LHS = S.CheckPlaceholderExpr(LHS.take());
8346  RHS = S.CheckPlaceholderExpr(RHS.take());
8347  if (LHS.isInvalid() || RHS.isInvalid())
8348    return QualType();
8349
8350  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8351  // operands, but not unary promotions.
8352  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8353
8354  // So we treat the LHS as a ignored value, and in C++ we allow the
8355  // containing site to determine what should be done with the RHS.
8356  LHS = S.IgnoredValueConversions(LHS.take());
8357  if (LHS.isInvalid())
8358    return QualType();
8359
8360  if (!S.getLangOptions().CPlusPlus) {
8361    RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8362    if (RHS.isInvalid())
8363      return QualType();
8364    if (!RHS.get()->getType()->isVoidType())
8365      S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
8366  }
8367
8368  return RHS.get()->getType();
8369}
8370
8371/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8372/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8373static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8374                                               ExprValueKind &VK,
8375                                               SourceLocation OpLoc,
8376                                               bool isInc, bool isPrefix) {
8377  if (Op->isTypeDependent())
8378    return S.Context.DependentTy;
8379
8380  QualType ResType = Op->getType();
8381  assert(!ResType.isNull() && "no type for increment/decrement expression");
8382
8383  if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
8384    // Decrement of bool is not allowed.
8385    if (!isInc) {
8386      S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8387      return QualType();
8388    }
8389    // Increment of bool sets it to true, but is deprecated.
8390    S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8391  } else if (ResType->isRealType()) {
8392    // OK!
8393  } else if (ResType->isAnyPointerType()) {
8394    QualType PointeeTy = ResType->getPointeeType();
8395
8396    // C99 6.5.2.4p2, 6.5.6p2
8397    if (PointeeTy->isVoidType()) {
8398      if (S.getLangOptions().CPlusPlus) {
8399        S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
8400          << Op->getSourceRange();
8401        return QualType();
8402      }
8403
8404      // Pointer to void is a GNU extension in C.
8405      S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
8406    } else if (PointeeTy->isFunctionType()) {
8407      if (S.getLangOptions().CPlusPlus) {
8408        S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
8409          << Op->getType() << Op->getSourceRange();
8410        return QualType();
8411      }
8412
8413      S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
8414        << ResType << Op->getSourceRange();
8415    } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8416                 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
8417                             << Op->getSourceRange()
8418                             << ResType))
8419      return QualType();
8420    // Diagnose bad cases where we step over interface counts.
8421    else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8422      S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
8423        << PointeeTy << Op->getSourceRange();
8424      return QualType();
8425    }
8426  } else if (ResType->isAnyComplexType()) {
8427    // C99 does not support ++/-- on complex types, we allow as an extension.
8428    S.Diag(OpLoc, diag::ext_integer_increment_complex)
8429      << ResType << Op->getSourceRange();
8430  } else if (ResType->isPlaceholderType()) {
8431    ExprResult PR = S.CheckPlaceholderExpr(Op);
8432    if (PR.isInvalid()) return QualType();
8433    return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8434                                          isInc, isPrefix);
8435  } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8436    // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8437  } else {
8438    S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8439      << ResType << int(isInc) << Op->getSourceRange();
8440    return QualType();
8441  }
8442  // At this point, we know we have a real, complex or pointer type.
8443  // Now make sure the operand is a modifiable lvalue.
8444  if (CheckForModifiableLvalue(Op, OpLoc, S))
8445    return QualType();
8446  // In C++, a prefix increment is the same type as the operand. Otherwise
8447  // (in C or with postfix), the increment is the unqualified type of the
8448  // operand.
8449  if (isPrefix && S.getLangOptions().CPlusPlus) {
8450    VK = VK_LValue;
8451    return ResType;
8452  } else {
8453    VK = VK_RValue;
8454    return ResType.getUnqualifiedType();
8455  }
8456}
8457
8458ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
8459  assert(E->getValueKind() == VK_LValue &&
8460         E->getObjectKind() == OK_ObjCProperty);
8461  const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8462
8463  QualType T = E->getType();
8464  QualType ReceiverType;
8465  if (PRE->isObjectReceiver())
8466    ReceiverType = PRE->getBase()->getType();
8467  else if (PRE->isSuperReceiver())
8468    ReceiverType = PRE->getSuperReceiverType();
8469  else
8470    ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
8471
8472  ExprValueKind VK = VK_RValue;
8473  if (PRE->isImplicitProperty()) {
8474    if (ObjCMethodDecl *GetterMethod =
8475          PRE->getImplicitPropertyGetter()) {
8476      T = getMessageSendResultType(ReceiverType, GetterMethod,
8477                                   PRE->isClassReceiver(),
8478                                   PRE->isSuperReceiver());
8479      VK = Expr::getValueKindForType(GetterMethod->getResultType());
8480    }
8481    else {
8482      Diag(PRE->getLocation(), diag::err_getter_not_found)
8483            << PRE->getBase()->getType();
8484    }
8485  }
8486
8487  E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
8488                               E, 0, VK);
8489
8490  ExprResult Result = MaybeBindToTemporary(E);
8491  if (!Result.isInvalid())
8492    E = Result.take();
8493
8494  return Owned(E);
8495}
8496
8497void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8498  assert(LHS.get()->getValueKind() == VK_LValue &&
8499         LHS.get()->getObjectKind() == OK_ObjCProperty);
8500  const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
8501
8502  bool Consumed = false;
8503
8504  if (PropRef->isImplicitProperty()) {
8505    // If using property-dot syntax notation for assignment, and there is a
8506    // setter, RHS expression is being passed to the setter argument. So,
8507    // type conversion (and comparison) is RHS to setter's argument type.
8508    if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
8509      ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8510      LHSTy = (*P)->getType();
8511      Consumed = (getLangOptions().ObjCAutoRefCount &&
8512                  (*P)->hasAttr<NSConsumedAttr>());
8513
8514    // Otherwise, if the getter returns an l-value, just call that.
8515    } else {
8516      QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
8517      ExprValueKind VK = Expr::getValueKindForType(Result);
8518      if (VK == VK_LValue) {
8519        LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8520                                        CK_GetObjCProperty, LHS.take(), 0, VK);
8521        return;
8522      }
8523    }
8524  } else if (getLangOptions().ObjCAutoRefCount) {
8525    const ObjCMethodDecl *setter
8526      = PropRef->getExplicitProperty()->getSetterMethodDecl();
8527    if (setter) {
8528      ObjCMethodDecl::param_iterator P = setter->param_begin();
8529      LHSTy = (*P)->getType();
8530      Consumed = (*P)->hasAttr<NSConsumedAttr>();
8531    }
8532  }
8533
8534  if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
8535      getLangOptions().ObjCAutoRefCount) {
8536    InitializedEntity Entity =
8537      InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
8538    ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
8539    if (!ArgE.isInvalid()) {
8540      RHS = ArgE;
8541      if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
8542        checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
8543    }
8544  }
8545}
8546
8547
8548/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8549/// This routine allows us to typecheck complex/recursive expressions
8550/// where the declaration is needed for type checking. We only need to
8551/// handle cases when the expression references a function designator
8552/// or is an lvalue. Here are some examples:
8553///  - &(x) => x
8554///  - &*****f => f for f a function designator.
8555///  - &s.xx => s
8556///  - &s.zz[1].yy -> s, if zz is an array
8557///  - *(x + 1) -> x, if x is an array
8558///  - &"123"[2] -> 0
8559///  - & __real__ x -> x
8560static ValueDecl *getPrimaryDecl(Expr *E) {
8561  switch (E->getStmtClass()) {
8562  case Stmt::DeclRefExprClass:
8563    return cast<DeclRefExpr>(E)->getDecl();
8564  case Stmt::MemberExprClass:
8565    // If this is an arrow operator, the address is an offset from
8566    // the base's value, so the object the base refers to is
8567    // irrelevant.
8568    if (cast<MemberExpr>(E)->isArrow())
8569      return 0;
8570    // Otherwise, the expression refers to a part of the base
8571    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8572  case Stmt::ArraySubscriptExprClass: {
8573    // FIXME: This code shouldn't be necessary!  We should catch the implicit
8574    // promotion of register arrays earlier.
8575    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8576    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8577      if (ICE->getSubExpr()->getType()->isArrayType())
8578        return getPrimaryDecl(ICE->getSubExpr());
8579    }
8580    return 0;
8581  }
8582  case Stmt::UnaryOperatorClass: {
8583    UnaryOperator *UO = cast<UnaryOperator>(E);
8584
8585    switch(UO->getOpcode()) {
8586    case UO_Real:
8587    case UO_Imag:
8588    case UO_Extension:
8589      return getPrimaryDecl(UO->getSubExpr());
8590    default:
8591      return 0;
8592    }
8593  }
8594  case Stmt::ParenExprClass:
8595    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8596  case Stmt::ImplicitCastExprClass:
8597    // If the result of an implicit cast is an l-value, we care about
8598    // the sub-expression; otherwise, the result here doesn't matter.
8599    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8600  default:
8601    return 0;
8602  }
8603}
8604
8605/// CheckAddressOfOperand - The operand of & must be either a function
8606/// designator or an lvalue designating an object. If it is an lvalue, the
8607/// object cannot be declared with storage class register or be a bit field.
8608/// Note: The usual conversions are *not* applied to the operand of the &
8609/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8610/// In C++, the operand might be an overloaded function name, in which case
8611/// we allow the '&' but retain the overloaded-function type.
8612static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8613                                      SourceLocation OpLoc) {
8614  if (OrigOp->isTypeDependent())
8615    return S.Context.DependentTy;
8616  if (OrigOp->getType() == S.Context.OverloadTy)
8617    return S.Context.OverloadTy;
8618  if (OrigOp->getType() == S.Context.UnknownAnyTy)
8619    return S.Context.UnknownAnyTy;
8620  if (OrigOp->getType() == S.Context.BoundMemberTy) {
8621    S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8622      << OrigOp->getSourceRange();
8623    return QualType();
8624  }
8625
8626  assert(!OrigOp->getType()->isPlaceholderType());
8627
8628  // Make sure to ignore parentheses in subsequent checks
8629  Expr *op = OrigOp->IgnoreParens();
8630
8631  if (S.getLangOptions().C99) {
8632    // Implement C99-only parts of addressof rules.
8633    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8634      if (uOp->getOpcode() == UO_Deref)
8635        // Per C99 6.5.3.2, the address of a deref always returns a valid result
8636        // (assuming the deref expression is valid).
8637        return uOp->getSubExpr()->getType();
8638    }
8639    // Technically, there should be a check for array subscript
8640    // expressions here, but the result of one is always an lvalue anyway.
8641  }
8642  ValueDecl *dcl = getPrimaryDecl(op);
8643  Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
8644
8645  if (lval == Expr::LV_ClassTemporary) {
8646    bool sfinae = S.isSFINAEContext();
8647    S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8648                         : diag::ext_typecheck_addrof_class_temporary)
8649      << op->getType() << op->getSourceRange();
8650    if (sfinae)
8651      return QualType();
8652  } else if (isa<ObjCSelectorExpr>(op)) {
8653    return S.Context.getPointerType(op->getType());
8654  } else if (lval == Expr::LV_MemberFunction) {
8655    // If it's an instance method, make a member pointer.
8656    // The expression must have exactly the form &A::foo.
8657
8658    // If the underlying expression isn't a decl ref, give up.
8659    if (!isa<DeclRefExpr>(op)) {
8660      S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8661        << OrigOp->getSourceRange();
8662      return QualType();
8663    }
8664    DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8665    CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8666
8667    // The id-expression was parenthesized.
8668    if (OrigOp != DRE) {
8669      S.Diag(OpLoc, diag::err_parens_pointer_member_function)
8670        << OrigOp->getSourceRange();
8671
8672    // The method was named without a qualifier.
8673    } else if (!DRE->getQualifier()) {
8674      S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8675        << op->getSourceRange();
8676    }
8677
8678    return S.Context.getMemberPointerType(op->getType(),
8679              S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
8680  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8681    // C99 6.5.3.2p1
8682    // The operand must be either an l-value or a function designator
8683    if (!op->getType()->isFunctionType()) {
8684      // FIXME: emit more specific diag...
8685      S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8686        << op->getSourceRange();
8687      return QualType();
8688    }
8689  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8690    // The operand cannot be a bit-field
8691    S.Diag(OpLoc, diag::err_typecheck_address_of)
8692      << "bit-field" << op->getSourceRange();
8693        return QualType();
8694  } else if (op->getObjectKind() == OK_VectorComponent) {
8695    // The operand cannot be an element of a vector
8696    S.Diag(OpLoc, diag::err_typecheck_address_of)
8697      << "vector element" << op->getSourceRange();
8698    return QualType();
8699  } else if (op->getObjectKind() == OK_ObjCProperty) {
8700    // cannot take address of a property expression.
8701    S.Diag(OpLoc, diag::err_typecheck_address_of)
8702      << "property expression" << op->getSourceRange();
8703    return QualType();
8704  } else if (dcl) { // C99 6.5.3.2p1
8705    // We have an lvalue with a decl. Make sure the decl is not declared
8706    // with the register storage-class specifier.
8707    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8708      // in C++ it is not error to take address of a register
8709      // variable (c++03 7.1.1P3)
8710      if (vd->getStorageClass() == SC_Register &&
8711          !S.getLangOptions().CPlusPlus) {
8712        S.Diag(OpLoc, diag::err_typecheck_address_of)
8713          << "register variable" << op->getSourceRange();
8714        return QualType();
8715      }
8716    } else if (isa<FunctionTemplateDecl>(dcl)) {
8717      return S.Context.OverloadTy;
8718    } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8719      // Okay: we can take the address of a field.
8720      // Could be a pointer to member, though, if there is an explicit
8721      // scope qualifier for the class.
8722      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8723        DeclContext *Ctx = dcl->getDeclContext();
8724        if (Ctx && Ctx->isRecord()) {
8725          if (dcl->getType()->isReferenceType()) {
8726            S.Diag(OpLoc,
8727                   diag::err_cannot_form_pointer_to_member_of_reference_type)
8728              << dcl->getDeclName() << dcl->getType();
8729            return QualType();
8730          }
8731
8732          while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8733            Ctx = Ctx->getParent();
8734          return S.Context.getMemberPointerType(op->getType(),
8735                S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8736        }
8737      }
8738    } else if (!isa<FunctionDecl>(dcl))
8739      assert(0 && "Unknown/unexpected decl type");
8740  }
8741
8742  if (lval == Expr::LV_IncompleteVoidType) {
8743    // Taking the address of a void variable is technically illegal, but we
8744    // allow it in cases which are otherwise valid.
8745    // Example: "extern void x; void* y = &x;".
8746    S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8747  }
8748
8749  // If the operand has type "type", the result has type "pointer to type".
8750  if (op->getType()->isObjCObjectType())
8751    return S.Context.getObjCObjectPointerType(op->getType());
8752  return S.Context.getPointerType(op->getType());
8753}
8754
8755/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8756static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8757                                        SourceLocation OpLoc) {
8758  if (Op->isTypeDependent())
8759    return S.Context.DependentTy;
8760
8761  ExprResult ConvResult = S.UsualUnaryConversions(Op);
8762  if (ConvResult.isInvalid())
8763    return QualType();
8764  Op = ConvResult.take();
8765  QualType OpTy = Op->getType();
8766  QualType Result;
8767
8768  if (isa<CXXReinterpretCastExpr>(Op)) {
8769    QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8770    S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8771                                     Op->getSourceRange());
8772  }
8773
8774  // Note that per both C89 and C99, indirection is always legal, even if OpTy
8775  // is an incomplete type or void.  It would be possible to warn about
8776  // dereferencing a void pointer, but it's completely well-defined, and such a
8777  // warning is unlikely to catch any mistakes.
8778  if (const PointerType *PT = OpTy->getAs<PointerType>())
8779    Result = PT->getPointeeType();
8780  else if (const ObjCObjectPointerType *OPT =
8781             OpTy->getAs<ObjCObjectPointerType>())
8782    Result = OPT->getPointeeType();
8783  else {
8784    ExprResult PR = S.CheckPlaceholderExpr(Op);
8785    if (PR.isInvalid()) return QualType();
8786    if (PR.take() != Op)
8787      return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8788  }
8789
8790  if (Result.isNull()) {
8791    S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8792      << OpTy << Op->getSourceRange();
8793    return QualType();
8794  }
8795
8796  // Dereferences are usually l-values...
8797  VK = VK_LValue;
8798
8799  // ...except that certain expressions are never l-values in C.
8800  if (!S.getLangOptions().CPlusPlus &&
8801      IsCForbiddenLValueType(S.Context, Result))
8802    VK = VK_RValue;
8803
8804  return Result;
8805}
8806
8807static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8808  tok::TokenKind Kind) {
8809  BinaryOperatorKind Opc;
8810  switch (Kind) {
8811  default: assert(0 && "Unknown binop!");
8812  case tok::periodstar:           Opc = BO_PtrMemD; break;
8813  case tok::arrowstar:            Opc = BO_PtrMemI; break;
8814  case tok::star:                 Opc = BO_Mul; break;
8815  case tok::slash:                Opc = BO_Div; break;
8816  case tok::percent:              Opc = BO_Rem; break;
8817  case tok::plus:                 Opc = BO_Add; break;
8818  case tok::minus:                Opc = BO_Sub; break;
8819  case tok::lessless:             Opc = BO_Shl; break;
8820  case tok::greatergreater:       Opc = BO_Shr; break;
8821  case tok::lessequal:            Opc = BO_LE; break;
8822  case tok::less:                 Opc = BO_LT; break;
8823  case tok::greaterequal:         Opc = BO_GE; break;
8824  case tok::greater:              Opc = BO_GT; break;
8825  case tok::exclaimequal:         Opc = BO_NE; break;
8826  case tok::equalequal:           Opc = BO_EQ; break;
8827  case tok::amp:                  Opc = BO_And; break;
8828  case tok::caret:                Opc = BO_Xor; break;
8829  case tok::pipe:                 Opc = BO_Or; break;
8830  case tok::ampamp:               Opc = BO_LAnd; break;
8831  case tok::pipepipe:             Opc = BO_LOr; break;
8832  case tok::equal:                Opc = BO_Assign; break;
8833  case tok::starequal:            Opc = BO_MulAssign; break;
8834  case tok::slashequal:           Opc = BO_DivAssign; break;
8835  case tok::percentequal:         Opc = BO_RemAssign; break;
8836  case tok::plusequal:            Opc = BO_AddAssign; break;
8837  case tok::minusequal:           Opc = BO_SubAssign; break;
8838  case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8839  case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8840  case tok::ampequal:             Opc = BO_AndAssign; break;
8841  case tok::caretequal:           Opc = BO_XorAssign; break;
8842  case tok::pipeequal:            Opc = BO_OrAssign; break;
8843  case tok::comma:                Opc = BO_Comma; break;
8844  }
8845  return Opc;
8846}
8847
8848static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8849  tok::TokenKind Kind) {
8850  UnaryOperatorKind Opc;
8851  switch (Kind) {
8852  default: assert(0 && "Unknown unary op!");
8853  case tok::plusplus:     Opc = UO_PreInc; break;
8854  case tok::minusminus:   Opc = UO_PreDec; break;
8855  case tok::amp:          Opc = UO_AddrOf; break;
8856  case tok::star:         Opc = UO_Deref; break;
8857  case tok::plus:         Opc = UO_Plus; break;
8858  case tok::minus:        Opc = UO_Minus; break;
8859  case tok::tilde:        Opc = UO_Not; break;
8860  case tok::exclaim:      Opc = UO_LNot; break;
8861  case tok::kw___real:    Opc = UO_Real; break;
8862  case tok::kw___imag:    Opc = UO_Imag; break;
8863  case tok::kw___extension__: Opc = UO_Extension; break;
8864  }
8865  return Opc;
8866}
8867
8868/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8869/// This warning is only emitted for builtin assignment operations. It is also
8870/// suppressed in the event of macro expansions.
8871static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8872                                   SourceLocation OpLoc) {
8873  if (!S.ActiveTemplateInstantiations.empty())
8874    return;
8875  if (OpLoc.isInvalid() || OpLoc.isMacroID())
8876    return;
8877  lhs = lhs->IgnoreParenImpCasts();
8878  rhs = rhs->IgnoreParenImpCasts();
8879  const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8880  const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8881  if (!LeftDeclRef || !RightDeclRef ||
8882      LeftDeclRef->getLocation().isMacroID() ||
8883      RightDeclRef->getLocation().isMacroID())
8884    return;
8885  const ValueDecl *LeftDecl =
8886    cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8887  const ValueDecl *RightDecl =
8888    cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8889  if (LeftDecl != RightDecl)
8890    return;
8891  if (LeftDecl->getType().isVolatileQualified())
8892    return;
8893  if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8894    if (RefTy->getPointeeType().isVolatileQualified())
8895      return;
8896
8897  S.Diag(OpLoc, diag::warn_self_assignment)
8898      << LeftDeclRef->getType()
8899      << lhs->getSourceRange() << rhs->getSourceRange();
8900}
8901
8902/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8903/// operator @p Opc at location @c TokLoc. This routine only supports
8904/// built-in operations; ActOnBinOp handles overloaded operators.
8905ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8906                                    BinaryOperatorKind Opc,
8907                                    Expr *lhsExpr, Expr *rhsExpr) {
8908  ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
8909  QualType ResultTy;     // Result type of the binary operator.
8910  // The following two variables are used for compound assignment operators
8911  QualType CompLHSTy;    // Type of LHS after promotions for computation
8912  QualType CompResultTy; // Type of computation result
8913  ExprValueKind VK = VK_RValue;
8914  ExprObjectKind OK = OK_Ordinary;
8915
8916  // Check if a 'foo<int>' involved in a binary op, identifies a single
8917  // function unambiguously (i.e. an lvalue ala 13.4)
8918  // But since an assignment can trigger target based overload, exclude it in
8919  // our blind search. i.e:
8920  // template<class T> void f(); template<class T, class U> void f(U);
8921  // f<int> == 0;  // resolve f<int> blindly
8922  // void (*p)(int); p = f<int>;  // resolve f<int> using target
8923  if (Opc != BO_Assign) {
8924    ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
8925    if (!resolvedLHS.isUsable()) return ExprError();
8926    lhs = move(resolvedLHS);
8927
8928    ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
8929    if (!resolvedRHS.isUsable()) return ExprError();
8930    rhs = move(resolvedRHS);
8931  }
8932
8933  bool LeftNull = Expr::NPCK_GNUNull ==
8934      lhs.get()->isNullPointerConstant(Context,
8935                                       Expr::NPC_ValueDependentIsNotNull);
8936  bool RightNull = Expr::NPCK_GNUNull ==
8937      rhs.get()->isNullPointerConstant(Context,
8938                                       Expr::NPC_ValueDependentIsNotNull);
8939
8940  // Detect when a NULL constant is used improperly in an expression.  These
8941  // are mainly cases where the null pointer is used as an integer instead
8942  // of a pointer.
8943  if (LeftNull || RightNull) {
8944    if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
8945        Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
8946        Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
8947        Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
8948        Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
8949        Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
8950      // These are the operations that would not make sense with a null pointer
8951      // no matter what the other expression is.
8952      if (LeftNull && RightNull) {
8953        Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8954             << lhs.get()->getSourceRange() << rhs.get()->getSourceRange();
8955      } else if (LeftNull) {
8956        Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8957             << lhs.get()->getSourceRange();
8958      } else if (RightNull) {
8959        Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8960             << rhs.get()->getSourceRange();
8961      }
8962    } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
8963               Opc == BO_EQ || Opc == BO_NE) {
8964      // These are the operations that would not make sense with a null pointer
8965      // if the other expression the other expression is not a pointer.
8966      QualType LeftType = lhs.get()->getType();
8967      QualType RightType = rhs.get()->getType();
8968      bool LeftPointer = LeftType->isPointerType() ||
8969                         LeftType->isBlockPointerType() ||
8970                         LeftType->isMemberPointerType() ||
8971                         LeftType->isObjCObjectPointerType();
8972      bool RightPointer = RightType->isPointerType() ||
8973                          RightType->isBlockPointerType() ||
8974                          RightType->isMemberPointerType() ||
8975                          RightType->isObjCObjectPointerType();
8976      if ((LeftNull != RightNull) && !LeftPointer && !RightPointer) {
8977        if (LeftNull)
8978          Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8979               << lhs.get()->getSourceRange();
8980        if (RightNull)
8981          Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8982               << rhs.get()->getSourceRange();
8983      }
8984    }
8985  }
8986
8987  switch (Opc) {
8988  case BO_Assign:
8989    ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
8990    if (getLangOptions().CPlusPlus &&
8991        lhs.get()->getObjectKind() != OK_ObjCProperty) {
8992      VK = lhs.get()->getValueKind();
8993      OK = lhs.get()->getObjectKind();
8994    }
8995    if (!ResultTy.isNull())
8996      DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
8997    break;
8998  case BO_PtrMemD:
8999  case BO_PtrMemI:
9000    ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
9001                                            Opc == BO_PtrMemI);
9002    break;
9003  case BO_Mul:
9004  case BO_Div:
9005    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
9006                                           Opc == BO_Div);
9007    break;
9008  case BO_Rem:
9009    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
9010    break;
9011  case BO_Add:
9012    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
9013    break;
9014  case BO_Sub:
9015    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
9016    break;
9017  case BO_Shl:
9018  case BO_Shr:
9019    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
9020    break;
9021  case BO_LE:
9022  case BO_LT:
9023  case BO_GE:
9024  case BO_GT:
9025    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
9026    break;
9027  case BO_EQ:
9028  case BO_NE:
9029    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
9030    break;
9031  case BO_And:
9032  case BO_Xor:
9033  case BO_Or:
9034    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
9035    break;
9036  case BO_LAnd:
9037  case BO_LOr:
9038    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
9039    break;
9040  case BO_MulAssign:
9041  case BO_DivAssign:
9042    CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
9043                                               Opc == BO_DivAssign);
9044    CompLHSTy = CompResultTy;
9045    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9046      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
9047    break;
9048  case BO_RemAssign:
9049    CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
9050    CompLHSTy = CompResultTy;
9051    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9052      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
9053    break;
9054  case BO_AddAssign:
9055    CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
9056    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9057      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
9058    break;
9059  case BO_SubAssign:
9060    CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
9061    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9062      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
9063    break;
9064  case BO_ShlAssign:
9065  case BO_ShrAssign:
9066    CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
9067    CompLHSTy = CompResultTy;
9068    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9069      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
9070    break;
9071  case BO_AndAssign:
9072  case BO_XorAssign:
9073  case BO_OrAssign:
9074    CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
9075    CompLHSTy = CompResultTy;
9076    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9077      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
9078    break;
9079  case BO_Comma:
9080    ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
9081    if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
9082      VK = rhs.get()->getValueKind();
9083      OK = rhs.get()->getObjectKind();
9084    }
9085    break;
9086  }
9087  if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
9088    return ExprError();
9089  if (CompResultTy.isNull())
9090    return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
9091                                              ResultTy, VK, OK, OpLoc));
9092  if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
9093    VK = VK_LValue;
9094    OK = lhs.get()->getObjectKind();
9095  }
9096  return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
9097                                                    ResultTy, VK, OK, CompLHSTy,
9098                                                    CompResultTy, OpLoc));
9099}
9100
9101/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9102/// operators are mixed in a way that suggests that the programmer forgot that
9103/// comparison operators have higher precedence. The most typical example of
9104/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9105static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9106                                      SourceLocation OpLoc,Expr *lhs,Expr *rhs){
9107  typedef BinaryOperator BinOp;
9108  BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
9109                rhsopc = static_cast<BinOp::Opcode>(-1);
9110  if (BinOp *BO = dyn_cast<BinOp>(lhs))
9111    lhsopc = BO->getOpcode();
9112  if (BinOp *BO = dyn_cast<BinOp>(rhs))
9113    rhsopc = BO->getOpcode();
9114
9115  // Subs are not binary operators.
9116  if (lhsopc == -1 && rhsopc == -1)
9117    return;
9118
9119  // Bitwise operations are sometimes used as eager logical ops.
9120  // Don't diagnose this.
9121  if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
9122      (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
9123    return;
9124
9125  if (BinOp::isComparisonOp(lhsopc)) {
9126    Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9127        << SourceRange(lhs->getLocStart(), OpLoc)
9128        << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
9129    SuggestParentheses(Self, OpLoc,
9130      Self.PDiag(diag::note_precedence_bitwise_silence)
9131          << BinOp::getOpcodeStr(lhsopc),
9132      lhs->getSourceRange());
9133    SuggestParentheses(Self, OpLoc,
9134      Self.PDiag(diag::note_precedence_bitwise_first)
9135          << BinOp::getOpcodeStr(Opc),
9136      SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
9137  } else if (BinOp::isComparisonOp(rhsopc)) {
9138    Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9139        << SourceRange(OpLoc, rhs->getLocEnd())
9140        << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
9141    SuggestParentheses(Self, OpLoc,
9142      Self.PDiag(diag::note_precedence_bitwise_silence)
9143          << BinOp::getOpcodeStr(rhsopc),
9144      rhs->getSourceRange());
9145    SuggestParentheses(Self, OpLoc,
9146      Self.PDiag(diag::note_precedence_bitwise_first)
9147        << BinOp::getOpcodeStr(Opc),
9148      SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
9149  }
9150}
9151
9152/// \brief It accepts a '&&' expr that is inside a '||' one.
9153/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9154/// in parentheses.
9155static void
9156EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9157                                       BinaryOperator *Bop) {
9158  assert(Bop->getOpcode() == BO_LAnd);
9159  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9160      << Bop->getSourceRange() << OpLoc;
9161  SuggestParentheses(Self, Bop->getOperatorLoc(),
9162    Self.PDiag(diag::note_logical_and_in_logical_or_silence),
9163    Bop->getSourceRange());
9164}
9165
9166/// \brief Returns true if the given expression can be evaluated as a constant
9167/// 'true'.
9168static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9169  bool Res;
9170  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9171}
9172
9173/// \brief Returns true if the given expression can be evaluated as a constant
9174/// 'false'.
9175static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9176  bool Res;
9177  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9178}
9179
9180/// \brief Look for '&&' in the left hand of a '||' expr.
9181static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9182                                             Expr *OrLHS, Expr *OrRHS) {
9183  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
9184    if (Bop->getOpcode() == BO_LAnd) {
9185      // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9186      if (EvaluatesAsFalse(S, OrRHS))
9187        return;
9188      // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9189      if (!EvaluatesAsTrue(S, Bop->getLHS()))
9190        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9191    } else if (Bop->getOpcode() == BO_LOr) {
9192      if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9193        // If it's "a || b && 1 || c" we didn't warn earlier for
9194        // "a || b && 1", but warn now.
9195        if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9196          return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9197      }
9198    }
9199  }
9200}
9201
9202/// \brief Look for '&&' in the right hand of a '||' expr.
9203static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9204                                             Expr *OrLHS, Expr *OrRHS) {
9205  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
9206    if (Bop->getOpcode() == BO_LAnd) {
9207      // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9208      if (EvaluatesAsFalse(S, OrLHS))
9209        return;
9210      // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9211      if (!EvaluatesAsTrue(S, Bop->getRHS()))
9212        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9213    }
9214  }
9215}
9216
9217/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9218/// precedence.
9219static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9220                                    SourceLocation OpLoc, Expr *lhs, Expr *rhs){
9221  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9222  if (BinaryOperator::isBitwiseOp(Opc))
9223    return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
9224
9225  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9226  // We don't warn for 'assert(a || b && "bad")' since this is safe.
9227  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9228    DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
9229    DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
9230  }
9231}
9232
9233// Binary Operators.  'Tok' is the token for the operator.
9234ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9235                            tok::TokenKind Kind,
9236                            Expr *lhs, Expr *rhs) {
9237  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9238  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
9239  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
9240
9241  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9242  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
9243
9244  return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
9245}
9246
9247ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9248                            BinaryOperatorKind Opc,
9249                            Expr *lhs, Expr *rhs) {
9250  if (getLangOptions().CPlusPlus) {
9251    bool UseBuiltinOperator;
9252
9253    if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
9254      UseBuiltinOperator = false;
9255    } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
9256      UseBuiltinOperator = true;
9257    } else {
9258      UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
9259                           !rhs->getType()->isOverloadableType();
9260    }
9261
9262    if (!UseBuiltinOperator) {
9263      // Find all of the overloaded operators visible from this
9264      // point. We perform both an operator-name lookup from the local
9265      // scope and an argument-dependent lookup based on the types of
9266      // the arguments.
9267      UnresolvedSet<16> Functions;
9268      OverloadedOperatorKind OverOp
9269        = BinaryOperator::getOverloadedOperator(Opc);
9270      if (S && OverOp != OO_None)
9271        LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
9272                                     Functions);
9273
9274      // Build the (potentially-overloaded, potentially-dependent)
9275      // binary operation.
9276      return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
9277    }
9278  }
9279
9280  // Build a built-in binary operation.
9281  return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
9282}
9283
9284ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9285                                      UnaryOperatorKind Opc,
9286                                      Expr *InputExpr) {
9287  ExprResult Input = Owned(InputExpr);
9288  ExprValueKind VK = VK_RValue;
9289  ExprObjectKind OK = OK_Ordinary;
9290  QualType resultType;
9291  switch (Opc) {
9292  case UO_PreInc:
9293  case UO_PreDec:
9294  case UO_PostInc:
9295  case UO_PostDec:
9296    resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9297                                                Opc == UO_PreInc ||
9298                                                Opc == UO_PostInc,
9299                                                Opc == UO_PreInc ||
9300                                                Opc == UO_PreDec);
9301    break;
9302  case UO_AddrOf:
9303    resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
9304    break;
9305  case UO_Deref: {
9306    ExprResult resolved = CheckPlaceholderExpr(Input.get());
9307    if (!resolved.isUsable()) return ExprError();
9308    Input = move(resolved);
9309    Input = DefaultFunctionArrayLvalueConversion(Input.take());
9310    resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9311    break;
9312  }
9313  case UO_Plus:
9314  case UO_Minus:
9315    Input = UsualUnaryConversions(Input.take());
9316    if (Input.isInvalid()) return ExprError();
9317    resultType = Input.get()->getType();
9318    if (resultType->isDependentType())
9319      break;
9320    if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9321        resultType->isVectorType())
9322      break;
9323    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
9324             resultType->isEnumeralType())
9325      break;
9326    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
9327             Opc == UO_Plus &&
9328             resultType->isPointerType())
9329      break;
9330    else if (resultType->isPlaceholderType()) {
9331      Input = CheckPlaceholderExpr(Input.take());
9332      if (Input.isInvalid()) return ExprError();
9333      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
9334    }
9335
9336    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9337      << resultType << Input.get()->getSourceRange());
9338
9339  case UO_Not: // bitwise complement
9340    Input = UsualUnaryConversions(Input.take());
9341    if (Input.isInvalid()) return ExprError();
9342    resultType = Input.get()->getType();
9343    if (resultType->isDependentType())
9344      break;
9345    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9346    if (resultType->isComplexType() || resultType->isComplexIntegerType())
9347      // C99 does not support '~' for complex conjugation.
9348      Diag(OpLoc, diag::ext_integer_complement_complex)
9349        << resultType << Input.get()->getSourceRange();
9350    else if (resultType->hasIntegerRepresentation())
9351      break;
9352    else if (resultType->isPlaceholderType()) {
9353      Input = CheckPlaceholderExpr(Input.take());
9354      if (Input.isInvalid()) return ExprError();
9355      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
9356    } else {
9357      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9358        << resultType << Input.get()->getSourceRange());
9359    }
9360    break;
9361
9362  case UO_LNot: // logical negation
9363    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9364    Input = DefaultFunctionArrayLvalueConversion(Input.take());
9365    if (Input.isInvalid()) return ExprError();
9366    resultType = Input.get()->getType();
9367    if (resultType->isDependentType())
9368      break;
9369    if (resultType->isScalarType()) {
9370      // C99 6.5.3.3p1: ok, fallthrough;
9371      if (Context.getLangOptions().CPlusPlus) {
9372        // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9373        // operand contextually converted to bool.
9374        Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9375                                  ScalarTypeToBooleanCastKind(resultType));
9376      }
9377    } else if (resultType->isPlaceholderType()) {
9378      Input = CheckPlaceholderExpr(Input.take());
9379      if (Input.isInvalid()) return ExprError();
9380      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
9381    } else {
9382      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9383        << resultType << Input.get()->getSourceRange());
9384    }
9385
9386    // LNot always has type int. C99 6.5.3.3p5.
9387    // In C++, it's bool. C++ 5.3.1p8
9388    resultType = Context.getLogicalOperationType();
9389    break;
9390  case UO_Real:
9391  case UO_Imag:
9392    resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9393    // _Real and _Imag map ordinary l-values into ordinary l-values.
9394    if (Input.isInvalid()) return ExprError();
9395    if (Input.get()->getValueKind() != VK_RValue &&
9396        Input.get()->getObjectKind() == OK_Ordinary)
9397      VK = Input.get()->getValueKind();
9398    break;
9399  case UO_Extension:
9400    resultType = Input.get()->getType();
9401    VK = Input.get()->getValueKind();
9402    OK = Input.get()->getObjectKind();
9403    break;
9404  }
9405  if (resultType.isNull() || Input.isInvalid())
9406    return ExprError();
9407
9408  return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9409                                           VK, OK, OpLoc));
9410}
9411
9412ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9413                              UnaryOperatorKind Opc,
9414                              Expr *Input) {
9415  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
9416      UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
9417    // Find all of the overloaded operators visible from this
9418    // point. We perform both an operator-name lookup from the local
9419    // scope and an argument-dependent lookup based on the types of
9420    // the arguments.
9421    UnresolvedSet<16> Functions;
9422    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9423    if (S && OverOp != OO_None)
9424      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9425                                   Functions);
9426
9427    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9428  }
9429
9430  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9431}
9432
9433// Unary Operators.  'Tok' is the token for the operator.
9434ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9435                              tok::TokenKind Op, Expr *Input) {
9436  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9437}
9438
9439/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9440ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9441                                LabelDecl *TheDecl) {
9442  TheDecl->setUsed();
9443  // Create the AST node.  The address of a label always has type 'void*'.
9444  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9445                                       Context.getPointerType(Context.VoidTy)));
9446}
9447
9448/// Given the last statement in a statement-expression, check whether
9449/// the result is a producing expression (like a call to an
9450/// ns_returns_retained function) and, if so, rebuild it to hoist the
9451/// release out of the full-expression.  Otherwise, return null.
9452/// Cannot fail.
9453static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
9454  // Should always be wrapped with one of these.
9455  ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
9456  if (!cleanups) return 0;
9457
9458  ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9459  if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
9460    return 0;
9461
9462  // Splice out the cast.  This shouldn't modify any interesting
9463  // features of the statement.
9464  Expr *producer = cast->getSubExpr();
9465  assert(producer->getType() == cast->getType());
9466  assert(producer->getValueKind() == cast->getValueKind());
9467  cleanups->setSubExpr(producer);
9468  return cleanups;
9469}
9470
9471ExprResult
9472Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9473                    SourceLocation RPLoc) { // "({..})"
9474  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9475  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9476
9477  bool isFileScope
9478    = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9479  if (isFileScope)
9480    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9481
9482  // FIXME: there are a variety of strange constraints to enforce here, for
9483  // example, it is not possible to goto into a stmt expression apparently.
9484  // More semantic analysis is needed.
9485
9486  // If there are sub stmts in the compound stmt, take the type of the last one
9487  // as the type of the stmtexpr.
9488  QualType Ty = Context.VoidTy;
9489  bool StmtExprMayBindToTemp = false;
9490  if (!Compound->body_empty()) {
9491    Stmt *LastStmt = Compound->body_back();
9492    LabelStmt *LastLabelStmt = 0;
9493    // If LastStmt is a label, skip down through into the body.
9494    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9495      LastLabelStmt = Label;
9496      LastStmt = Label->getSubStmt();
9497    }
9498
9499    if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9500      // Do function/array conversion on the last expression, but not
9501      // lvalue-to-rvalue.  However, initialize an unqualified type.
9502      ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9503      if (LastExpr.isInvalid())
9504        return ExprError();
9505      Ty = LastExpr.get()->getType().getUnqualifiedType();
9506
9507      if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9508        // In ARC, if the final expression ends in a consume, splice
9509        // the consume out and bind it later.  In the alternate case
9510        // (when dealing with a retainable type), the result
9511        // initialization will create a produce.  In both cases the
9512        // result will be +1, and we'll need to balance that out with
9513        // a bind.
9514        if (Expr *rebuiltLastStmt
9515              = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9516          LastExpr = rebuiltLastStmt;
9517        } else {
9518          LastExpr = PerformCopyInitialization(
9519                            InitializedEntity::InitializeResult(LPLoc,
9520                                                                Ty,
9521                                                                false),
9522                                                   SourceLocation(),
9523                                               LastExpr);
9524        }
9525
9526        if (LastExpr.isInvalid())
9527          return ExprError();
9528        if (LastExpr.get() != 0) {
9529          if (!LastLabelStmt)
9530            Compound->setLastStmt(LastExpr.take());
9531          else
9532            LastLabelStmt->setSubStmt(LastExpr.take());
9533          StmtExprMayBindToTemp = true;
9534        }
9535      }
9536    }
9537  }
9538
9539  // FIXME: Check that expression type is complete/non-abstract; statement
9540  // expressions are not lvalues.
9541  Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9542  if (StmtExprMayBindToTemp)
9543    return MaybeBindToTemporary(ResStmtExpr);
9544  return Owned(ResStmtExpr);
9545}
9546
9547ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9548                                      TypeSourceInfo *TInfo,
9549                                      OffsetOfComponent *CompPtr,
9550                                      unsigned NumComponents,
9551                                      SourceLocation RParenLoc) {
9552  QualType ArgTy = TInfo->getType();
9553  bool Dependent = ArgTy->isDependentType();
9554  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9555
9556  // We must have at least one component that refers to the type, and the first
9557  // one is known to be a field designator.  Verify that the ArgTy represents
9558  // a struct/union/class.
9559  if (!Dependent && !ArgTy->isRecordType())
9560    return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9561                       << ArgTy << TypeRange);
9562
9563  // Type must be complete per C99 7.17p3 because a declaring a variable
9564  // with an incomplete type would be ill-formed.
9565  if (!Dependent
9566      && RequireCompleteType(BuiltinLoc, ArgTy,
9567                             PDiag(diag::err_offsetof_incomplete_type)
9568                               << TypeRange))
9569    return ExprError();
9570
9571  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9572  // GCC extension, diagnose them.
9573  // FIXME: This diagnostic isn't actually visible because the location is in
9574  // a system header!
9575  if (NumComponents != 1)
9576    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9577      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9578
9579  bool DidWarnAboutNonPOD = false;
9580  QualType CurrentType = ArgTy;
9581  typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9582  llvm::SmallVector<OffsetOfNode, 4> Comps;
9583  llvm::SmallVector<Expr*, 4> Exprs;
9584  for (unsigned i = 0; i != NumComponents; ++i) {
9585    const OffsetOfComponent &OC = CompPtr[i];
9586    if (OC.isBrackets) {
9587      // Offset of an array sub-field.  TODO: Should we allow vector elements?
9588      if (!CurrentType->isDependentType()) {
9589        const ArrayType *AT = Context.getAsArrayType(CurrentType);
9590        if(!AT)
9591          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9592                           << CurrentType);
9593        CurrentType = AT->getElementType();
9594      } else
9595        CurrentType = Context.DependentTy;
9596
9597      // The expression must be an integral expression.
9598      // FIXME: An integral constant expression?
9599      Expr *Idx = static_cast<Expr*>(OC.U.E);
9600      if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9601          !Idx->getType()->isIntegerType())
9602        return ExprError(Diag(Idx->getLocStart(),
9603                              diag::err_typecheck_subscript_not_integer)
9604                         << Idx->getSourceRange());
9605
9606      // Record this array index.
9607      Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9608      Exprs.push_back(Idx);
9609      continue;
9610    }
9611
9612    // Offset of a field.
9613    if (CurrentType->isDependentType()) {
9614      // We have the offset of a field, but we can't look into the dependent
9615      // type. Just record the identifier of the field.
9616      Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9617      CurrentType = Context.DependentTy;
9618      continue;
9619    }
9620
9621    // We need to have a complete type to look into.
9622    if (RequireCompleteType(OC.LocStart, CurrentType,
9623                            diag::err_offsetof_incomplete_type))
9624      return ExprError();
9625
9626    // Look for the designated field.
9627    const RecordType *RC = CurrentType->getAs<RecordType>();
9628    if (!RC)
9629      return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9630                       << CurrentType);
9631    RecordDecl *RD = RC->getDecl();
9632
9633    // C++ [lib.support.types]p5:
9634    //   The macro offsetof accepts a restricted set of type arguments in this
9635    //   International Standard. type shall be a POD structure or a POD union
9636    //   (clause 9).
9637    if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9638      if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
9639          DiagRuntimeBehavior(BuiltinLoc, 0,
9640                              PDiag(diag::warn_offsetof_non_pod_type)
9641                              << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9642                              << CurrentType))
9643        DidWarnAboutNonPOD = true;
9644    }
9645
9646    // Look for the field.
9647    LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9648    LookupQualifiedName(R, RD);
9649    FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9650    IndirectFieldDecl *IndirectMemberDecl = 0;
9651    if (!MemberDecl) {
9652      if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9653        MemberDecl = IndirectMemberDecl->getAnonField();
9654    }
9655
9656    if (!MemberDecl)
9657      return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9658                       << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9659                                                              OC.LocEnd));
9660
9661    // C99 7.17p3:
9662    //   (If the specified member is a bit-field, the behavior is undefined.)
9663    //
9664    // We diagnose this as an error.
9665    if (MemberDecl->getBitWidth()) {
9666      Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9667        << MemberDecl->getDeclName()
9668        << SourceRange(BuiltinLoc, RParenLoc);
9669      Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9670      return ExprError();
9671    }
9672
9673    RecordDecl *Parent = MemberDecl->getParent();
9674    if (IndirectMemberDecl)
9675      Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9676
9677    // If the member was found in a base class, introduce OffsetOfNodes for
9678    // the base class indirections.
9679    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9680                       /*DetectVirtual=*/false);
9681    if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9682      CXXBasePath &Path = Paths.front();
9683      for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9684           B != BEnd; ++B)
9685        Comps.push_back(OffsetOfNode(B->Base));
9686    }
9687
9688    if (IndirectMemberDecl) {
9689      for (IndirectFieldDecl::chain_iterator FI =
9690           IndirectMemberDecl->chain_begin(),
9691           FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9692        assert(isa<FieldDecl>(*FI));
9693        Comps.push_back(OffsetOfNode(OC.LocStart,
9694                                     cast<FieldDecl>(*FI), OC.LocEnd));
9695      }
9696    } else
9697      Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9698
9699    CurrentType = MemberDecl->getType().getNonReferenceType();
9700  }
9701
9702  return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9703                                    TInfo, Comps.data(), Comps.size(),
9704                                    Exprs.data(), Exprs.size(), RParenLoc));
9705}
9706
9707ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9708                                      SourceLocation BuiltinLoc,
9709                                      SourceLocation TypeLoc,
9710                                      ParsedType argty,
9711                                      OffsetOfComponent *CompPtr,
9712                                      unsigned NumComponents,
9713                                      SourceLocation RPLoc) {
9714
9715  TypeSourceInfo *ArgTInfo;
9716  QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9717  if (ArgTy.isNull())
9718    return ExprError();
9719
9720  if (!ArgTInfo)
9721    ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9722
9723  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9724                              RPLoc);
9725}
9726
9727
9728ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9729                                 Expr *CondExpr,
9730                                 Expr *LHSExpr, Expr *RHSExpr,
9731                                 SourceLocation RPLoc) {
9732  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9733
9734  ExprValueKind VK = VK_RValue;
9735  ExprObjectKind OK = OK_Ordinary;
9736  QualType resType;
9737  bool ValueDependent = false;
9738  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9739    resType = Context.DependentTy;
9740    ValueDependent = true;
9741  } else {
9742    // The conditional expression is required to be a constant expression.
9743    llvm::APSInt condEval(32);
9744    SourceLocation ExpLoc;
9745    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
9746      return ExprError(Diag(ExpLoc,
9747                       diag::err_typecheck_choose_expr_requires_constant)
9748        << CondExpr->getSourceRange());
9749
9750    // If the condition is > zero, then the AST type is the same as the LSHExpr.
9751    Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9752
9753    resType = ActiveExpr->getType();
9754    ValueDependent = ActiveExpr->isValueDependent();
9755    VK = ActiveExpr->getValueKind();
9756    OK = ActiveExpr->getObjectKind();
9757  }
9758
9759  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9760                                        resType, VK, OK, RPLoc,
9761                                        resType->isDependentType(),
9762                                        ValueDependent));
9763}
9764
9765//===----------------------------------------------------------------------===//
9766// Clang Extensions.
9767//===----------------------------------------------------------------------===//
9768
9769/// ActOnBlockStart - This callback is invoked when a block literal is started.
9770void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
9771  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9772  PushBlockScope(BlockScope, Block);
9773  CurContext->addDecl(Block);
9774  if (BlockScope)
9775    PushDeclContext(BlockScope, Block);
9776  else
9777    CurContext = Block;
9778}
9779
9780void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
9781  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9782  assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9783  BlockScopeInfo *CurBlock = getCurBlock();
9784
9785  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9786  QualType T = Sig->getType();
9787
9788  // GetTypeForDeclarator always produces a function type for a block
9789  // literal signature.  Furthermore, it is always a FunctionProtoType
9790  // unless the function was written with a typedef.
9791  assert(T->isFunctionType() &&
9792         "GetTypeForDeclarator made a non-function block signature");
9793
9794  // Look for an explicit signature in that function type.
9795  FunctionProtoTypeLoc ExplicitSignature;
9796
9797  TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9798  if (isa<FunctionProtoTypeLoc>(tmp)) {
9799    ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9800
9801    // Check whether that explicit signature was synthesized by
9802    // GetTypeForDeclarator.  If so, don't save that as part of the
9803    // written signature.
9804    if (ExplicitSignature.getLocalRangeBegin() ==
9805        ExplicitSignature.getLocalRangeEnd()) {
9806      // This would be much cheaper if we stored TypeLocs instead of
9807      // TypeSourceInfos.
9808      TypeLoc Result = ExplicitSignature.getResultLoc();
9809      unsigned Size = Result.getFullDataSize();
9810      Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9811      Sig->getTypeLoc().initializeFullCopy(Result, Size);
9812
9813      ExplicitSignature = FunctionProtoTypeLoc();
9814    }
9815  }
9816
9817  CurBlock->TheDecl->setSignatureAsWritten(Sig);
9818  CurBlock->FunctionType = T;
9819
9820  const FunctionType *Fn = T->getAs<FunctionType>();
9821  QualType RetTy = Fn->getResultType();
9822  bool isVariadic =
9823    (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9824
9825  CurBlock->TheDecl->setIsVariadic(isVariadic);
9826
9827  // Don't allow returning a objc interface by value.
9828  if (RetTy->isObjCObjectType()) {
9829    Diag(ParamInfo.getSourceRange().getBegin(),
9830         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9831    return;
9832  }
9833
9834  // Context.DependentTy is used as a placeholder for a missing block
9835  // return type.  TODO:  what should we do with declarators like:
9836  //   ^ * { ... }
9837  // If the answer is "apply template argument deduction"....
9838  if (RetTy != Context.DependentTy)
9839    CurBlock->ReturnType = RetTy;
9840
9841  // Push block parameters from the declarator if we had them.
9842  llvm::SmallVector<ParmVarDecl*, 8> Params;
9843  if (ExplicitSignature) {
9844    for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9845      ParmVarDecl *Param = ExplicitSignature.getArg(I);
9846      if (Param->getIdentifier() == 0 &&
9847          !Param->isImplicit() &&
9848          !Param->isInvalidDecl() &&
9849          !getLangOptions().CPlusPlus)
9850        Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9851      Params.push_back(Param);
9852    }
9853
9854  // Fake up parameter variables if we have a typedef, like
9855  //   ^ fntype { ... }
9856  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9857    for (FunctionProtoType::arg_type_iterator
9858           I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9859      ParmVarDecl *Param =
9860        BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9861                                   ParamInfo.getSourceRange().getBegin(),
9862                                   *I);
9863      Params.push_back(Param);
9864    }
9865  }
9866
9867  // Set the parameters on the block decl.
9868  if (!Params.empty()) {
9869    CurBlock->TheDecl->setParams(Params.data(), Params.size());
9870    CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9871                             CurBlock->TheDecl->param_end(),
9872                             /*CheckParameterNames=*/false);
9873  }
9874
9875  // Finally we can process decl attributes.
9876  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9877
9878  if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
9879    Diag(ParamInfo.getAttributes()->getLoc(),
9880         diag::warn_attribute_sentinel_not_variadic) << 1;
9881    // FIXME: remove the attribute.
9882  }
9883
9884  // Put the parameter variables in scope.  We can bail out immediately
9885  // if we don't have any.
9886  if (Params.empty())
9887    return;
9888
9889  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9890         E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9891    (*AI)->setOwningFunction(CurBlock->TheDecl);
9892
9893    // If this has an identifier, add it to the scope stack.
9894    if ((*AI)->getIdentifier()) {
9895      CheckShadow(CurBlock->TheScope, *AI);
9896
9897      PushOnScopeChains(*AI, CurBlock->TheScope);
9898    }
9899  }
9900}
9901
9902/// ActOnBlockError - If there is an error parsing a block, this callback
9903/// is invoked to pop the information about the block from the action impl.
9904void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9905  // Pop off CurBlock, handle nested blocks.
9906  PopDeclContext();
9907  PopFunctionOrBlockScope();
9908}
9909
9910/// ActOnBlockStmtExpr - This is called when the body of a block statement
9911/// literal was successfully completed.  ^(int x){...}
9912ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9913                                    Stmt *Body, Scope *CurScope) {
9914  // If blocks are disabled, emit an error.
9915  if (!LangOpts.Blocks)
9916    Diag(CaretLoc, diag::err_blocks_disable);
9917
9918  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9919
9920  PopDeclContext();
9921
9922  QualType RetTy = Context.VoidTy;
9923  if (!BSI->ReturnType.isNull())
9924    RetTy = BSI->ReturnType;
9925
9926  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9927  QualType BlockTy;
9928
9929  // Set the captured variables on the block.
9930  BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9931                            BSI->CapturesCXXThis);
9932
9933  // If the user wrote a function type in some form, try to use that.
9934  if (!BSI->FunctionType.isNull()) {
9935    const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9936
9937    FunctionType::ExtInfo Ext = FTy->getExtInfo();
9938    if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9939
9940    // Turn protoless block types into nullary block types.
9941    if (isa<FunctionNoProtoType>(FTy)) {
9942      FunctionProtoType::ExtProtoInfo EPI;
9943      EPI.ExtInfo = Ext;
9944      BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9945
9946    // Otherwise, if we don't need to change anything about the function type,
9947    // preserve its sugar structure.
9948    } else if (FTy->getResultType() == RetTy &&
9949               (!NoReturn || FTy->getNoReturnAttr())) {
9950      BlockTy = BSI->FunctionType;
9951
9952    // Otherwise, make the minimal modifications to the function type.
9953    } else {
9954      const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9955      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9956      EPI.TypeQuals = 0; // FIXME: silently?
9957      EPI.ExtInfo = Ext;
9958      BlockTy = Context.getFunctionType(RetTy,
9959                                        FPT->arg_type_begin(),
9960                                        FPT->getNumArgs(),
9961                                        EPI);
9962    }
9963
9964  // If we don't have a function type, just build one from nothing.
9965  } else {
9966    FunctionProtoType::ExtProtoInfo EPI;
9967    EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9968    BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9969  }
9970
9971  DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9972                           BSI->TheDecl->param_end());
9973  BlockTy = Context.getBlockPointerType(BlockTy);
9974
9975  // If needed, diagnose invalid gotos and switches in the block.
9976  if (getCurFunction()->NeedsScopeChecking() &&
9977      !hasAnyUnrecoverableErrorsInThisFunction())
9978    DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9979
9980  BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9981
9982  BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9983
9984  const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9985  PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
9986  return Owned(Result);
9987}
9988
9989ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9990                                        Expr *expr, ParsedType type,
9991                                        SourceLocation RPLoc) {
9992  TypeSourceInfo *TInfo;
9993  GetTypeFromParser(type, &TInfo);
9994  return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
9995}
9996
9997ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9998                                Expr *E, TypeSourceInfo *TInfo,
9999                                SourceLocation RPLoc) {
10000  Expr *OrigExpr = E;
10001
10002  // Get the va_list type
10003  QualType VaListType = Context.getBuiltinVaListType();
10004  if (VaListType->isArrayType()) {
10005    // Deal with implicit array decay; for example, on x86-64,
10006    // va_list is an array, but it's supposed to decay to
10007    // a pointer for va_arg.
10008    VaListType = Context.getArrayDecayedType(VaListType);
10009    // Make sure the input expression also decays appropriately.
10010    ExprResult Result = UsualUnaryConversions(E);
10011    if (Result.isInvalid())
10012      return ExprError();
10013    E = Result.take();
10014  } else {
10015    // Otherwise, the va_list argument must be an l-value because
10016    // it is modified by va_arg.
10017    if (!E->isTypeDependent() &&
10018        CheckForModifiableLvalue(E, BuiltinLoc, *this))
10019      return ExprError();
10020  }
10021
10022  if (!E->isTypeDependent() &&
10023      !Context.hasSameType(VaListType, E->getType())) {
10024    return ExprError(Diag(E->getLocStart(),
10025                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
10026      << OrigExpr->getType() << E->getSourceRange());
10027  }
10028
10029  if (!TInfo->getType()->isDependentType()) {
10030    if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10031          PDiag(diag::err_second_parameter_to_va_arg_incomplete)
10032          << TInfo->getTypeLoc().getSourceRange()))
10033      return ExprError();
10034
10035    if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10036          TInfo->getType(),
10037          PDiag(diag::err_second_parameter_to_va_arg_abstract)
10038          << TInfo->getTypeLoc().getSourceRange()))
10039      return ExprError();
10040
10041    if (!TInfo->getType().isPODType(Context))
10042      Diag(TInfo->getTypeLoc().getBeginLoc(),
10043          diag::warn_second_parameter_to_va_arg_not_pod)
10044        << TInfo->getType()
10045        << TInfo->getTypeLoc().getSourceRange();
10046  }
10047
10048  QualType T = TInfo->getType().getNonLValueExprType(Context);
10049  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10050}
10051
10052ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10053  // The type of __null will be int or long, depending on the size of
10054  // pointers on the target.
10055  QualType Ty;
10056  unsigned pw = Context.Target.getPointerWidth(0);
10057  if (pw == Context.Target.getIntWidth())
10058    Ty = Context.IntTy;
10059  else if (pw == Context.Target.getLongWidth())
10060    Ty = Context.LongTy;
10061  else if (pw == Context.Target.getLongLongWidth())
10062    Ty = Context.LongLongTy;
10063  else {
10064    assert(!"I don't know size of pointer!");
10065    Ty = Context.IntTy;
10066  }
10067
10068  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10069}
10070
10071static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
10072                                           Expr *SrcExpr, FixItHint &Hint) {
10073  if (!SemaRef.getLangOptions().ObjC1)
10074    return;
10075
10076  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10077  if (!PT)
10078    return;
10079
10080  // Check if the destination is of type 'id'.
10081  if (!PT->isObjCIdType()) {
10082    // Check if the destination is the 'NSString' interface.
10083    const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10084    if (!ID || !ID->getIdentifier()->isStr("NSString"))
10085      return;
10086  }
10087
10088  // Strip off any parens and casts.
10089  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
10090  if (!SL || SL->isWide())
10091    return;
10092
10093  Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
10094}
10095
10096bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10097                                    SourceLocation Loc,
10098                                    QualType DstType, QualType SrcType,
10099                                    Expr *SrcExpr, AssignmentAction Action,
10100                                    bool *Complained) {
10101  if (Complained)
10102    *Complained = false;
10103
10104  // Decode the result (notice that AST's are still created for extensions).
10105  bool CheckInferredResultType = false;
10106  bool isInvalid = false;
10107  unsigned DiagKind;
10108  FixItHint Hint;
10109
10110  switch (ConvTy) {
10111  default: assert(0 && "Unknown conversion type");
10112  case Compatible: return false;
10113  case PointerToInt:
10114    DiagKind = diag::ext_typecheck_convert_pointer_int;
10115    break;
10116  case IntToPointer:
10117    DiagKind = diag::ext_typecheck_convert_int_pointer;
10118    break;
10119  case IncompatiblePointer:
10120    MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
10121    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
10122    CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10123      SrcType->isObjCObjectPointerType();
10124    break;
10125  case IncompatiblePointerSign:
10126    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10127    break;
10128  case FunctionVoidPointer:
10129    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10130    break;
10131  case IncompatiblePointerDiscardsQualifiers: {
10132    // Perform array-to-pointer decay if necessary.
10133    if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10134
10135    Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10136    Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10137    if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10138      DiagKind = diag::err_typecheck_incompatible_address_space;
10139      break;
10140
10141
10142    } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10143      DiagKind = diag::err_typecheck_incompatible_lifetime;
10144      break;
10145    }
10146
10147    llvm_unreachable("unknown error case for discarding qualifiers!");
10148    // fallthrough
10149  }
10150  case CompatiblePointerDiscardsQualifiers:
10151    // If the qualifiers lost were because we were applying the
10152    // (deprecated) C++ conversion from a string literal to a char*
10153    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10154    // Ideally, this check would be performed in
10155    // checkPointerTypesForAssignment. However, that would require a
10156    // bit of refactoring (so that the second argument is an
10157    // expression, rather than a type), which should be done as part
10158    // of a larger effort to fix checkPointerTypesForAssignment for
10159    // C++ semantics.
10160    if (getLangOptions().CPlusPlus &&
10161        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10162      return false;
10163    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10164    break;
10165  case IncompatibleNestedPointerQualifiers:
10166    DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10167    break;
10168  case IntToBlockPointer:
10169    DiagKind = diag::err_int_to_block_pointer;
10170    break;
10171  case IncompatibleBlockPointer:
10172    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10173    break;
10174  case IncompatibleObjCQualifiedId:
10175    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10176    // it can give a more specific diagnostic.
10177    DiagKind = diag::warn_incompatible_qualified_id;
10178    break;
10179  case IncompatibleVectors:
10180    DiagKind = diag::warn_incompatible_vectors;
10181    break;
10182  case Incompatible:
10183    DiagKind = diag::err_typecheck_convert_incompatible;
10184    isInvalid = true;
10185    break;
10186  }
10187
10188  QualType FirstType, SecondType;
10189  switch (Action) {
10190  case AA_Assigning:
10191  case AA_Initializing:
10192    // The destination type comes first.
10193    FirstType = DstType;
10194    SecondType = SrcType;
10195    break;
10196
10197  case AA_Returning:
10198  case AA_Passing:
10199  case AA_Converting:
10200  case AA_Sending:
10201  case AA_Casting:
10202    // The source type comes first.
10203    FirstType = SrcType;
10204    SecondType = DstType;
10205    break;
10206  }
10207
10208  Diag(Loc, DiagKind) << FirstType << SecondType << Action
10209    << SrcExpr->getSourceRange() << Hint;
10210  if (CheckInferredResultType)
10211    EmitRelatedResultTypeNote(SrcExpr);
10212
10213  if (Complained)
10214    *Complained = true;
10215  return isInvalid;
10216}
10217
10218bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
10219  llvm::APSInt ICEResult;
10220  if (E->isIntegerConstantExpr(ICEResult, Context)) {
10221    if (Result)
10222      *Result = ICEResult;
10223    return false;
10224  }
10225
10226  Expr::EvalResult EvalResult;
10227
10228  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
10229      EvalResult.HasSideEffects) {
10230    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
10231
10232    if (EvalResult.Diag) {
10233      // We only show the note if it's not the usual "invalid subexpression"
10234      // or if it's actually in a subexpression.
10235      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
10236          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
10237        Diag(EvalResult.DiagLoc, EvalResult.Diag);
10238    }
10239
10240    return true;
10241  }
10242
10243  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
10244    E->getSourceRange();
10245
10246  if (EvalResult.Diag &&
10247      Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
10248          != Diagnostic::Ignored)
10249    Diag(EvalResult.DiagLoc, EvalResult.Diag);
10250
10251  if (Result)
10252    *Result = EvalResult.Val.getInt();
10253  return false;
10254}
10255
10256void
10257Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
10258  ExprEvalContexts.push_back(
10259             ExpressionEvaluationContextRecord(NewContext,
10260                                               ExprTemporaries.size(),
10261                                               ExprNeedsCleanups));
10262  ExprNeedsCleanups = false;
10263}
10264
10265void
10266Sema::PopExpressionEvaluationContext() {
10267  // Pop the current expression evaluation context off the stack.
10268  ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
10269  ExprEvalContexts.pop_back();
10270
10271  if (Rec.Context == PotentiallyPotentiallyEvaluated) {
10272    if (Rec.PotentiallyReferenced) {
10273      // Mark any remaining declarations in the current position of the stack
10274      // as "referenced". If they were not meant to be referenced, semantic
10275      // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
10276      for (PotentiallyReferencedDecls::iterator
10277             I = Rec.PotentiallyReferenced->begin(),
10278             IEnd = Rec.PotentiallyReferenced->end();
10279           I != IEnd; ++I)
10280        MarkDeclarationReferenced(I->first, I->second);
10281    }
10282
10283    if (Rec.PotentiallyDiagnosed) {
10284      // Emit any pending diagnostics.
10285      for (PotentiallyEmittedDiagnostics::iterator
10286                I = Rec.PotentiallyDiagnosed->begin(),
10287             IEnd = Rec.PotentiallyDiagnosed->end();
10288           I != IEnd; ++I)
10289        Diag(I->first, I->second);
10290    }
10291  }
10292
10293  // When are coming out of an unevaluated context, clear out any
10294  // temporaries that we may have created as part of the evaluation of
10295  // the expression in that context: they aren't relevant because they
10296  // will never be constructed.
10297  if (Rec.Context == Unevaluated) {
10298    ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
10299                          ExprTemporaries.end());
10300    ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10301
10302  // Otherwise, merge the contexts together.
10303  } else {
10304    ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10305  }
10306
10307  // Destroy the popped expression evaluation record.
10308  Rec.Destroy();
10309}
10310
10311void Sema::DiscardCleanupsInEvaluationContext() {
10312  ExprTemporaries.erase(
10313              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
10314              ExprTemporaries.end());
10315  ExprNeedsCleanups = false;
10316}
10317
10318/// \brief Note that the given declaration was referenced in the source code.
10319///
10320/// This routine should be invoke whenever a given declaration is referenced
10321/// in the source code, and where that reference occurred. If this declaration
10322/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
10323/// C99 6.9p3), then the declaration will be marked as used.
10324///
10325/// \param Loc the location where the declaration was referenced.
10326///
10327/// \param D the declaration that has been referenced by the source code.
10328void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
10329  assert(D && "No declaration?");
10330
10331  D->setReferenced();
10332
10333  if (D->isUsed(false))
10334    return;
10335
10336  // Mark a parameter or variable declaration "used", regardless of whether we're in a
10337  // template or not. The reason for this is that unevaluated expressions
10338  // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
10339  // -Wunused-parameters)
10340  if (isa<ParmVarDecl>(D) ||
10341      (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
10342    D->setUsed();
10343    return;
10344  }
10345
10346  if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
10347    return;
10348
10349  // Do not mark anything as "used" within a dependent context; wait for
10350  // an instantiation.
10351  if (CurContext->isDependentContext())
10352    return;
10353
10354  switch (ExprEvalContexts.back().Context) {
10355    case Unevaluated:
10356      // We are in an expression that is not potentially evaluated; do nothing.
10357      return;
10358
10359    case PotentiallyEvaluated:
10360      // We are in a potentially-evaluated expression, so this declaration is
10361      // "used"; handle this below.
10362      break;
10363
10364    case PotentiallyPotentiallyEvaluated:
10365      // We are in an expression that may be potentially evaluated; queue this
10366      // declaration reference until we know whether the expression is
10367      // potentially evaluated.
10368      ExprEvalContexts.back().addReferencedDecl(Loc, D);
10369      return;
10370
10371    case PotentiallyEvaluatedIfUsed:
10372      // Referenced declarations will only be used if the construct in the
10373      // containing expression is used.
10374      return;
10375  }
10376
10377  // Note that this declaration has been used.
10378  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
10379    if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
10380      if (Constructor->isTrivial())
10381        return;
10382      if (!Constructor->isUsed(false))
10383        DefineImplicitDefaultConstructor(Loc, Constructor);
10384    } else if (Constructor->isDefaulted() &&
10385               Constructor->isCopyConstructor()) {
10386      if (!Constructor->isUsed(false))
10387        DefineImplicitCopyConstructor(Loc, Constructor);
10388    }
10389
10390    MarkVTableUsed(Loc, Constructor->getParent());
10391  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
10392    if (Destructor->isDefaulted() && !Destructor->isUsed(false))
10393      DefineImplicitDestructor(Loc, Destructor);
10394    if (Destructor->isVirtual())
10395      MarkVTableUsed(Loc, Destructor->getParent());
10396  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
10397    if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
10398        MethodDecl->getOverloadedOperator() == OO_Equal) {
10399      if (!MethodDecl->isUsed(false))
10400        DefineImplicitCopyAssignment(Loc, MethodDecl);
10401    } else if (MethodDecl->isVirtual())
10402      MarkVTableUsed(Loc, MethodDecl->getParent());
10403  }
10404  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
10405    // Recursive functions should be marked when used from another function.
10406    if (CurContext == Function) return;
10407
10408    // Implicit instantiation of function templates and member functions of
10409    // class templates.
10410    if (Function->isImplicitlyInstantiable()) {
10411      bool AlreadyInstantiated = false;
10412      if (FunctionTemplateSpecializationInfo *SpecInfo
10413                                = Function->getTemplateSpecializationInfo()) {
10414        if (SpecInfo->getPointOfInstantiation().isInvalid())
10415          SpecInfo->setPointOfInstantiation(Loc);
10416        else if (SpecInfo->getTemplateSpecializationKind()
10417                   == TSK_ImplicitInstantiation)
10418          AlreadyInstantiated = true;
10419      } else if (MemberSpecializationInfo *MSInfo
10420                                  = Function->getMemberSpecializationInfo()) {
10421        if (MSInfo->getPointOfInstantiation().isInvalid())
10422          MSInfo->setPointOfInstantiation(Loc);
10423        else if (MSInfo->getTemplateSpecializationKind()
10424                   == TSK_ImplicitInstantiation)
10425          AlreadyInstantiated = true;
10426      }
10427
10428      if (!AlreadyInstantiated) {
10429        if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
10430            cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
10431          PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
10432                                                                      Loc));
10433        else
10434          PendingInstantiations.push_back(std::make_pair(Function, Loc));
10435      }
10436    } else {
10437      // Walk redefinitions, as some of them may be instantiable.
10438      for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
10439           e(Function->redecls_end()); i != e; ++i) {
10440        if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10441          MarkDeclarationReferenced(Loc, *i);
10442      }
10443    }
10444
10445    // Keep track of used but undefined functions.
10446    if (!Function->isPure() && !Function->hasBody() &&
10447        Function->getLinkage() != ExternalLinkage) {
10448      SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
10449      if (old.isInvalid()) old = Loc;
10450    }
10451
10452    Function->setUsed(true);
10453    return;
10454  }
10455
10456  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10457    // Implicit instantiation of static data members of class templates.
10458    if (Var->isStaticDataMember() &&
10459        Var->getInstantiatedFromStaticDataMember()) {
10460      MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10461      assert(MSInfo && "Missing member specialization information?");
10462      if (MSInfo->getPointOfInstantiation().isInvalid() &&
10463          MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10464        MSInfo->setPointOfInstantiation(Loc);
10465        // This is a modification of an existing AST node. Notify listeners.
10466        if (ASTMutationListener *L = getASTMutationListener())
10467          L->StaticDataMemberInstantiated(Var);
10468        PendingInstantiations.push_back(std::make_pair(Var, Loc));
10469      }
10470    }
10471
10472    // Keep track of used but undefined variables.  We make a hole in
10473    // the warning for static const data members with in-line
10474    // initializers.
10475    if (Var->hasDefinition() == VarDecl::DeclarationOnly
10476        && Var->getLinkage() != ExternalLinkage
10477        && !(Var->isStaticDataMember() && Var->hasInit())) {
10478      SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10479      if (old.isInvalid()) old = Loc;
10480    }
10481
10482    D->setUsed(true);
10483    return;
10484  }
10485}
10486
10487namespace {
10488  // Mark all of the declarations referenced
10489  // FIXME: Not fully implemented yet! We need to have a better understanding
10490  // of when we're entering
10491  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10492    Sema &S;
10493    SourceLocation Loc;
10494
10495  public:
10496    typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
10497
10498    MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
10499
10500    bool TraverseTemplateArgument(const TemplateArgument &Arg);
10501    bool TraverseRecordType(RecordType *T);
10502  };
10503}
10504
10505bool MarkReferencedDecls::TraverseTemplateArgument(
10506  const TemplateArgument &Arg) {
10507  if (Arg.getKind() == TemplateArgument::Declaration) {
10508    S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10509  }
10510
10511  return Inherited::TraverseTemplateArgument(Arg);
10512}
10513
10514bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
10515  if (ClassTemplateSpecializationDecl *Spec
10516                  = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10517    const TemplateArgumentList &Args = Spec->getTemplateArgs();
10518    return TraverseTemplateArguments(Args.data(), Args.size());
10519  }
10520
10521  return true;
10522}
10523
10524void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10525  MarkReferencedDecls Marker(*this, Loc);
10526  Marker.TraverseType(Context.getCanonicalType(T));
10527}
10528
10529namespace {
10530  /// \brief Helper class that marks all of the declarations referenced by
10531  /// potentially-evaluated subexpressions as "referenced".
10532  class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10533    Sema &S;
10534
10535  public:
10536    typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10537
10538    explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10539
10540    void VisitDeclRefExpr(DeclRefExpr *E) {
10541      S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10542    }
10543
10544    void VisitMemberExpr(MemberExpr *E) {
10545      S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
10546      Inherited::VisitMemberExpr(E);
10547    }
10548
10549    void VisitCXXNewExpr(CXXNewExpr *E) {
10550      if (E->getConstructor())
10551        S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10552      if (E->getOperatorNew())
10553        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10554      if (E->getOperatorDelete())
10555        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
10556      Inherited::VisitCXXNewExpr(E);
10557    }
10558
10559    void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10560      if (E->getOperatorDelete())
10561        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
10562      QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10563      if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10564        CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10565        S.MarkDeclarationReferenced(E->getLocStart(),
10566                                    S.LookupDestructor(Record));
10567      }
10568
10569      Inherited::VisitCXXDeleteExpr(E);
10570    }
10571
10572    void VisitCXXConstructExpr(CXXConstructExpr *E) {
10573      S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10574      Inherited::VisitCXXConstructExpr(E);
10575    }
10576
10577    void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10578      S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10579    }
10580
10581    void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10582      Visit(E->getExpr());
10583    }
10584  };
10585}
10586
10587/// \brief Mark any declarations that appear within this expression or any
10588/// potentially-evaluated subexpressions as "referenced".
10589void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10590  EvaluatedExprMarker(*this).Visit(E);
10591}
10592
10593/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10594/// of the program being compiled.
10595///
10596/// This routine emits the given diagnostic when the code currently being
10597/// type-checked is "potentially evaluated", meaning that there is a
10598/// possibility that the code will actually be executable. Code in sizeof()
10599/// expressions, code used only during overload resolution, etc., are not
10600/// potentially evaluated. This routine will suppress such diagnostics or,
10601/// in the absolutely nutty case of potentially potentially evaluated
10602/// expressions (C++ typeid), queue the diagnostic to potentially emit it
10603/// later.
10604///
10605/// This routine should be used for all diagnostics that describe the run-time
10606/// behavior of a program, such as passing a non-POD value through an ellipsis.
10607/// Failure to do so will likely result in spurious diagnostics or failures
10608/// during overload resolution or within sizeof/alignof/typeof/typeid.
10609bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
10610                               const PartialDiagnostic &PD) {
10611  switch (ExprEvalContexts.back().Context) {
10612  case Unevaluated:
10613    // The argument will never be evaluated, so don't complain.
10614    break;
10615
10616  case PotentiallyEvaluated:
10617  case PotentiallyEvaluatedIfUsed:
10618    if (stmt && getCurFunctionOrMethodDecl()) {
10619      FunctionScopes.back()->PossiblyUnreachableDiags.
10620        push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10621    }
10622    else
10623      Diag(Loc, PD);
10624
10625    return true;
10626
10627  case PotentiallyPotentiallyEvaluated:
10628    ExprEvalContexts.back().addDiagnostic(Loc, PD);
10629    break;
10630  }
10631
10632  return false;
10633}
10634
10635bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10636                               CallExpr *CE, FunctionDecl *FD) {
10637  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10638    return false;
10639
10640  PartialDiagnostic Note =
10641    FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10642    << FD->getDeclName() : PDiag();
10643  SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
10644
10645  if (RequireCompleteType(Loc, ReturnType,
10646                          FD ?
10647                          PDiag(diag::err_call_function_incomplete_return)
10648                            << CE->getSourceRange() << FD->getDeclName() :
10649                          PDiag(diag::err_call_incomplete_return)
10650                            << CE->getSourceRange(),
10651                          std::make_pair(NoteLoc, Note)))
10652    return true;
10653
10654  return false;
10655}
10656
10657// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
10658// will prevent this condition from triggering, which is what we want.
10659void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10660  SourceLocation Loc;
10661
10662  unsigned diagnostic = diag::warn_condition_is_assignment;
10663  bool IsOrAssign = false;
10664
10665  if (isa<BinaryOperator>(E)) {
10666    BinaryOperator *Op = cast<BinaryOperator>(E);
10667    if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
10668      return;
10669
10670    IsOrAssign = Op->getOpcode() == BO_OrAssign;
10671
10672    // Greylist some idioms by putting them into a warning subcategory.
10673    if (ObjCMessageExpr *ME
10674          = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10675      Selector Sel = ME->getSelector();
10676
10677      // self = [<foo> init...]
10678      if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
10679        diagnostic = diag::warn_condition_is_idiomatic_assignment;
10680
10681      // <foo> = [<bar> nextObject]
10682      else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
10683        diagnostic = diag::warn_condition_is_idiomatic_assignment;
10684    }
10685
10686    Loc = Op->getOperatorLoc();
10687  } else if (isa<CXXOperatorCallExpr>(E)) {
10688    CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
10689    if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
10690      return;
10691
10692    IsOrAssign = Op->getOperator() == OO_PipeEqual;
10693    Loc = Op->getOperatorLoc();
10694  } else {
10695    // Not an assignment.
10696    return;
10697  }
10698
10699  Diag(Loc, diagnostic) << E->getSourceRange();
10700
10701  SourceLocation Open = E->getSourceRange().getBegin();
10702  SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10703  Diag(Loc, diag::note_condition_assign_silence)
10704        << FixItHint::CreateInsertion(Open, "(")
10705        << FixItHint::CreateInsertion(Close, ")");
10706
10707  if (IsOrAssign)
10708    Diag(Loc, diag::note_condition_or_assign_to_comparison)
10709      << FixItHint::CreateReplacement(Loc, "!=");
10710  else
10711    Diag(Loc, diag::note_condition_assign_to_comparison)
10712      << FixItHint::CreateReplacement(Loc, "==");
10713}
10714
10715/// \brief Redundant parentheses over an equality comparison can indicate
10716/// that the user intended an assignment used as condition.
10717void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
10718  // Don't warn if the parens came from a macro.
10719  SourceLocation parenLoc = parenE->getLocStart();
10720  if (parenLoc.isInvalid() || parenLoc.isMacroID())
10721    return;
10722  // Don't warn for dependent expressions.
10723  if (parenE->isTypeDependent())
10724    return;
10725
10726  Expr *E = parenE->IgnoreParens();
10727
10728  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
10729    if (opE->getOpcode() == BO_EQ &&
10730        opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10731                                                           == Expr::MLV_Valid) {
10732      SourceLocation Loc = opE->getOperatorLoc();
10733
10734      Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
10735      Diag(Loc, diag::note_equality_comparison_silence)
10736        << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10737        << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
10738      Diag(Loc, diag::note_equality_comparison_to_assign)
10739        << FixItHint::CreateReplacement(Loc, "=");
10740    }
10741}
10742
10743ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
10744  DiagnoseAssignmentAsCondition(E);
10745  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10746    DiagnoseEqualityWithExtraParens(parenE);
10747
10748  ExprResult result = CheckPlaceholderExpr(E);
10749  if (result.isInvalid()) return ExprError();
10750  E = result.take();
10751
10752  if (!E->isTypeDependent()) {
10753    if (getLangOptions().CPlusPlus)
10754      return CheckCXXBooleanCondition(E); // C++ 6.4p4
10755
10756    ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10757    if (ERes.isInvalid())
10758      return ExprError();
10759    E = ERes.take();
10760
10761    QualType T = E->getType();
10762    if (!T->isScalarType()) { // C99 6.8.4.1p1
10763      Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10764        << T << E->getSourceRange();
10765      return ExprError();
10766    }
10767  }
10768
10769  return Owned(E);
10770}
10771
10772ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10773                                       Expr *Sub) {
10774  if (!Sub)
10775    return ExprError();
10776
10777  return CheckBooleanCondition(Sub, Loc);
10778}
10779
10780namespace {
10781  /// A visitor for rebuilding a call to an __unknown_any expression
10782  /// to have an appropriate type.
10783  struct RebuildUnknownAnyFunction
10784    : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10785
10786    Sema &S;
10787
10788    RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10789
10790    ExprResult VisitStmt(Stmt *S) {
10791      llvm_unreachable("unexpected statement!");
10792      return ExprError();
10793    }
10794
10795    ExprResult VisitExpr(Expr *expr) {
10796      S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10797        << expr->getSourceRange();
10798      return ExprError();
10799    }
10800
10801    /// Rebuild an expression which simply semantically wraps another
10802    /// expression which it shares the type and value kind of.
10803    template <class T> ExprResult rebuildSugarExpr(T *expr) {
10804      ExprResult subResult = Visit(expr->getSubExpr());
10805      if (subResult.isInvalid()) return ExprError();
10806
10807      Expr *subExpr = subResult.take();
10808      expr->setSubExpr(subExpr);
10809      expr->setType(subExpr->getType());
10810      expr->setValueKind(subExpr->getValueKind());
10811      assert(expr->getObjectKind() == OK_Ordinary);
10812      return expr;
10813    }
10814
10815    ExprResult VisitParenExpr(ParenExpr *paren) {
10816      return rebuildSugarExpr(paren);
10817    }
10818
10819    ExprResult VisitUnaryExtension(UnaryOperator *op) {
10820      return rebuildSugarExpr(op);
10821    }
10822
10823    ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10824      ExprResult subResult = Visit(op->getSubExpr());
10825      if (subResult.isInvalid()) return ExprError();
10826
10827      Expr *subExpr = subResult.take();
10828      op->setSubExpr(subExpr);
10829      op->setType(S.Context.getPointerType(subExpr->getType()));
10830      assert(op->getValueKind() == VK_RValue);
10831      assert(op->getObjectKind() == OK_Ordinary);
10832      return op;
10833    }
10834
10835    ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10836      if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10837
10838      expr->setType(decl->getType());
10839
10840      assert(expr->getValueKind() == VK_RValue);
10841      if (S.getLangOptions().CPlusPlus &&
10842          !(isa<CXXMethodDecl>(decl) &&
10843            cast<CXXMethodDecl>(decl)->isInstance()))
10844        expr->setValueKind(VK_LValue);
10845
10846      return expr;
10847    }
10848
10849    ExprResult VisitMemberExpr(MemberExpr *mem) {
10850      return resolveDecl(mem, mem->getMemberDecl());
10851    }
10852
10853    ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10854      return resolveDecl(ref, ref->getDecl());
10855    }
10856  };
10857}
10858
10859/// Given a function expression of unknown-any type, try to rebuild it
10860/// to have a function type.
10861static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10862  ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10863  if (result.isInvalid()) return ExprError();
10864  return S.DefaultFunctionArrayConversion(result.take());
10865}
10866
10867namespace {
10868  /// A visitor for rebuilding an expression of type __unknown_anytype
10869  /// into one which resolves the type directly on the referring
10870  /// expression.  Strict preservation of the original source
10871  /// structure is not a goal.
10872  struct RebuildUnknownAnyExpr
10873    : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
10874
10875    Sema &S;
10876
10877    /// The current destination type.
10878    QualType DestType;
10879
10880    RebuildUnknownAnyExpr(Sema &S, QualType castType)
10881      : S(S), DestType(castType) {}
10882
10883    ExprResult VisitStmt(Stmt *S) {
10884      llvm_unreachable("unexpected statement!");
10885      return ExprError();
10886    }
10887
10888    ExprResult VisitExpr(Expr *expr) {
10889      S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10890        << expr->getSourceRange();
10891      return ExprError();
10892    }
10893
10894    ExprResult VisitCallExpr(CallExpr *call);
10895    ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10896
10897    /// Rebuild an expression which simply semantically wraps another
10898    /// expression which it shares the type and value kind of.
10899    template <class T> ExprResult rebuildSugarExpr(T *expr) {
10900      ExprResult subResult = Visit(expr->getSubExpr());
10901      if (subResult.isInvalid()) return ExprError();
10902      Expr *subExpr = subResult.take();
10903      expr->setSubExpr(subExpr);
10904      expr->setType(subExpr->getType());
10905      expr->setValueKind(subExpr->getValueKind());
10906      assert(expr->getObjectKind() == OK_Ordinary);
10907      return expr;
10908    }
10909
10910    ExprResult VisitParenExpr(ParenExpr *paren) {
10911      return rebuildSugarExpr(paren);
10912    }
10913
10914    ExprResult VisitUnaryExtension(UnaryOperator *op) {
10915      return rebuildSugarExpr(op);
10916    }
10917
10918    ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10919      const PointerType *ptr = DestType->getAs<PointerType>();
10920      if (!ptr) {
10921        S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10922          << op->getSourceRange();
10923        return ExprError();
10924      }
10925      assert(op->getValueKind() == VK_RValue);
10926      assert(op->getObjectKind() == OK_Ordinary);
10927      op->setType(DestType);
10928
10929      // Build the sub-expression as if it were an object of the pointee type.
10930      DestType = ptr->getPointeeType();
10931      ExprResult subResult = Visit(op->getSubExpr());
10932      if (subResult.isInvalid()) return ExprError();
10933      op->setSubExpr(subResult.take());
10934      return op;
10935    }
10936
10937    ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
10938
10939    ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
10940
10941    ExprResult VisitMemberExpr(MemberExpr *mem) {
10942      return resolveDecl(mem, mem->getMemberDecl());
10943    }
10944
10945    ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10946      return resolveDecl(ref, ref->getDecl());
10947    }
10948  };
10949}
10950
10951/// Rebuilds a call expression which yielded __unknown_anytype.
10952ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10953  Expr *callee = call->getCallee();
10954
10955  enum FnKind {
10956    FK_MemberFunction,
10957    FK_FunctionPointer,
10958    FK_BlockPointer
10959  };
10960
10961  FnKind kind;
10962  QualType type = callee->getType();
10963  if (type == S.Context.BoundMemberTy) {
10964    assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10965    kind = FK_MemberFunction;
10966    type = Expr::findBoundMemberType(callee);
10967  } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10968    type = ptr->getPointeeType();
10969    kind = FK_FunctionPointer;
10970  } else {
10971    type = type->castAs<BlockPointerType>()->getPointeeType();
10972    kind = FK_BlockPointer;
10973  }
10974  const FunctionType *fnType = type->castAs<FunctionType>();
10975
10976  // Verify that this is a legal result type of a function.
10977  if (DestType->isArrayType() || DestType->isFunctionType()) {
10978    unsigned diagID = diag::err_func_returning_array_function;
10979    if (kind == FK_BlockPointer)
10980      diagID = diag::err_block_returning_array_function;
10981
10982    S.Diag(call->getExprLoc(), diagID)
10983      << DestType->isFunctionType() << DestType;
10984    return ExprError();
10985  }
10986
10987  // Otherwise, go ahead and set DestType as the call's result.
10988  call->setType(DestType.getNonLValueExprType(S.Context));
10989  call->setValueKind(Expr::getValueKindForType(DestType));
10990  assert(call->getObjectKind() == OK_Ordinary);
10991
10992  // Rebuild the function type, replacing the result type with DestType.
10993  if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10994    DestType = S.Context.getFunctionType(DestType,
10995                                         proto->arg_type_begin(),
10996                                         proto->getNumArgs(),
10997                                         proto->getExtProtoInfo());
10998  else
10999    DestType = S.Context.getFunctionNoProtoType(DestType,
11000                                                fnType->getExtInfo());
11001
11002  // Rebuild the appropriate pointer-to-function type.
11003  switch (kind) {
11004  case FK_MemberFunction:
11005    // Nothing to do.
11006    break;
11007
11008  case FK_FunctionPointer:
11009    DestType = S.Context.getPointerType(DestType);
11010    break;
11011
11012  case FK_BlockPointer:
11013    DestType = S.Context.getBlockPointerType(DestType);
11014    break;
11015  }
11016
11017  // Finally, we can recurse.
11018  ExprResult calleeResult = Visit(callee);
11019  if (!calleeResult.isUsable()) return ExprError();
11020  call->setCallee(calleeResult.take());
11021
11022  // Bind a temporary if necessary.
11023  return S.MaybeBindToTemporary(call);
11024}
11025
11026ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
11027  ObjCMethodDecl *method = msg->getMethodDecl();
11028  assert(method && "__unknown_anytype message without result type?");
11029
11030  // Verify that this is a legal result type of a call.
11031  if (DestType->isArrayType() || DestType->isFunctionType()) {
11032    S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
11033      << DestType->isFunctionType() << DestType;
11034    return ExprError();
11035  }
11036
11037  assert(method->getResultType() == S.Context.UnknownAnyTy);
11038  method->setResultType(DestType);
11039
11040  // Change the type of the message.
11041  msg->setType(DestType.getNonReferenceType());
11042  msg->setValueKind(Expr::getValueKindForType(DestType));
11043
11044  return S.MaybeBindToTemporary(msg);
11045}
11046
11047ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
11048  // The only case we should ever see here is a function-to-pointer decay.
11049  assert(ice->getCastKind() == CK_FunctionToPointerDecay);
11050  assert(ice->getValueKind() == VK_RValue);
11051  assert(ice->getObjectKind() == OK_Ordinary);
11052
11053  ice->setType(DestType);
11054
11055  // Rebuild the sub-expression as the pointee (function) type.
11056  DestType = DestType->castAs<PointerType>()->getPointeeType();
11057
11058  ExprResult result = Visit(ice->getSubExpr());
11059  if (!result.isUsable()) return ExprError();
11060
11061  ice->setSubExpr(result.take());
11062  return S.Owned(ice);
11063}
11064
11065ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
11066  ExprValueKind valueKind = VK_LValue;
11067  QualType type = DestType;
11068
11069  // We know how to make this work for certain kinds of decls:
11070
11071  //  - functions
11072  if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
11073    // This is true because FunctionDecls must always have function
11074    // type, so we can't be resolving the entire thing at once.
11075    assert(type->isFunctionType());
11076
11077    if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
11078      if (method->isInstance()) {
11079        valueKind = VK_RValue;
11080        type = S.Context.BoundMemberTy;
11081      }
11082
11083    // Function references aren't l-values in C.
11084    if (!S.getLangOptions().CPlusPlus)
11085      valueKind = VK_RValue;
11086
11087  //  - variables
11088  } else if (isa<VarDecl>(decl)) {
11089    if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
11090      type = refTy->getPointeeType();
11091    } else if (type->isFunctionType()) {
11092      S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
11093        << decl << expr->getSourceRange();
11094      return ExprError();
11095    }
11096
11097  //  - nothing else
11098  } else {
11099    S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11100      << decl << expr->getSourceRange();
11101    return ExprError();
11102  }
11103
11104  decl->setType(DestType);
11105  expr->setType(type);
11106  expr->setValueKind(valueKind);
11107  return S.Owned(expr);
11108}
11109
11110/// Check a cast of an unknown-any type.  We intentionally only
11111/// trigger this for C-style casts.
11112ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
11113                                     Expr *castExpr, CastKind &castKind,
11114                                     ExprValueKind &VK, CXXCastPath &path) {
11115  // Rewrite the casted expression from scratch.
11116  ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
11117  if (!result.isUsable()) return ExprError();
11118
11119  castExpr = result.take();
11120  VK = castExpr->getValueKind();
11121  castKind = CK_NoOp;
11122
11123  return castExpr;
11124}
11125
11126static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
11127  Expr *orig = e;
11128  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
11129  while (true) {
11130    e = e->IgnoreParenImpCasts();
11131    if (CallExpr *call = dyn_cast<CallExpr>(e)) {
11132      e = call->getCallee();
11133      diagID = diag::err_uncasted_call_of_unknown_any;
11134    } else {
11135      break;
11136    }
11137  }
11138
11139  SourceLocation loc;
11140  NamedDecl *d;
11141  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11142    loc = ref->getLocation();
11143    d = ref->getDecl();
11144  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
11145    loc = mem->getMemberLoc();
11146    d = mem->getMemberDecl();
11147  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
11148    diagID = diag::err_uncasted_call_of_unknown_any;
11149    loc = msg->getSelectorLoc();
11150    d = msg->getMethodDecl();
11151    assert(d && "unknown method returning __unknown_any?");
11152  } else {
11153    S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11154      << e->getSourceRange();
11155    return ExprError();
11156  }
11157
11158  S.Diag(loc, diagID) << d << orig->getSourceRange();
11159
11160  // Never recoverable.
11161  return ExprError();
11162}
11163
11164/// Check for operands with placeholder types and complain if found.
11165/// Returns true if there was an error and no recovery was possible.
11166ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
11167  // Placeholder types are always *exactly* the appropriate builtin type.
11168  QualType type = E->getType();
11169
11170  // Overloaded expressions.
11171  if (type == Context.OverloadTy)
11172    return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
11173                                                           E->getSourceRange(),
11174                                                             QualType(),
11175                                                   diag::err_ovl_unresolvable);
11176
11177  // Bound member functions.
11178  if (type == Context.BoundMemberTy) {
11179    Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
11180      << E->getSourceRange();
11181    return ExprError();
11182  }
11183
11184  // Expressions of unknown type.
11185  if (type == Context.UnknownAnyTy)
11186    return diagnoseUnknownAnyExpr(*this, E);
11187
11188  assert(!type->isPlaceholderType());
11189  return Owned(E);
11190}
11191
11192bool Sema::CheckCaseExpression(Expr *expr) {
11193  if (expr->isTypeDependent())
11194    return true;
11195  if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
11196    return expr->getType()->isIntegralOrEnumerationType();
11197  return false;
11198}
11199