SemaExpr.cpp revision 89ebaed91cca7fd296ec7804e4e9fb68949c1d0e
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/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/RecursiveASTVisitor.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Template.h"
39using namespace clang;
40using namespace sema;
41
42
43/// \brief Determine whether the use of this declaration is valid, and
44/// emit any corresponding diagnostics.
45///
46/// This routine diagnoses various problems with referencing
47/// declarations that can occur when using a declaration. For example,
48/// it might warn if a deprecated or unavailable declaration is being
49/// used, or produce an error (and return true) if a C++0x deleted
50/// function is being used.
51///
52/// If IgnoreDeprecated is set to true, this should not warn about deprecated
53/// decls.
54///
55/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
57///
58bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
59                             const ObjCInterfaceDecl *UnknownObjCClass) {
60  if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61    // If there were any diagnostics suppressed by template argument deduction,
62    // emit them now.
63    llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64      Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65    if (Pos != SuppressedDiagnostics.end()) {
66      llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67      for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68        Diag(Suppressed[I].first, Suppressed[I].second);
69
70      // Clear out the list of suppressed diagnostics, so that we don't emit
71      // them again for this specialization. However, we don't obsolete this
72      // entry from the table, because we want to avoid ever emitting these
73      // diagnostics again.
74      Suppressed.clear();
75    }
76  }
77
78  // See if this is an auto-typed variable whose initializer we are parsing.
79  if (ParsingInitForAutoVars.count(D)) {
80    Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
81      << D->getDeclName();
82    return true;
83  }
84
85  // See if this is a deleted function.
86  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
87    if (FD->isDeleted()) {
88      Diag(Loc, diag::err_deleted_function_use);
89      Diag(D->getLocation(), diag::note_unavailable_here) << true;
90      return true;
91    }
92  }
93
94  // See if this declaration is unavailable or deprecated.
95  std::string Message;
96  switch (D->getAvailability(&Message)) {
97  case AR_Available:
98  case AR_NotYetIntroduced:
99    break;
100
101  case AR_Deprecated:
102    EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
103    break;
104
105  case AR_Unavailable:
106    if (Message.empty()) {
107      if (!UnknownObjCClass)
108        Diag(Loc, diag::err_unavailable) << D->getDeclName();
109      else
110        Diag(Loc, diag::warn_unavailable_fwdclass_message)
111             << D->getDeclName();
112    }
113    else
114      Diag(Loc, diag::err_unavailable_message)
115        << D->getDeclName() << Message;
116    Diag(D->getLocation(), diag::note_unavailable_here) << 0;
117    break;
118  }
119
120  // Warn if this is used but marked unused.
121  if (D->hasAttr<UnusedAttr>())
122    Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
123
124  return false;
125}
126
127/// \brief Retrieve the message suffix that should be added to a
128/// diagnostic complaining about the given function being deleted or
129/// unavailable.
130std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
131  // FIXME: C++0x implicitly-deleted special member functions could be
132  // detected here so that we could improve diagnostics to say, e.g.,
133  // "base class 'A' had a deleted copy constructor".
134  if (FD->isDeleted())
135    return std::string();
136
137  std::string Message;
138  if (FD->getAvailability(&Message))
139    return ": " + Message;
140
141  return std::string();
142}
143
144/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
145/// (and other functions in future), which have been declared with sentinel
146/// attribute. It warns if call does not have the sentinel argument.
147///
148void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
149                                 Expr **Args, unsigned NumArgs) {
150  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
151  if (!attr)
152    return;
153
154  // FIXME: In C++0x, if any of the arguments are parameter pack
155  // expansions, we can't check for the sentinel now.
156  int sentinelPos = attr->getSentinel();
157  int nullPos = attr->getNullPos();
158
159  // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
160  // base class. Then we won't be needing two versions of the same code.
161  unsigned int i = 0;
162  bool warnNotEnoughArgs = false;
163  int isMethod = 0;
164  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
165    // skip over named parameters.
166    ObjCMethodDecl::param_iterator P, E = MD->param_end();
167    for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
168      if (nullPos)
169        --nullPos;
170      else
171        ++i;
172    }
173    warnNotEnoughArgs = (P != E || i >= NumArgs);
174    isMethod = 1;
175  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
176    // skip over named parameters.
177    ObjCMethodDecl::param_iterator P, E = FD->param_end();
178    for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
179      if (nullPos)
180        --nullPos;
181      else
182        ++i;
183    }
184    warnNotEnoughArgs = (P != E || i >= NumArgs);
185  } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
186    // block or function pointer call.
187    QualType Ty = V->getType();
188    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
189      const FunctionType *FT = Ty->isFunctionPointerType()
190      ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
191      : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
192      if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
193        unsigned NumArgsInProto = Proto->getNumArgs();
194        unsigned k;
195        for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
196          if (nullPos)
197            --nullPos;
198          else
199            ++i;
200        }
201        warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
202      }
203      if (Ty->isBlockPointerType())
204        isMethod = 2;
205    } else
206      return;
207  } else
208    return;
209
210  if (warnNotEnoughArgs) {
211    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
212    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
213    return;
214  }
215  int sentinel = i;
216  while (sentinelPos > 0 && i < NumArgs-1) {
217    --sentinelPos;
218    ++i;
219  }
220  if (sentinelPos > 0) {
221    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
222    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
223    return;
224  }
225  while (i < NumArgs-1) {
226    ++i;
227    ++sentinel;
228  }
229  Expr *sentinelExpr = Args[sentinel];
230  if (!sentinelExpr) return;
231  if (sentinelExpr->isTypeDependent()) return;
232  if (sentinelExpr->isValueDependent()) return;
233
234  // nullptr_t is always treated as null.
235  if (sentinelExpr->getType()->isNullPtrType()) return;
236
237  if (sentinelExpr->getType()->isAnyPointerType() &&
238      sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
239                                            Expr::NPC_ValueDependentIsNull))
240    return;
241
242  // Unfortunately, __null has type 'int'.
243  if (isa<GNUNullExpr>(sentinelExpr)) return;
244
245  Diag(Loc, diag::warn_missing_sentinel) << isMethod;
246  Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
247}
248
249SourceRange Sema::getExprRange(ExprTy *E) const {
250  Expr *Ex = (Expr *)E;
251  return Ex? Ex->getSourceRange() : SourceRange();
252}
253
254//===----------------------------------------------------------------------===//
255//  Standard Promotions and Conversions
256//===----------------------------------------------------------------------===//
257
258/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
259ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
260  QualType Ty = E->getType();
261  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
262
263  if (Ty->isFunctionType())
264    E = ImpCastExprToType(E, Context.getPointerType(Ty),
265                          CK_FunctionToPointerDecay).take();
266  else if (Ty->isArrayType()) {
267    // In C90 mode, arrays only promote to pointers if the array expression is
268    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
269    // type 'array of type' is converted to an expression that has type 'pointer
270    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
271    // that has type 'array of type' ...".  The relevant change is "an lvalue"
272    // (C90) to "an expression" (C99).
273    //
274    // C++ 4.2p1:
275    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
276    // T" can be converted to an rvalue of type "pointer to T".
277    //
278    if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
279      E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
280                            CK_ArrayToPointerDecay).take();
281  }
282  return Owned(E);
283}
284
285ExprResult Sema::DefaultLvalueConversion(Expr *E) {
286  // C++ [conv.lval]p1:
287  //   A glvalue of a non-function, non-array type T can be
288  //   converted to a prvalue.
289  if (!E->isGLValue()) return Owned(E);
290
291  QualType T = E->getType();
292  assert(!T.isNull() && "r-value conversion on typeless expression?");
293
294  // Create a load out of an ObjCProperty l-value, if necessary.
295  if (E->getObjectKind() == OK_ObjCProperty) {
296    ExprResult Res = ConvertPropertyForRValue(E);
297    if (Res.isInvalid())
298      return Owned(E);
299    E = Res.take();
300    if (!E->isGLValue())
301      return Owned(E);
302  }
303
304  // We don't want to throw lvalue-to-rvalue casts on top of
305  // expressions of certain types in C++.
306  if (getLangOptions().CPlusPlus &&
307      (E->getType() == Context.OverloadTy ||
308       T->isDependentType() ||
309       T->isRecordType()))
310    return Owned(E);
311
312  // The C standard is actually really unclear on this point, and
313  // DR106 tells us what the result should be but not why.  It's
314  // generally best to say that void types just doesn't undergo
315  // lvalue-to-rvalue at all.  Note that expressions of unqualified
316  // 'void' type are never l-values, but qualified void can be.
317  if (T->isVoidType())
318    return Owned(E);
319
320  // C++ [conv.lval]p1:
321  //   [...] If T is a non-class type, the type of the prvalue is the
322  //   cv-unqualified version of T. Otherwise, the type of the
323  //   rvalue is T.
324  //
325  // C99 6.3.2.1p2:
326  //   If the lvalue has qualified type, the value has the unqualified
327  //   version of the type of the lvalue; otherwise, the value has the
328  //   type of the lvalue.
329  if (T.hasQualifiers())
330    T = T.getUnqualifiedType();
331
332  CheckArrayAccess(E);
333
334  return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
335                                        E, 0, VK_RValue));
336}
337
338ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
339  ExprResult Res = DefaultFunctionArrayConversion(E);
340  if (Res.isInvalid())
341    return ExprError();
342  Res = DefaultLvalueConversion(Res.take());
343  if (Res.isInvalid())
344    return ExprError();
345  return move(Res);
346}
347
348
349/// UsualUnaryConversions - Performs various conversions that are common to most
350/// operators (C99 6.3). The conversions of array and function types are
351/// sometimes suppressed. For example, the array->pointer conversion doesn't
352/// apply if the array is an argument to the sizeof or address (&) operators.
353/// In these instances, this routine should *not* be called.
354ExprResult Sema::UsualUnaryConversions(Expr *E) {
355  // First, convert to an r-value.
356  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
357  if (Res.isInvalid())
358    return Owned(E);
359  E = Res.take();
360
361  QualType Ty = E->getType();
362  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
363
364  // Try to perform integral promotions if the object has a theoretically
365  // promotable type.
366  if (Ty->isIntegralOrUnscopedEnumerationType()) {
367    // C99 6.3.1.1p2:
368    //
369    //   The following may be used in an expression wherever an int or
370    //   unsigned int may be used:
371    //     - an object or expression with an integer type whose integer
372    //       conversion rank is less than or equal to the rank of int
373    //       and unsigned int.
374    //     - A bit-field of type _Bool, int, signed int, or unsigned int.
375    //
376    //   If an int can represent all values of the original type, the
377    //   value is converted to an int; otherwise, it is converted to an
378    //   unsigned int. These are called the integer promotions. All
379    //   other types are unchanged by the integer promotions.
380
381    QualType PTy = Context.isPromotableBitField(E);
382    if (!PTy.isNull()) {
383      E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
384      return Owned(E);
385    }
386    if (Ty->isPromotableIntegerType()) {
387      QualType PT = Context.getPromotedIntegerType(Ty);
388      E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
389      return Owned(E);
390    }
391  }
392  return Owned(E);
393}
394
395/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
396/// do not have a prototype. Arguments that have type float are promoted to
397/// double. All other argument types are converted by UsualUnaryConversions().
398ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
399  QualType Ty = E->getType();
400  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
401
402  ExprResult Res = UsualUnaryConversions(E);
403  if (Res.isInvalid())
404    return Owned(E);
405  E = Res.take();
406
407  // If this is a 'float' (CVR qualified or typedef) promote to double.
408  if (Ty->isSpecificBuiltinType(BuiltinType::Float))
409    E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
410
411  return Owned(E);
412}
413
414/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
415/// will warn if the resulting type is not a POD type, and rejects ObjC
416/// interfaces passed by value.
417ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
418                                            FunctionDecl *FDecl) {
419  ExprResult ExprRes = DefaultArgumentPromotion(E);
420  if (ExprRes.isInvalid())
421    return ExprError();
422  E = ExprRes.take();
423
424  // __builtin_va_start takes the second argument as a "varargs" argument, but
425  // it doesn't actually do anything with it.  It doesn't need to be non-pod
426  // etc.
427  if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
428    return Owned(E);
429
430  if (E->getType()->isObjCObjectType() &&
431      DiagRuntimeBehavior(E->getLocStart(), 0,
432        PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
433          << E->getType() << CT))
434    return ExprError();
435
436  if (!E->getType()->isPODType() &&
437      DiagRuntimeBehavior(E->getLocStart(), 0,
438                          PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
439                            << E->getType() << CT))
440    return ExprError();
441
442  return Owned(E);
443}
444
445/// UsualArithmeticConversions - Performs various conversions that are common to
446/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
447/// routine returns the first non-arithmetic type found. The client is
448/// responsible for emitting appropriate error diagnostics.
449/// FIXME: verify the conversion rules for "complex int" are consistent with
450/// GCC.
451QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
452                                          bool isCompAssign) {
453  if (!isCompAssign) {
454    lhsExpr = UsualUnaryConversions(lhsExpr.take());
455    if (lhsExpr.isInvalid())
456      return QualType();
457  }
458
459  rhsExpr = UsualUnaryConversions(rhsExpr.take());
460  if (rhsExpr.isInvalid())
461    return QualType();
462
463  // For conversion purposes, we ignore any qualifiers.
464  // For example, "const float" and "float" are equivalent.
465  QualType lhs =
466    Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
467  QualType rhs =
468    Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
469
470  // If both types are identical, no conversion is needed.
471  if (lhs == rhs)
472    return lhs;
473
474  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
475  // The caller can deal with this (e.g. pointer + int).
476  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
477    return lhs;
478
479  // Apply unary and bitfield promotions to the LHS's type.
480  QualType lhs_unpromoted = lhs;
481  if (lhs->isPromotableIntegerType())
482    lhs = Context.getPromotedIntegerType(lhs);
483  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
484  if (!LHSBitfieldPromoteTy.isNull())
485    lhs = LHSBitfieldPromoteTy;
486  if (lhs != lhs_unpromoted && !isCompAssign)
487    lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
488
489  // If both types are identical, no conversion is needed.
490  if (lhs == rhs)
491    return lhs;
492
493  // At this point, we have two different arithmetic types.
494
495  // Handle complex types first (C99 6.3.1.8p1).
496  bool LHSComplexFloat = lhs->isComplexType();
497  bool RHSComplexFloat = rhs->isComplexType();
498  if (LHSComplexFloat || RHSComplexFloat) {
499    // if we have an integer operand, the result is the complex type.
500
501    if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
502      if (rhs->isIntegerType()) {
503        QualType fp = cast<ComplexType>(lhs)->getElementType();
504        rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
505        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
506      } else {
507        assert(rhs->isComplexIntegerType());
508        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
509      }
510      return lhs;
511    }
512
513    if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
514      if (!isCompAssign) {
515        // int -> float -> _Complex float
516        if (lhs->isIntegerType()) {
517          QualType fp = cast<ComplexType>(rhs)->getElementType();
518          lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
519          lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
520        } else {
521          assert(lhs->isComplexIntegerType());
522          lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
523        }
524      }
525      return rhs;
526    }
527
528    // This handles complex/complex, complex/float, or float/complex.
529    // When both operands are complex, the shorter operand is converted to the
530    // type of the longer, and that is the type of the result. This corresponds
531    // to what is done when combining two real floating-point operands.
532    // The fun begins when size promotion occur across type domains.
533    // From H&S 6.3.4: When one operand is complex and the other is a real
534    // floating-point type, the less precise type is converted, within it's
535    // real or complex domain, to the precision of the other type. For example,
536    // when combining a "long double" with a "double _Complex", the
537    // "double _Complex" is promoted to "long double _Complex".
538    int order = Context.getFloatingTypeOrder(lhs, rhs);
539
540    // If both are complex, just cast to the more precise type.
541    if (LHSComplexFloat && RHSComplexFloat) {
542      if (order > 0) {
543        // _Complex float -> _Complex double
544        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
545        return lhs;
546
547      } else if (order < 0) {
548        // _Complex float -> _Complex double
549        if (!isCompAssign)
550          lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
551        return rhs;
552      }
553      return lhs;
554    }
555
556    // If just the LHS is complex, the RHS needs to be converted,
557    // and the LHS might need to be promoted.
558    if (LHSComplexFloat) {
559      if (order > 0) { // LHS is wider
560        // float -> _Complex double
561        QualType fp = cast<ComplexType>(lhs)->getElementType();
562        rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
563        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
564        return lhs;
565      }
566
567      // RHS is at least as wide.  Find its corresponding complex type.
568      QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
569
570      // double -> _Complex double
571      rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
572
573      // _Complex float -> _Complex double
574      if (!isCompAssign && order < 0)
575        lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
576
577      return result;
578    }
579
580    // Just the RHS is complex, so the LHS needs to be converted
581    // and the RHS might need to be promoted.
582    assert(RHSComplexFloat);
583
584    if (order < 0) { // RHS is wider
585      // float -> _Complex double
586      if (!isCompAssign) {
587        QualType fp = cast<ComplexType>(rhs)->getElementType();
588        lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
589        lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
590      }
591      return rhs;
592    }
593
594    // LHS is at least as wide.  Find its corresponding complex type.
595    QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
596
597    // double -> _Complex double
598    if (!isCompAssign)
599      lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
600
601    // _Complex float -> _Complex double
602    if (order > 0)
603      rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
604
605    return result;
606  }
607
608  // Now handle "real" floating types (i.e. float, double, long double).
609  bool LHSFloat = lhs->isRealFloatingType();
610  bool RHSFloat = rhs->isRealFloatingType();
611  if (LHSFloat || RHSFloat) {
612    // If we have two real floating types, convert the smaller operand
613    // to the bigger result.
614    if (LHSFloat && RHSFloat) {
615      int order = Context.getFloatingTypeOrder(lhs, rhs);
616      if (order > 0) {
617        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
618        return lhs;
619      }
620
621      assert(order < 0 && "illegal float comparison");
622      if (!isCompAssign)
623        lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
624      return rhs;
625    }
626
627    // If we have an integer operand, the result is the real floating type.
628    if (LHSFloat) {
629      if (rhs->isIntegerType()) {
630        // Convert rhs to the lhs floating point type.
631        rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
632        return lhs;
633      }
634
635      // Convert both sides to the appropriate complex float.
636      assert(rhs->isComplexIntegerType());
637      QualType result = Context.getComplexType(lhs);
638
639      // _Complex int -> _Complex float
640      rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
641
642      // float -> _Complex float
643      if (!isCompAssign)
644        lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
645
646      return result;
647    }
648
649    assert(RHSFloat);
650    if (lhs->isIntegerType()) {
651      // Convert lhs to the rhs floating point type.
652      if (!isCompAssign)
653        lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
654      return rhs;
655    }
656
657    // Convert both sides to the appropriate complex float.
658    assert(lhs->isComplexIntegerType());
659    QualType result = Context.getComplexType(rhs);
660
661    // _Complex int -> _Complex float
662    if (!isCompAssign)
663      lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
664
665    // float -> _Complex float
666    rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
667
668    return result;
669  }
670
671  // Handle GCC complex int extension.
672  // FIXME: if the operands are (int, _Complex long), we currently
673  // don't promote the complex.  Also, signedness?
674  const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
675  const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
676  if (lhsComplexInt && rhsComplexInt) {
677    int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
678                                            rhsComplexInt->getElementType());
679    assert(order && "inequal types with equal element ordering");
680    if (order > 0) {
681      // _Complex int -> _Complex long
682      rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
683      return lhs;
684    }
685
686    if (!isCompAssign)
687      lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
688    return rhs;
689  } else if (lhsComplexInt) {
690    // int -> _Complex int
691    rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
692    return lhs;
693  } else if (rhsComplexInt) {
694    // int -> _Complex int
695    if (!isCompAssign)
696      lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
697    return rhs;
698  }
699
700  // Finally, we have two differing integer types.
701  // The rules for this case are in C99 6.3.1.8
702  int compare = Context.getIntegerTypeOrder(lhs, rhs);
703  bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
704       rhsSigned = rhs->hasSignedIntegerRepresentation();
705  if (lhsSigned == rhsSigned) {
706    // Same signedness; use the higher-ranked type
707    if (compare >= 0) {
708      rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
709      return lhs;
710    } else if (!isCompAssign)
711      lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
712    return rhs;
713  } else if (compare != (lhsSigned ? 1 : -1)) {
714    // The unsigned type has greater than or equal rank to the
715    // signed type, so use the unsigned type
716    if (rhsSigned) {
717      rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
718      return lhs;
719    } else if (!isCompAssign)
720      lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
721    return rhs;
722  } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
723    // The two types are different widths; if we are here, that
724    // means the signed type is larger than the unsigned type, so
725    // use the signed type.
726    if (lhsSigned) {
727      rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
728      return lhs;
729    } else if (!isCompAssign)
730      lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
731    return rhs;
732  } else {
733    // The signed type is higher-ranked than the unsigned type,
734    // but isn't actually any bigger (like unsigned int and long
735    // on most 32-bit systems).  Use the unsigned type corresponding
736    // to the signed type.
737    QualType result =
738      Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
739    rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
740    if (!isCompAssign)
741      lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
742    return result;
743  }
744}
745
746//===----------------------------------------------------------------------===//
747//  Semantic Analysis for various Expression Types
748//===----------------------------------------------------------------------===//
749
750
751ExprResult
752Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
753                                SourceLocation DefaultLoc,
754                                SourceLocation RParenLoc,
755                                Expr *ControllingExpr,
756                                MultiTypeArg types,
757                                MultiExprArg exprs) {
758  unsigned NumAssocs = types.size();
759  assert(NumAssocs == exprs.size());
760
761  ParsedType *ParsedTypes = types.release();
762  Expr **Exprs = exprs.release();
763
764  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
765  for (unsigned i = 0; i < NumAssocs; ++i) {
766    if (ParsedTypes[i])
767      (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
768    else
769      Types[i] = 0;
770  }
771
772  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
773                                             ControllingExpr, Types, Exprs,
774                                             NumAssocs);
775  delete [] Types;
776  return ER;
777}
778
779ExprResult
780Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
781                                 SourceLocation DefaultLoc,
782                                 SourceLocation RParenLoc,
783                                 Expr *ControllingExpr,
784                                 TypeSourceInfo **Types,
785                                 Expr **Exprs,
786                                 unsigned NumAssocs) {
787  bool TypeErrorFound = false,
788       IsResultDependent = ControllingExpr->isTypeDependent(),
789       ContainsUnexpandedParameterPack
790         = ControllingExpr->containsUnexpandedParameterPack();
791
792  for (unsigned i = 0; i < NumAssocs; ++i) {
793    if (Exprs[i]->containsUnexpandedParameterPack())
794      ContainsUnexpandedParameterPack = true;
795
796    if (Types[i]) {
797      if (Types[i]->getType()->containsUnexpandedParameterPack())
798        ContainsUnexpandedParameterPack = true;
799
800      if (Types[i]->getType()->isDependentType()) {
801        IsResultDependent = true;
802      } else {
803        // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
804        // complete object type other than a variably modified type."
805        unsigned D = 0;
806        if (Types[i]->getType()->isIncompleteType())
807          D = diag::err_assoc_type_incomplete;
808        else if (!Types[i]->getType()->isObjectType())
809          D = diag::err_assoc_type_nonobject;
810        else if (Types[i]->getType()->isVariablyModifiedType())
811          D = diag::err_assoc_type_variably_modified;
812
813        if (D != 0) {
814          Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
815            << Types[i]->getTypeLoc().getSourceRange()
816            << Types[i]->getType();
817          TypeErrorFound = true;
818        }
819
820        // C1X 6.5.1.1p2 "No two generic associations in the same generic
821        // selection shall specify compatible types."
822        for (unsigned j = i+1; j < NumAssocs; ++j)
823          if (Types[j] && !Types[j]->getType()->isDependentType() &&
824              Context.typesAreCompatible(Types[i]->getType(),
825                                         Types[j]->getType())) {
826            Diag(Types[j]->getTypeLoc().getBeginLoc(),
827                 diag::err_assoc_compatible_types)
828              << Types[j]->getTypeLoc().getSourceRange()
829              << Types[j]->getType()
830              << Types[i]->getType();
831            Diag(Types[i]->getTypeLoc().getBeginLoc(),
832                 diag::note_compat_assoc)
833              << Types[i]->getTypeLoc().getSourceRange()
834              << Types[i]->getType();
835            TypeErrorFound = true;
836          }
837      }
838    }
839  }
840  if (TypeErrorFound)
841    return ExprError();
842
843  // If we determined that the generic selection is result-dependent, don't
844  // try to compute the result expression.
845  if (IsResultDependent)
846    return Owned(new (Context) GenericSelectionExpr(
847                   Context, KeyLoc, ControllingExpr,
848                   Types, Exprs, NumAssocs, DefaultLoc,
849                   RParenLoc, ContainsUnexpandedParameterPack));
850
851  llvm::SmallVector<unsigned, 1> CompatIndices;
852  unsigned DefaultIndex = -1U;
853  for (unsigned i = 0; i < NumAssocs; ++i) {
854    if (!Types[i])
855      DefaultIndex = i;
856    else if (Context.typesAreCompatible(ControllingExpr->getType(),
857                                        Types[i]->getType()))
858      CompatIndices.push_back(i);
859  }
860
861  // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
862  // type compatible with at most one of the types named in its generic
863  // association list."
864  if (CompatIndices.size() > 1) {
865    // We strip parens here because the controlling expression is typically
866    // parenthesized in macro definitions.
867    ControllingExpr = ControllingExpr->IgnoreParens();
868    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
869      << ControllingExpr->getSourceRange() << ControllingExpr->getType()
870      << (unsigned) CompatIndices.size();
871    for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
872         E = CompatIndices.end(); I != E; ++I) {
873      Diag(Types[*I]->getTypeLoc().getBeginLoc(),
874           diag::note_compat_assoc)
875        << Types[*I]->getTypeLoc().getSourceRange()
876        << Types[*I]->getType();
877    }
878    return ExprError();
879  }
880
881  // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
882  // its controlling expression shall have type compatible with exactly one of
883  // the types named in its generic association list."
884  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
885    // We strip parens here because the controlling expression is typically
886    // parenthesized in macro definitions.
887    ControllingExpr = ControllingExpr->IgnoreParens();
888    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
889      << ControllingExpr->getSourceRange() << ControllingExpr->getType();
890    return ExprError();
891  }
892
893  // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
894  // type name that is compatible with the type of the controlling expression,
895  // then the result expression of the generic selection is the expression
896  // in that generic association. Otherwise, the result expression of the
897  // generic selection is the expression in the default generic association."
898  unsigned ResultIndex =
899    CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
900
901  return Owned(new (Context) GenericSelectionExpr(
902                 Context, KeyLoc, ControllingExpr,
903                 Types, Exprs, NumAssocs, DefaultLoc,
904                 RParenLoc, ContainsUnexpandedParameterPack,
905                 ResultIndex));
906}
907
908/// ActOnStringLiteral - The specified tokens were lexed as pasted string
909/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
910/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
911/// multiple tokens.  However, the common case is that StringToks points to one
912/// string.
913///
914ExprResult
915Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
916  assert(NumStringToks && "Must have at least one string!");
917
918  StringLiteralParser Literal(StringToks, NumStringToks, PP);
919  if (Literal.hadError)
920    return ExprError();
921
922  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
923  for (unsigned i = 0; i != NumStringToks; ++i)
924    StringTokLocs.push_back(StringToks[i].getLocation());
925
926  QualType StrTy = Context.CharTy;
927  if (Literal.AnyWide)
928    StrTy = Context.getWCharType();
929  else if (Literal.Pascal)
930    StrTy = Context.UnsignedCharTy;
931
932  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
933  if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
934    StrTy.addConst();
935
936  // Get an array type for the string, according to C99 6.4.5.  This includes
937  // the nul terminator character as well as the string length for pascal
938  // strings.
939  StrTy = Context.getConstantArrayType(StrTy,
940                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
941                                       ArrayType::Normal, 0);
942
943  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
944  return Owned(StringLiteral::Create(Context, Literal.GetString(),
945                                     Literal.GetStringLength(),
946                                     Literal.AnyWide, Literal.Pascal, StrTy,
947                                     &StringTokLocs[0],
948                                     StringTokLocs.size()));
949}
950
951enum CaptureResult {
952  /// No capture is required.
953  CR_NoCapture,
954
955  /// A capture is required.
956  CR_Capture,
957
958  /// A by-ref capture is required.
959  CR_CaptureByRef,
960
961  /// An error occurred when trying to capture the given variable.
962  CR_Error
963};
964
965/// Diagnose an uncapturable value reference.
966///
967/// \param var - the variable referenced
968/// \param DC - the context which we couldn't capture through
969static CaptureResult
970diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
971                                   VarDecl *var, DeclContext *DC) {
972  switch (S.ExprEvalContexts.back().Context) {
973  case Sema::Unevaluated:
974    // The argument will never be evaluated, so don't complain.
975    return CR_NoCapture;
976
977  case Sema::PotentiallyEvaluated:
978  case Sema::PotentiallyEvaluatedIfUsed:
979    break;
980
981  case Sema::PotentiallyPotentiallyEvaluated:
982    // FIXME: delay these!
983    break;
984  }
985
986  // Don't diagnose about capture if we're not actually in code right
987  // now; in general, there are more appropriate places that will
988  // diagnose this.
989  if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
990
991  // Certain madnesses can happen with parameter declarations, which
992  // we want to ignore.
993  if (isa<ParmVarDecl>(var)) {
994    // - If the parameter still belongs to the translation unit, then
995    //   we're actually just using one parameter in the declaration of
996    //   the next.  This is useful in e.g. VLAs.
997    if (isa<TranslationUnitDecl>(var->getDeclContext()))
998      return CR_NoCapture;
999
1000    // - This particular madness can happen in ill-formed default
1001    //   arguments; claim it's okay and let downstream code handle it.
1002    if (S.CurContext == var->getDeclContext()->getParent())
1003      return CR_NoCapture;
1004  }
1005
1006  DeclarationName functionName;
1007  if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1008    functionName = fn->getDeclName();
1009  // FIXME: variable from enclosing block that we couldn't capture from!
1010
1011  S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1012    << var->getIdentifier() << functionName;
1013  S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1014    << var->getIdentifier();
1015
1016  return CR_Error;
1017}
1018
1019/// There is a well-formed capture at a particular scope level;
1020/// propagate it through all the nested blocks.
1021static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1022                                      const BlockDecl::Capture &capture) {
1023  VarDecl *var = capture.getVariable();
1024
1025  // Update all the inner blocks with the capture information.
1026  for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1027         i != e; ++i) {
1028    BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1029    innerBlock->Captures.push_back(
1030      BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1031                         /*nested*/ true, capture.getCopyExpr()));
1032    innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1033  }
1034
1035  return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1036}
1037
1038/// shouldCaptureValueReference - Determine if a reference to the
1039/// given value in the current context requires a variable capture.
1040///
1041/// This also keeps the captures set in the BlockScopeInfo records
1042/// up-to-date.
1043static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
1044                                                 ValueDecl *value) {
1045  // Only variables ever require capture.
1046  VarDecl *var = dyn_cast<VarDecl>(value);
1047  if (!var) return CR_NoCapture;
1048
1049  // Fast path: variables from the current context never require capture.
1050  DeclContext *DC = S.CurContext;
1051  if (var->getDeclContext() == DC) return CR_NoCapture;
1052
1053  // Only variables with local storage require capture.
1054  // FIXME: What about 'const' variables in C++?
1055  if (!var->hasLocalStorage()) return CR_NoCapture;
1056
1057  // Otherwise, we need to capture.
1058
1059  unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
1060  do {
1061    // Only blocks (and eventually C++0x closures) can capture; other
1062    // scopes don't work.
1063    if (!isa<BlockDecl>(DC))
1064      return diagnoseUncapturableValueReference(S, loc, var, DC);
1065
1066    BlockScopeInfo *blockScope =
1067      cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1068    assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1069
1070    // Check whether we've already captured it in this block.  If so,
1071    // we're done.
1072    if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1073      return propagateCapture(S, functionScopesIndex,
1074                              blockScope->Captures[indexPlus1 - 1]);
1075
1076    functionScopesIndex--;
1077    DC = cast<BlockDecl>(DC)->getDeclContext();
1078  } while (var->getDeclContext() != DC);
1079
1080  // Okay, we descended all the way to the block that defines the variable.
1081  // Actually try to capture it.
1082  QualType type = var->getType();
1083
1084  // Prohibit variably-modified types.
1085  if (type->isVariablyModifiedType()) {
1086    S.Diag(loc, diag::err_ref_vm_type);
1087    S.Diag(var->getLocation(), diag::note_declared_at);
1088    return CR_Error;
1089  }
1090
1091  // Prohibit arrays, even in __block variables, but not references to
1092  // them.
1093  if (type->isArrayType()) {
1094    S.Diag(loc, diag::err_ref_array_type);
1095    S.Diag(var->getLocation(), diag::note_declared_at);
1096    return CR_Error;
1097  }
1098
1099  S.MarkDeclarationReferenced(loc, var);
1100
1101  // The BlocksAttr indicates the variable is bound by-reference.
1102  bool byRef = var->hasAttr<BlocksAttr>();
1103
1104  // Build a copy expression.
1105  Expr *copyExpr = 0;
1106  if (!byRef && S.getLangOptions().CPlusPlus &&
1107      !type->isDependentType() && type->isStructureOrClassType()) {
1108    // According to the blocks spec, the capture of a variable from
1109    // the stack requires a const copy constructor.  This is not true
1110    // of the copy/move done to move a __block variable to the heap.
1111    type.addConst();
1112
1113    Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1114    ExprResult result =
1115      S.PerformCopyInitialization(
1116                      InitializedEntity::InitializeBlock(var->getLocation(),
1117                                                         type, false),
1118                                  loc, S.Owned(declRef));
1119
1120    // Build a full-expression copy expression if initialization
1121    // succeeded and used a non-trivial constructor.  Recover from
1122    // errors by pretending that the copy isn't necessary.
1123    if (!result.isInvalid() &&
1124        !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1125      result = S.MaybeCreateExprWithCleanups(result);
1126      copyExpr = result.take();
1127    }
1128  }
1129
1130  // We're currently at the declarer; go back to the closure.
1131  functionScopesIndex++;
1132  BlockScopeInfo *blockScope =
1133    cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1134
1135  // Build a valid capture in this scope.
1136  blockScope->Captures.push_back(
1137                 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1138  blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1139
1140  // Propagate that to inner captures if necessary.
1141  return propagateCapture(S, functionScopesIndex,
1142                          blockScope->Captures.back());
1143}
1144
1145static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1146                                        const DeclarationNameInfo &NameInfo,
1147                                        bool byRef) {
1148  assert(isa<VarDecl>(vd) && "capturing non-variable");
1149
1150  VarDecl *var = cast<VarDecl>(vd);
1151  assert(var->hasLocalStorage() && "capturing non-local");
1152  assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1153
1154  QualType exprType = var->getType().getNonReferenceType();
1155
1156  BlockDeclRefExpr *BDRE;
1157  if (!byRef) {
1158    // The variable will be bound by copy; make it const within the
1159    // closure, but record that this was done in the expression.
1160    bool constAdded = !exprType.isConstQualified();
1161    exprType.addConst();
1162
1163    BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1164                                            NameInfo.getLoc(), false,
1165                                            constAdded);
1166  } else {
1167    BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1168                                            NameInfo.getLoc(), true);
1169  }
1170
1171  return S.Owned(BDRE);
1172}
1173
1174ExprResult
1175Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1176                       SourceLocation Loc,
1177                       const CXXScopeSpec *SS) {
1178  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1179  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1180}
1181
1182/// BuildDeclRefExpr - Build an expression that references a
1183/// declaration that does not require a closure capture.
1184ExprResult
1185Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1186                       const DeclarationNameInfo &NameInfo,
1187                       const CXXScopeSpec *SS) {
1188  MarkDeclarationReferenced(NameInfo.getLoc(), D);
1189
1190  Expr *E = DeclRefExpr::Create(Context,
1191                                SS? SS->getWithLocInContext(Context)
1192                                  : NestedNameSpecifierLoc(),
1193                                D, NameInfo, Ty, VK);
1194
1195  // Just in case we're building an illegal pointer-to-member.
1196  if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1197    E->setObjectKind(OK_BitField);
1198
1199  return Owned(E);
1200}
1201
1202static ExprResult
1203BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1204                        const CXXScopeSpec &SS, FieldDecl *Field,
1205                        DeclAccessPair FoundDecl,
1206                        const DeclarationNameInfo &MemberNameInfo);
1207
1208ExprResult
1209Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1210                                               SourceLocation loc,
1211                                               IndirectFieldDecl *indirectField,
1212                                               Expr *baseObjectExpr,
1213                                               SourceLocation opLoc) {
1214  // First, build the expression that refers to the base object.
1215
1216  bool baseObjectIsPointer = false;
1217  Qualifiers baseQuals;
1218
1219  // Case 1:  the base of the indirect field is not a field.
1220  VarDecl *baseVariable = indirectField->getVarDecl();
1221  CXXScopeSpec EmptySS;
1222  if (baseVariable) {
1223    assert(baseVariable->getType()->isRecordType());
1224
1225    // In principle we could have a member access expression that
1226    // accesses an anonymous struct/union that's a static member of
1227    // the base object's class.  However, under the current standard,
1228    // static data members cannot be anonymous structs or unions.
1229    // Supporting this is as easy as building a MemberExpr here.
1230    assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1231
1232    DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1233
1234    ExprResult result =
1235      BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
1236    if (result.isInvalid()) return ExprError();
1237
1238    baseObjectExpr = result.take();
1239    baseObjectIsPointer = false;
1240    baseQuals = baseObjectExpr->getType().getQualifiers();
1241
1242  // Case 2: the base of the indirect field is a field and the user
1243  // wrote a member expression.
1244  } else if (baseObjectExpr) {
1245    // The caller provided the base object expression. Determine
1246    // whether its a pointer and whether it adds any qualifiers to the
1247    // anonymous struct/union fields we're looking into.
1248    QualType objectType = baseObjectExpr->getType();
1249
1250    if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1251      baseObjectIsPointer = true;
1252      objectType = ptr->getPointeeType();
1253    } else {
1254      baseObjectIsPointer = false;
1255    }
1256    baseQuals = objectType.getQualifiers();
1257
1258  // Case 3: the base of the indirect field is a field and we should
1259  // build an implicit member access.
1260  } else {
1261    // We've found a member of an anonymous struct/union that is
1262    // inside a non-anonymous struct/union, so in a well-formed
1263    // program our base object expression is "this".
1264    CXXMethodDecl *method = tryCaptureCXXThis();
1265    if (!method) {
1266      Diag(loc, diag::err_invalid_member_use_in_static_method)
1267        << indirectField->getDeclName();
1268      return ExprError();
1269    }
1270
1271    // Our base object expression is "this".
1272    baseObjectExpr =
1273      new (Context) CXXThisExpr(loc, method->getThisType(Context),
1274                                /*isImplicit=*/ true);
1275    baseObjectIsPointer = true;
1276    baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
1277  }
1278
1279  // Build the implicit member references to the field of the
1280  // anonymous struct/union.
1281  Expr *result = baseObjectExpr;
1282  IndirectFieldDecl::chain_iterator
1283    FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
1284
1285  // Build the first member access in the chain with full information.
1286  if (!baseVariable) {
1287    FieldDecl *field = cast<FieldDecl>(*FI);
1288
1289    // FIXME: use the real found-decl info!
1290    DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1291
1292    // Make a nameInfo that properly uses the anonymous name.
1293    DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1294
1295    result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
1296                                     EmptySS, field, foundDecl,
1297                                     memberNameInfo).take();
1298    baseObjectIsPointer = false;
1299
1300    // FIXME: check qualified member access
1301  }
1302
1303  // In all cases, we should now skip the first declaration in the chain.
1304  ++FI;
1305
1306  while (FI != FEnd) {
1307    FieldDecl *field = cast<FieldDecl>(*FI++);
1308
1309    // FIXME: these are somewhat meaningless
1310    DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1311    DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1312
1313    result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
1314                                     (FI == FEnd? SS : EmptySS), field,
1315                                     foundDecl, memberNameInfo)
1316      .take();
1317  }
1318
1319  return Owned(result);
1320}
1321
1322/// Decomposes the given name into a DeclarationNameInfo, its location, and
1323/// possibly a list of template arguments.
1324///
1325/// If this produces template arguments, it is permitted to call
1326/// DecomposeTemplateName.
1327///
1328/// This actually loses a lot of source location information for
1329/// non-standard name kinds; we should consider preserving that in
1330/// some way.
1331static void DecomposeUnqualifiedId(Sema &SemaRef,
1332                                   const UnqualifiedId &Id,
1333                                   TemplateArgumentListInfo &Buffer,
1334                                   DeclarationNameInfo &NameInfo,
1335                             const TemplateArgumentListInfo *&TemplateArgs) {
1336  if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1337    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1338    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1339
1340    ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1341                                       Id.TemplateId->getTemplateArgs(),
1342                                       Id.TemplateId->NumArgs);
1343    SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1344    TemplateArgsPtr.release();
1345
1346    TemplateName TName = Id.TemplateId->Template.get();
1347    SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1348    NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
1349    TemplateArgs = &Buffer;
1350  } else {
1351    NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
1352    TemplateArgs = 0;
1353  }
1354}
1355
1356/// Determines if the given class is provably not derived from all of
1357/// the prospective base classes.
1358static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1359                                     CXXRecordDecl *Record,
1360                            const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
1361  if (Bases.count(Record->getCanonicalDecl()))
1362    return false;
1363
1364  RecordDecl *RD = Record->getDefinition();
1365  if (!RD) return false;
1366  Record = cast<CXXRecordDecl>(RD);
1367
1368  for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1369         E = Record->bases_end(); I != E; ++I) {
1370    CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1371    CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1372    if (!BaseRT) return false;
1373
1374    CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
1375    if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1376      return false;
1377  }
1378
1379  return true;
1380}
1381
1382enum IMAKind {
1383  /// The reference is definitely not an instance member access.
1384  IMA_Static,
1385
1386  /// The reference may be an implicit instance member access.
1387  IMA_Mixed,
1388
1389  /// The reference may be to an instance member, but it is invalid if
1390  /// so, because the context is not an instance method.
1391  IMA_Mixed_StaticContext,
1392
1393  /// The reference may be to an instance member, but it is invalid if
1394  /// so, because the context is from an unrelated class.
1395  IMA_Mixed_Unrelated,
1396
1397  /// The reference is definitely an implicit instance member access.
1398  IMA_Instance,
1399
1400  /// The reference may be to an unresolved using declaration.
1401  IMA_Unresolved,
1402
1403  /// The reference may be to an unresolved using declaration and the
1404  /// context is not an instance method.
1405  IMA_Unresolved_StaticContext,
1406
1407  /// All possible referrents are instance members and the current
1408  /// context is not an instance method.
1409  IMA_Error_StaticContext,
1410
1411  /// All possible referrents are instance members of an unrelated
1412  /// class.
1413  IMA_Error_Unrelated
1414};
1415
1416/// The given lookup names class member(s) and is not being used for
1417/// an address-of-member expression.  Classify the type of access
1418/// according to whether it's possible that this reference names an
1419/// instance member.  This is best-effort; it is okay to
1420/// conservatively answer "yes", in which case some errors will simply
1421/// not be caught until template-instantiation.
1422static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1423                                            const LookupResult &R) {
1424  assert(!R.empty() && (*R.begin())->isCXXClassMember());
1425
1426  DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
1427  bool isStaticContext =
1428    (!isa<CXXMethodDecl>(DC) ||
1429     cast<CXXMethodDecl>(DC)->isStatic());
1430
1431  if (R.isUnresolvableResult())
1432    return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1433
1434  // Collect all the declaring classes of instance members we find.
1435  bool hasNonInstance = false;
1436  bool hasField = false;
1437  llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1438  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1439    NamedDecl *D = *I;
1440
1441    if (D->isCXXInstanceMember()) {
1442      if (dyn_cast<FieldDecl>(D))
1443        hasField = true;
1444
1445      CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
1446      Classes.insert(R->getCanonicalDecl());
1447    }
1448    else
1449      hasNonInstance = true;
1450  }
1451
1452  // If we didn't find any instance members, it can't be an implicit
1453  // member reference.
1454  if (Classes.empty())
1455    return IMA_Static;
1456
1457  // If the current context is not an instance method, it can't be
1458  // an implicit member reference.
1459  if (isStaticContext) {
1460    if (hasNonInstance)
1461        return IMA_Mixed_StaticContext;
1462
1463    if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1464      // C++0x [expr.prim.general]p10:
1465      //   An id-expression that denotes a non-static data member or non-static
1466      //   member function of a class can only be used:
1467      //   (...)
1468      //   - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1469      const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1470      bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1471      if (isUnevaluatedExpression)
1472        return IMA_Mixed_StaticContext;
1473    }
1474
1475    return IMA_Error_StaticContext;
1476  }
1477
1478  CXXRecordDecl *
1479        contextClass = cast<CXXMethodDecl>(DC)->getParent()->getCanonicalDecl();
1480
1481  // [class.mfct.non-static]p3:
1482  // ...is used in the body of a non-static member function of class X,
1483  // if name lookup (3.4.1) resolves the name in the id-expression to a
1484  // non-static non-type member of some class C [...]
1485  // ...if C is not X or a base class of X, the class member access expression
1486  // is ill-formed.
1487  if (R.getNamingClass() &&
1488      contextClass != R.getNamingClass()->getCanonicalDecl() &&
1489      contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1490    return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1491
1492  // If we can prove that the current context is unrelated to all the
1493  // declaring classes, it can't be an implicit member reference (in
1494  // which case it's an error if any of those members are selected).
1495  if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
1496    return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1497
1498  return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1499}
1500
1501/// Diagnose a reference to a field with no object available.
1502static void DiagnoseInstanceReference(Sema &SemaRef,
1503                                      const CXXScopeSpec &SS,
1504                                      NamedDecl *rep,
1505                                      const DeclarationNameInfo &nameInfo) {
1506  SourceLocation Loc = nameInfo.getLoc();
1507  SourceRange Range(Loc);
1508  if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1509
1510  if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
1511    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1512      if (MD->isStatic()) {
1513        // "invalid use of member 'x' in static member function"
1514        SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1515          << Range << nameInfo.getName();
1516        return;
1517      }
1518    }
1519
1520    SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1521      << nameInfo.getName() << Range;
1522    return;
1523  }
1524
1525  SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
1526}
1527
1528/// Diagnose an empty lookup.
1529///
1530/// \return false if new lookup candidates were found
1531bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1532                               CorrectTypoContext CTC) {
1533  DeclarationName Name = R.getLookupName();
1534
1535  unsigned diagnostic = diag::err_undeclared_var_use;
1536  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1537  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1538      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1539      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1540    diagnostic = diag::err_undeclared_use;
1541    diagnostic_suggest = diag::err_undeclared_use_suggest;
1542  }
1543
1544  // If the original lookup was an unqualified lookup, fake an
1545  // unqualified lookup.  This is useful when (for example) the
1546  // original lookup would not have found something because it was a
1547  // dependent name.
1548  for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1549       DC; DC = DC->getParent()) {
1550    if (isa<CXXRecordDecl>(DC)) {
1551      LookupQualifiedName(R, DC);
1552
1553      if (!R.empty()) {
1554        // Don't give errors about ambiguities in this lookup.
1555        R.suppressDiagnostics();
1556
1557        CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1558        bool isInstance = CurMethod &&
1559                          CurMethod->isInstance() &&
1560                          DC == CurMethod->getParent();
1561
1562        // Give a code modification hint to insert 'this->'.
1563        // TODO: fixit for inserting 'Base<T>::' in the other cases.
1564        // Actually quite difficult!
1565        if (isInstance) {
1566          UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1567              CallsUndergoingInstantiation.back()->getCallee());
1568          CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
1569              CurMethod->getInstantiatedFromMemberFunction());
1570          if (DepMethod) {
1571            Diag(R.getNameLoc(), diagnostic) << Name
1572              << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1573            QualType DepThisType = DepMethod->getThisType(Context);
1574            CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1575                                       R.getNameLoc(), DepThisType, false);
1576            TemplateArgumentListInfo TList;
1577            if (ULE->hasExplicitTemplateArgs())
1578              ULE->copyTemplateArgumentsInto(TList);
1579
1580            CXXScopeSpec SS;
1581            SS.Adopt(ULE->getQualifierLoc());
1582            CXXDependentScopeMemberExpr *DepExpr =
1583                CXXDependentScopeMemberExpr::Create(
1584                    Context, DepThis, DepThisType, true, SourceLocation(),
1585                    SS.getWithLocInContext(Context), NULL,
1586                    R.getLookupNameInfo(), &TList);
1587            CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1588          } else {
1589            // FIXME: we should be able to handle this case too. It is correct
1590            // to add this-> here. This is a workaround for PR7947.
1591            Diag(R.getNameLoc(), diagnostic) << Name;
1592          }
1593        } else {
1594          Diag(R.getNameLoc(), diagnostic) << Name;
1595        }
1596
1597        // Do we really want to note all of these?
1598        for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1599          Diag((*I)->getLocation(), diag::note_dependent_var_use);
1600
1601        // Tell the callee to try to recover.
1602        return false;
1603      }
1604
1605      R.clear();
1606    }
1607  }
1608
1609  // We didn't find anything, so try to correct for a typo.
1610  DeclarationName Corrected;
1611  if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
1612    if (!R.empty()) {
1613      if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1614        if (SS.isEmpty())
1615          Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1616            << FixItHint::CreateReplacement(R.getNameLoc(),
1617                                            R.getLookupName().getAsString());
1618        else
1619          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1620            << Name << computeDeclContext(SS, false) << R.getLookupName()
1621            << SS.getRange()
1622            << FixItHint::CreateReplacement(R.getNameLoc(),
1623                                            R.getLookupName().getAsString());
1624        if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1625          Diag(ND->getLocation(), diag::note_previous_decl)
1626            << ND->getDeclName();
1627
1628        // Tell the callee to try to recover.
1629        return false;
1630      }
1631
1632      if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1633        // FIXME: If we ended up with a typo for a type name or
1634        // Objective-C class name, we're in trouble because the parser
1635        // is in the wrong place to recover. Suggest the typo
1636        // correction, but don't make it a fix-it since we're not going
1637        // to recover well anyway.
1638        if (SS.isEmpty())
1639          Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1640        else
1641          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1642            << Name << computeDeclContext(SS, false) << R.getLookupName()
1643            << SS.getRange();
1644
1645        // Don't try to recover; it won't work.
1646        return true;
1647      }
1648    } else {
1649      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1650      // because we aren't able to recover.
1651      if (SS.isEmpty())
1652        Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
1653      else
1654        Diag(R.getNameLoc(), diag::err_no_member_suggest)
1655        << Name << computeDeclContext(SS, false) << Corrected
1656        << SS.getRange();
1657      return true;
1658    }
1659    R.clear();
1660  }
1661
1662  // Emit a special diagnostic for failed member lookups.
1663  // FIXME: computing the declaration context might fail here (?)
1664  if (!SS.isEmpty()) {
1665    Diag(R.getNameLoc(), diag::err_no_member)
1666      << Name << computeDeclContext(SS, false)
1667      << SS.getRange();
1668    return true;
1669  }
1670
1671  // Give up, we can't recover.
1672  Diag(R.getNameLoc(), diagnostic) << Name;
1673  return true;
1674}
1675
1676ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1677  ObjCMethodDecl *CurMeth = getCurMethodDecl();
1678  ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1679  if (!IDecl)
1680    return 0;
1681  ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1682  if (!ClassImpDecl)
1683    return 0;
1684  ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
1685  if (!property)
1686    return 0;
1687  if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1688    if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1689        PIDecl->getPropertyIvarDecl())
1690      return 0;
1691  return property;
1692}
1693
1694bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1695  ObjCMethodDecl *CurMeth = getCurMethodDecl();
1696  ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1697  if (!IDecl)
1698    return false;
1699  ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1700  if (!ClassImpDecl)
1701    return false;
1702  if (ObjCPropertyImplDecl *PIDecl
1703                = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1704    if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1705        PIDecl->getPropertyIvarDecl())
1706      return false;
1707
1708  return true;
1709}
1710
1711static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
1712                                               LookupResult &Lookup,
1713                                               IdentifierInfo *II,
1714                                               SourceLocation NameLoc) {
1715  ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1716  bool LookForIvars;
1717  if (Lookup.empty())
1718    LookForIvars = true;
1719  else if (CurMeth->isClassMethod())
1720    LookForIvars = false;
1721  else
1722    LookForIvars = (Lookup.isSingleResult() &&
1723                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1724                    (Lookup.getAsSingle<VarDecl>() != 0));
1725  if (!LookForIvars)
1726    return 0;
1727
1728  ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1729  if (!IDecl)
1730    return 0;
1731  ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1732  if (!ClassImpDecl)
1733    return 0;
1734  bool DynamicImplSeen = false;
1735  ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1736  if (!property)
1737    return 0;
1738  if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
1739    DynamicImplSeen =
1740      (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1741    // property implementation has a designated ivar. No need to assume a new
1742    // one.
1743    if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1744      return 0;
1745  }
1746  if (!DynamicImplSeen) {
1747    QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1748    ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
1749                                              NameLoc, NameLoc,
1750                                              II, PropType, /*Dinfo=*/0,
1751                                              ObjCIvarDecl::Private,
1752                                              (Expr *)0, true);
1753    ClassImpDecl->addDecl(Ivar);
1754    IDecl->makeDeclVisibleInContext(Ivar, false);
1755    property->setPropertyIvarDecl(Ivar);
1756    return Ivar;
1757  }
1758  return 0;
1759}
1760
1761ExprResult Sema::ActOnIdExpression(Scope *S,
1762                                   CXXScopeSpec &SS,
1763                                   UnqualifiedId &Id,
1764                                   bool HasTrailingLParen,
1765                                   bool isAddressOfOperand) {
1766  assert(!(isAddressOfOperand && HasTrailingLParen) &&
1767         "cannot be direct & operand and have a trailing lparen");
1768
1769  if (SS.isInvalid())
1770    return ExprError();
1771
1772  TemplateArgumentListInfo TemplateArgsBuffer;
1773
1774  // Decompose the UnqualifiedId into the following data.
1775  DeclarationNameInfo NameInfo;
1776  const TemplateArgumentListInfo *TemplateArgs;
1777  DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1778
1779  DeclarationName Name = NameInfo.getName();
1780  IdentifierInfo *II = Name.getAsIdentifierInfo();
1781  SourceLocation NameLoc = NameInfo.getLoc();
1782
1783  // C++ [temp.dep.expr]p3:
1784  //   An id-expression is type-dependent if it contains:
1785  //     -- an identifier that was declared with a dependent type,
1786  //        (note: handled after lookup)
1787  //     -- a template-id that is dependent,
1788  //        (note: handled in BuildTemplateIdExpr)
1789  //     -- a conversion-function-id that specifies a dependent type,
1790  //     -- a nested-name-specifier that contains a class-name that
1791  //        names a dependent type.
1792  // Determine whether this is a member of an unknown specialization;
1793  // we need to handle these differently.
1794  bool DependentID = false;
1795  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1796      Name.getCXXNameType()->isDependentType()) {
1797    DependentID = true;
1798  } else if (SS.isSet()) {
1799    if (DeclContext *DC = computeDeclContext(SS, false)) {
1800      if (RequireCompleteDeclContext(SS, DC))
1801        return ExprError();
1802    } else {
1803      DependentID = true;
1804    }
1805  }
1806
1807  if (DependentID)
1808    return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1809                                      TemplateArgs);
1810
1811  bool IvarLookupFollowUp = false;
1812  // Perform the required lookup.
1813  LookupResult R(*this, NameInfo, LookupOrdinaryName);
1814  if (TemplateArgs) {
1815    // Lookup the template name again to correctly establish the context in
1816    // which it was found. This is really unfortunate as we already did the
1817    // lookup to determine that it was a template name in the first place. If
1818    // this becomes a performance hit, we can work harder to preserve those
1819    // results until we get here but it's likely not worth it.
1820    bool MemberOfUnknownSpecialization;
1821    LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1822                       MemberOfUnknownSpecialization);
1823
1824    if (MemberOfUnknownSpecialization ||
1825        (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1826      return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1827                                        TemplateArgs);
1828  } else {
1829    IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1830    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1831
1832    // If the result might be in a dependent base class, this is a dependent
1833    // id-expression.
1834    if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1835      return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1836                                        TemplateArgs);
1837
1838    // If this reference is in an Objective-C method, then we need to do
1839    // some special Objective-C lookup, too.
1840    if (IvarLookupFollowUp) {
1841      ExprResult E(LookupInObjCMethod(R, S, II, true));
1842      if (E.isInvalid())
1843        return ExprError();
1844
1845      if (Expr *Ex = E.takeAs<Expr>())
1846        return Owned(Ex);
1847
1848      // Synthesize ivars lazily.
1849      if (getLangOptions().ObjCDefaultSynthProperties &&
1850          getLangOptions().ObjCNonFragileABI2) {
1851        if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1852          if (const ObjCPropertyDecl *Property =
1853                canSynthesizeProvisionalIvar(II)) {
1854            Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1855            Diag(Property->getLocation(), diag::note_property_declare);
1856          }
1857          return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1858                                   isAddressOfOperand);
1859        }
1860      }
1861      // for further use, this must be set to false if in class method.
1862      IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
1863    }
1864  }
1865
1866  if (R.isAmbiguous())
1867    return ExprError();
1868
1869  // Determine whether this name might be a candidate for
1870  // argument-dependent lookup.
1871  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1872
1873  if (R.empty() && !ADL) {
1874    // Otherwise, this could be an implicitly declared function reference (legal
1875    // in C90, extension in C99, forbidden in C++).
1876    if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1877      NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1878      if (D) R.addDecl(D);
1879    }
1880
1881    // If this name wasn't predeclared and if this is not a function
1882    // call, diagnose the problem.
1883    if (R.empty()) {
1884      if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1885        return ExprError();
1886
1887      assert(!R.empty() &&
1888             "DiagnoseEmptyLookup returned false but added no results");
1889
1890      // If we found an Objective-C instance variable, let
1891      // LookupInObjCMethod build the appropriate expression to
1892      // reference the ivar.
1893      if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1894        R.clear();
1895        ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1896        assert(E.isInvalid() || E.get());
1897        return move(E);
1898      }
1899    }
1900  }
1901
1902  // This is guaranteed from this point on.
1903  assert(!R.empty() || ADL);
1904
1905  // Check whether this might be a C++ implicit instance member access.
1906  // C++ [class.mfct.non-static]p3:
1907  //   When an id-expression that is not part of a class member access
1908  //   syntax and not used to form a pointer to member is used in the
1909  //   body of a non-static member function of class X, if name lookup
1910  //   resolves the name in the id-expression to a non-static non-type
1911  //   member of some class C, the id-expression is transformed into a
1912  //   class member access expression using (*this) as the
1913  //   postfix-expression to the left of the . operator.
1914  //
1915  // But we don't actually need to do this for '&' operands if R
1916  // resolved to a function or overloaded function set, because the
1917  // expression is ill-formed if it actually works out to be a
1918  // non-static member function:
1919  //
1920  // C++ [expr.ref]p4:
1921  //   Otherwise, if E1.E2 refers to a non-static member function. . .
1922  //   [t]he expression can be used only as the left-hand operand of a
1923  //   member function call.
1924  //
1925  // There are other safeguards against such uses, but it's important
1926  // to get this right here so that we don't end up making a
1927  // spuriously dependent expression if we're inside a dependent
1928  // instance method.
1929  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1930    bool MightBeImplicitMember;
1931    if (!isAddressOfOperand)
1932      MightBeImplicitMember = true;
1933    else if (!SS.isEmpty())
1934      MightBeImplicitMember = false;
1935    else if (R.isOverloadedResult())
1936      MightBeImplicitMember = false;
1937    else if (R.isUnresolvableResult())
1938      MightBeImplicitMember = true;
1939    else
1940      MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1941                              isa<IndirectFieldDecl>(R.getFoundDecl());
1942
1943    if (MightBeImplicitMember)
1944      return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1945  }
1946
1947  if (TemplateArgs)
1948    return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1949
1950  return BuildDeclarationNameExpr(SS, R, ADL);
1951}
1952
1953/// Builds an expression which might be an implicit member expression.
1954ExprResult
1955Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1956                                      LookupResult &R,
1957                                const TemplateArgumentListInfo *TemplateArgs) {
1958  switch (ClassifyImplicitMemberAccess(*this, R)) {
1959  case IMA_Instance:
1960    return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1961
1962  case IMA_Mixed:
1963  case IMA_Mixed_Unrelated:
1964  case IMA_Unresolved:
1965    return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1966
1967  case IMA_Static:
1968  case IMA_Mixed_StaticContext:
1969  case IMA_Unresolved_StaticContext:
1970    if (TemplateArgs)
1971      return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1972    return BuildDeclarationNameExpr(SS, R, false);
1973
1974  case IMA_Error_StaticContext:
1975  case IMA_Error_Unrelated:
1976    DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1977                              R.getLookupNameInfo());
1978    return ExprError();
1979  }
1980
1981  llvm_unreachable("unexpected instance member access kind");
1982  return ExprError();
1983}
1984
1985/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1986/// declaration name, generally during template instantiation.
1987/// There's a large number of things which don't need to be done along
1988/// this path.
1989ExprResult
1990Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1991                                        const DeclarationNameInfo &NameInfo) {
1992  DeclContext *DC;
1993  if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1994    return BuildDependentDeclRefExpr(SS, NameInfo, 0);
1995
1996  if (RequireCompleteDeclContext(SS, DC))
1997    return ExprError();
1998
1999  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2000  LookupQualifiedName(R, DC);
2001
2002  if (R.isAmbiguous())
2003    return ExprError();
2004
2005  if (R.empty()) {
2006    Diag(NameInfo.getLoc(), diag::err_no_member)
2007      << NameInfo.getName() << DC << SS.getRange();
2008    return ExprError();
2009  }
2010
2011  return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2012}
2013
2014/// LookupInObjCMethod - The parser has read a name in, and Sema has
2015/// detected that we're currently inside an ObjC method.  Perform some
2016/// additional lookup.
2017///
2018/// Ideally, most of this would be done by lookup, but there's
2019/// actually quite a lot of extra work involved.
2020///
2021/// Returns a null sentinel to indicate trivial success.
2022ExprResult
2023Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2024                         IdentifierInfo *II, bool AllowBuiltinCreation) {
2025  SourceLocation Loc = Lookup.getNameLoc();
2026  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2027
2028  // There are two cases to handle here.  1) scoped lookup could have failed,
2029  // in which case we should look for an ivar.  2) scoped lookup could have
2030  // found a decl, but that decl is outside the current instance method (i.e.
2031  // a global variable).  In these two cases, we do a lookup for an ivar with
2032  // this name, if the lookup sucedes, we replace it our current decl.
2033
2034  // If we're in a class method, we don't normally want to look for
2035  // ivars.  But if we don't find anything else, and there's an
2036  // ivar, that's an error.
2037  bool IsClassMethod = CurMethod->isClassMethod();
2038
2039  bool LookForIvars;
2040  if (Lookup.empty())
2041    LookForIvars = true;
2042  else if (IsClassMethod)
2043    LookForIvars = false;
2044  else
2045    LookForIvars = (Lookup.isSingleResult() &&
2046                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2047  ObjCInterfaceDecl *IFace = 0;
2048  if (LookForIvars) {
2049    IFace = CurMethod->getClassInterface();
2050    ObjCInterfaceDecl *ClassDeclared;
2051    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2052      // Diagnose using an ivar in a class method.
2053      if (IsClassMethod)
2054        return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2055                         << IV->getDeclName());
2056
2057      // If we're referencing an invalid decl, just return this as a silent
2058      // error node.  The error diagnostic was already emitted on the decl.
2059      if (IV->isInvalidDecl())
2060        return ExprError();
2061
2062      // Check if referencing a field with __attribute__((deprecated)).
2063      if (DiagnoseUseOfDecl(IV, Loc))
2064        return ExprError();
2065
2066      // Diagnose the use of an ivar outside of the declaring class.
2067      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2068          ClassDeclared != IFace)
2069        Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2070
2071      // FIXME: This should use a new expr for a direct reference, don't
2072      // turn this into Self->ivar, just return a BareIVarExpr or something.
2073      IdentifierInfo &II = Context.Idents.get("self");
2074      UnqualifiedId SelfName;
2075      SelfName.setIdentifier(&II, SourceLocation());
2076      CXXScopeSpec SelfScopeSpec;
2077      ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
2078                                              SelfName, false, false);
2079      if (SelfExpr.isInvalid())
2080        return ExprError();
2081
2082      SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2083      if (SelfExpr.isInvalid())
2084        return ExprError();
2085
2086      MarkDeclarationReferenced(Loc, IV);
2087      Expr *base = SelfExpr.take();
2088      base = base->IgnoreParenImpCasts();
2089      if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2090        const NamedDecl *ND = DE->getDecl();
2091        if (!isa<ImplicitParamDecl>(ND)) {
2092          // relax the rule such that it is allowed to have a shadow 'self'
2093          // where stand-alone ivar can be found in this 'self' object.
2094          // This is to match gcc's behavior.
2095          ObjCInterfaceDecl *selfIFace = 0;
2096          if (const ObjCObjectPointerType *OPT =
2097              base->getType()->getAsObjCInterfacePointerType())
2098            selfIFace = OPT->getInterfaceDecl();
2099          if (!selfIFace ||
2100              !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
2101            Diag(Loc, diag::error_implicit_ivar_access)
2102            << IV->getDeclName();
2103            Diag(ND->getLocation(), diag::note_declared_at);
2104            return ExprError();
2105          }
2106        }
2107      }
2108      return Owned(new (Context)
2109                   ObjCIvarRefExpr(IV, IV->getType(), Loc,
2110                                   SelfExpr.take(), true, true));
2111    }
2112  } else if (CurMethod->isInstanceMethod()) {
2113    // We should warn if a local variable hides an ivar.
2114    ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2115    ObjCInterfaceDecl *ClassDeclared;
2116    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2117      if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2118          IFace == ClassDeclared)
2119        Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2120    }
2121  }
2122
2123  if (Lookup.empty() && II && AllowBuiltinCreation) {
2124    // FIXME. Consolidate this with similar code in LookupName.
2125    if (unsigned BuiltinID = II->getBuiltinID()) {
2126      if (!(getLangOptions().CPlusPlus &&
2127            Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2128        NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2129                                           S, Lookup.isForRedeclaration(),
2130                                           Lookup.getNameLoc());
2131        if (D) Lookup.addDecl(D);
2132      }
2133    }
2134  }
2135  // Sentinel value saying that we didn't do anything special.
2136  return Owned((Expr*) 0);
2137}
2138
2139/// \brief Cast a base object to a member's actual type.
2140///
2141/// Logically this happens in three phases:
2142///
2143/// * First we cast from the base type to the naming class.
2144///   The naming class is the class into which we were looking
2145///   when we found the member;  it's the qualifier type if a
2146///   qualifier was provided, and otherwise it's the base type.
2147///
2148/// * Next we cast from the naming class to the declaring class.
2149///   If the member we found was brought into a class's scope by
2150///   a using declaration, this is that class;  otherwise it's
2151///   the class declaring the member.
2152///
2153/// * Finally we cast from the declaring class to the "true"
2154///   declaring class of the member.  This conversion does not
2155///   obey access control.
2156ExprResult
2157Sema::PerformObjectMemberConversion(Expr *From,
2158                                    NestedNameSpecifier *Qualifier,
2159                                    NamedDecl *FoundDecl,
2160                                    NamedDecl *Member) {
2161  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2162  if (!RD)
2163    return Owned(From);
2164
2165  QualType DestRecordType;
2166  QualType DestType;
2167  QualType FromRecordType;
2168  QualType FromType = From->getType();
2169  bool PointerConversions = false;
2170  if (isa<FieldDecl>(Member)) {
2171    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2172
2173    if (FromType->getAs<PointerType>()) {
2174      DestType = Context.getPointerType(DestRecordType);
2175      FromRecordType = FromType->getPointeeType();
2176      PointerConversions = true;
2177    } else {
2178      DestType = DestRecordType;
2179      FromRecordType = FromType;
2180    }
2181  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2182    if (Method->isStatic())
2183      return Owned(From);
2184
2185    DestType = Method->getThisType(Context);
2186    DestRecordType = DestType->getPointeeType();
2187
2188    if (FromType->getAs<PointerType>()) {
2189      FromRecordType = FromType->getPointeeType();
2190      PointerConversions = true;
2191    } else {
2192      FromRecordType = FromType;
2193      DestType = DestRecordType;
2194    }
2195  } else {
2196    // No conversion necessary.
2197    return Owned(From);
2198  }
2199
2200  if (DestType->isDependentType() || FromType->isDependentType())
2201    return Owned(From);
2202
2203  // If the unqualified types are the same, no conversion is necessary.
2204  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2205    return Owned(From);
2206
2207  SourceRange FromRange = From->getSourceRange();
2208  SourceLocation FromLoc = FromRange.getBegin();
2209
2210  ExprValueKind VK = CastCategory(From);
2211
2212  // C++ [class.member.lookup]p8:
2213  //   [...] Ambiguities can often be resolved by qualifying a name with its
2214  //   class name.
2215  //
2216  // If the member was a qualified name and the qualified referred to a
2217  // specific base subobject type, we'll cast to that intermediate type
2218  // first and then to the object in which the member is declared. That allows
2219  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2220  //
2221  //   class Base { public: int x; };
2222  //   class Derived1 : public Base { };
2223  //   class Derived2 : public Base { };
2224  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2225  //
2226  //   void VeryDerived::f() {
2227  //     x = 17; // error: ambiguous base subobjects
2228  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2229  //   }
2230  if (Qualifier) {
2231    QualType QType = QualType(Qualifier->getAsType(), 0);
2232    assert(!QType.isNull() && "lookup done with dependent qualifier?");
2233    assert(QType->isRecordType() && "lookup done with non-record type");
2234
2235    QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2236
2237    // In C++98, the qualifier type doesn't actually have to be a base
2238    // type of the object type, in which case we just ignore it.
2239    // Otherwise build the appropriate casts.
2240    if (IsDerivedFrom(FromRecordType, QRecordType)) {
2241      CXXCastPath BasePath;
2242      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2243                                       FromLoc, FromRange, &BasePath))
2244        return ExprError();
2245
2246      if (PointerConversions)
2247        QType = Context.getPointerType(QType);
2248      From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2249                               VK, &BasePath).take();
2250
2251      FromType = QType;
2252      FromRecordType = QRecordType;
2253
2254      // If the qualifier type was the same as the destination type,
2255      // we're done.
2256      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2257        return Owned(From);
2258    }
2259  }
2260
2261  bool IgnoreAccess = false;
2262
2263  // If we actually found the member through a using declaration, cast
2264  // down to the using declaration's type.
2265  //
2266  // Pointer equality is fine here because only one declaration of a
2267  // class ever has member declarations.
2268  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2269    assert(isa<UsingShadowDecl>(FoundDecl));
2270    QualType URecordType = Context.getTypeDeclType(
2271                           cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2272
2273    // We only need to do this if the naming-class to declaring-class
2274    // conversion is non-trivial.
2275    if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2276      assert(IsDerivedFrom(FromRecordType, URecordType));
2277      CXXCastPath BasePath;
2278      if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2279                                       FromLoc, FromRange, &BasePath))
2280        return ExprError();
2281
2282      QualType UType = URecordType;
2283      if (PointerConversions)
2284        UType = Context.getPointerType(UType);
2285      From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2286                               VK, &BasePath).take();
2287      FromType = UType;
2288      FromRecordType = URecordType;
2289    }
2290
2291    // We don't do access control for the conversion from the
2292    // declaring class to the true declaring class.
2293    IgnoreAccess = true;
2294  }
2295
2296  CXXCastPath BasePath;
2297  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2298                                   FromLoc, FromRange, &BasePath,
2299                                   IgnoreAccess))
2300    return ExprError();
2301
2302  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2303                           VK, &BasePath);
2304}
2305
2306/// \brief Build a MemberExpr AST node.
2307static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
2308                                   const CXXScopeSpec &SS, ValueDecl *Member,
2309                                   DeclAccessPair FoundDecl,
2310                                   const DeclarationNameInfo &MemberNameInfo,
2311                                   QualType Ty,
2312                                   ExprValueKind VK, ExprObjectKind OK,
2313                          const TemplateArgumentListInfo *TemplateArgs = 0) {
2314  return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
2315                            Member, FoundDecl, MemberNameInfo,
2316                            TemplateArgs, Ty, VK, OK);
2317}
2318
2319static ExprResult
2320BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2321                        const CXXScopeSpec &SS, FieldDecl *Field,
2322                        DeclAccessPair FoundDecl,
2323                        const DeclarationNameInfo &MemberNameInfo) {
2324  // x.a is an l-value if 'a' has a reference type. Otherwise:
2325  // x.a is an l-value/x-value/pr-value if the base is (and note
2326  //   that *x is always an l-value), except that if the base isn't
2327  //   an ordinary object then we must have an rvalue.
2328  ExprValueKind VK = VK_LValue;
2329  ExprObjectKind OK = OK_Ordinary;
2330  if (!IsArrow) {
2331    if (BaseExpr->getObjectKind() == OK_Ordinary)
2332      VK = BaseExpr->getValueKind();
2333    else
2334      VK = VK_RValue;
2335  }
2336  if (VK != VK_RValue && Field->isBitField())
2337    OK = OK_BitField;
2338
2339  // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2340  QualType MemberType = Field->getType();
2341  if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2342    MemberType = Ref->getPointeeType();
2343    VK = VK_LValue;
2344  } else {
2345    QualType BaseType = BaseExpr->getType();
2346    if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2347
2348    Qualifiers BaseQuals = BaseType.getQualifiers();
2349
2350    // GC attributes are never picked up by members.
2351    BaseQuals.removeObjCGCAttr();
2352
2353    // CVR attributes from the base are picked up by members,
2354    // except that 'mutable' members don't pick up 'const'.
2355    if (Field->isMutable()) BaseQuals.removeConst();
2356
2357    Qualifiers MemberQuals
2358      = S.Context.getCanonicalType(MemberType).getQualifiers();
2359
2360    // TR 18037 does not allow fields to be declared with address spaces.
2361    assert(!MemberQuals.hasAddressSpace());
2362
2363    Qualifiers Combined = BaseQuals + MemberQuals;
2364    if (Combined != MemberQuals)
2365      MemberType = S.Context.getQualifiedType(MemberType, Combined);
2366  }
2367
2368  S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2369  ExprResult Base =
2370    S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2371                                    FoundDecl, Field);
2372  if (Base.isInvalid())
2373    return ExprError();
2374  return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
2375                                 Field, FoundDecl, MemberNameInfo,
2376                                 MemberType, VK, OK));
2377}
2378
2379/// Builds an implicit member access expression.  The current context
2380/// is known to be an instance method, and the given unqualified lookup
2381/// set is known to contain only instance members, at least one of which
2382/// is from an appropriate type.
2383ExprResult
2384Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2385                              LookupResult &R,
2386                              const TemplateArgumentListInfo *TemplateArgs,
2387                              bool IsKnownInstance) {
2388  assert(!R.empty() && !R.isAmbiguous());
2389
2390  SourceLocation loc = R.getNameLoc();
2391
2392  // We may have found a field within an anonymous union or struct
2393  // (C++ [class.union]).
2394  // FIXME: template-ids inside anonymous structs?
2395  if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2396    return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
2397
2398  // If this is known to be an instance access, go ahead and build an
2399  // implicit 'this' expression now.
2400  // 'this' expression now.
2401  CXXMethodDecl *method = tryCaptureCXXThis();
2402  assert(method && "didn't correctly pre-flight capture of 'this'");
2403
2404  QualType thisType = method->getThisType(Context);
2405  Expr *baseExpr = 0; // null signifies implicit access
2406  if (IsKnownInstance) {
2407    SourceLocation Loc = R.getNameLoc();
2408    if (SS.getRange().isValid())
2409      Loc = SS.getRange().getBegin();
2410    baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
2411  }
2412
2413  return BuildMemberReferenceExpr(baseExpr, thisType,
2414                                  /*OpLoc*/ SourceLocation(),
2415                                  /*IsArrow*/ true,
2416                                  SS,
2417                                  /*FirstQualifierInScope*/ 0,
2418                                  R, TemplateArgs);
2419}
2420
2421bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2422                                      const LookupResult &R,
2423                                      bool HasTrailingLParen) {
2424  // Only when used directly as the postfix-expression of a call.
2425  if (!HasTrailingLParen)
2426    return false;
2427
2428  // Never if a scope specifier was provided.
2429  if (SS.isSet())
2430    return false;
2431
2432  // Only in C++ or ObjC++.
2433  if (!getLangOptions().CPlusPlus)
2434    return false;
2435
2436  // Turn off ADL when we find certain kinds of declarations during
2437  // normal lookup:
2438  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2439    NamedDecl *D = *I;
2440
2441    // C++0x [basic.lookup.argdep]p3:
2442    //     -- a declaration of a class member
2443    // Since using decls preserve this property, we check this on the
2444    // original decl.
2445    if (D->isCXXClassMember())
2446      return false;
2447
2448    // C++0x [basic.lookup.argdep]p3:
2449    //     -- a block-scope function declaration that is not a
2450    //        using-declaration
2451    // NOTE: we also trigger this for function templates (in fact, we
2452    // don't check the decl type at all, since all other decl types
2453    // turn off ADL anyway).
2454    if (isa<UsingShadowDecl>(D))
2455      D = cast<UsingShadowDecl>(D)->getTargetDecl();
2456    else if (D->getDeclContext()->isFunctionOrMethod())
2457      return false;
2458
2459    // C++0x [basic.lookup.argdep]p3:
2460    //     -- a declaration that is neither a function or a function
2461    //        template
2462    // And also for builtin functions.
2463    if (isa<FunctionDecl>(D)) {
2464      FunctionDecl *FDecl = cast<FunctionDecl>(D);
2465
2466      // But also builtin functions.
2467      if (FDecl->getBuiltinID() && FDecl->isImplicit())
2468        return false;
2469    } else if (!isa<FunctionTemplateDecl>(D))
2470      return false;
2471  }
2472
2473  return true;
2474}
2475
2476
2477/// Diagnoses obvious problems with the use of the given declaration
2478/// as an expression.  This is only actually called for lookups that
2479/// were not overloaded, and it doesn't promise that the declaration
2480/// will in fact be used.
2481static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2482  if (isa<TypedefNameDecl>(D)) {
2483    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2484    return true;
2485  }
2486
2487  if (isa<ObjCInterfaceDecl>(D)) {
2488    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2489    return true;
2490  }
2491
2492  if (isa<NamespaceDecl>(D)) {
2493    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2494    return true;
2495  }
2496
2497  return false;
2498}
2499
2500ExprResult
2501Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2502                               LookupResult &R,
2503                               bool NeedsADL) {
2504  // If this is a single, fully-resolved result and we don't need ADL,
2505  // just build an ordinary singleton decl ref.
2506  if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2507    return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2508                                    R.getFoundDecl());
2509
2510  // We only need to check the declaration if there's exactly one
2511  // result, because in the overloaded case the results can only be
2512  // functions and function templates.
2513  if (R.isSingleResult() &&
2514      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2515    return ExprError();
2516
2517  // Otherwise, just build an unresolved lookup expression.  Suppress
2518  // any lookup-related diagnostics; we'll hash these out later, when
2519  // we've picked a target.
2520  R.suppressDiagnostics();
2521
2522  UnresolvedLookupExpr *ULE
2523    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2524                                   SS.getWithLocInContext(Context),
2525                                   R.getLookupNameInfo(),
2526                                   NeedsADL, R.isOverloadedResult(),
2527                                   R.begin(), R.end());
2528
2529  return Owned(ULE);
2530}
2531
2532/// \brief Complete semantic analysis for a reference to the given declaration.
2533ExprResult
2534Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2535                               const DeclarationNameInfo &NameInfo,
2536                               NamedDecl *D) {
2537  assert(D && "Cannot refer to a NULL declaration");
2538  assert(!isa<FunctionTemplateDecl>(D) &&
2539         "Cannot refer unambiguously to a function template");
2540
2541  SourceLocation Loc = NameInfo.getLoc();
2542  if (CheckDeclInExpr(*this, Loc, D))
2543    return ExprError();
2544
2545  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2546    // Specifically diagnose references to class templates that are missing
2547    // a template argument list.
2548    Diag(Loc, diag::err_template_decl_ref)
2549      << Template << SS.getRange();
2550    Diag(Template->getLocation(), diag::note_template_decl_here);
2551    return ExprError();
2552  }
2553
2554  // Make sure that we're referring to a value.
2555  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2556  if (!VD) {
2557    Diag(Loc, diag::err_ref_non_value)
2558      << D << SS.getRange();
2559    Diag(D->getLocation(), diag::note_declared_at);
2560    return ExprError();
2561  }
2562
2563  // Check whether this declaration can be used. Note that we suppress
2564  // this check when we're going to perform argument-dependent lookup
2565  // on this function name, because this might not be the function
2566  // that overload resolution actually selects.
2567  if (DiagnoseUseOfDecl(VD, Loc))
2568    return ExprError();
2569
2570  // Only create DeclRefExpr's for valid Decl's.
2571  if (VD->isInvalidDecl())
2572    return ExprError();
2573
2574  // Handle members of anonymous structs and unions.  If we got here,
2575  // and the reference is to a class member indirect field, then this
2576  // must be the subject of a pointer-to-member expression.
2577  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2578    if (!indirectField->isCXXClassMember())
2579      return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2580                                                      indirectField);
2581
2582  // If the identifier reference is inside a block, and it refers to a value
2583  // that is outside the block, create a BlockDeclRefExpr instead of a
2584  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
2585  // the block is formed.
2586  //
2587  // We do not do this for things like enum constants, global variables, etc,
2588  // as they do not get snapshotted.
2589  //
2590  switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
2591  case CR_Error:
2592    return ExprError();
2593
2594  case CR_Capture:
2595    assert(!SS.isSet() && "referenced local variable with scope specifier?");
2596    return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2597
2598  case CR_CaptureByRef:
2599    assert(!SS.isSet() && "referenced local variable with scope specifier?");
2600    return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
2601
2602  case CR_NoCapture: {
2603    // If this reference is not in a block or if the referenced
2604    // variable is within the block, create a normal DeclRefExpr.
2605
2606    QualType type = VD->getType();
2607    ExprValueKind valueKind = VK_RValue;
2608
2609    switch (D->getKind()) {
2610    // Ignore all the non-ValueDecl kinds.
2611#define ABSTRACT_DECL(kind)
2612#define VALUE(type, base)
2613#define DECL(type, base) \
2614    case Decl::type:
2615#include "clang/AST/DeclNodes.inc"
2616      llvm_unreachable("invalid value decl kind");
2617      return ExprError();
2618
2619    // These shouldn't make it here.
2620    case Decl::ObjCAtDefsField:
2621    case Decl::ObjCIvar:
2622      llvm_unreachable("forming non-member reference to ivar?");
2623      return ExprError();
2624
2625    // Enum constants are always r-values and never references.
2626    // Unresolved using declarations are dependent.
2627    case Decl::EnumConstant:
2628    case Decl::UnresolvedUsingValue:
2629      valueKind = VK_RValue;
2630      break;
2631
2632    // Fields and indirect fields that got here must be for
2633    // pointer-to-member expressions; we just call them l-values for
2634    // internal consistency, because this subexpression doesn't really
2635    // exist in the high-level semantics.
2636    case Decl::Field:
2637    case Decl::IndirectField:
2638      assert(getLangOptions().CPlusPlus &&
2639             "building reference to field in C?");
2640
2641      // These can't have reference type in well-formed programs, but
2642      // for internal consistency we do this anyway.
2643      type = type.getNonReferenceType();
2644      valueKind = VK_LValue;
2645      break;
2646
2647    // Non-type template parameters are either l-values or r-values
2648    // depending on the type.
2649    case Decl::NonTypeTemplateParm: {
2650      if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2651        type = reftype->getPointeeType();
2652        valueKind = VK_LValue; // even if the parameter is an r-value reference
2653        break;
2654      }
2655
2656      // For non-references, we need to strip qualifiers just in case
2657      // the template parameter was declared as 'const int' or whatever.
2658      valueKind = VK_RValue;
2659      type = type.getUnqualifiedType();
2660      break;
2661    }
2662
2663    case Decl::Var:
2664      // In C, "extern void blah;" is valid and is an r-value.
2665      if (!getLangOptions().CPlusPlus &&
2666          !type.hasQualifiers() &&
2667          type->isVoidType()) {
2668        valueKind = VK_RValue;
2669        break;
2670      }
2671      // fallthrough
2672
2673    case Decl::ImplicitParam:
2674    case Decl::ParmVar:
2675      // These are always l-values.
2676      valueKind = VK_LValue;
2677      type = type.getNonReferenceType();
2678      break;
2679
2680    case Decl::Function: {
2681      const FunctionType *fty = type->castAs<FunctionType>();
2682
2683      // If we're referring to a function with an __unknown_anytype
2684      // result type, make the entire expression __unknown_anytype.
2685      if (fty->getResultType() == Context.UnknownAnyTy) {
2686        type = Context.UnknownAnyTy;
2687        valueKind = VK_RValue;
2688        break;
2689      }
2690
2691      // Functions are l-values in C++.
2692      if (getLangOptions().CPlusPlus) {
2693        valueKind = VK_LValue;
2694        break;
2695      }
2696
2697      // C99 DR 316 says that, if a function type comes from a
2698      // function definition (without a prototype), that type is only
2699      // used for checking compatibility. Therefore, when referencing
2700      // the function, we pretend that we don't have the full function
2701      // type.
2702      if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2703          isa<FunctionProtoType>(fty))
2704        type = Context.getFunctionNoProtoType(fty->getResultType(),
2705                                              fty->getExtInfo());
2706
2707      // Functions are r-values in C.
2708      valueKind = VK_RValue;
2709      break;
2710    }
2711
2712    case Decl::CXXMethod:
2713      // If we're referring to a method with an __unknown_anytype
2714      // result type, make the entire expression __unknown_anytype.
2715      // This should only be possible with a type written directly.
2716      if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2717        if (proto->getResultType() == Context.UnknownAnyTy) {
2718          type = Context.UnknownAnyTy;
2719          valueKind = VK_RValue;
2720          break;
2721        }
2722
2723      // C++ methods are l-values if static, r-values if non-static.
2724      if (cast<CXXMethodDecl>(VD)->isStatic()) {
2725        valueKind = VK_LValue;
2726        break;
2727      }
2728      // fallthrough
2729
2730    case Decl::CXXConversion:
2731    case Decl::CXXDestructor:
2732    case Decl::CXXConstructor:
2733      valueKind = VK_RValue;
2734      break;
2735    }
2736
2737    return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2738  }
2739
2740  }
2741
2742  llvm_unreachable("unknown capture result");
2743  return ExprError();
2744}
2745
2746ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2747  PredefinedExpr::IdentType IT;
2748
2749  switch (Kind) {
2750  default: assert(0 && "Unknown simple primary expr!");
2751  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2752  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2753  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2754  }
2755
2756  // Pre-defined identifiers are of type char[x], where x is the length of the
2757  // string.
2758
2759  Decl *currentDecl = getCurFunctionOrMethodDecl();
2760  if (!currentDecl && getCurBlock())
2761    currentDecl = getCurBlock()->TheDecl;
2762  if (!currentDecl) {
2763    Diag(Loc, diag::ext_predef_outside_function);
2764    currentDecl = Context.getTranslationUnitDecl();
2765  }
2766
2767  QualType ResTy;
2768  if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2769    ResTy = Context.DependentTy;
2770  } else {
2771    unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2772
2773    llvm::APInt LengthI(32, Length + 1);
2774    ResTy = Context.CharTy.withConst();
2775    ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2776  }
2777  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2778}
2779
2780ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
2781  llvm::SmallString<16> CharBuffer;
2782  bool Invalid = false;
2783  llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2784  if (Invalid)
2785    return ExprError();
2786
2787  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2788                            PP);
2789  if (Literal.hadError())
2790    return ExprError();
2791
2792  QualType Ty;
2793  if (!getLangOptions().CPlusPlus)
2794    Ty = Context.IntTy;   // 'x' and L'x' -> int in C.
2795  else if (Literal.isWide())
2796    Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
2797  else if (Literal.isMultiChar())
2798    Ty = Context.IntTy;   // 'wxyz' -> int in C++.
2799  else
2800    Ty = Context.CharTy;  // 'x' -> char in C++
2801
2802  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2803                                              Literal.isWide(),
2804                                              Ty, Tok.getLocation()));
2805}
2806
2807ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
2808  // Fast path for a single digit (which is quite common).  A single digit
2809  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2810  if (Tok.getLength() == 1) {
2811    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2812    unsigned IntSize = Context.Target.getIntWidth();
2813    return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
2814                    Context.IntTy, Tok.getLocation()));
2815  }
2816
2817  llvm::SmallString<512> IntegerBuffer;
2818  // Add padding so that NumericLiteralParser can overread by one character.
2819  IntegerBuffer.resize(Tok.getLength()+1);
2820  const char *ThisTokBegin = &IntegerBuffer[0];
2821
2822  // Get the spelling of the token, which eliminates trigraphs, etc.
2823  bool Invalid = false;
2824  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2825  if (Invalid)
2826    return ExprError();
2827
2828  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2829                               Tok.getLocation(), PP);
2830  if (Literal.hadError)
2831    return ExprError();
2832
2833  Expr *Res;
2834
2835  if (Literal.isFloatingLiteral()) {
2836    QualType Ty;
2837    if (Literal.isFloat)
2838      Ty = Context.FloatTy;
2839    else if (!Literal.isLong)
2840      Ty = Context.DoubleTy;
2841    else
2842      Ty = Context.LongDoubleTy;
2843
2844    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2845
2846    using llvm::APFloat;
2847    APFloat Val(Format);
2848
2849    APFloat::opStatus result = Literal.GetFloatValue(Val);
2850
2851    // Overflow is always an error, but underflow is only an error if
2852    // we underflowed to zero (APFloat reports denormals as underflow).
2853    if ((result & APFloat::opOverflow) ||
2854        ((result & APFloat::opUnderflow) && Val.isZero())) {
2855      unsigned diagnostic;
2856      llvm::SmallString<20> buffer;
2857      if (result & APFloat::opOverflow) {
2858        diagnostic = diag::warn_float_overflow;
2859        APFloat::getLargest(Format).toString(buffer);
2860      } else {
2861        diagnostic = diag::warn_float_underflow;
2862        APFloat::getSmallest(Format).toString(buffer);
2863      }
2864
2865      Diag(Tok.getLocation(), diagnostic)
2866        << Ty
2867        << llvm::StringRef(buffer.data(), buffer.size());
2868    }
2869
2870    bool isExact = (result == APFloat::opOK);
2871    Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
2872
2873    if (Ty == Context.DoubleTy) {
2874      if (getLangOptions().SinglePrecisionConstants) {
2875        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2876      } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2877        Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2878        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2879      }
2880    }
2881  } else if (!Literal.isIntegerLiteral()) {
2882    return ExprError();
2883  } else {
2884    QualType Ty;
2885
2886    // long long is a C99 feature.
2887    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
2888        Literal.isLongLong)
2889      Diag(Tok.getLocation(), diag::ext_longlong);
2890
2891    // Get the value in the widest-possible width.
2892    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
2893
2894    if (Literal.GetIntegerValue(ResultVal)) {
2895      // If this value didn't fit into uintmax_t, warn and force to ull.
2896      Diag(Tok.getLocation(), diag::warn_integer_too_large);
2897      Ty = Context.UnsignedLongLongTy;
2898      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2899             "long long is not intmax_t?");
2900    } else {
2901      // If this value fits into a ULL, try to figure out what else it fits into
2902      // according to the rules of C99 6.4.4.1p5.
2903
2904      // Octal, Hexadecimal, and integers with a U suffix are allowed to
2905      // be an unsigned int.
2906      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2907
2908      // Check from smallest to largest, picking the smallest type we can.
2909      unsigned Width = 0;
2910      if (!Literal.isLong && !Literal.isLongLong) {
2911        // Are int/unsigned possibilities?
2912        unsigned IntSize = Context.Target.getIntWidth();
2913
2914        // Does it fit in a unsigned int?
2915        if (ResultVal.isIntN(IntSize)) {
2916          // Does it fit in a signed int?
2917          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2918            Ty = Context.IntTy;
2919          else if (AllowUnsigned)
2920            Ty = Context.UnsignedIntTy;
2921          Width = IntSize;
2922        }
2923      }
2924
2925      // Are long/unsigned long possibilities?
2926      if (Ty.isNull() && !Literal.isLongLong) {
2927        unsigned LongSize = Context.Target.getLongWidth();
2928
2929        // Does it fit in a unsigned long?
2930        if (ResultVal.isIntN(LongSize)) {
2931          // Does it fit in a signed long?
2932          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2933            Ty = Context.LongTy;
2934          else if (AllowUnsigned)
2935            Ty = Context.UnsignedLongTy;
2936          Width = LongSize;
2937        }
2938      }
2939
2940      // Finally, check long long if needed.
2941      if (Ty.isNull()) {
2942        unsigned LongLongSize = Context.Target.getLongLongWidth();
2943
2944        // Does it fit in a unsigned long long?
2945        if (ResultVal.isIntN(LongLongSize)) {
2946          // Does it fit in a signed long long?
2947          // To be compatible with MSVC, hex integer literals ending with the
2948          // LL or i64 suffix are always signed in Microsoft mode.
2949          if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2950              (getLangOptions().Microsoft && Literal.isLongLong)))
2951            Ty = Context.LongLongTy;
2952          else if (AllowUnsigned)
2953            Ty = Context.UnsignedLongLongTy;
2954          Width = LongLongSize;
2955        }
2956      }
2957
2958      // If we still couldn't decide a type, we probably have something that
2959      // does not fit in a signed long long, but has no U suffix.
2960      if (Ty.isNull()) {
2961        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2962        Ty = Context.UnsignedLongLongTy;
2963        Width = Context.Target.getLongLongWidth();
2964      }
2965
2966      if (ResultVal.getBitWidth() != Width)
2967        ResultVal = ResultVal.trunc(Width);
2968    }
2969    Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2970  }
2971
2972  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2973  if (Literal.isImaginary)
2974    Res = new (Context) ImaginaryLiteral(Res,
2975                                        Context.getComplexType(Res->getType()));
2976
2977  return Owned(Res);
2978}
2979
2980ExprResult Sema::ActOnParenExpr(SourceLocation L,
2981                                              SourceLocation R, Expr *E) {
2982  assert((E != 0) && "ActOnParenExpr() missing expr");
2983  return Owned(new (Context) ParenExpr(L, R, E));
2984}
2985
2986/// The UsualUnaryConversions() function is *not* called by this routine.
2987/// See C99 6.3.2.1p[2-4] for more details.
2988bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2989                                            SourceLocation OpLoc,
2990                                            SourceRange ExprRange,
2991                                            UnaryExprOrTypeTrait ExprKind) {
2992  if (exprType->isDependentType())
2993    return false;
2994
2995  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2996  //   the result is the size of the referenced type."
2997  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2998  //   result shall be the alignment of the referenced type."
2999  if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3000    exprType = Ref->getPointeeType();
3001
3002  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3003  // scalar or vector data type argument..."
3004  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3005  // type (C99 6.2.5p18) or void.
3006  if (ExprKind == UETT_VecStep) {
3007    if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
3008          exprType->isVectorType())) {
3009      Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
3010        << exprType << ExprRange;
3011      return true;
3012    }
3013  }
3014
3015  // C99 6.5.3.4p1:
3016  if (exprType->isFunctionType()) {
3017    // alignof(function) is allowed as an extension.
3018    if (ExprKind == UETT_SizeOf)
3019      Diag(OpLoc, diag::ext_sizeof_function_type)
3020        << ExprRange;
3021    return false;
3022  }
3023
3024  // Allow sizeof(void)/alignof(void) as an extension.  vec_step(void) is not
3025  // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
3026  if (exprType->isVoidType()) {
3027    if (ExprKind != UETT_VecStep)
3028      Diag(OpLoc, diag::ext_sizeof_void_type)
3029        << ExprKind << ExprRange;
3030    return false;
3031  }
3032
3033  if (RequireCompleteType(OpLoc, exprType,
3034                          PDiag(diag::err_sizeof_alignof_incomplete_type)
3035                          << ExprKind << ExprRange))
3036    return true;
3037
3038  // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
3039  if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
3040    Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
3041      << exprType << (ExprKind == UETT_SizeOf)
3042      << ExprRange;
3043    return true;
3044  }
3045
3046  return false;
3047}
3048
3049static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
3050                             SourceRange ExprRange) {
3051  E = E->IgnoreParens();
3052
3053  // alignof decl is always ok.
3054  if (isa<DeclRefExpr>(E))
3055    return false;
3056
3057  // Cannot know anything else if the expression is dependent.
3058  if (E->isTypeDependent())
3059    return false;
3060
3061  if (E->getBitField()) {
3062   S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
3063    return true;
3064  }
3065
3066  // Alignment of a field access is always okay, so long as it isn't a
3067  // bit-field.
3068  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3069    if (isa<FieldDecl>(ME->getMemberDecl()))
3070      return false;
3071
3072  return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3073                                            UETT_AlignOf);
3074}
3075
3076bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
3077                            SourceRange ExprRange) {
3078  E = E->IgnoreParens();
3079
3080  // Cannot know anything else if the expression is dependent.
3081  if (E->isTypeDependent())
3082    return false;
3083
3084  return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3085                                          UETT_VecStep);
3086}
3087
3088/// \brief Build a sizeof or alignof expression given a type operand.
3089ExprResult
3090Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3091                                     SourceLocation OpLoc,
3092                                     UnaryExprOrTypeTrait ExprKind,
3093                                     SourceRange R) {
3094  if (!TInfo)
3095    return ExprError();
3096
3097  QualType T = TInfo->getType();
3098
3099  if (!T->isDependentType() &&
3100      CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3101    return ExprError();
3102
3103  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3104  return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3105                                                      Context.getSizeType(),
3106                                                      OpLoc, R.getEnd()));
3107}
3108
3109/// \brief Build a sizeof or alignof expression given an expression
3110/// operand.
3111ExprResult
3112Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3113                                     UnaryExprOrTypeTrait ExprKind,
3114                                     SourceRange R) {
3115  // Verify that the operand is valid.
3116  bool isInvalid = false;
3117  if (E->isTypeDependent()) {
3118    // Delay type-checking for type-dependent expressions.
3119  } else if (ExprKind == UETT_AlignOf) {
3120    isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
3121  } else if (ExprKind == UETT_VecStep) {
3122    isInvalid = CheckVecStepExpr(E, OpLoc, R);
3123  } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3124    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
3125    isInvalid = true;
3126  } else if (E->getType()->isPlaceholderType()) {
3127    ExprResult PE = CheckPlaceholderExpr(E);
3128    if (PE.isInvalid()) return ExprError();
3129    return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
3130  } else {
3131    isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
3132                                                 UETT_SizeOf);
3133  }
3134
3135  if (isInvalid)
3136    return ExprError();
3137
3138  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3139  return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
3140                                                      Context.getSizeType(),
3141                                                      OpLoc, R.getEnd()));
3142}
3143
3144/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3145/// expr and the same for @c alignof and @c __alignof
3146/// Note that the ArgRange is invalid if isType is false.
3147ExprResult
3148Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3149                                    UnaryExprOrTypeTrait ExprKind, bool isType,
3150                                    void *TyOrEx, const SourceRange &ArgRange) {
3151  // If error parsing type, ignore.
3152  if (TyOrEx == 0) return ExprError();
3153
3154  if (isType) {
3155    TypeSourceInfo *TInfo;
3156    (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3157    return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3158  }
3159
3160  Expr *ArgEx = (Expr *)TyOrEx;
3161  ExprResult Result
3162    = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
3163                                     ArgEx->getSourceRange());
3164
3165  return move(Result);
3166}
3167
3168static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3169                                     bool isReal) {
3170  if (V.get()->isTypeDependent())
3171    return S.Context.DependentTy;
3172
3173  // _Real and _Imag are only l-values for normal l-values.
3174  if (V.get()->getObjectKind() != OK_Ordinary) {
3175    V = S.DefaultLvalueConversion(V.take());
3176    if (V.isInvalid())
3177      return QualType();
3178  }
3179
3180  // These operators return the element type of a complex type.
3181  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3182    return CT->getElementType();
3183
3184  // Otherwise they pass through real integer and floating point types here.
3185  if (V.get()->getType()->isArithmeticType())
3186    return V.get()->getType();
3187
3188  // Test for placeholders.
3189  ExprResult PR = S.CheckPlaceholderExpr(V.get());
3190  if (PR.isInvalid()) return QualType();
3191  if (PR.get() != V.get()) {
3192    V = move(PR);
3193    return CheckRealImagOperand(S, V, Loc, isReal);
3194  }
3195
3196  // Reject anything else.
3197  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3198    << (isReal ? "__real" : "__imag");
3199  return QualType();
3200}
3201
3202
3203
3204ExprResult
3205Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3206                          tok::TokenKind Kind, Expr *Input) {
3207  UnaryOperatorKind Opc;
3208  switch (Kind) {
3209  default: assert(0 && "Unknown unary op!");
3210  case tok::plusplus:   Opc = UO_PostInc; break;
3211  case tok::minusminus: Opc = UO_PostDec; break;
3212  }
3213
3214  return BuildUnaryOp(S, OpLoc, Opc, Input);
3215}
3216
3217/// Expressions of certain arbitrary types are forbidden by C from
3218/// having l-value type.  These are:
3219///   - 'void', but not qualified void
3220///   - function types
3221///
3222/// The exact rule here is C99 6.3.2.1:
3223///   An lvalue is an expression with an object type or an incomplete
3224///   type other than void.
3225static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3226  return ((T->isVoidType() && !T.hasQualifiers()) ||
3227          T->isFunctionType());
3228}
3229
3230ExprResult
3231Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3232                              Expr *Idx, SourceLocation RLoc) {
3233  // Since this might be a postfix expression, get rid of ParenListExprs.
3234  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3235  if (Result.isInvalid()) return ExprError();
3236  Base = Result.take();
3237
3238  Expr *LHSExp = Base, *RHSExp = Idx;
3239
3240  if (getLangOptions().CPlusPlus &&
3241      (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3242    return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3243                                                  Context.DependentTy,
3244                                                  VK_LValue, OK_Ordinary,
3245                                                  RLoc));
3246  }
3247
3248  if (getLangOptions().CPlusPlus &&
3249      (LHSExp->getType()->isRecordType() ||
3250       LHSExp->getType()->isEnumeralType() ||
3251       RHSExp->getType()->isRecordType() ||
3252       RHSExp->getType()->isEnumeralType())) {
3253    return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3254  }
3255
3256  return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3257}
3258
3259
3260ExprResult
3261Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3262                                     Expr *Idx, SourceLocation RLoc) {
3263  Expr *LHSExp = Base;
3264  Expr *RHSExp = Idx;
3265
3266  // Perform default conversions.
3267  if (!LHSExp->getType()->getAs<VectorType>()) {
3268    ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3269    if (Result.isInvalid())
3270      return ExprError();
3271    LHSExp = Result.take();
3272  }
3273  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3274  if (Result.isInvalid())
3275    return ExprError();
3276  RHSExp = Result.take();
3277
3278  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3279  ExprValueKind VK = VK_LValue;
3280  ExprObjectKind OK = OK_Ordinary;
3281
3282  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3283  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3284  // in the subscript position. As a result, we need to derive the array base
3285  // and index from the expression types.
3286  Expr *BaseExpr, *IndexExpr;
3287  QualType ResultType;
3288  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3289    BaseExpr = LHSExp;
3290    IndexExpr = RHSExp;
3291    ResultType = Context.DependentTy;
3292  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3293    BaseExpr = LHSExp;
3294    IndexExpr = RHSExp;
3295    ResultType = PTy->getPointeeType();
3296  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3297     // Handle the uncommon case of "123[Ptr]".
3298    BaseExpr = RHSExp;
3299    IndexExpr = LHSExp;
3300    ResultType = PTy->getPointeeType();
3301  } else if (const ObjCObjectPointerType *PTy =
3302               LHSTy->getAs<ObjCObjectPointerType>()) {
3303    BaseExpr = LHSExp;
3304    IndexExpr = RHSExp;
3305    ResultType = PTy->getPointeeType();
3306  } else if (const ObjCObjectPointerType *PTy =
3307               RHSTy->getAs<ObjCObjectPointerType>()) {
3308     // Handle the uncommon case of "123[Ptr]".
3309    BaseExpr = RHSExp;
3310    IndexExpr = LHSExp;
3311    ResultType = PTy->getPointeeType();
3312  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3313    BaseExpr = LHSExp;    // vectors: V[123]
3314    IndexExpr = RHSExp;
3315    VK = LHSExp->getValueKind();
3316    if (VK != VK_RValue)
3317      OK = OK_VectorComponent;
3318
3319    // FIXME: need to deal with const...
3320    ResultType = VTy->getElementType();
3321  } else if (LHSTy->isArrayType()) {
3322    // If we see an array that wasn't promoted by
3323    // DefaultFunctionArrayLvalueConversion, it must be an array that
3324    // wasn't promoted because of the C90 rule that doesn't
3325    // allow promoting non-lvalue arrays.  Warn, then
3326    // force the promotion here.
3327    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3328        LHSExp->getSourceRange();
3329    LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3330                               CK_ArrayToPointerDecay).take();
3331    LHSTy = LHSExp->getType();
3332
3333    BaseExpr = LHSExp;
3334    IndexExpr = RHSExp;
3335    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3336  } else if (RHSTy->isArrayType()) {
3337    // Same as previous, except for 123[f().a] case
3338    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3339        RHSExp->getSourceRange();
3340    RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3341                               CK_ArrayToPointerDecay).take();
3342    RHSTy = RHSExp->getType();
3343
3344    BaseExpr = RHSExp;
3345    IndexExpr = LHSExp;
3346    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3347  } else {
3348    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3349       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3350  }
3351  // C99 6.5.2.1p1
3352  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3353    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3354                     << IndexExpr->getSourceRange());
3355
3356  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3357       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3358         && !IndexExpr->isTypeDependent())
3359    Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3360
3361  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3362  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3363  // type. Note that Functions are not objects, and that (in C99 parlance)
3364  // incomplete types are not object types.
3365  if (ResultType->isFunctionType()) {
3366    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3367      << ResultType << BaseExpr->getSourceRange();
3368    return ExprError();
3369  }
3370
3371  if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3372    // GNU extension: subscripting on pointer to void
3373    Diag(LLoc, diag::ext_gnu_void_ptr)
3374      << BaseExpr->getSourceRange();
3375
3376    // C forbids expressions of unqualified void type from being l-values.
3377    // See IsCForbiddenLValueType.
3378    if (!ResultType.hasQualifiers()) VK = VK_RValue;
3379  } else if (!ResultType->isDependentType() &&
3380      RequireCompleteType(LLoc, ResultType,
3381                          PDiag(diag::err_subscript_incomplete_type)
3382                            << BaseExpr->getSourceRange()))
3383    return ExprError();
3384
3385  // Diagnose bad cases where we step over interface counts.
3386  if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
3387    Diag(LLoc, diag::err_subscript_nonfragile_interface)
3388      << ResultType << BaseExpr->getSourceRange();
3389    return ExprError();
3390  }
3391
3392  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3393         !IsCForbiddenLValueType(Context, ResultType));
3394
3395  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3396                                                ResultType, VK, OK, RLoc));
3397}
3398
3399/// Check an ext-vector component access expression.
3400///
3401/// VK should be set in advance to the value kind of the base
3402/// expression.
3403static QualType
3404CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3405                        SourceLocation OpLoc, const IdentifierInfo *CompName,
3406                        SourceLocation CompLoc) {
3407  // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3408  // see FIXME there.
3409  //
3410  // FIXME: This logic can be greatly simplified by splitting it along
3411  // halving/not halving and reworking the component checking.
3412  const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
3413
3414  // The vector accessor can't exceed the number of elements.
3415  const char *compStr = CompName->getNameStart();
3416
3417  // This flag determines whether or not the component is one of the four
3418  // special names that indicate a subset of exactly half the elements are
3419  // to be selected.
3420  bool HalvingSwizzle = false;
3421
3422  // This flag determines whether or not CompName has an 's' char prefix,
3423  // indicating that it is a string of hex values to be used as vector indices.
3424  bool HexSwizzle = *compStr == 's' || *compStr == 'S';
3425
3426  bool HasRepeated = false;
3427  bool HasIndex[16] = {};
3428
3429  int Idx;
3430
3431  // Check that we've found one of the special components, or that the component
3432  // names must come from the same set.
3433  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
3434      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3435    HalvingSwizzle = true;
3436  } else if (!HexSwizzle &&
3437             (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3438    do {
3439      if (HasIndex[Idx]) HasRepeated = true;
3440      HasIndex[Idx] = true;
3441      compStr++;
3442    } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3443  } else {
3444    if (HexSwizzle) compStr++;
3445    while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3446      if (HasIndex[Idx]) HasRepeated = true;
3447      HasIndex[Idx] = true;
3448      compStr++;
3449    }
3450  }
3451
3452  if (!HalvingSwizzle && *compStr) {
3453    // We didn't get to the end of the string. This means the component names
3454    // didn't come from the same set *or* we encountered an illegal name.
3455    S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
3456      << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
3457    return QualType();
3458  }
3459
3460  // Ensure no component accessor exceeds the width of the vector type it
3461  // operates on.
3462  if (!HalvingSwizzle) {
3463    compStr = CompName->getNameStart();
3464
3465    if (HexSwizzle)
3466      compStr++;
3467
3468    while (*compStr) {
3469      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
3470        S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
3471          << baseType << SourceRange(CompLoc);
3472        return QualType();
3473      }
3474    }
3475  }
3476
3477  // The component accessor looks fine - now we need to compute the actual type.
3478  // The vector type is implied by the component accessor. For example,
3479  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
3480  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
3481  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
3482  unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
3483                                     : CompName->getLength();
3484  if (HexSwizzle)
3485    CompSize--;
3486
3487  if (CompSize == 1)
3488    return vecType->getElementType();
3489
3490  if (HasRepeated) VK = VK_RValue;
3491
3492  QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
3493  // Now look up the TypeDefDecl from the vector type. Without this,
3494  // diagostics look bad. We want extended vector types to appear built-in.
3495  for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3496    if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3497      return S.Context.getTypedefType(S.ExtVectorDecls[i]);
3498  }
3499  return VT; // should never get here (a typedef type should always be found).
3500}
3501
3502static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
3503                                                IdentifierInfo *Member,
3504                                                const Selector &Sel,
3505                                                ASTContext &Context) {
3506  if (Member)
3507    if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3508      return PD;
3509  if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
3510    return OMD;
3511
3512  for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3513       E = PDecl->protocol_end(); I != E; ++I) {
3514    if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3515                                                           Context))
3516      return D;
3517  }
3518  return 0;
3519}
3520
3521static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3522                                      IdentifierInfo *Member,
3523                                      const Selector &Sel,
3524                                      ASTContext &Context) {
3525  // Check protocols on qualified interfaces.
3526  Decl *GDecl = 0;
3527  for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3528       E = QIdTy->qual_end(); I != E; ++I) {
3529    if (Member)
3530      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3531        GDecl = PD;
3532        break;
3533      }
3534    // Also must look for a getter or setter name which uses property syntax.
3535    if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
3536      GDecl = OMD;
3537      break;
3538    }
3539  }
3540  if (!GDecl) {
3541    for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3542         E = QIdTy->qual_end(); I != E; ++I) {
3543      // Search in the protocol-qualifier list of current protocol.
3544      GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3545                                                       Context);
3546      if (GDecl)
3547        return GDecl;
3548    }
3549  }
3550  return GDecl;
3551}
3552
3553ExprResult
3554Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
3555                               bool IsArrow, SourceLocation OpLoc,
3556                               const CXXScopeSpec &SS,
3557                               NamedDecl *FirstQualifierInScope,
3558                               const DeclarationNameInfo &NameInfo,
3559                               const TemplateArgumentListInfo *TemplateArgs) {
3560  // Even in dependent contexts, try to diagnose base expressions with
3561  // obviously wrong types, e.g.:
3562  //
3563  // T* t;
3564  // t.f;
3565  //
3566  // In Obj-C++, however, the above expression is valid, since it could be
3567  // accessing the 'f' property if T is an Obj-C interface. The extra check
3568  // allows this, while still reporting an error if T is a struct pointer.
3569  if (!IsArrow) {
3570    const PointerType *PT = BaseType->getAs<PointerType>();
3571    if (PT && (!getLangOptions().ObjC1 ||
3572               PT->getPointeeType()->isRecordType())) {
3573      assert(BaseExpr && "cannot happen with implicit member accesses");
3574      Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
3575        << BaseType << BaseExpr->getSourceRange();
3576      return ExprError();
3577    }
3578  }
3579
3580  assert(BaseType->isDependentType() ||
3581         NameInfo.getName().isDependentName() ||
3582         isDependentScopeSpecifier(SS));
3583
3584  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
3585  // must have pointer type, and the accessed type is the pointee.
3586  return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
3587                                                   IsArrow, OpLoc,
3588                                               SS.getWithLocInContext(Context),
3589                                                   FirstQualifierInScope,
3590                                                   NameInfo, TemplateArgs));
3591}
3592
3593/// We know that the given qualified member reference points only to
3594/// declarations which do not belong to the static type of the base
3595/// expression.  Diagnose the problem.
3596static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3597                                             Expr *BaseExpr,
3598                                             QualType BaseType,
3599                                             const CXXScopeSpec &SS,
3600                                             NamedDecl *rep,
3601                                       const DeclarationNameInfo &nameInfo) {
3602  // If this is an implicit member access, use a different set of
3603  // diagnostics.
3604  if (!BaseExpr)
3605    return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
3606
3607  SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3608    << SS.getRange() << rep << BaseType;
3609}
3610
3611// Check whether the declarations we found through a nested-name
3612// specifier in a member expression are actually members of the base
3613// type.  The restriction here is:
3614//
3615//   C++ [expr.ref]p2:
3616//     ... In these cases, the id-expression shall name a
3617//     member of the class or of one of its base classes.
3618//
3619// So it's perfectly legitimate for the nested-name specifier to name
3620// an unrelated class, and for us to find an overload set including
3621// decls from classes which are not superclasses, as long as the decl
3622// we actually pick through overload resolution is from a superclass.
3623bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3624                                         QualType BaseType,
3625                                         const CXXScopeSpec &SS,
3626                                         const LookupResult &R) {
3627  const RecordType *BaseRT = BaseType->getAs<RecordType>();
3628  if (!BaseRT) {
3629    // We can't check this yet because the base type is still
3630    // dependent.
3631    assert(BaseType->isDependentType());
3632    return false;
3633  }
3634  CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
3635
3636  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3637    // If this is an implicit member reference and we find a
3638    // non-instance member, it's not an error.
3639    if (!BaseExpr && !(*I)->isCXXInstanceMember())
3640      return false;
3641
3642    // Note that we use the DC of the decl, not the underlying decl.
3643    DeclContext *DC = (*I)->getDeclContext();
3644    while (DC->isTransparentContext())
3645      DC = DC->getParent();
3646
3647    if (!DC->isRecord())
3648      continue;
3649
3650    llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
3651    MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
3652
3653    if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3654      return false;
3655  }
3656
3657  DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3658                                   R.getRepresentativeDecl(),
3659                                   R.getLookupNameInfo());
3660  return true;
3661}
3662
3663static bool
3664LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3665                         SourceRange BaseRange, const RecordType *RTy,
3666                         SourceLocation OpLoc, CXXScopeSpec &SS,
3667                         bool HasTemplateArgs) {
3668  RecordDecl *RDecl = RTy->getDecl();
3669  if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
3670                              SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
3671                                    << BaseRange))
3672    return true;
3673
3674  if (HasTemplateArgs) {
3675    // LookupTemplateName doesn't expect these both to exist simultaneously.
3676    QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3677
3678    bool MOUS;
3679    SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3680    return false;
3681  }
3682
3683  DeclContext *DC = RDecl;
3684  if (SS.isSet()) {
3685    // If the member name was a qualified-id, look into the
3686    // nested-name-specifier.
3687    DC = SemaRef.computeDeclContext(SS, false);
3688
3689    if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
3690      SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3691        << SS.getRange() << DC;
3692      return true;
3693    }
3694
3695    assert(DC && "Cannot handle non-computable dependent contexts in lookup");
3696
3697    if (!isa<TypeDecl>(DC)) {
3698      SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3699        << DC << SS.getRange();
3700      return true;
3701    }
3702  }
3703
3704  // The record definition is complete, now look up the member.
3705  SemaRef.LookupQualifiedName(R, DC);
3706
3707  if (!R.empty())
3708    return false;
3709
3710  // We didn't find anything with the given name, so try to correct
3711  // for typos.
3712  DeclarationName Name = R.getLookupName();
3713  if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
3714      !R.empty() &&
3715      (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3716    SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3717      << Name << DC << R.getLookupName() << SS.getRange()
3718      << FixItHint::CreateReplacement(R.getNameLoc(),
3719                                      R.getLookupName().getAsString());
3720    if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3721      SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3722        << ND->getDeclName();
3723    return false;
3724  } else {
3725    R.clear();
3726    R.setLookupName(Name);
3727  }
3728
3729  return false;
3730}
3731
3732ExprResult
3733Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3734                               SourceLocation OpLoc, bool IsArrow,
3735                               CXXScopeSpec &SS,
3736                               NamedDecl *FirstQualifierInScope,
3737                               const DeclarationNameInfo &NameInfo,
3738                               const TemplateArgumentListInfo *TemplateArgs) {
3739  if (BaseType->isDependentType() ||
3740      (SS.isSet() && isDependentScopeSpecifier(SS)))
3741    return ActOnDependentMemberExpr(Base, BaseType,
3742                                    IsArrow, OpLoc,
3743                                    SS, FirstQualifierInScope,
3744                                    NameInfo, TemplateArgs);
3745
3746  LookupResult R(*this, NameInfo, LookupMemberName);
3747
3748  // Implicit member accesses.
3749  if (!Base) {
3750    QualType RecordTy = BaseType;
3751    if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3752    if (LookupMemberExprInRecord(*this, R, SourceRange(),
3753                                 RecordTy->getAs<RecordType>(),
3754                                 OpLoc, SS, TemplateArgs != 0))
3755      return ExprError();
3756
3757  // Explicit member accesses.
3758  } else {
3759    ExprResult BaseResult = Owned(Base);
3760    ExprResult Result =
3761      LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
3762                       SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
3763
3764    if (BaseResult.isInvalid())
3765      return ExprError();
3766    Base = BaseResult.take();
3767
3768    if (Result.isInvalid()) {
3769      Owned(Base);
3770      return ExprError();
3771    }
3772
3773    if (Result.get())
3774      return move(Result);
3775
3776    // LookupMemberExpr can modify Base, and thus change BaseType
3777    BaseType = Base->getType();
3778  }
3779
3780  return BuildMemberReferenceExpr(Base, BaseType,
3781                                  OpLoc, IsArrow, SS, FirstQualifierInScope,
3782                                  R, TemplateArgs);
3783}
3784
3785ExprResult
3786Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
3787                               SourceLocation OpLoc, bool IsArrow,
3788                               const CXXScopeSpec &SS,
3789                               NamedDecl *FirstQualifierInScope,
3790                               LookupResult &R,
3791                         const TemplateArgumentListInfo *TemplateArgs,
3792                               bool SuppressQualifierCheck) {
3793  QualType BaseType = BaseExprType;
3794  if (IsArrow) {
3795    assert(BaseType->isPointerType());
3796    BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3797  }
3798  R.setBaseObjectType(BaseType);
3799
3800  const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3801  DeclarationName MemberName = MemberNameInfo.getName();
3802  SourceLocation MemberLoc = MemberNameInfo.getLoc();
3803
3804  if (R.isAmbiguous())
3805    return ExprError();
3806
3807  if (R.empty()) {
3808    // Rederive where we looked up.
3809    DeclContext *DC = (SS.isSet()
3810                       ? computeDeclContext(SS, false)
3811                       : BaseType->getAs<RecordType>()->getDecl());
3812
3813    Diag(R.getNameLoc(), diag::err_no_member)
3814      << MemberName << DC
3815      << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
3816    return ExprError();
3817  }
3818
3819  // Diagnose lookups that find only declarations from a non-base
3820  // type.  This is possible for either qualified lookups (which may
3821  // have been qualified with an unrelated type) or implicit member
3822  // expressions (which were found with unqualified lookup and thus
3823  // may have come from an enclosing scope).  Note that it's okay for
3824  // lookup to find declarations from a non-base type as long as those
3825  // aren't the ones picked by overload resolution.
3826  if ((SS.isSet() || !BaseExpr ||
3827       (isa<CXXThisExpr>(BaseExpr) &&
3828        cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
3829      !SuppressQualifierCheck &&
3830      CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
3831    return ExprError();
3832
3833  // Construct an unresolved result if we in fact got an unresolved
3834  // result.
3835  if (R.isOverloadedResult() || R.isUnresolvableResult()) {
3836    // Suppress any lookup-related diagnostics; we'll do these when we
3837    // pick a member.
3838    R.suppressDiagnostics();
3839
3840    UnresolvedMemberExpr *MemExpr
3841      = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
3842                                     BaseExpr, BaseExprType,
3843                                     IsArrow, OpLoc,
3844                                     SS.getWithLocInContext(Context),
3845                                     MemberNameInfo,
3846                                     TemplateArgs, R.begin(), R.end());
3847
3848    return Owned(MemExpr);
3849  }
3850
3851  assert(R.isSingleResult());
3852  DeclAccessPair FoundDecl = R.begin().getPair();
3853  NamedDecl *MemberDecl = R.getFoundDecl();
3854
3855  // FIXME: diagnose the presence of template arguments now.
3856
3857  // If the decl being referenced had an error, return an error for this
3858  // sub-expr without emitting another error, in order to avoid cascading
3859  // error cases.
3860  if (MemberDecl->isInvalidDecl())
3861    return ExprError();
3862
3863  // Handle the implicit-member-access case.
3864  if (!BaseExpr) {
3865    // If this is not an instance member, convert to a non-member access.
3866    if (!MemberDecl->isCXXInstanceMember())
3867      return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
3868
3869    SourceLocation Loc = R.getNameLoc();
3870    if (SS.getRange().isValid())
3871      Loc = SS.getRange().getBegin();
3872    BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
3873  }
3874
3875  bool ShouldCheckUse = true;
3876  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3877    // Don't diagnose the use of a virtual member function unless it's
3878    // explicitly qualified.
3879    if (MD->isVirtual() && !SS.isSet())
3880      ShouldCheckUse = false;
3881  }
3882
3883  // Check the use of this member.
3884  if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3885    Owned(BaseExpr);
3886    return ExprError();
3887  }
3888
3889  // Perform a property load on the base regardless of whether we
3890  // actually need it for the declaration.
3891  if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3892    ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3893    if (Result.isInvalid())
3894      return ExprError();
3895    BaseExpr = Result.take();
3896  }
3897
3898  if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3899    return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3900                                   SS, FD, FoundDecl, MemberNameInfo);
3901
3902  if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3903    // We may have found a field within an anonymous union or struct
3904    // (C++ [class.union]).
3905    return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
3906                                                    BaseExpr, OpLoc);
3907
3908  if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3909    MarkDeclarationReferenced(MemberLoc, Var);
3910    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3911                                 Var, FoundDecl, MemberNameInfo,
3912                                 Var->getType().getNonReferenceType(),
3913                                 VK_LValue, OK_Ordinary));
3914  }
3915
3916  if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3917    MarkDeclarationReferenced(MemberLoc, MemberDecl);
3918    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3919                                 MemberFn, FoundDecl, MemberNameInfo,
3920                                 MemberFn->getType(),
3921                                 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3922                                 OK_Ordinary));
3923  }
3924  assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
3925
3926  if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3927    MarkDeclarationReferenced(MemberLoc, MemberDecl);
3928    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3929                                 Enum, FoundDecl, MemberNameInfo,
3930                                 Enum->getType(), VK_RValue, OK_Ordinary));
3931  }
3932
3933  Owned(BaseExpr);
3934
3935  // We found something that we didn't expect. Complain.
3936  if (isa<TypeDecl>(MemberDecl))
3937    Diag(MemberLoc, diag::err_typecheck_member_reference_type)
3938      << MemberName << BaseType << int(IsArrow);
3939  else
3940    Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3941      << MemberName << BaseType << int(IsArrow);
3942
3943  Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3944    << MemberName;
3945  R.suppressDiagnostics();
3946  return ExprError();
3947}
3948
3949/// Given that normal member access failed on the given expression,
3950/// and given that the expression's type involves builtin-id or
3951/// builtin-Class, decide whether substituting in the redefinition
3952/// types would be profitable.  The redefinition type is whatever
3953/// this translation unit tried to typedef to id/Class;  we store
3954/// it to the side and then re-use it in places like this.
3955static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
3956  const ObjCObjectPointerType *opty
3957    = base.get()->getType()->getAs<ObjCObjectPointerType>();
3958  if (!opty) return false;
3959
3960  const ObjCObjectType *ty = opty->getObjectType();
3961
3962  QualType redef;
3963  if (ty->isObjCId()) {
3964    redef = S.Context.ObjCIdRedefinitionType;
3965  } else if (ty->isObjCClass()) {
3966    redef = S.Context.ObjCClassRedefinitionType;
3967  } else {
3968    return false;
3969  }
3970
3971  // Do the substitution as long as the redefinition type isn't just a
3972  // possibly-qualified pointer to builtin-id or builtin-Class again.
3973  opty = redef->getAs<ObjCObjectPointerType>();
3974  if (opty && !opty->getObjectType()->getInterface() != 0)
3975    return false;
3976
3977  base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
3978  return true;
3979}
3980
3981/// Look up the given member of the given non-type-dependent
3982/// expression.  This can return in one of two ways:
3983///  * If it returns a sentinel null-but-valid result, the caller will
3984///    assume that lookup was performed and the results written into
3985///    the provided structure.  It will take over from there.
3986///  * Otherwise, the returned expression will be produced in place of
3987///    an ordinary member expression.
3988///
3989/// The ObjCImpDecl bit is a gross hack that will need to be properly
3990/// fixed for ObjC++.
3991ExprResult
3992Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
3993                       bool &IsArrow, SourceLocation OpLoc,
3994                       CXXScopeSpec &SS,
3995                       Decl *ObjCImpDecl, bool HasTemplateArgs) {
3996  assert(BaseExpr.get() && "no base expression");
3997
3998  // Perform default conversions.
3999  BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4000
4001  if (IsArrow) {
4002    BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4003    if (BaseExpr.isInvalid())
4004      return ExprError();
4005  }
4006
4007  QualType BaseType = BaseExpr.get()->getType();
4008  assert(!BaseType->isDependentType());
4009
4010  DeclarationName MemberName = R.getLookupName();
4011  SourceLocation MemberLoc = R.getNameLoc();
4012
4013  // For later type-checking purposes, turn arrow accesses into dot
4014  // accesses.  The only access type we support that doesn't follow
4015  // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4016  // and those never use arrows, so this is unaffected.
4017  if (IsArrow) {
4018    if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4019      BaseType = Ptr->getPointeeType();
4020    else if (const ObjCObjectPointerType *Ptr
4021               = BaseType->getAs<ObjCObjectPointerType>())
4022      BaseType = Ptr->getPointeeType();
4023    else if (BaseType->isRecordType()) {
4024      // Recover from arrow accesses to records, e.g.:
4025      //   struct MyRecord foo;
4026      //   foo->bar
4027      // This is actually well-formed in C++ if MyRecord has an
4028      // overloaded operator->, but that should have been dealt with
4029      // by now.
4030      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4031        << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
4032        << FixItHint::CreateReplacement(OpLoc, ".");
4033      IsArrow = false;
4034    } else {
4035      Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
4036        << BaseType << BaseExpr.get()->getSourceRange();
4037      return ExprError();
4038    }
4039  }
4040
4041  // Handle field access to simple records.
4042  if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
4043    if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
4044                                 RTy, OpLoc, SS, HasTemplateArgs))
4045      return ExprError();
4046
4047    // Returning valid-but-null is how we indicate to the caller that
4048    // the lookup result was filled in.
4049    return Owned((Expr*) 0);
4050  }
4051
4052  // Handle ivar access to Objective-C objects.
4053  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
4054    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4055
4056    // There are three cases for the base type:
4057    //   - builtin id (qualified or unqualified)
4058    //   - builtin Class (qualified or unqualified)
4059    //   - an interface
4060    ObjCInterfaceDecl *IDecl = OTy->getInterface();
4061    if (!IDecl) {
4062      // There's an implicit 'isa' ivar on all objects.
4063      // But we only actually find it this way on objects of type 'id',
4064      // apparently.
4065      if (OTy->isObjCId() && Member->isStr("isa"))
4066        return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
4067                                               Context.getObjCClassType()));
4068
4069      if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4070        return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4071                                ObjCImpDecl, HasTemplateArgs);
4072      goto fail;
4073    }
4074
4075    ObjCInterfaceDecl *ClassDeclared;
4076    ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4077
4078    if (!IV) {
4079      // Attempt to correct for typos in ivar names.
4080      LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4081                       LookupMemberName);
4082      if (CorrectTypo(Res, 0, 0, IDecl, false,
4083                      IsArrow ? CTC_ObjCIvarLookup
4084                              : CTC_ObjCPropertyLookup) &&
4085          (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4086        Diag(R.getNameLoc(),
4087             diag::err_typecheck_member_reference_ivar_suggest)
4088          << IDecl->getDeclName() << MemberName << IV->getDeclName()
4089          << FixItHint::CreateReplacement(R.getNameLoc(),
4090                                          IV->getNameAsString());
4091        Diag(IV->getLocation(), diag::note_previous_decl)
4092          << IV->getDeclName();
4093      } else {
4094        Res.clear();
4095        Res.setLookupName(Member);
4096
4097        Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4098          << IDecl->getDeclName() << MemberName
4099          << BaseExpr.get()->getSourceRange();
4100        return ExprError();
4101      }
4102    }
4103
4104    // If the decl being referenced had an error, return an error for this
4105    // sub-expr without emitting another error, in order to avoid cascading
4106    // error cases.
4107    if (IV->isInvalidDecl())
4108      return ExprError();
4109
4110    // Check whether we can reference this field.
4111    if (DiagnoseUseOfDecl(IV, MemberLoc))
4112      return ExprError();
4113    if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4114        IV->getAccessControl() != ObjCIvarDecl::Package) {
4115      ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4116      if (ObjCMethodDecl *MD = getCurMethodDecl())
4117        ClassOfMethodDecl =  MD->getClassInterface();
4118      else if (ObjCImpDecl && getCurFunctionDecl()) {
4119        // Case of a c-function declared inside an objc implementation.
4120        // FIXME: For a c-style function nested inside an objc implementation
4121        // class, there is no implementation context available, so we pass
4122        // down the context as argument to this routine. Ideally, this context
4123        // need be passed down in the AST node and somehow calculated from the
4124        // AST for a function decl.
4125        if (ObjCImplementationDecl *IMPD =
4126              dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4127          ClassOfMethodDecl = IMPD->getClassInterface();
4128        else if (ObjCCategoryImplDecl* CatImplClass =
4129                   dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4130          ClassOfMethodDecl = CatImplClass->getClassInterface();
4131      }
4132
4133      if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4134        if (ClassDeclared != IDecl ||
4135            ClassOfMethodDecl != ClassDeclared)
4136          Diag(MemberLoc, diag::error_private_ivar_access)
4137            << IV->getDeclName();
4138      } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4139        // @protected
4140        Diag(MemberLoc, diag::error_protected_ivar_access)
4141          << IV->getDeclName();
4142    }
4143
4144    return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
4145                                               MemberLoc, BaseExpr.take(),
4146                                               IsArrow));
4147  }
4148
4149  // Objective-C property access.
4150  const ObjCObjectPointerType *OPT;
4151  if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4152    // This actually uses the base as an r-value.
4153    BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4154    if (BaseExpr.isInvalid())
4155      return ExprError();
4156
4157    assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
4158
4159    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4160
4161    const ObjCObjectType *OT = OPT->getObjectType();
4162
4163    // id, with and without qualifiers.
4164    if (OT->isObjCId()) {
4165      // Check protocols on qualified interfaces.
4166      Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4167      if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4168        if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4169          // Check the use of this declaration
4170          if (DiagnoseUseOfDecl(PD, MemberLoc))
4171            return ExprError();
4172
4173          return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
4174                                                         VK_LValue,
4175                                                         OK_ObjCProperty,
4176                                                         MemberLoc,
4177                                                         BaseExpr.take()));
4178        }
4179
4180        if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4181          // Check the use of this method.
4182          if (DiagnoseUseOfDecl(OMD, MemberLoc))
4183            return ExprError();
4184          Selector SetterSel =
4185            SelectorTable::constructSetterName(PP.getIdentifierTable(),
4186                                               PP.getSelectorTable(), Member);
4187          ObjCMethodDecl *SMD = 0;
4188          if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4189                                                     SetterSel, Context))
4190            SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4191          QualType PType = OMD->getSendResultType();
4192
4193          ExprValueKind VK = VK_LValue;
4194          if (!getLangOptions().CPlusPlus &&
4195              IsCForbiddenLValueType(Context, PType))
4196            VK = VK_RValue;
4197          ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4198
4199          return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4200                                                         VK, OK,
4201                                                         MemberLoc, BaseExpr.take()));
4202        }
4203      }
4204      // Use of id.member can only be for a property reference. Do not
4205      // use the 'id' redefinition in this case.
4206      if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4207        return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4208                                ObjCImpDecl, HasTemplateArgs);
4209
4210      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4211                         << MemberName << BaseType);
4212    }
4213
4214    // 'Class', unqualified only.
4215    if (OT->isObjCClass()) {
4216      // Only works in a method declaration (??!).
4217      ObjCMethodDecl *MD = getCurMethodDecl();
4218      if (!MD) {
4219        if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4220          return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4221                                  ObjCImpDecl, HasTemplateArgs);
4222
4223        goto fail;
4224      }
4225
4226      // Also must look for a getter name which uses property syntax.
4227      Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4228      ObjCInterfaceDecl *IFace = MD->getClassInterface();
4229      ObjCMethodDecl *Getter;
4230      if ((Getter = IFace->lookupClassMethod(Sel))) {
4231        // Check the use of this method.
4232        if (DiagnoseUseOfDecl(Getter, MemberLoc))
4233          return ExprError();
4234      } else
4235        Getter = IFace->lookupPrivateMethod(Sel, false);
4236      // If we found a getter then this may be a valid dot-reference, we
4237      // will look for the matching setter, in case it is needed.
4238      Selector SetterSel =
4239        SelectorTable::constructSetterName(PP.getIdentifierTable(),
4240                                           PP.getSelectorTable(), Member);
4241      ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4242      if (!Setter) {
4243        // If this reference is in an @implementation, also check for 'private'
4244        // methods.
4245        Setter = IFace->lookupPrivateMethod(SetterSel, false);
4246      }
4247      // Look through local category implementations associated with the class.
4248      if (!Setter)
4249        Setter = IFace->getCategoryClassMethod(SetterSel);
4250
4251      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4252        return ExprError();
4253
4254      if (Getter || Setter) {
4255        QualType PType;
4256
4257        ExprValueKind VK = VK_LValue;
4258        if (Getter) {
4259          PType = Getter->getSendResultType();
4260          if (!getLangOptions().CPlusPlus &&
4261              IsCForbiddenLValueType(Context, PType))
4262            VK = VK_RValue;
4263        } else {
4264          // Get the expression type from Setter's incoming parameter.
4265          PType = (*(Setter->param_end() -1))->getType();
4266        }
4267        ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4268
4269        // FIXME: we must check that the setter has property type.
4270        return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4271                                                       PType, VK, OK,
4272                                                       MemberLoc, BaseExpr.take()));
4273      }
4274
4275      if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4276        return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4277                                ObjCImpDecl, HasTemplateArgs);
4278
4279      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4280                         << MemberName << BaseType);
4281    }
4282
4283    // Normal property access.
4284    return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
4285                                     SourceLocation(), QualType(), false);
4286  }
4287
4288  // Handle 'field access' to vectors, such as 'V.xx'.
4289  if (BaseType->isExtVectorType()) {
4290    // FIXME: this expr should store IsArrow.
4291    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4292    ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
4293    QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4294                                           Member, MemberLoc);
4295    if (ret.isNull())
4296      return ExprError();
4297
4298    return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
4299                                                    *Member, MemberLoc));
4300  }
4301
4302  // Adjust builtin-sel to the appropriate redefinition type if that's
4303  // not just a pointer to builtin-sel again.
4304  if (IsArrow &&
4305      BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4306      !Context.ObjCSelRedefinitionType->isObjCSelType()) {
4307    BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4308                                 CK_BitCast);
4309    return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4310                            ObjCImpDecl, HasTemplateArgs);
4311  }
4312
4313  // Failure cases.
4314 fail:
4315
4316  // Recover from dot accesses to pointers, e.g.:
4317  //   type *foo;
4318  //   foo.bar
4319  // This is actually well-formed in two cases:
4320  //   - 'type' is an Objective C type
4321  //   - 'bar' is a pseudo-destructor name which happens to refer to
4322  //     the appropriate pointer type
4323  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4324    if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4325        MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
4326      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4327        << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
4328          << FixItHint::CreateReplacement(OpLoc, "->");
4329
4330      // Recurse as an -> access.
4331      IsArrow = true;
4332      return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4333                              ObjCImpDecl, HasTemplateArgs);
4334    }
4335  }
4336
4337  // If the user is trying to apply -> or . to a function name, it's probably
4338  // because they forgot parentheses to call that function.
4339  bool TryCall = false;
4340  bool Overloaded = false;
4341  UnresolvedSet<8> AllOverloads;
4342  if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr.get())) {
4343    AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4344    TryCall = true;
4345    Overloaded = true;
4346  } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr.get())) {
4347    if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4348      AllOverloads.addDecl(Fun);
4349      TryCall = true;
4350    }
4351  }
4352
4353  if (TryCall) {
4354    // Plunder the overload set for something that would make the member
4355    // expression valid.
4356    UnresolvedSet<4> ViableOverloads;
4357    bool HasViableZeroArgOverload = false;
4358    for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4359         DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
4360      // Our overload set may include TemplateDecls, which we'll ignore for the
4361      // purposes of determining whether we can issue a '()' fixit.
4362      if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4363        QualType ResultTy = OverloadDecl->getResultType();
4364        if ((!IsArrow && ResultTy->isRecordType()) ||
4365            (IsArrow && ResultTy->isPointerType() &&
4366             ResultTy->getPointeeType()->isRecordType())) {
4367          ViableOverloads.addDecl(*it);
4368          if (OverloadDecl->getMinRequiredArguments() == 0) {
4369            HasViableZeroArgOverload = true;
4370          }
4371        }
4372      }
4373    }
4374
4375    if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
4376      Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4377          << (AllOverloads.size() > 1) << 0
4378          << BaseExpr.get()->getSourceRange();
4379      int ViableOverloadCount = ViableOverloads.size();
4380      int I;
4381      for (I = 0; I < ViableOverloadCount; ++I) {
4382        // FIXME: Magic number for max shown overloads stolen from
4383        // OverloadCandidateSet::NoteCandidates.
4384        if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4385          break;
4386        }
4387        Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4388             diag::note_member_ref_possible_intended_overload);
4389      }
4390      if (I != ViableOverloadCount) {
4391        Diag(BaseExpr.get()->getExprLoc(), diag::note_ovl_too_many_candidates)
4392            << int(ViableOverloadCount - I);
4393      }
4394      return ExprError();
4395    }
4396  } else {
4397    // We don't have an expression that's convenient to get a Decl from, but we
4398    // can at least check if the type is "function of 0 arguments which returns
4399    // an acceptable type".
4400    const FunctionType *Fun = NULL;
4401    if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4402      if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4403        TryCall = true;
4404      }
4405    } else if ((Fun = BaseType->getAs<FunctionType>())) {
4406      TryCall = true;
4407    }
4408
4409    if (TryCall) {
4410      if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4411        if (FPT->getNumArgs() == 0) {
4412          QualType ResultTy = Fun->getResultType();
4413          TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4414              (IsArrow && ResultTy->isPointerType() &&
4415               ResultTy->getPointeeType()->isRecordType());
4416        }
4417      }
4418    }
4419  }
4420
4421  if (TryCall) {
4422    // At this point, we know BaseExpr looks like it's potentially callable with
4423    // 0 arguments, and that it returns something of a reasonable type, so we
4424    // can emit a fixit and carry on pretending that BaseExpr was actually a
4425    // CallExpr.
4426    SourceLocation ParenInsertionLoc =
4427        PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4428    Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4429        << int(Overloaded) << 1
4430        << BaseExpr.get()->getSourceRange()
4431        << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4432    ExprResult NewBase = ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
4433                                       MultiExprArg(*this, 0, 0),
4434                                       ParenInsertionLoc);
4435    if (NewBase.isInvalid())
4436      return ExprError();
4437    BaseExpr = NewBase;
4438    BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4439    return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4440                            ObjCImpDecl, HasTemplateArgs);
4441  }
4442
4443  Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4444    << BaseType << BaseExpr.get()->getSourceRange();
4445
4446  return ExprError();
4447}
4448
4449/// The main callback when the parser finds something like
4450///   expression . [nested-name-specifier] identifier
4451///   expression -> [nested-name-specifier] identifier
4452/// where 'identifier' encompasses a fairly broad spectrum of
4453/// possibilities, including destructor and operator references.
4454///
4455/// \param OpKind either tok::arrow or tok::period
4456/// \param HasTrailingLParen whether the next token is '(', which
4457///   is used to diagnose mis-uses of special members that can
4458///   only be called
4459/// \param ObjCImpDecl the current ObjC @implementation decl;
4460///   this is an ugly hack around the fact that ObjC @implementations
4461///   aren't properly put in the context chain
4462ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
4463                                       SourceLocation OpLoc,
4464                                       tok::TokenKind OpKind,
4465                                       CXXScopeSpec &SS,
4466                                       UnqualifiedId &Id,
4467                                       Decl *ObjCImpDecl,
4468                                       bool HasTrailingLParen) {
4469  if (SS.isSet() && SS.isInvalid())
4470    return ExprError();
4471
4472  // Warn about the explicit constructor calls Microsoft extension.
4473  if (getLangOptions().Microsoft &&
4474      Id.getKind() == UnqualifiedId::IK_ConstructorName)
4475    Diag(Id.getSourceRange().getBegin(),
4476         diag::ext_ms_explicit_constructor_call);
4477
4478  TemplateArgumentListInfo TemplateArgsBuffer;
4479
4480  // Decompose the name into its component parts.
4481  DeclarationNameInfo NameInfo;
4482  const TemplateArgumentListInfo *TemplateArgs;
4483  DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
4484                         NameInfo, TemplateArgs);
4485
4486  DeclarationName Name = NameInfo.getName();
4487  bool IsArrow = (OpKind == tok::arrow);
4488
4489  NamedDecl *FirstQualifierInScope
4490    = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4491                       static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4492
4493  // This is a postfix expression, so get rid of ParenListExprs.
4494  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
4495  if (Result.isInvalid()) return ExprError();
4496  Base = Result.take();
4497
4498  if (Base->getType()->isDependentType() || Name.isDependentName() ||
4499      isDependentScopeSpecifier(SS)) {
4500    Result = ActOnDependentMemberExpr(Base, Base->getType(),
4501                                      IsArrow, OpLoc,
4502                                      SS, FirstQualifierInScope,
4503                                      NameInfo, TemplateArgs);
4504  } else {
4505    LookupResult R(*this, NameInfo, LookupMemberName);
4506    ExprResult BaseResult = Owned(Base);
4507    Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
4508                              SS, ObjCImpDecl, TemplateArgs != 0);
4509    if (BaseResult.isInvalid())
4510      return ExprError();
4511    Base = BaseResult.take();
4512
4513    if (Result.isInvalid()) {
4514      Owned(Base);
4515      return ExprError();
4516    }
4517
4518    if (Result.get()) {
4519      // The only way a reference to a destructor can be used is to
4520      // immediately call it, which falls into this case.  If the
4521      // next token is not a '(', produce a diagnostic and build the
4522      // call now.
4523      if (!HasTrailingLParen &&
4524          Id.getKind() == UnqualifiedId::IK_DestructorName)
4525        return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
4526
4527      return move(Result);
4528    }
4529
4530    Result = BuildMemberReferenceExpr(Base, Base->getType(),
4531                                      OpLoc, IsArrow, SS, FirstQualifierInScope,
4532                                      R, TemplateArgs);
4533  }
4534
4535  return move(Result);
4536}
4537
4538ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4539                                        FunctionDecl *FD,
4540                                        ParmVarDecl *Param) {
4541  if (Param->hasUnparsedDefaultArg()) {
4542    Diag(CallLoc,
4543         diag::err_use_of_default_argument_to_function_declared_later) <<
4544      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4545    Diag(UnparsedDefaultArgLocs[Param],
4546         diag::note_default_argument_declared_here);
4547    return ExprError();
4548  }
4549
4550  if (Param->hasUninstantiatedDefaultArg()) {
4551    Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4552
4553    // Instantiate the expression.
4554    MultiLevelTemplateArgumentList ArgList
4555      = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
4556
4557    std::pair<const TemplateArgument *, unsigned> Innermost
4558      = ArgList.getInnermost();
4559    InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4560                               Innermost.second);
4561
4562    ExprResult Result;
4563    {
4564      // C++ [dcl.fct.default]p5:
4565      //   The names in the [default argument] expression are bound, and
4566      //   the semantic constraints are checked, at the point where the
4567      //   default argument expression appears.
4568      ContextRAII SavedContext(*this, FD);
4569      Result = SubstExpr(UninstExpr, ArgList);
4570    }
4571    if (Result.isInvalid())
4572      return ExprError();
4573
4574    // Check the expression as an initializer for the parameter.
4575    InitializedEntity Entity
4576      = InitializedEntity::InitializeParameter(Context, Param);
4577    InitializationKind Kind
4578      = InitializationKind::CreateCopy(Param->getLocation(),
4579             /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4580    Expr *ResultE = Result.takeAs<Expr>();
4581
4582    InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4583    Result = InitSeq.Perform(*this, Entity, Kind,
4584                             MultiExprArg(*this, &ResultE, 1));
4585    if (Result.isInvalid())
4586      return ExprError();
4587
4588    // Build the default argument expression.
4589    return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4590                                           Result.takeAs<Expr>()));
4591  }
4592
4593  // If the default expression creates temporaries, we need to
4594  // push them to the current stack of expression temporaries so they'll
4595  // be properly destroyed.
4596  // FIXME: We should really be rebuilding the default argument with new
4597  // bound temporaries; see the comment in PR5810.
4598  for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4599    CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4600    MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4601                    const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4602    ExprTemporaries.push_back(Temporary);
4603  }
4604
4605  // We already type-checked the argument, so we know it works.
4606  // Just mark all of the declarations in this potentially-evaluated expression
4607  // as being "referenced".
4608  MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
4609  return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
4610}
4611
4612/// ConvertArgumentsForCall - Converts the arguments specified in
4613/// Args/NumArgs to the parameter types of the function FDecl with
4614/// function prototype Proto. Call is the call expression itself, and
4615/// Fn is the function expression. For a C++ member function, this
4616/// routine does not attempt to convert the object argument. Returns
4617/// true if the call is ill-formed.
4618bool
4619Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4620                              FunctionDecl *FDecl,
4621                              const FunctionProtoType *Proto,
4622                              Expr **Args, unsigned NumArgs,
4623                              SourceLocation RParenLoc) {
4624  // Bail out early if calling a builtin with custom typechecking.
4625  // We don't need to do this in the
4626  if (FDecl)
4627    if (unsigned ID = FDecl->getBuiltinID())
4628      if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4629        return false;
4630
4631  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4632  // assignment, to the types of the corresponding parameter, ...
4633  unsigned NumArgsInProto = Proto->getNumArgs();
4634  bool Invalid = false;
4635
4636  // If too few arguments are available (and we don't have default
4637  // arguments for the remaining parameters), don't make the call.
4638  if (NumArgs < NumArgsInProto) {
4639    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4640      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4641        << Fn->getType()->isBlockPointerType()
4642        << NumArgsInProto << NumArgs << Fn->getSourceRange();
4643    Call->setNumArgs(Context, NumArgsInProto);
4644  }
4645
4646  // If too many are passed and not variadic, error on the extras and drop
4647  // them.
4648  if (NumArgs > NumArgsInProto) {
4649    if (!Proto->isVariadic()) {
4650      Diag(Args[NumArgsInProto]->getLocStart(),
4651           diag::err_typecheck_call_too_many_args)
4652        << Fn->getType()->isBlockPointerType()
4653        << NumArgsInProto << NumArgs << Fn->getSourceRange()
4654        << SourceRange(Args[NumArgsInProto]->getLocStart(),
4655                       Args[NumArgs-1]->getLocEnd());
4656
4657      // Emit the location of the prototype.
4658      if (FDecl && !FDecl->getBuiltinID())
4659        Diag(FDecl->getLocStart(),
4660             diag::note_typecheck_call_too_many_args)
4661             << FDecl;
4662
4663      // This deletes the extra arguments.
4664      Call->setNumArgs(Context, NumArgsInProto);
4665      return true;
4666    }
4667  }
4668  llvm::SmallVector<Expr *, 8> AllArgs;
4669  VariadicCallType CallType =
4670    Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4671  if (Fn->getType()->isBlockPointerType())
4672    CallType = VariadicBlock; // Block
4673  else if (isa<MemberExpr>(Fn))
4674    CallType = VariadicMethod;
4675  Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
4676                                   Proto, 0, Args, NumArgs, AllArgs, CallType);
4677  if (Invalid)
4678    return true;
4679  unsigned TotalNumArgs = AllArgs.size();
4680  for (unsigned i = 0; i < TotalNumArgs; ++i)
4681    Call->setArg(i, AllArgs[i]);
4682
4683  return false;
4684}
4685
4686bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4687                                  FunctionDecl *FDecl,
4688                                  const FunctionProtoType *Proto,
4689                                  unsigned FirstProtoArg,
4690                                  Expr **Args, unsigned NumArgs,
4691                                  llvm::SmallVector<Expr *, 8> &AllArgs,
4692                                  VariadicCallType CallType) {
4693  unsigned NumArgsInProto = Proto->getNumArgs();
4694  unsigned NumArgsToCheck = NumArgs;
4695  bool Invalid = false;
4696  if (NumArgs != NumArgsInProto)
4697    // Use default arguments for missing arguments
4698    NumArgsToCheck = NumArgsInProto;
4699  unsigned ArgIx = 0;
4700  // Continue to check argument types (even if we have too few/many args).
4701  for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4702    QualType ProtoArgType = Proto->getArgType(i);
4703
4704    Expr *Arg;
4705    if (ArgIx < NumArgs) {
4706      Arg = Args[ArgIx++];
4707
4708      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4709                              ProtoArgType,
4710                              PDiag(diag::err_call_incomplete_argument)
4711                              << Arg->getSourceRange()))
4712        return true;
4713
4714      // Pass the argument
4715      ParmVarDecl *Param = 0;
4716      if (FDecl && i < FDecl->getNumParams())
4717        Param = FDecl->getParamDecl(i);
4718
4719      InitializedEntity Entity =
4720        Param? InitializedEntity::InitializeParameter(Context, Param)
4721             : InitializedEntity::InitializeParameter(Context, ProtoArgType);
4722      ExprResult ArgE = PerformCopyInitialization(Entity,
4723                                                  SourceLocation(),
4724                                                  Owned(Arg));
4725      if (ArgE.isInvalid())
4726        return true;
4727
4728      Arg = ArgE.takeAs<Expr>();
4729    } else {
4730      ParmVarDecl *Param = FDecl->getParamDecl(i);
4731
4732      ExprResult ArgExpr =
4733        BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4734      if (ArgExpr.isInvalid())
4735        return true;
4736
4737      Arg = ArgExpr.takeAs<Expr>();
4738    }
4739    AllArgs.push_back(Arg);
4740  }
4741
4742  // If this is a variadic call, handle args passed through "...".
4743  if (CallType != VariadicDoesNotApply) {
4744
4745    // Assume that extern "C" functions with variadic arguments that
4746    // return __unknown_anytype aren't *really* variadic.
4747    if (Proto->getResultType() == Context.UnknownAnyTy &&
4748        FDecl && FDecl->isExternC()) {
4749      for (unsigned i = ArgIx; i != NumArgs; ++i) {
4750        ExprResult arg;
4751        if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4752          arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4753        else
4754          arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4755        Invalid |= arg.isInvalid();
4756        AllArgs.push_back(arg.take());
4757      }
4758
4759    // Otherwise do argument promotion, (C99 6.5.2.2p7).
4760    } else {
4761      for (unsigned i = ArgIx; i != NumArgs; ++i) {
4762        ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4763        Invalid |= Arg.isInvalid();
4764        AllArgs.push_back(Arg.take());
4765      }
4766    }
4767  }
4768  return Invalid;
4769}
4770
4771/// Given a function expression of unknown-any type, try to rebuild it
4772/// to have a function type.
4773static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4774
4775/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4776/// This provides the location of the left/right parens and a list of comma
4777/// locations.
4778ExprResult
4779Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4780                    MultiExprArg args, SourceLocation RParenLoc,
4781                    Expr *ExecConfig) {
4782  unsigned NumArgs = args.size();
4783
4784  // Since this might be a postfix expression, get rid of ParenListExprs.
4785  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4786  if (Result.isInvalid()) return ExprError();
4787  Fn = Result.take();
4788
4789  Expr **Args = args.release();
4790
4791  if (getLangOptions().CPlusPlus) {
4792    // If this is a pseudo-destructor expression, build the call immediately.
4793    if (isa<CXXPseudoDestructorExpr>(Fn)) {
4794      if (NumArgs > 0) {
4795        // Pseudo-destructor calls should not have any arguments.
4796        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4797          << FixItHint::CreateRemoval(
4798                                    SourceRange(Args[0]->getLocStart(),
4799                                                Args[NumArgs-1]->getLocEnd()));
4800
4801        NumArgs = 0;
4802      }
4803
4804      return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
4805                                          VK_RValue, RParenLoc));
4806    }
4807
4808    // Determine whether this is a dependent call inside a C++ template,
4809    // in which case we won't do any semantic analysis now.
4810    // FIXME: Will need to cache the results of name lookup (including ADL) in
4811    // Fn.
4812    bool Dependent = false;
4813    if (Fn->isTypeDependent())
4814      Dependent = true;
4815    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4816      Dependent = true;
4817
4818    if (Dependent) {
4819      if (ExecConfig) {
4820        return Owned(new (Context) CUDAKernelCallExpr(
4821            Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4822            Context.DependentTy, VK_RValue, RParenLoc));
4823      } else {
4824        return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4825                                            Context.DependentTy, VK_RValue,
4826                                            RParenLoc));
4827      }
4828    }
4829
4830    // Determine whether this is a call to an object (C++ [over.call.object]).
4831    if (Fn->getType()->isRecordType())
4832      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
4833                                                RParenLoc));
4834
4835    if (Fn->getType() == Context.UnknownAnyTy) {
4836      ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4837      if (result.isInvalid()) return ExprError();
4838      Fn = result.take();
4839    }
4840
4841    Expr *NakedFn = Fn->IgnoreParens();
4842
4843    // Determine whether this is a call to an unresolved member function.
4844    if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4845      // If lookup was unresolved but not dependent (i.e. didn't find
4846      // an unresolved using declaration), it has to be an overloaded
4847      // function set, which means it must contain either multiple
4848      // declarations (all methods or method templates) or a single
4849      // method template.
4850      assert((MemE->getNumDecls() > 1) ||
4851             isa<FunctionTemplateDecl>(
4852                                 (*MemE->decls_begin())->getUnderlyingDecl()));
4853      (void)MemE;
4854
4855      return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
4856                                       RParenLoc);
4857    }
4858
4859    // Determine whether this is a call to a member function.
4860    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
4861      NamedDecl *MemDecl = MemExpr->getMemberDecl();
4862      if (isa<CXXMethodDecl>(MemDecl))
4863        return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
4864                                         RParenLoc);
4865    }
4866
4867    // Determine whether this is a call to a pointer-to-member function.
4868    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
4869      if (BO->getOpcode() == BO_PtrMemD ||
4870          BO->getOpcode() == BO_PtrMemI) {
4871        if (const FunctionProtoType *FPT
4872                                = BO->getType()->getAs<FunctionProtoType>()) {
4873          QualType ResultTy = FPT->getCallResultType(Context);
4874          ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
4875
4876          // Check that the object type isn't more qualified than the
4877          // member function we're calling.
4878          Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4879          Qualifiers ObjectQuals
4880            = BO->getOpcode() == BO_PtrMemD
4881                ? BO->getLHS()->getType().getQualifiers()
4882                : BO->getLHS()->getType()->getAs<PointerType>()
4883                                            ->getPointeeType().getQualifiers();
4884
4885          Qualifiers Difference = ObjectQuals - FuncQuals;
4886          Difference.removeObjCGCAttr();
4887          Difference.removeAddressSpace();
4888          if (Difference) {
4889            std::string QualsString = Difference.getAsString();
4890            Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4891              << BO->getType().getUnqualifiedType()
4892              << QualsString
4893              << (QualsString.find(' ') == std::string::npos? 1 : 2);
4894          }
4895
4896          CXXMemberCallExpr *TheCall
4897            = new (Context) CXXMemberCallExpr(Context, Fn, Args,
4898                                              NumArgs, ResultTy, VK,
4899                                              RParenLoc);
4900
4901          if (CheckCallReturnType(FPT->getResultType(),
4902                                  BO->getRHS()->getSourceRange().getBegin(),
4903                                  TheCall, 0))
4904            return ExprError();
4905
4906          if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
4907                                      RParenLoc))
4908            return ExprError();
4909
4910          return MaybeBindToTemporary(TheCall);
4911        }
4912      }
4913    }
4914  }
4915
4916  // If we're directly calling a function, get the appropriate declaration.
4917  // Also, in C++, keep track of whether we should perform argument-dependent
4918  // lookup and whether there were any explicitly-specified template arguments.
4919
4920  Expr *NakedFn = Fn->IgnoreParens();
4921  if (isa<UnresolvedLookupExpr>(NakedFn)) {
4922    UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4923    return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4924                                   RParenLoc, ExecConfig);
4925  }
4926
4927  NamedDecl *NDecl = 0;
4928  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4929    if (UnOp->getOpcode() == UO_AddrOf)
4930      NakedFn = UnOp->getSubExpr()->IgnoreParens();
4931
4932  if (isa<DeclRefExpr>(NakedFn))
4933    NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4934
4935  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4936                               ExecConfig);
4937}
4938
4939ExprResult
4940Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4941                              MultiExprArg execConfig, SourceLocation GGGLoc) {
4942  FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4943  if (!ConfigDecl)
4944    return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4945                          << "cudaConfigureCall");
4946  QualType ConfigQTy = ConfigDecl->getType();
4947
4948  DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4949      ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4950
4951  return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
4952}
4953
4954/// BuildResolvedCallExpr - Build a call to a resolved expression,
4955/// i.e. an expression not of \p OverloadTy.  The expression should
4956/// unary-convert to an expression of function-pointer or
4957/// block-pointer type.
4958///
4959/// \param NDecl the declaration being called, if available
4960ExprResult
4961Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4962                            SourceLocation LParenLoc,
4963                            Expr **Args, unsigned NumArgs,
4964                            SourceLocation RParenLoc,
4965                            Expr *Config) {
4966  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4967
4968  // Promote the function operand.
4969  ExprResult Result = UsualUnaryConversions(Fn);
4970  if (Result.isInvalid())
4971    return ExprError();
4972  Fn = Result.take();
4973
4974  // Make the call expr early, before semantic checks.  This guarantees cleanup
4975  // of arguments and function on error.
4976  CallExpr *TheCall;
4977  if (Config) {
4978    TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4979                                               cast<CallExpr>(Config),
4980                                               Args, NumArgs,
4981                                               Context.BoolTy,
4982                                               VK_RValue,
4983                                               RParenLoc);
4984  } else {
4985    TheCall = new (Context) CallExpr(Context, Fn,
4986                                     Args, NumArgs,
4987                                     Context.BoolTy,
4988                                     VK_RValue,
4989                                     RParenLoc);
4990  }
4991
4992  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4993
4994  // Bail out early if calling a builtin with custom typechecking.
4995  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4996    return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4997
4998 retry:
4999  const FunctionType *FuncT;
5000  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5001    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5002    // have type pointer to function".
5003    FuncT = PT->getPointeeType()->getAs<FunctionType>();
5004    if (FuncT == 0)
5005      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5006                         << Fn->getType() << Fn->getSourceRange());
5007  } else if (const BlockPointerType *BPT =
5008               Fn->getType()->getAs<BlockPointerType>()) {
5009    FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5010  } else {
5011    // Handle calls to expressions of unknown-any type.
5012    if (Fn->getType() == Context.UnknownAnyTy) {
5013      ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5014      if (rewrite.isInvalid()) return ExprError();
5015      Fn = rewrite.take();
5016      TheCall->setCallee(Fn);
5017      goto retry;
5018    }
5019
5020    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5021      << Fn->getType() << Fn->getSourceRange());
5022  }
5023
5024  if (getLangOptions().CUDA) {
5025    if (Config) {
5026      // CUDA: Kernel calls must be to global functions
5027      if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5028        return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5029            << FDecl->getName() << Fn->getSourceRange());
5030
5031      // CUDA: Kernel function must have 'void' return type
5032      if (!FuncT->getResultType()->isVoidType())
5033        return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5034            << Fn->getType() << Fn->getSourceRange());
5035    }
5036  }
5037
5038  // Check for a valid return type
5039  if (CheckCallReturnType(FuncT->getResultType(),
5040                          Fn->getSourceRange().getBegin(), TheCall,
5041                          FDecl))
5042    return ExprError();
5043
5044  // We know the result type of the call, set it.
5045  TheCall->setType(FuncT->getCallResultType(Context));
5046  TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
5047
5048  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
5049    if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
5050                                RParenLoc))
5051      return ExprError();
5052  } else {
5053    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5054
5055    if (FDecl) {
5056      // Check if we have too few/too many template arguments, based
5057      // on our knowledge of the function definition.
5058      const FunctionDecl *Def = 0;
5059      if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
5060        const FunctionProtoType *Proto
5061          = Def->getType()->getAs<FunctionProtoType>();
5062        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
5063          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5064            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
5065      }
5066
5067      // If the function we're calling isn't a function prototype, but we have
5068      // a function prototype from a prior declaratiom, use that prototype.
5069      if (!FDecl->hasPrototype())
5070        Proto = FDecl->getType()->getAs<FunctionProtoType>();
5071    }
5072
5073    // Promote the arguments (C99 6.5.2.2p6).
5074    for (unsigned i = 0; i != NumArgs; i++) {
5075      Expr *Arg = Args[i];
5076
5077      if (Proto && i < Proto->getNumArgs()) {
5078        InitializedEntity Entity
5079          = InitializedEntity::InitializeParameter(Context,
5080                                                   Proto->getArgType(i));
5081        ExprResult ArgE = PerformCopyInitialization(Entity,
5082                                                    SourceLocation(),
5083                                                    Owned(Arg));
5084        if (ArgE.isInvalid())
5085          return true;
5086
5087        Arg = ArgE.takeAs<Expr>();
5088
5089      } else {
5090        ExprResult ArgE = DefaultArgumentPromotion(Arg);
5091
5092        if (ArgE.isInvalid())
5093          return true;
5094
5095        Arg = ArgE.takeAs<Expr>();
5096      }
5097
5098      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5099                              Arg->getType(),
5100                              PDiag(diag::err_call_incomplete_argument)
5101                                << Arg->getSourceRange()))
5102        return ExprError();
5103
5104      TheCall->setArg(i, Arg);
5105    }
5106  }
5107
5108  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5109    if (!Method->isStatic())
5110      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5111        << Fn->getSourceRange());
5112
5113  // Check for sentinels
5114  if (NDecl)
5115    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
5116
5117  // Do special checking on direct calls to functions.
5118  if (FDecl) {
5119    if (CheckFunctionCall(FDecl, TheCall))
5120      return ExprError();
5121
5122    if (BuiltinID)
5123      return CheckBuiltinFunctionCall(BuiltinID, TheCall);
5124  } else if (NDecl) {
5125    if (CheckBlockCall(NDecl, TheCall))
5126      return ExprError();
5127  }
5128
5129  return MaybeBindToTemporary(TheCall);
5130}
5131
5132ExprResult
5133Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5134                           SourceLocation RParenLoc, Expr *InitExpr) {
5135  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
5136  // FIXME: put back this assert when initializers are worked out.
5137  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
5138
5139  TypeSourceInfo *TInfo;
5140  QualType literalType = GetTypeFromParser(Ty, &TInfo);
5141  if (!TInfo)
5142    TInfo = Context.getTrivialTypeSourceInfo(literalType);
5143
5144  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5145}
5146
5147ExprResult
5148Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5149                               SourceLocation RParenLoc, Expr *literalExpr) {
5150  QualType literalType = TInfo->getType();
5151
5152  if (literalType->isArrayType()) {
5153    if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5154             PDiag(diag::err_illegal_decl_array_incomplete_type)
5155               << SourceRange(LParenLoc,
5156                              literalExpr->getSourceRange().getEnd())))
5157      return ExprError();
5158    if (literalType->isVariableArrayType())
5159      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5160        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
5161  } else if (!literalType->isDependentType() &&
5162             RequireCompleteType(LParenLoc, literalType,
5163                      PDiag(diag::err_typecheck_decl_incomplete_type)
5164                        << SourceRange(LParenLoc,
5165                                       literalExpr->getSourceRange().getEnd())))
5166    return ExprError();
5167
5168  InitializedEntity Entity
5169    = InitializedEntity::InitializeTemporary(literalType);
5170  InitializationKind Kind
5171    = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
5172                                     /*IsCStyleCast=*/true);
5173  InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
5174  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5175                                       MultiExprArg(*this, &literalExpr, 1),
5176                                            &literalType);
5177  if (Result.isInvalid())
5178    return ExprError();
5179  literalExpr = Result.get();
5180
5181  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
5182  if (isFileScope) { // 6.5.2.5p3
5183    if (CheckForConstantInitializer(literalExpr, literalType))
5184      return ExprError();
5185  }
5186
5187  // In C, compound literals are l-values for some reason.
5188  ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5189
5190  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5191                                                 VK, literalExpr, isFileScope));
5192}
5193
5194ExprResult
5195Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
5196                    SourceLocation RBraceLoc) {
5197  unsigned NumInit = initlist.size();
5198  Expr **InitList = initlist.release();
5199
5200  // Semantic analysis for initializers is done by ActOnDeclarator() and
5201  // CheckInitializer() - it requires knowledge of the object being intialized.
5202
5203  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5204                                               NumInit, RBraceLoc);
5205  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5206  return Owned(E);
5207}
5208
5209/// Prepares for a scalar cast, performing all the necessary stages
5210/// except the final cast and returning the kind required.
5211static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
5212  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5213  // Also, callers should have filtered out the invalid cases with
5214  // pointers.  Everything else should be possible.
5215
5216  QualType SrcTy = Src.get()->getType();
5217  if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
5218    return CK_NoOp;
5219
5220  switch (SrcTy->getScalarTypeKind()) {
5221  case Type::STK_MemberPointer:
5222    llvm_unreachable("member pointer type in C");
5223
5224  case Type::STK_Pointer:
5225    switch (DestTy->getScalarTypeKind()) {
5226    case Type::STK_Pointer:
5227      return DestTy->isObjCObjectPointerType() ?
5228                CK_AnyPointerToObjCPointerCast :
5229                CK_BitCast;
5230    case Type::STK_Bool:
5231      return CK_PointerToBoolean;
5232    case Type::STK_Integral:
5233      return CK_PointerToIntegral;
5234    case Type::STK_Floating:
5235    case Type::STK_FloatingComplex:
5236    case Type::STK_IntegralComplex:
5237    case Type::STK_MemberPointer:
5238      llvm_unreachable("illegal cast from pointer");
5239    }
5240    break;
5241
5242  case Type::STK_Bool: // casting from bool is like casting from an integer
5243  case Type::STK_Integral:
5244    switch (DestTy->getScalarTypeKind()) {
5245    case Type::STK_Pointer:
5246      if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
5247        return CK_NullToPointer;
5248      return CK_IntegralToPointer;
5249    case Type::STK_Bool:
5250      return CK_IntegralToBoolean;
5251    case Type::STK_Integral:
5252      return CK_IntegralCast;
5253    case Type::STK_Floating:
5254      return CK_IntegralToFloating;
5255    case Type::STK_IntegralComplex:
5256      Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5257                                CK_IntegralCast);
5258      return CK_IntegralRealToComplex;
5259    case Type::STK_FloatingComplex:
5260      Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5261                                CK_IntegralToFloating);
5262      return CK_FloatingRealToComplex;
5263    case Type::STK_MemberPointer:
5264      llvm_unreachable("member pointer type in C");
5265    }
5266    break;
5267
5268  case Type::STK_Floating:
5269    switch (DestTy->getScalarTypeKind()) {
5270    case Type::STK_Floating:
5271      return CK_FloatingCast;
5272    case Type::STK_Bool:
5273      return CK_FloatingToBoolean;
5274    case Type::STK_Integral:
5275      return CK_FloatingToIntegral;
5276    case Type::STK_FloatingComplex:
5277      Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5278                                CK_FloatingCast);
5279      return CK_FloatingRealToComplex;
5280    case Type::STK_IntegralComplex:
5281      Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5282                                CK_FloatingToIntegral);
5283      return CK_IntegralRealToComplex;
5284    case Type::STK_Pointer:
5285      llvm_unreachable("valid float->pointer cast?");
5286    case Type::STK_MemberPointer:
5287      llvm_unreachable("member pointer type in C");
5288    }
5289    break;
5290
5291  case Type::STK_FloatingComplex:
5292    switch (DestTy->getScalarTypeKind()) {
5293    case Type::STK_FloatingComplex:
5294      return CK_FloatingComplexCast;
5295    case Type::STK_IntegralComplex:
5296      return CK_FloatingComplexToIntegralComplex;
5297    case Type::STK_Floating: {
5298      QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
5299      if (S.Context.hasSameType(ET, DestTy))
5300        return CK_FloatingComplexToReal;
5301      Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
5302      return CK_FloatingCast;
5303    }
5304    case Type::STK_Bool:
5305      return CK_FloatingComplexToBoolean;
5306    case Type::STK_Integral:
5307      Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5308                                CK_FloatingComplexToReal);
5309      return CK_FloatingToIntegral;
5310    case Type::STK_Pointer:
5311      llvm_unreachable("valid complex float->pointer cast?");
5312    case Type::STK_MemberPointer:
5313      llvm_unreachable("member pointer type in C");
5314    }
5315    break;
5316
5317  case Type::STK_IntegralComplex:
5318    switch (DestTy->getScalarTypeKind()) {
5319    case Type::STK_FloatingComplex:
5320      return CK_IntegralComplexToFloatingComplex;
5321    case Type::STK_IntegralComplex:
5322      return CK_IntegralComplexCast;
5323    case Type::STK_Integral: {
5324      QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
5325      if (S.Context.hasSameType(ET, DestTy))
5326        return CK_IntegralComplexToReal;
5327      Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
5328      return CK_IntegralCast;
5329    }
5330    case Type::STK_Bool:
5331      return CK_IntegralComplexToBoolean;
5332    case Type::STK_Floating:
5333      Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5334                                CK_IntegralComplexToReal);
5335      return CK_IntegralToFloating;
5336    case Type::STK_Pointer:
5337      llvm_unreachable("valid complex int->pointer cast?");
5338    case Type::STK_MemberPointer:
5339      llvm_unreachable("member pointer type in C");
5340    }
5341    break;
5342  }
5343
5344  llvm_unreachable("Unhandled scalar cast");
5345  return CK_BitCast;
5346}
5347
5348/// CheckCastTypes - Check type constraints for casting between types.
5349ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5350                                Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5351                                CXXCastPath &BasePath, bool FunctionalStyle) {
5352  if (castExpr->getType() == Context.UnknownAnyTy)
5353    return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5354
5355  if (getLangOptions().CPlusPlus)
5356    return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5357                                          castExpr->getLocEnd()),
5358                              castType, VK, castExpr, Kind, BasePath,
5359                              FunctionalStyle);
5360
5361  assert(!castExpr->getType()->isPlaceholderType());
5362
5363  // We only support r-value casts in C.
5364  VK = VK_RValue;
5365
5366  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5367  // type needs to be scalar.
5368  if (castType->isVoidType()) {
5369    // We don't necessarily do lvalue-to-rvalue conversions on this.
5370    ExprResult castExprRes = IgnoredValueConversions(castExpr);
5371    if (castExprRes.isInvalid())
5372      return ExprError();
5373    castExpr = castExprRes.take();
5374
5375    // Cast to void allows any expr type.
5376    Kind = CK_ToVoid;
5377    return Owned(castExpr);
5378  }
5379
5380  ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5381  if (castExprRes.isInvalid())
5382    return ExprError();
5383  castExpr = castExprRes.take();
5384
5385  if (RequireCompleteType(TyR.getBegin(), castType,
5386                          diag::err_typecheck_cast_to_incomplete))
5387    return ExprError();
5388
5389  if (!castType->isScalarType() && !castType->isVectorType()) {
5390    if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
5391        (castType->isStructureType() || castType->isUnionType())) {
5392      // GCC struct/union extension: allow cast to self.
5393      // FIXME: Check that the cast destination type is complete.
5394      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5395        << castType << castExpr->getSourceRange();
5396      Kind = CK_NoOp;
5397      return Owned(castExpr);
5398    }
5399
5400    if (castType->isUnionType()) {
5401      // GCC cast to union extension
5402      RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
5403      RecordDecl::field_iterator Field, FieldEnd;
5404      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
5405           Field != FieldEnd; ++Field) {
5406        if (Context.hasSameUnqualifiedType(Field->getType(),
5407                                           castExpr->getType()) &&
5408            !Field->isUnnamedBitfield()) {
5409          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5410            << castExpr->getSourceRange();
5411          break;
5412        }
5413      }
5414      if (Field == FieldEnd) {
5415        Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5416          << castExpr->getType() << castExpr->getSourceRange();
5417        return ExprError();
5418      }
5419      Kind = CK_ToUnion;
5420      return Owned(castExpr);
5421    }
5422
5423    // Reject any other conversions to non-scalar types.
5424    Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5425      << castType << castExpr->getSourceRange();
5426    return ExprError();
5427  }
5428
5429  // The type we're casting to is known to be a scalar or vector.
5430
5431  // Require the operand to be a scalar or vector.
5432  if (!castExpr->getType()->isScalarType() &&
5433      !castExpr->getType()->isVectorType()) {
5434    Diag(castExpr->getLocStart(),
5435                diag::err_typecheck_expect_scalar_operand)
5436      << castExpr->getType() << castExpr->getSourceRange();
5437    return ExprError();
5438  }
5439
5440  if (castType->isExtVectorType())
5441    return CheckExtVectorCast(TyR, castType, castExpr, Kind);
5442
5443  if (castType->isVectorType()) {
5444    if (castType->getAs<VectorType>()->getVectorKind() ==
5445        VectorType::AltiVecVector &&
5446          (castExpr->getType()->isIntegerType() ||
5447           castExpr->getType()->isFloatingType())) {
5448      Kind = CK_VectorSplat;
5449      return Owned(castExpr);
5450    } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5451      return ExprError();
5452    } else
5453      return Owned(castExpr);
5454  }
5455  if (castExpr->getType()->isVectorType()) {
5456    if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5457      return ExprError();
5458    else
5459      return Owned(castExpr);
5460  }
5461
5462  // The source and target types are both scalars, i.e.
5463  //   - arithmetic types (fundamental, enum, and complex)
5464  //   - all kinds of pointers
5465  // Note that member pointers were filtered out with C++, above.
5466
5467  if (isa<ObjCSelectorExpr>(castExpr)) {
5468    Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5469    return ExprError();
5470  }
5471
5472  // If either type is a pointer, the other type has to be either an
5473  // integer or a pointer.
5474  if (!castType->isArithmeticType()) {
5475    QualType castExprType = castExpr->getType();
5476    if (!castExprType->isIntegralType(Context) &&
5477        castExprType->isArithmeticType()) {
5478      Diag(castExpr->getLocStart(),
5479           diag::err_cast_pointer_from_non_pointer_int)
5480        << castExprType << castExpr->getSourceRange();
5481      return ExprError();
5482    }
5483  } else if (!castExpr->getType()->isArithmeticType()) {
5484    if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5485      Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
5486        << castType << castExpr->getSourceRange();
5487      return ExprError();
5488    }
5489  }
5490
5491  castExprRes = Owned(castExpr);
5492  Kind = PrepareScalarCast(*this, castExprRes, castType);
5493  if (castExprRes.isInvalid())
5494    return ExprError();
5495  castExpr = castExprRes.take();
5496
5497  if (Kind == CK_BitCast)
5498    CheckCastAlign(castExpr, castType, TyR);
5499
5500  return Owned(castExpr);
5501}
5502
5503bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5504                           CastKind &Kind) {
5505  assert(VectorTy->isVectorType() && "Not a vector type!");
5506
5507  if (Ty->isVectorType() || Ty->isIntegerType()) {
5508    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
5509      return Diag(R.getBegin(),
5510                  Ty->isVectorType() ?
5511                  diag::err_invalid_conversion_between_vectors :
5512                  diag::err_invalid_conversion_between_vector_and_integer)
5513        << VectorTy << Ty << R;
5514  } else
5515    return Diag(R.getBegin(),
5516                diag::err_invalid_conversion_between_vector_and_scalar)
5517      << VectorTy << Ty << R;
5518
5519  Kind = CK_BitCast;
5520  return false;
5521}
5522
5523ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5524                                    Expr *CastExpr, CastKind &Kind) {
5525  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5526
5527  QualType SrcTy = CastExpr->getType();
5528
5529  // If SrcTy is a VectorType, the total size must match to explicitly cast to
5530  // an ExtVectorType.
5531  if (SrcTy->isVectorType()) {
5532    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5533      Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5534        << DestTy << SrcTy << R;
5535      return ExprError();
5536    }
5537    Kind = CK_BitCast;
5538    return Owned(CastExpr);
5539  }
5540
5541  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5542  // conversion will take place first from scalar to elt type, and then
5543  // splat from elt type to vector.
5544  if (SrcTy->isPointerType())
5545    return Diag(R.getBegin(),
5546                diag::err_invalid_conversion_between_vector_and_scalar)
5547      << DestTy << SrcTy << R;
5548
5549  QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5550  ExprResult CastExprRes = Owned(CastExpr);
5551  CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5552  if (CastExprRes.isInvalid())
5553    return ExprError();
5554  CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
5555
5556  Kind = CK_VectorSplat;
5557  return Owned(CastExpr);
5558}
5559
5560ExprResult
5561Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
5562                    SourceLocation RParenLoc, Expr *castExpr) {
5563  assert((Ty != 0) && (castExpr != 0) &&
5564         "ActOnCastExpr(): missing type or expr");
5565
5566  TypeSourceInfo *castTInfo;
5567  QualType castType = GetTypeFromParser(Ty, &castTInfo);
5568  if (!castTInfo)
5569    castTInfo = Context.getTrivialTypeSourceInfo(castType);
5570
5571  // If the Expr being casted is a ParenListExpr, handle it specially.
5572  if (isa<ParenListExpr>(castExpr))
5573    return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
5574                                    castTInfo);
5575
5576  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
5577}
5578
5579ExprResult
5580Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
5581                          SourceLocation RParenLoc, Expr *castExpr) {
5582  CastKind Kind = CK_Invalid;
5583  ExprValueKind VK = VK_RValue;
5584  CXXCastPath BasePath;
5585  ExprResult CastResult =
5586    CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5587                   Kind, VK, BasePath);
5588  if (CastResult.isInvalid())
5589    return ExprError();
5590  castExpr = CastResult.take();
5591
5592  return Owned(CStyleCastExpr::Create(Context,
5593                                      Ty->getType().getNonLValueExprType(Context),
5594                                      VK, Kind, castExpr, &BasePath, Ty,
5595                                      LParenLoc, RParenLoc));
5596}
5597
5598/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5599/// of comma binary operators.
5600ExprResult
5601Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
5602  ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5603  if (!E)
5604    return Owned(expr);
5605
5606  ExprResult Result(E->getExpr(0));
5607
5608  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5609    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5610                        E->getExpr(i));
5611
5612  if (Result.isInvalid()) return ExprError();
5613
5614  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5615}
5616
5617ExprResult
5618Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
5619                               SourceLocation RParenLoc, Expr *Op,
5620                               TypeSourceInfo *TInfo) {
5621  ParenListExpr *PE = cast<ParenListExpr>(Op);
5622  QualType Ty = TInfo->getType();
5623  bool isVectorLiteral = false;
5624
5625  // Check for an altivec or OpenCL literal,
5626  // i.e. all the elements are integer constants.
5627  if (getLangOptions().AltiVec && Ty->isVectorType()) {
5628    if (PE->getNumExprs() == 0) {
5629      Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5630      return ExprError();
5631    }
5632    if (PE->getNumExprs() == 1) {
5633      if (!PE->getExpr(0)->getType()->isVectorType())
5634        isVectorLiteral = true;
5635    }
5636    else
5637      isVectorLiteral = true;
5638  }
5639
5640  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5641  // then handle it as such.
5642  if (isVectorLiteral) {
5643    llvm::SmallVector<Expr *, 8> initExprs;
5644    // '(...)' form of vector initialization in AltiVec: the number of
5645    // initializers must be one or must match the size of the vector.
5646    // If a single value is specified in the initializer then it will be
5647    // replicated to all the components of the vector
5648    if (Ty->getAs<VectorType>()->getVectorKind() ==
5649        VectorType::AltiVecVector) {
5650      unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5651      // The number of initializers must be one or must match the size of the
5652      // vector. If a single value is specified in the initializer then it will
5653      // be replicated to all the components of the vector
5654      if (PE->getNumExprs() == 1) {
5655        QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5656        ExprResult Literal = Owned(PE->getExpr(0));
5657        Literal = ImpCastExprToType(Literal.take(), ElemTy,
5658                                    PrepareScalarCast(*this, Literal, ElemTy));
5659        return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5660      }
5661      else if (PE->getNumExprs() < numElems) {
5662        Diag(PE->getExprLoc(),
5663             diag::err_incorrect_number_of_vector_initializers);
5664        return ExprError();
5665      }
5666      else
5667        for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5668          initExprs.push_back(PE->getExpr(i));
5669    }
5670    else
5671      for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5672        initExprs.push_back(PE->getExpr(i));
5673
5674    // FIXME: This means that pretty-printing the final AST will produce curly
5675    // braces instead of the original commas.
5676    InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5677                                                 &initExprs[0],
5678                                                 initExprs.size(), RParenLoc);
5679    E->setType(Ty);
5680    return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
5681  } else {
5682    // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5683    // sequence of BinOp comma operators.
5684    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
5685    if (Result.isInvalid()) return ExprError();
5686    return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
5687  }
5688}
5689
5690ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
5691                                                  SourceLocation R,
5692                                                  MultiExprArg Val,
5693                                                  ParsedType TypeOfCast) {
5694  unsigned nexprs = Val.size();
5695  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
5696  assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5697  Expr *expr;
5698  if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5699    expr = new (Context) ParenExpr(L, R, exprs[0]);
5700  else
5701    expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
5702  return Owned(expr);
5703}
5704
5705/// \brief Emit a specialized diagnostic when one expression is a null pointer
5706/// constant and the other is not a pointer.
5707bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5708                                      SourceLocation QuestionLoc) {
5709  Expr *NullExpr = LHS;
5710  Expr *NonPointerExpr = RHS;
5711  Expr::NullPointerConstantKind NullKind =
5712      NullExpr->isNullPointerConstant(Context,
5713                                      Expr::NPC_ValueDependentIsNotNull);
5714
5715  if (NullKind == Expr::NPCK_NotNull) {
5716    NullExpr = RHS;
5717    NonPointerExpr = LHS;
5718    NullKind =
5719        NullExpr->isNullPointerConstant(Context,
5720                                        Expr::NPC_ValueDependentIsNotNull);
5721  }
5722
5723  if (NullKind == Expr::NPCK_NotNull)
5724    return false;
5725
5726  if (NullKind == Expr::NPCK_ZeroInteger) {
5727    // In this case, check to make sure that we got here from a "NULL"
5728    // string in the source code.
5729    NullExpr = NullExpr->IgnoreParenImpCasts();
5730    SourceLocation loc = NullExpr->getExprLoc();
5731    if (!findMacroSpelling(loc, "NULL"))
5732      return false;
5733  }
5734
5735  int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5736  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5737      << NonPointerExpr->getType() << DiagType
5738      << NonPointerExpr->getSourceRange();
5739  return true;
5740}
5741
5742/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5743/// In that case, lhs = cond.
5744/// C99 6.5.15
5745QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
5746                                        ExprValueKind &VK, ExprObjectKind &OK,
5747                                        SourceLocation QuestionLoc) {
5748
5749  ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
5750  if (!lhsResult.isUsable()) return QualType();
5751  LHS = move(lhsResult);
5752
5753  ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
5754  if (!rhsResult.isUsable()) return QualType();
5755  RHS = move(rhsResult);
5756
5757  // C++ is sufficiently different to merit its own checker.
5758  if (getLangOptions().CPlusPlus)
5759    return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5760
5761  VK = VK_RValue;
5762  OK = OK_Ordinary;
5763
5764  Cond = UsualUnaryConversions(Cond.take());
5765  if (Cond.isInvalid())
5766    return QualType();
5767  LHS = UsualUnaryConversions(LHS.take());
5768  if (LHS.isInvalid())
5769    return QualType();
5770  RHS = UsualUnaryConversions(RHS.take());
5771  if (RHS.isInvalid())
5772    return QualType();
5773
5774  QualType CondTy = Cond.get()->getType();
5775  QualType LHSTy = LHS.get()->getType();
5776  QualType RHSTy = RHS.get()->getType();
5777
5778  // first, check the condition.
5779  if (!CondTy->isScalarType()) { // C99 6.5.15p2
5780    // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5781    // Throw an error if its not either.
5782    if (getLangOptions().OpenCL) {
5783      if (!CondTy->isVectorType()) {
5784        Diag(Cond.get()->getLocStart(),
5785             diag::err_typecheck_cond_expect_scalar_or_vector)
5786          << CondTy;
5787        return QualType();
5788      }
5789    }
5790    else {
5791      Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5792        << CondTy;
5793      return QualType();
5794    }
5795  }
5796
5797  // Now check the two expressions.
5798  if (LHSTy->isVectorType() || RHSTy->isVectorType())
5799    return CheckVectorOperands(QuestionLoc, LHS, RHS);
5800
5801  // OpenCL: If the condition is a vector, and both operands are scalar,
5802  // attempt to implicity convert them to the vector type to act like the
5803  // built in select.
5804  if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5805    // Both operands should be of scalar type.
5806    if (!LHSTy->isScalarType()) {
5807      Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5808        << CondTy;
5809      return QualType();
5810    }
5811    if (!RHSTy->isScalarType()) {
5812      Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5813        << CondTy;
5814      return QualType();
5815    }
5816    // Implicity convert these scalars to the type of the condition.
5817    LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5818    RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5819  }
5820
5821  // If both operands have arithmetic type, do the usual arithmetic conversions
5822  // to find a common type: C99 6.5.15p3,5.
5823  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5824    UsualArithmeticConversions(LHS, RHS);
5825    if (LHS.isInvalid() || RHS.isInvalid())
5826      return QualType();
5827    return LHS.get()->getType();
5828  }
5829
5830  // If both operands are the same structure or union type, the result is that
5831  // type.
5832  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5833    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5834      if (LHSRT->getDecl() == RHSRT->getDecl())
5835        // "If both the operands have structure or union type, the result has
5836        // that type."  This implies that CV qualifiers are dropped.
5837        return LHSTy.getUnqualifiedType();
5838    // FIXME: Type of conditional expression must be complete in C mode.
5839  }
5840
5841  // C99 6.5.15p5: "If both operands have void type, the result has void type."
5842  // The following || allows only one side to be void (a GCC-ism).
5843  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5844    if (!LHSTy->isVoidType())
5845      Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5846        << RHS.get()->getSourceRange();
5847    if (!RHSTy->isVoidType())
5848      Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5849        << LHS.get()->getSourceRange();
5850    LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5851    RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
5852    return Context.VoidTy;
5853  }
5854  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5855  // the type of the other operand."
5856  if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
5857      RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5858    // promote the null to a pointer.
5859    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
5860    return LHSTy;
5861  }
5862  if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
5863      LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5864    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
5865    return RHSTy;
5866  }
5867
5868  // All objective-c pointer type analysis is done here.
5869  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5870                                                        QuestionLoc);
5871  if (LHS.isInvalid() || RHS.isInvalid())
5872    return QualType();
5873  if (!compositeType.isNull())
5874    return compositeType;
5875
5876
5877  // Handle block pointer types.
5878  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5879    if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5880      if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5881        QualType destType = Context.getPointerType(Context.VoidTy);
5882        LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5883        RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5884        return destType;
5885      }
5886      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5887      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5888      return QualType();
5889    }
5890    // We have 2 block pointer types.
5891    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5892      // Two identical block pointer types are always compatible.
5893      return LHSTy;
5894    }
5895    // The block pointer types aren't identical, continue checking.
5896    QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5897    QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
5898
5899    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5900                                    rhptee.getUnqualifiedType())) {
5901      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5902      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5903      // In this situation, we assume void* type. No especially good
5904      // reason, but this is what gcc does, and we do have to pick
5905      // to get a consistent AST.
5906      QualType incompatTy = Context.getPointerType(Context.VoidTy);
5907      LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5908      RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5909      return incompatTy;
5910    }
5911    // The block pointer types are compatible.
5912    LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5913    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5914    return LHSTy;
5915  }
5916
5917  // Check constraints for C object pointers types (C99 6.5.15p3,6).
5918  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5919    // get the "pointed to" types
5920    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5921    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5922
5923    // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5924    if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5925      // Figure out necessary qualifiers (C99 6.5.15p6)
5926      QualType destPointee
5927        = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5928      QualType destType = Context.getPointerType(destPointee);
5929      // Add qualifiers if necessary.
5930      LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5931      // Promote to void*.
5932      RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5933      return destType;
5934    }
5935    if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5936      QualType destPointee
5937        = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5938      QualType destType = Context.getPointerType(destPointee);
5939      // Add qualifiers if necessary.
5940      RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5941      // Promote to void*.
5942      LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5943      return destType;
5944    }
5945
5946    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5947      // Two identical pointer types are always compatible.
5948      return LHSTy;
5949    }
5950    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5951                                    rhptee.getUnqualifiedType())) {
5952      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5953        << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5954      // In this situation, we assume void* type. No especially good
5955      // reason, but this is what gcc does, and we do have to pick
5956      // to get a consistent AST.
5957      QualType incompatTy = Context.getPointerType(Context.VoidTy);
5958      LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5959      RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5960      return incompatTy;
5961    }
5962    // The pointer types are compatible.
5963    // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5964    // differently qualified versions of compatible types, the result type is
5965    // a pointer to an appropriately qualified version of the *composite*
5966    // type.
5967    // FIXME: Need to calculate the composite type.
5968    // FIXME: Need to add qualifiers
5969    LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5970    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5971    return LHSTy;
5972  }
5973
5974  // GCC compatibility: soften pointer/integer mismatch.  Note that
5975  // null pointers have been filtered out by this point.
5976  if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5977    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5978      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5979    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
5980    return RHSTy;
5981  }
5982  if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5983    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5984      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5985    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
5986    return LHSTy;
5987  }
5988
5989  // Emit a better diagnostic if one of the expressions is a null pointer
5990  // constant and the other is not a pointer type. In this case, the user most
5991  // likely forgot to take the address of the other expression.
5992  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5993    return QualType();
5994
5995  // Otherwise, the operands are not compatible.
5996  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5997    << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5998  return QualType();
5999}
6000
6001/// FindCompositeObjCPointerType - Helper method to find composite type of
6002/// two objective-c pointer types of the two input expressions.
6003QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6004                                        SourceLocation QuestionLoc) {
6005  QualType LHSTy = LHS.get()->getType();
6006  QualType RHSTy = RHS.get()->getType();
6007
6008  // Handle things like Class and struct objc_class*.  Here we case the result
6009  // to the pseudo-builtin, because that will be implicitly cast back to the
6010  // redefinition type if an attempt is made to access its fields.
6011  if (LHSTy->isObjCClassType() &&
6012      (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
6013    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
6014    return LHSTy;
6015  }
6016  if (RHSTy->isObjCClassType() &&
6017      (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
6018    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
6019    return RHSTy;
6020  }
6021  // And the same for struct objc_object* / id
6022  if (LHSTy->isObjCIdType() &&
6023      (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
6024    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
6025    return LHSTy;
6026  }
6027  if (RHSTy->isObjCIdType() &&
6028      (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
6029    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
6030    return RHSTy;
6031  }
6032  // And the same for struct objc_selector* / SEL
6033  if (Context.isObjCSelType(LHSTy) &&
6034      (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
6035    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
6036    return LHSTy;
6037  }
6038  if (Context.isObjCSelType(RHSTy) &&
6039      (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
6040    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
6041    return RHSTy;
6042  }
6043  // Check constraints for Objective-C object pointers types.
6044  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6045
6046    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6047      // Two identical object pointer types are always compatible.
6048      return LHSTy;
6049    }
6050    const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6051    const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6052    QualType compositeType = LHSTy;
6053
6054    // If both operands are interfaces and either operand can be
6055    // assigned to the other, use that type as the composite
6056    // type. This allows
6057    //   xxx ? (A*) a : (B*) b
6058    // where B is a subclass of A.
6059    //
6060    // Additionally, as for assignment, if either type is 'id'
6061    // allow silent coercion. Finally, if the types are
6062    // incompatible then make sure to use 'id' as the composite
6063    // type so the result is acceptable for sending messages to.
6064
6065    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6066    // It could return the composite type.
6067    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6068      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6069    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6070      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6071    } else if ((LHSTy->isObjCQualifiedIdType() ||
6072                RHSTy->isObjCQualifiedIdType()) &&
6073               Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6074      // Need to handle "id<xx>" explicitly.
6075      // GCC allows qualified id and any Objective-C type to devolve to
6076      // id. Currently localizing to here until clear this should be
6077      // part of ObjCQualifiedIdTypesAreCompatible.
6078      compositeType = Context.getObjCIdType();
6079    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6080      compositeType = Context.getObjCIdType();
6081    } else if (!(compositeType =
6082                 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6083      ;
6084    else {
6085      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6086      << LHSTy << RHSTy
6087      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6088      QualType incompatTy = Context.getObjCIdType();
6089      LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6090      RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
6091      return incompatTy;
6092    }
6093    // The object pointer types are compatible.
6094    LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6095    RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
6096    return compositeType;
6097  }
6098  // Check Objective-C object pointer types and 'void *'
6099  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6100    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6101    QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6102    QualType destPointee
6103    = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6104    QualType destType = Context.getPointerType(destPointee);
6105    // Add qualifiers if necessary.
6106    LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
6107    // Promote to void*.
6108    RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
6109    return destType;
6110  }
6111  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6112    QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6113    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6114    QualType destPointee
6115    = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6116    QualType destType = Context.getPointerType(destPointee);
6117    // Add qualifiers if necessary.
6118    RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
6119    // Promote to void*.
6120    LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
6121    return destType;
6122  }
6123  return QualType();
6124}
6125
6126/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6127/// in the case of a the GNU conditional expr extension.
6128ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6129                                    SourceLocation ColonLoc,
6130                                    Expr *CondExpr, Expr *LHSExpr,
6131                                    Expr *RHSExpr) {
6132  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6133  // was the condition.
6134  OpaqueValueExpr *opaqueValue = 0;
6135  Expr *commonExpr = 0;
6136  if (LHSExpr == 0) {
6137    commonExpr = CondExpr;
6138
6139    // We usually want to apply unary conversions *before* saving, except
6140    // in the special case of a C++ l-value conditional.
6141    if (!(getLangOptions().CPlusPlus
6142          && !commonExpr->isTypeDependent()
6143          && commonExpr->getValueKind() == RHSExpr->getValueKind()
6144          && commonExpr->isGLValue()
6145          && commonExpr->isOrdinaryOrBitFieldObject()
6146          && RHSExpr->isOrdinaryOrBitFieldObject()
6147          && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6148      ExprResult commonRes = UsualUnaryConversions(commonExpr);
6149      if (commonRes.isInvalid())
6150        return ExprError();
6151      commonExpr = commonRes.take();
6152    }
6153
6154    opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6155                                                commonExpr->getType(),
6156                                                commonExpr->getValueKind(),
6157                                                commonExpr->getObjectKind());
6158    LHSExpr = CondExpr = opaqueValue;
6159  }
6160
6161  ExprValueKind VK = VK_RValue;
6162  ExprObjectKind OK = OK_Ordinary;
6163  ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6164  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6165                                             VK, OK, QuestionLoc);
6166  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6167      RHS.isInvalid())
6168    return ExprError();
6169
6170  if (!commonExpr)
6171    return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6172                                                   LHS.take(), ColonLoc,
6173                                                   RHS.take(), result, VK, OK));
6174
6175  return Owned(new (Context)
6176    BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6177                              RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
6178}
6179
6180// checkPointerTypesForAssignment - This is a very tricky routine (despite
6181// being closely modeled after the C99 spec:-). The odd characteristic of this
6182// routine is it effectively iqnores the qualifiers on the top level pointee.
6183// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6184// FIXME: add a couple examples in this comment.
6185static Sema::AssignConvertType
6186checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6187  assert(lhsType.isCanonical() && "LHS not canonicalized!");
6188  assert(rhsType.isCanonical() && "RHS not canonicalized!");
6189
6190  // get the "pointed to" type (ignoring qualifiers at the top level)
6191  const Type *lhptee, *rhptee;
6192  Qualifiers lhq, rhq;
6193  llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6194  llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
6195
6196  Sema::AssignConvertType ConvTy = Sema::Compatible;
6197
6198  // C99 6.5.16.1p1: This following citation is common to constraints
6199  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6200  // qualifiers of the type *pointed to* by the right;
6201  Qualifiers lq;
6202
6203  if (!lhq.compatiblyIncludes(rhq)) {
6204    // Treat address-space mismatches as fatal.  TODO: address subspaces
6205    if (lhq.getAddressSpace() != rhq.getAddressSpace())
6206      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6207
6208    // It's okay to add or remove GC qualifiers when converting to
6209    // and from void*.
6210    else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6211             && (lhptee->isVoidType() || rhptee->isVoidType()))
6212      ; // keep old
6213
6214    // For GCC compatibility, other qualifier mismatches are treated
6215    // as still compatible in C.
6216    else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6217  }
6218
6219  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6220  // incomplete type and the other is a pointer to a qualified or unqualified
6221  // version of void...
6222  if (lhptee->isVoidType()) {
6223    if (rhptee->isIncompleteOrObjectType())
6224      return ConvTy;
6225
6226    // As an extension, we allow cast to/from void* to function pointer.
6227    assert(rhptee->isFunctionType());
6228    return Sema::FunctionVoidPointer;
6229  }
6230
6231  if (rhptee->isVoidType()) {
6232    if (lhptee->isIncompleteOrObjectType())
6233      return ConvTy;
6234
6235    // As an extension, we allow cast to/from void* to function pointer.
6236    assert(lhptee->isFunctionType());
6237    return Sema::FunctionVoidPointer;
6238  }
6239
6240  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6241  // unqualified versions of compatible types, ...
6242  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6243  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6244    // Check if the pointee types are compatible ignoring the sign.
6245    // We explicitly check for char so that we catch "char" vs
6246    // "unsigned char" on systems where "char" is unsigned.
6247    if (lhptee->isCharType())
6248      ltrans = S.Context.UnsignedCharTy;
6249    else if (lhptee->hasSignedIntegerRepresentation())
6250      ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6251
6252    if (rhptee->isCharType())
6253      rtrans = S.Context.UnsignedCharTy;
6254    else if (rhptee->hasSignedIntegerRepresentation())
6255      rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6256
6257    if (ltrans == rtrans) {
6258      // Types are compatible ignoring the sign. Qualifier incompatibility
6259      // takes priority over sign incompatibility because the sign
6260      // warning can be disabled.
6261      if (ConvTy != Sema::Compatible)
6262        return ConvTy;
6263
6264      return Sema::IncompatiblePointerSign;
6265    }
6266
6267    // If we are a multi-level pointer, it's possible that our issue is simply
6268    // one of qualification - e.g. char ** -> const char ** is not allowed. If
6269    // the eventual target type is the same and the pointers have the same
6270    // level of indirection, this must be the issue.
6271    if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6272      do {
6273        lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6274        rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6275      } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6276
6277      if (lhptee == rhptee)
6278        return Sema::IncompatibleNestedPointerQualifiers;
6279    }
6280
6281    // General pointer incompatibility takes priority over qualifiers.
6282    return Sema::IncompatiblePointer;
6283  }
6284  return ConvTy;
6285}
6286
6287/// checkBlockPointerTypesForAssignment - This routine determines whether two
6288/// block pointer types are compatible or whether a block and normal pointer
6289/// are compatible. It is more restrict than comparing two function pointer
6290// types.
6291static Sema::AssignConvertType
6292checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6293                                    QualType rhsType) {
6294  assert(lhsType.isCanonical() && "LHS not canonicalized!");
6295  assert(rhsType.isCanonical() && "RHS not canonicalized!");
6296
6297  QualType lhptee, rhptee;
6298
6299  // get the "pointed to" type (ignoring qualifiers at the top level)
6300  lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6301  rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
6302
6303  // In C++, the types have to match exactly.
6304  if (S.getLangOptions().CPlusPlus)
6305    return Sema::IncompatibleBlockPointer;
6306
6307  Sema::AssignConvertType ConvTy = Sema::Compatible;
6308
6309  // For blocks we enforce that qualifiers are identical.
6310  if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6311    ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6312
6313  if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6314    return Sema::IncompatibleBlockPointer;
6315
6316  return ConvTy;
6317}
6318
6319/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6320/// for assignment compatibility.
6321static Sema::AssignConvertType
6322checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6323  assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6324  assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6325
6326  if (lhsType->isObjCBuiltinType()) {
6327    // Class is not compatible with ObjC object pointers.
6328    if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6329        !rhsType->isObjCQualifiedClassType())
6330      return Sema::IncompatiblePointer;
6331    return Sema::Compatible;
6332  }
6333  if (rhsType->isObjCBuiltinType()) {
6334    // Class is not compatible with ObjC object pointers.
6335    if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6336        !lhsType->isObjCQualifiedClassType())
6337      return Sema::IncompatiblePointer;
6338    return Sema::Compatible;
6339  }
6340  QualType lhptee =
6341  lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
6342  QualType rhptee =
6343  rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
6344
6345  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6346    return Sema::CompatiblePointerDiscardsQualifiers;
6347
6348  if (S.Context.typesAreCompatible(lhsType, rhsType))
6349    return Sema::Compatible;
6350  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
6351    return Sema::IncompatibleObjCQualifiedId;
6352  return Sema::IncompatiblePointer;
6353}
6354
6355Sema::AssignConvertType
6356Sema::CheckAssignmentConstraints(SourceLocation Loc,
6357                                 QualType lhsType, QualType rhsType) {
6358  // Fake up an opaque expression.  We don't actually care about what
6359  // cast operations are required, so if CheckAssignmentConstraints
6360  // adds casts to this they'll be wasted, but fortunately that doesn't
6361  // usually happen on valid code.
6362  OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
6363  ExprResult rhsPtr = &rhs;
6364  CastKind K = CK_Invalid;
6365
6366  return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6367}
6368
6369/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6370/// has code to accommodate several GCC extensions when type checking
6371/// pointers. Here are some objectionable examples that GCC considers warnings:
6372///
6373///  int a, *pint;
6374///  short *pshort;
6375///  struct foo *pfoo;
6376///
6377///  pint = pshort; // warning: assignment from incompatible pointer type
6378///  a = pint; // warning: assignment makes integer from pointer without a cast
6379///  pint = a; // warning: assignment makes pointer from integer without a cast
6380///  pint = pfoo; // warning: assignment from incompatible pointer type
6381///
6382/// As a result, the code for dealing with pointers is more complex than the
6383/// C99 spec dictates.
6384///
6385/// Sets 'Kind' for any result kind except Incompatible.
6386Sema::AssignConvertType
6387Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
6388                                 CastKind &Kind) {
6389  QualType rhsType = rhs.get()->getType();
6390
6391  // Get canonical types.  We're not formatting these types, just comparing
6392  // them.
6393  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6394  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
6395
6396  // Common case: no conversion required.
6397  if (lhsType == rhsType) {
6398    Kind = CK_NoOp;
6399    return Compatible;
6400  }
6401
6402  // If the left-hand side is a reference type, then we are in a
6403  // (rare!) case where we've allowed the use of references in C,
6404  // e.g., as a parameter type in a built-in function. In this case,
6405  // just make sure that the type referenced is compatible with the
6406  // right-hand side type. The caller is responsible for adjusting
6407  // lhsType so that the resulting expression does not have reference
6408  // type.
6409  if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
6410    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6411      Kind = CK_LValueBitCast;
6412      return Compatible;
6413    }
6414    return Incompatible;
6415  }
6416
6417  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6418  // to the same ExtVector type.
6419  if (lhsType->isExtVectorType()) {
6420    if (rhsType->isExtVectorType())
6421      return Incompatible;
6422    if (rhsType->isArithmeticType()) {
6423      // CK_VectorSplat does T -> vector T, so first cast to the
6424      // element type.
6425      QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6426      if (elType != rhsType) {
6427        Kind = PrepareScalarCast(*this, rhs, elType);
6428        rhs = ImpCastExprToType(rhs.take(), elType, Kind);
6429      }
6430      Kind = CK_VectorSplat;
6431      return Compatible;
6432    }
6433  }
6434
6435  // Conversions to or from vector type.
6436  if (lhsType->isVectorType() || rhsType->isVectorType()) {
6437    if (lhsType->isVectorType() && rhsType->isVectorType()) {
6438      // Allow assignments of an AltiVec vector type to an equivalent GCC
6439      // vector type and vice versa
6440      if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6441        Kind = CK_BitCast;
6442        return Compatible;
6443      }
6444
6445      // If we are allowing lax vector conversions, and LHS and RHS are both
6446      // vectors, the total size only needs to be the same. This is a bitcast;
6447      // no bits are changed but the result type is different.
6448      if (getLangOptions().LaxVectorConversions &&
6449          (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
6450        Kind = CK_BitCast;
6451        return IncompatibleVectors;
6452      }
6453    }
6454    return Incompatible;
6455  }
6456
6457  // Arithmetic conversions.
6458  if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
6459      !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
6460    Kind = PrepareScalarCast(*this, rhs, lhsType);
6461    return Compatible;
6462  }
6463
6464  // Conversions to normal pointers.
6465  if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6466    // U* -> T*
6467    if (isa<PointerType>(rhsType)) {
6468      Kind = CK_BitCast;
6469      return checkPointerTypesForAssignment(*this, lhsType, rhsType);
6470    }
6471
6472    // int -> T*
6473    if (rhsType->isIntegerType()) {
6474      Kind = CK_IntegralToPointer; // FIXME: null?
6475      return IntToPointer;
6476    }
6477
6478    // C pointers are not compatible with ObjC object pointers,
6479    // with two exceptions:
6480    if (isa<ObjCObjectPointerType>(rhsType)) {
6481      //  - conversions to void*
6482      if (lhsPointer->getPointeeType()->isVoidType()) {
6483        Kind = CK_AnyPointerToObjCPointerCast;
6484        return Compatible;
6485      }
6486
6487      //  - conversions from 'Class' to the redefinition type
6488      if (rhsType->isObjCClassType() &&
6489          Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
6490        Kind = CK_BitCast;
6491        return Compatible;
6492      }
6493
6494      Kind = CK_BitCast;
6495      return IncompatiblePointer;
6496    }
6497
6498    // U^ -> void*
6499    if (rhsType->getAs<BlockPointerType>()) {
6500      if (lhsPointer->getPointeeType()->isVoidType()) {
6501        Kind = CK_BitCast;
6502        return Compatible;
6503      }
6504    }
6505
6506    return Incompatible;
6507  }
6508
6509  // Conversions to block pointers.
6510  if (isa<BlockPointerType>(lhsType)) {
6511    // U^ -> T^
6512    if (rhsType->isBlockPointerType()) {
6513      Kind = CK_AnyPointerToBlockPointerCast;
6514      return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
6515    }
6516
6517    // int or null -> T^
6518    if (rhsType->isIntegerType()) {
6519      Kind = CK_IntegralToPointer; // FIXME: null
6520      return IntToBlockPointer;
6521    }
6522
6523    // id -> T^
6524    if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6525      Kind = CK_AnyPointerToBlockPointerCast;
6526      return Compatible;
6527    }
6528
6529    // void* -> T^
6530    if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
6531      if (RHSPT->getPointeeType()->isVoidType()) {
6532        Kind = CK_AnyPointerToBlockPointerCast;
6533        return Compatible;
6534      }
6535
6536    return Incompatible;
6537  }
6538
6539  // Conversions to Objective-C pointers.
6540  if (isa<ObjCObjectPointerType>(lhsType)) {
6541    // A* -> B*
6542    if (rhsType->isObjCObjectPointerType()) {
6543      Kind = CK_BitCast;
6544      return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
6545    }
6546
6547    // int or null -> A*
6548    if (rhsType->isIntegerType()) {
6549      Kind = CK_IntegralToPointer; // FIXME: null
6550      return IntToPointer;
6551    }
6552
6553    // In general, C pointers are not compatible with ObjC object pointers,
6554    // with two exceptions:
6555    if (isa<PointerType>(rhsType)) {
6556      //  - conversions from 'void*'
6557      if (rhsType->isVoidPointerType()) {
6558        Kind = CK_AnyPointerToObjCPointerCast;
6559        return Compatible;
6560      }
6561
6562      //  - conversions to 'Class' from its redefinition type
6563      if (lhsType->isObjCClassType() &&
6564          Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6565        Kind = CK_BitCast;
6566        return Compatible;
6567      }
6568
6569      Kind = CK_AnyPointerToObjCPointerCast;
6570      return IncompatiblePointer;
6571    }
6572
6573    // T^ -> A*
6574    if (rhsType->isBlockPointerType()) {
6575      Kind = CK_AnyPointerToObjCPointerCast;
6576      return Compatible;
6577    }
6578
6579    return Incompatible;
6580  }
6581
6582  // Conversions from pointers that are not covered by the above.
6583  if (isa<PointerType>(rhsType)) {
6584    // T* -> _Bool
6585    if (lhsType == Context.BoolTy) {
6586      Kind = CK_PointerToBoolean;
6587      return Compatible;
6588    }
6589
6590    // T* -> int
6591    if (lhsType->isIntegerType()) {
6592      Kind = CK_PointerToIntegral;
6593      return PointerToInt;
6594    }
6595
6596    return Incompatible;
6597  }
6598
6599  // Conversions from Objective-C pointers that are not covered by the above.
6600  if (isa<ObjCObjectPointerType>(rhsType)) {
6601    // T* -> _Bool
6602    if (lhsType == Context.BoolTy) {
6603      Kind = CK_PointerToBoolean;
6604      return Compatible;
6605    }
6606
6607    // T* -> int
6608    if (lhsType->isIntegerType()) {
6609      Kind = CK_PointerToIntegral;
6610      return PointerToInt;
6611    }
6612
6613    return Incompatible;
6614  }
6615
6616  // struct A -> struct B
6617  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
6618    if (Context.typesAreCompatible(lhsType, rhsType)) {
6619      Kind = CK_NoOp;
6620      return Compatible;
6621    }
6622  }
6623
6624  return Incompatible;
6625}
6626
6627/// \brief Constructs a transparent union from an expression that is
6628/// used to initialize the transparent union.
6629static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
6630                                      QualType UnionType, FieldDecl *Field) {
6631  // Build an initializer list that designates the appropriate member
6632  // of the transparent union.
6633  Expr *E = EResult.take();
6634  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6635                                                   &E, 1,
6636                                                   SourceLocation());
6637  Initializer->setType(UnionType);
6638  Initializer->setInitializedFieldInUnion(Field);
6639
6640  // Build a compound literal constructing a value of the transparent
6641  // union type from this initializer list.
6642  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6643  EResult = S.Owned(
6644    new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6645                                VK_RValue, Initializer, false));
6646}
6647
6648Sema::AssignConvertType
6649Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6650  QualType FromType = rExpr.get()->getType();
6651
6652  // If the ArgType is a Union type, we want to handle a potential
6653  // transparent_union GCC extension.
6654  const RecordType *UT = ArgType->getAsUnionType();
6655  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6656    return Incompatible;
6657
6658  // The field to initialize within the transparent union.
6659  RecordDecl *UD = UT->getDecl();
6660  FieldDecl *InitField = 0;
6661  // It's compatible if the expression matches any of the fields.
6662  for (RecordDecl::field_iterator it = UD->field_begin(),
6663         itend = UD->field_end();
6664       it != itend; ++it) {
6665    if (it->getType()->isPointerType()) {
6666      // If the transparent union contains a pointer type, we allow:
6667      // 1) void pointer
6668      // 2) null pointer constant
6669      if (FromType->isPointerType())
6670        if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
6671          rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
6672          InitField = *it;
6673          break;
6674        }
6675
6676      if (rExpr.get()->isNullPointerConstant(Context,
6677                                       Expr::NPC_ValueDependentIsNull)) {
6678        rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
6679        InitField = *it;
6680        break;
6681      }
6682    }
6683
6684    CastKind Kind = CK_Invalid;
6685    if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
6686          == Compatible) {
6687      rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
6688      InitField = *it;
6689      break;
6690    }
6691  }
6692
6693  if (!InitField)
6694    return Incompatible;
6695
6696  ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
6697  return Compatible;
6698}
6699
6700Sema::AssignConvertType
6701Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
6702  if (getLangOptions().CPlusPlus) {
6703    if (!lhsType->isRecordType()) {
6704      // C++ 5.17p3: If the left operand is not of class type, the
6705      // expression is implicitly converted (C++ 4) to the
6706      // cv-unqualified type of the left operand.
6707      ExprResult Res = PerformImplicitConversion(rExpr.get(),
6708                                                 lhsType.getUnqualifiedType(),
6709                                                 AA_Assigning);
6710      if (Res.isInvalid())
6711        return Incompatible;
6712      rExpr = move(Res);
6713      return Compatible;
6714    }
6715
6716    // FIXME: Currently, we fall through and treat C++ classes like C
6717    // structures.
6718  }
6719
6720  // C99 6.5.16.1p1: the left operand is a pointer and the right is
6721  // a null pointer constant.
6722  if ((lhsType->isPointerType() ||
6723       lhsType->isObjCObjectPointerType() ||
6724       lhsType->isBlockPointerType())
6725      && rExpr.get()->isNullPointerConstant(Context,
6726                                      Expr::NPC_ValueDependentIsNull)) {
6727    rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
6728    return Compatible;
6729  }
6730
6731  // This check seems unnatural, however it is necessary to ensure the proper
6732  // conversion of functions/arrays. If the conversion were done for all
6733  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6734  // expressions that suppress this implicit conversion (&, sizeof).
6735  //
6736  // Suppress this for references: C++ 8.5.3p5.
6737  if (!lhsType->isReferenceType()) {
6738    rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6739    if (rExpr.isInvalid())
6740      return Incompatible;
6741  }
6742
6743  CastKind Kind = CK_Invalid;
6744  Sema::AssignConvertType result =
6745    CheckAssignmentConstraints(lhsType, rExpr, Kind);
6746
6747  // C99 6.5.16.1p2: The value of the right operand is converted to the
6748  // type of the assignment expression.
6749  // CheckAssignmentConstraints allows the left-hand side to be a reference,
6750  // so that we can use references in built-in functions even in C.
6751  // The getNonReferenceType() call makes sure that the resulting expression
6752  // does not have reference type.
6753  if (result != Incompatible && rExpr.get()->getType() != lhsType)
6754    rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
6755  return result;
6756}
6757
6758QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
6759  Diag(Loc, diag::err_typecheck_invalid_operands)
6760    << lex.get()->getType() << rex.get()->getType()
6761    << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6762  return QualType();
6763}
6764
6765QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
6766  // For conversion purposes, we ignore any qualifiers.
6767  // For example, "const float" and "float" are equivalent.
6768  QualType lhsType =
6769    Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
6770  QualType rhsType =
6771    Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
6772
6773  // If the vector types are identical, return.
6774  if (lhsType == rhsType)
6775    return lhsType;
6776
6777  // Handle the case of a vector & extvector type of the same size and element
6778  // type.  It would be nice if we only had one vector type someday.
6779  if (getLangOptions().LaxVectorConversions) {
6780    if (const VectorType *LV = lhsType->getAs<VectorType>()) {
6781      if (const VectorType *RV = rhsType->getAs<VectorType>()) {
6782        if (LV->getElementType() == RV->getElementType() &&
6783            LV->getNumElements() == RV->getNumElements()) {
6784          if (lhsType->isExtVectorType()) {
6785            rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
6786            return lhsType;
6787          }
6788
6789          lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
6790          return rhsType;
6791        } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6792          // If we are allowing lax vector conversions, and LHS and RHS are both
6793          // vectors, the total size only needs to be the same. This is a
6794          // bitcast; no bits are changed but the result type is different.
6795          rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
6796          return lhsType;
6797        }
6798      }
6799    }
6800  }
6801
6802  // Handle the case of equivalent AltiVec and GCC vector types
6803  if (lhsType->isVectorType() && rhsType->isVectorType() &&
6804      Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6805    lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
6806    return rhsType;
6807  }
6808
6809  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6810  // swap back (so that we don't reverse the inputs to a subtract, for instance.
6811  bool swapped = false;
6812  if (rhsType->isExtVectorType()) {
6813    swapped = true;
6814    std::swap(rex, lex);
6815    std::swap(rhsType, lhsType);
6816  }
6817
6818  // Handle the case of an ext vector and scalar.
6819  if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
6820    QualType EltTy = LV->getElementType();
6821    if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
6822      int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6823      if (order > 0)
6824        rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
6825      if (order >= 0) {
6826        rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
6827        if (swapped) std::swap(rex, lex);
6828        return lhsType;
6829      }
6830    }
6831    if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6832        rhsType->isRealFloatingType()) {
6833      int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6834      if (order > 0)
6835        rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
6836      if (order >= 0) {
6837        rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
6838        if (swapped) std::swap(rex, lex);
6839        return lhsType;
6840      }
6841    }
6842  }
6843
6844  // Vectors of different size or scalar and non-ext-vector are errors.
6845  Diag(Loc, diag::err_typecheck_vector_not_convertable)
6846    << lex.get()->getType() << rex.get()->getType()
6847    << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6848  return QualType();
6849}
6850
6851QualType Sema::CheckMultiplyDivideOperands(
6852  ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6853  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
6854    return CheckVectorOperands(Loc, lex, rex);
6855
6856  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6857  if (lex.isInvalid() || rex.isInvalid())
6858    return QualType();
6859
6860  if (!lex.get()->getType()->isArithmeticType() ||
6861      !rex.get()->getType()->isArithmeticType())
6862    return InvalidOperands(Loc, lex, rex);
6863
6864  // Check for division by zero.
6865  if (isDiv &&
6866      rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6867    DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6868                                     << rex.get()->getSourceRange());
6869
6870  return compType;
6871}
6872
6873QualType Sema::CheckRemainderOperands(
6874  ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6875  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6876    if (lex.get()->getType()->hasIntegerRepresentation() &&
6877        rex.get()->getType()->hasIntegerRepresentation())
6878      return CheckVectorOperands(Loc, lex, rex);
6879    return InvalidOperands(Loc, lex, rex);
6880  }
6881
6882  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6883  if (lex.isInvalid() || rex.isInvalid())
6884    return QualType();
6885
6886  if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
6887    return InvalidOperands(Loc, lex, rex);
6888
6889  // Check for remainder by zero.
6890  if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6891    DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6892                                 << rex.get()->getSourceRange());
6893
6894  return compType;
6895}
6896
6897QualType Sema::CheckAdditionOperands( // C99 6.5.6
6898  ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6899  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6900    QualType compType = CheckVectorOperands(Loc, lex, rex);
6901    if (CompLHSTy) *CompLHSTy = compType;
6902    return compType;
6903  }
6904
6905  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
6906  if (lex.isInvalid() || rex.isInvalid())
6907    return QualType();
6908
6909  // handle the common case first (both operands are arithmetic).
6910  if (lex.get()->getType()->isArithmeticType() &&
6911      rex.get()->getType()->isArithmeticType()) {
6912    if (CompLHSTy) *CompLHSTy = compType;
6913    return compType;
6914  }
6915
6916  // Put any potential pointer into PExp
6917  Expr* PExp = lex.get(), *IExp = rex.get();
6918  if (IExp->getType()->isAnyPointerType())
6919    std::swap(PExp, IExp);
6920
6921  if (PExp->getType()->isAnyPointerType()) {
6922
6923    if (IExp->getType()->isIntegerType()) {
6924      QualType PointeeTy = PExp->getType()->getPointeeType();
6925
6926      // Check for arithmetic on pointers to incomplete types.
6927      if (PointeeTy->isVoidType()) {
6928        if (getLangOptions().CPlusPlus) {
6929          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6930            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6931          return QualType();
6932        }
6933
6934        // GNU extension: arithmetic on pointer to void
6935        Diag(Loc, diag::ext_gnu_void_ptr)
6936          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6937      } else if (PointeeTy->isFunctionType()) {
6938        if (getLangOptions().CPlusPlus) {
6939          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6940            << lex.get()->getType() << lex.get()->getSourceRange();
6941          return QualType();
6942        }
6943
6944        // GNU extension: arithmetic on pointer to function
6945        Diag(Loc, diag::ext_gnu_ptr_func_arith)
6946          << lex.get()->getType() << lex.get()->getSourceRange();
6947      } else {
6948        // Check if we require a complete type.
6949        if (((PExp->getType()->isPointerType() &&
6950              !PExp->getType()->isDependentType()) ||
6951              PExp->getType()->isObjCObjectPointerType()) &&
6952             RequireCompleteType(Loc, PointeeTy,
6953                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6954                             << PExp->getSourceRange()
6955                             << PExp->getType()))
6956          return QualType();
6957      }
6958      // Diagnose bad cases where we step over interface counts.
6959      if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6960        Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6961          << PointeeTy << PExp->getSourceRange();
6962        return QualType();
6963      }
6964
6965      if (CompLHSTy) {
6966        QualType LHSTy = Context.isPromotableBitField(lex.get());
6967        if (LHSTy.isNull()) {
6968          LHSTy = lex.get()->getType();
6969          if (LHSTy->isPromotableIntegerType())
6970            LHSTy = Context.getPromotedIntegerType(LHSTy);
6971        }
6972        *CompLHSTy = LHSTy;
6973      }
6974      return PExp->getType();
6975    }
6976  }
6977
6978  return InvalidOperands(Loc, lex, rex);
6979}
6980
6981// C99 6.5.6
6982QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
6983                                        SourceLocation Loc, QualType* CompLHSTy) {
6984  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6985    QualType compType = CheckVectorOperands(Loc, lex, rex);
6986    if (CompLHSTy) *CompLHSTy = compType;
6987    return compType;
6988  }
6989
6990  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
6991  if (lex.isInvalid() || rex.isInvalid())
6992    return QualType();
6993
6994  // Enforce type constraints: C99 6.5.6p3.
6995
6996  // Handle the common case first (both operands are arithmetic).
6997  if (lex.get()->getType()->isArithmeticType() &&
6998      rex.get()->getType()->isArithmeticType()) {
6999    if (CompLHSTy) *CompLHSTy = compType;
7000    return compType;
7001  }
7002
7003  // Either ptr - int   or   ptr - ptr.
7004  if (lex.get()->getType()->isAnyPointerType()) {
7005    QualType lpointee = lex.get()->getType()->getPointeeType();
7006
7007    // The LHS must be an completely-defined object type.
7008
7009    bool ComplainAboutVoid = false;
7010    Expr *ComplainAboutFunc = 0;
7011    if (lpointee->isVoidType()) {
7012      if (getLangOptions().CPlusPlus) {
7013        Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
7014          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7015        return QualType();
7016      }
7017
7018      // GNU C extension: arithmetic on pointer to void
7019      ComplainAboutVoid = true;
7020    } else if (lpointee->isFunctionType()) {
7021      if (getLangOptions().CPlusPlus) {
7022        Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
7023          << lex.get()->getType() << lex.get()->getSourceRange();
7024        return QualType();
7025      }
7026
7027      // GNU C extension: arithmetic on pointer to function
7028      ComplainAboutFunc = lex.get();
7029    } else if (!lpointee->isDependentType() &&
7030               RequireCompleteType(Loc, lpointee,
7031                                   PDiag(diag::err_typecheck_sub_ptr_object)
7032                                     << lex.get()->getSourceRange()
7033                                     << lex.get()->getType()))
7034      return QualType();
7035
7036    // Diagnose bad cases where we step over interface counts.
7037    if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
7038      Diag(Loc, diag::err_arithmetic_nonfragile_interface)
7039        << lpointee << lex.get()->getSourceRange();
7040      return QualType();
7041    }
7042
7043    // The result type of a pointer-int computation is the pointer type.
7044    if (rex.get()->getType()->isIntegerType()) {
7045      if (ComplainAboutVoid)
7046        Diag(Loc, diag::ext_gnu_void_ptr)
7047          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7048      if (ComplainAboutFunc)
7049        Diag(Loc, diag::ext_gnu_ptr_func_arith)
7050          << ComplainAboutFunc->getType()
7051          << ComplainAboutFunc->getSourceRange();
7052
7053      if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7054      return lex.get()->getType();
7055    }
7056
7057    // Handle pointer-pointer subtractions.
7058    if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
7059      QualType rpointee = RHSPTy->getPointeeType();
7060
7061      // RHS must be a completely-type object type.
7062      // Handle the GNU void* extension.
7063      if (rpointee->isVoidType()) {
7064        if (getLangOptions().CPlusPlus) {
7065          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
7066            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7067          return QualType();
7068        }
7069
7070        ComplainAboutVoid = true;
7071      } else if (rpointee->isFunctionType()) {
7072        if (getLangOptions().CPlusPlus) {
7073          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
7074            << rex.get()->getType() << rex.get()->getSourceRange();
7075          return QualType();
7076        }
7077
7078        // GNU extension: arithmetic on pointer to function
7079        if (!ComplainAboutFunc)
7080          ComplainAboutFunc = rex.get();
7081      } else if (!rpointee->isDependentType() &&
7082                 RequireCompleteType(Loc, rpointee,
7083                                     PDiag(diag::err_typecheck_sub_ptr_object)
7084                                       << rex.get()->getSourceRange()
7085                                       << rex.get()->getType()))
7086        return QualType();
7087
7088      if (getLangOptions().CPlusPlus) {
7089        // Pointee types must be the same: C++ [expr.add]
7090        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7091          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7092            << lex.get()->getType() << rex.get()->getType()
7093            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7094          return QualType();
7095        }
7096      } else {
7097        // Pointee types must be compatible C99 6.5.6p3
7098        if (!Context.typesAreCompatible(
7099                Context.getCanonicalType(lpointee).getUnqualifiedType(),
7100                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7101          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7102            << lex.get()->getType() << rex.get()->getType()
7103            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7104          return QualType();
7105        }
7106      }
7107
7108      if (ComplainAboutVoid)
7109        Diag(Loc, diag::ext_gnu_void_ptr)
7110          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7111      if (ComplainAboutFunc)
7112        Diag(Loc, diag::ext_gnu_ptr_func_arith)
7113          << ComplainAboutFunc->getType()
7114          << ComplainAboutFunc->getSourceRange();
7115
7116      if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7117      return Context.getPointerDiffType();
7118    }
7119  }
7120
7121  return InvalidOperands(Loc, lex, rex);
7122}
7123
7124static bool isScopedEnumerationType(QualType T) {
7125  if (const EnumType *ET = dyn_cast<EnumType>(T))
7126    return ET->getDecl()->isScoped();
7127  return false;
7128}
7129
7130static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
7131                                   SourceLocation Loc, unsigned Opc,
7132                                   QualType LHSTy) {
7133  llvm::APSInt Right;
7134  // Check right/shifter operand
7135  if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
7136    return;
7137
7138  if (Right.isNegative()) {
7139    S.DiagRuntimeBehavior(Loc, rex.get(),
7140                          S.PDiag(diag::warn_shift_negative)
7141                            << rex.get()->getSourceRange());
7142    return;
7143  }
7144  llvm::APInt LeftBits(Right.getBitWidth(),
7145                       S.Context.getTypeSize(lex.get()->getType()));
7146  if (Right.uge(LeftBits)) {
7147    S.DiagRuntimeBehavior(Loc, rex.get(),
7148                          S.PDiag(diag::warn_shift_gt_typewidth)
7149                            << rex.get()->getSourceRange());
7150    return;
7151  }
7152  if (Opc != BO_Shl)
7153    return;
7154
7155  // When left shifting an ICE which is signed, we can check for overflow which
7156  // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7157  // integers have defined behavior modulo one more than the maximum value
7158  // representable in the result type, so never warn for those.
7159  llvm::APSInt Left;
7160  if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
7161      LHSTy->hasUnsignedIntegerRepresentation())
7162    return;
7163  llvm::APInt ResultBits =
7164      static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7165  if (LeftBits.uge(ResultBits))
7166    return;
7167  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7168  Result = Result.shl(Right);
7169
7170  // If we are only missing a sign bit, this is less likely to result in actual
7171  // bugs -- if the result is cast back to an unsigned type, it will have the
7172  // expected value. Thus we place this behind a different warning that can be
7173  // turned off separately if needed.
7174  if (LeftBits == ResultBits - 1) {
7175    S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7176        << Result.toString(10) << LHSTy
7177        << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7178    return;
7179  }
7180
7181  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7182    << Result.toString(10) << Result.getMinSignedBits() << LHSTy
7183    << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7184}
7185
7186// C99 6.5.7
7187QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
7188                                  unsigned Opc, bool isCompAssign) {
7189  // C99 6.5.7p2: Each of the operands shall have integer type.
7190  if (!lex.get()->getType()->hasIntegerRepresentation() ||
7191      !rex.get()->getType()->hasIntegerRepresentation())
7192    return InvalidOperands(Loc, lex, rex);
7193
7194  // C++0x: Don't allow scoped enums. FIXME: Use something better than
7195  // hasIntegerRepresentation() above instead of this.
7196  if (isScopedEnumerationType(lex.get()->getType()) ||
7197      isScopedEnumerationType(rex.get()->getType())) {
7198    return InvalidOperands(Loc, lex, rex);
7199  }
7200
7201  // Vector shifts promote their scalar inputs to vector type.
7202  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
7203    return CheckVectorOperands(Loc, lex, rex);
7204
7205  // Shifts don't perform usual arithmetic conversions, they just do integer
7206  // promotions on each operand. C99 6.5.7p3
7207
7208  // For the LHS, do usual unary conversions, but then reset them away
7209  // if this is a compound assignment.
7210  ExprResult old_lex = lex;
7211  lex = UsualUnaryConversions(lex.take());
7212  if (lex.isInvalid())
7213    return QualType();
7214  QualType LHSTy = lex.get()->getType();
7215  if (isCompAssign) lex = old_lex;
7216
7217  // The RHS is simpler.
7218  rex = UsualUnaryConversions(rex.take());
7219  if (rex.isInvalid())
7220    return QualType();
7221
7222  // Sanity-check shift operands
7223  DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
7224
7225  // "The type of the result is that of the promoted left operand."
7226  return LHSTy;
7227}
7228
7229static bool IsWithinTemplateSpecialization(Decl *D) {
7230  if (DeclContext *DC = D->getDeclContext()) {
7231    if (isa<ClassTemplateSpecializationDecl>(DC))
7232      return true;
7233    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7234      return FD->isFunctionTemplateSpecialization();
7235  }
7236  return false;
7237}
7238
7239// C99 6.5.8, C++ [expr.rel]
7240QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
7241                                    unsigned OpaqueOpc, bool isRelational) {
7242  BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7243
7244  // Handle vector comparisons separately.
7245  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
7246    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
7247
7248  QualType lType = lex.get()->getType();
7249  QualType rType = rex.get()->getType();
7250
7251  Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7252  Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
7253  QualType LHSStrippedType = LHSStripped->getType();
7254  QualType RHSStrippedType = RHSStripped->getType();
7255
7256
7257
7258  // Two different enums will raise a warning when compared.
7259  if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7260    if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7261      if (LHSEnumType->getDecl()->getIdentifier() &&
7262          RHSEnumType->getDecl()->getIdentifier() &&
7263          !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7264        Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7265          << LHSStrippedType << RHSStrippedType
7266          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7267      }
7268    }
7269  }
7270
7271  if (!lType->hasFloatingRepresentation() &&
7272      !(lType->isBlockPointerType() && isRelational) &&
7273      !lex.get()->getLocStart().isMacroID() &&
7274      !rex.get()->getLocStart().isMacroID()) {
7275    // For non-floating point types, check for self-comparisons of the form
7276    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7277    // often indicate logic errors in the program.
7278    //
7279    // NOTE: Don't warn about comparison expressions resulting from macro
7280    // expansion. Also don't warn about comparisons which are only self
7281    // comparisons within a template specialization. The warnings should catch
7282    // obvious cases in the definition of the template anyways. The idea is to
7283    // warn when the typed comparison operator will always evaluate to the same
7284    // result.
7285    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
7286      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
7287        if (DRL->getDecl() == DRR->getDecl() &&
7288            !IsWithinTemplateSpecialization(DRL->getDecl())) {
7289          DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7290                              << 0 // self-
7291                              << (Opc == BO_EQ
7292                                  || Opc == BO_LE
7293                                  || Opc == BO_GE));
7294        } else if (lType->isArrayType() && rType->isArrayType() &&
7295                   !DRL->getDecl()->getType()->isReferenceType() &&
7296                   !DRR->getDecl()->getType()->isReferenceType()) {
7297            // what is it always going to eval to?
7298            char always_evals_to;
7299            switch(Opc) {
7300            case BO_EQ: // e.g. array1 == array2
7301              always_evals_to = 0; // false
7302              break;
7303            case BO_NE: // e.g. array1 != array2
7304              always_evals_to = 1; // true
7305              break;
7306            default:
7307              // best we can say is 'a constant'
7308              always_evals_to = 2; // e.g. array1 <= array2
7309              break;
7310            }
7311            DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7312                                << 1 // array
7313                                << always_evals_to);
7314        }
7315      }
7316    }
7317
7318    if (isa<CastExpr>(LHSStripped))
7319      LHSStripped = LHSStripped->IgnoreParenCasts();
7320    if (isa<CastExpr>(RHSStripped))
7321      RHSStripped = RHSStripped->IgnoreParenCasts();
7322
7323    // Warn about comparisons against a string constant (unless the other
7324    // operand is null), the user probably wants strcmp.
7325    Expr *literalString = 0;
7326    Expr *literalStringStripped = 0;
7327    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7328        !RHSStripped->isNullPointerConstant(Context,
7329                                            Expr::NPC_ValueDependentIsNull)) {
7330      literalString = lex.get();
7331      literalStringStripped = LHSStripped;
7332    } else if ((isa<StringLiteral>(RHSStripped) ||
7333                isa<ObjCEncodeExpr>(RHSStripped)) &&
7334               !LHSStripped->isNullPointerConstant(Context,
7335                                            Expr::NPC_ValueDependentIsNull)) {
7336      literalString = rex.get();
7337      literalStringStripped = RHSStripped;
7338    }
7339
7340    if (literalString) {
7341      std::string resultComparison;
7342      switch (Opc) {
7343      case BO_LT: resultComparison = ") < 0"; break;
7344      case BO_GT: resultComparison = ") > 0"; break;
7345      case BO_LE: resultComparison = ") <= 0"; break;
7346      case BO_GE: resultComparison = ") >= 0"; break;
7347      case BO_EQ: resultComparison = ") == 0"; break;
7348      case BO_NE: resultComparison = ") != 0"; break;
7349      default: assert(false && "Invalid comparison operator");
7350      }
7351
7352      DiagRuntimeBehavior(Loc, 0,
7353        PDiag(diag::warn_stringcompare)
7354          << isa<ObjCEncodeExpr>(literalStringStripped)
7355          << literalString->getSourceRange());
7356    }
7357  }
7358
7359  // C99 6.5.8p3 / C99 6.5.9p4
7360  if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
7361    UsualArithmeticConversions(lex, rex);
7362    if (lex.isInvalid() || rex.isInvalid())
7363      return QualType();
7364  }
7365  else {
7366    lex = UsualUnaryConversions(lex.take());
7367    if (lex.isInvalid())
7368      return QualType();
7369
7370    rex = UsualUnaryConversions(rex.take());
7371    if (rex.isInvalid())
7372      return QualType();
7373  }
7374
7375  lType = lex.get()->getType();
7376  rType = rex.get()->getType();
7377
7378  // The result of comparisons is 'bool' in C++, 'int' in C.
7379  QualType ResultTy = Context.getLogicalOperationType();
7380
7381  if (isRelational) {
7382    if (lType->isRealType() && rType->isRealType())
7383      return ResultTy;
7384  } else {
7385    // Check for comparisons of floating point operands using != and ==.
7386    if (lType->hasFloatingRepresentation())
7387      CheckFloatComparison(Loc, lex.get(), rex.get());
7388
7389    if (lType->isArithmeticType() && rType->isArithmeticType())
7390      return ResultTy;
7391  }
7392
7393  bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
7394                                              Expr::NPC_ValueDependentIsNull);
7395  bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
7396                                              Expr::NPC_ValueDependentIsNull);
7397
7398  // All of the following pointer-related warnings are GCC extensions, except
7399  // when handling null pointer constants.
7400  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
7401    QualType LCanPointeeTy =
7402      Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
7403    QualType RCanPointeeTy =
7404      Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
7405
7406    if (getLangOptions().CPlusPlus) {
7407      if (LCanPointeeTy == RCanPointeeTy)
7408        return ResultTy;
7409      if (!isRelational &&
7410          (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7411        // Valid unless comparison between non-null pointer and function pointer
7412        // This is a gcc extension compatibility comparison.
7413        // In a SFINAE context, we treat this as a hard error to maintain
7414        // conformance with the C++ standard.
7415        if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7416            && !LHSIsNull && !RHSIsNull) {
7417          Diag(Loc,
7418               isSFINAEContext()?
7419                   diag::err_typecheck_comparison_of_fptr_to_void
7420                 : diag::ext_typecheck_comparison_of_fptr_to_void)
7421            << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7422
7423          if (isSFINAEContext())
7424            return QualType();
7425
7426          rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7427          return ResultTy;
7428        }
7429      }
7430
7431      // C++ [expr.rel]p2:
7432      //   [...] Pointer conversions (4.10) and qualification
7433      //   conversions (4.4) are performed on pointer operands (or on
7434      //   a pointer operand and a null pointer constant) to bring
7435      //   them to their composite pointer type. [...]
7436      //
7437      // C++ [expr.eq]p1 uses the same notion for (in)equality
7438      // comparisons of pointers.
7439      bool NonStandardCompositeType = false;
7440      QualType T = FindCompositePointerType(Loc, lex, rex,
7441                              isSFINAEContext()? 0 : &NonStandardCompositeType);
7442      if (T.isNull()) {
7443        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
7444          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7445        return QualType();
7446      } else if (NonStandardCompositeType) {
7447        Diag(Loc,
7448             diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7449          << lType << rType << T
7450          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7451      }
7452
7453      lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7454      rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
7455      return ResultTy;
7456    }
7457    // C99 6.5.9p2 and C99 6.5.8p2
7458    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7459                                   RCanPointeeTy.getUnqualifiedType())) {
7460      // Valid unless a relational comparison of function pointers
7461      if (isRelational && LCanPointeeTy->isFunctionType()) {
7462        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7463          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7464      }
7465    } else if (!isRelational &&
7466               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7467      // Valid unless comparison between non-null pointer and function pointer
7468      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7469          && !LHSIsNull && !RHSIsNull) {
7470        Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
7471          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7472      }
7473    } else {
7474      // Invalid
7475      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7476        << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7477    }
7478    if (LCanPointeeTy != RCanPointeeTy) {
7479      if (LHSIsNull && !RHSIsNull)
7480        lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
7481      else
7482        rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7483    }
7484    return ResultTy;
7485  }
7486
7487  if (getLangOptions().CPlusPlus) {
7488    // Comparison of nullptr_t with itself.
7489    if (lType->isNullPtrType() && rType->isNullPtrType())
7490      return ResultTy;
7491
7492    // Comparison of pointers with null pointer constants and equality
7493    // comparisons of member pointers to null pointer constants.
7494    if (RHSIsNull &&
7495        ((lType->isPointerType() || lType->isNullPtrType()) ||
7496         (!isRelational && lType->isMemberPointerType()))) {
7497      rex = ImpCastExprToType(rex.take(), lType,
7498                        lType->isMemberPointerType()
7499                          ? CK_NullToMemberPointer
7500                          : CK_NullToPointer);
7501      return ResultTy;
7502    }
7503    if (LHSIsNull &&
7504        ((rType->isPointerType() || rType->isNullPtrType()) ||
7505         (!isRelational && rType->isMemberPointerType()))) {
7506      lex = ImpCastExprToType(lex.take(), rType,
7507                        rType->isMemberPointerType()
7508                          ? CK_NullToMemberPointer
7509                          : CK_NullToPointer);
7510      return ResultTy;
7511    }
7512
7513    // Comparison of member pointers.
7514    if (!isRelational &&
7515        lType->isMemberPointerType() && rType->isMemberPointerType()) {
7516      // C++ [expr.eq]p2:
7517      //   In addition, pointers to members can be compared, or a pointer to
7518      //   member and a null pointer constant. Pointer to member conversions
7519      //   (4.11) and qualification conversions (4.4) are performed to bring
7520      //   them to a common type. If one operand is a null pointer constant,
7521      //   the common type is the type of the other operand. Otherwise, the
7522      //   common type is a pointer to member type similar (4.4) to the type
7523      //   of one of the operands, with a cv-qualification signature (4.4)
7524      //   that is the union of the cv-qualification signatures of the operand
7525      //   types.
7526      bool NonStandardCompositeType = false;
7527      QualType T = FindCompositePointerType(Loc, lex, rex,
7528                              isSFINAEContext()? 0 : &NonStandardCompositeType);
7529      if (T.isNull()) {
7530        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
7531          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7532        return QualType();
7533      } else if (NonStandardCompositeType) {
7534        Diag(Loc,
7535             diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7536          << lType << rType << T
7537          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7538      }
7539
7540      lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7541      rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
7542      return ResultTy;
7543    }
7544
7545    // Handle scoped enumeration types specifically, since they don't promote
7546    // to integers.
7547    if (lex.get()->getType()->isEnumeralType() &&
7548        Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
7549      return ResultTy;
7550  }
7551
7552  // Handle block pointer types.
7553  if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
7554    QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7555    QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
7556
7557    if (!LHSIsNull && !RHSIsNull &&
7558        !Context.typesAreCompatible(lpointee, rpointee)) {
7559      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7560        << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7561    }
7562    rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7563    return ResultTy;
7564  }
7565
7566  // Allow block pointers to be compared with null pointer constants.
7567  if (!isRelational
7568      && ((lType->isBlockPointerType() && rType->isPointerType())
7569          || (lType->isPointerType() && rType->isBlockPointerType()))) {
7570    if (!LHSIsNull && !RHSIsNull) {
7571      if (!((rType->isPointerType() && rType->castAs<PointerType>()
7572             ->getPointeeType()->isVoidType())
7573            || (lType->isPointerType() && lType->castAs<PointerType>()
7574                ->getPointeeType()->isVoidType())))
7575        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7576          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7577    }
7578    if (LHSIsNull && !RHSIsNull)
7579      lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
7580    else
7581      rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7582    return ResultTy;
7583  }
7584
7585  if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7586    const PointerType *LPT = lType->getAs<PointerType>();
7587    const PointerType *RPT = rType->getAs<PointerType>();
7588    if (LPT || RPT) {
7589      bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7590      bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7591
7592      if (!LPtrToVoid && !RPtrToVoid &&
7593          !Context.typesAreCompatible(lType, rType)) {
7594        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7595          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7596      }
7597      if (LHSIsNull && !RHSIsNull)
7598        lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
7599      else
7600        rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7601      return ResultTy;
7602    }
7603    if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
7604      if (!Context.areComparableObjCPointerTypes(lType, rType))
7605        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7606          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7607      if (LHSIsNull && !RHSIsNull)
7608        lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
7609      else
7610        rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
7611      return ResultTy;
7612    }
7613  }
7614  if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7615      (lType->isIntegerType() && rType->isAnyPointerType())) {
7616    unsigned DiagID = 0;
7617    bool isError = false;
7618    if ((LHSIsNull && lType->isIntegerType()) ||
7619        (RHSIsNull && rType->isIntegerType())) {
7620      if (isRelational && !getLangOptions().CPlusPlus)
7621        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7622    } else if (isRelational && !getLangOptions().CPlusPlus)
7623      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7624    else if (getLangOptions().CPlusPlus) {
7625      DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7626      isError = true;
7627    } else
7628      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7629
7630    if (DiagID) {
7631      Diag(Loc, DiagID)
7632        << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7633      if (isError)
7634        return QualType();
7635    }
7636
7637    if (lType->isIntegerType())
7638      lex = ImpCastExprToType(lex.take(), rType,
7639                        LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7640    else
7641      rex = ImpCastExprToType(rex.take(), lType,
7642                        RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7643    return ResultTy;
7644  }
7645
7646  // Handle block pointers.
7647  if (!isRelational && RHSIsNull
7648      && lType->isBlockPointerType() && rType->isIntegerType()) {
7649    rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
7650    return ResultTy;
7651  }
7652  if (!isRelational && LHSIsNull
7653      && lType->isIntegerType() && rType->isBlockPointerType()) {
7654    lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
7655    return ResultTy;
7656  }
7657
7658  return InvalidOperands(Loc, lex, rex);
7659}
7660
7661/// CheckVectorCompareOperands - vector comparisons are a clang extension that
7662/// operates on extended vector types.  Instead of producing an IntTy result,
7663/// like a scalar comparison, a vector comparison produces a vector of integer
7664/// types.
7665QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
7666                                          SourceLocation Loc,
7667                                          bool isRelational) {
7668  // Check to make sure we're operating on vectors of the same type and width,
7669  // Allowing one side to be a scalar of element type.
7670  QualType vType = CheckVectorOperands(Loc, lex, rex);
7671  if (vType.isNull())
7672    return vType;
7673
7674  QualType lType = lex.get()->getType();
7675  QualType rType = rex.get()->getType();
7676
7677  // If AltiVec, the comparison results in a numeric type, i.e.
7678  // bool for C++, int for C
7679  if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7680    return Context.getLogicalOperationType();
7681
7682  // For non-floating point types, check for self-comparisons of the form
7683  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7684  // often indicate logic errors in the program.
7685  if (!lType->hasFloatingRepresentation()) {
7686    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7687      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
7688        if (DRL->getDecl() == DRR->getDecl())
7689          DiagRuntimeBehavior(Loc, 0,
7690                              PDiag(diag::warn_comparison_always)
7691                                << 0 // self-
7692                                << 2 // "a constant"
7693                              );
7694  }
7695
7696  // Check for comparisons of floating point operands using != and ==.
7697  if (!isRelational && lType->hasFloatingRepresentation()) {
7698    assert (rType->hasFloatingRepresentation());
7699    CheckFloatComparison(Loc, lex.get(), rex.get());
7700  }
7701
7702  // Return the type for the comparison, which is the same as vector type for
7703  // integer vectors, or an integer type of identical size and number of
7704  // elements for floating point vectors.
7705  if (lType->hasIntegerRepresentation())
7706    return lType;
7707
7708  const VectorType *VTy = lType->getAs<VectorType>();
7709  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7710  if (TypeSize == Context.getTypeSize(Context.IntTy))
7711    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7712  if (TypeSize == Context.getTypeSize(Context.LongTy))
7713    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7714
7715  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7716         "Unhandled vector element size in vector compare");
7717  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7718}
7719
7720inline QualType Sema::CheckBitwiseOperands(
7721  ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7722  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7723    if (lex.get()->getType()->hasIntegerRepresentation() &&
7724        rex.get()->getType()->hasIntegerRepresentation())
7725      return CheckVectorOperands(Loc, lex, rex);
7726
7727    return InvalidOperands(Loc, lex, rex);
7728  }
7729
7730  ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7731  QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7732  if (lexResult.isInvalid() || rexResult.isInvalid())
7733    return QualType();
7734  lex = lexResult.take();
7735  rex = rexResult.take();
7736
7737  if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7738      rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
7739    return compType;
7740  return InvalidOperands(Loc, lex, rex);
7741}
7742
7743inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7744  ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
7745
7746  // Diagnose cases where the user write a logical and/or but probably meant a
7747  // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7748  // is a constant.
7749  if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7750      rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
7751      // Don't warn in macros.
7752      !Loc.isMacroID()) {
7753    // If the RHS can be constant folded, and if it constant folds to something
7754    // that isn't 0 or 1 (which indicate a potential logical operation that
7755    // happened to fold to true/false) then warn.
7756    Expr::EvalResult Result;
7757    if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
7758        Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7759      Diag(Loc, diag::warn_logical_instead_of_bitwise)
7760       << rex.get()->getSourceRange()
7761        << (Opc == BO_LAnd ? "&&" : "||")
7762        << (Opc == BO_LAnd ? "&" : "|");
7763    }
7764  }
7765
7766  if (!Context.getLangOptions().CPlusPlus) {
7767    lex = UsualUnaryConversions(lex.take());
7768    if (lex.isInvalid())
7769      return QualType();
7770
7771    rex = UsualUnaryConversions(rex.take());
7772    if (rex.isInvalid())
7773      return QualType();
7774
7775    if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
7776      return InvalidOperands(Loc, lex, rex);
7777
7778    return Context.IntTy;
7779  }
7780
7781  // The following is safe because we only use this method for
7782  // non-overloadable operands.
7783
7784  // C++ [expr.log.and]p1
7785  // C++ [expr.log.or]p1
7786  // The operands are both contextually converted to type bool.
7787  ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7788  if (lexRes.isInvalid())
7789    return InvalidOperands(Loc, lex, rex);
7790  lex = move(lexRes);
7791
7792  ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7793  if (rexRes.isInvalid())
7794    return InvalidOperands(Loc, lex, rex);
7795  rex = move(rexRes);
7796
7797  // C++ [expr.log.and]p2
7798  // C++ [expr.log.or]p2
7799  // The result is a bool.
7800  return Context.BoolTy;
7801}
7802
7803/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7804/// is a read-only property; return true if so. A readonly property expression
7805/// depends on various declarations and thus must be treated specially.
7806///
7807static bool IsReadonlyProperty(Expr *E, Sema &S) {
7808  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7809    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7810    if (PropExpr->isImplicitProperty()) return false;
7811
7812    ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7813    QualType BaseType = PropExpr->isSuperReceiver() ?
7814                            PropExpr->getSuperReceiverType() :
7815                            PropExpr->getBase()->getType();
7816
7817    if (const ObjCObjectPointerType *OPT =
7818          BaseType->getAsObjCInterfacePointerType())
7819      if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7820        if (S.isPropertyReadonly(PDecl, IFace))
7821          return true;
7822  }
7823  return false;
7824}
7825
7826static bool IsConstProperty(Expr *E, Sema &S) {
7827  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7828    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7829    if (PropExpr->isImplicitProperty()) return false;
7830
7831    ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7832    QualType T = PDecl->getType();
7833    if (T->isReferenceType())
7834      T = T->getAs<ReferenceType>()->getPointeeType();
7835    CanQualType CT = S.Context.getCanonicalType(T);
7836    return CT.isConstQualified();
7837  }
7838  return false;
7839}
7840
7841static bool IsReadonlyMessage(Expr *E, Sema &S) {
7842  if (E->getStmtClass() != Expr::MemberExprClass)
7843    return false;
7844  const MemberExpr *ME = cast<MemberExpr>(E);
7845  NamedDecl *Member = ME->getMemberDecl();
7846  if (isa<FieldDecl>(Member)) {
7847    Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7848    if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7849      return false;
7850    return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7851  }
7852  return false;
7853}
7854
7855/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7856/// emit an error and return true.  If so, return false.
7857static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7858  SourceLocation OrigLoc = Loc;
7859  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7860                                                              &Loc);
7861  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7862    IsLV = Expr::MLV_ReadonlyProperty;
7863  else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7864    IsLV = Expr::MLV_Valid;
7865  else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7866    IsLV = Expr::MLV_InvalidMessageExpression;
7867  if (IsLV == Expr::MLV_Valid)
7868    return false;
7869
7870  unsigned Diag = 0;
7871  bool NeedType = false;
7872  switch (IsLV) { // C99 6.5.16p2
7873  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
7874  case Expr::MLV_ArrayType:
7875    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7876    NeedType = true;
7877    break;
7878  case Expr::MLV_NotObjectType:
7879    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7880    NeedType = true;
7881    break;
7882  case Expr::MLV_LValueCast:
7883    Diag = diag::err_typecheck_lvalue_casts_not_supported;
7884    break;
7885  case Expr::MLV_Valid:
7886    llvm_unreachable("did not take early return for MLV_Valid");
7887  case Expr::MLV_InvalidExpression:
7888  case Expr::MLV_MemberFunction:
7889  case Expr::MLV_ClassTemporary:
7890    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7891    break;
7892  case Expr::MLV_IncompleteType:
7893  case Expr::MLV_IncompleteVoidType:
7894    return S.RequireCompleteType(Loc, E->getType(),
7895              S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
7896                  << E->getSourceRange());
7897  case Expr::MLV_DuplicateVectorComponents:
7898    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7899    break;
7900  case Expr::MLV_NotBlockQualified:
7901    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7902    break;
7903  case Expr::MLV_ReadonlyProperty:
7904    Diag = diag::error_readonly_property_assignment;
7905    break;
7906  case Expr::MLV_NoSetterProperty:
7907    Diag = diag::error_nosetter_property_assignment;
7908    break;
7909  case Expr::MLV_InvalidMessageExpression:
7910    Diag = diag::error_readonly_message_assignment;
7911    break;
7912  case Expr::MLV_SubObjCPropertySetting:
7913    Diag = diag::error_no_subobject_property_setting;
7914    break;
7915  }
7916
7917  SourceRange Assign;
7918  if (Loc != OrigLoc)
7919    Assign = SourceRange(OrigLoc, OrigLoc);
7920  if (NeedType)
7921    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7922  else
7923    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7924  return true;
7925}
7926
7927
7928
7929// C99 6.5.16.1
7930QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
7931                                       SourceLocation Loc,
7932                                       QualType CompoundType) {
7933  // Verify that LHS is a modifiable lvalue, and emit error if not.
7934  if (CheckForModifiableLvalue(LHS, Loc, *this))
7935    return QualType();
7936
7937  QualType LHSType = LHS->getType();
7938  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
7939  AssignConvertType ConvTy;
7940  if (CompoundType.isNull()) {
7941    QualType LHSTy(LHSType);
7942    // Simple assignment "x = y".
7943    if (LHS->getObjectKind() == OK_ObjCProperty) {
7944      ExprResult LHSResult = Owned(LHS);
7945      ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7946      if (LHSResult.isInvalid())
7947        return QualType();
7948      LHS = LHSResult.take();
7949    }
7950    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7951    if (RHS.isInvalid())
7952      return QualType();
7953    // Special case of NSObject attributes on c-style pointer types.
7954    if (ConvTy == IncompatiblePointer &&
7955        ((Context.isObjCNSObjectType(LHSType) &&
7956          RHSType->isObjCObjectPointerType()) ||
7957         (Context.isObjCNSObjectType(RHSType) &&
7958          LHSType->isObjCObjectPointerType())))
7959      ConvTy = Compatible;
7960
7961    if (ConvTy == Compatible &&
7962        getLangOptions().ObjCNonFragileABI &&
7963        LHSType->isObjCObjectType())
7964      Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7965        << LHSType;
7966
7967    // If the RHS is a unary plus or minus, check to see if they = and + are
7968    // right next to each other.  If so, the user may have typo'd "x =+ 4"
7969    // instead of "x += 4".
7970    Expr *RHSCheck = RHS.get();
7971    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7972      RHSCheck = ICE->getSubExpr();
7973    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7974      if ((UO->getOpcode() == UO_Plus ||
7975           UO->getOpcode() == UO_Minus) &&
7976          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7977          // Only if the two operators are exactly adjacent.
7978          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7979          // And there is a space or other character before the subexpr of the
7980          // unary +/-.  We don't want to warn on "x=-1".
7981          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7982          UO->getSubExpr()->getLocStart().isFileID()) {
7983        Diag(Loc, diag::warn_not_compound_assign)
7984          << (UO->getOpcode() == UO_Plus ? "+" : "-")
7985          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7986      }
7987    }
7988  } else {
7989    // Compound assignment "x += y"
7990    ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7991  }
7992
7993  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7994                               RHS.get(), AA_Assigning))
7995    return QualType();
7996
7997
7998  // Check to see if the destination operand is a dereferenced null pointer.  If
7999  // so, and if not volatile-qualified, this is undefined behavior that the
8000  // optimizer will delete, so warn about it.  People sometimes try to use this
8001  // to get a deterministic trap and are surprised by clang's behavior.  This
8002  // only handles the pattern "*null = whatever", which is a very syntactic
8003  // check.
8004  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
8005    if (UO->getOpcode() == UO_Deref &&
8006        UO->getSubExpr()->IgnoreParenCasts()->
8007          isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
8008        !UO->getType().isVolatileQualified()) {
8009    DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8010                        PDiag(diag::warn_indirection_through_null)
8011                          << UO->getSubExpr()->getSourceRange());
8012    DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8013                        PDiag(diag::note_indirection_through_null));
8014  }
8015
8016  // Check for trivial buffer overflows.
8017  CheckArrayAccess(LHS->IgnoreParenCasts());
8018
8019  // C99 6.5.16p3: The type of an assignment expression is the type of the
8020  // left operand unless the left operand has qualified type, in which case
8021  // it is the unqualified version of the type of the left operand.
8022  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8023  // is converted to the type of the assignment expression (above).
8024  // C++ 5.17p1: the type of the assignment expression is that of its left
8025  // operand.
8026  return (getLangOptions().CPlusPlus
8027          ? LHSType : LHSType.getUnqualifiedType());
8028}
8029
8030// C99 6.5.17
8031static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8032                                   SourceLocation Loc) {
8033  S.DiagnoseUnusedExprResult(LHS.get());
8034
8035  LHS = S.CheckPlaceholderExpr(LHS.take());
8036  RHS = S.CheckPlaceholderExpr(RHS.take());
8037  if (LHS.isInvalid() || RHS.isInvalid())
8038    return QualType();
8039
8040  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8041  // operands, but not unary promotions.
8042  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8043
8044  // So we treat the LHS as a ignored value, and in C++ we allow the
8045  // containing site to determine what should be done with the RHS.
8046  LHS = S.IgnoredValueConversions(LHS.take());
8047  if (LHS.isInvalid())
8048    return QualType();
8049
8050  if (!S.getLangOptions().CPlusPlus) {
8051    RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8052    if (RHS.isInvalid())
8053      return QualType();
8054    if (!RHS.get()->getType()->isVoidType())
8055      S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
8056  }
8057
8058  return RHS.get()->getType();
8059}
8060
8061/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8062/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8063static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8064                                               ExprValueKind &VK,
8065                                               SourceLocation OpLoc,
8066                                               bool isInc, bool isPrefix) {
8067  if (Op->isTypeDependent())
8068    return S.Context.DependentTy;
8069
8070  QualType ResType = Op->getType();
8071  assert(!ResType.isNull() && "no type for increment/decrement expression");
8072
8073  if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
8074    // Decrement of bool is not allowed.
8075    if (!isInc) {
8076      S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8077      return QualType();
8078    }
8079    // Increment of bool sets it to true, but is deprecated.
8080    S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8081  } else if (ResType->isRealType()) {
8082    // OK!
8083  } else if (ResType->isAnyPointerType()) {
8084    QualType PointeeTy = ResType->getPointeeType();
8085
8086    // C99 6.5.2.4p2, 6.5.6p2
8087    if (PointeeTy->isVoidType()) {
8088      if (S.getLangOptions().CPlusPlus) {
8089        S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
8090          << Op->getSourceRange();
8091        return QualType();
8092      }
8093
8094      // Pointer to void is a GNU extension in C.
8095      S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
8096    } else if (PointeeTy->isFunctionType()) {
8097      if (S.getLangOptions().CPlusPlus) {
8098        S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
8099          << Op->getType() << Op->getSourceRange();
8100        return QualType();
8101      }
8102
8103      S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
8104        << ResType << Op->getSourceRange();
8105    } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8106                 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
8107                             << Op->getSourceRange()
8108                             << ResType))
8109      return QualType();
8110    // Diagnose bad cases where we step over interface counts.
8111    else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8112      S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
8113        << PointeeTy << Op->getSourceRange();
8114      return QualType();
8115    }
8116  } else if (ResType->isAnyComplexType()) {
8117    // C99 does not support ++/-- on complex types, we allow as an extension.
8118    S.Diag(OpLoc, diag::ext_integer_increment_complex)
8119      << ResType << Op->getSourceRange();
8120  } else if (ResType->isPlaceholderType()) {
8121    ExprResult PR = S.CheckPlaceholderExpr(Op);
8122    if (PR.isInvalid()) return QualType();
8123    return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8124                                          isInc, isPrefix);
8125  } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8126    // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8127  } else {
8128    S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8129      << ResType << int(isInc) << Op->getSourceRange();
8130    return QualType();
8131  }
8132  // At this point, we know we have a real, complex or pointer type.
8133  // Now make sure the operand is a modifiable lvalue.
8134  if (CheckForModifiableLvalue(Op, OpLoc, S))
8135    return QualType();
8136  // In C++, a prefix increment is the same type as the operand. Otherwise
8137  // (in C or with postfix), the increment is the unqualified type of the
8138  // operand.
8139  if (isPrefix && S.getLangOptions().CPlusPlus) {
8140    VK = VK_LValue;
8141    return ResType;
8142  } else {
8143    VK = VK_RValue;
8144    return ResType.getUnqualifiedType();
8145  }
8146}
8147
8148ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
8149  assert(E->getValueKind() == VK_LValue &&
8150         E->getObjectKind() == OK_ObjCProperty);
8151  const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8152
8153  ExprValueKind VK = VK_RValue;
8154  if (PRE->isImplicitProperty()) {
8155    if (const ObjCMethodDecl *GetterMethod =
8156          PRE->getImplicitPropertyGetter()) {
8157      QualType Result = GetterMethod->getResultType();
8158      VK = Expr::getValueKindForType(Result);
8159    }
8160    else {
8161      Diag(PRE->getLocation(), diag::err_getter_not_found)
8162            << PRE->getBase()->getType();
8163    }
8164  }
8165
8166  E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
8167                               E, 0, VK);
8168
8169  ExprResult Result = MaybeBindToTemporary(E);
8170  if (!Result.isInvalid())
8171    E = Result.take();
8172
8173  return Owned(E);
8174}
8175
8176void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8177  assert(LHS.get()->getValueKind() == VK_LValue &&
8178         LHS.get()->getObjectKind() == OK_ObjCProperty);
8179  const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
8180
8181  if (PropRef->isImplicitProperty()) {
8182    // If using property-dot syntax notation for assignment, and there is a
8183    // setter, RHS expression is being passed to the setter argument. So,
8184    // type conversion (and comparison) is RHS to setter's argument type.
8185    if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
8186      ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8187      LHSTy = (*P)->getType();
8188
8189    // Otherwise, if the getter returns an l-value, just call that.
8190    } else {
8191      QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
8192      ExprValueKind VK = Expr::getValueKindForType(Result);
8193      if (VK == VK_LValue) {
8194        LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8195                                        CK_GetObjCProperty, LHS.take(), 0, VK);
8196        return;
8197      }
8198    }
8199  }
8200
8201  if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
8202    InitializedEntity Entity =
8203    InitializedEntity::InitializeParameter(Context, LHSTy);
8204    ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
8205    if (!ArgE.isInvalid())
8206      RHS = ArgE;
8207  }
8208}
8209
8210
8211/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8212/// This routine allows us to typecheck complex/recursive expressions
8213/// where the declaration is needed for type checking. We only need to
8214/// handle cases when the expression references a function designator
8215/// or is an lvalue. Here are some examples:
8216///  - &(x) => x
8217///  - &*****f => f for f a function designator.
8218///  - &s.xx => s
8219///  - &s.zz[1].yy -> s, if zz is an array
8220///  - *(x + 1) -> x, if x is an array
8221///  - &"123"[2] -> 0
8222///  - & __real__ x -> x
8223static ValueDecl *getPrimaryDecl(Expr *E) {
8224  switch (E->getStmtClass()) {
8225  case Stmt::DeclRefExprClass:
8226    return cast<DeclRefExpr>(E)->getDecl();
8227  case Stmt::MemberExprClass:
8228    // If this is an arrow operator, the address is an offset from
8229    // the base's value, so the object the base refers to is
8230    // irrelevant.
8231    if (cast<MemberExpr>(E)->isArrow())
8232      return 0;
8233    // Otherwise, the expression refers to a part of the base
8234    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8235  case Stmt::ArraySubscriptExprClass: {
8236    // FIXME: This code shouldn't be necessary!  We should catch the implicit
8237    // promotion of register arrays earlier.
8238    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8239    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8240      if (ICE->getSubExpr()->getType()->isArrayType())
8241        return getPrimaryDecl(ICE->getSubExpr());
8242    }
8243    return 0;
8244  }
8245  case Stmt::UnaryOperatorClass: {
8246    UnaryOperator *UO = cast<UnaryOperator>(E);
8247
8248    switch(UO->getOpcode()) {
8249    case UO_Real:
8250    case UO_Imag:
8251    case UO_Extension:
8252      return getPrimaryDecl(UO->getSubExpr());
8253    default:
8254      return 0;
8255    }
8256  }
8257  case Stmt::ParenExprClass:
8258    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8259  case Stmt::ImplicitCastExprClass:
8260    // If the result of an implicit cast is an l-value, we care about
8261    // the sub-expression; otherwise, the result here doesn't matter.
8262    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8263  default:
8264    return 0;
8265  }
8266}
8267
8268/// CheckAddressOfOperand - The operand of & must be either a function
8269/// designator or an lvalue designating an object. If it is an lvalue, the
8270/// object cannot be declared with storage class register or be a bit field.
8271/// Note: The usual conversions are *not* applied to the operand of the &
8272/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8273/// In C++, the operand might be an overloaded function name, in which case
8274/// we allow the '&' but retain the overloaded-function type.
8275static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8276                                      SourceLocation OpLoc) {
8277  if (OrigOp->isTypeDependent())
8278    return S.Context.DependentTy;
8279  if (OrigOp->getType() == S.Context.OverloadTy)
8280    return S.Context.OverloadTy;
8281  if (OrigOp->getType() == S.Context.UnknownAnyTy)
8282    return S.Context.UnknownAnyTy;
8283
8284  assert(!OrigOp->getType()->isPlaceholderType());
8285
8286  // Make sure to ignore parentheses in subsequent checks
8287  Expr *op = OrigOp->IgnoreParens();
8288
8289  if (S.getLangOptions().C99) {
8290    // Implement C99-only parts of addressof rules.
8291    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8292      if (uOp->getOpcode() == UO_Deref)
8293        // Per C99 6.5.3.2, the address of a deref always returns a valid result
8294        // (assuming the deref expression is valid).
8295        return uOp->getSubExpr()->getType();
8296    }
8297    // Technically, there should be a check for array subscript
8298    // expressions here, but the result of one is always an lvalue anyway.
8299  }
8300  ValueDecl *dcl = getPrimaryDecl(op);
8301  Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
8302
8303  if (lval == Expr::LV_ClassTemporary) {
8304    bool sfinae = S.isSFINAEContext();
8305    S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8306                         : diag::ext_typecheck_addrof_class_temporary)
8307      << op->getType() << op->getSourceRange();
8308    if (sfinae)
8309      return QualType();
8310  } else if (isa<ObjCSelectorExpr>(op)) {
8311    return S.Context.getPointerType(op->getType());
8312  } else if (lval == Expr::LV_MemberFunction) {
8313    // If it's an instance method, make a member pointer.
8314    // The expression must have exactly the form &A::foo.
8315
8316    // If the underlying expression isn't a decl ref, give up.
8317    if (!isa<DeclRefExpr>(op)) {
8318      S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8319        << OrigOp->getSourceRange();
8320      return QualType();
8321    }
8322    DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8323    CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8324
8325    // The id-expression was parenthesized.
8326    if (OrigOp != DRE) {
8327      S.Diag(OpLoc, diag::err_parens_pointer_member_function)
8328        << OrigOp->getSourceRange();
8329
8330    // The method was named without a qualifier.
8331    } else if (!DRE->getQualifier()) {
8332      S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8333        << op->getSourceRange();
8334    }
8335
8336    return S.Context.getMemberPointerType(op->getType(),
8337              S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
8338  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8339    // C99 6.5.3.2p1
8340    // The operand must be either an l-value or a function designator
8341    if (!op->getType()->isFunctionType()) {
8342      // FIXME: emit more specific diag...
8343      S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8344        << op->getSourceRange();
8345      return QualType();
8346    }
8347  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8348    // The operand cannot be a bit-field
8349    S.Diag(OpLoc, diag::err_typecheck_address_of)
8350      << "bit-field" << op->getSourceRange();
8351        return QualType();
8352  } else if (op->getObjectKind() == OK_VectorComponent) {
8353    // The operand cannot be an element of a vector
8354    S.Diag(OpLoc, diag::err_typecheck_address_of)
8355      << "vector element" << op->getSourceRange();
8356    return QualType();
8357  } else if (op->getObjectKind() == OK_ObjCProperty) {
8358    // cannot take address of a property expression.
8359    S.Diag(OpLoc, diag::err_typecheck_address_of)
8360      << "property expression" << op->getSourceRange();
8361    return QualType();
8362  } else if (dcl) { // C99 6.5.3.2p1
8363    // We have an lvalue with a decl. Make sure the decl is not declared
8364    // with the register storage-class specifier.
8365    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8366      // in C++ it is not error to take address of a register
8367      // variable (c++03 7.1.1P3)
8368      if (vd->getStorageClass() == SC_Register &&
8369          !S.getLangOptions().CPlusPlus) {
8370        S.Diag(OpLoc, diag::err_typecheck_address_of)
8371          << "register variable" << op->getSourceRange();
8372        return QualType();
8373      }
8374    } else if (isa<FunctionTemplateDecl>(dcl)) {
8375      return S.Context.OverloadTy;
8376    } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8377      // Okay: we can take the address of a field.
8378      // Could be a pointer to member, though, if there is an explicit
8379      // scope qualifier for the class.
8380      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8381        DeclContext *Ctx = dcl->getDeclContext();
8382        if (Ctx && Ctx->isRecord()) {
8383          if (dcl->getType()->isReferenceType()) {
8384            S.Diag(OpLoc,
8385                   diag::err_cannot_form_pointer_to_member_of_reference_type)
8386              << dcl->getDeclName() << dcl->getType();
8387            return QualType();
8388          }
8389
8390          while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8391            Ctx = Ctx->getParent();
8392          return S.Context.getMemberPointerType(op->getType(),
8393                S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8394        }
8395      }
8396    } else if (!isa<FunctionDecl>(dcl))
8397      assert(0 && "Unknown/unexpected decl type");
8398  }
8399
8400  if (lval == Expr::LV_IncompleteVoidType) {
8401    // Taking the address of a void variable is technically illegal, but we
8402    // allow it in cases which are otherwise valid.
8403    // Example: "extern void x; void* y = &x;".
8404    S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8405  }
8406
8407  // If the operand has type "type", the result has type "pointer to type".
8408  if (op->getType()->isObjCObjectType())
8409    return S.Context.getObjCObjectPointerType(op->getType());
8410  return S.Context.getPointerType(op->getType());
8411}
8412
8413/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8414static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8415                                        SourceLocation OpLoc) {
8416  if (Op->isTypeDependent())
8417    return S.Context.DependentTy;
8418
8419  ExprResult ConvResult = S.UsualUnaryConversions(Op);
8420  if (ConvResult.isInvalid())
8421    return QualType();
8422  Op = ConvResult.take();
8423  QualType OpTy = Op->getType();
8424  QualType Result;
8425
8426  // Note that per both C89 and C99, indirection is always legal, even if OpTy
8427  // is an incomplete type or void.  It would be possible to warn about
8428  // dereferencing a void pointer, but it's completely well-defined, and such a
8429  // warning is unlikely to catch any mistakes.
8430  if (const PointerType *PT = OpTy->getAs<PointerType>())
8431    Result = PT->getPointeeType();
8432  else if (const ObjCObjectPointerType *OPT =
8433             OpTy->getAs<ObjCObjectPointerType>())
8434    Result = OPT->getPointeeType();
8435  else {
8436    ExprResult PR = S.CheckPlaceholderExpr(Op);
8437    if (PR.isInvalid()) return QualType();
8438    if (PR.take() != Op)
8439      return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8440  }
8441
8442  if (Result.isNull()) {
8443    S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8444      << OpTy << Op->getSourceRange();
8445    return QualType();
8446  }
8447
8448  // Dereferences are usually l-values...
8449  VK = VK_LValue;
8450
8451  // ...except that certain expressions are never l-values in C.
8452  if (!S.getLangOptions().CPlusPlus &&
8453      IsCForbiddenLValueType(S.Context, Result))
8454    VK = VK_RValue;
8455
8456  return Result;
8457}
8458
8459static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8460  tok::TokenKind Kind) {
8461  BinaryOperatorKind Opc;
8462  switch (Kind) {
8463  default: assert(0 && "Unknown binop!");
8464  case tok::periodstar:           Opc = BO_PtrMemD; break;
8465  case tok::arrowstar:            Opc = BO_PtrMemI; break;
8466  case tok::star:                 Opc = BO_Mul; break;
8467  case tok::slash:                Opc = BO_Div; break;
8468  case tok::percent:              Opc = BO_Rem; break;
8469  case tok::plus:                 Opc = BO_Add; break;
8470  case tok::minus:                Opc = BO_Sub; break;
8471  case tok::lessless:             Opc = BO_Shl; break;
8472  case tok::greatergreater:       Opc = BO_Shr; break;
8473  case tok::lessequal:            Opc = BO_LE; break;
8474  case tok::less:                 Opc = BO_LT; break;
8475  case tok::greaterequal:         Opc = BO_GE; break;
8476  case tok::greater:              Opc = BO_GT; break;
8477  case tok::exclaimequal:         Opc = BO_NE; break;
8478  case tok::equalequal:           Opc = BO_EQ; break;
8479  case tok::amp:                  Opc = BO_And; break;
8480  case tok::caret:                Opc = BO_Xor; break;
8481  case tok::pipe:                 Opc = BO_Or; break;
8482  case tok::ampamp:               Opc = BO_LAnd; break;
8483  case tok::pipepipe:             Opc = BO_LOr; break;
8484  case tok::equal:                Opc = BO_Assign; break;
8485  case tok::starequal:            Opc = BO_MulAssign; break;
8486  case tok::slashequal:           Opc = BO_DivAssign; break;
8487  case tok::percentequal:         Opc = BO_RemAssign; break;
8488  case tok::plusequal:            Opc = BO_AddAssign; break;
8489  case tok::minusequal:           Opc = BO_SubAssign; break;
8490  case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8491  case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8492  case tok::ampequal:             Opc = BO_AndAssign; break;
8493  case tok::caretequal:           Opc = BO_XorAssign; break;
8494  case tok::pipeequal:            Opc = BO_OrAssign; break;
8495  case tok::comma:                Opc = BO_Comma; break;
8496  }
8497  return Opc;
8498}
8499
8500static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8501  tok::TokenKind Kind) {
8502  UnaryOperatorKind Opc;
8503  switch (Kind) {
8504  default: assert(0 && "Unknown unary op!");
8505  case tok::plusplus:     Opc = UO_PreInc; break;
8506  case tok::minusminus:   Opc = UO_PreDec; break;
8507  case tok::amp:          Opc = UO_AddrOf; break;
8508  case tok::star:         Opc = UO_Deref; break;
8509  case tok::plus:         Opc = UO_Plus; break;
8510  case tok::minus:        Opc = UO_Minus; break;
8511  case tok::tilde:        Opc = UO_Not; break;
8512  case tok::exclaim:      Opc = UO_LNot; break;
8513  case tok::kw___real:    Opc = UO_Real; break;
8514  case tok::kw___imag:    Opc = UO_Imag; break;
8515  case tok::kw___extension__: Opc = UO_Extension; break;
8516  }
8517  return Opc;
8518}
8519
8520/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8521/// This warning is only emitted for builtin assignment operations. It is also
8522/// suppressed in the event of macro expansions.
8523static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8524                                   SourceLocation OpLoc) {
8525  if (!S.ActiveTemplateInstantiations.empty())
8526    return;
8527  if (OpLoc.isInvalid() || OpLoc.isMacroID())
8528    return;
8529  lhs = lhs->IgnoreParenImpCasts();
8530  rhs = rhs->IgnoreParenImpCasts();
8531  const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8532  const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8533  if (!LeftDeclRef || !RightDeclRef ||
8534      LeftDeclRef->getLocation().isMacroID() ||
8535      RightDeclRef->getLocation().isMacroID())
8536    return;
8537  const ValueDecl *LeftDecl =
8538    cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8539  const ValueDecl *RightDecl =
8540    cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8541  if (LeftDecl != RightDecl)
8542    return;
8543  if (LeftDecl->getType().isVolatileQualified())
8544    return;
8545  if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8546    if (RefTy->getPointeeType().isVolatileQualified())
8547      return;
8548
8549  S.Diag(OpLoc, diag::warn_self_assignment)
8550      << LeftDeclRef->getType()
8551      << lhs->getSourceRange() << rhs->getSourceRange();
8552}
8553
8554/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8555/// operator @p Opc at location @c TokLoc. This routine only supports
8556/// built-in operations; ActOnBinOp handles overloaded operators.
8557ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8558                                    BinaryOperatorKind Opc,
8559                                    Expr *lhsExpr, Expr *rhsExpr) {
8560  ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
8561  QualType ResultTy;     // Result type of the binary operator.
8562  // The following two variables are used for compound assignment operators
8563  QualType CompLHSTy;    // Type of LHS after promotions for computation
8564  QualType CompResultTy; // Type of computation result
8565  ExprValueKind VK = VK_RValue;
8566  ExprObjectKind OK = OK_Ordinary;
8567
8568  // Check if a 'foo<int>' involved in a binary op, identifies a single
8569  // function unambiguously (i.e. an lvalue ala 13.4)
8570  // But since an assignment can trigger target based overload, exclude it in
8571  // our blind search. i.e:
8572  // template<class T> void f(); template<class T, class U> void f(U);
8573  // f<int> == 0;  // resolve f<int> blindly
8574  // void (*p)(int); p = f<int>;  // resolve f<int> using target
8575  if (Opc != BO_Assign) {
8576    ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
8577    if (!resolvedLHS.isUsable()) return ExprError();
8578    lhs = move(resolvedLHS);
8579
8580    ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
8581    if (!resolvedRHS.isUsable()) return ExprError();
8582    rhs = move(resolvedRHS);
8583  }
8584
8585  switch (Opc) {
8586  case BO_Assign:
8587    ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
8588    if (getLangOptions().CPlusPlus &&
8589        lhs.get()->getObjectKind() != OK_ObjCProperty) {
8590      VK = lhs.get()->getValueKind();
8591      OK = lhs.get()->getObjectKind();
8592    }
8593    if (!ResultTy.isNull())
8594      DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
8595    break;
8596  case BO_PtrMemD:
8597  case BO_PtrMemI:
8598    ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
8599                                            Opc == BO_PtrMemI);
8600    break;
8601  case BO_Mul:
8602  case BO_Div:
8603    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
8604                                           Opc == BO_Div);
8605    break;
8606  case BO_Rem:
8607    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8608    break;
8609  case BO_Add:
8610    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8611    break;
8612  case BO_Sub:
8613    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8614    break;
8615  case BO_Shl:
8616  case BO_Shr:
8617    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
8618    break;
8619  case BO_LE:
8620  case BO_LT:
8621  case BO_GE:
8622  case BO_GT:
8623    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
8624    break;
8625  case BO_EQ:
8626  case BO_NE:
8627    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
8628    break;
8629  case BO_And:
8630  case BO_Xor:
8631  case BO_Or:
8632    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8633    break;
8634  case BO_LAnd:
8635  case BO_LOr:
8636    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
8637    break;
8638  case BO_MulAssign:
8639  case BO_DivAssign:
8640    CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
8641                                               Opc == BO_DivAssign);
8642    CompLHSTy = CompResultTy;
8643    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8644      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
8645    break;
8646  case BO_RemAssign:
8647    CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8648    CompLHSTy = CompResultTy;
8649    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8650      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
8651    break;
8652  case BO_AddAssign:
8653    CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8654    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8655      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
8656    break;
8657  case BO_SubAssign:
8658    CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8659    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8660      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
8661    break;
8662  case BO_ShlAssign:
8663  case BO_ShrAssign:
8664    CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
8665    CompLHSTy = CompResultTy;
8666    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8667      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
8668    break;
8669  case BO_AndAssign:
8670  case BO_XorAssign:
8671  case BO_OrAssign:
8672    CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8673    CompLHSTy = CompResultTy;
8674    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8675      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
8676    break;
8677  case BO_Comma:
8678    ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
8679    if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8680      VK = rhs.get()->getValueKind();
8681      OK = rhs.get()->getObjectKind();
8682    }
8683    break;
8684  }
8685  if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
8686    return ExprError();
8687  if (CompResultTy.isNull())
8688    return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8689                                              ResultTy, VK, OK, OpLoc));
8690  if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
8691    VK = VK_LValue;
8692    OK = lhs.get()->getObjectKind();
8693  }
8694  return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8695                                                    ResultTy, VK, OK, CompLHSTy,
8696                                                    CompResultTy, OpLoc));
8697}
8698
8699/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8700/// ParenRange in parentheses.
8701static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8702                               const PartialDiagnostic &PD,
8703                               const PartialDiagnostic &FirstNote,
8704                               SourceRange FirstParenRange,
8705                               const PartialDiagnostic &SecondNote,
8706                               SourceRange SecondParenRange) {
8707  Self.Diag(Loc, PD);
8708
8709  if (!FirstNote.getDiagID())
8710    return;
8711
8712  SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8713  if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8714    // We can't display the parentheses, so just return.
8715    return;
8716  }
8717
8718  Self.Diag(Loc, FirstNote)
8719    << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
8720    << FixItHint::CreateInsertion(EndLoc, ")");
8721
8722  if (!SecondNote.getDiagID())
8723    return;
8724
8725  EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8726  if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8727    // We can't display the parentheses, so just dig the
8728    // warning/error and return.
8729    Self.Diag(Loc, SecondNote);
8730    return;
8731  }
8732
8733  Self.Diag(Loc, SecondNote)
8734    << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8735    << FixItHint::CreateInsertion(EndLoc, ")");
8736}
8737
8738/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8739/// operators are mixed in a way that suggests that the programmer forgot that
8740/// comparison operators have higher precedence. The most typical example of
8741/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8742static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8743                                      SourceLocation OpLoc,Expr *lhs,Expr *rhs){
8744  typedef BinaryOperator BinOp;
8745  BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8746                rhsopc = static_cast<BinOp::Opcode>(-1);
8747  if (BinOp *BO = dyn_cast<BinOp>(lhs))
8748    lhsopc = BO->getOpcode();
8749  if (BinOp *BO = dyn_cast<BinOp>(rhs))
8750    rhsopc = BO->getOpcode();
8751
8752  // Subs are not binary operators.
8753  if (lhsopc == -1 && rhsopc == -1)
8754    return;
8755
8756  // Bitwise operations are sometimes used as eager logical ops.
8757  // Don't diagnose this.
8758  if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8759      (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
8760    return;
8761
8762  if (BinOp::isComparisonOp(lhsopc))
8763    SuggestParentheses(Self, OpLoc,
8764      Self.PDiag(diag::warn_precedence_bitwise_rel)
8765          << SourceRange(lhs->getLocStart(), OpLoc)
8766          << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
8767      Self.PDiag(diag::note_precedence_bitwise_first)
8768          << BinOp::getOpcodeStr(Opc),
8769      SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8770      Self.PDiag(diag::note_precedence_bitwise_silence)
8771          << BinOp::getOpcodeStr(lhsopc),
8772                       lhs->getSourceRange());
8773  else if (BinOp::isComparisonOp(rhsopc))
8774    SuggestParentheses(Self, OpLoc,
8775      Self.PDiag(diag::warn_precedence_bitwise_rel)
8776          << SourceRange(OpLoc, rhs->getLocEnd())
8777          << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
8778      Self.PDiag(diag::note_precedence_bitwise_first)
8779        << BinOp::getOpcodeStr(Opc),
8780      SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8781      Self.PDiag(diag::note_precedence_bitwise_silence)
8782        << BinOp::getOpcodeStr(rhsopc),
8783                       rhs->getSourceRange());
8784}
8785
8786/// \brief It accepts a '&&' expr that is inside a '||' one.
8787/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8788/// in parentheses.
8789static void
8790EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8791                                       BinaryOperator *Bop) {
8792  assert(Bop->getOpcode() == BO_LAnd);
8793  SuggestParentheses(Self, Bop->getOperatorLoc(),
8794    Self.PDiag(diag::warn_logical_and_in_logical_or)
8795        << Bop->getSourceRange() << OpLoc,
8796    Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8797    Bop->getSourceRange(),
8798    Self.PDiag(0), SourceRange());
8799}
8800
8801/// \brief Returns true if the given expression can be evaluated as a constant
8802/// 'true'.
8803static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8804  bool Res;
8805  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8806}
8807
8808/// \brief Returns true if the given expression can be evaluated as a constant
8809/// 'false'.
8810static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8811  bool Res;
8812  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8813}
8814
8815/// \brief Look for '&&' in the left hand of a '||' expr.
8816static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8817                                             Expr *OrLHS, Expr *OrRHS) {
8818  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
8819    if (Bop->getOpcode() == BO_LAnd) {
8820      // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8821      if (EvaluatesAsFalse(S, OrRHS))
8822        return;
8823      // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8824      if (!EvaluatesAsTrue(S, Bop->getLHS()))
8825        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8826    } else if (Bop->getOpcode() == BO_LOr) {
8827      if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8828        // If it's "a || b && 1 || c" we didn't warn earlier for
8829        // "a || b && 1", but warn now.
8830        if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8831          return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8832      }
8833    }
8834  }
8835}
8836
8837/// \brief Look for '&&' in the right hand of a '||' expr.
8838static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8839                                             Expr *OrLHS, Expr *OrRHS) {
8840  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
8841    if (Bop->getOpcode() == BO_LAnd) {
8842      // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8843      if (EvaluatesAsFalse(S, OrLHS))
8844        return;
8845      // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8846      if (!EvaluatesAsTrue(S, Bop->getRHS()))
8847        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8848    }
8849  }
8850}
8851
8852/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8853/// precedence.
8854static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8855                                    SourceLocation OpLoc, Expr *lhs, Expr *rhs){
8856  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8857  if (BinaryOperator::isBitwiseOp(Opc))
8858    return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8859
8860  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8861  // We don't warn for 'assert(a || b && "bad")' since this is safe.
8862  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8863    DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8864    DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
8865  }
8866}
8867
8868// Binary Operators.  'Tok' is the token for the operator.
8869ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8870                            tok::TokenKind Kind,
8871                            Expr *lhs, Expr *rhs) {
8872  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8873  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8874  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
8875
8876  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8877  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8878
8879  return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8880}
8881
8882ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8883                            BinaryOperatorKind Opc,
8884                            Expr *lhs, Expr *rhs) {
8885  if (getLangOptions().CPlusPlus) {
8886    bool UseBuiltinOperator;
8887
8888    if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8889      UseBuiltinOperator = false;
8890    } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8891      UseBuiltinOperator = true;
8892    } else {
8893      UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8894                           !rhs->getType()->isOverloadableType();
8895    }
8896
8897    if (!UseBuiltinOperator) {
8898      // Find all of the overloaded operators visible from this
8899      // point. We perform both an operator-name lookup from the local
8900      // scope and an argument-dependent lookup based on the types of
8901      // the arguments.
8902      UnresolvedSet<16> Functions;
8903      OverloadedOperatorKind OverOp
8904        = BinaryOperator::getOverloadedOperator(Opc);
8905      if (S && OverOp != OO_None)
8906        LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8907                                     Functions);
8908
8909      // Build the (potentially-overloaded, potentially-dependent)
8910      // binary operation.
8911      return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8912    }
8913  }
8914
8915  // Build a built-in binary operation.
8916  return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
8917}
8918
8919ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8920                                      UnaryOperatorKind Opc,
8921                                      Expr *InputExpr) {
8922  ExprResult Input = Owned(InputExpr);
8923  ExprValueKind VK = VK_RValue;
8924  ExprObjectKind OK = OK_Ordinary;
8925  QualType resultType;
8926  switch (Opc) {
8927  case UO_PreInc:
8928  case UO_PreDec:
8929  case UO_PostInc:
8930  case UO_PostDec:
8931    resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8932                                                Opc == UO_PreInc ||
8933                                                Opc == UO_PostInc,
8934                                                Opc == UO_PreInc ||
8935                                                Opc == UO_PreDec);
8936    break;
8937  case UO_AddrOf:
8938    resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
8939    break;
8940  case UO_Deref: {
8941    ExprResult resolved = CheckPlaceholderExpr(Input.get());
8942    if (!resolved.isUsable()) return ExprError();
8943    Input = move(resolved);
8944    Input = DefaultFunctionArrayLvalueConversion(Input.take());
8945    resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8946    break;
8947  }
8948  case UO_Plus:
8949  case UO_Minus:
8950    Input = UsualUnaryConversions(Input.take());
8951    if (Input.isInvalid()) return ExprError();
8952    resultType = Input.get()->getType();
8953    if (resultType->isDependentType())
8954      break;
8955    if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8956        resultType->isVectorType())
8957      break;
8958    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8959             resultType->isEnumeralType())
8960      break;
8961    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
8962             Opc == UO_Plus &&
8963             resultType->isPointerType())
8964      break;
8965    else if (resultType->isPlaceholderType()) {
8966      Input = CheckPlaceholderExpr(Input.take());
8967      if (Input.isInvalid()) return ExprError();
8968      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
8969    }
8970
8971    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8972      << resultType << Input.get()->getSourceRange());
8973
8974  case UO_Not: // bitwise complement
8975    Input = UsualUnaryConversions(Input.take());
8976    if (Input.isInvalid()) return ExprError();
8977    resultType = Input.get()->getType();
8978    if (resultType->isDependentType())
8979      break;
8980    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8981    if (resultType->isComplexType() || resultType->isComplexIntegerType())
8982      // C99 does not support '~' for complex conjugation.
8983      Diag(OpLoc, diag::ext_integer_complement_complex)
8984        << resultType << Input.get()->getSourceRange();
8985    else if (resultType->hasIntegerRepresentation())
8986      break;
8987    else if (resultType->isPlaceholderType()) {
8988      Input = CheckPlaceholderExpr(Input.take());
8989      if (Input.isInvalid()) return ExprError();
8990      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
8991    } else {
8992      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8993        << resultType << Input.get()->getSourceRange());
8994    }
8995    break;
8996
8997  case UO_LNot: // logical negation
8998    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8999    Input = DefaultFunctionArrayLvalueConversion(Input.take());
9000    if (Input.isInvalid()) return ExprError();
9001    resultType = Input.get()->getType();
9002    if (resultType->isDependentType())
9003      break;
9004    if (resultType->isScalarType()) {
9005      // C99 6.5.3.3p1: ok, fallthrough;
9006      if (Context.getLangOptions().CPlusPlus) {
9007        // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9008        // operand contextually converted to bool.
9009        Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9010                                  ScalarTypeToBooleanCastKind(resultType));
9011      }
9012    } else if (resultType->isPlaceholderType()) {
9013      Input = CheckPlaceholderExpr(Input.take());
9014      if (Input.isInvalid()) return ExprError();
9015      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
9016    } else {
9017      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9018        << resultType << Input.get()->getSourceRange());
9019    }
9020
9021    // LNot always has type int. C99 6.5.3.3p5.
9022    // In C++, it's bool. C++ 5.3.1p8
9023    resultType = Context.getLogicalOperationType();
9024    break;
9025  case UO_Real:
9026  case UO_Imag:
9027    resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9028    // _Real and _Imag map ordinary l-values into ordinary l-values.
9029    if (Input.isInvalid()) return ExprError();
9030    if (Input.get()->getValueKind() != VK_RValue &&
9031        Input.get()->getObjectKind() == OK_Ordinary)
9032      VK = Input.get()->getValueKind();
9033    break;
9034  case UO_Extension:
9035    resultType = Input.get()->getType();
9036    VK = Input.get()->getValueKind();
9037    OK = Input.get()->getObjectKind();
9038    break;
9039  }
9040  if (resultType.isNull() || Input.isInvalid())
9041    return ExprError();
9042
9043  return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9044                                           VK, OK, OpLoc));
9045}
9046
9047ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9048                              UnaryOperatorKind Opc,
9049                              Expr *Input) {
9050  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
9051      UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
9052    // Find all of the overloaded operators visible from this
9053    // point. We perform both an operator-name lookup from the local
9054    // scope and an argument-dependent lookup based on the types of
9055    // the arguments.
9056    UnresolvedSet<16> Functions;
9057    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9058    if (S && OverOp != OO_None)
9059      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9060                                   Functions);
9061
9062    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9063  }
9064
9065  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9066}
9067
9068// Unary Operators.  'Tok' is the token for the operator.
9069ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9070                              tok::TokenKind Op, Expr *Input) {
9071  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9072}
9073
9074/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9075ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9076                                LabelDecl *TheDecl) {
9077  TheDecl->setUsed();
9078  // Create the AST node.  The address of a label always has type 'void*'.
9079  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9080                                       Context.getPointerType(Context.VoidTy)));
9081}
9082
9083ExprResult
9084Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9085                    SourceLocation RPLoc) { // "({..})"
9086  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9087  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9088
9089  bool isFileScope
9090    = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9091  if (isFileScope)
9092    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9093
9094  // FIXME: there are a variety of strange constraints to enforce here, for
9095  // example, it is not possible to goto into a stmt expression apparently.
9096  // More semantic analysis is needed.
9097
9098  // If there are sub stmts in the compound stmt, take the type of the last one
9099  // as the type of the stmtexpr.
9100  QualType Ty = Context.VoidTy;
9101  bool StmtExprMayBindToTemp = false;
9102  if (!Compound->body_empty()) {
9103    Stmt *LastStmt = Compound->body_back();
9104    LabelStmt *LastLabelStmt = 0;
9105    // If LastStmt is a label, skip down through into the body.
9106    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9107      LastLabelStmt = Label;
9108      LastStmt = Label->getSubStmt();
9109    }
9110    if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9111      // Do function/array conversion on the last expression, but not
9112      // lvalue-to-rvalue.  However, initialize an unqualified type.
9113      ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9114      if (LastExpr.isInvalid())
9115        return ExprError();
9116      Ty = LastExpr.get()->getType().getUnqualifiedType();
9117
9118      if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9119        LastExpr = PerformCopyInitialization(
9120                            InitializedEntity::InitializeResult(LPLoc,
9121                                                                Ty,
9122                                                                false),
9123                                                   SourceLocation(),
9124                                             LastExpr);
9125        if (LastExpr.isInvalid())
9126          return ExprError();
9127        if (LastExpr.get() != 0) {
9128          if (!LastLabelStmt)
9129            Compound->setLastStmt(LastExpr.take());
9130          else
9131            LastLabelStmt->setSubStmt(LastExpr.take());
9132          StmtExprMayBindToTemp = true;
9133        }
9134      }
9135    }
9136  }
9137
9138  // FIXME: Check that expression type is complete/non-abstract; statement
9139  // expressions are not lvalues.
9140  Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9141  if (StmtExprMayBindToTemp)
9142    return MaybeBindToTemporary(ResStmtExpr);
9143  return Owned(ResStmtExpr);
9144}
9145
9146ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9147                                      TypeSourceInfo *TInfo,
9148                                      OffsetOfComponent *CompPtr,
9149                                      unsigned NumComponents,
9150                                      SourceLocation RParenLoc) {
9151  QualType ArgTy = TInfo->getType();
9152  bool Dependent = ArgTy->isDependentType();
9153  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9154
9155  // We must have at least one component that refers to the type, and the first
9156  // one is known to be a field designator.  Verify that the ArgTy represents
9157  // a struct/union/class.
9158  if (!Dependent && !ArgTy->isRecordType())
9159    return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9160                       << ArgTy << TypeRange);
9161
9162  // Type must be complete per C99 7.17p3 because a declaring a variable
9163  // with an incomplete type would be ill-formed.
9164  if (!Dependent
9165      && RequireCompleteType(BuiltinLoc, ArgTy,
9166                             PDiag(diag::err_offsetof_incomplete_type)
9167                               << TypeRange))
9168    return ExprError();
9169
9170  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9171  // GCC extension, diagnose them.
9172  // FIXME: This diagnostic isn't actually visible because the location is in
9173  // a system header!
9174  if (NumComponents != 1)
9175    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9176      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9177
9178  bool DidWarnAboutNonPOD = false;
9179  QualType CurrentType = ArgTy;
9180  typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9181  llvm::SmallVector<OffsetOfNode, 4> Comps;
9182  llvm::SmallVector<Expr*, 4> Exprs;
9183  for (unsigned i = 0; i != NumComponents; ++i) {
9184    const OffsetOfComponent &OC = CompPtr[i];
9185    if (OC.isBrackets) {
9186      // Offset of an array sub-field.  TODO: Should we allow vector elements?
9187      if (!CurrentType->isDependentType()) {
9188        const ArrayType *AT = Context.getAsArrayType(CurrentType);
9189        if(!AT)
9190          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9191                           << CurrentType);
9192        CurrentType = AT->getElementType();
9193      } else
9194        CurrentType = Context.DependentTy;
9195
9196      // The expression must be an integral expression.
9197      // FIXME: An integral constant expression?
9198      Expr *Idx = static_cast<Expr*>(OC.U.E);
9199      if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9200          !Idx->getType()->isIntegerType())
9201        return ExprError(Diag(Idx->getLocStart(),
9202                              diag::err_typecheck_subscript_not_integer)
9203                         << Idx->getSourceRange());
9204
9205      // Record this array index.
9206      Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9207      Exprs.push_back(Idx);
9208      continue;
9209    }
9210
9211    // Offset of a field.
9212    if (CurrentType->isDependentType()) {
9213      // We have the offset of a field, but we can't look into the dependent
9214      // type. Just record the identifier of the field.
9215      Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9216      CurrentType = Context.DependentTy;
9217      continue;
9218    }
9219
9220    // We need to have a complete type to look into.
9221    if (RequireCompleteType(OC.LocStart, CurrentType,
9222                            diag::err_offsetof_incomplete_type))
9223      return ExprError();
9224
9225    // Look for the designated field.
9226    const RecordType *RC = CurrentType->getAs<RecordType>();
9227    if (!RC)
9228      return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9229                       << CurrentType);
9230    RecordDecl *RD = RC->getDecl();
9231
9232    // C++ [lib.support.types]p5:
9233    //   The macro offsetof accepts a restricted set of type arguments in this
9234    //   International Standard. type shall be a POD structure or a POD union
9235    //   (clause 9).
9236    if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9237      if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
9238          DiagRuntimeBehavior(BuiltinLoc, 0,
9239                              PDiag(diag::warn_offsetof_non_pod_type)
9240                              << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9241                              << CurrentType))
9242        DidWarnAboutNonPOD = true;
9243    }
9244
9245    // Look for the field.
9246    LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9247    LookupQualifiedName(R, RD);
9248    FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9249    IndirectFieldDecl *IndirectMemberDecl = 0;
9250    if (!MemberDecl) {
9251      if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9252        MemberDecl = IndirectMemberDecl->getAnonField();
9253    }
9254
9255    if (!MemberDecl)
9256      return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9257                       << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9258                                                              OC.LocEnd));
9259
9260    // C99 7.17p3:
9261    //   (If the specified member is a bit-field, the behavior is undefined.)
9262    //
9263    // We diagnose this as an error.
9264    if (MemberDecl->getBitWidth()) {
9265      Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9266        << MemberDecl->getDeclName()
9267        << SourceRange(BuiltinLoc, RParenLoc);
9268      Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9269      return ExprError();
9270    }
9271
9272    RecordDecl *Parent = MemberDecl->getParent();
9273    if (IndirectMemberDecl)
9274      Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9275
9276    // If the member was found in a base class, introduce OffsetOfNodes for
9277    // the base class indirections.
9278    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9279                       /*DetectVirtual=*/false);
9280    if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9281      CXXBasePath &Path = Paths.front();
9282      for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9283           B != BEnd; ++B)
9284        Comps.push_back(OffsetOfNode(B->Base));
9285    }
9286
9287    if (IndirectMemberDecl) {
9288      for (IndirectFieldDecl::chain_iterator FI =
9289           IndirectMemberDecl->chain_begin(),
9290           FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9291        assert(isa<FieldDecl>(*FI));
9292        Comps.push_back(OffsetOfNode(OC.LocStart,
9293                                     cast<FieldDecl>(*FI), OC.LocEnd));
9294      }
9295    } else
9296      Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9297
9298    CurrentType = MemberDecl->getType().getNonReferenceType();
9299  }
9300
9301  return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9302                                    TInfo, Comps.data(), Comps.size(),
9303                                    Exprs.data(), Exprs.size(), RParenLoc));
9304}
9305
9306ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9307                                      SourceLocation BuiltinLoc,
9308                                      SourceLocation TypeLoc,
9309                                      ParsedType argty,
9310                                      OffsetOfComponent *CompPtr,
9311                                      unsigned NumComponents,
9312                                      SourceLocation RPLoc) {
9313
9314  TypeSourceInfo *ArgTInfo;
9315  QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9316  if (ArgTy.isNull())
9317    return ExprError();
9318
9319  if (!ArgTInfo)
9320    ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9321
9322  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9323                              RPLoc);
9324}
9325
9326
9327ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9328                                 Expr *CondExpr,
9329                                 Expr *LHSExpr, Expr *RHSExpr,
9330                                 SourceLocation RPLoc) {
9331  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9332
9333  ExprValueKind VK = VK_RValue;
9334  ExprObjectKind OK = OK_Ordinary;
9335  QualType resType;
9336  bool ValueDependent = false;
9337  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9338    resType = Context.DependentTy;
9339    ValueDependent = true;
9340  } else {
9341    // The conditional expression is required to be a constant expression.
9342    llvm::APSInt condEval(32);
9343    SourceLocation ExpLoc;
9344    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
9345      return ExprError(Diag(ExpLoc,
9346                       diag::err_typecheck_choose_expr_requires_constant)
9347        << CondExpr->getSourceRange());
9348
9349    // If the condition is > zero, then the AST type is the same as the LSHExpr.
9350    Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9351
9352    resType = ActiveExpr->getType();
9353    ValueDependent = ActiveExpr->isValueDependent();
9354    VK = ActiveExpr->getValueKind();
9355    OK = ActiveExpr->getObjectKind();
9356  }
9357
9358  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9359                                        resType, VK, OK, RPLoc,
9360                                        resType->isDependentType(),
9361                                        ValueDependent));
9362}
9363
9364//===----------------------------------------------------------------------===//
9365// Clang Extensions.
9366//===----------------------------------------------------------------------===//
9367
9368/// ActOnBlockStart - This callback is invoked when a block literal is started.
9369void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
9370  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9371  PushBlockScope(BlockScope, Block);
9372  CurContext->addDecl(Block);
9373  if (BlockScope)
9374    PushDeclContext(BlockScope, Block);
9375  else
9376    CurContext = Block;
9377}
9378
9379void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
9380  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9381  assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9382  BlockScopeInfo *CurBlock = getCurBlock();
9383
9384  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9385  QualType T = Sig->getType();
9386
9387  // GetTypeForDeclarator always produces a function type for a block
9388  // literal signature.  Furthermore, it is always a FunctionProtoType
9389  // unless the function was written with a typedef.
9390  assert(T->isFunctionType() &&
9391         "GetTypeForDeclarator made a non-function block signature");
9392
9393  // Look for an explicit signature in that function type.
9394  FunctionProtoTypeLoc ExplicitSignature;
9395
9396  TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9397  if (isa<FunctionProtoTypeLoc>(tmp)) {
9398    ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9399
9400    // Check whether that explicit signature was synthesized by
9401    // GetTypeForDeclarator.  If so, don't save that as part of the
9402    // written signature.
9403    if (ExplicitSignature.getLocalRangeBegin() ==
9404        ExplicitSignature.getLocalRangeEnd()) {
9405      // This would be much cheaper if we stored TypeLocs instead of
9406      // TypeSourceInfos.
9407      TypeLoc Result = ExplicitSignature.getResultLoc();
9408      unsigned Size = Result.getFullDataSize();
9409      Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9410      Sig->getTypeLoc().initializeFullCopy(Result, Size);
9411
9412      ExplicitSignature = FunctionProtoTypeLoc();
9413    }
9414  }
9415
9416  CurBlock->TheDecl->setSignatureAsWritten(Sig);
9417  CurBlock->FunctionType = T;
9418
9419  const FunctionType *Fn = T->getAs<FunctionType>();
9420  QualType RetTy = Fn->getResultType();
9421  bool isVariadic =
9422    (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9423
9424  CurBlock->TheDecl->setIsVariadic(isVariadic);
9425
9426  // Don't allow returning a objc interface by value.
9427  if (RetTy->isObjCObjectType()) {
9428    Diag(ParamInfo.getSourceRange().getBegin(),
9429         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9430    return;
9431  }
9432
9433  // Context.DependentTy is used as a placeholder for a missing block
9434  // return type.  TODO:  what should we do with declarators like:
9435  //   ^ * { ... }
9436  // If the answer is "apply template argument deduction"....
9437  if (RetTy != Context.DependentTy)
9438    CurBlock->ReturnType = RetTy;
9439
9440  // Push block parameters from the declarator if we had them.
9441  llvm::SmallVector<ParmVarDecl*, 8> Params;
9442  if (ExplicitSignature) {
9443    for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9444      ParmVarDecl *Param = ExplicitSignature.getArg(I);
9445      if (Param->getIdentifier() == 0 &&
9446          !Param->isImplicit() &&
9447          !Param->isInvalidDecl() &&
9448          !getLangOptions().CPlusPlus)
9449        Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9450      Params.push_back(Param);
9451    }
9452
9453  // Fake up parameter variables if we have a typedef, like
9454  //   ^ fntype { ... }
9455  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9456    for (FunctionProtoType::arg_type_iterator
9457           I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9458      ParmVarDecl *Param =
9459        BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9460                                   ParamInfo.getSourceRange().getBegin(),
9461                                   *I);
9462      Params.push_back(Param);
9463    }
9464  }
9465
9466  // Set the parameters on the block decl.
9467  if (!Params.empty()) {
9468    CurBlock->TheDecl->setParams(Params.data(), Params.size());
9469    CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9470                             CurBlock->TheDecl->param_end(),
9471                             /*CheckParameterNames=*/false);
9472  }
9473
9474  // Finally we can process decl attributes.
9475  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9476
9477  if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
9478    Diag(ParamInfo.getAttributes()->getLoc(),
9479         diag::warn_attribute_sentinel_not_variadic) << 1;
9480    // FIXME: remove the attribute.
9481  }
9482
9483  // Put the parameter variables in scope.  We can bail out immediately
9484  // if we don't have any.
9485  if (Params.empty())
9486    return;
9487
9488  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9489         E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9490    (*AI)->setOwningFunction(CurBlock->TheDecl);
9491
9492    // If this has an identifier, add it to the scope stack.
9493    if ((*AI)->getIdentifier()) {
9494      CheckShadow(CurBlock->TheScope, *AI);
9495
9496      PushOnScopeChains(*AI, CurBlock->TheScope);
9497    }
9498  }
9499}
9500
9501/// ActOnBlockError - If there is an error parsing a block, this callback
9502/// is invoked to pop the information about the block from the action impl.
9503void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9504  // Pop off CurBlock, handle nested blocks.
9505  PopDeclContext();
9506  PopFunctionOrBlockScope();
9507}
9508
9509/// ActOnBlockStmtExpr - This is called when the body of a block statement
9510/// literal was successfully completed.  ^(int x){...}
9511ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9512                                    Stmt *Body, Scope *CurScope) {
9513  // If blocks are disabled, emit an error.
9514  if (!LangOpts.Blocks)
9515    Diag(CaretLoc, diag::err_blocks_disable);
9516
9517  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9518
9519  PopDeclContext();
9520
9521  QualType RetTy = Context.VoidTy;
9522  if (!BSI->ReturnType.isNull())
9523    RetTy = BSI->ReturnType;
9524
9525  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9526  QualType BlockTy;
9527
9528  // Set the captured variables on the block.
9529  BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9530                            BSI->CapturesCXXThis);
9531
9532  // If the user wrote a function type in some form, try to use that.
9533  if (!BSI->FunctionType.isNull()) {
9534    const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9535
9536    FunctionType::ExtInfo Ext = FTy->getExtInfo();
9537    if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9538
9539    // Turn protoless block types into nullary block types.
9540    if (isa<FunctionNoProtoType>(FTy)) {
9541      FunctionProtoType::ExtProtoInfo EPI;
9542      EPI.ExtInfo = Ext;
9543      BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9544
9545    // Otherwise, if we don't need to change anything about the function type,
9546    // preserve its sugar structure.
9547    } else if (FTy->getResultType() == RetTy &&
9548               (!NoReturn || FTy->getNoReturnAttr())) {
9549      BlockTy = BSI->FunctionType;
9550
9551    // Otherwise, make the minimal modifications to the function type.
9552    } else {
9553      const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9554      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9555      EPI.TypeQuals = 0; // FIXME: silently?
9556      EPI.ExtInfo = Ext;
9557      BlockTy = Context.getFunctionType(RetTy,
9558                                        FPT->arg_type_begin(),
9559                                        FPT->getNumArgs(),
9560                                        EPI);
9561    }
9562
9563  // If we don't have a function type, just build one from nothing.
9564  } else {
9565    FunctionProtoType::ExtProtoInfo EPI;
9566    EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
9567    BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9568  }
9569
9570  DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9571                           BSI->TheDecl->param_end());
9572  BlockTy = Context.getBlockPointerType(BlockTy);
9573
9574  // If needed, diagnose invalid gotos and switches in the block.
9575  if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
9576    DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9577
9578  BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9579
9580  BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9581
9582  const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9583  PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
9584  return Owned(Result);
9585}
9586
9587ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9588                                        Expr *expr, ParsedType type,
9589                                        SourceLocation RPLoc) {
9590  TypeSourceInfo *TInfo;
9591  GetTypeFromParser(type, &TInfo);
9592  return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
9593}
9594
9595ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9596                                Expr *E, TypeSourceInfo *TInfo,
9597                                SourceLocation RPLoc) {
9598  Expr *OrigExpr = E;
9599
9600  // Get the va_list type
9601  QualType VaListType = Context.getBuiltinVaListType();
9602  if (VaListType->isArrayType()) {
9603    // Deal with implicit array decay; for example, on x86-64,
9604    // va_list is an array, but it's supposed to decay to
9605    // a pointer for va_arg.
9606    VaListType = Context.getArrayDecayedType(VaListType);
9607    // Make sure the input expression also decays appropriately.
9608    ExprResult Result = UsualUnaryConversions(E);
9609    if (Result.isInvalid())
9610      return ExprError();
9611    E = Result.take();
9612  } else {
9613    // Otherwise, the va_list argument must be an l-value because
9614    // it is modified by va_arg.
9615    if (!E->isTypeDependent() &&
9616        CheckForModifiableLvalue(E, BuiltinLoc, *this))
9617      return ExprError();
9618  }
9619
9620  if (!E->isTypeDependent() &&
9621      !Context.hasSameType(VaListType, E->getType())) {
9622    return ExprError(Diag(E->getLocStart(),
9623                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
9624      << OrigExpr->getType() << E->getSourceRange());
9625  }
9626
9627  // FIXME: Check that type is complete/non-abstract
9628  // FIXME: Warn if a non-POD type is passed in.
9629
9630  QualType T = TInfo->getType().getNonLValueExprType(Context);
9631  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9632}
9633
9634ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9635  // The type of __null will be int or long, depending on the size of
9636  // pointers on the target.
9637  QualType Ty;
9638  unsigned pw = Context.Target.getPointerWidth(0);
9639  if (pw == Context.Target.getIntWidth())
9640    Ty = Context.IntTy;
9641  else if (pw == Context.Target.getLongWidth())
9642    Ty = Context.LongTy;
9643  else if (pw == Context.Target.getLongLongWidth())
9644    Ty = Context.LongLongTy;
9645  else {
9646    assert(!"I don't know size of pointer!");
9647    Ty = Context.IntTy;
9648  }
9649
9650  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9651}
9652
9653static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9654                                           Expr *SrcExpr, FixItHint &Hint) {
9655  if (!SemaRef.getLangOptions().ObjC1)
9656    return;
9657
9658  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9659  if (!PT)
9660    return;
9661
9662  // Check if the destination is of type 'id'.
9663  if (!PT->isObjCIdType()) {
9664    // Check if the destination is the 'NSString' interface.
9665    const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9666    if (!ID || !ID->getIdentifier()->isStr("NSString"))
9667      return;
9668  }
9669
9670  // Strip off any parens and casts.
9671  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9672  if (!SL || SL->isWide())
9673    return;
9674
9675  Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9676}
9677
9678bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9679                                    SourceLocation Loc,
9680                                    QualType DstType, QualType SrcType,
9681                                    Expr *SrcExpr, AssignmentAction Action,
9682                                    bool *Complained) {
9683  if (Complained)
9684    *Complained = false;
9685
9686  // Decode the result (notice that AST's are still created for extensions).
9687  bool isInvalid = false;
9688  unsigned DiagKind;
9689  FixItHint Hint;
9690
9691  switch (ConvTy) {
9692  default: assert(0 && "Unknown conversion type");
9693  case Compatible: return false;
9694  case PointerToInt:
9695    DiagKind = diag::ext_typecheck_convert_pointer_int;
9696    break;
9697  case IntToPointer:
9698    DiagKind = diag::ext_typecheck_convert_int_pointer;
9699    break;
9700  case IncompatiblePointer:
9701    MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9702    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9703    break;
9704  case IncompatiblePointerSign:
9705    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9706    break;
9707  case FunctionVoidPointer:
9708    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9709    break;
9710  case IncompatiblePointerDiscardsQualifiers: {
9711    // Perform array-to-pointer decay if necessary.
9712    if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9713
9714    Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9715    Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9716    if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9717      DiagKind = diag::err_typecheck_incompatible_address_space;
9718      break;
9719    }
9720
9721    llvm_unreachable("unknown error case for discarding qualifiers!");
9722    // fallthrough
9723  }
9724  case CompatiblePointerDiscardsQualifiers:
9725    // If the qualifiers lost were because we were applying the
9726    // (deprecated) C++ conversion from a string literal to a char*
9727    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9728    // Ideally, this check would be performed in
9729    // checkPointerTypesForAssignment. However, that would require a
9730    // bit of refactoring (so that the second argument is an
9731    // expression, rather than a type), which should be done as part
9732    // of a larger effort to fix checkPointerTypesForAssignment for
9733    // C++ semantics.
9734    if (getLangOptions().CPlusPlus &&
9735        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9736      return false;
9737    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9738    break;
9739  case IncompatibleNestedPointerQualifiers:
9740    DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9741    break;
9742  case IntToBlockPointer:
9743    DiagKind = diag::err_int_to_block_pointer;
9744    break;
9745  case IncompatibleBlockPointer:
9746    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9747    break;
9748  case IncompatibleObjCQualifiedId:
9749    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9750    // it can give a more specific diagnostic.
9751    DiagKind = diag::warn_incompatible_qualified_id;
9752    break;
9753  case IncompatibleVectors:
9754    DiagKind = diag::warn_incompatible_vectors;
9755    break;
9756  case Incompatible:
9757    DiagKind = diag::err_typecheck_convert_incompatible;
9758    isInvalid = true;
9759    break;
9760  }
9761
9762  QualType FirstType, SecondType;
9763  switch (Action) {
9764  case AA_Assigning:
9765  case AA_Initializing:
9766    // The destination type comes first.
9767    FirstType = DstType;
9768    SecondType = SrcType;
9769    break;
9770
9771  case AA_Returning:
9772  case AA_Passing:
9773  case AA_Converting:
9774  case AA_Sending:
9775  case AA_Casting:
9776    // The source type comes first.
9777    FirstType = SrcType;
9778    SecondType = DstType;
9779    break;
9780  }
9781
9782  Diag(Loc, DiagKind) << FirstType << SecondType << Action
9783    << SrcExpr->getSourceRange() << Hint;
9784  if (Complained)
9785    *Complained = true;
9786  return isInvalid;
9787}
9788
9789bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
9790  llvm::APSInt ICEResult;
9791  if (E->isIntegerConstantExpr(ICEResult, Context)) {
9792    if (Result)
9793      *Result = ICEResult;
9794    return false;
9795  }
9796
9797  Expr::EvalResult EvalResult;
9798
9799  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
9800      EvalResult.HasSideEffects) {
9801    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9802
9803    if (EvalResult.Diag) {
9804      // We only show the note if it's not the usual "invalid subexpression"
9805      // or if it's actually in a subexpression.
9806      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9807          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9808        Diag(EvalResult.DiagLoc, EvalResult.Diag);
9809    }
9810
9811    return true;
9812  }
9813
9814  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9815    E->getSourceRange();
9816
9817  if (EvalResult.Diag &&
9818      Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9819          != Diagnostic::Ignored)
9820    Diag(EvalResult.DiagLoc, EvalResult.Diag);
9821
9822  if (Result)
9823    *Result = EvalResult.Val.getInt();
9824  return false;
9825}
9826
9827void
9828Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
9829  ExprEvalContexts.push_back(
9830        ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
9831}
9832
9833void
9834Sema::PopExpressionEvaluationContext() {
9835  // Pop the current expression evaluation context off the stack.
9836  ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9837  ExprEvalContexts.pop_back();
9838
9839  if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9840    if (Rec.PotentiallyReferenced) {
9841      // Mark any remaining declarations in the current position of the stack
9842      // as "referenced". If they were not meant to be referenced, semantic
9843      // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
9844      for (PotentiallyReferencedDecls::iterator
9845             I = Rec.PotentiallyReferenced->begin(),
9846             IEnd = Rec.PotentiallyReferenced->end();
9847           I != IEnd; ++I)
9848        MarkDeclarationReferenced(I->first, I->second);
9849    }
9850
9851    if (Rec.PotentiallyDiagnosed) {
9852      // Emit any pending diagnostics.
9853      for (PotentiallyEmittedDiagnostics::iterator
9854                I = Rec.PotentiallyDiagnosed->begin(),
9855             IEnd = Rec.PotentiallyDiagnosed->end();
9856           I != IEnd; ++I)
9857        Diag(I->first, I->second);
9858    }
9859  }
9860
9861  // When are coming out of an unevaluated context, clear out any
9862  // temporaries that we may have created as part of the evaluation of
9863  // the expression in that context: they aren't relevant because they
9864  // will never be constructed.
9865  if (Rec.Context == Unevaluated &&
9866      ExprTemporaries.size() > Rec.NumTemporaries)
9867    ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9868                          ExprTemporaries.end());
9869
9870  // Destroy the popped expression evaluation record.
9871  Rec.Destroy();
9872}
9873
9874/// \brief Note that the given declaration was referenced in the source code.
9875///
9876/// This routine should be invoke whenever a given declaration is referenced
9877/// in the source code, and where that reference occurred. If this declaration
9878/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9879/// C99 6.9p3), then the declaration will be marked as used.
9880///
9881/// \param Loc the location where the declaration was referenced.
9882///
9883/// \param D the declaration that has been referenced by the source code.
9884void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9885  assert(D && "No declaration?");
9886
9887  D->setReferenced();
9888
9889  if (D->isUsed(false))
9890    return;
9891
9892  // Mark a parameter or variable declaration "used", regardless of whether we're in a
9893  // template or not. The reason for this is that unevaluated expressions
9894  // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9895  // -Wunused-parameters)
9896  if (isa<ParmVarDecl>(D) ||
9897      (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
9898    D->setUsed();
9899    return;
9900  }
9901
9902  if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9903    return;
9904
9905  // Do not mark anything as "used" within a dependent context; wait for
9906  // an instantiation.
9907  if (CurContext->isDependentContext())
9908    return;
9909
9910  switch (ExprEvalContexts.back().Context) {
9911    case Unevaluated:
9912      // We are in an expression that is not potentially evaluated; do nothing.
9913      return;
9914
9915    case PotentiallyEvaluated:
9916      // We are in a potentially-evaluated expression, so this declaration is
9917      // "used"; handle this below.
9918      break;
9919
9920    case PotentiallyPotentiallyEvaluated:
9921      // We are in an expression that may be potentially evaluated; queue this
9922      // declaration reference until we know whether the expression is
9923      // potentially evaluated.
9924      ExprEvalContexts.back().addReferencedDecl(Loc, D);
9925      return;
9926
9927    case PotentiallyEvaluatedIfUsed:
9928      // Referenced declarations will only be used if the construct in the
9929      // containing expression is used.
9930      return;
9931  }
9932
9933  // Note that this declaration has been used.
9934  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
9935    unsigned TypeQuals;
9936    if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
9937      if (Constructor->getParent()->hasTrivialConstructor())
9938        return;
9939      if (!Constructor->isUsed(false))
9940        DefineImplicitDefaultConstructor(Loc, Constructor);
9941    } else if (Constructor->isImplicit() &&
9942               Constructor->isCopyConstructor(TypeQuals)) {
9943      if (!Constructor->isUsed(false))
9944        DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9945    }
9946
9947    MarkVTableUsed(Loc, Constructor->getParent());
9948  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
9949    if (Destructor->isImplicit() && !Destructor->isUsed(false))
9950      DefineImplicitDestructor(Loc, Destructor);
9951    if (Destructor->isVirtual())
9952      MarkVTableUsed(Loc, Destructor->getParent());
9953  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9954    if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9955        MethodDecl->getOverloadedOperator() == OO_Equal) {
9956      if (!MethodDecl->isUsed(false))
9957        DefineImplicitCopyAssignment(Loc, MethodDecl);
9958    } else if (MethodDecl->isVirtual())
9959      MarkVTableUsed(Loc, MethodDecl->getParent());
9960  }
9961  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
9962    // Recursive functions should be marked when used from another function.
9963    if (CurContext == Function) return;
9964
9965    // Implicit instantiation of function templates and member functions of
9966    // class templates.
9967    if (Function->isImplicitlyInstantiable()) {
9968      bool AlreadyInstantiated = false;
9969      if (FunctionTemplateSpecializationInfo *SpecInfo
9970                                = Function->getTemplateSpecializationInfo()) {
9971        if (SpecInfo->getPointOfInstantiation().isInvalid())
9972          SpecInfo->setPointOfInstantiation(Loc);
9973        else if (SpecInfo->getTemplateSpecializationKind()
9974                   == TSK_ImplicitInstantiation)
9975          AlreadyInstantiated = true;
9976      } else if (MemberSpecializationInfo *MSInfo
9977                                  = Function->getMemberSpecializationInfo()) {
9978        if (MSInfo->getPointOfInstantiation().isInvalid())
9979          MSInfo->setPointOfInstantiation(Loc);
9980        else if (MSInfo->getTemplateSpecializationKind()
9981                   == TSK_ImplicitInstantiation)
9982          AlreadyInstantiated = true;
9983      }
9984
9985      if (!AlreadyInstantiated) {
9986        if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9987            cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9988          PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9989                                                                      Loc));
9990        else
9991          PendingInstantiations.push_back(std::make_pair(Function, Loc));
9992      }
9993    } else {
9994      // Walk redefinitions, as some of them may be instantiable.
9995      for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9996           e(Function->redecls_end()); i != e; ++i) {
9997        if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9998          MarkDeclarationReferenced(Loc, *i);
9999      }
10000    }
10001
10002    // Keep track of used but undefined functions.
10003    if (!Function->isPure() && !Function->hasBody() &&
10004        Function->getLinkage() != ExternalLinkage) {
10005      SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
10006      if (old.isInvalid()) old = Loc;
10007    }
10008
10009    Function->setUsed(true);
10010    return;
10011  }
10012
10013  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10014    // Implicit instantiation of static data members of class templates.
10015    if (Var->isStaticDataMember() &&
10016        Var->getInstantiatedFromStaticDataMember()) {
10017      MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10018      assert(MSInfo && "Missing member specialization information?");
10019      if (MSInfo->getPointOfInstantiation().isInvalid() &&
10020          MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10021        MSInfo->setPointOfInstantiation(Loc);
10022        PendingInstantiations.push_back(std::make_pair(Var, Loc));
10023      }
10024    }
10025
10026    // Keep track of used but undefined variables.  We make a hole in
10027    // the warning for static const data members with in-line
10028    // initializers.
10029    if (Var->hasDefinition() == VarDecl::DeclarationOnly
10030        && Var->getLinkage() != ExternalLinkage
10031        && !(Var->isStaticDataMember() && Var->hasInit())) {
10032      SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10033      if (old.isInvalid()) old = Loc;
10034    }
10035
10036    D->setUsed(true);
10037    return;
10038  }
10039}
10040
10041namespace {
10042  // Mark all of the declarations referenced
10043  // FIXME: Not fully implemented yet! We need to have a better understanding
10044  // of when we're entering
10045  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10046    Sema &S;
10047    SourceLocation Loc;
10048
10049  public:
10050    typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
10051
10052    MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
10053
10054    bool TraverseTemplateArgument(const TemplateArgument &Arg);
10055    bool TraverseRecordType(RecordType *T);
10056  };
10057}
10058
10059bool MarkReferencedDecls::TraverseTemplateArgument(
10060  const TemplateArgument &Arg) {
10061  if (Arg.getKind() == TemplateArgument::Declaration) {
10062    S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10063  }
10064
10065  return Inherited::TraverseTemplateArgument(Arg);
10066}
10067
10068bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
10069  if (ClassTemplateSpecializationDecl *Spec
10070                  = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10071    const TemplateArgumentList &Args = Spec->getTemplateArgs();
10072    return TraverseTemplateArguments(Args.data(), Args.size());
10073  }
10074
10075  return true;
10076}
10077
10078void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10079  MarkReferencedDecls Marker(*this, Loc);
10080  Marker.TraverseType(Context.getCanonicalType(T));
10081}
10082
10083namespace {
10084  /// \brief Helper class that marks all of the declarations referenced by
10085  /// potentially-evaluated subexpressions as "referenced".
10086  class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10087    Sema &S;
10088
10089  public:
10090    typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10091
10092    explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10093
10094    void VisitDeclRefExpr(DeclRefExpr *E) {
10095      S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10096    }
10097
10098    void VisitMemberExpr(MemberExpr *E) {
10099      S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
10100      Inherited::VisitMemberExpr(E);
10101    }
10102
10103    void VisitCXXNewExpr(CXXNewExpr *E) {
10104      if (E->getConstructor())
10105        S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10106      if (E->getOperatorNew())
10107        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10108      if (E->getOperatorDelete())
10109        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
10110      Inherited::VisitCXXNewExpr(E);
10111    }
10112
10113    void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10114      if (E->getOperatorDelete())
10115        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
10116      QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10117      if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10118        CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10119        S.MarkDeclarationReferenced(E->getLocStart(),
10120                                    S.LookupDestructor(Record));
10121      }
10122
10123      Inherited::VisitCXXDeleteExpr(E);
10124    }
10125
10126    void VisitCXXConstructExpr(CXXConstructExpr *E) {
10127      S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10128      Inherited::VisitCXXConstructExpr(E);
10129    }
10130
10131    void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10132      S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10133    }
10134
10135    void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10136      Visit(E->getExpr());
10137    }
10138  };
10139}
10140
10141/// \brief Mark any declarations that appear within this expression or any
10142/// potentially-evaluated subexpressions as "referenced".
10143void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10144  EvaluatedExprMarker(*this).Visit(E);
10145}
10146
10147/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10148/// of the program being compiled.
10149///
10150/// This routine emits the given diagnostic when the code currently being
10151/// type-checked is "potentially evaluated", meaning that there is a
10152/// possibility that the code will actually be executable. Code in sizeof()
10153/// expressions, code used only during overload resolution, etc., are not
10154/// potentially evaluated. This routine will suppress such diagnostics or,
10155/// in the absolutely nutty case of potentially potentially evaluated
10156/// expressions (C++ typeid), queue the diagnostic to potentially emit it
10157/// later.
10158///
10159/// This routine should be used for all diagnostics that describe the run-time
10160/// behavior of a program, such as passing a non-POD value through an ellipsis.
10161/// Failure to do so will likely result in spurious diagnostics or failures
10162/// during overload resolution or within sizeof/alignof/typeof/typeid.
10163bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
10164                               const PartialDiagnostic &PD) {
10165  switch (ExprEvalContexts.back().Context ) {
10166  case Unevaluated:
10167    // The argument will never be evaluated, so don't complain.
10168    break;
10169
10170  case PotentiallyEvaluated:
10171  case PotentiallyEvaluatedIfUsed:
10172    if (stmt && getCurFunctionOrMethodDecl()) {
10173      FunctionScopes.back()->PossiblyUnreachableDiags.
10174        push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10175    }
10176    else
10177      Diag(Loc, PD);
10178
10179    return true;
10180
10181  case PotentiallyPotentiallyEvaluated:
10182    ExprEvalContexts.back().addDiagnostic(Loc, PD);
10183    break;
10184  }
10185
10186  return false;
10187}
10188
10189bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10190                               CallExpr *CE, FunctionDecl *FD) {
10191  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10192    return false;
10193
10194  PartialDiagnostic Note =
10195    FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10196    << FD->getDeclName() : PDiag();
10197  SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
10198
10199  if (RequireCompleteType(Loc, ReturnType,
10200                          FD ?
10201                          PDiag(diag::err_call_function_incomplete_return)
10202                            << CE->getSourceRange() << FD->getDeclName() :
10203                          PDiag(diag::err_call_incomplete_return)
10204                            << CE->getSourceRange(),
10205                          std::make_pair(NoteLoc, Note)))
10206    return true;
10207
10208  return false;
10209}
10210
10211// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
10212// will prevent this condition from triggering, which is what we want.
10213void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10214  SourceLocation Loc;
10215
10216  unsigned diagnostic = diag::warn_condition_is_assignment;
10217  bool IsOrAssign = false;
10218
10219  if (isa<BinaryOperator>(E)) {
10220    BinaryOperator *Op = cast<BinaryOperator>(E);
10221    if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
10222      return;
10223
10224    IsOrAssign = Op->getOpcode() == BO_OrAssign;
10225
10226    // Greylist some idioms by putting them into a warning subcategory.
10227    if (ObjCMessageExpr *ME
10228          = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10229      Selector Sel = ME->getSelector();
10230
10231      // self = [<foo> init...]
10232      if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
10233        diagnostic = diag::warn_condition_is_idiomatic_assignment;
10234
10235      // <foo> = [<bar> nextObject]
10236      else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
10237        diagnostic = diag::warn_condition_is_idiomatic_assignment;
10238    }
10239
10240    Loc = Op->getOperatorLoc();
10241  } else if (isa<CXXOperatorCallExpr>(E)) {
10242    CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
10243    if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
10244      return;
10245
10246    IsOrAssign = Op->getOperator() == OO_PipeEqual;
10247    Loc = Op->getOperatorLoc();
10248  } else {
10249    // Not an assignment.
10250    return;
10251  }
10252
10253  Diag(Loc, diagnostic) << E->getSourceRange();
10254
10255  if (IsOrAssign)
10256    Diag(Loc, diag::note_condition_or_assign_to_comparison)
10257      << FixItHint::CreateReplacement(Loc, "!=");
10258  else
10259    Diag(Loc, diag::note_condition_assign_to_comparison)
10260      << FixItHint::CreateReplacement(Loc, "==");
10261
10262  SourceLocation Open = E->getSourceRange().getBegin();
10263  SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10264  Diag(Loc, diag::note_condition_assign_silence)
10265        << FixItHint::CreateInsertion(Open, "(")
10266        << FixItHint::CreateInsertion(Close, ")");
10267}
10268
10269/// \brief Redundant parentheses over an equality comparison can indicate
10270/// that the user intended an assignment used as condition.
10271void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
10272  // Don't warn if the parens came from a macro.
10273  SourceLocation parenLoc = parenE->getLocStart();
10274  if (parenLoc.isInvalid() || parenLoc.isMacroID())
10275    return;
10276  // Don't warn for dependent expressions.
10277  if (parenE->isTypeDependent())
10278    return;
10279
10280  Expr *E = parenE->IgnoreParens();
10281
10282  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
10283    if (opE->getOpcode() == BO_EQ &&
10284        opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10285                                                           == Expr::MLV_Valid) {
10286      SourceLocation Loc = opE->getOperatorLoc();
10287
10288      Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
10289      Diag(Loc, diag::note_equality_comparison_to_assign)
10290        << FixItHint::CreateReplacement(Loc, "=");
10291      Diag(Loc, diag::note_equality_comparison_silence)
10292        << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10293        << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
10294    }
10295}
10296
10297ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
10298  DiagnoseAssignmentAsCondition(E);
10299  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10300    DiagnoseEqualityWithExtraParens(parenE);
10301
10302  if (!E->isTypeDependent()) {
10303    if (E->isBoundMemberFunction(Context)) {
10304      Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10305        << E->getSourceRange();
10306      return ExprError();
10307    }
10308
10309    if (getLangOptions().CPlusPlus)
10310      return CheckCXXBooleanCondition(E); // C++ 6.4p4
10311
10312    ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10313    if (ERes.isInvalid())
10314      return ExprError();
10315    E = ERes.take();
10316
10317    QualType T = E->getType();
10318    if (!T->isScalarType()) { // C99 6.8.4.1p1
10319      Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10320        << T << E->getSourceRange();
10321      return ExprError();
10322    }
10323  }
10324
10325  return Owned(E);
10326}
10327
10328ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10329                                       Expr *Sub) {
10330  if (!Sub)
10331    return ExprError();
10332
10333  return CheckBooleanCondition(Sub, Loc);
10334}
10335
10336namespace {
10337  /// A visitor for rebuilding a call to an __unknown_any expression
10338  /// to have an appropriate type.
10339  struct RebuildUnknownAnyFunction
10340    : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10341
10342    Sema &S;
10343
10344    RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10345
10346    ExprResult VisitStmt(Stmt *S) {
10347      llvm_unreachable("unexpected statement!");
10348      return ExprError();
10349    }
10350
10351    ExprResult VisitExpr(Expr *expr) {
10352      S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10353        << expr->getSourceRange();
10354      return ExprError();
10355    }
10356
10357    /// Rebuild an expression which simply semantically wraps another
10358    /// expression which it shares the type and value kind of.
10359    template <class T> ExprResult rebuildSugarExpr(T *expr) {
10360      ExprResult subResult = Visit(expr->getSubExpr());
10361      if (subResult.isInvalid()) return ExprError();
10362
10363      Expr *subExpr = subResult.take();
10364      expr->setSubExpr(subExpr);
10365      expr->setType(subExpr->getType());
10366      expr->setValueKind(subExpr->getValueKind());
10367      assert(expr->getObjectKind() == OK_Ordinary);
10368      return expr;
10369    }
10370
10371    ExprResult VisitParenExpr(ParenExpr *paren) {
10372      return rebuildSugarExpr(paren);
10373    }
10374
10375    ExprResult VisitUnaryExtension(UnaryOperator *op) {
10376      return rebuildSugarExpr(op);
10377    }
10378
10379    ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10380      ExprResult subResult = Visit(op->getSubExpr());
10381      if (subResult.isInvalid()) return ExprError();
10382
10383      Expr *subExpr = subResult.take();
10384      op->setSubExpr(subExpr);
10385      op->setType(S.Context.getPointerType(subExpr->getType()));
10386      assert(op->getValueKind() == VK_RValue);
10387      assert(op->getObjectKind() == OK_Ordinary);
10388      return op;
10389    }
10390
10391    ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10392      if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10393
10394      expr->setType(decl->getType());
10395
10396      assert(expr->getValueKind() == VK_RValue);
10397      if (S.getLangOptions().CPlusPlus &&
10398          !(isa<CXXMethodDecl>(decl) &&
10399            cast<CXXMethodDecl>(decl)->isInstance()))
10400        expr->setValueKind(VK_LValue);
10401
10402      return expr;
10403    }
10404
10405    ExprResult VisitMemberExpr(MemberExpr *mem) {
10406      return resolveDecl(mem, mem->getMemberDecl());
10407    }
10408
10409    ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10410      return resolveDecl(ref, ref->getDecl());
10411    }
10412  };
10413}
10414
10415/// Given a function expression of unknown-any type, try to rebuild it
10416/// to have a function type.
10417static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10418  ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10419  if (result.isInvalid()) return ExprError();
10420  return S.DefaultFunctionArrayConversion(result.take());
10421}
10422
10423namespace {
10424  /// A visitor for rebuilding an expression of type __unknown_anytype
10425  /// into one which resolves the type directly on the referring
10426  /// expression.  Strict preservation of the original source
10427  /// structure is not a goal.
10428  struct RebuildUnknownAnyExpr
10429    : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
10430
10431    Sema &S;
10432
10433    /// The current destination type.
10434    QualType DestType;
10435
10436    RebuildUnknownAnyExpr(Sema &S, QualType castType)
10437      : S(S), DestType(castType) {}
10438
10439    ExprResult VisitStmt(Stmt *S) {
10440      llvm_unreachable("unexpected statement!");
10441      return ExprError();
10442    }
10443
10444    ExprResult VisitExpr(Expr *expr) {
10445      S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10446        << expr->getSourceRange();
10447      return ExprError();
10448    }
10449
10450    ExprResult VisitCallExpr(CallExpr *call);
10451    ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10452
10453    /// Rebuild an expression which simply semantically wraps another
10454    /// expression which it shares the type and value kind of.
10455    template <class T> ExprResult rebuildSugarExpr(T *expr) {
10456      ExprResult subResult = Visit(expr->getSubExpr());
10457      if (subResult.isInvalid()) return ExprError();
10458      Expr *subExpr = subResult.take();
10459      expr->setSubExpr(subExpr);
10460      expr->setType(subExpr->getType());
10461      expr->setValueKind(subExpr->getValueKind());
10462      assert(expr->getObjectKind() == OK_Ordinary);
10463      return expr;
10464    }
10465
10466    ExprResult VisitParenExpr(ParenExpr *paren) {
10467      return rebuildSugarExpr(paren);
10468    }
10469
10470    ExprResult VisitUnaryExtension(UnaryOperator *op) {
10471      return rebuildSugarExpr(op);
10472    }
10473
10474    ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10475      const PointerType *ptr = DestType->getAs<PointerType>();
10476      if (!ptr) {
10477        S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10478          << op->getSourceRange();
10479        return ExprError();
10480      }
10481      assert(op->getValueKind() == VK_RValue);
10482      assert(op->getObjectKind() == OK_Ordinary);
10483      op->setType(DestType);
10484
10485      // Build the sub-expression as if it were an object of the pointee type.
10486      DestType = ptr->getPointeeType();
10487      ExprResult subResult = Visit(op->getSubExpr());
10488      if (subResult.isInvalid()) return ExprError();
10489      op->setSubExpr(subResult.take());
10490      return op;
10491    }
10492
10493    ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
10494
10495    ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
10496
10497    ExprResult VisitMemberExpr(MemberExpr *mem) {
10498      return resolveDecl(mem, mem->getMemberDecl());
10499    }
10500
10501    ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10502      return resolveDecl(ref, ref->getDecl());
10503    }
10504  };
10505}
10506
10507/// Rebuilds a call expression which yielded __unknown_anytype.
10508ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10509  Expr *callee = call->getCallee();
10510
10511  enum FnKind {
10512    FK_Function,
10513    FK_FunctionPointer,
10514    FK_BlockPointer
10515  };
10516
10517  FnKind kind;
10518  QualType type = callee->getType();
10519  if (type->isFunctionType()) {
10520    assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10521    kind = FK_Function;
10522  } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10523    type = ptr->getPointeeType();
10524    kind = FK_FunctionPointer;
10525  } else {
10526    type = type->castAs<BlockPointerType>()->getPointeeType();
10527    kind = FK_BlockPointer;
10528  }
10529  const FunctionType *fnType = type->castAs<FunctionType>();
10530
10531  // Verify that this is a legal result type of a function.
10532  if (DestType->isArrayType() || DestType->isFunctionType()) {
10533    unsigned diagID = diag::err_func_returning_array_function;
10534    if (kind == FK_BlockPointer)
10535      diagID = diag::err_block_returning_array_function;
10536
10537    S.Diag(call->getExprLoc(), diagID)
10538      << DestType->isFunctionType() << DestType;
10539    return ExprError();
10540  }
10541
10542  // Otherwise, go ahead and set DestType as the call's result.
10543  call->setType(DestType.getNonLValueExprType(S.Context));
10544  call->setValueKind(Expr::getValueKindForType(DestType));
10545  assert(call->getObjectKind() == OK_Ordinary);
10546
10547  // Rebuild the function type, replacing the result type with DestType.
10548  if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10549    DestType = S.Context.getFunctionType(DestType,
10550                                         proto->arg_type_begin(),
10551                                         proto->getNumArgs(),
10552                                         proto->getExtProtoInfo());
10553  else
10554    DestType = S.Context.getFunctionNoProtoType(DestType,
10555                                                fnType->getExtInfo());
10556
10557  // Rebuild the appropriate pointer-to-function type.
10558  switch (kind) {
10559  case FK_Function:
10560    // Nothing to do.
10561    break;
10562
10563  case FK_FunctionPointer:
10564    DestType = S.Context.getPointerType(DestType);
10565    break;
10566
10567  case FK_BlockPointer:
10568    DestType = S.Context.getBlockPointerType(DestType);
10569    break;
10570  }
10571
10572  // Finally, we can recurse.
10573  ExprResult calleeResult = Visit(callee);
10574  if (!calleeResult.isUsable()) return ExprError();
10575  call->setCallee(calleeResult.take());
10576
10577  // Bind a temporary if necessary.
10578  return S.MaybeBindToTemporary(call);
10579}
10580
10581ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
10582  ObjCMethodDecl *method = msg->getMethodDecl();
10583  assert(method && "__unknown_anytype message without result type?");
10584
10585  // Verify that this is a legal result type of a call.
10586  if (DestType->isArrayType() || DestType->isFunctionType()) {
10587    S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10588      << DestType->isFunctionType() << DestType;
10589    return ExprError();
10590  }
10591
10592  assert(method->getResultType() == S.Context.UnknownAnyTy);
10593  method->setResultType(DestType);
10594
10595  // Change the type of the message.
10596  msg->setType(DestType.getNonReferenceType());
10597  msg->setValueKind(Expr::getValueKindForType(DestType));
10598
10599  return S.MaybeBindToTemporary(msg);
10600}
10601
10602ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
10603  // The only case we should ever see here is a function-to-pointer decay.
10604  assert(ice->getCastKind() == CK_FunctionToPointerDecay);
10605  assert(ice->getValueKind() == VK_RValue);
10606  assert(ice->getObjectKind() == OK_Ordinary);
10607
10608  ice->setType(DestType);
10609
10610  // Rebuild the sub-expression as the pointee (function) type.
10611  DestType = DestType->castAs<PointerType>()->getPointeeType();
10612
10613  ExprResult result = Visit(ice->getSubExpr());
10614  if (!result.isUsable()) return ExprError();
10615
10616  ice->setSubExpr(result.take());
10617  return S.Owned(ice);
10618}
10619
10620ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
10621  ExprValueKind valueKind = VK_LValue;
10622  QualType type = DestType;
10623
10624  // We know how to make this work for certain kinds of decls:
10625
10626  //  - functions
10627  if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
10628    if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
10629      if (method->isInstance()) valueKind = VK_RValue;
10630
10631    // This is true because FunctionDecls must always have function
10632    // type, so we can't be resolving the entire thing at once.
10633    assert(type->isFunctionType());
10634
10635    // Function references aren't l-values in C.
10636    if (!S.getLangOptions().CPlusPlus)
10637      valueKind = VK_RValue;
10638
10639  //  - variables
10640  } else if (isa<VarDecl>(decl)) {
10641    if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10642      type = refTy->getPointeeType();
10643    } else if (type->isFunctionType()) {
10644      S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10645        << decl << expr->getSourceRange();
10646      return ExprError();
10647    }
10648
10649  //  - nothing else
10650  } else {
10651    S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10652      << decl << expr->getSourceRange();
10653    return ExprError();
10654  }
10655
10656  decl->setType(DestType);
10657  expr->setType(type);
10658  expr->setValueKind(valueKind);
10659  return S.Owned(expr);
10660}
10661
10662/// Check a cast of an unknown-any type.  We intentionally only
10663/// trigger this for C-style casts.
10664ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10665                                     Expr *castExpr, CastKind &castKind,
10666                                     ExprValueKind &VK, CXXCastPath &path) {
10667  // Rewrite the casted expression from scratch.
10668  ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10669  if (!result.isUsable()) return ExprError();
10670
10671  castExpr = result.take();
10672  VK = castExpr->getValueKind();
10673  castKind = CK_NoOp;
10674
10675  return castExpr;
10676}
10677
10678static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10679  Expr *orig = e;
10680  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
10681  while (true) {
10682    e = e->IgnoreParenImpCasts();
10683    if (CallExpr *call = dyn_cast<CallExpr>(e)) {
10684      e = call->getCallee();
10685      diagID = diag::err_uncasted_call_of_unknown_any;
10686    } else {
10687      break;
10688    }
10689  }
10690
10691  SourceLocation loc;
10692  NamedDecl *d;
10693  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10694    loc = ref->getLocation();
10695    d = ref->getDecl();
10696  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10697    loc = mem->getMemberLoc();
10698    d = mem->getMemberDecl();
10699  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10700    diagID = diag::err_uncasted_call_of_unknown_any;
10701    loc = msg->getSelectorLoc();
10702    d = msg->getMethodDecl();
10703    assert(d && "unknown method returning __unknown_any?");
10704  } else {
10705    S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10706      << e->getSourceRange();
10707    return ExprError();
10708  }
10709
10710  S.Diag(loc, diagID) << d << orig->getSourceRange();
10711
10712  // Never recoverable.
10713  return ExprError();
10714}
10715
10716/// Check for operands with placeholder types and complain if found.
10717/// Returns true if there was an error and no recovery was possible.
10718ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
10719  // Placeholder types are always *exactly* the appropriate builtin type.
10720  QualType type = E->getType();
10721
10722  // Overloaded expressions.
10723  if (type == Context.OverloadTy)
10724    return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
10725                                                           E->getSourceRange(),
10726                                                             QualType(),
10727                                                   diag::err_ovl_unresolvable);
10728
10729  // Expressions of unknown type.
10730  if (type == Context.UnknownAnyTy)
10731    return diagnoseUnknownAnyExpr(*this, E);
10732
10733  assert(!type->isPlaceholderType());
10734  return Owned(E);
10735}
10736
10737bool Sema::CheckCaseExpression(Expr *expr) {
10738  if (expr->isTypeDependent())
10739    return true;
10740  if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10741    return expr->getType()->isIntegralOrEnumerationType();
10742  return false;
10743}
10744