SemaExpr.cpp revision 039bfd7e038eb852c66be03bb34c47fa2a7b79a7
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "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/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/RecursiveASTVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Parse/DeclSpec.h"
33#include "clang/Parse/Designator.h"
34#include "clang/Parse/Scope.h"
35#include "clang/Parse/Template.h"
36using namespace clang;
37
38
39/// \brief Determine whether the use of this declaration is valid, and
40/// emit any corresponding diagnostics.
41///
42/// This routine diagnoses various problems with referencing
43/// declarations that can occur when using a declaration. For example,
44/// it might warn if a deprecated or unavailable declaration is being
45/// used, or produce an error (and return true) if a C++0x deleted
46/// function is being used.
47///
48/// If IgnoreDeprecated is set to true, this should not want about deprecated
49/// decls.
50///
51/// \returns true if there was an error (this declaration cannot be
52/// referenced), false otherwise.
53///
54bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
55  // See if the decl is deprecated.
56  if (D->getAttr<DeprecatedAttr>()) {
57    EmitDeprecationWarning(D, Loc);
58  }
59
60  // See if the decl is unavailable
61  if (D->getAttr<UnavailableAttr>()) {
62    Diag(Loc, diag::err_unavailable) << D->getDeclName();
63    Diag(D->getLocation(), diag::note_unavailable_here) << 0;
64  }
65
66  // See if this is a deleted function.
67  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
68    if (FD->isDeleted()) {
69      Diag(Loc, diag::err_deleted_function_use);
70      Diag(D->getLocation(), diag::note_unavailable_here) << true;
71      return true;
72    }
73  }
74
75  return false;
76}
77
78/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
79/// (and other functions in future), which have been declared with sentinel
80/// attribute. It warns if call does not have the sentinel argument.
81///
82void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
83                                 Expr **Args, unsigned NumArgs) {
84  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
85  if (!attr)
86    return;
87
88  // FIXME: In C++0x, if any of the arguments are parameter pack
89  // expansions, we can't check for the sentinel now.
90  int sentinelPos = attr->getSentinel();
91  int nullPos = attr->getNullPos();
92
93  // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
94  // base class. Then we won't be needing two versions of the same code.
95  unsigned int i = 0;
96  bool warnNotEnoughArgs = false;
97  int isMethod = 0;
98  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
99    // skip over named parameters.
100    ObjCMethodDecl::param_iterator P, E = MD->param_end();
101    for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
102      if (nullPos)
103        --nullPos;
104      else
105        ++i;
106    }
107    warnNotEnoughArgs = (P != E || i >= NumArgs);
108    isMethod = 1;
109  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
110    // skip over named parameters.
111    ObjCMethodDecl::param_iterator P, E = FD->param_end();
112    for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
113      if (nullPos)
114        --nullPos;
115      else
116        ++i;
117    }
118    warnNotEnoughArgs = (P != E || i >= NumArgs);
119  } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
120    // block or function pointer call.
121    QualType Ty = V->getType();
122    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
123      const FunctionType *FT = Ty->isFunctionPointerType()
124      ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
125      : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
126      if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
127        unsigned NumArgsInProto = Proto->getNumArgs();
128        unsigned k;
129        for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
130          if (nullPos)
131            --nullPos;
132          else
133            ++i;
134        }
135        warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
136      }
137      if (Ty->isBlockPointerType())
138        isMethod = 2;
139    } else
140      return;
141  } else
142    return;
143
144  if (warnNotEnoughArgs) {
145    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
146    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
147    return;
148  }
149  int sentinel = i;
150  while (sentinelPos > 0 && i < NumArgs-1) {
151    --sentinelPos;
152    ++i;
153  }
154  if (sentinelPos > 0) {
155    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
156    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
157    return;
158  }
159  while (i < NumArgs-1) {
160    ++i;
161    ++sentinel;
162  }
163  Expr *sentinelExpr = Args[sentinel];
164  if (!sentinelExpr) return;
165  if (sentinelExpr->isTypeDependent()) return;
166  if (sentinelExpr->isValueDependent()) return;
167  if (sentinelExpr->getType()->isAnyPointerType() &&
168      sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
169                                            Expr::NPC_ValueDependentIsNull))
170    return;
171
172  // Unfortunately, __null has type 'int'.
173  if (isa<GNUNullExpr>(sentinelExpr)) return;
174
175  Diag(Loc, diag::warn_missing_sentinel) << isMethod;
176  Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
177}
178
179SourceRange Sema::getExprRange(ExprTy *E) const {
180  Expr *Ex = (Expr *)E;
181  return Ex? Ex->getSourceRange() : SourceRange();
182}
183
184//===----------------------------------------------------------------------===//
185//  Standard Promotions and Conversions
186//===----------------------------------------------------------------------===//
187
188/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
189void Sema::DefaultFunctionArrayConversion(Expr *&E) {
190  QualType Ty = E->getType();
191  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
192
193  if (Ty->isFunctionType())
194    ImpCastExprToType(E, Context.getPointerType(Ty),
195                      CastExpr::CK_FunctionToPointerDecay);
196  else if (Ty->isArrayType()) {
197    // In C90 mode, arrays only promote to pointers if the array expression is
198    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
199    // type 'array of type' is converted to an expression that has type 'pointer
200    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
201    // that has type 'array of type' ...".  The relevant change is "an lvalue"
202    // (C90) to "an expression" (C99).
203    //
204    // C++ 4.2p1:
205    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
206    // T" can be converted to an rvalue of type "pointer to T".
207    //
208    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
209        E->isLvalue(Context) == Expr::LV_Valid)
210      ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
211                        CastExpr::CK_ArrayToPointerDecay);
212  }
213}
214
215void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
216  DefaultFunctionArrayConversion(E);
217
218  QualType Ty = E->getType();
219  assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
220  if (!Ty->isDependentType() && Ty.hasQualifiers() &&
221      (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
222      E->isLvalue(Context) == Expr::LV_Valid) {
223    // C++ [conv.lval]p1:
224    //   [...] If T is a non-class type, the type of the rvalue is the
225    //   cv-unqualified version of T. Otherwise, the type of the
226    //   rvalue is T
227    //
228    // C99 6.3.2.1p2:
229    //   If the lvalue has qualified type, the value has the unqualified
230    //   version of the type of the lvalue; otherwise, the value has the
231    //   type of the lvalue.
232    ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
233  }
234}
235
236
237/// UsualUnaryConversions - Performs various conversions that are common to most
238/// operators (C99 6.3). The conversions of array and function types are
239/// sometimes surpressed. For example, the array->pointer conversion doesn't
240/// apply if the array is an argument to the sizeof or address (&) operators.
241/// In these instances, this routine should *not* be called.
242Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
243  QualType Ty = Expr->getType();
244  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
245
246  // C99 6.3.1.1p2:
247  //
248  //   The following may be used in an expression wherever an int or
249  //   unsigned int may be used:
250  //     - an object or expression with an integer type whose integer
251  //       conversion rank is less than or equal to the rank of int
252  //       and unsigned int.
253  //     - A bit-field of type _Bool, int, signed int, or unsigned int.
254  //
255  //   If an int can represent all values of the original type, the
256  //   value is converted to an int; otherwise, it is converted to an
257  //   unsigned int. These are called the integer promotions. All
258  //   other types are unchanged by the integer promotions.
259  QualType PTy = Context.isPromotableBitField(Expr);
260  if (!PTy.isNull()) {
261    ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
262    return Expr;
263  }
264  if (Ty->isPromotableIntegerType()) {
265    QualType PT = Context.getPromotedIntegerType(Ty);
266    ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
267    return Expr;
268  }
269
270  DefaultFunctionArrayLvalueConversion(Expr);
271  return Expr;
272}
273
274/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
275/// do not have a prototype. Arguments that have type float are promoted to
276/// double. All other argument types are converted by UsualUnaryConversions().
277void Sema::DefaultArgumentPromotion(Expr *&Expr) {
278  QualType Ty = Expr->getType();
279  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
280
281  // If this is a 'float' (CVR qualified or typedef) promote to double.
282  if (Ty->isSpecificBuiltinType(BuiltinType::Float))
283    return ImpCastExprToType(Expr, Context.DoubleTy,
284                             CastExpr::CK_FloatingCast);
285
286  UsualUnaryConversions(Expr);
287}
288
289/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
290/// will warn if the resulting type is not a POD type, and rejects ObjC
291/// interfaces passed by value.  This returns true if the argument type is
292/// completely illegal.
293bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
294                                            FunctionDecl *FDecl) {
295  DefaultArgumentPromotion(Expr);
296
297  // __builtin_va_start takes the second argument as a "varargs" argument, but
298  // it doesn't actually do anything with it.  It doesn't need to be non-pod
299  // etc.
300  if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
301    return false;
302
303  if (Expr->getType()->isObjCObjectType() &&
304      DiagRuntimeBehavior(Expr->getLocStart(),
305        PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
306          << Expr->getType() << CT))
307    return true;
308
309  if (!Expr->getType()->isPODType() &&
310      DiagRuntimeBehavior(Expr->getLocStart(),
311                          PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
312                            << Expr->getType() << CT))
313    return true;
314
315  return false;
316}
317
318
319/// UsualArithmeticConversions - Performs various conversions that are common to
320/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
321/// routine returns the first non-arithmetic type found. The client is
322/// responsible for emitting appropriate error diagnostics.
323/// FIXME: verify the conversion rules for "complex int" are consistent with
324/// GCC.
325QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
326                                          bool isCompAssign) {
327  if (!isCompAssign)
328    UsualUnaryConversions(lhsExpr);
329
330  UsualUnaryConversions(rhsExpr);
331
332  // For conversion purposes, we ignore any qualifiers.
333  // For example, "const float" and "float" are equivalent.
334  QualType lhs =
335    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
336  QualType rhs =
337    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
338
339  // If both types are identical, no conversion is needed.
340  if (lhs == rhs)
341    return lhs;
342
343  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
344  // The caller can deal with this (e.g. pointer + int).
345  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
346    return lhs;
347
348  // Perform bitfield promotions.
349  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
350  if (!LHSBitfieldPromoteTy.isNull())
351    lhs = LHSBitfieldPromoteTy;
352  QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
353  if (!RHSBitfieldPromoteTy.isNull())
354    rhs = RHSBitfieldPromoteTy;
355
356  QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
357  if (!isCompAssign)
358    ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
359  ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
360  return destType;
361}
362
363//===----------------------------------------------------------------------===//
364//  Semantic Analysis for various Expression Types
365//===----------------------------------------------------------------------===//
366
367
368/// ActOnStringLiteral - The specified tokens were lexed as pasted string
369/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
370/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
371/// multiple tokens.  However, the common case is that StringToks points to one
372/// string.
373///
374Action::OwningExprResult
375Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
376  assert(NumStringToks && "Must have at least one string!");
377
378  StringLiteralParser Literal(StringToks, NumStringToks, PP);
379  if (Literal.hadError)
380    return ExprError();
381
382  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
383  for (unsigned i = 0; i != NumStringToks; ++i)
384    StringTokLocs.push_back(StringToks[i].getLocation());
385
386  QualType StrTy = Context.CharTy;
387  if (Literal.AnyWide) StrTy = Context.getWCharType();
388  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
389
390  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
391  if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
392    StrTy.addConst();
393
394  // Get an array type for the string, according to C99 6.4.5.  This includes
395  // the nul terminator character as well as the string length for pascal
396  // strings.
397  StrTy = Context.getConstantArrayType(StrTy,
398                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
399                                       ArrayType::Normal, 0);
400
401  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
402  return Owned(StringLiteral::Create(Context, Literal.GetString(),
403                                     Literal.GetStringLength(),
404                                     Literal.AnyWide, StrTy,
405                                     &StringTokLocs[0],
406                                     StringTokLocs.size()));
407}
408
409/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
410/// CurBlock to VD should cause it to be snapshotted (as we do for auto
411/// variables defined outside the block) or false if this is not needed (e.g.
412/// for values inside the block or for globals).
413///
414/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
415/// up-to-date.
416///
417static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
418                                              ValueDecl *VD) {
419  // If the value is defined inside the block, we couldn't snapshot it even if
420  // we wanted to.
421  if (CurBlock->TheDecl == VD->getDeclContext())
422    return false;
423
424  // If this is an enum constant or function, it is constant, don't snapshot.
425  if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
426    return false;
427
428  // If this is a reference to an extern, static, or global variable, no need to
429  // snapshot it.
430  // FIXME: What about 'const' variables in C++?
431  if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
432    if (!Var->hasLocalStorage())
433      return false;
434
435  // Blocks that have these can't be constant.
436  CurBlock->hasBlockDeclRefExprs = true;
437
438  // If we have nested blocks, the decl may be declared in an outer block (in
439  // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
440  // be defined outside all of the current blocks (in which case the blocks do
441  // all get the bit).  Walk the nesting chain.
442  for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
443    BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
444
445    if (!NextBlock)
446      continue;
447
448    // If we found the defining block for the variable, don't mark the block as
449    // having a reference outside it.
450    if (NextBlock->TheDecl == VD->getDeclContext())
451      break;
452
453    // Otherwise, the DeclRef from the inner block causes the outer one to need
454    // a snapshot as well.
455    NextBlock->hasBlockDeclRefExprs = true;
456  }
457
458  return true;
459}
460
461
462
463/// BuildDeclRefExpr - Build a DeclRefExpr.
464Sema::OwningExprResult
465Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
466                       const CXXScopeSpec *SS) {
467  if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
468    Diag(Loc,
469         diag::err_auto_variable_cannot_appear_in_own_initializer)
470      << D->getDeclName();
471    return ExprError();
472  }
473
474  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
475    if (isa<NonTypeTemplateParmDecl>(VD)) {
476      // Non-type template parameters can be referenced anywhere they are
477      // visible.
478      Ty = Ty.getNonLValueExprType(Context);
479    } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
480      if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
481        if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
482          Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
483            << D->getIdentifier() << FD->getDeclName();
484          Diag(D->getLocation(), diag::note_local_variable_declared_here)
485            << D->getIdentifier();
486          return ExprError();
487        }
488      }
489    }
490  }
491
492  MarkDeclarationReferenced(Loc, D);
493
494  return Owned(DeclRefExpr::Create(Context,
495                              SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
496                                   SS? SS->getRange() : SourceRange(),
497                                   D, Loc, Ty));
498}
499
500/// \brief Given a field that represents a member of an anonymous
501/// struct/union, build the path from that field's context to the
502/// actual member.
503///
504/// Construct the sequence of field member references we'll have to
505/// perform to get to the field in the anonymous union/struct. The
506/// list of members is built from the field outward, so traverse it
507/// backwards to go from an object in the current context to the field
508/// we found.
509///
510/// \returns The variable from which the field access should begin,
511/// for an anonymous struct/union that is not a member of another
512/// class. Otherwise, returns NULL.
513VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
514                                   llvm::SmallVectorImpl<FieldDecl *> &Path) {
515  assert(Field->getDeclContext()->isRecord() &&
516         cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
517         && "Field must be stored inside an anonymous struct or union");
518
519  Path.push_back(Field);
520  VarDecl *BaseObject = 0;
521  DeclContext *Ctx = Field->getDeclContext();
522  do {
523    RecordDecl *Record = cast<RecordDecl>(Ctx);
524    ValueDecl *AnonObject = Record->getAnonymousStructOrUnionObject();
525    if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
526      Path.push_back(AnonField);
527    else {
528      BaseObject = cast<VarDecl>(AnonObject);
529      break;
530    }
531    Ctx = Ctx->getParent();
532  } while (Ctx->isRecord() &&
533           cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
534
535  return BaseObject;
536}
537
538Sema::OwningExprResult
539Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
540                                               FieldDecl *Field,
541                                               Expr *BaseObjectExpr,
542                                               SourceLocation OpLoc) {
543  llvm::SmallVector<FieldDecl *, 4> AnonFields;
544  VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
545                                                            AnonFields);
546
547  // Build the expression that refers to the base object, from
548  // which we will build a sequence of member references to each
549  // of the anonymous union objects and, eventually, the field we
550  // found via name lookup.
551  bool BaseObjectIsPointer = false;
552  Qualifiers BaseQuals;
553  if (BaseObject) {
554    // BaseObject is an anonymous struct/union variable (and is,
555    // therefore, not part of another non-anonymous record).
556    MarkDeclarationReferenced(Loc, BaseObject);
557    BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
558                                               SourceLocation());
559    BaseQuals
560      = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
561  } else if (BaseObjectExpr) {
562    // The caller provided the base object expression. Determine
563    // whether its a pointer and whether it adds any qualifiers to the
564    // anonymous struct/union fields we're looking into.
565    QualType ObjectType = BaseObjectExpr->getType();
566    if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
567      BaseObjectIsPointer = true;
568      ObjectType = ObjectPtr->getPointeeType();
569    }
570    BaseQuals
571      = Context.getCanonicalType(ObjectType).getQualifiers();
572  } else {
573    // We've found a member of an anonymous struct/union that is
574    // inside a non-anonymous struct/union, so in a well-formed
575    // program our base object expression is "this".
576    DeclContext *DC = getFunctionLevelDeclContext();
577    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
578      if (!MD->isStatic()) {
579        QualType AnonFieldType
580          = Context.getTagDeclType(
581                     cast<RecordDecl>(AnonFields.back()->getDeclContext()));
582        QualType ThisType = Context.getTagDeclType(MD->getParent());
583        if ((Context.getCanonicalType(AnonFieldType)
584               == Context.getCanonicalType(ThisType)) ||
585            IsDerivedFrom(ThisType, AnonFieldType)) {
586          // Our base object expression is "this".
587          BaseObjectExpr = new (Context) CXXThisExpr(Loc,
588                                                     MD->getThisType(Context),
589                                                     /*isImplicit=*/true);
590          BaseObjectIsPointer = true;
591        }
592      } else {
593        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
594          << Field->getDeclName());
595      }
596      BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
597    }
598
599    if (!BaseObjectExpr)
600      return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
601        << Field->getDeclName());
602  }
603
604  // Build the implicit member references to the field of the
605  // anonymous struct/union.
606  Expr *Result = BaseObjectExpr;
607  Qualifiers ResultQuals = BaseQuals;
608  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
609         FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
610       FI != FIEnd; ++FI) {
611    QualType MemberType = (*FI)->getType();
612    Qualifiers MemberTypeQuals =
613      Context.getCanonicalType(MemberType).getQualifiers();
614
615    // CVR attributes from the base are picked up by members,
616    // except that 'mutable' members don't pick up 'const'.
617    if ((*FI)->isMutable())
618      ResultQuals.removeConst();
619
620    // GC attributes are never picked up by members.
621    ResultQuals.removeObjCGCAttr();
622
623    // TR 18037 does not allow fields to be declared with address spaces.
624    assert(!MemberTypeQuals.hasAddressSpace());
625
626    Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
627    if (NewQuals != MemberTypeQuals)
628      MemberType = Context.getQualifiedType(MemberType, NewQuals);
629
630    MarkDeclarationReferenced(Loc, *FI);
631    PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
632    // FIXME: Might this end up being a qualified name?
633    Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
634                                      OpLoc, MemberType);
635    BaseObjectIsPointer = false;
636    ResultQuals = NewQuals;
637  }
638
639  return Owned(Result);
640}
641
642/// Decomposes the given name into a DeclarationName, its location, and
643/// possibly a list of template arguments.
644///
645/// If this produces template arguments, it is permitted to call
646/// DecomposeTemplateName.
647///
648/// This actually loses a lot of source location information for
649/// non-standard name kinds; we should consider preserving that in
650/// some way.
651static void DecomposeUnqualifiedId(Sema &SemaRef,
652                                   const UnqualifiedId &Id,
653                                   TemplateArgumentListInfo &Buffer,
654                                   DeclarationName &Name,
655                                   SourceLocation &NameLoc,
656                             const TemplateArgumentListInfo *&TemplateArgs) {
657  if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
658    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
659    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
660
661    ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
662                                       Id.TemplateId->getTemplateArgs(),
663                                       Id.TemplateId->NumArgs);
664    SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
665    TemplateArgsPtr.release();
666
667    TemplateName TName =
668      Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
669
670    Name = SemaRef.Context.getNameForTemplate(TName);
671    NameLoc = Id.TemplateId->TemplateNameLoc;
672    TemplateArgs = &Buffer;
673  } else {
674    Name = SemaRef.GetNameFromUnqualifiedId(Id);
675    NameLoc = Id.StartLocation;
676    TemplateArgs = 0;
677  }
678}
679
680/// Determines whether the given record is "fully-formed" at the given
681/// location, i.e. whether a qualified lookup into it is assured of
682/// getting consistent results already.
683static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
684  if (!Record->hasDefinition())
685    return false;
686
687  for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
688         E = Record->bases_end(); I != E; ++I) {
689    CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
690    CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
691    if (!BaseRT) return false;
692
693    CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
694    if (!BaseRecord->hasDefinition() ||
695        !IsFullyFormedScope(SemaRef, BaseRecord))
696      return false;
697  }
698
699  return true;
700}
701
702/// Determines if the given class is provably not derived from all of
703/// the prospective base classes.
704static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
705                                     CXXRecordDecl *Record,
706                            const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
707  if (Bases.count(Record->getCanonicalDecl()))
708    return false;
709
710  RecordDecl *RD = Record->getDefinition();
711  if (!RD) return false;
712  Record = cast<CXXRecordDecl>(RD);
713
714  for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
715         E = Record->bases_end(); I != E; ++I) {
716    CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
717    CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
718    if (!BaseRT) return false;
719
720    CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
721    if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
722      return false;
723  }
724
725  return true;
726}
727
728enum IMAKind {
729  /// The reference is definitely not an instance member access.
730  IMA_Static,
731
732  /// The reference may be an implicit instance member access.
733  IMA_Mixed,
734
735  /// The reference may be to an instance member, but it is invalid if
736  /// so, because the context is not an instance method.
737  IMA_Mixed_StaticContext,
738
739  /// The reference may be to an instance member, but it is invalid if
740  /// so, because the context is from an unrelated class.
741  IMA_Mixed_Unrelated,
742
743  /// The reference is definitely an implicit instance member access.
744  IMA_Instance,
745
746  /// The reference may be to an unresolved using declaration.
747  IMA_Unresolved,
748
749  /// The reference may be to an unresolved using declaration and the
750  /// context is not an instance method.
751  IMA_Unresolved_StaticContext,
752
753  /// The reference is to a member of an anonymous structure in a
754  /// non-class context.
755  IMA_AnonymousMember,
756
757  /// All possible referrents are instance members and the current
758  /// context is not an instance method.
759  IMA_Error_StaticContext,
760
761  /// All possible referrents are instance members of an unrelated
762  /// class.
763  IMA_Error_Unrelated
764};
765
766/// The given lookup names class member(s) and is not being used for
767/// an address-of-member expression.  Classify the type of access
768/// according to whether it's possible that this reference names an
769/// instance member.  This is best-effort; it is okay to
770/// conservatively answer "yes", in which case some errors will simply
771/// not be caught until template-instantiation.
772static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
773                                            const LookupResult &R) {
774  assert(!R.empty() && (*R.begin())->isCXXClassMember());
775
776  DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
777  bool isStaticContext =
778    (!isa<CXXMethodDecl>(DC) ||
779     cast<CXXMethodDecl>(DC)->isStatic());
780
781  if (R.isUnresolvableResult())
782    return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
783
784  // Collect all the declaring classes of instance members we find.
785  bool hasNonInstance = false;
786  llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
787  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
788    NamedDecl *D = *I;
789    if (D->isCXXInstanceMember()) {
790      CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
791
792      // If this is a member of an anonymous record, move out to the
793      // innermost non-anonymous struct or union.  If there isn't one,
794      // that's a special case.
795      while (R->isAnonymousStructOrUnion()) {
796        R = dyn_cast<CXXRecordDecl>(R->getParent());
797        if (!R) return IMA_AnonymousMember;
798      }
799      Classes.insert(R->getCanonicalDecl());
800    }
801    else
802      hasNonInstance = true;
803  }
804
805  // If we didn't find any instance members, it can't be an implicit
806  // member reference.
807  if (Classes.empty())
808    return IMA_Static;
809
810  // If the current context is not an instance method, it can't be
811  // an implicit member reference.
812  if (isStaticContext)
813    return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
814
815  // If we can prove that the current context is unrelated to all the
816  // declaring classes, it can't be an implicit member reference (in
817  // which case it's an error if any of those members are selected).
818  if (IsProvablyNotDerivedFrom(SemaRef,
819                               cast<CXXMethodDecl>(DC)->getParent(),
820                               Classes))
821    return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
822
823  return (hasNonInstance ? IMA_Mixed : IMA_Instance);
824}
825
826/// Diagnose a reference to a field with no object available.
827static void DiagnoseInstanceReference(Sema &SemaRef,
828                                      const CXXScopeSpec &SS,
829                                      const LookupResult &R) {
830  SourceLocation Loc = R.getNameLoc();
831  SourceRange Range(Loc);
832  if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
833
834  if (R.getAsSingle<FieldDecl>()) {
835    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
836      if (MD->isStatic()) {
837        // "invalid use of member 'x' in static member function"
838        SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
839          << Range << R.getLookupName();
840        return;
841      }
842    }
843
844    SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
845      << R.getLookupName() << Range;
846    return;
847  }
848
849  SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
850}
851
852/// Diagnose an empty lookup.
853///
854/// \return false if new lookup candidates were found
855bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
856                               CorrectTypoContext CTC) {
857  DeclarationName Name = R.getLookupName();
858
859  unsigned diagnostic = diag::err_undeclared_var_use;
860  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
861  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
862      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
863      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
864    diagnostic = diag::err_undeclared_use;
865    diagnostic_suggest = diag::err_undeclared_use_suggest;
866  }
867
868  // If the original lookup was an unqualified lookup, fake an
869  // unqualified lookup.  This is useful when (for example) the
870  // original lookup would not have found something because it was a
871  // dependent name.
872  for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
873       DC; DC = DC->getParent()) {
874    if (isa<CXXRecordDecl>(DC)) {
875      LookupQualifiedName(R, DC);
876
877      if (!R.empty()) {
878        // Don't give errors about ambiguities in this lookup.
879        R.suppressDiagnostics();
880
881        CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
882        bool isInstance = CurMethod &&
883                          CurMethod->isInstance() &&
884                          DC == CurMethod->getParent();
885
886        // Give a code modification hint to insert 'this->'.
887        // TODO: fixit for inserting 'Base<T>::' in the other cases.
888        // Actually quite difficult!
889        if (isInstance) {
890          Diag(R.getNameLoc(), diagnostic) << Name
891            << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
892
893          UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
894              CallsUndergoingInstantiation.back()->getCallee());
895          CXXMethodDecl *DepMethod = cast<CXXMethodDecl>(
896              CurMethod->getInstantiatedFromMemberFunction());
897          QualType DepThisType = DepMethod->getThisType(Context);
898          CXXThisExpr *DepThis = new (Context) CXXThisExpr(R.getNameLoc(),
899                                                           DepThisType, false);
900          TemplateArgumentListInfo TList;
901          if (ULE->hasExplicitTemplateArgs())
902            ULE->copyTemplateArgumentsInto(TList);
903          CXXDependentScopeMemberExpr *DepExpr =
904              CXXDependentScopeMemberExpr::Create(
905                  Context, DepThis, DepThisType, true, SourceLocation(),
906                  ULE->getQualifier(), ULE->getQualifierRange(), NULL, Name,
907                  R.getNameLoc(), &TList);
908          CallsUndergoingInstantiation.back()->setCallee(DepExpr);
909        } else {
910          Diag(R.getNameLoc(), diagnostic) << Name;
911        }
912
913        // Do we really want to note all of these?
914        for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
915          Diag((*I)->getLocation(), diag::note_dependent_var_use);
916
917        // Tell the callee to try to recover.
918        return false;
919      }
920    }
921  }
922
923  // We didn't find anything, so try to correct for a typo.
924  DeclarationName Corrected;
925  if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
926    if (!R.empty()) {
927      if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
928        if (SS.isEmpty())
929          Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
930            << FixItHint::CreateReplacement(R.getNameLoc(),
931                                            R.getLookupName().getAsString());
932        else
933          Diag(R.getNameLoc(), diag::err_no_member_suggest)
934            << Name << computeDeclContext(SS, false) << R.getLookupName()
935            << SS.getRange()
936            << FixItHint::CreateReplacement(R.getNameLoc(),
937                                            R.getLookupName().getAsString());
938        if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
939          Diag(ND->getLocation(), diag::note_previous_decl)
940            << ND->getDeclName();
941
942        // Tell the callee to try to recover.
943        return false;
944      }
945
946      if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
947        // FIXME: If we ended up with a typo for a type name or
948        // Objective-C class name, we're in trouble because the parser
949        // is in the wrong place to recover. Suggest the typo
950        // correction, but don't make it a fix-it since we're not going
951        // to recover well anyway.
952        if (SS.isEmpty())
953          Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
954        else
955          Diag(R.getNameLoc(), diag::err_no_member_suggest)
956            << Name << computeDeclContext(SS, false) << R.getLookupName()
957            << SS.getRange();
958
959        // Don't try to recover; it won't work.
960        return true;
961      }
962    } else {
963      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
964      // because we aren't able to recover.
965      if (SS.isEmpty())
966        Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
967      else
968        Diag(R.getNameLoc(), diag::err_no_member_suggest)
969        << Name << computeDeclContext(SS, false) << Corrected
970        << SS.getRange();
971      return true;
972    }
973    R.clear();
974  }
975
976  // Emit a special diagnostic for failed member lookups.
977  // FIXME: computing the declaration context might fail here (?)
978  if (!SS.isEmpty()) {
979    Diag(R.getNameLoc(), diag::err_no_member)
980      << Name << computeDeclContext(SS, false)
981      << SS.getRange();
982    return true;
983  }
984
985  // Give up, we can't recover.
986  Diag(R.getNameLoc(), diagnostic) << Name;
987  return true;
988}
989
990static ObjCPropertyDecl *OkToSynthesizeProvisionalIvar(Sema &SemaRef,
991                                                       IdentifierInfo *II,
992                                                       SourceLocation NameLoc) {
993  ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
994  ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
995  if (!IDecl)
996    return 0;
997  ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
998  if (!ClassImpDecl)
999    return 0;
1000  ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1001  if (!property)
1002    return 0;
1003  if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1004    if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
1005      return 0;
1006  return property;
1007}
1008
1009static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
1010                                               LookupResult &Lookup,
1011                                               IdentifierInfo *II,
1012                                               SourceLocation NameLoc) {
1013  ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1014  bool LookForIvars;
1015  if (Lookup.empty())
1016    LookForIvars = true;
1017  else if (CurMeth->isClassMethod())
1018    LookForIvars = false;
1019  else
1020    LookForIvars = (Lookup.isSingleResult() &&
1021                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1022  if (!LookForIvars)
1023    return 0;
1024
1025  ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1026  if (!IDecl)
1027    return 0;
1028  ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1029  if (!ClassImpDecl)
1030    return 0;
1031  bool DynamicImplSeen = false;
1032  ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1033  if (!property)
1034    return 0;
1035  if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1036    DynamicImplSeen =
1037      (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1038  if (!DynamicImplSeen) {
1039    QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1040    ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
1041                                              NameLoc,
1042                                              II, PropType, /*Dinfo=*/0,
1043                                              ObjCIvarDecl::Protected,
1044                                              (Expr *)0, true);
1045    ClassImpDecl->addDecl(Ivar);
1046    IDecl->makeDeclVisibleInContext(Ivar, false);
1047    property->setPropertyIvarDecl(Ivar);
1048    return Ivar;
1049  }
1050  return 0;
1051}
1052
1053Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
1054                                               CXXScopeSpec &SS,
1055                                               UnqualifiedId &Id,
1056                                               bool HasTrailingLParen,
1057                                               bool isAddressOfOperand) {
1058  assert(!(isAddressOfOperand && HasTrailingLParen) &&
1059         "cannot be direct & operand and have a trailing lparen");
1060
1061  if (SS.isInvalid())
1062    return ExprError();
1063
1064  TemplateArgumentListInfo TemplateArgsBuffer;
1065
1066  // Decompose the UnqualifiedId into the following data.
1067  DeclarationName Name;
1068  SourceLocation NameLoc;
1069  const TemplateArgumentListInfo *TemplateArgs;
1070  DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1071                         Name, NameLoc, TemplateArgs);
1072
1073  IdentifierInfo *II = Name.getAsIdentifierInfo();
1074
1075  // C++ [temp.dep.expr]p3:
1076  //   An id-expression is type-dependent if it contains:
1077  //     -- an identifier that was declared with a dependent type,
1078  //        (note: handled after lookup)
1079  //     -- a template-id that is dependent,
1080  //        (note: handled in BuildTemplateIdExpr)
1081  //     -- a conversion-function-id that specifies a dependent type,
1082  //     -- a nested-name-specifier that contains a class-name that
1083  //        names a dependent type.
1084  // Determine whether this is a member of an unknown specialization;
1085  // we need to handle these differently.
1086  bool DependentID = false;
1087  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1088      Name.getCXXNameType()->isDependentType()) {
1089    DependentID = true;
1090  } else if (SS.isSet()) {
1091    DeclContext *DC = computeDeclContext(SS, false);
1092    if (DC) {
1093      if (RequireCompleteDeclContext(SS, DC))
1094        return ExprError();
1095      // FIXME: We should be checking whether DC is the current instantiation.
1096      if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1097        DependentID = !IsFullyFormedScope(*this, RD);
1098    } else {
1099      DependentID = true;
1100    }
1101  }
1102
1103  if (DependentID) {
1104    return ActOnDependentIdExpression(SS, Name, NameLoc,
1105                                      isAddressOfOperand,
1106                                      TemplateArgs);
1107  }
1108  bool IvarLookupFollowUp = false;
1109  // Perform the required lookup.
1110  LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1111  if (TemplateArgs) {
1112    // Lookup the template name again to correctly establish the context in
1113    // which it was found. This is really unfortunate as we already did the
1114    // lookup to determine that it was a template name in the first place. If
1115    // this becomes a performance hit, we can work harder to preserve those
1116    // results until we get here but it's likely not worth it.
1117    bool MemberOfUnknownSpecialization;
1118    LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1119                       MemberOfUnknownSpecialization);
1120  } else {
1121    IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1122    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1123
1124    // If this reference is in an Objective-C method, then we need to do
1125    // some special Objective-C lookup, too.
1126    if (IvarLookupFollowUp) {
1127      OwningExprResult E(LookupInObjCMethod(R, S, II, true));
1128      if (E.isInvalid())
1129        return ExprError();
1130
1131      Expr *Ex = E.takeAs<Expr>();
1132      if (Ex) return Owned(Ex);
1133      // Synthesize ivars lazily
1134      if (getLangOptions().ObjCNonFragileABI2) {
1135        if (SynthesizeProvisionalIvar(*this, R, II, NameLoc))
1136          return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1137                                   isAddressOfOperand);
1138      }
1139    }
1140  }
1141
1142  if (R.isAmbiguous())
1143    return ExprError();
1144
1145  // Determine whether this name might be a candidate for
1146  // argument-dependent lookup.
1147  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1148
1149  if (R.empty() && !ADL) {
1150    // Otherwise, this could be an implicitly declared function reference (legal
1151    // in C90, extension in C99, forbidden in C++).
1152    if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1153      NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1154      if (D) R.addDecl(D);
1155    }
1156
1157    // If this name wasn't predeclared and if this is not a function
1158    // call, diagnose the problem.
1159    if (R.empty()) {
1160      if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1161        return ExprError();
1162
1163      assert(!R.empty() &&
1164             "DiagnoseEmptyLookup returned false but added no results");
1165
1166      // If we found an Objective-C instance variable, let
1167      // LookupInObjCMethod build the appropriate expression to
1168      // reference the ivar.
1169      if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1170        R.clear();
1171        OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1172        assert(E.isInvalid() || E.get());
1173        return move(E);
1174      }
1175    }
1176  }
1177
1178  // This is guaranteed from this point on.
1179  assert(!R.empty() || ADL);
1180
1181  if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
1182    if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
1183        !getLangOptions().ObjCNonFragileABI2 &&
1184        Var->isFileVarDecl()) {
1185      ObjCPropertyDecl *Property =
1186        OkToSynthesizeProvisionalIvar(*this, II, NameLoc);
1187      if (Property) {
1188        Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1189        Diag(Property->getLocation(), diag::note_property_declare);
1190      }
1191    }
1192  } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
1193    if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1194      // C99 DR 316 says that, if a function type comes from a
1195      // function definition (without a prototype), that type is only
1196      // used for checking compatibility. Therefore, when referencing
1197      // the function, we pretend that we don't have the full function
1198      // type.
1199      if (DiagnoseUseOfDecl(Func, NameLoc))
1200        return ExprError();
1201
1202      QualType T = Func->getType();
1203      QualType NoProtoType = T;
1204      if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
1205        NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1206                                                     Proto->getExtInfo());
1207      return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
1208    }
1209  }
1210
1211  // Check whether this might be a C++ implicit instance member access.
1212  // C++ [expr.prim.general]p6:
1213  //   Within the definition of a non-static member function, an
1214  //   identifier that names a non-static member is transformed to a
1215  //   class member access expression.
1216  // But note that &SomeClass::foo is grammatically distinct, even
1217  // though we don't parse it that way.
1218  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1219    bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
1220    if (!isAbstractMemberPointer)
1221      return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1222  }
1223
1224  if (TemplateArgs)
1225    return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1226
1227  return BuildDeclarationNameExpr(SS, R, ADL);
1228}
1229
1230/// Builds an expression which might be an implicit member expression.
1231Sema::OwningExprResult
1232Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1233                                      LookupResult &R,
1234                                const TemplateArgumentListInfo *TemplateArgs) {
1235  switch (ClassifyImplicitMemberAccess(*this, R)) {
1236  case IMA_Instance:
1237    return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1238
1239  case IMA_AnonymousMember:
1240    assert(R.isSingleResult());
1241    return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1242                                                    R.getAsSingle<FieldDecl>());
1243
1244  case IMA_Mixed:
1245  case IMA_Mixed_Unrelated:
1246  case IMA_Unresolved:
1247    return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1248
1249  case IMA_Static:
1250  case IMA_Mixed_StaticContext:
1251  case IMA_Unresolved_StaticContext:
1252    if (TemplateArgs)
1253      return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1254    return BuildDeclarationNameExpr(SS, R, false);
1255
1256  case IMA_Error_StaticContext:
1257  case IMA_Error_Unrelated:
1258    DiagnoseInstanceReference(*this, SS, R);
1259    return ExprError();
1260  }
1261
1262  llvm_unreachable("unexpected instance member access kind");
1263  return ExprError();
1264}
1265
1266/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1267/// declaration name, generally during template instantiation.
1268/// There's a large number of things which don't need to be done along
1269/// this path.
1270Sema::OwningExprResult
1271Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1272                                        DeclarationName Name,
1273                                        SourceLocation NameLoc) {
1274  DeclContext *DC;
1275  if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1276    return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1277
1278  if (RequireCompleteDeclContext(SS, DC))
1279    return ExprError();
1280
1281  LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1282  LookupQualifiedName(R, DC);
1283
1284  if (R.isAmbiguous())
1285    return ExprError();
1286
1287  if (R.empty()) {
1288    Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1289    return ExprError();
1290  }
1291
1292  return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1293}
1294
1295/// LookupInObjCMethod - The parser has read a name in, and Sema has
1296/// detected that we're currently inside an ObjC method.  Perform some
1297/// additional lookup.
1298///
1299/// Ideally, most of this would be done by lookup, but there's
1300/// actually quite a lot of extra work involved.
1301///
1302/// Returns a null sentinel to indicate trivial success.
1303Sema::OwningExprResult
1304Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1305                         IdentifierInfo *II, bool AllowBuiltinCreation) {
1306  SourceLocation Loc = Lookup.getNameLoc();
1307  ObjCMethodDecl *CurMethod = getCurMethodDecl();
1308
1309  // There are two cases to handle here.  1) scoped lookup could have failed,
1310  // in which case we should look for an ivar.  2) scoped lookup could have
1311  // found a decl, but that decl is outside the current instance method (i.e.
1312  // a global variable).  In these two cases, we do a lookup for an ivar with
1313  // this name, if the lookup sucedes, we replace it our current decl.
1314
1315  // If we're in a class method, we don't normally want to look for
1316  // ivars.  But if we don't find anything else, and there's an
1317  // ivar, that's an error.
1318  bool IsClassMethod = CurMethod->isClassMethod();
1319
1320  bool LookForIvars;
1321  if (Lookup.empty())
1322    LookForIvars = true;
1323  else if (IsClassMethod)
1324    LookForIvars = false;
1325  else
1326    LookForIvars = (Lookup.isSingleResult() &&
1327                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1328  ObjCInterfaceDecl *IFace = 0;
1329  if (LookForIvars) {
1330    IFace = CurMethod->getClassInterface();
1331    ObjCInterfaceDecl *ClassDeclared;
1332    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1333      // Diagnose using an ivar in a class method.
1334      if (IsClassMethod)
1335        return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1336                         << IV->getDeclName());
1337
1338      // If we're referencing an invalid decl, just return this as a silent
1339      // error node.  The error diagnostic was already emitted on the decl.
1340      if (IV->isInvalidDecl())
1341        return ExprError();
1342
1343      // Check if referencing a field with __attribute__((deprecated)).
1344      if (DiagnoseUseOfDecl(IV, Loc))
1345        return ExprError();
1346
1347      // Diagnose the use of an ivar outside of the declaring class.
1348      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1349          ClassDeclared != IFace)
1350        Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1351
1352      // FIXME: This should use a new expr for a direct reference, don't
1353      // turn this into Self->ivar, just return a BareIVarExpr or something.
1354      IdentifierInfo &II = Context.Idents.get("self");
1355      UnqualifiedId SelfName;
1356      SelfName.setIdentifier(&II, SourceLocation());
1357      CXXScopeSpec SelfScopeSpec;
1358      OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1359                                                    SelfName, false, false);
1360      MarkDeclarationReferenced(Loc, IV);
1361      return Owned(new (Context)
1362                   ObjCIvarRefExpr(IV, IV->getType(), Loc,
1363                                   SelfExpr.takeAs<Expr>(), true, true));
1364    }
1365  } else if (CurMethod->isInstanceMethod()) {
1366    // We should warn if a local variable hides an ivar.
1367    ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
1368    ObjCInterfaceDecl *ClassDeclared;
1369    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1370      if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1371          IFace == ClassDeclared)
1372        Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1373    }
1374  }
1375
1376  if (Lookup.empty() && II && AllowBuiltinCreation) {
1377    // FIXME. Consolidate this with similar code in LookupName.
1378    if (unsigned BuiltinID = II->getBuiltinID()) {
1379      if (!(getLangOptions().CPlusPlus &&
1380            Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1381        NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1382                                           S, Lookup.isForRedeclaration(),
1383                                           Lookup.getNameLoc());
1384        if (D) Lookup.addDecl(D);
1385      }
1386    }
1387  }
1388  // Sentinel value saying that we didn't do anything special.
1389  return Owned((Expr*) 0);
1390}
1391
1392/// \brief Cast a base object to a member's actual type.
1393///
1394/// Logically this happens in three phases:
1395///
1396/// * First we cast from the base type to the naming class.
1397///   The naming class is the class into which we were looking
1398///   when we found the member;  it's the qualifier type if a
1399///   qualifier was provided, and otherwise it's the base type.
1400///
1401/// * Next we cast from the naming class to the declaring class.
1402///   If the member we found was brought into a class's scope by
1403///   a using declaration, this is that class;  otherwise it's
1404///   the class declaring the member.
1405///
1406/// * Finally we cast from the declaring class to the "true"
1407///   declaring class of the member.  This conversion does not
1408///   obey access control.
1409bool
1410Sema::PerformObjectMemberConversion(Expr *&From,
1411                                    NestedNameSpecifier *Qualifier,
1412                                    NamedDecl *FoundDecl,
1413                                    NamedDecl *Member) {
1414  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1415  if (!RD)
1416    return false;
1417
1418  QualType DestRecordType;
1419  QualType DestType;
1420  QualType FromRecordType;
1421  QualType FromType = From->getType();
1422  bool PointerConversions = false;
1423  if (isa<FieldDecl>(Member)) {
1424    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
1425
1426    if (FromType->getAs<PointerType>()) {
1427      DestType = Context.getPointerType(DestRecordType);
1428      FromRecordType = FromType->getPointeeType();
1429      PointerConversions = true;
1430    } else {
1431      DestType = DestRecordType;
1432      FromRecordType = FromType;
1433    }
1434  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1435    if (Method->isStatic())
1436      return false;
1437
1438    DestType = Method->getThisType(Context);
1439    DestRecordType = DestType->getPointeeType();
1440
1441    if (FromType->getAs<PointerType>()) {
1442      FromRecordType = FromType->getPointeeType();
1443      PointerConversions = true;
1444    } else {
1445      FromRecordType = FromType;
1446      DestType = DestRecordType;
1447    }
1448  } else {
1449    // No conversion necessary.
1450    return false;
1451  }
1452
1453  if (DestType->isDependentType() || FromType->isDependentType())
1454    return false;
1455
1456  // If the unqualified types are the same, no conversion is necessary.
1457  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1458    return false;
1459
1460  SourceRange FromRange = From->getSourceRange();
1461  SourceLocation FromLoc = FromRange.getBegin();
1462
1463  ImplicitCastExpr::ResultCategory Category = CastCategory(From);
1464
1465  // C++ [class.member.lookup]p8:
1466  //   [...] Ambiguities can often be resolved by qualifying a name with its
1467  //   class name.
1468  //
1469  // If the member was a qualified name and the qualified referred to a
1470  // specific base subobject type, we'll cast to that intermediate type
1471  // first and then to the object in which the member is declared. That allows
1472  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1473  //
1474  //   class Base { public: int x; };
1475  //   class Derived1 : public Base { };
1476  //   class Derived2 : public Base { };
1477  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
1478  //
1479  //   void VeryDerived::f() {
1480  //     x = 17; // error: ambiguous base subobjects
1481  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
1482  //   }
1483  if (Qualifier) {
1484    QualType QType = QualType(Qualifier->getAsType(), 0);
1485    assert(!QType.isNull() && "lookup done with dependent qualifier?");
1486    assert(QType->isRecordType() && "lookup done with non-record type");
1487
1488    QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1489
1490    // In C++98, the qualifier type doesn't actually have to be a base
1491    // type of the object type, in which case we just ignore it.
1492    // Otherwise build the appropriate casts.
1493    if (IsDerivedFrom(FromRecordType, QRecordType)) {
1494      CXXBaseSpecifierArray BasePath;
1495      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
1496                                       FromLoc, FromRange, &BasePath))
1497        return true;
1498
1499      if (PointerConversions)
1500        QType = Context.getPointerType(QType);
1501      ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
1502                        Category, BasePath);
1503
1504      FromType = QType;
1505      FromRecordType = QRecordType;
1506
1507      // If the qualifier type was the same as the destination type,
1508      // we're done.
1509      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1510        return false;
1511    }
1512  }
1513
1514  bool IgnoreAccess = false;
1515
1516  // If we actually found the member through a using declaration, cast
1517  // down to the using declaration's type.
1518  //
1519  // Pointer equality is fine here because only one declaration of a
1520  // class ever has member declarations.
1521  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1522    assert(isa<UsingShadowDecl>(FoundDecl));
1523    QualType URecordType = Context.getTypeDeclType(
1524                           cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1525
1526    // We only need to do this if the naming-class to declaring-class
1527    // conversion is non-trivial.
1528    if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1529      assert(IsDerivedFrom(FromRecordType, URecordType));
1530      CXXBaseSpecifierArray BasePath;
1531      if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
1532                                       FromLoc, FromRange, &BasePath))
1533        return true;
1534
1535      QualType UType = URecordType;
1536      if (PointerConversions)
1537        UType = Context.getPointerType(UType);
1538      ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
1539                        Category, BasePath);
1540      FromType = UType;
1541      FromRecordType = URecordType;
1542    }
1543
1544    // We don't do access control for the conversion from the
1545    // declaring class to the true declaring class.
1546    IgnoreAccess = true;
1547  }
1548
1549  CXXBaseSpecifierArray BasePath;
1550  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1551                                   FromLoc, FromRange, &BasePath,
1552                                   IgnoreAccess))
1553    return true;
1554
1555  ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
1556                    Category, BasePath);
1557  return false;
1558}
1559
1560/// \brief Build a MemberExpr AST node.
1561static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
1562                                   const CXXScopeSpec &SS, ValueDecl *Member,
1563                                   DeclAccessPair FoundDecl,
1564                                   SourceLocation Loc, QualType Ty,
1565                          const TemplateArgumentListInfo *TemplateArgs = 0) {
1566  NestedNameSpecifier *Qualifier = 0;
1567  SourceRange QualifierRange;
1568  if (SS.isSet()) {
1569    Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1570    QualifierRange = SS.getRange();
1571  }
1572
1573  return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1574                            Member, FoundDecl, Loc, TemplateArgs, Ty);
1575}
1576
1577/// Builds an implicit member access expression.  The current context
1578/// is known to be an instance method, and the given unqualified lookup
1579/// set is known to contain only instance members, at least one of which
1580/// is from an appropriate type.
1581Sema::OwningExprResult
1582Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1583                              LookupResult &R,
1584                              const TemplateArgumentListInfo *TemplateArgs,
1585                              bool IsKnownInstance) {
1586  assert(!R.empty() && !R.isAmbiguous());
1587
1588  SourceLocation Loc = R.getNameLoc();
1589
1590  // We may have found a field within an anonymous union or struct
1591  // (C++ [class.union]).
1592  // FIXME: This needs to happen post-isImplicitMemberReference?
1593  // FIXME: template-ids inside anonymous structs?
1594  if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
1595    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1596      return BuildAnonymousStructUnionMemberReference(Loc, FD);
1597
1598  // If this is known to be an instance access, go ahead and build a
1599  // 'this' expression now.
1600  DeclContext *DC = getFunctionLevelDeclContext();
1601  QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
1602  Expr *This = 0; // null signifies implicit access
1603  if (IsKnownInstance) {
1604    SourceLocation Loc = R.getNameLoc();
1605    if (SS.getRange().isValid())
1606      Loc = SS.getRange().getBegin();
1607    This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
1608  }
1609
1610  return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1611                                  /*OpLoc*/ SourceLocation(),
1612                                  /*IsArrow*/ true,
1613                                  SS,
1614                                  /*FirstQualifierInScope*/ 0,
1615                                  R, TemplateArgs);
1616}
1617
1618bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
1619                                      const LookupResult &R,
1620                                      bool HasTrailingLParen) {
1621  // Only when used directly as the postfix-expression of a call.
1622  if (!HasTrailingLParen)
1623    return false;
1624
1625  // Never if a scope specifier was provided.
1626  if (SS.isSet())
1627    return false;
1628
1629  // Only in C++ or ObjC++.
1630  if (!getLangOptions().CPlusPlus)
1631    return false;
1632
1633  // Turn off ADL when we find certain kinds of declarations during
1634  // normal lookup:
1635  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1636    NamedDecl *D = *I;
1637
1638    // C++0x [basic.lookup.argdep]p3:
1639    //     -- a declaration of a class member
1640    // Since using decls preserve this property, we check this on the
1641    // original decl.
1642    if (D->isCXXClassMember())
1643      return false;
1644
1645    // C++0x [basic.lookup.argdep]p3:
1646    //     -- a block-scope function declaration that is not a
1647    //        using-declaration
1648    // NOTE: we also trigger this for function templates (in fact, we
1649    // don't check the decl type at all, since all other decl types
1650    // turn off ADL anyway).
1651    if (isa<UsingShadowDecl>(D))
1652      D = cast<UsingShadowDecl>(D)->getTargetDecl();
1653    else if (D->getDeclContext()->isFunctionOrMethod())
1654      return false;
1655
1656    // C++0x [basic.lookup.argdep]p3:
1657    //     -- a declaration that is neither a function or a function
1658    //        template
1659    // And also for builtin functions.
1660    if (isa<FunctionDecl>(D)) {
1661      FunctionDecl *FDecl = cast<FunctionDecl>(D);
1662
1663      // But also builtin functions.
1664      if (FDecl->getBuiltinID() && FDecl->isImplicit())
1665        return false;
1666    } else if (!isa<FunctionTemplateDecl>(D))
1667      return false;
1668  }
1669
1670  return true;
1671}
1672
1673
1674/// Diagnoses obvious problems with the use of the given declaration
1675/// as an expression.  This is only actually called for lookups that
1676/// were not overloaded, and it doesn't promise that the declaration
1677/// will in fact be used.
1678static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1679  if (isa<TypedefDecl>(D)) {
1680    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1681    return true;
1682  }
1683
1684  if (isa<ObjCInterfaceDecl>(D)) {
1685    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1686    return true;
1687  }
1688
1689  if (isa<NamespaceDecl>(D)) {
1690    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1691    return true;
1692  }
1693
1694  return false;
1695}
1696
1697Sema::OwningExprResult
1698Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
1699                               LookupResult &R,
1700                               bool NeedsADL) {
1701  // If this is a single, fully-resolved result and we don't need ADL,
1702  // just build an ordinary singleton decl ref.
1703  if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
1704    return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
1705
1706  // We only need to check the declaration if there's exactly one
1707  // result, because in the overloaded case the results can only be
1708  // functions and function templates.
1709  if (R.isSingleResult() &&
1710      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
1711    return ExprError();
1712
1713  // Otherwise, just build an unresolved lookup expression.  Suppress
1714  // any lookup-related diagnostics; we'll hash these out later, when
1715  // we've picked a target.
1716  R.suppressDiagnostics();
1717
1718  bool Dependent
1719    = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
1720  UnresolvedLookupExpr *ULE
1721    = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
1722                                   (NestedNameSpecifier*) SS.getScopeRep(),
1723                                   SS.getRange(),
1724                                   R.getLookupName(), R.getNameLoc(),
1725                                   NeedsADL, R.isOverloadedResult(),
1726                                   R.begin(), R.end());
1727
1728  return Owned(ULE);
1729}
1730
1731
1732/// \brief Complete semantic analysis for a reference to the given declaration.
1733Sema::OwningExprResult
1734Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
1735                               SourceLocation Loc, NamedDecl *D) {
1736  assert(D && "Cannot refer to a NULL declaration");
1737  assert(!isa<FunctionTemplateDecl>(D) &&
1738         "Cannot refer unambiguously to a function template");
1739
1740  if (CheckDeclInExpr(*this, Loc, D))
1741    return ExprError();
1742
1743  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1744    // Specifically diagnose references to class templates that are missing
1745    // a template argument list.
1746    Diag(Loc, diag::err_template_decl_ref)
1747      << Template << SS.getRange();
1748    Diag(Template->getLocation(), diag::note_template_decl_here);
1749    return ExprError();
1750  }
1751
1752  // Make sure that we're referring to a value.
1753  ValueDecl *VD = dyn_cast<ValueDecl>(D);
1754  if (!VD) {
1755    Diag(Loc, diag::err_ref_non_value)
1756      << D << SS.getRange();
1757    Diag(D->getLocation(), diag::note_declared_at);
1758    return ExprError();
1759  }
1760
1761  // Check whether this declaration can be used. Note that we suppress
1762  // this check when we're going to perform argument-dependent lookup
1763  // on this function name, because this might not be the function
1764  // that overload resolution actually selects.
1765  if (DiagnoseUseOfDecl(VD, Loc))
1766    return ExprError();
1767
1768  // Only create DeclRefExpr's for valid Decl's.
1769  if (VD->isInvalidDecl())
1770    return ExprError();
1771
1772  // If the identifier reference is inside a block, and it refers to a value
1773  // that is outside the block, create a BlockDeclRefExpr instead of a
1774  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
1775  // the block is formed.
1776  //
1777  // We do not do this for things like enum constants, global variables, etc,
1778  // as they do not get snapshotted.
1779  //
1780  if (getCurBlock() &&
1781      ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
1782    if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1783      Diag(Loc, diag::err_ref_vm_type);
1784      Diag(D->getLocation(), diag::note_declared_at);
1785      return ExprError();
1786    }
1787
1788    if (VD->getType()->isArrayType()) {
1789      Diag(Loc, diag::err_ref_array_type);
1790      Diag(D->getLocation(), diag::note_declared_at);
1791      return ExprError();
1792    }
1793
1794    MarkDeclarationReferenced(Loc, VD);
1795    QualType ExprTy = VD->getType().getNonReferenceType();
1796    // The BlocksAttr indicates the variable is bound by-reference.
1797    if (VD->getAttr<BlocksAttr>())
1798      return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
1799    // This is to record that a 'const' was actually synthesize and added.
1800    bool constAdded = !ExprTy.isConstQualified();
1801    // Variable will be bound by-copy, make it const within the closure.
1802
1803    ExprTy.addConst();
1804    QualType T = VD->getType();
1805    BlockDeclRefExpr *BDRE = new (Context) BlockDeclRefExpr(VD,
1806                                                            ExprTy, Loc, false,
1807                                                            constAdded);
1808    if (getLangOptions().CPlusPlus) {
1809      if (!T->isDependentType() && !T->isReferenceType()) {
1810        Expr *E = new (Context)
1811                    DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
1812                                          SourceLocation());
1813
1814        OwningExprResult Res = PerformCopyInitialization(
1815                          InitializedEntity::InitializeBlock(VD->getLocation(),
1816                                                         T, false),
1817                                                         SourceLocation(),
1818                                                         Owned(E));
1819        if (!Res.isInvalid()) {
1820          Res = MaybeCreateCXXExprWithTemporaries(move(Res));
1821          Expr *Init = Res.takeAs<Expr>();
1822          BDRE->setCopyConstructorExpr(Init);
1823        }
1824      }
1825    }
1826    return Owned(BDRE);
1827  }
1828  // If this reference is not in a block or if the referenced variable is
1829  // within the block, create a normal DeclRefExpr.
1830
1831  return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
1832}
1833
1834Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1835                                                 tok::TokenKind Kind) {
1836  PredefinedExpr::IdentType IT;
1837
1838  switch (Kind) {
1839  default: assert(0 && "Unknown simple primary expr!");
1840  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1841  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1842  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
1843  }
1844
1845  // Pre-defined identifiers are of type char[x], where x is the length of the
1846  // string.
1847
1848  Decl *currentDecl = getCurFunctionOrMethodDecl();
1849  if (!currentDecl && getCurBlock())
1850    currentDecl = getCurBlock()->TheDecl;
1851  if (!currentDecl) {
1852    Diag(Loc, diag::ext_predef_outside_function);
1853    currentDecl = Context.getTranslationUnitDecl();
1854  }
1855
1856  QualType ResTy;
1857  if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1858    ResTy = Context.DependentTy;
1859  } else {
1860    unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
1861
1862    llvm::APInt LengthI(32, Length + 1);
1863    ResTy = Context.CharTy.withConst();
1864    ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1865  }
1866  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1867}
1868
1869Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1870  llvm::SmallString<16> CharBuffer;
1871  bool Invalid = false;
1872  llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1873  if (Invalid)
1874    return ExprError();
1875
1876  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1877                            PP);
1878  if (Literal.hadError())
1879    return ExprError();
1880
1881  QualType Ty;
1882  if (!getLangOptions().CPlusPlus)
1883    Ty = Context.IntTy;   // 'x' and L'x' -> int in C.
1884  else if (Literal.isWide())
1885    Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
1886  else if (Literal.isMultiChar())
1887    Ty = Context.IntTy;   // 'wxyz' -> int in C++.
1888  else
1889    Ty = Context.CharTy;  // 'x' -> char in C++
1890
1891  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1892                                              Literal.isWide(),
1893                                              Ty, Tok.getLocation()));
1894}
1895
1896Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1897  // Fast path for a single digit (which is quite common).  A single digit
1898  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1899  if (Tok.getLength() == 1) {
1900    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1901    unsigned IntSize = Context.Target.getIntWidth();
1902    return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1903                    Context.IntTy, Tok.getLocation()));
1904  }
1905
1906  llvm::SmallString<512> IntegerBuffer;
1907  // Add padding so that NumericLiteralParser can overread by one character.
1908  IntegerBuffer.resize(Tok.getLength()+1);
1909  const char *ThisTokBegin = &IntegerBuffer[0];
1910
1911  // Get the spelling of the token, which eliminates trigraphs, etc.
1912  bool Invalid = false;
1913  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1914  if (Invalid)
1915    return ExprError();
1916
1917  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1918                               Tok.getLocation(), PP);
1919  if (Literal.hadError)
1920    return ExprError();
1921
1922  Expr *Res;
1923
1924  if (Literal.isFloatingLiteral()) {
1925    QualType Ty;
1926    if (Literal.isFloat)
1927      Ty = Context.FloatTy;
1928    else if (!Literal.isLong)
1929      Ty = Context.DoubleTy;
1930    else
1931      Ty = Context.LongDoubleTy;
1932
1933    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1934
1935    using llvm::APFloat;
1936    APFloat Val(Format);
1937
1938    APFloat::opStatus result = Literal.GetFloatValue(Val);
1939
1940    // Overflow is always an error, but underflow is only an error if
1941    // we underflowed to zero (APFloat reports denormals as underflow).
1942    if ((result & APFloat::opOverflow) ||
1943        ((result & APFloat::opUnderflow) && Val.isZero())) {
1944      unsigned diagnostic;
1945      llvm::SmallString<20> buffer;
1946      if (result & APFloat::opOverflow) {
1947        diagnostic = diag::warn_float_overflow;
1948        APFloat::getLargest(Format).toString(buffer);
1949      } else {
1950        diagnostic = diag::warn_float_underflow;
1951        APFloat::getSmallest(Format).toString(buffer);
1952      }
1953
1954      Diag(Tok.getLocation(), diagnostic)
1955        << Ty
1956        << llvm::StringRef(buffer.data(), buffer.size());
1957    }
1958
1959    bool isExact = (result == APFloat::opOK);
1960    Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
1961
1962  } else if (!Literal.isIntegerLiteral()) {
1963    return ExprError();
1964  } else {
1965    QualType Ty;
1966
1967    // long long is a C99 feature.
1968    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1969        Literal.isLongLong)
1970      Diag(Tok.getLocation(), diag::ext_longlong);
1971
1972    // Get the value in the widest-possible width.
1973    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1974
1975    if (Literal.GetIntegerValue(ResultVal)) {
1976      // If this value didn't fit into uintmax_t, warn and force to ull.
1977      Diag(Tok.getLocation(), diag::warn_integer_too_large);
1978      Ty = Context.UnsignedLongLongTy;
1979      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1980             "long long is not intmax_t?");
1981    } else {
1982      // If this value fits into a ULL, try to figure out what else it fits into
1983      // according to the rules of C99 6.4.4.1p5.
1984
1985      // Octal, Hexadecimal, and integers with a U suffix are allowed to
1986      // be an unsigned int.
1987      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1988
1989      // Check from smallest to largest, picking the smallest type we can.
1990      unsigned Width = 0;
1991      if (!Literal.isLong && !Literal.isLongLong) {
1992        // Are int/unsigned possibilities?
1993        unsigned IntSize = Context.Target.getIntWidth();
1994
1995        // Does it fit in a unsigned int?
1996        if (ResultVal.isIntN(IntSize)) {
1997          // Does it fit in a signed int?
1998          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1999            Ty = Context.IntTy;
2000          else if (AllowUnsigned)
2001            Ty = Context.UnsignedIntTy;
2002          Width = IntSize;
2003        }
2004      }
2005
2006      // Are long/unsigned long possibilities?
2007      if (Ty.isNull() && !Literal.isLongLong) {
2008        unsigned LongSize = Context.Target.getLongWidth();
2009
2010        // Does it fit in a unsigned long?
2011        if (ResultVal.isIntN(LongSize)) {
2012          // Does it fit in a signed long?
2013          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2014            Ty = Context.LongTy;
2015          else if (AllowUnsigned)
2016            Ty = Context.UnsignedLongTy;
2017          Width = LongSize;
2018        }
2019      }
2020
2021      // Finally, check long long if needed.
2022      if (Ty.isNull()) {
2023        unsigned LongLongSize = Context.Target.getLongLongWidth();
2024
2025        // Does it fit in a unsigned long long?
2026        if (ResultVal.isIntN(LongLongSize)) {
2027          // Does it fit in a signed long long?
2028          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
2029            Ty = Context.LongLongTy;
2030          else if (AllowUnsigned)
2031            Ty = Context.UnsignedLongLongTy;
2032          Width = LongLongSize;
2033        }
2034      }
2035
2036      // If we still couldn't decide a type, we probably have something that
2037      // does not fit in a signed long long, but has no U suffix.
2038      if (Ty.isNull()) {
2039        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2040        Ty = Context.UnsignedLongLongTy;
2041        Width = Context.Target.getLongLongWidth();
2042      }
2043
2044      if (ResultVal.getBitWidth() != Width)
2045        ResultVal.trunc(Width);
2046    }
2047    Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
2048  }
2049
2050  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2051  if (Literal.isImaginary)
2052    Res = new (Context) ImaginaryLiteral(Res,
2053                                        Context.getComplexType(Res->getType()));
2054
2055  return Owned(Res);
2056}
2057
2058Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
2059                                              SourceLocation R, ExprArg Val) {
2060  Expr *E = Val.takeAs<Expr>();
2061  assert((E != 0) && "ActOnParenExpr() missing expr");
2062  return Owned(new (Context) ParenExpr(L, R, E));
2063}
2064
2065/// The UsualUnaryConversions() function is *not* called by this routine.
2066/// See C99 6.3.2.1p[2-4] for more details.
2067bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
2068                                     SourceLocation OpLoc,
2069                                     const SourceRange &ExprRange,
2070                                     bool isSizeof) {
2071  if (exprType->isDependentType())
2072    return false;
2073
2074  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2075  //   the result is the size of the referenced type."
2076  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2077  //   result shall be the alignment of the referenced type."
2078  if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2079    exprType = Ref->getPointeeType();
2080
2081  // C99 6.5.3.4p1:
2082  if (exprType->isFunctionType()) {
2083    // alignof(function) is allowed as an extension.
2084    if (isSizeof)
2085      Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2086    return false;
2087  }
2088
2089  // Allow sizeof(void)/alignof(void) as an extension.
2090  if (exprType->isVoidType()) {
2091    Diag(OpLoc, diag::ext_sizeof_void_type)
2092      << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
2093    return false;
2094  }
2095
2096  if (RequireCompleteType(OpLoc, exprType,
2097                          PDiag(diag::err_sizeof_alignof_incomplete_type)
2098                          << int(!isSizeof) << ExprRange))
2099    return true;
2100
2101  // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2102  if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
2103    Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
2104      << exprType << isSizeof << ExprRange;
2105    return true;
2106  }
2107
2108  if (Context.hasSameUnqualifiedType(exprType, Context.OverloadTy)) {
2109    Diag(OpLoc, diag::err_sizeof_alignof_overloaded_function_type)
2110      << !isSizeof << ExprRange;
2111    return true;
2112  }
2113
2114  return false;
2115}
2116
2117bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2118                            const SourceRange &ExprRange) {
2119  E = E->IgnoreParens();
2120
2121  // alignof decl is always ok.
2122  if (isa<DeclRefExpr>(E))
2123    return false;
2124
2125  // Cannot know anything else if the expression is dependent.
2126  if (E->isTypeDependent())
2127    return false;
2128
2129  if (E->getBitField()) {
2130    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2131    return true;
2132  }
2133
2134  // Alignment of a field access is always okay, so long as it isn't a
2135  // bit-field.
2136  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2137    if (isa<FieldDecl>(ME->getMemberDecl()))
2138      return false;
2139
2140  return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2141}
2142
2143/// \brief Build a sizeof or alignof expression given a type operand.
2144Action::OwningExprResult
2145Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
2146                              SourceLocation OpLoc,
2147                              bool isSizeOf, SourceRange R) {
2148  if (!TInfo)
2149    return ExprError();
2150
2151  QualType T = TInfo->getType();
2152
2153  if (!T->isDependentType() &&
2154      CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2155    return ExprError();
2156
2157  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2158  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
2159                                               Context.getSizeType(), OpLoc,
2160                                               R.getEnd()));
2161}
2162
2163/// \brief Build a sizeof or alignof expression given an expression
2164/// operand.
2165Action::OwningExprResult
2166Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
2167                              bool isSizeOf, SourceRange R) {
2168  // Verify that the operand is valid.
2169  bool isInvalid = false;
2170  if (E->isTypeDependent()) {
2171    // Delay type-checking for type-dependent expressions.
2172  } else if (!isSizeOf) {
2173    isInvalid = CheckAlignOfExpr(E, OpLoc, R);
2174  } else if (E->getBitField()) {  // C99 6.5.3.4p1.
2175    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2176    isInvalid = true;
2177  } else {
2178    isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2179  }
2180
2181  if (isInvalid)
2182    return ExprError();
2183
2184  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2185  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2186                                               Context.getSizeType(), OpLoc,
2187                                               R.getEnd()));
2188}
2189
2190/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2191/// the same for @c alignof and @c __alignof
2192/// Note that the ArgRange is invalid if isType is false.
2193Action::OwningExprResult
2194Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2195                             void *TyOrEx, const SourceRange &ArgRange) {
2196  // If error parsing type, ignore.
2197  if (TyOrEx == 0) return ExprError();
2198
2199  if (isType) {
2200    TypeSourceInfo *TInfo;
2201    (void) GetTypeFromParser(TyOrEx, &TInfo);
2202    return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
2203  }
2204
2205  Expr *ArgEx = (Expr *)TyOrEx;
2206  Action::OwningExprResult Result
2207    = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2208
2209  if (Result.isInvalid())
2210    DeleteExpr(ArgEx);
2211
2212  return move(Result);
2213}
2214
2215QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
2216  if (V->isTypeDependent())
2217    return Context.DependentTy;
2218
2219  // These operators return the element type of a complex type.
2220  if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
2221    return CT->getElementType();
2222
2223  // Otherwise they pass through real integer and floating point types here.
2224  if (V->getType()->isArithmeticType())
2225    return V->getType();
2226
2227  // Reject anything else.
2228  Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2229    << (isReal ? "__real" : "__imag");
2230  return QualType();
2231}
2232
2233
2234
2235Action::OwningExprResult
2236Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2237                          tok::TokenKind Kind, ExprArg Input) {
2238  UnaryOperator::Opcode Opc;
2239  switch (Kind) {
2240  default: assert(0 && "Unknown unary op!");
2241  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
2242  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2243  }
2244
2245  return BuildUnaryOp(S, OpLoc, Opc, move(Input));
2246}
2247
2248Action::OwningExprResult
2249Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2250                              ExprArg Idx, SourceLocation RLoc) {
2251  // Since this might be a postfix expression, get rid of ParenListExprs.
2252  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2253
2254  Expr *LHSExp = static_cast<Expr*>(Base.get()),
2255       *RHSExp = static_cast<Expr*>(Idx.get());
2256
2257  if (getLangOptions().CPlusPlus &&
2258      (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2259    Base.release();
2260    Idx.release();
2261    return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2262                                                  Context.DependentTy, RLoc));
2263  }
2264
2265  if (getLangOptions().CPlusPlus &&
2266      (LHSExp->getType()->isRecordType() ||
2267       LHSExp->getType()->isEnumeralType() ||
2268       RHSExp->getType()->isRecordType() ||
2269       RHSExp->getType()->isEnumeralType())) {
2270    return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
2271  }
2272
2273  return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2274}
2275
2276
2277Action::OwningExprResult
2278Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2279                                     ExprArg Idx, SourceLocation RLoc) {
2280  Expr *LHSExp = static_cast<Expr*>(Base.get());
2281  Expr *RHSExp = static_cast<Expr*>(Idx.get());
2282
2283  // Perform default conversions.
2284  if (!LHSExp->getType()->getAs<VectorType>())
2285      DefaultFunctionArrayLvalueConversion(LHSExp);
2286  DefaultFunctionArrayLvalueConversion(RHSExp);
2287
2288  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
2289
2290  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
2291  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
2292  // in the subscript position. As a result, we need to derive the array base
2293  // and index from the expression types.
2294  Expr *BaseExpr, *IndexExpr;
2295  QualType ResultType;
2296  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2297    BaseExpr = LHSExp;
2298    IndexExpr = RHSExp;
2299    ResultType = Context.DependentTy;
2300  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
2301    BaseExpr = LHSExp;
2302    IndexExpr = RHSExp;
2303    ResultType = PTy->getPointeeType();
2304  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
2305     // Handle the uncommon case of "123[Ptr]".
2306    BaseExpr = RHSExp;
2307    IndexExpr = LHSExp;
2308    ResultType = PTy->getPointeeType();
2309  } else if (const ObjCObjectPointerType *PTy =
2310               LHSTy->getAs<ObjCObjectPointerType>()) {
2311    BaseExpr = LHSExp;
2312    IndexExpr = RHSExp;
2313    ResultType = PTy->getPointeeType();
2314  } else if (const ObjCObjectPointerType *PTy =
2315               RHSTy->getAs<ObjCObjectPointerType>()) {
2316     // Handle the uncommon case of "123[Ptr]".
2317    BaseExpr = RHSExp;
2318    IndexExpr = LHSExp;
2319    ResultType = PTy->getPointeeType();
2320  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
2321    BaseExpr = LHSExp;    // vectors: V[123]
2322    IndexExpr = RHSExp;
2323
2324    // FIXME: need to deal with const...
2325    ResultType = VTy->getElementType();
2326  } else if (LHSTy->isArrayType()) {
2327    // If we see an array that wasn't promoted by
2328    // DefaultFunctionArrayLvalueConversion, it must be an array that
2329    // wasn't promoted because of the C90 rule that doesn't
2330    // allow promoting non-lvalue arrays.  Warn, then
2331    // force the promotion here.
2332    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2333        LHSExp->getSourceRange();
2334    ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2335                      CastExpr::CK_ArrayToPointerDecay);
2336    LHSTy = LHSExp->getType();
2337
2338    BaseExpr = LHSExp;
2339    IndexExpr = RHSExp;
2340    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
2341  } else if (RHSTy->isArrayType()) {
2342    // Same as previous, except for 123[f().a] case
2343    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2344        RHSExp->getSourceRange();
2345    ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2346                      CastExpr::CK_ArrayToPointerDecay);
2347    RHSTy = RHSExp->getType();
2348
2349    BaseExpr = RHSExp;
2350    IndexExpr = LHSExp;
2351    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
2352  } else {
2353    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2354       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
2355  }
2356  // C99 6.5.2.1p1
2357  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
2358    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2359                     << IndexExpr->getSourceRange());
2360
2361  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
2362       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2363         && !IndexExpr->isTypeDependent())
2364    Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2365
2366  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
2367  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2368  // type. Note that Functions are not objects, and that (in C99 parlance)
2369  // incomplete types are not object types.
2370  if (ResultType->isFunctionType()) {
2371    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2372      << ResultType << BaseExpr->getSourceRange();
2373    return ExprError();
2374  }
2375
2376  if (!ResultType->isDependentType() &&
2377      RequireCompleteType(LLoc, ResultType,
2378                          PDiag(diag::err_subscript_incomplete_type)
2379                            << BaseExpr->getSourceRange()))
2380    return ExprError();
2381
2382  // Diagnose bad cases where we step over interface counts.
2383  if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
2384    Diag(LLoc, diag::err_subscript_nonfragile_interface)
2385      << ResultType << BaseExpr->getSourceRange();
2386    return ExprError();
2387  }
2388
2389  Base.release();
2390  Idx.release();
2391  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2392                                                ResultType, RLoc));
2393}
2394
2395QualType Sema::
2396CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
2397                        const IdentifierInfo *CompName,
2398                        SourceLocation CompLoc) {
2399  // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2400  // see FIXME there.
2401  //
2402  // FIXME: This logic can be greatly simplified by splitting it along
2403  // halving/not halving and reworking the component checking.
2404  const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
2405
2406  // The vector accessor can't exceed the number of elements.
2407  const char *compStr = CompName->getNameStart();
2408
2409  // This flag determines whether or not the component is one of the four
2410  // special names that indicate a subset of exactly half the elements are
2411  // to be selected.
2412  bool HalvingSwizzle = false;
2413
2414  // This flag determines whether or not CompName has an 's' char prefix,
2415  // indicating that it is a string of hex values to be used as vector indices.
2416  bool HexSwizzle = *compStr == 's' || *compStr == 'S';
2417
2418  // Check that we've found one of the special components, or that the component
2419  // names must come from the same set.
2420  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
2421      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2422    HalvingSwizzle = true;
2423  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
2424    do
2425      compStr++;
2426    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
2427  } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
2428    do
2429      compStr++;
2430    while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
2431  }
2432
2433  if (!HalvingSwizzle && *compStr) {
2434    // We didn't get to the end of the string. This means the component names
2435    // didn't come from the same set *or* we encountered an illegal name.
2436    Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2437      << std::string(compStr,compStr+1) << SourceRange(CompLoc);
2438    return QualType();
2439  }
2440
2441  // Ensure no component accessor exceeds the width of the vector type it
2442  // operates on.
2443  if (!HalvingSwizzle) {
2444    compStr = CompName->getNameStart();
2445
2446    if (HexSwizzle)
2447      compStr++;
2448
2449    while (*compStr) {
2450      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2451        Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2452          << baseType << SourceRange(CompLoc);
2453        return QualType();
2454      }
2455    }
2456  }
2457
2458  // The component accessor looks fine - now we need to compute the actual type.
2459  // The vector type is implied by the component accessor. For example,
2460  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
2461  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
2462  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
2463  unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
2464                                     : CompName->getLength();
2465  if (HexSwizzle)
2466    CompSize--;
2467
2468  if (CompSize == 1)
2469    return vecType->getElementType();
2470
2471  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
2472  // Now look up the TypeDefDecl from the vector type. Without this,
2473  // diagostics look bad. We want extended vector types to appear built-in.
2474  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2475    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2476      return Context.getTypedefType(ExtVectorDecls[i]);
2477  }
2478  return VT; // should never get here (a typedef type should always be found).
2479}
2480
2481static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
2482                                                IdentifierInfo *Member,
2483                                                const Selector &Sel,
2484                                                ASTContext &Context) {
2485
2486  if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
2487    return PD;
2488  if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
2489    return OMD;
2490
2491  for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2492       E = PDecl->protocol_end(); I != E; ++I) {
2493    if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
2494                                                     Context))
2495      return D;
2496  }
2497  return 0;
2498}
2499
2500static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
2501                                IdentifierInfo *Member,
2502                                const Selector &Sel,
2503                                ASTContext &Context) {
2504  // Check protocols on qualified interfaces.
2505  Decl *GDecl = 0;
2506  for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
2507       E = QIdTy->qual_end(); I != E; ++I) {
2508    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2509      GDecl = PD;
2510      break;
2511    }
2512    // Also must look for a getter name which uses property syntax.
2513    if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
2514      GDecl = OMD;
2515      break;
2516    }
2517  }
2518  if (!GDecl) {
2519    for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
2520         E = QIdTy->qual_end(); I != E; ++I) {
2521      // Search in the protocol-qualifier list of current protocol.
2522      GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
2523      if (GDecl)
2524        return GDecl;
2525    }
2526  }
2527  return GDecl;
2528}
2529
2530Sema::OwningExprResult
2531Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2532                               bool IsArrow, SourceLocation OpLoc,
2533                               const CXXScopeSpec &SS,
2534                               NamedDecl *FirstQualifierInScope,
2535                               DeclarationName Name, SourceLocation NameLoc,
2536                               const TemplateArgumentListInfo *TemplateArgs) {
2537  Expr *BaseExpr = Base.takeAs<Expr>();
2538
2539  // Even in dependent contexts, try to diagnose base expressions with
2540  // obviously wrong types, e.g.:
2541  //
2542  // T* t;
2543  // t.f;
2544  //
2545  // In Obj-C++, however, the above expression is valid, since it could be
2546  // accessing the 'f' property if T is an Obj-C interface. The extra check
2547  // allows this, while still reporting an error if T is a struct pointer.
2548  if (!IsArrow) {
2549    const PointerType *PT = BaseType->getAs<PointerType>();
2550    if (PT && (!getLangOptions().ObjC1 ||
2551               PT->getPointeeType()->isRecordType())) {
2552      assert(BaseExpr && "cannot happen with implicit member accesses");
2553      Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
2554        << BaseType << BaseExpr->getSourceRange();
2555      return ExprError();
2556    }
2557  }
2558
2559  assert(BaseType->isDependentType() || Name.isDependentName() ||
2560         isDependentScopeSpecifier(SS));
2561
2562  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
2563  // must have pointer type, and the accessed type is the pointee.
2564  return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
2565                                                   IsArrow, OpLoc,
2566                 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2567                                                   SS.getRange(),
2568                                                   FirstQualifierInScope,
2569                                                   Name, NameLoc,
2570                                                   TemplateArgs));
2571}
2572
2573/// We know that the given qualified member reference points only to
2574/// declarations which do not belong to the static type of the base
2575/// expression.  Diagnose the problem.
2576static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2577                                             Expr *BaseExpr,
2578                                             QualType BaseType,
2579                                             const CXXScopeSpec &SS,
2580                                             const LookupResult &R) {
2581  // If this is an implicit member access, use a different set of
2582  // diagnostics.
2583  if (!BaseExpr)
2584    return DiagnoseInstanceReference(SemaRef, SS, R);
2585
2586  SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
2587    << SS.getRange() << R.getRepresentativeDecl() << BaseType;
2588}
2589
2590// Check whether the declarations we found through a nested-name
2591// specifier in a member expression are actually members of the base
2592// type.  The restriction here is:
2593//
2594//   C++ [expr.ref]p2:
2595//     ... In these cases, the id-expression shall name a
2596//     member of the class or of one of its base classes.
2597//
2598// So it's perfectly legitimate for the nested-name specifier to name
2599// an unrelated class, and for us to find an overload set including
2600// decls from classes which are not superclasses, as long as the decl
2601// we actually pick through overload resolution is from a superclass.
2602bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2603                                         QualType BaseType,
2604                                         const CXXScopeSpec &SS,
2605                                         const LookupResult &R) {
2606  const RecordType *BaseRT = BaseType->getAs<RecordType>();
2607  if (!BaseRT) {
2608    // We can't check this yet because the base type is still
2609    // dependent.
2610    assert(BaseType->isDependentType());
2611    return false;
2612  }
2613  CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
2614
2615  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2616    // If this is an implicit member reference and we find a
2617    // non-instance member, it's not an error.
2618    if (!BaseExpr && !(*I)->isCXXInstanceMember())
2619      return false;
2620
2621    // Note that we use the DC of the decl, not the underlying decl.
2622    DeclContext *DC = (*I)->getDeclContext();
2623    while (DC->isTransparentContext())
2624      DC = DC->getParent();
2625
2626    if (!DC->isRecord())
2627      continue;
2628
2629    llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2630    MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
2631
2632    if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2633      return false;
2634  }
2635
2636  DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
2637  return true;
2638}
2639
2640static bool
2641LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2642                         SourceRange BaseRange, const RecordType *RTy,
2643                         SourceLocation OpLoc, CXXScopeSpec &SS,
2644                         bool HasTemplateArgs) {
2645  RecordDecl *RDecl = RTy->getDecl();
2646  if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2647                              SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
2648                                    << BaseRange))
2649    return true;
2650
2651  if (HasTemplateArgs) {
2652    // LookupTemplateName doesn't expect these both to exist simultaneously.
2653    QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
2654
2655    bool MOUS;
2656    SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
2657    return false;
2658  }
2659
2660  DeclContext *DC = RDecl;
2661  if (SS.isSet()) {
2662    // If the member name was a qualified-id, look into the
2663    // nested-name-specifier.
2664    DC = SemaRef.computeDeclContext(SS, false);
2665
2666    if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
2667      SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2668        << SS.getRange() << DC;
2669      return true;
2670    }
2671
2672    assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2673
2674    if (!isa<TypeDecl>(DC)) {
2675      SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2676        << DC << SS.getRange();
2677      return true;
2678    }
2679  }
2680
2681  // The record definition is complete, now look up the member.
2682  SemaRef.LookupQualifiedName(R, DC);
2683
2684  if (!R.empty())
2685    return false;
2686
2687  // We didn't find anything with the given name, so try to correct
2688  // for typos.
2689  DeclarationName Name = R.getLookupName();
2690  if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
2691      !R.empty() &&
2692      (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2693    SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2694      << Name << DC << R.getLookupName() << SS.getRange()
2695      << FixItHint::CreateReplacement(R.getNameLoc(),
2696                                      R.getLookupName().getAsString());
2697    if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2698      SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2699        << ND->getDeclName();
2700    return false;
2701  } else {
2702    R.clear();
2703    R.setLookupName(Name);
2704  }
2705
2706  return false;
2707}
2708
2709Sema::OwningExprResult
2710Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
2711                               SourceLocation OpLoc, bool IsArrow,
2712                               CXXScopeSpec &SS,
2713                               NamedDecl *FirstQualifierInScope,
2714                               DeclarationName Name, SourceLocation NameLoc,
2715                               const TemplateArgumentListInfo *TemplateArgs) {
2716  Expr *Base = BaseArg.takeAs<Expr>();
2717
2718  if (BaseType->isDependentType() ||
2719      (SS.isSet() && isDependentScopeSpecifier(SS)))
2720    return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
2721                                    IsArrow, OpLoc,
2722                                    SS, FirstQualifierInScope,
2723                                    Name, NameLoc,
2724                                    TemplateArgs);
2725
2726  LookupResult R(*this, Name, NameLoc, LookupMemberName);
2727
2728  // Implicit member accesses.
2729  if (!Base) {
2730    QualType RecordTy = BaseType;
2731    if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2732    if (LookupMemberExprInRecord(*this, R, SourceRange(),
2733                                 RecordTy->getAs<RecordType>(),
2734                                 OpLoc, SS, TemplateArgs != 0))
2735      return ExprError();
2736
2737  // Explicit member accesses.
2738  } else {
2739    OwningExprResult Result =
2740      LookupMemberExpr(R, Base, IsArrow, OpLoc,
2741                       SS, /*ObjCImpDecl*/ DeclPtrTy(), TemplateArgs != 0);
2742
2743    if (Result.isInvalid()) {
2744      Owned(Base);
2745      return ExprError();
2746    }
2747
2748    if (Result.get())
2749      return move(Result);
2750
2751    // LookupMemberExpr can modify Base, and thus change BaseType
2752    BaseType = Base->getType();
2753  }
2754
2755  return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2756                                  OpLoc, IsArrow, SS, FirstQualifierInScope,
2757                                  R, TemplateArgs);
2758}
2759
2760Sema::OwningExprResult
2761Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2762                               SourceLocation OpLoc, bool IsArrow,
2763                               const CXXScopeSpec &SS,
2764                               NamedDecl *FirstQualifierInScope,
2765                               LookupResult &R,
2766                         const TemplateArgumentListInfo *TemplateArgs,
2767                               bool SuppressQualifierCheck) {
2768  Expr *BaseExpr = Base.takeAs<Expr>();
2769  QualType BaseType = BaseExprType;
2770  if (IsArrow) {
2771    assert(BaseType->isPointerType());
2772    BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2773  }
2774  R.setBaseObjectType(BaseType);
2775
2776  NestedNameSpecifier *Qualifier =
2777    static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2778  DeclarationName MemberName = R.getLookupName();
2779  SourceLocation MemberLoc = R.getNameLoc();
2780
2781  if (R.isAmbiguous())
2782    return ExprError();
2783
2784  if (R.empty()) {
2785    // Rederive where we looked up.
2786    DeclContext *DC = (SS.isSet()
2787                       ? computeDeclContext(SS, false)
2788                       : BaseType->getAs<RecordType>()->getDecl());
2789
2790    Diag(R.getNameLoc(), diag::err_no_member)
2791      << MemberName << DC
2792      << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
2793    return ExprError();
2794  }
2795
2796  // Diagnose lookups that find only declarations from a non-base
2797  // type.  This is possible for either qualified lookups (which may
2798  // have been qualified with an unrelated type) or implicit member
2799  // expressions (which were found with unqualified lookup and thus
2800  // may have come from an enclosing scope).  Note that it's okay for
2801  // lookup to find declarations from a non-base type as long as those
2802  // aren't the ones picked by overload resolution.
2803  if ((SS.isSet() || !BaseExpr ||
2804       (isa<CXXThisExpr>(BaseExpr) &&
2805        cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
2806      !SuppressQualifierCheck &&
2807      CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
2808    return ExprError();
2809
2810  // Construct an unresolved result if we in fact got an unresolved
2811  // result.
2812  if (R.isOverloadedResult() || R.isUnresolvableResult()) {
2813    bool Dependent =
2814      BaseExprType->isDependentType() ||
2815      R.isUnresolvableResult() ||
2816      OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
2817
2818    // Suppress any lookup-related diagnostics; we'll do these when we
2819    // pick a member.
2820    R.suppressDiagnostics();
2821
2822    UnresolvedMemberExpr *MemExpr
2823      = UnresolvedMemberExpr::Create(Context, Dependent,
2824                                     R.isUnresolvableResult(),
2825                                     BaseExpr, BaseExprType,
2826                                     IsArrow, OpLoc,
2827                                     Qualifier, SS.getRange(),
2828                                     MemberName, MemberLoc,
2829                                     TemplateArgs, R.begin(), R.end());
2830
2831    return Owned(MemExpr);
2832  }
2833
2834  assert(R.isSingleResult());
2835  DeclAccessPair FoundDecl = R.begin().getPair();
2836  NamedDecl *MemberDecl = R.getFoundDecl();
2837
2838  // FIXME: diagnose the presence of template arguments now.
2839
2840  // If the decl being referenced had an error, return an error for this
2841  // sub-expr without emitting another error, in order to avoid cascading
2842  // error cases.
2843  if (MemberDecl->isInvalidDecl())
2844    return ExprError();
2845
2846  // Handle the implicit-member-access case.
2847  if (!BaseExpr) {
2848    // If this is not an instance member, convert to a non-member access.
2849    if (!MemberDecl->isCXXInstanceMember())
2850      return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2851
2852    SourceLocation Loc = R.getNameLoc();
2853    if (SS.getRange().isValid())
2854      Loc = SS.getRange().getBegin();
2855    BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
2856  }
2857
2858  bool ShouldCheckUse = true;
2859  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2860    // Don't diagnose the use of a virtual member function unless it's
2861    // explicitly qualified.
2862    if (MD->isVirtual() && !SS.isSet())
2863      ShouldCheckUse = false;
2864  }
2865
2866  // Check the use of this member.
2867  if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2868    Owned(BaseExpr);
2869    return ExprError();
2870  }
2871
2872  if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2873    // We may have found a field within an anonymous union or struct
2874    // (C++ [class.union]).
2875    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2876        !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
2877      return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2878                                                      BaseExpr, OpLoc);
2879
2880    // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2881    QualType MemberType = FD->getType();
2882    if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2883      MemberType = Ref->getPointeeType();
2884    else {
2885      Qualifiers BaseQuals = BaseType.getQualifiers();
2886      BaseQuals.removeObjCGCAttr();
2887      if (FD->isMutable()) BaseQuals.removeConst();
2888
2889      Qualifiers MemberQuals
2890        = Context.getCanonicalType(MemberType).getQualifiers();
2891
2892      Qualifiers Combined = BaseQuals + MemberQuals;
2893      if (Combined != MemberQuals)
2894        MemberType = Context.getQualifiedType(MemberType, Combined);
2895    }
2896
2897    MarkDeclarationReferenced(MemberLoc, FD);
2898    if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
2899      return ExprError();
2900    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2901                                 FD, FoundDecl, MemberLoc, MemberType));
2902  }
2903
2904  if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2905    MarkDeclarationReferenced(MemberLoc, Var);
2906    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2907                                 Var, FoundDecl, MemberLoc,
2908                                 Var->getType().getNonReferenceType()));
2909  }
2910
2911  if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2912    MarkDeclarationReferenced(MemberLoc, MemberDecl);
2913    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2914                                 MemberFn, FoundDecl, MemberLoc,
2915                                 MemberFn->getType()));
2916  }
2917
2918  if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2919    MarkDeclarationReferenced(MemberLoc, MemberDecl);
2920    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2921                                 Enum, FoundDecl, MemberLoc, Enum->getType()));
2922  }
2923
2924  Owned(BaseExpr);
2925
2926  // We found something that we didn't expect. Complain.
2927  if (isa<TypeDecl>(MemberDecl))
2928    Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2929      << MemberName << BaseType << int(IsArrow);
2930  else
2931    Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
2932      << MemberName << BaseType << int(IsArrow);
2933
2934  Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
2935    << MemberName;
2936  R.suppressDiagnostics();
2937  return ExprError();
2938}
2939
2940/// Look up the given member of the given non-type-dependent
2941/// expression.  This can return in one of two ways:
2942///  * If it returns a sentinel null-but-valid result, the caller will
2943///    assume that lookup was performed and the results written into
2944///    the provided structure.  It will take over from there.
2945///  * Otherwise, the returned expression will be produced in place of
2946///    an ordinary member expression.
2947///
2948/// The ObjCImpDecl bit is a gross hack that will need to be properly
2949/// fixed for ObjC++.
2950Sema::OwningExprResult
2951Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
2952                       bool &IsArrow, SourceLocation OpLoc,
2953                       CXXScopeSpec &SS,
2954                       DeclPtrTy ObjCImpDecl, bool HasTemplateArgs) {
2955  assert(BaseExpr && "no base expression");
2956
2957  // Perform default conversions.
2958  DefaultFunctionArrayConversion(BaseExpr);
2959
2960  QualType BaseType = BaseExpr->getType();
2961  assert(!BaseType->isDependentType());
2962
2963  DeclarationName MemberName = R.getLookupName();
2964  SourceLocation MemberLoc = R.getNameLoc();
2965
2966  // If the user is trying to apply -> or . to a function pointer
2967  // type, it's probably because they forgot parentheses to call that
2968  // function. Suggest the addition of those parentheses, build the
2969  // call, and continue on.
2970  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2971    if (const FunctionProtoType *Fun
2972          = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2973      QualType ResultTy = Fun->getResultType();
2974      if (Fun->getNumArgs() == 0 &&
2975          ((!IsArrow && ResultTy->isRecordType()) ||
2976           (IsArrow && ResultTy->isPointerType() &&
2977            ResultTy->getAs<PointerType>()->getPointeeType()
2978                                                          ->isRecordType()))) {
2979        SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2980        Diag(Loc, diag::err_member_reference_needs_call)
2981          << QualType(Fun, 0)
2982          << FixItHint::CreateInsertion(Loc, "()");
2983
2984        OwningExprResult NewBase
2985          = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
2986                          MultiExprArg(*this, 0, 0), 0, Loc);
2987        BaseExpr = 0;
2988        if (NewBase.isInvalid())
2989          return ExprError();
2990
2991        BaseExpr = NewBase.takeAs<Expr>();
2992        DefaultFunctionArrayConversion(BaseExpr);
2993        BaseType = BaseExpr->getType();
2994      }
2995    }
2996  }
2997
2998  // If this is an Objective-C pseudo-builtin and a definition is provided then
2999  // use that.
3000  if (BaseType->isObjCIdType()) {
3001    if (IsArrow) {
3002      // Handle the following exceptional case PObj->isa.
3003      if (const ObjCObjectPointerType *OPT =
3004          BaseType->getAs<ObjCObjectPointerType>()) {
3005        if (OPT->getObjectType()->isObjCId() &&
3006            MemberName.getAsIdentifierInfo()->isStr("isa"))
3007          return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
3008                                                 Context.getObjCClassType()));
3009      }
3010    }
3011    // We have an 'id' type. Rather than fall through, we check if this
3012    // is a reference to 'isa'.
3013    if (BaseType != Context.ObjCIdRedefinitionType) {
3014      BaseType = Context.ObjCIdRedefinitionType;
3015      ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
3016    }
3017  }
3018
3019  // If this is an Objective-C pseudo-builtin and a definition is provided then
3020  // use that.
3021  if (Context.isObjCSelType(BaseType)) {
3022    // We have an 'SEL' type. Rather than fall through, we check if this
3023    // is a reference to 'sel_id'.
3024    if (BaseType != Context.ObjCSelRedefinitionType) {
3025      BaseType = Context.ObjCSelRedefinitionType;
3026      ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
3027    }
3028  }
3029
3030  assert(!BaseType.isNull() && "no type for member expression");
3031
3032  // Handle properties on ObjC 'Class' types.
3033  if (!IsArrow && BaseType->isObjCClassType()) {
3034    // Also must look for a getter name which uses property syntax.
3035    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3036    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3037    if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3038      ObjCInterfaceDecl *IFace = MD->getClassInterface();
3039      ObjCMethodDecl *Getter;
3040      // FIXME: need to also look locally in the implementation.
3041      if ((Getter = IFace->lookupClassMethod(Sel))) {
3042        // Check the use of this method.
3043        if (DiagnoseUseOfDecl(Getter, MemberLoc))
3044          return ExprError();
3045      }
3046      // If we found a getter then this may be a valid dot-reference, we
3047      // will look for the matching setter, in case it is needed.
3048      Selector SetterSel =
3049      SelectorTable::constructSetterName(PP.getIdentifierTable(),
3050                                         PP.getSelectorTable(), Member);
3051      ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3052      if (!Setter) {
3053        // If this reference is in an @implementation, also check for 'private'
3054        // methods.
3055        Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
3056      }
3057      // Look through local category implementations associated with the class.
3058      if (!Setter)
3059        Setter = IFace->getCategoryClassMethod(SetterSel);
3060
3061      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3062        return ExprError();
3063
3064      if (Getter || Setter) {
3065        QualType PType;
3066
3067        if (Getter)
3068          PType = Getter->getSendResultType();
3069        else
3070          // Get the expression type from Setter's incoming parameter.
3071          PType = (*(Setter->param_end() -1))->getType();
3072        // FIXME: we must check that the setter has property type.
3073        return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
3074                                                  PType,
3075                                                  Setter, MemberLoc, BaseExpr));
3076      }
3077      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3078                       << MemberName << BaseType);
3079    }
3080  }
3081
3082  if (BaseType->isObjCClassType() &&
3083      BaseType != Context.ObjCClassRedefinitionType) {
3084    BaseType = Context.ObjCClassRedefinitionType;
3085    ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
3086  }
3087
3088  if (IsArrow) {
3089    if (const PointerType *PT = BaseType->getAs<PointerType>())
3090      BaseType = PT->getPointeeType();
3091    else if (BaseType->isObjCObjectPointerType())
3092      ;
3093    else if (BaseType->isRecordType()) {
3094      // Recover from arrow accesses to records, e.g.:
3095      //   struct MyRecord foo;
3096      //   foo->bar
3097      // This is actually well-formed in C++ if MyRecord has an
3098      // overloaded operator->, but that should have been dealt with
3099      // by now.
3100      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3101        << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3102        << FixItHint::CreateReplacement(OpLoc, ".");
3103      IsArrow = false;
3104    } else {
3105      Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3106        << BaseType << BaseExpr->getSourceRange();
3107      return ExprError();
3108    }
3109  } else {
3110    // Recover from dot accesses to pointers, e.g.:
3111    //   type *foo;
3112    //   foo.bar
3113    // This is actually well-formed in two cases:
3114    //   - 'type' is an Objective C type
3115    //   - 'bar' is a pseudo-destructor name which happens to refer to
3116    //     the appropriate pointer type
3117    if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3118      const PointerType *PT = BaseType->getAs<PointerType>();
3119      if (PT && PT->getPointeeType()->isRecordType()) {
3120        Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3121          << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3122          << FixItHint::CreateReplacement(OpLoc, "->");
3123        BaseType = PT->getPointeeType();
3124        IsArrow = true;
3125      }
3126    }
3127  }
3128
3129  // Handle field access to simple records.
3130  if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3131    if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3132                                 RTy, OpLoc, SS, HasTemplateArgs))
3133      return ExprError();
3134    return Owned((Expr*) 0);
3135  }
3136
3137  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3138  // (*Obj).ivar.
3139  if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3140      (!IsArrow && BaseType->isObjCObjectType())) {
3141    const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
3142    ObjCInterfaceDecl *IDecl =
3143      OPT ? OPT->getInterfaceDecl()
3144          : BaseType->getAs<ObjCObjectType>()->getInterface();
3145    if (IDecl) {
3146      IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3147
3148      ObjCInterfaceDecl *ClassDeclared;
3149      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3150
3151      if (!IV) {
3152        // Attempt to correct for typos in ivar names.
3153        LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3154                         LookupMemberName);
3155        if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
3156            (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3157          Diag(R.getNameLoc(),
3158               diag::err_typecheck_member_reference_ivar_suggest)
3159            << IDecl->getDeclName() << MemberName << IV->getDeclName()
3160            << FixItHint::CreateReplacement(R.getNameLoc(),
3161                                            IV->getNameAsString());
3162          Diag(IV->getLocation(), diag::note_previous_decl)
3163            << IV->getDeclName();
3164        } else {
3165          Res.clear();
3166          Res.setLookupName(Member);
3167        }
3168      }
3169
3170      if (IV) {
3171        // If the decl being referenced had an error, return an error for this
3172        // sub-expr without emitting another error, in order to avoid cascading
3173        // error cases.
3174        if (IV->isInvalidDecl())
3175          return ExprError();
3176
3177        // Check whether we can reference this field.
3178        if (DiagnoseUseOfDecl(IV, MemberLoc))
3179          return ExprError();
3180        if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3181            IV->getAccessControl() != ObjCIvarDecl::Package) {
3182          ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3183          if (ObjCMethodDecl *MD = getCurMethodDecl())
3184            ClassOfMethodDecl =  MD->getClassInterface();
3185          else if (ObjCImpDecl && getCurFunctionDecl()) {
3186            // Case of a c-function declared inside an objc implementation.
3187            // FIXME: For a c-style function nested inside an objc implementation
3188            // class, there is no implementation context available, so we pass
3189            // down the context as argument to this routine. Ideally, this context
3190            // need be passed down in the AST node and somehow calculated from the
3191            // AST for a function decl.
3192            Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
3193            if (ObjCImplementationDecl *IMPD =
3194                dyn_cast<ObjCImplementationDecl>(ImplDecl))
3195              ClassOfMethodDecl = IMPD->getClassInterface();
3196            else if (ObjCCategoryImplDecl* CatImplClass =
3197                        dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
3198              ClassOfMethodDecl = CatImplClass->getClassInterface();
3199          }
3200
3201          if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3202            if (ClassDeclared != IDecl ||
3203                ClassOfMethodDecl != ClassDeclared)
3204              Diag(MemberLoc, diag::error_private_ivar_access)
3205                << IV->getDeclName();
3206          } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3207            // @protected
3208            Diag(MemberLoc, diag::error_protected_ivar_access)
3209              << IV->getDeclName();
3210        }
3211
3212        return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3213                                                   MemberLoc, BaseExpr,
3214                                                   IsArrow));
3215      }
3216      return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3217                         << IDecl->getDeclName() << MemberName
3218                         << BaseExpr->getSourceRange());
3219    }
3220  }
3221  // Handle properties on 'id' and qualified "id".
3222  if (!IsArrow && (BaseType->isObjCIdType() ||
3223                   BaseType->isObjCQualifiedIdType())) {
3224    const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
3225    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3226
3227    // Check protocols on qualified interfaces.
3228    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3229    if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3230      if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3231        // Check the use of this declaration
3232        if (DiagnoseUseOfDecl(PD, MemberLoc))
3233          return ExprError();
3234
3235        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3236                                                       MemberLoc, BaseExpr));
3237      }
3238      if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3239        // Check the use of this method.
3240        if (DiagnoseUseOfDecl(OMD, MemberLoc))
3241          return ExprError();
3242
3243        return Owned(ObjCMessageExpr::Create(Context,
3244                                             OMD->getSendResultType(),
3245                                             OpLoc, BaseExpr, Sel,
3246                                             OMD, NULL, 0, MemberLoc));
3247      }
3248    }
3249
3250    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3251                       << MemberName << BaseType);
3252  }
3253
3254  // Handle Objective-C property access, which is "Obj.property" where Obj is a
3255  // pointer to a (potentially qualified) interface type.
3256  if (!IsArrow)
3257    if (const ObjCObjectPointerType *OPT =
3258          BaseType->getAsObjCInterfacePointerType())
3259      return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
3260
3261  // Handle the following exceptional case (*Obj).isa.
3262  if (!IsArrow &&
3263      BaseType->isObjCObjectType() &&
3264      BaseType->getAs<ObjCObjectType>()->isObjCId() &&
3265      MemberName.getAsIdentifierInfo()->isStr("isa"))
3266    return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
3267                                           Context.getObjCClassType()));
3268
3269  // Handle 'field access' to vectors, such as 'V.xx'.
3270  if (BaseType->isExtVectorType()) {
3271    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3272    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3273    if (ret.isNull())
3274      return ExprError();
3275    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
3276                                                    MemberLoc));
3277  }
3278
3279  Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3280    << BaseType << BaseExpr->getSourceRange();
3281
3282  return ExprError();
3283}
3284
3285/// The main callback when the parser finds something like
3286///   expression . [nested-name-specifier] identifier
3287///   expression -> [nested-name-specifier] identifier
3288/// where 'identifier' encompasses a fairly broad spectrum of
3289/// possibilities, including destructor and operator references.
3290///
3291/// \param OpKind either tok::arrow or tok::period
3292/// \param HasTrailingLParen whether the next token is '(', which
3293///   is used to diagnose mis-uses of special members that can
3294///   only be called
3295/// \param ObjCImpDecl the current ObjC @implementation decl;
3296///   this is an ugly hack around the fact that ObjC @implementations
3297///   aren't properly put in the context chain
3298Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3299                                                   SourceLocation OpLoc,
3300                                                   tok::TokenKind OpKind,
3301                                                   CXXScopeSpec &SS,
3302                                                   UnqualifiedId &Id,
3303                                                   DeclPtrTy ObjCImpDecl,
3304                                                   bool HasTrailingLParen) {
3305  if (SS.isSet() && SS.isInvalid())
3306    return ExprError();
3307
3308  TemplateArgumentListInfo TemplateArgsBuffer;
3309
3310  // Decompose the name into its component parts.
3311  DeclarationName Name;
3312  SourceLocation NameLoc;
3313  const TemplateArgumentListInfo *TemplateArgs;
3314  DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3315                         Name, NameLoc, TemplateArgs);
3316
3317  bool IsArrow = (OpKind == tok::arrow);
3318
3319  NamedDecl *FirstQualifierInScope
3320    = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3321                       static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3322
3323  // This is a postfix expression, so get rid of ParenListExprs.
3324  BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3325
3326  Expr *Base = BaseArg.takeAs<Expr>();
3327  OwningExprResult Result(*this);
3328  if (Base->getType()->isDependentType() || Name.isDependentName() ||
3329      isDependentScopeSpecifier(SS)) {
3330    Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
3331                                      IsArrow, OpLoc,
3332                                      SS, FirstQualifierInScope,
3333                                      Name, NameLoc,
3334                                      TemplateArgs);
3335  } else {
3336    LookupResult R(*this, Name, NameLoc, LookupMemberName);
3337    Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3338                              SS, ObjCImpDecl, TemplateArgs != 0);
3339
3340    if (Result.isInvalid()) {
3341      Owned(Base);
3342      return ExprError();
3343    }
3344
3345    if (Result.get()) {
3346      // The only way a reference to a destructor can be used is to
3347      // immediately call it, which falls into this case.  If the
3348      // next token is not a '(', produce a diagnostic and build the
3349      // call now.
3350      if (!HasTrailingLParen &&
3351          Id.getKind() == UnqualifiedId::IK_DestructorName)
3352        return DiagnoseDtorReference(NameLoc, move(Result));
3353
3354      return move(Result);
3355    }
3356
3357    Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3358                                      OpLoc, IsArrow, SS, FirstQualifierInScope,
3359                                      R, TemplateArgs);
3360  }
3361
3362  return move(Result);
3363}
3364
3365Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3366                                                    FunctionDecl *FD,
3367                                                    ParmVarDecl *Param) {
3368  if (Param->hasUnparsedDefaultArg()) {
3369    Diag (CallLoc,
3370          diag::err_use_of_default_argument_to_function_declared_later) <<
3371      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3372    Diag(UnparsedDefaultArgLocs[Param],
3373          diag::note_default_argument_declared_here);
3374  } else {
3375    if (Param->hasUninstantiatedDefaultArg()) {
3376      Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3377
3378      // Instantiate the expression.
3379      MultiLevelTemplateArgumentList ArgList
3380        = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3381
3382      std::pair<const TemplateArgument *, unsigned> Innermost
3383        = ArgList.getInnermost();
3384      InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3385                                 Innermost.second);
3386
3387      OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
3388      if (Result.isInvalid())
3389        return ExprError();
3390
3391      // Check the expression as an initializer for the parameter.
3392      InitializedEntity Entity
3393        = InitializedEntity::InitializeParameter(Param);
3394      InitializationKind Kind
3395        = InitializationKind::CreateCopy(Param->getLocation(),
3396               /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3397      Expr *ResultE = Result.takeAs<Expr>();
3398
3399      InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3400      Result = InitSeq.Perform(*this, Entity, Kind,
3401                               MultiExprArg(*this, (void**)&ResultE, 1));
3402      if (Result.isInvalid())
3403        return ExprError();
3404
3405      // Build the default argument expression.
3406      return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3407                                             Result.takeAs<Expr>()));
3408    }
3409
3410    // If the default expression creates temporaries, we need to
3411    // push them to the current stack of expression temporaries so they'll
3412    // be properly destroyed.
3413    // FIXME: We should really be rebuilding the default argument with new
3414    // bound temporaries; see the comment in PR5810.
3415    for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3416      ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
3417  }
3418
3419  // We already type-checked the argument, so we know it works.
3420  return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3421}
3422
3423/// ConvertArgumentsForCall - Converts the arguments specified in
3424/// Args/NumArgs to the parameter types of the function FDecl with
3425/// function prototype Proto. Call is the call expression itself, and
3426/// Fn is the function expression. For a C++ member function, this
3427/// routine does not attempt to convert the object argument. Returns
3428/// true if the call is ill-formed.
3429bool
3430Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3431                              FunctionDecl *FDecl,
3432                              const FunctionProtoType *Proto,
3433                              Expr **Args, unsigned NumArgs,
3434                              SourceLocation RParenLoc) {
3435  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3436  // assignment, to the types of the corresponding parameter, ...
3437  unsigned NumArgsInProto = Proto->getNumArgs();
3438  bool Invalid = false;
3439
3440  // If too few arguments are available (and we don't have default
3441  // arguments for the remaining parameters), don't make the call.
3442  if (NumArgs < NumArgsInProto) {
3443    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3444      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3445        << Fn->getType()->isBlockPointerType()
3446        << NumArgsInProto << NumArgs << Fn->getSourceRange();
3447    Call->setNumArgs(Context, NumArgsInProto);
3448  }
3449
3450  // If too many are passed and not variadic, error on the extras and drop
3451  // them.
3452  if (NumArgs > NumArgsInProto) {
3453    if (!Proto->isVariadic()) {
3454      Diag(Args[NumArgsInProto]->getLocStart(),
3455           diag::err_typecheck_call_too_many_args)
3456        << Fn->getType()->isBlockPointerType()
3457        << NumArgsInProto << NumArgs << Fn->getSourceRange()
3458        << SourceRange(Args[NumArgsInProto]->getLocStart(),
3459                       Args[NumArgs-1]->getLocEnd());
3460      // This deletes the extra arguments.
3461      Call->setNumArgs(Context, NumArgsInProto);
3462      return true;
3463    }
3464  }
3465  llvm::SmallVector<Expr *, 8> AllArgs;
3466  VariadicCallType CallType =
3467    Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3468  if (Fn->getType()->isBlockPointerType())
3469    CallType = VariadicBlock; // Block
3470  else if (isa<MemberExpr>(Fn))
3471    CallType = VariadicMethod;
3472  Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
3473                                   Proto, 0, Args, NumArgs, AllArgs, CallType);
3474  if (Invalid)
3475    return true;
3476  unsigned TotalNumArgs = AllArgs.size();
3477  for (unsigned i = 0; i < TotalNumArgs; ++i)
3478    Call->setArg(i, AllArgs[i]);
3479
3480  return false;
3481}
3482
3483bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3484                                  FunctionDecl *FDecl,
3485                                  const FunctionProtoType *Proto,
3486                                  unsigned FirstProtoArg,
3487                                  Expr **Args, unsigned NumArgs,
3488                                  llvm::SmallVector<Expr *, 8> &AllArgs,
3489                                  VariadicCallType CallType) {
3490  unsigned NumArgsInProto = Proto->getNumArgs();
3491  unsigned NumArgsToCheck = NumArgs;
3492  bool Invalid = false;
3493  if (NumArgs != NumArgsInProto)
3494    // Use default arguments for missing arguments
3495    NumArgsToCheck = NumArgsInProto;
3496  unsigned ArgIx = 0;
3497  // Continue to check argument types (even if we have too few/many args).
3498  for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3499    QualType ProtoArgType = Proto->getArgType(i);
3500
3501    Expr *Arg;
3502    if (ArgIx < NumArgs) {
3503      Arg = Args[ArgIx++];
3504
3505      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3506                              ProtoArgType,
3507                              PDiag(diag::err_call_incomplete_argument)
3508                              << Arg->getSourceRange()))
3509        return true;
3510
3511      // Pass the argument
3512      ParmVarDecl *Param = 0;
3513      if (FDecl && i < FDecl->getNumParams())
3514        Param = FDecl->getParamDecl(i);
3515
3516
3517      InitializedEntity Entity =
3518        Param? InitializedEntity::InitializeParameter(Param)
3519             : InitializedEntity::InitializeParameter(ProtoArgType);
3520      OwningExprResult ArgE = PerformCopyInitialization(Entity,
3521                                                        SourceLocation(),
3522                                                        Owned(Arg));
3523      if (ArgE.isInvalid())
3524        return true;
3525
3526      Arg = ArgE.takeAs<Expr>();
3527    } else {
3528      ParmVarDecl *Param = FDecl->getParamDecl(i);
3529
3530      OwningExprResult ArgExpr =
3531        BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3532      if (ArgExpr.isInvalid())
3533        return true;
3534
3535      Arg = ArgExpr.takeAs<Expr>();
3536    }
3537    AllArgs.push_back(Arg);
3538  }
3539
3540  // If this is a variadic call, handle args passed through "...".
3541  if (CallType != VariadicDoesNotApply) {
3542    // Promote the arguments (C99 6.5.2.2p7).
3543    for (unsigned i = ArgIx; i != NumArgs; ++i) {
3544      Expr *Arg = Args[i];
3545      Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
3546      AllArgs.push_back(Arg);
3547    }
3548  }
3549  return Invalid;
3550}
3551
3552/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3553/// This provides the location of the left/right parens and a list of comma
3554/// locations.
3555Action::OwningExprResult
3556Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3557                    MultiExprArg args,
3558                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
3559  unsigned NumArgs = args.size();
3560
3561  // Since this might be a postfix expression, get rid of ParenListExprs.
3562  fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
3563
3564  Expr *Fn = fn.takeAs<Expr>();
3565  Expr **Args = reinterpret_cast<Expr**>(args.release());
3566  assert(Fn && "no function call expression");
3567
3568  if (getLangOptions().CPlusPlus) {
3569    // If this is a pseudo-destructor expression, build the call immediately.
3570    if (isa<CXXPseudoDestructorExpr>(Fn)) {
3571      if (NumArgs > 0) {
3572        // Pseudo-destructor calls should not have any arguments.
3573        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3574          << FixItHint::CreateRemoval(
3575                                    SourceRange(Args[0]->getLocStart(),
3576                                                Args[NumArgs-1]->getLocEnd()));
3577
3578        NumArgs = 0;
3579      }
3580
3581      return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3582                                          RParenLoc));
3583    }
3584
3585    // Determine whether this is a dependent call inside a C++ template,
3586    // in which case we won't do any semantic analysis now.
3587    // FIXME: Will need to cache the results of name lookup (including ADL) in
3588    // Fn.
3589    bool Dependent = false;
3590    if (Fn->isTypeDependent())
3591      Dependent = true;
3592    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3593      Dependent = true;
3594
3595    if (Dependent)
3596      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3597                                          Context.DependentTy, RParenLoc));
3598
3599    // Determine whether this is a call to an object (C++ [over.call.object]).
3600    if (Fn->getType()->isRecordType())
3601      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3602                                                CommaLocs, RParenLoc));
3603
3604    Expr *NakedFn = Fn->IgnoreParens();
3605
3606    // Determine whether this is a call to an unresolved member function.
3607    if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3608      // If lookup was unresolved but not dependent (i.e. didn't find
3609      // an unresolved using declaration), it has to be an overloaded
3610      // function set, which means it must contain either multiple
3611      // declarations (all methods or method templates) or a single
3612      // method template.
3613      assert((MemE->getNumDecls() > 1) ||
3614             isa<FunctionTemplateDecl>(
3615                                 (*MemE->decls_begin())->getUnderlyingDecl()));
3616      (void)MemE;
3617
3618      return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3619                                       CommaLocs, RParenLoc);
3620    }
3621
3622    // Determine whether this is a call to a member function.
3623    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
3624      NamedDecl *MemDecl = MemExpr->getMemberDecl();
3625      if (isa<CXXMethodDecl>(MemDecl))
3626        return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3627                                         CommaLocs, RParenLoc);
3628    }
3629
3630    // Determine whether this is a call to a pointer-to-member function.
3631    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
3632      if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3633          BO->getOpcode() == BinaryOperator::PtrMemI) {
3634        if (const FunctionProtoType *FPT
3635                                = BO->getType()->getAs<FunctionProtoType>()) {
3636          QualType ResultTy = FPT->getCallResultType(Context);
3637
3638          ExprOwningPtr<CXXMemberCallExpr>
3639            TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3640                                                          NumArgs, ResultTy,
3641                                                          RParenLoc));
3642
3643          if (CheckCallReturnType(FPT->getResultType(),
3644                                  BO->getRHS()->getSourceRange().getBegin(),
3645                                  TheCall.get(), 0))
3646            return ExprError();
3647
3648          if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3649                                      RParenLoc))
3650            return ExprError();
3651
3652          return Owned(MaybeBindToTemporary(TheCall.release()).release());
3653        }
3654        return ExprError(Diag(Fn->getLocStart(),
3655                              diag::err_typecheck_call_not_function)
3656                              << Fn->getType() << Fn->getSourceRange());
3657      }
3658    }
3659  }
3660
3661  // If we're directly calling a function, get the appropriate declaration.
3662  // Also, in C++, keep track of whether we should perform argument-dependent
3663  // lookup and whether there were any explicitly-specified template arguments.
3664
3665  Expr *NakedFn = Fn->IgnoreParens();
3666  if (isa<UnresolvedLookupExpr>(NakedFn)) {
3667    UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3668    return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3669                                   CommaLocs, RParenLoc);
3670  }
3671
3672  NamedDecl *NDecl = 0;
3673  if (isa<DeclRefExpr>(NakedFn))
3674    NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3675
3676  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3677}
3678
3679/// BuildResolvedCallExpr - Build a call to a resolved expression,
3680/// i.e. an expression not of \p OverloadTy.  The expression should
3681/// unary-convert to an expression of function-pointer or
3682/// block-pointer type.
3683///
3684/// \param NDecl the declaration being called, if available
3685Sema::OwningExprResult
3686Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3687                            SourceLocation LParenLoc,
3688                            Expr **Args, unsigned NumArgs,
3689                            SourceLocation RParenLoc) {
3690  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3691
3692  // Promote the function operand.
3693  UsualUnaryConversions(Fn);
3694
3695  // Make the call expr early, before semantic checks.  This guarantees cleanup
3696  // of arguments and function on error.
3697  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3698                                                               Args, NumArgs,
3699                                                               Context.BoolTy,
3700                                                               RParenLoc));
3701
3702  const FunctionType *FuncT;
3703  if (!Fn->getType()->isBlockPointerType()) {
3704    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3705    // have type pointer to function".
3706    const PointerType *PT = Fn->getType()->getAs<PointerType>();
3707    if (PT == 0)
3708      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3709        << Fn->getType() << Fn->getSourceRange());
3710    FuncT = PT->getPointeeType()->getAs<FunctionType>();
3711  } else { // This is a block call.
3712    FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
3713                getAs<FunctionType>();
3714  }
3715  if (FuncT == 0)
3716    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3717      << Fn->getType() << Fn->getSourceRange());
3718
3719  // Check for a valid return type
3720  if (CheckCallReturnType(FuncT->getResultType(),
3721                          Fn->getSourceRange().getBegin(), TheCall.get(),
3722                          FDecl))
3723    return ExprError();
3724
3725  // We know the result type of the call, set it.
3726  TheCall->setType(FuncT->getCallResultType(Context));
3727
3728  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
3729    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
3730                                RParenLoc))
3731      return ExprError();
3732  } else {
3733    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
3734
3735    if (FDecl) {
3736      // Check if we have too few/too many template arguments, based
3737      // on our knowledge of the function definition.
3738      const FunctionDecl *Def = 0;
3739      if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
3740        const FunctionProtoType *Proto =
3741            Def->getType()->getAs<FunctionProtoType>();
3742        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3743          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3744            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3745        }
3746      }
3747    }
3748
3749    // Promote the arguments (C99 6.5.2.2p6).
3750    for (unsigned i = 0; i != NumArgs; i++) {
3751      Expr *Arg = Args[i];
3752      DefaultArgumentPromotion(Arg);
3753      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3754                              Arg->getType(),
3755                              PDiag(diag::err_call_incomplete_argument)
3756                                << Arg->getSourceRange()))
3757        return ExprError();
3758      TheCall->setArg(i, Arg);
3759    }
3760  }
3761
3762  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3763    if (!Method->isStatic())
3764      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3765        << Fn->getSourceRange());
3766
3767  // Check for sentinels
3768  if (NDecl)
3769    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
3770
3771  // Do special checking on direct calls to functions.
3772  if (FDecl) {
3773    if (CheckFunctionCall(FDecl, TheCall.get()))
3774      return ExprError();
3775
3776    if (unsigned BuiltinID = FDecl->getBuiltinID())
3777      return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3778  } else if (NDecl) {
3779    if (CheckBlockCall(NDecl, TheCall.get()))
3780      return ExprError();
3781  }
3782
3783  return MaybeBindToTemporary(TheCall.take());
3784}
3785
3786Action::OwningExprResult
3787Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3788                           SourceLocation RParenLoc, ExprArg InitExpr) {
3789  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3790  // FIXME: put back this assert when initializers are worked out.
3791  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3792
3793  TypeSourceInfo *TInfo;
3794  QualType literalType = GetTypeFromParser(Ty, &TInfo);
3795  if (!TInfo)
3796    TInfo = Context.getTrivialTypeSourceInfo(literalType);
3797
3798  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3799}
3800
3801Action::OwningExprResult
3802Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3803                               SourceLocation RParenLoc, ExprArg InitExpr) {
3804  QualType literalType = TInfo->getType();
3805  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
3806
3807  if (literalType->isArrayType()) {
3808    if (literalType->isVariableArrayType())
3809      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3810        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
3811  } else if (!literalType->isDependentType() &&
3812             RequireCompleteType(LParenLoc, literalType,
3813                      PDiag(diag::err_typecheck_decl_incomplete_type)
3814                        << SourceRange(LParenLoc,
3815                                       literalExpr->getSourceRange().getEnd())))
3816    return ExprError();
3817
3818  InitializedEntity Entity
3819    = InitializedEntity::InitializeTemporary(literalType);
3820  InitializationKind Kind
3821    = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3822                                     /*IsCStyleCast=*/true);
3823  InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3824  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3825                                   MultiExprArg(*this, (void**)&literalExpr, 1),
3826                                            &literalType);
3827  if (Result.isInvalid())
3828    return ExprError();
3829  InitExpr.release();
3830  literalExpr = static_cast<Expr*>(Result.get());
3831
3832  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3833  if (isFileScope) { // 6.5.2.5p3
3834    if (CheckForConstantInitializer(literalExpr, literalType))
3835      return ExprError();
3836  }
3837
3838  Result.release();
3839
3840  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3841                                                 literalExpr, isFileScope));
3842}
3843
3844Action::OwningExprResult
3845Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
3846                    SourceLocation RBraceLoc) {
3847  unsigned NumInit = initlist.size();
3848  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
3849
3850  // Semantic analysis for initializers is done by ActOnDeclarator() and
3851  // CheckInitializer() - it requires knowledge of the object being intialized.
3852
3853  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3854                                               NumInit, RBraceLoc);
3855  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3856  return Owned(E);
3857}
3858
3859static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3860                                            QualType SrcTy, QualType DestTy) {
3861  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
3862    return CastExpr::CK_NoOp;
3863
3864  if (SrcTy->hasPointerRepresentation()) {
3865    if (DestTy->hasPointerRepresentation())
3866      return DestTy->isObjCObjectPointerType() ?
3867                CastExpr::CK_AnyPointerToObjCPointerCast :
3868                CastExpr::CK_BitCast;
3869    if (DestTy->isIntegerType())
3870      return CastExpr::CK_PointerToIntegral;
3871  }
3872
3873  if (SrcTy->isIntegerType()) {
3874    if (DestTy->isIntegerType())
3875      return CastExpr::CK_IntegralCast;
3876    if (DestTy->hasPointerRepresentation())
3877      return CastExpr::CK_IntegralToPointer;
3878    if (DestTy->isRealFloatingType())
3879      return CastExpr::CK_IntegralToFloating;
3880  }
3881
3882  if (SrcTy->isRealFloatingType()) {
3883    if (DestTy->isRealFloatingType())
3884      return CastExpr::CK_FloatingCast;
3885    if (DestTy->isIntegerType())
3886      return CastExpr::CK_FloatingToIntegral;
3887  }
3888
3889  // FIXME: Assert here.
3890  // assert(false && "Unhandled cast combination!");
3891  return CastExpr::CK_Unknown;
3892}
3893
3894/// CheckCastTypes - Check type constraints for casting between types.
3895bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
3896                          CastExpr::CastKind& Kind,
3897                          CXXBaseSpecifierArray &BasePath,
3898                          bool FunctionalStyle) {
3899  if (getLangOptions().CPlusPlus)
3900    return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath,
3901                              FunctionalStyle);
3902
3903  DefaultFunctionArrayLvalueConversion(castExpr);
3904
3905  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3906  // type needs to be scalar.
3907  if (castType->isVoidType()) {
3908    // Cast to void allows any expr type.
3909    Kind = CastExpr::CK_ToVoid;
3910    return false;
3911  }
3912
3913  if (RequireCompleteType(TyR.getBegin(), castType,
3914                          diag::err_typecheck_cast_to_incomplete))
3915    return true;
3916
3917  if (!castType->isScalarType() && !castType->isVectorType()) {
3918    if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
3919        (castType->isStructureType() || castType->isUnionType())) {
3920      // GCC struct/union extension: allow cast to self.
3921      // FIXME: Check that the cast destination type is complete.
3922      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3923        << castType << castExpr->getSourceRange();
3924      Kind = CastExpr::CK_NoOp;
3925      return false;
3926    }
3927
3928    if (castType->isUnionType()) {
3929      // GCC cast to union extension
3930      RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
3931      RecordDecl::field_iterator Field, FieldEnd;
3932      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
3933           Field != FieldEnd; ++Field) {
3934        if (Context.hasSameUnqualifiedType(Field->getType(),
3935                                           castExpr->getType())) {
3936          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3937            << castExpr->getSourceRange();
3938          break;
3939        }
3940      }
3941      if (Field == FieldEnd)
3942        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3943          << castExpr->getType() << castExpr->getSourceRange();
3944      Kind = CastExpr::CK_ToUnion;
3945      return false;
3946    }
3947
3948    // Reject any other conversions to non-scalar types.
3949    return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3950      << castType << castExpr->getSourceRange();
3951  }
3952
3953  if (!castExpr->getType()->isScalarType() &&
3954      !castExpr->getType()->isVectorType()) {
3955    return Diag(castExpr->getLocStart(),
3956                diag::err_typecheck_expect_scalar_operand)
3957      << castExpr->getType() << castExpr->getSourceRange();
3958  }
3959
3960  if (castType->isExtVectorType())
3961    return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3962
3963  if (castType->isVectorType())
3964    return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3965  if (castExpr->getType()->isVectorType())
3966    return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3967
3968  if (isa<ObjCSelectorExpr>(castExpr))
3969    return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3970
3971  if (!castType->isArithmeticType()) {
3972    QualType castExprType = castExpr->getType();
3973    if (!castExprType->isIntegralType(Context) &&
3974        castExprType->isArithmeticType())
3975      return Diag(castExpr->getLocStart(),
3976                  diag::err_cast_pointer_from_non_pointer_int)
3977        << castExprType << castExpr->getSourceRange();
3978  } else if (!castExpr->getType()->isArithmeticType()) {
3979    if (!castType->isIntegralType(Context) && castType->isArithmeticType())
3980      return Diag(castExpr->getLocStart(),
3981                  diag::err_cast_pointer_to_non_pointer_int)
3982        << castType << castExpr->getSourceRange();
3983  }
3984
3985  Kind = getScalarCastKind(Context, castExpr->getType(), castType);
3986  return false;
3987}
3988
3989bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3990                           CastExpr::CastKind &Kind) {
3991  assert(VectorTy->isVectorType() && "Not a vector type!");
3992
3993  if (Ty->isVectorType() || Ty->isIntegerType()) {
3994    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
3995      return Diag(R.getBegin(),
3996                  Ty->isVectorType() ?
3997                  diag::err_invalid_conversion_between_vectors :
3998                  diag::err_invalid_conversion_between_vector_and_integer)
3999        << VectorTy << Ty << R;
4000  } else
4001    return Diag(R.getBegin(),
4002                diag::err_invalid_conversion_between_vector_and_scalar)
4003      << VectorTy << Ty << R;
4004
4005  Kind = CastExpr::CK_BitCast;
4006  return false;
4007}
4008
4009bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
4010                              CastExpr::CastKind &Kind) {
4011  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4012
4013  QualType SrcTy = CastExpr->getType();
4014
4015  // If SrcTy is a VectorType, the total size must match to explicitly cast to
4016  // an ExtVectorType.
4017  if (SrcTy->isVectorType()) {
4018    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4019      return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4020        << DestTy << SrcTy << R;
4021    Kind = CastExpr::CK_BitCast;
4022    return false;
4023  }
4024
4025  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4026  // conversion will take place first from scalar to elt type, and then
4027  // splat from elt type to vector.
4028  if (SrcTy->isPointerType())
4029    return Diag(R.getBegin(),
4030                diag::err_invalid_conversion_between_vector_and_scalar)
4031      << DestTy << SrcTy << R;
4032
4033  QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4034  ImpCastExprToType(CastExpr, DestElemTy,
4035                    getScalarCastKind(Context, SrcTy, DestElemTy));
4036
4037  Kind = CastExpr::CK_VectorSplat;
4038  return false;
4039}
4040
4041Action::OwningExprResult
4042Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
4043                    SourceLocation RParenLoc, ExprArg Op) {
4044  assert((Ty != 0) && (Op.get() != 0) &&
4045         "ActOnCastExpr(): missing type or expr");
4046
4047  TypeSourceInfo *castTInfo;
4048  QualType castType = GetTypeFromParser(Ty, &castTInfo);
4049  if (!castTInfo)
4050    castTInfo = Context.getTrivialTypeSourceInfo(castType);
4051
4052  // If the Expr being casted is a ParenListExpr, handle it specially.
4053  Expr *castExpr = (Expr *)Op.get();
4054  if (isa<ParenListExpr>(castExpr))
4055    return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
4056                                    castTInfo);
4057
4058  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
4059}
4060
4061Action::OwningExprResult
4062Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
4063                          SourceLocation RParenLoc, ExprArg Op) {
4064  Expr *castExpr = static_cast<Expr*>(Op.get());
4065
4066  CastExpr::CastKind Kind = CastExpr::CK_Unknown;
4067  CXXBaseSpecifierArray BasePath;
4068  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
4069                     Kind, BasePath))
4070    return ExprError();
4071
4072  Op.release();
4073  return Owned(new (Context) CStyleCastExpr(
4074                                    Ty->getType().getNonLValueExprType(Context),
4075                                            Kind, castExpr, BasePath, Ty,
4076                                            LParenLoc, RParenLoc));
4077}
4078
4079/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4080/// of comma binary operators.
4081Action::OwningExprResult
4082Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
4083  Expr *expr = EA.takeAs<Expr>();
4084  ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4085  if (!E)
4086    return Owned(expr);
4087
4088  OwningExprResult Result(*this, E->getExpr(0));
4089
4090  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4091    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
4092                        Owned(E->getExpr(i)));
4093
4094  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
4095}
4096
4097Action::OwningExprResult
4098Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4099                               SourceLocation RParenLoc, ExprArg Op,
4100                               TypeSourceInfo *TInfo) {
4101  ParenListExpr *PE = (ParenListExpr *)Op.get();
4102  QualType Ty = TInfo->getType();
4103  bool isAltiVecLiteral = false;
4104
4105  // Check for an altivec literal,
4106  // i.e. all the elements are integer constants.
4107  if (getLangOptions().AltiVec && Ty->isVectorType()) {
4108    if (PE->getNumExprs() == 0) {
4109      Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4110      return ExprError();
4111    }
4112    if (PE->getNumExprs() == 1) {
4113      if (!PE->getExpr(0)->getType()->isVectorType())
4114        isAltiVecLiteral = true;
4115    }
4116    else
4117      isAltiVecLiteral = true;
4118  }
4119
4120  // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4121  // then handle it as such.
4122  if (isAltiVecLiteral) {
4123    llvm::SmallVector<Expr *, 8> initExprs;
4124    for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4125      initExprs.push_back(PE->getExpr(i));
4126
4127    // FIXME: This means that pretty-printing the final AST will produce curly
4128    // braces instead of the original commas.
4129    Op.release();
4130    InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4131                                                 &initExprs[0],
4132                                                 initExprs.size(), RParenLoc);
4133    E->setType(Ty);
4134    return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
4135  } else {
4136    // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4137    // sequence of BinOp comma operators.
4138    Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
4139    return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
4140  }
4141}
4142
4143Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
4144                                                  SourceLocation R,
4145                                                  MultiExprArg Val,
4146                                                  TypeTy *TypeOfCast) {
4147  unsigned nexprs = Val.size();
4148  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4149  assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4150  Expr *expr;
4151  if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4152    expr = new (Context) ParenExpr(L, R, exprs[0]);
4153  else
4154    expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
4155  return Owned(expr);
4156}
4157
4158/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4159/// In that case, lhs = cond.
4160/// C99 6.5.15
4161QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4162                                        SourceLocation QuestionLoc) {
4163  // C++ is sufficiently different to merit its own checker.
4164  if (getLangOptions().CPlusPlus)
4165    return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4166
4167  UsualUnaryConversions(Cond);
4168  UsualUnaryConversions(LHS);
4169  UsualUnaryConversions(RHS);
4170  QualType CondTy = Cond->getType();
4171  QualType LHSTy = LHS->getType();
4172  QualType RHSTy = RHS->getType();
4173
4174  // first, check the condition.
4175  if (!CondTy->isScalarType()) { // C99 6.5.15p2
4176    Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4177      << CondTy;
4178    return QualType();
4179  }
4180
4181  // Now check the two expressions.
4182  if (LHSTy->isVectorType() || RHSTy->isVectorType())
4183    return CheckVectorOperands(QuestionLoc, LHS, RHS);
4184
4185  // If both operands have arithmetic type, do the usual arithmetic conversions
4186  // to find a common type: C99 6.5.15p3,5.
4187  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4188    UsualArithmeticConversions(LHS, RHS);
4189    return LHS->getType();
4190  }
4191
4192  // If both operands are the same structure or union type, the result is that
4193  // type.
4194  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
4195    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4196      if (LHSRT->getDecl() == RHSRT->getDecl())
4197        // "If both the operands have structure or union type, the result has
4198        // that type."  This implies that CV qualifiers are dropped.
4199        return LHSTy.getUnqualifiedType();
4200    // FIXME: Type of conditional expression must be complete in C mode.
4201  }
4202
4203  // C99 6.5.15p5: "If both operands have void type, the result has void type."
4204  // The following || allows only one side to be void (a GCC-ism).
4205  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4206    if (!LHSTy->isVoidType())
4207      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4208        << RHS->getSourceRange();
4209    if (!RHSTy->isVoidType())
4210      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4211        << LHS->getSourceRange();
4212    ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4213    ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
4214    return Context.VoidTy;
4215  }
4216  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4217  // the type of the other operand."
4218  if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
4219      RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4220    // promote the null to a pointer.
4221    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
4222    return LHSTy;
4223  }
4224  if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
4225      LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4226    ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
4227    return RHSTy;
4228  }
4229
4230  // All objective-c pointer type analysis is done here.
4231  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4232                                                        QuestionLoc);
4233  if (!compositeType.isNull())
4234    return compositeType;
4235
4236
4237  // Handle block pointer types.
4238  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4239    if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4240      if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4241        QualType destType = Context.getPointerType(Context.VoidTy);
4242        ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4243        ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4244        return destType;
4245      }
4246      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4247      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4248      return QualType();
4249    }
4250    // We have 2 block pointer types.
4251    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4252      // Two identical block pointer types are always compatible.
4253      return LHSTy;
4254    }
4255    // The block pointer types aren't identical, continue checking.
4256    QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4257    QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
4258
4259    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4260                                    rhptee.getUnqualifiedType())) {
4261      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4262      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4263      // In this situation, we assume void* type. No especially good
4264      // reason, but this is what gcc does, and we do have to pick
4265      // to get a consistent AST.
4266      QualType incompatTy = Context.getPointerType(Context.VoidTy);
4267      ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4268      ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4269      return incompatTy;
4270    }
4271    // The block pointer types are compatible.
4272    ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4273    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4274    return LHSTy;
4275  }
4276
4277  // Check constraints for C object pointers types (C99 6.5.15p3,6).
4278  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4279    // get the "pointed to" types
4280    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4281    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4282
4283    // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4284    if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4285      // Figure out necessary qualifiers (C99 6.5.15p6)
4286      QualType destPointee
4287        = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4288      QualType destType = Context.getPointerType(destPointee);
4289      // Add qualifiers if necessary.
4290      ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4291      // Promote to void*.
4292      ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4293      return destType;
4294    }
4295    if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4296      QualType destPointee
4297        = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4298      QualType destType = Context.getPointerType(destPointee);
4299      // Add qualifiers if necessary.
4300      ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4301      // Promote to void*.
4302      ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4303      return destType;
4304    }
4305
4306    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4307      // Two identical pointer types are always compatible.
4308      return LHSTy;
4309    }
4310    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4311                                    rhptee.getUnqualifiedType())) {
4312      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4313        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4314      // In this situation, we assume void* type. No especially good
4315      // reason, but this is what gcc does, and we do have to pick
4316      // to get a consistent AST.
4317      QualType incompatTy = Context.getPointerType(Context.VoidTy);
4318      ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4319      ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4320      return incompatTy;
4321    }
4322    // The pointer types are compatible.
4323    // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4324    // differently qualified versions of compatible types, the result type is
4325    // a pointer to an appropriately qualified version of the *composite*
4326    // type.
4327    // FIXME: Need to calculate the composite type.
4328    // FIXME: Need to add qualifiers
4329    ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4330    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4331    return LHSTy;
4332  }
4333
4334  // GCC compatibility: soften pointer/integer mismatch.
4335  if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4336    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4337      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4338    ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
4339    return RHSTy;
4340  }
4341  if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4342    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4343      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4344    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
4345    return LHSTy;
4346  }
4347
4348  // Otherwise, the operands are not compatible.
4349  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4350    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4351  return QualType();
4352}
4353
4354/// FindCompositeObjCPointerType - Helper method to find composite type of
4355/// two objective-c pointer types of the two input expressions.
4356QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4357                                        SourceLocation QuestionLoc) {
4358  QualType LHSTy = LHS->getType();
4359  QualType RHSTy = RHS->getType();
4360
4361  // Handle things like Class and struct objc_class*.  Here we case the result
4362  // to the pseudo-builtin, because that will be implicitly cast back to the
4363  // redefinition type if an attempt is made to access its fields.
4364  if (LHSTy->isObjCClassType() &&
4365      (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4366    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4367    return LHSTy;
4368  }
4369  if (RHSTy->isObjCClassType() &&
4370      (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4371    ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4372    return RHSTy;
4373  }
4374  // And the same for struct objc_object* / id
4375  if (LHSTy->isObjCIdType() &&
4376      (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4377    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4378    return LHSTy;
4379  }
4380  if (RHSTy->isObjCIdType() &&
4381      (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4382    ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4383    return RHSTy;
4384  }
4385  // And the same for struct objc_selector* / SEL
4386  if (Context.isObjCSelType(LHSTy) &&
4387      (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4388    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4389    return LHSTy;
4390  }
4391  if (Context.isObjCSelType(RHSTy) &&
4392      (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4393    ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4394    return RHSTy;
4395  }
4396  // Check constraints for Objective-C object pointers types.
4397  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4398
4399    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4400      // Two identical object pointer types are always compatible.
4401      return LHSTy;
4402    }
4403    const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4404    const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4405    QualType compositeType = LHSTy;
4406
4407    // If both operands are interfaces and either operand can be
4408    // assigned to the other, use that type as the composite
4409    // type. This allows
4410    //   xxx ? (A*) a : (B*) b
4411    // where B is a subclass of A.
4412    //
4413    // Additionally, as for assignment, if either type is 'id'
4414    // allow silent coercion. Finally, if the types are
4415    // incompatible then make sure to use 'id' as the composite
4416    // type so the result is acceptable for sending messages to.
4417
4418    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4419    // It could return the composite type.
4420    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4421      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4422    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4423      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4424    } else if ((LHSTy->isObjCQualifiedIdType() ||
4425                RHSTy->isObjCQualifiedIdType()) &&
4426               Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4427      // Need to handle "id<xx>" explicitly.
4428      // GCC allows qualified id and any Objective-C type to devolve to
4429      // id. Currently localizing to here until clear this should be
4430      // part of ObjCQualifiedIdTypesAreCompatible.
4431      compositeType = Context.getObjCIdType();
4432    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4433      compositeType = Context.getObjCIdType();
4434    } else if (!(compositeType =
4435                 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4436      ;
4437    else {
4438      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4439      << LHSTy << RHSTy
4440      << LHS->getSourceRange() << RHS->getSourceRange();
4441      QualType incompatTy = Context.getObjCIdType();
4442      ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4443      ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4444      return incompatTy;
4445    }
4446    // The object pointer types are compatible.
4447    ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4448    ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4449    return compositeType;
4450  }
4451  // Check Objective-C object pointer types and 'void *'
4452  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4453    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4454    QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4455    QualType destPointee
4456    = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4457    QualType destType = Context.getPointerType(destPointee);
4458    // Add qualifiers if necessary.
4459    ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4460    // Promote to void*.
4461    ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4462    return destType;
4463  }
4464  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4465    QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4466    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4467    QualType destPointee
4468    = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4469    QualType destType = Context.getPointerType(destPointee);
4470    // Add qualifiers if necessary.
4471    ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4472    // Promote to void*.
4473    ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4474    return destType;
4475  }
4476  return QualType();
4477}
4478
4479/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
4480/// in the case of a the GNU conditional expr extension.
4481Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4482                                                  SourceLocation ColonLoc,
4483                                                  ExprArg Cond, ExprArg LHS,
4484                                                  ExprArg RHS) {
4485  Expr *CondExpr = (Expr *) Cond.get();
4486  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
4487
4488  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4489  // was the condition.
4490  bool isLHSNull = LHSExpr == 0;
4491  if (isLHSNull)
4492    LHSExpr = CondExpr;
4493
4494  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
4495                                             RHSExpr, QuestionLoc);
4496  if (result.isNull())
4497    return ExprError();
4498
4499  Cond.release();
4500  LHS.release();
4501  RHS.release();
4502  return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
4503                                                 isLHSNull ? 0 : LHSExpr,
4504                                                 ColonLoc, RHSExpr, result));
4505}
4506
4507// CheckPointerTypesForAssignment - This is a very tricky routine (despite
4508// being closely modeled after the C99 spec:-). The odd characteristic of this
4509// routine is it effectively iqnores the qualifiers on the top level pointee.
4510// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4511// FIXME: add a couple examples in this comment.
4512Sema::AssignConvertType
4513Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4514  QualType lhptee, rhptee;
4515
4516  if ((lhsType->isObjCClassType() &&
4517       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4518     (rhsType->isObjCClassType() &&
4519       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4520      return Compatible;
4521  }
4522
4523  // get the "pointed to" type (ignoring qualifiers at the top level)
4524  lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4525  rhptee = rhsType->getAs<PointerType>()->getPointeeType();
4526
4527  // make sure we operate on the canonical type
4528  lhptee = Context.getCanonicalType(lhptee);
4529  rhptee = Context.getCanonicalType(rhptee);
4530
4531  AssignConvertType ConvTy = Compatible;
4532
4533  // C99 6.5.16.1p1: This following citation is common to constraints
4534  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4535  // qualifiers of the type *pointed to* by the right;
4536  // FIXME: Handle ExtQualType
4537  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4538    ConvTy = CompatiblePointerDiscardsQualifiers;
4539
4540  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4541  // incomplete type and the other is a pointer to a qualified or unqualified
4542  // version of void...
4543  if (lhptee->isVoidType()) {
4544    if (rhptee->isIncompleteOrObjectType())
4545      return ConvTy;
4546
4547    // As an extension, we allow cast to/from void* to function pointer.
4548    assert(rhptee->isFunctionType());
4549    return FunctionVoidPointer;
4550  }
4551
4552  if (rhptee->isVoidType()) {
4553    if (lhptee->isIncompleteOrObjectType())
4554      return ConvTy;
4555
4556    // As an extension, we allow cast to/from void* to function pointer.
4557    assert(lhptee->isFunctionType());
4558    return FunctionVoidPointer;
4559  }
4560  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
4561  // unqualified versions of compatible types, ...
4562  lhptee = lhptee.getUnqualifiedType();
4563  rhptee = rhptee.getUnqualifiedType();
4564  if (!Context.typesAreCompatible(lhptee, rhptee)) {
4565    // Check if the pointee types are compatible ignoring the sign.
4566    // We explicitly check for char so that we catch "char" vs
4567    // "unsigned char" on systems where "char" is unsigned.
4568    if (lhptee->isCharType())
4569      lhptee = Context.UnsignedCharTy;
4570    else if (lhptee->hasSignedIntegerRepresentation())
4571      lhptee = Context.getCorrespondingUnsignedType(lhptee);
4572
4573    if (rhptee->isCharType())
4574      rhptee = Context.UnsignedCharTy;
4575    else if (rhptee->hasSignedIntegerRepresentation())
4576      rhptee = Context.getCorrespondingUnsignedType(rhptee);
4577
4578    if (lhptee == rhptee) {
4579      // Types are compatible ignoring the sign. Qualifier incompatibility
4580      // takes priority over sign incompatibility because the sign
4581      // warning can be disabled.
4582      if (ConvTy != Compatible)
4583        return ConvTy;
4584      return IncompatiblePointerSign;
4585    }
4586
4587    // If we are a multi-level pointer, it's possible that our issue is simply
4588    // one of qualification - e.g. char ** -> const char ** is not allowed. If
4589    // the eventual target type is the same and the pointers have the same
4590    // level of indirection, this must be the issue.
4591    if (lhptee->isPointerType() && rhptee->isPointerType()) {
4592      do {
4593        lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4594        rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4595
4596        lhptee = Context.getCanonicalType(lhptee);
4597        rhptee = Context.getCanonicalType(rhptee);
4598      } while (lhptee->isPointerType() && rhptee->isPointerType());
4599
4600      if (Context.hasSameUnqualifiedType(lhptee, rhptee))
4601        return IncompatibleNestedPointerQualifiers;
4602    }
4603
4604    // General pointer incompatibility takes priority over qualifiers.
4605    return IncompatiblePointer;
4606  }
4607  return ConvTy;
4608}
4609
4610/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4611/// block pointer types are compatible or whether a block and normal pointer
4612/// are compatible. It is more restrict than comparing two function pointer
4613// types.
4614Sema::AssignConvertType
4615Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
4616                                          QualType rhsType) {
4617  QualType lhptee, rhptee;
4618
4619  // get the "pointed to" type (ignoring qualifiers at the top level)
4620  lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4621  rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
4622
4623  // make sure we operate on the canonical type
4624  lhptee = Context.getCanonicalType(lhptee);
4625  rhptee = Context.getCanonicalType(rhptee);
4626
4627  AssignConvertType ConvTy = Compatible;
4628
4629  // For blocks we enforce that qualifiers are identical.
4630  if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
4631    ConvTy = CompatiblePointerDiscardsQualifiers;
4632
4633  if (!getLangOptions().CPlusPlus) {
4634    if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4635      return IncompatibleBlockPointer;
4636  }
4637  else if (!Context.typesAreCompatible(lhptee, rhptee))
4638    return IncompatibleBlockPointer;
4639  return ConvTy;
4640}
4641
4642/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4643/// for assignment compatibility.
4644Sema::AssignConvertType
4645Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4646  if (lhsType->isObjCBuiltinType()) {
4647    // Class is not compatible with ObjC object pointers.
4648    if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4649        !rhsType->isObjCQualifiedClassType())
4650      return IncompatiblePointer;
4651    return Compatible;
4652  }
4653  if (rhsType->isObjCBuiltinType()) {
4654    // Class is not compatible with ObjC object pointers.
4655    if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4656        !lhsType->isObjCQualifiedClassType())
4657      return IncompatiblePointer;
4658    return Compatible;
4659  }
4660  QualType lhptee =
4661  lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4662  QualType rhptee =
4663  rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4664  // make sure we operate on the canonical type
4665  lhptee = Context.getCanonicalType(lhptee);
4666  rhptee = Context.getCanonicalType(rhptee);
4667  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4668    return CompatiblePointerDiscardsQualifiers;
4669
4670  if (Context.typesAreCompatible(lhsType, rhsType))
4671    return Compatible;
4672  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4673    return IncompatibleObjCQualifiedId;
4674  return IncompatiblePointer;
4675}
4676
4677/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4678/// has code to accommodate several GCC extensions when type checking
4679/// pointers. Here are some objectionable examples that GCC considers warnings:
4680///
4681///  int a, *pint;
4682///  short *pshort;
4683///  struct foo *pfoo;
4684///
4685///  pint = pshort; // warning: assignment from incompatible pointer type
4686///  a = pint; // warning: assignment makes integer from pointer without a cast
4687///  pint = a; // warning: assignment makes pointer from integer without a cast
4688///  pint = pfoo; // warning: assignment from incompatible pointer type
4689///
4690/// As a result, the code for dealing with pointers is more complex than the
4691/// C99 spec dictates.
4692///
4693Sema::AssignConvertType
4694Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
4695  // Get canonical types.  We're not formatting these types, just comparing
4696  // them.
4697  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4698  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
4699
4700  if (lhsType == rhsType)
4701    return Compatible; // Common case: fast path an exact match.
4702
4703  if ((lhsType->isObjCClassType() &&
4704       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4705     (rhsType->isObjCClassType() &&
4706       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4707      return Compatible;
4708  }
4709
4710  // If the left-hand side is a reference type, then we are in a
4711  // (rare!) case where we've allowed the use of references in C,
4712  // e.g., as a parameter type in a built-in function. In this case,
4713  // just make sure that the type referenced is compatible with the
4714  // right-hand side type. The caller is responsible for adjusting
4715  // lhsType so that the resulting expression does not have reference
4716  // type.
4717  if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
4718    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
4719      return Compatible;
4720    return Incompatible;
4721  }
4722  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4723  // to the same ExtVector type.
4724  if (lhsType->isExtVectorType()) {
4725    if (rhsType->isExtVectorType())
4726      return lhsType == rhsType ? Compatible : Incompatible;
4727    if (rhsType->isArithmeticType())
4728      return Compatible;
4729  }
4730
4731  if (lhsType->isVectorType() || rhsType->isVectorType()) {
4732    if (lhsType->isVectorType() && rhsType->isVectorType()) {
4733      // If we are allowing lax vector conversions, and LHS and RHS are both
4734      // vectors, the total size only needs to be the same. This is a bitcast;
4735      // no bits are changed but the result type is different.
4736      if (getLangOptions().LaxVectorConversions &&
4737         (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)))
4738        return IncompatibleVectors;
4739
4740      // Allow assignments of an AltiVec vector type to an equivalent GCC
4741      // vector type and vice versa
4742      if (Context.areCompatibleVectorTypes(lhsType, rhsType))
4743        return Compatible;
4744    }
4745    return Incompatible;
4746  }
4747
4748  if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
4749      !(getLangOptions().CPlusPlus && lhsType->isEnumeralType()))
4750    return Compatible;
4751
4752  if (isa<PointerType>(lhsType)) {
4753    if (rhsType->isIntegerType())
4754      return IntToPointer;
4755
4756    if (isa<PointerType>(rhsType))
4757      return CheckPointerTypesForAssignment(lhsType, rhsType);
4758
4759    // In general, C pointers are not compatible with ObjC object pointers.
4760    if (isa<ObjCObjectPointerType>(rhsType)) {
4761      if (lhsType->isVoidPointerType()) // an exception to the rule.
4762        return Compatible;
4763      return IncompatiblePointer;
4764    }
4765    if (rhsType->getAs<BlockPointerType>()) {
4766      if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
4767        return Compatible;
4768
4769      // Treat block pointers as objects.
4770      if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
4771        return Compatible;
4772    }
4773    return Incompatible;
4774  }
4775
4776  if (isa<BlockPointerType>(lhsType)) {
4777    if (rhsType->isIntegerType())
4778      return IntToBlockPointer;
4779
4780    // Treat block pointers as objects.
4781    if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
4782      return Compatible;
4783
4784    if (rhsType->isBlockPointerType())
4785      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
4786
4787    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
4788      if (RHSPT->getPointeeType()->isVoidType())
4789        return Compatible;
4790    }
4791    return Incompatible;
4792  }
4793
4794  if (isa<ObjCObjectPointerType>(lhsType)) {
4795    if (rhsType->isIntegerType())
4796      return IntToPointer;
4797
4798    // In general, C pointers are not compatible with ObjC object pointers.
4799    if (isa<PointerType>(rhsType)) {
4800      if (rhsType->isVoidPointerType()) // an exception to the rule.
4801        return Compatible;
4802      return IncompatiblePointer;
4803    }
4804    if (rhsType->isObjCObjectPointerType()) {
4805      return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
4806    }
4807    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
4808      if (RHSPT->getPointeeType()->isVoidType())
4809        return Compatible;
4810    }
4811    // Treat block pointers as objects.
4812    if (rhsType->isBlockPointerType())
4813      return Compatible;
4814    return Incompatible;
4815  }
4816  if (isa<PointerType>(rhsType)) {
4817    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4818    if (lhsType == Context.BoolTy)
4819      return Compatible;
4820
4821    if (lhsType->isIntegerType())
4822      return PointerToInt;
4823
4824    if (isa<PointerType>(lhsType))
4825      return CheckPointerTypesForAssignment(lhsType, rhsType);
4826
4827    if (isa<BlockPointerType>(lhsType) &&
4828        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
4829      return Compatible;
4830    return Incompatible;
4831  }
4832  if (isa<ObjCObjectPointerType>(rhsType)) {
4833    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4834    if (lhsType == Context.BoolTy)
4835      return Compatible;
4836
4837    if (lhsType->isIntegerType())
4838      return PointerToInt;
4839
4840    // In general, C pointers are not compatible with ObjC object pointers.
4841    if (isa<PointerType>(lhsType)) {
4842      if (lhsType->isVoidPointerType()) // an exception to the rule.
4843        return Compatible;
4844      return IncompatiblePointer;
4845    }
4846    if (isa<BlockPointerType>(lhsType) &&
4847        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
4848      return Compatible;
4849    return Incompatible;
4850  }
4851
4852  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
4853    if (Context.typesAreCompatible(lhsType, rhsType))
4854      return Compatible;
4855  }
4856  return Incompatible;
4857}
4858
4859/// \brief Constructs a transparent union from an expression that is
4860/// used to initialize the transparent union.
4861static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
4862                                      QualType UnionType, FieldDecl *Field) {
4863  // Build an initializer list that designates the appropriate member
4864  // of the transparent union.
4865  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
4866                                                   &E, 1,
4867                                                   SourceLocation());
4868  Initializer->setType(UnionType);
4869  Initializer->setInitializedFieldInUnion(Field);
4870
4871  // Build a compound literal constructing a value of the transparent
4872  // union type from this initializer list.
4873  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
4874  E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
4875                                  Initializer, false);
4876}
4877
4878Sema::AssignConvertType
4879Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4880  QualType FromType = rExpr->getType();
4881
4882  // If the ArgType is a Union type, we want to handle a potential
4883  // transparent_union GCC extension.
4884  const RecordType *UT = ArgType->getAsUnionType();
4885  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
4886    return Incompatible;
4887
4888  // The field to initialize within the transparent union.
4889  RecordDecl *UD = UT->getDecl();
4890  FieldDecl *InitField = 0;
4891  // It's compatible if the expression matches any of the fields.
4892  for (RecordDecl::field_iterator it = UD->field_begin(),
4893         itend = UD->field_end();
4894       it != itend; ++it) {
4895    if (it->getType()->isPointerType()) {
4896      // If the transparent union contains a pointer type, we allow:
4897      // 1) void pointer
4898      // 2) null pointer constant
4899      if (FromType->isPointerType())
4900        if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
4901          ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
4902          InitField = *it;
4903          break;
4904        }
4905
4906      if (rExpr->isNullPointerConstant(Context,
4907                                       Expr::NPC_ValueDependentIsNull)) {
4908        ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
4909        InitField = *it;
4910        break;
4911      }
4912    }
4913
4914    if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4915          == Compatible) {
4916      InitField = *it;
4917      break;
4918    }
4919  }
4920
4921  if (!InitField)
4922    return Incompatible;
4923
4924  ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4925  return Compatible;
4926}
4927
4928Sema::AssignConvertType
4929Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
4930  if (getLangOptions().CPlusPlus) {
4931    if (!lhsType->isRecordType()) {
4932      // C++ 5.17p3: If the left operand is not of class type, the
4933      // expression is implicitly converted (C++ 4) to the
4934      // cv-unqualified type of the left operand.
4935      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4936                                    AA_Assigning))
4937        return Incompatible;
4938      return Compatible;
4939    }
4940
4941    // FIXME: Currently, we fall through and treat C++ classes like C
4942    // structures.
4943  }
4944
4945  // C99 6.5.16.1p1: the left operand is a pointer and the right is
4946  // a null pointer constant.
4947  if ((lhsType->isPointerType() ||
4948       lhsType->isObjCObjectPointerType() ||
4949       lhsType->isBlockPointerType())
4950      && rExpr->isNullPointerConstant(Context,
4951                                      Expr::NPC_ValueDependentIsNull)) {
4952    ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
4953    return Compatible;
4954  }
4955
4956  // This check seems unnatural, however it is necessary to ensure the proper
4957  // conversion of functions/arrays. If the conversion were done for all
4958  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
4959  // expressions that suppress this implicit conversion (&, sizeof).
4960  //
4961  // Suppress this for references: C++ 8.5.3p5.
4962  if (!lhsType->isReferenceType())
4963    DefaultFunctionArrayLvalueConversion(rExpr);
4964
4965  Sema::AssignConvertType result =
4966    CheckAssignmentConstraints(lhsType, rExpr->getType());
4967
4968  // C99 6.5.16.1p2: The value of the right operand is converted to the
4969  // type of the assignment expression.
4970  // CheckAssignmentConstraints allows the left-hand side to be a reference,
4971  // so that we can use references in built-in functions even in C.
4972  // The getNonReferenceType() call makes sure that the resulting expression
4973  // does not have reference type.
4974  if (result != Incompatible && rExpr->getType() != lhsType)
4975    ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context),
4976                      CastExpr::CK_Unknown);
4977  return result;
4978}
4979
4980QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
4981  Diag(Loc, diag::err_typecheck_invalid_operands)
4982    << lex->getType() << rex->getType()
4983    << lex->getSourceRange() << rex->getSourceRange();
4984  return QualType();
4985}
4986
4987QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
4988  // For conversion purposes, we ignore any qualifiers.
4989  // For example, "const float" and "float" are equivalent.
4990  QualType lhsType =
4991    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4992  QualType rhsType =
4993    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
4994
4995  // If the vector types are identical, return.
4996  if (lhsType == rhsType)
4997    return lhsType;
4998
4999  // Handle the case of a vector & extvector type of the same size and element
5000  // type.  It would be nice if we only had one vector type someday.
5001  if (getLangOptions().LaxVectorConversions) {
5002    // FIXME: Should we warn here?
5003    if (const VectorType *LV = lhsType->getAs<VectorType>()) {
5004      if (const VectorType *RV = rhsType->getAs<VectorType>())
5005        if (LV->getElementType() == RV->getElementType() &&
5006            LV->getNumElements() == RV->getNumElements()) {
5007          if (lhsType->isExtVectorType()) {
5008            ImpCastExprToType(rex, lhsType, CastExpr::CK_BitCast);
5009            return lhsType;
5010          }
5011
5012          ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
5013          return rhsType;
5014        }
5015    }
5016  }
5017
5018  // Handle the case of equivalent AltiVec and GCC vector types
5019  if (lhsType->isVectorType() && rhsType->isVectorType() &&
5020      Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5021    ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
5022    return rhsType;
5023  }
5024
5025  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5026  // swap back (so that we don't reverse the inputs to a subtract, for instance.
5027  bool swapped = false;
5028  if (rhsType->isExtVectorType()) {
5029    swapped = true;
5030    std::swap(rex, lex);
5031    std::swap(rhsType, lhsType);
5032  }
5033
5034  // Handle the case of an ext vector and scalar.
5035  if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
5036    QualType EltTy = LV->getElementType();
5037    if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
5038      if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
5039        ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
5040        if (swapped) std::swap(rex, lex);
5041        return lhsType;
5042      }
5043    }
5044    if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5045        rhsType->isRealFloatingType()) {
5046      if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
5047        ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
5048        if (swapped) std::swap(rex, lex);
5049        return lhsType;
5050      }
5051    }
5052  }
5053
5054  // Vectors of different size or scalar and non-ext-vector are errors.
5055  Diag(Loc, diag::err_typecheck_vector_not_convertable)
5056    << lex->getType() << rex->getType()
5057    << lex->getSourceRange() << rex->getSourceRange();
5058  return QualType();
5059}
5060
5061QualType Sema::CheckMultiplyDivideOperands(
5062  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
5063  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5064    return CheckVectorOperands(Loc, lex, rex);
5065
5066  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
5067
5068  if (!lex->getType()->isArithmeticType() ||
5069      !rex->getType()->isArithmeticType())
5070    return InvalidOperands(Loc, lex, rex);
5071
5072  // Check for division by zero.
5073  if (isDiv &&
5074      rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5075    DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
5076                                     << rex->getSourceRange());
5077
5078  return compType;
5079}
5080
5081QualType Sema::CheckRemainderOperands(
5082  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
5083  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5084    if (lex->getType()->hasIntegerRepresentation() &&
5085        rex->getType()->hasIntegerRepresentation())
5086      return CheckVectorOperands(Loc, lex, rex);
5087    return InvalidOperands(Loc, lex, rex);
5088  }
5089
5090  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
5091
5092  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5093    return InvalidOperands(Loc, lex, rex);
5094
5095  // Check for remainder by zero.
5096  if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5097    DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5098                                 << rex->getSourceRange());
5099
5100  return compType;
5101}
5102
5103QualType Sema::CheckAdditionOperands( // C99 6.5.6
5104  Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
5105  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5106    QualType compType = CheckVectorOperands(Loc, lex, rex);
5107    if (CompLHSTy) *CompLHSTy = compType;
5108    return compType;
5109  }
5110
5111  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
5112
5113  // handle the common case first (both operands are arithmetic).
5114  if (lex->getType()->isArithmeticType() &&
5115      rex->getType()->isArithmeticType()) {
5116    if (CompLHSTy) *CompLHSTy = compType;
5117    return compType;
5118  }
5119
5120  // Put any potential pointer into PExp
5121  Expr* PExp = lex, *IExp = rex;
5122  if (IExp->getType()->isAnyPointerType())
5123    std::swap(PExp, IExp);
5124
5125  if (PExp->getType()->isAnyPointerType()) {
5126
5127    if (IExp->getType()->isIntegerType()) {
5128      QualType PointeeTy = PExp->getType()->getPointeeType();
5129
5130      // Check for arithmetic on pointers to incomplete types.
5131      if (PointeeTy->isVoidType()) {
5132        if (getLangOptions().CPlusPlus) {
5133          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5134            << lex->getSourceRange() << rex->getSourceRange();
5135          return QualType();
5136        }
5137
5138        // GNU extension: arithmetic on pointer to void
5139        Diag(Loc, diag::ext_gnu_void_ptr)
5140          << lex->getSourceRange() << rex->getSourceRange();
5141      } else if (PointeeTy->isFunctionType()) {
5142        if (getLangOptions().CPlusPlus) {
5143          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5144            << lex->getType() << lex->getSourceRange();
5145          return QualType();
5146        }
5147
5148        // GNU extension: arithmetic on pointer to function
5149        Diag(Loc, diag::ext_gnu_ptr_func_arith)
5150          << lex->getType() << lex->getSourceRange();
5151      } else {
5152        // Check if we require a complete type.
5153        if (((PExp->getType()->isPointerType() &&
5154              !PExp->getType()->isDependentType()) ||
5155              PExp->getType()->isObjCObjectPointerType()) &&
5156             RequireCompleteType(Loc, PointeeTy,
5157                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5158                             << PExp->getSourceRange()
5159                             << PExp->getType()))
5160          return QualType();
5161      }
5162      // Diagnose bad cases where we step over interface counts.
5163      if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
5164        Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5165          << PointeeTy << PExp->getSourceRange();
5166        return QualType();
5167      }
5168
5169      if (CompLHSTy) {
5170        QualType LHSTy = Context.isPromotableBitField(lex);
5171        if (LHSTy.isNull()) {
5172          LHSTy = lex->getType();
5173          if (LHSTy->isPromotableIntegerType())
5174            LHSTy = Context.getPromotedIntegerType(LHSTy);
5175        }
5176        *CompLHSTy = LHSTy;
5177      }
5178      return PExp->getType();
5179    }
5180  }
5181
5182  return InvalidOperands(Loc, lex, rex);
5183}
5184
5185// C99 6.5.6
5186QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
5187                                        SourceLocation Loc, QualType* CompLHSTy) {
5188  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5189    QualType compType = CheckVectorOperands(Loc, lex, rex);
5190    if (CompLHSTy) *CompLHSTy = compType;
5191    return compType;
5192  }
5193
5194  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
5195
5196  // Enforce type constraints: C99 6.5.6p3.
5197
5198  // Handle the common case first (both operands are arithmetic).
5199  if (lex->getType()->isArithmeticType()
5200      && rex->getType()->isArithmeticType()) {
5201    if (CompLHSTy) *CompLHSTy = compType;
5202    return compType;
5203  }
5204
5205  // Either ptr - int   or   ptr - ptr.
5206  if (lex->getType()->isAnyPointerType()) {
5207    QualType lpointee = lex->getType()->getPointeeType();
5208
5209    // The LHS must be an completely-defined object type.
5210
5211    bool ComplainAboutVoid = false;
5212    Expr *ComplainAboutFunc = 0;
5213    if (lpointee->isVoidType()) {
5214      if (getLangOptions().CPlusPlus) {
5215        Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5216          << lex->getSourceRange() << rex->getSourceRange();
5217        return QualType();
5218      }
5219
5220      // GNU C extension: arithmetic on pointer to void
5221      ComplainAboutVoid = true;
5222    } else if (lpointee->isFunctionType()) {
5223      if (getLangOptions().CPlusPlus) {
5224        Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5225          << lex->getType() << lex->getSourceRange();
5226        return QualType();
5227      }
5228
5229      // GNU C extension: arithmetic on pointer to function
5230      ComplainAboutFunc = lex;
5231    } else if (!lpointee->isDependentType() &&
5232               RequireCompleteType(Loc, lpointee,
5233                                   PDiag(diag::err_typecheck_sub_ptr_object)
5234                                     << lex->getSourceRange()
5235                                     << lex->getType()))
5236      return QualType();
5237
5238    // Diagnose bad cases where we step over interface counts.
5239    if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
5240      Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5241        << lpointee << lex->getSourceRange();
5242      return QualType();
5243    }
5244
5245    // The result type of a pointer-int computation is the pointer type.
5246    if (rex->getType()->isIntegerType()) {
5247      if (ComplainAboutVoid)
5248        Diag(Loc, diag::ext_gnu_void_ptr)
5249          << lex->getSourceRange() << rex->getSourceRange();
5250      if (ComplainAboutFunc)
5251        Diag(Loc, diag::ext_gnu_ptr_func_arith)
5252          << ComplainAboutFunc->getType()
5253          << ComplainAboutFunc->getSourceRange();
5254
5255      if (CompLHSTy) *CompLHSTy = lex->getType();
5256      return lex->getType();
5257    }
5258
5259    // Handle pointer-pointer subtractions.
5260    if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
5261      QualType rpointee = RHSPTy->getPointeeType();
5262
5263      // RHS must be a completely-type object type.
5264      // Handle the GNU void* extension.
5265      if (rpointee->isVoidType()) {
5266        if (getLangOptions().CPlusPlus) {
5267          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5268            << lex->getSourceRange() << rex->getSourceRange();
5269          return QualType();
5270        }
5271
5272        ComplainAboutVoid = true;
5273      } else if (rpointee->isFunctionType()) {
5274        if (getLangOptions().CPlusPlus) {
5275          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5276            << rex->getType() << rex->getSourceRange();
5277          return QualType();
5278        }
5279
5280        // GNU extension: arithmetic on pointer to function
5281        if (!ComplainAboutFunc)
5282          ComplainAboutFunc = rex;
5283      } else if (!rpointee->isDependentType() &&
5284                 RequireCompleteType(Loc, rpointee,
5285                                     PDiag(diag::err_typecheck_sub_ptr_object)
5286                                       << rex->getSourceRange()
5287                                       << rex->getType()))
5288        return QualType();
5289
5290      if (getLangOptions().CPlusPlus) {
5291        // Pointee types must be the same: C++ [expr.add]
5292        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5293          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5294            << lex->getType() << rex->getType()
5295            << lex->getSourceRange() << rex->getSourceRange();
5296          return QualType();
5297        }
5298      } else {
5299        // Pointee types must be compatible C99 6.5.6p3
5300        if (!Context.typesAreCompatible(
5301                Context.getCanonicalType(lpointee).getUnqualifiedType(),
5302                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5303          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5304            << lex->getType() << rex->getType()
5305            << lex->getSourceRange() << rex->getSourceRange();
5306          return QualType();
5307        }
5308      }
5309
5310      if (ComplainAboutVoid)
5311        Diag(Loc, diag::ext_gnu_void_ptr)
5312          << lex->getSourceRange() << rex->getSourceRange();
5313      if (ComplainAboutFunc)
5314        Diag(Loc, diag::ext_gnu_ptr_func_arith)
5315          << ComplainAboutFunc->getType()
5316          << ComplainAboutFunc->getSourceRange();
5317
5318      if (CompLHSTy) *CompLHSTy = lex->getType();
5319      return Context.getPointerDiffType();
5320    }
5321  }
5322
5323  return InvalidOperands(Loc, lex, rex);
5324}
5325
5326// C99 6.5.7
5327QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
5328                                  bool isCompAssign) {
5329  // C99 6.5.7p2: Each of the operands shall have integer type.
5330  if (!lex->getType()->hasIntegerRepresentation() ||
5331      !rex->getType()->hasIntegerRepresentation())
5332    return InvalidOperands(Loc, lex, rex);
5333
5334  // Vector shifts promote their scalar inputs to vector type.
5335  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5336    return CheckVectorOperands(Loc, lex, rex);
5337
5338  // Shifts don't perform usual arithmetic conversions, they just do integer
5339  // promotions on each operand. C99 6.5.7p3
5340  QualType LHSTy = Context.isPromotableBitField(lex);
5341  if (LHSTy.isNull()) {
5342    LHSTy = lex->getType();
5343    if (LHSTy->isPromotableIntegerType())
5344      LHSTy = Context.getPromotedIntegerType(LHSTy);
5345  }
5346  if (!isCompAssign)
5347    ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
5348
5349  UsualUnaryConversions(rex);
5350
5351  // Sanity-check shift operands
5352  llvm::APSInt Right;
5353  // Check right/shifter operand
5354  if (!rex->isValueDependent() &&
5355      rex->isIntegerConstantExpr(Right, Context)) {
5356    if (Right.isNegative())
5357      Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5358    else {
5359      llvm::APInt LeftBits(Right.getBitWidth(),
5360                          Context.getTypeSize(lex->getType()));
5361      if (Right.uge(LeftBits))
5362        Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5363    }
5364  }
5365
5366  // "The type of the result is that of the promoted left operand."
5367  return LHSTy;
5368}
5369
5370static bool IsWithinTemplateSpecialization(Decl *D) {
5371  if (DeclContext *DC = D->getDeclContext()) {
5372    if (isa<ClassTemplateSpecializationDecl>(DC))
5373      return true;
5374    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
5375      return FD->isFunctionTemplateSpecialization();
5376  }
5377  return false;
5378}
5379
5380// C99 6.5.8, C++ [expr.rel]
5381QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
5382                                    unsigned OpaqueOpc, bool isRelational) {
5383  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5384
5385  // Handle vector comparisons separately.
5386  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5387    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
5388
5389  QualType lType = lex->getType();
5390  QualType rType = rex->getType();
5391
5392  if (!lType->hasFloatingRepresentation() &&
5393      !(lType->isBlockPointerType() && isRelational)) {
5394    // For non-floating point types, check for self-comparisons of the form
5395    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
5396    // often indicate logic errors in the program.
5397    //
5398    // NOTE: Don't warn about comparison expressions resulting from macro
5399    // expansion. Also don't warn about comparisons which are only self
5400    // comparisons within a template specialization. The warnings should catch
5401    // obvious cases in the definition of the template anyways. The idea is to
5402    // warn when the typed comparison operator will always evaluate to the same
5403    // result.
5404    Expr *LHSStripped = lex->IgnoreParens();
5405    Expr *RHSStripped = rex->IgnoreParens();
5406    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
5407      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
5408        if (DRL->getDecl() == DRR->getDecl() && !Loc.isMacroID() &&
5409            !IsWithinTemplateSpecialization(DRL->getDecl())) {
5410          DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5411                              << 0 // self-
5412                              << (Opc == BinaryOperator::EQ
5413                                  || Opc == BinaryOperator::LE
5414                                  || Opc == BinaryOperator::GE));
5415        } else if (lType->isArrayType() && rType->isArrayType() &&
5416                   !DRL->getDecl()->getType()->isReferenceType() &&
5417                   !DRR->getDecl()->getType()->isReferenceType()) {
5418            // what is it always going to eval to?
5419            char always_evals_to;
5420            switch(Opc) {
5421            case BinaryOperator::EQ: // e.g. array1 == array2
5422              always_evals_to = 0; // false
5423              break;
5424            case BinaryOperator::NE: // e.g. array1 != array2
5425              always_evals_to = 1; // true
5426              break;
5427            default:
5428              // best we can say is 'a constant'
5429              always_evals_to = 2; // e.g. array1 <= array2
5430              break;
5431            }
5432            DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5433                                << 1 // array
5434                                << always_evals_to);
5435        }
5436      }
5437    }
5438
5439    if (isa<CastExpr>(LHSStripped))
5440      LHSStripped = LHSStripped->IgnoreParenCasts();
5441    if (isa<CastExpr>(RHSStripped))
5442      RHSStripped = RHSStripped->IgnoreParenCasts();
5443
5444    // Warn about comparisons against a string constant (unless the other
5445    // operand is null), the user probably wants strcmp.
5446    Expr *literalString = 0;
5447    Expr *literalStringStripped = 0;
5448    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
5449        !RHSStripped->isNullPointerConstant(Context,
5450                                            Expr::NPC_ValueDependentIsNull)) {
5451      literalString = lex;
5452      literalStringStripped = LHSStripped;
5453    } else if ((isa<StringLiteral>(RHSStripped) ||
5454                isa<ObjCEncodeExpr>(RHSStripped)) &&
5455               !LHSStripped->isNullPointerConstant(Context,
5456                                            Expr::NPC_ValueDependentIsNull)) {
5457      literalString = rex;
5458      literalStringStripped = RHSStripped;
5459    }
5460
5461    if (literalString) {
5462      std::string resultComparison;
5463      switch (Opc) {
5464      case BinaryOperator::LT: resultComparison = ") < 0"; break;
5465      case BinaryOperator::GT: resultComparison = ") > 0"; break;
5466      case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5467      case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5468      case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5469      case BinaryOperator::NE: resultComparison = ") != 0"; break;
5470      default: assert(false && "Invalid comparison operator");
5471      }
5472
5473      DiagRuntimeBehavior(Loc,
5474        PDiag(diag::warn_stringcompare)
5475          << isa<ObjCEncodeExpr>(literalStringStripped)
5476          << literalString->getSourceRange());
5477    }
5478  }
5479
5480  // C99 6.5.8p3 / C99 6.5.9p4
5481  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5482    UsualArithmeticConversions(lex, rex);
5483  else {
5484    UsualUnaryConversions(lex);
5485    UsualUnaryConversions(rex);
5486  }
5487
5488  lType = lex->getType();
5489  rType = rex->getType();
5490
5491  // The result of comparisons is 'bool' in C++, 'int' in C.
5492  QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
5493
5494  if (isRelational) {
5495    if (lType->isRealType() && rType->isRealType())
5496      return ResultTy;
5497  } else {
5498    // Check for comparisons of floating point operands using != and ==.
5499    if (lType->hasFloatingRepresentation())
5500      CheckFloatComparison(Loc,lex,rex);
5501
5502    if (lType->isArithmeticType() && rType->isArithmeticType())
5503      return ResultTy;
5504  }
5505
5506  bool LHSIsNull = lex->isNullPointerConstant(Context,
5507                                              Expr::NPC_ValueDependentIsNull);
5508  bool RHSIsNull = rex->isNullPointerConstant(Context,
5509                                              Expr::NPC_ValueDependentIsNull);
5510
5511  // All of the following pointer-related warnings are GCC extensions, except
5512  // when handling null pointer constants.
5513  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
5514    QualType LCanPointeeTy =
5515      Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
5516    QualType RCanPointeeTy =
5517      Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
5518
5519    if (getLangOptions().CPlusPlus) {
5520      if (LCanPointeeTy == RCanPointeeTy)
5521        return ResultTy;
5522      if (!isRelational &&
5523          (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5524        // Valid unless comparison between non-null pointer and function pointer
5525        // This is a gcc extension compatibility comparison.
5526        // In a SFINAE context, we treat this as a hard error to maintain
5527        // conformance with the C++ standard.
5528        if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5529            && !LHSIsNull && !RHSIsNull) {
5530          Diag(Loc,
5531               isSFINAEContext()?
5532                   diag::err_typecheck_comparison_of_fptr_to_void
5533                 : diag::ext_typecheck_comparison_of_fptr_to_void)
5534            << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5535
5536          if (isSFINAEContext())
5537            return QualType();
5538
5539          ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5540          return ResultTy;
5541        }
5542      }
5543      // C++ [expr.rel]p2:
5544      //   [...] Pointer conversions (4.10) and qualification
5545      //   conversions (4.4) are performed on pointer operands (or on
5546      //   a pointer operand and a null pointer constant) to bring
5547      //   them to their composite pointer type. [...]
5548      //
5549      // C++ [expr.eq]p1 uses the same notion for (in)equality
5550      // comparisons of pointers.
5551      bool NonStandardCompositeType = false;
5552      QualType T = FindCompositePointerType(Loc, lex, rex,
5553                              isSFINAEContext()? 0 : &NonStandardCompositeType);
5554      if (T.isNull()) {
5555        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5556          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5557        return QualType();
5558      } else if (NonStandardCompositeType) {
5559        Diag(Loc,
5560             diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
5561          << lType << rType << T
5562          << lex->getSourceRange() << rex->getSourceRange();
5563      }
5564
5565      ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5566      ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
5567      return ResultTy;
5568    }
5569    // C99 6.5.9p2 and C99 6.5.8p2
5570    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5571                                   RCanPointeeTy.getUnqualifiedType())) {
5572      // Valid unless a relational comparison of function pointers
5573      if (isRelational && LCanPointeeTy->isFunctionType()) {
5574        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5575          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5576      }
5577    } else if (!isRelational &&
5578               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5579      // Valid unless comparison between non-null pointer and function pointer
5580      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5581          && !LHSIsNull && !RHSIsNull) {
5582        Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5583          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5584      }
5585    } else {
5586      // Invalid
5587      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5588        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5589    }
5590    if (LCanPointeeTy != RCanPointeeTy)
5591      ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5592    return ResultTy;
5593  }
5594
5595  if (getLangOptions().CPlusPlus) {
5596    // Comparison of pointers with null pointer constants and equality
5597    // comparisons of member pointers to null pointer constants.
5598    if (RHSIsNull &&
5599        (lType->isPointerType() ||
5600         (!isRelational && lType->isMemberPointerType()))) {
5601      ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
5602      return ResultTy;
5603    }
5604    if (LHSIsNull &&
5605        (rType->isPointerType() ||
5606         (!isRelational && rType->isMemberPointerType()))) {
5607      ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
5608      return ResultTy;
5609    }
5610
5611    // Comparison of member pointers.
5612    if (!isRelational &&
5613        lType->isMemberPointerType() && rType->isMemberPointerType()) {
5614      // C++ [expr.eq]p2:
5615      //   In addition, pointers to members can be compared, or a pointer to
5616      //   member and a null pointer constant. Pointer to member conversions
5617      //   (4.11) and qualification conversions (4.4) are performed to bring
5618      //   them to a common type. If one operand is a null pointer constant,
5619      //   the common type is the type of the other operand. Otherwise, the
5620      //   common type is a pointer to member type similar (4.4) to the type
5621      //   of one of the operands, with a cv-qualification signature (4.4)
5622      //   that is the union of the cv-qualification signatures of the operand
5623      //   types.
5624      bool NonStandardCompositeType = false;
5625      QualType T = FindCompositePointerType(Loc, lex, rex,
5626                              isSFINAEContext()? 0 : &NonStandardCompositeType);
5627      if (T.isNull()) {
5628        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5629          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5630        return QualType();
5631      } else if (NonStandardCompositeType) {
5632        Diag(Loc,
5633             diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
5634          << lType << rType << T
5635          << lex->getSourceRange() << rex->getSourceRange();
5636      }
5637
5638      ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5639      ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
5640      return ResultTy;
5641    }
5642
5643    // Comparison of nullptr_t with itself.
5644    if (lType->isNullPtrType() && rType->isNullPtrType())
5645      return ResultTy;
5646  }
5647
5648  // Handle block pointer types.
5649  if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
5650    QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5651    QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
5652
5653    if (!LHSIsNull && !RHSIsNull &&
5654        !Context.typesAreCompatible(lpointee, rpointee)) {
5655      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5656        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5657    }
5658    ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5659    return ResultTy;
5660  }
5661  // Allow block pointers to be compared with null pointer constants.
5662  if (!isRelational
5663      && ((lType->isBlockPointerType() && rType->isPointerType())
5664          || (lType->isPointerType() && rType->isBlockPointerType()))) {
5665    if (!LHSIsNull && !RHSIsNull) {
5666      if (!((rType->isPointerType() && rType->getAs<PointerType>()
5667             ->getPointeeType()->isVoidType())
5668            || (lType->isPointerType() && lType->getAs<PointerType>()
5669                ->getPointeeType()->isVoidType())))
5670        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5671          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5672    }
5673    ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5674    return ResultTy;
5675  }
5676
5677  if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
5678    if (lType->isPointerType() || rType->isPointerType()) {
5679      const PointerType *LPT = lType->getAs<PointerType>();
5680      const PointerType *RPT = rType->getAs<PointerType>();
5681      bool LPtrToVoid = LPT ?
5682        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
5683      bool RPtrToVoid = RPT ?
5684        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
5685
5686      if (!LPtrToVoid && !RPtrToVoid &&
5687          !Context.typesAreCompatible(lType, rType)) {
5688        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5689          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5690      }
5691      ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5692      return ResultTy;
5693    }
5694    if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
5695      if (!Context.areComparableObjCPointerTypes(lType, rType))
5696        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5697          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5698      ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5699      return ResultTy;
5700    }
5701  }
5702  if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
5703      (lType->isIntegerType() && rType->isAnyPointerType())) {
5704    unsigned DiagID = 0;
5705    bool isError = false;
5706    if ((LHSIsNull && lType->isIntegerType()) ||
5707        (RHSIsNull && rType->isIntegerType())) {
5708      if (isRelational && !getLangOptions().CPlusPlus)
5709        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5710    } else if (isRelational && !getLangOptions().CPlusPlus)
5711      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5712    else if (getLangOptions().CPlusPlus) {
5713      DiagID = diag::err_typecheck_comparison_of_pointer_integer;
5714      isError = true;
5715    } else
5716      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
5717
5718    if (DiagID) {
5719      Diag(Loc, DiagID)
5720        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5721      if (isError)
5722        return QualType();
5723    }
5724
5725    if (lType->isIntegerType())
5726      ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
5727    else
5728      ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
5729    return ResultTy;
5730  }
5731
5732  // Handle block pointers.
5733  if (!isRelational && RHSIsNull
5734      && lType->isBlockPointerType() && rType->isIntegerType()) {
5735    ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
5736    return ResultTy;
5737  }
5738  if (!isRelational && LHSIsNull
5739      && lType->isIntegerType() && rType->isBlockPointerType()) {
5740    ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
5741    return ResultTy;
5742  }
5743  return InvalidOperands(Loc, lex, rex);
5744}
5745
5746/// CheckVectorCompareOperands - vector comparisons are a clang extension that
5747/// operates on extended vector types.  Instead of producing an IntTy result,
5748/// like a scalar comparison, a vector comparison produces a vector of integer
5749/// types.
5750QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
5751                                          SourceLocation Loc,
5752                                          bool isRelational) {
5753  // Check to make sure we're operating on vectors of the same type and width,
5754  // Allowing one side to be a scalar of element type.
5755  QualType vType = CheckVectorOperands(Loc, lex, rex);
5756  if (vType.isNull())
5757    return vType;
5758
5759  QualType lType = lex->getType();
5760  QualType rType = rex->getType();
5761
5762  // For non-floating point types, check for self-comparisons of the form
5763  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
5764  // often indicate logic errors in the program.
5765  if (!lType->hasFloatingRepresentation()) {
5766    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5767      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5768        if (DRL->getDecl() == DRR->getDecl())
5769          DiagRuntimeBehavior(Loc,
5770                              PDiag(diag::warn_comparison_always)
5771                                << 0 // self-
5772                                << 2 // "a constant"
5773                              );
5774  }
5775
5776  // Check for comparisons of floating point operands using != and ==.
5777  if (!isRelational && lType->hasFloatingRepresentation()) {
5778    assert (rType->hasFloatingRepresentation());
5779    CheckFloatComparison(Loc,lex,rex);
5780  }
5781
5782  // Return the type for the comparison, which is the same as vector type for
5783  // integer vectors, or an integer type of identical size and number of
5784  // elements for floating point vectors.
5785  if (lType->hasIntegerRepresentation())
5786    return lType;
5787
5788  const VectorType *VTy = lType->getAs<VectorType>();
5789  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
5790  if (TypeSize == Context.getTypeSize(Context.IntTy))
5791    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
5792  if (TypeSize == Context.getTypeSize(Context.LongTy))
5793    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5794
5795  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
5796         "Unhandled vector element size in vector compare");
5797  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5798}
5799
5800inline QualType Sema::CheckBitwiseOperands(
5801  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
5802  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5803    if (lex->getType()->hasIntegerRepresentation() &&
5804        rex->getType()->hasIntegerRepresentation())
5805      return CheckVectorOperands(Loc, lex, rex);
5806
5807    return InvalidOperands(Loc, lex, rex);
5808  }
5809
5810  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
5811
5812  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
5813    return compType;
5814  return InvalidOperands(Loc, lex, rex);
5815}
5816
5817inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
5818  Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
5819
5820  // Diagnose cases where the user write a logical and/or but probably meant a
5821  // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
5822  // is a constant.
5823  if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
5824      rex->getType()->isIntegerType() && !rex->isValueDependent() &&
5825      // Don't warn in macros.
5826      !Loc.isMacroID()) {
5827    // If the RHS can be constant folded, and if it constant folds to something
5828    // that isn't 0 or 1 (which indicate a potential logical operation that
5829    // happened to fold to true/false) then warn.
5830    Expr::EvalResult Result;
5831    if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
5832        Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
5833      Diag(Loc, diag::warn_logical_instead_of_bitwise)
5834       << rex->getSourceRange()
5835        << (Opc == BinaryOperator::LAnd ? "&&" : "||")
5836        << (Opc == BinaryOperator::LAnd ? "&" : "|");
5837    }
5838  }
5839
5840  if (!Context.getLangOptions().CPlusPlus) {
5841    UsualUnaryConversions(lex);
5842    UsualUnaryConversions(rex);
5843
5844    if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5845      return InvalidOperands(Loc, lex, rex);
5846
5847    return Context.IntTy;
5848  }
5849
5850  // The following is safe because we only use this method for
5851  // non-overloadable operands.
5852
5853  // C++ [expr.log.and]p1
5854  // C++ [expr.log.or]p1
5855  // The operands are both contextually converted to type bool.
5856  if (PerformContextuallyConvertToBool(lex) ||
5857      PerformContextuallyConvertToBool(rex))
5858    return InvalidOperands(Loc, lex, rex);
5859
5860  // C++ [expr.log.and]p2
5861  // C++ [expr.log.or]p2
5862  // The result is a bool.
5863  return Context.BoolTy;
5864}
5865
5866/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5867/// is a read-only property; return true if so. A readonly property expression
5868/// depends on various declarations and thus must be treated specially.
5869///
5870static bool IsReadonlyProperty(Expr *E, Sema &S) {
5871  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5872    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5873    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5874      QualType BaseType = PropExpr->getBase()->getType();
5875      if (const ObjCObjectPointerType *OPT =
5876            BaseType->getAsObjCInterfacePointerType())
5877        if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5878          if (S.isPropertyReadonly(PDecl, IFace))
5879            return true;
5880    }
5881  }
5882  return false;
5883}
5884
5885/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
5886/// emit an error and return true.  If so, return false.
5887static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
5888  SourceLocation OrigLoc = Loc;
5889  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
5890                                                              &Loc);
5891  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5892    IsLV = Expr::MLV_ReadonlyProperty;
5893  if (IsLV == Expr::MLV_Valid)
5894    return false;
5895
5896  unsigned Diag = 0;
5897  bool NeedType = false;
5898  switch (IsLV) { // C99 6.5.16p2
5899  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
5900  case Expr::MLV_ArrayType:
5901    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5902    NeedType = true;
5903    break;
5904  case Expr::MLV_NotObjectType:
5905    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5906    NeedType = true;
5907    break;
5908  case Expr::MLV_LValueCast:
5909    Diag = diag::err_typecheck_lvalue_casts_not_supported;
5910    break;
5911  case Expr::MLV_Valid:
5912    llvm_unreachable("did not take early return for MLV_Valid");
5913  case Expr::MLV_InvalidExpression:
5914  case Expr::MLV_MemberFunction:
5915  case Expr::MLV_ClassTemporary:
5916    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5917    break;
5918  case Expr::MLV_IncompleteType:
5919  case Expr::MLV_IncompleteVoidType:
5920    return S.RequireCompleteType(Loc, E->getType(),
5921              S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5922                  << E->getSourceRange());
5923  case Expr::MLV_DuplicateVectorComponents:
5924    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5925    break;
5926  case Expr::MLV_NotBlockQualified:
5927    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5928    break;
5929  case Expr::MLV_ReadonlyProperty:
5930    Diag = diag::error_readonly_property_assignment;
5931    break;
5932  case Expr::MLV_NoSetterProperty:
5933    Diag = diag::error_nosetter_property_assignment;
5934    break;
5935  case Expr::MLV_SubObjCPropertySetting:
5936    Diag = diag::error_no_subobject_property_setting;
5937    break;
5938  }
5939
5940  SourceRange Assign;
5941  if (Loc != OrigLoc)
5942    Assign = SourceRange(OrigLoc, OrigLoc);
5943  if (NeedType)
5944    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
5945  else
5946    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
5947  return true;
5948}
5949
5950
5951
5952// C99 6.5.16.1
5953QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5954                                       SourceLocation Loc,
5955                                       QualType CompoundType) {
5956  // Verify that LHS is a modifiable lvalue, and emit error if not.
5957  if (CheckForModifiableLvalue(LHS, Loc, *this))
5958    return QualType();
5959
5960  QualType LHSType = LHS->getType();
5961  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
5962  AssignConvertType ConvTy;
5963  if (CompoundType.isNull()) {
5964    QualType LHSTy(LHSType);
5965    // Simple assignment "x = y".
5966    if (const ObjCImplicitSetterGetterRefExpr *OISGE =
5967        dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) {
5968      // If using property-dot syntax notation for assignment, and there is a
5969      // setter, RHS expression is being passed to the setter argument. So,
5970      // type conversion (and comparison) is RHS to setter's argument type.
5971      if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) {
5972        ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
5973        LHSTy = (*P)->getType();
5974      }
5975    }
5976
5977    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
5978    // Special case of NSObject attributes on c-style pointer types.
5979    if (ConvTy == IncompatiblePointer &&
5980        ((Context.isObjCNSObjectType(LHSType) &&
5981          RHSType->isObjCObjectPointerType()) ||
5982         (Context.isObjCNSObjectType(RHSType) &&
5983          LHSType->isObjCObjectPointerType())))
5984      ConvTy = Compatible;
5985
5986    // If the RHS is a unary plus or minus, check to see if they = and + are
5987    // right next to each other.  If so, the user may have typo'd "x =+ 4"
5988    // instead of "x += 4".
5989    Expr *RHSCheck = RHS;
5990    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5991      RHSCheck = ICE->getSubExpr();
5992    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5993      if ((UO->getOpcode() == UnaryOperator::Plus ||
5994           UO->getOpcode() == UnaryOperator::Minus) &&
5995          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
5996          // Only if the two operators are exactly adjacent.
5997          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5998          // And there is a space or other character before the subexpr of the
5999          // unary +/-.  We don't want to warn on "x=-1".
6000          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6001          UO->getSubExpr()->getLocStart().isFileID()) {
6002        Diag(Loc, diag::warn_not_compound_assign)
6003          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
6004          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
6005      }
6006    }
6007  } else {
6008    // Compound assignment "x += y"
6009    ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
6010  }
6011
6012  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
6013                               RHS, AA_Assigning))
6014    return QualType();
6015
6016
6017  // Check to see if the destination operand is a dereferenced null pointer.  If
6018  // so, and if not volatile-qualified, this is undefined behavior that the
6019  // optimizer will delete, so warn about it.  People sometimes try to use this
6020  // to get a deterministic trap and are surprised by clang's behavior.  This
6021  // only handles the pattern "*null = whatever", which is a very syntactic
6022  // check.
6023  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
6024    if (UO->getOpcode() == UnaryOperator::Deref &&
6025        UO->getSubExpr()->IgnoreParenCasts()->
6026          isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6027        !UO->getType().isVolatileQualified()) {
6028    Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6029        << UO->getSubExpr()->getSourceRange();
6030    Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6031  }
6032
6033  // C99 6.5.16p3: The type of an assignment expression is the type of the
6034  // left operand unless the left operand has qualified type, in which case
6035  // it is the unqualified version of the type of the left operand.
6036  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6037  // is converted to the type of the assignment expression (above).
6038  // C++ 5.17p1: the type of the assignment expression is that of its left
6039  // operand.
6040  return LHSType.getUnqualifiedType();
6041}
6042
6043// C99 6.5.17
6044QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
6045  DiagnoseUnusedExprResult(LHS);
6046
6047  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
6048  // C++ does not perform this conversion (C++ [expr.comma]p1).
6049  if (!getLangOptions().CPlusPlus)
6050    DefaultFunctionArrayLvalueConversion(RHS);
6051
6052  // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
6053  // incomplete in C++).
6054
6055  return RHS->getType();
6056}
6057
6058/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6059/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
6060QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
6061                                              bool isInc, bool isPrefix) {
6062  if (Op->isTypeDependent())
6063    return Context.DependentTy;
6064
6065  QualType ResType = Op->getType();
6066  assert(!ResType.isNull() && "no type for increment/decrement expression");
6067
6068  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
6069    // Decrement of bool is not allowed.
6070    if (!isInc) {
6071      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
6072      return QualType();
6073    }
6074    // Increment of bool sets it to true, but is deprecated.
6075    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
6076  } else if (ResType->isRealType()) {
6077    // OK!
6078  } else if (ResType->isAnyPointerType()) {
6079    QualType PointeeTy = ResType->getPointeeType();
6080
6081    // C99 6.5.2.4p2, 6.5.6p2
6082    if (PointeeTy->isVoidType()) {
6083      if (getLangOptions().CPlusPlus) {
6084        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
6085          << Op->getSourceRange();
6086        return QualType();
6087      }
6088
6089      // Pointer to void is a GNU extension in C.
6090      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
6091    } else if (PointeeTy->isFunctionType()) {
6092      if (getLangOptions().CPlusPlus) {
6093        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
6094          << Op->getType() << Op->getSourceRange();
6095        return QualType();
6096      }
6097
6098      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
6099        << ResType << Op->getSourceRange();
6100    } else if (RequireCompleteType(OpLoc, PointeeTy,
6101                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6102                             << Op->getSourceRange()
6103                             << ResType))
6104      return QualType();
6105    // Diagnose bad cases where we step over interface counts.
6106    else if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6107      Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6108        << PointeeTy << Op->getSourceRange();
6109      return QualType();
6110    }
6111  } else if (ResType->isAnyComplexType()) {
6112    // C99 does not support ++/-- on complex types, we allow as an extension.
6113    Diag(OpLoc, diag::ext_integer_increment_complex)
6114      << ResType << Op->getSourceRange();
6115  } else {
6116    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
6117      << ResType << int(isInc) << Op->getSourceRange();
6118    return QualType();
6119  }
6120  // At this point, we know we have a real, complex or pointer type.
6121  // Now make sure the operand is a modifiable lvalue.
6122  if (CheckForModifiableLvalue(Op, OpLoc, *this))
6123    return QualType();
6124  // In C++, a prefix increment is the same type as the operand. Otherwise
6125  // (in C or with postfix), the increment is the unqualified type of the
6126  // operand.
6127  return isPrefix && getLangOptions().CPlusPlus
6128    ? ResType : ResType.getUnqualifiedType();
6129}
6130
6131/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
6132/// This routine allows us to typecheck complex/recursive expressions
6133/// where the declaration is needed for type checking. We only need to
6134/// handle cases when the expression references a function designator
6135/// or is an lvalue. Here are some examples:
6136///  - &(x) => x
6137///  - &*****f => f for f a function designator.
6138///  - &s.xx => s
6139///  - &s.zz[1].yy -> s, if zz is an array
6140///  - *(x + 1) -> x, if x is an array
6141///  - &"123"[2] -> 0
6142///  - & __real__ x -> x
6143static NamedDecl *getPrimaryDecl(Expr *E) {
6144  switch (E->getStmtClass()) {
6145  case Stmt::DeclRefExprClass:
6146    return cast<DeclRefExpr>(E)->getDecl();
6147  case Stmt::MemberExprClass:
6148    // If this is an arrow operator, the address is an offset from
6149    // the base's value, so the object the base refers to is
6150    // irrelevant.
6151    if (cast<MemberExpr>(E)->isArrow())
6152      return 0;
6153    // Otherwise, the expression refers to a part of the base
6154    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
6155  case Stmt::ArraySubscriptExprClass: {
6156    // FIXME: This code shouldn't be necessary!  We should catch the implicit
6157    // promotion of register arrays earlier.
6158    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
6159    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
6160      if (ICE->getSubExpr()->getType()->isArrayType())
6161        return getPrimaryDecl(ICE->getSubExpr());
6162    }
6163    return 0;
6164  }
6165  case Stmt::UnaryOperatorClass: {
6166    UnaryOperator *UO = cast<UnaryOperator>(E);
6167
6168    switch(UO->getOpcode()) {
6169    case UnaryOperator::Real:
6170    case UnaryOperator::Imag:
6171    case UnaryOperator::Extension:
6172      return getPrimaryDecl(UO->getSubExpr());
6173    default:
6174      return 0;
6175    }
6176  }
6177  case Stmt::ParenExprClass:
6178    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
6179  case Stmt::ImplicitCastExprClass:
6180    // If the result of an implicit cast is an l-value, we care about
6181    // the sub-expression; otherwise, the result here doesn't matter.
6182    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
6183  default:
6184    return 0;
6185  }
6186}
6187
6188/// CheckAddressOfOperand - The operand of & must be either a function
6189/// designator or an lvalue designating an object. If it is an lvalue, the
6190/// object cannot be declared with storage class register or be a bit field.
6191/// Note: The usual conversions are *not* applied to the operand of the &
6192/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
6193/// In C++, the operand might be an overloaded function name, in which case
6194/// we allow the '&' but retain the overloaded-function type.
6195QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
6196  // Make sure to ignore parentheses in subsequent checks
6197  op = op->IgnoreParens();
6198
6199  if (op->isTypeDependent())
6200    return Context.DependentTy;
6201
6202  if (getLangOptions().C99) {
6203    // Implement C99-only parts of addressof rules.
6204    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
6205      if (uOp->getOpcode() == UnaryOperator::Deref)
6206        // Per C99 6.5.3.2, the address of a deref always returns a valid result
6207        // (assuming the deref expression is valid).
6208        return uOp->getSubExpr()->getType();
6209    }
6210    // Technically, there should be a check for array subscript
6211    // expressions here, but the result of one is always an lvalue anyway.
6212  }
6213  NamedDecl *dcl = getPrimaryDecl(op);
6214  Expr::isLvalueResult lval = op->isLvalue(Context);
6215
6216  MemberExpr *ME = dyn_cast<MemberExpr>(op);
6217  if (lval == Expr::LV_MemberFunction && ME &&
6218      isa<CXXMethodDecl>(ME->getMemberDecl())) {
6219    ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
6220    // &f where f is a member of the current object, or &o.f, or &p->f
6221    // All these are not allowed, and we need to catch them before the dcl
6222    // branch of the if, below.
6223    Diag(OpLoc, diag::err_unqualified_pointer_member_function)
6224        << dcl;
6225    // FIXME: Improve this diagnostic and provide a fixit.
6226
6227    // Now recover by acting as if the function had been accessed qualified.
6228    return Context.getMemberPointerType(op->getType(),
6229                Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
6230                       .getTypePtr());
6231  }
6232
6233  if (lval == Expr::LV_ClassTemporary) {
6234    Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6235                                 : diag::ext_typecheck_addrof_class_temporary)
6236      << op->getType() << op->getSourceRange();
6237    if (isSFINAEContext())
6238      return QualType();
6239  } else if (isa<ObjCSelectorExpr>(op))
6240    return Context.getPointerType(op->getType());
6241  else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
6242    // C99 6.5.3.2p1
6243    // The operand must be either an l-value or a function designator
6244    if (!op->getType()->isFunctionType()) {
6245      // FIXME: emit more specific diag...
6246      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6247        << op->getSourceRange();
6248      return QualType();
6249    }
6250  } else if (op->getBitField()) { // C99 6.5.3.2p1
6251    // The operand cannot be a bit-field
6252    Diag(OpLoc, diag::err_typecheck_address_of)
6253      << "bit-field" << op->getSourceRange();
6254        return QualType();
6255  } else if (op->refersToVectorElement()) {
6256    // The operand cannot be an element of a vector
6257    Diag(OpLoc, diag::err_typecheck_address_of)
6258      << "vector element" << op->getSourceRange();
6259    return QualType();
6260  } else if (isa<ObjCPropertyRefExpr>(op)) {
6261    // cannot take address of a property expression.
6262    Diag(OpLoc, diag::err_typecheck_address_of)
6263      << "property expression" << op->getSourceRange();
6264    return QualType();
6265  } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6266    // FIXME: Can LHS ever be null here?
6267    if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6268      return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
6269  } else if (isa<UnresolvedLookupExpr>(op)) {
6270    return Context.OverloadTy;
6271  } else if (dcl) { // C99 6.5.3.2p1
6272    // We have an lvalue with a decl. Make sure the decl is not declared
6273    // with the register storage-class specifier.
6274    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
6275      if (vd->getStorageClass() == VarDecl::Register) {
6276        Diag(OpLoc, diag::err_typecheck_address_of)
6277          << "register variable" << op->getSourceRange();
6278        return QualType();
6279      }
6280    } else if (isa<FunctionTemplateDecl>(dcl)) {
6281      return Context.OverloadTy;
6282    } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
6283      // Okay: we can take the address of a field.
6284      // Could be a pointer to member, though, if there is an explicit
6285      // scope qualifier for the class.
6286      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
6287        DeclContext *Ctx = dcl->getDeclContext();
6288        if (Ctx && Ctx->isRecord()) {
6289          if (FD->getType()->isReferenceType()) {
6290            Diag(OpLoc,
6291                 diag::err_cannot_form_pointer_to_member_of_reference_type)
6292              << FD->getDeclName() << FD->getType();
6293            return QualType();
6294          }
6295
6296          return Context.getMemberPointerType(op->getType(),
6297                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
6298        }
6299      }
6300    } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
6301      // Okay: we can take the address of a function.
6302      // As above.
6303      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6304          MD->isInstance())
6305        return Context.getMemberPointerType(op->getType(),
6306              Context.getTypeDeclType(MD->getParent()).getTypePtr());
6307    } else if (!isa<FunctionDecl>(dcl))
6308      assert(0 && "Unknown/unexpected decl type");
6309  }
6310
6311  if (lval == Expr::LV_IncompleteVoidType) {
6312    // Taking the address of a void variable is technically illegal, but we
6313    // allow it in cases which are otherwise valid.
6314    // Example: "extern void x; void* y = &x;".
6315    Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6316  }
6317
6318  // If the operand has type "type", the result has type "pointer to type".
6319  if (op->getType()->isObjCObjectType())
6320    return Context.getObjCObjectPointerType(op->getType());
6321  return Context.getPointerType(op->getType());
6322}
6323
6324/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
6325QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
6326  if (Op->isTypeDependent())
6327    return Context.DependentTy;
6328
6329  UsualUnaryConversions(Op);
6330  QualType OpTy = Op->getType();
6331  QualType Result;
6332
6333  // Note that per both C89 and C99, indirection is always legal, even if OpTy
6334  // is an incomplete type or void.  It would be possible to warn about
6335  // dereferencing a void pointer, but it's completely well-defined, and such a
6336  // warning is unlikely to catch any mistakes.
6337  if (const PointerType *PT = OpTy->getAs<PointerType>())
6338    Result = PT->getPointeeType();
6339  else if (const ObjCObjectPointerType *OPT =
6340             OpTy->getAs<ObjCObjectPointerType>())
6341    Result = OPT->getPointeeType();
6342
6343  if (Result.isNull()) {
6344    Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
6345      << OpTy << Op->getSourceRange();
6346    return QualType();
6347  }
6348
6349  return Result;
6350}
6351
6352static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6353  tok::TokenKind Kind) {
6354  BinaryOperator::Opcode Opc;
6355  switch (Kind) {
6356  default: assert(0 && "Unknown binop!");
6357  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
6358  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
6359  case tok::star:                 Opc = BinaryOperator::Mul; break;
6360  case tok::slash:                Opc = BinaryOperator::Div; break;
6361  case tok::percent:              Opc = BinaryOperator::Rem; break;
6362  case tok::plus:                 Opc = BinaryOperator::Add; break;
6363  case tok::minus:                Opc = BinaryOperator::Sub; break;
6364  case tok::lessless:             Opc = BinaryOperator::Shl; break;
6365  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
6366  case tok::lessequal:            Opc = BinaryOperator::LE; break;
6367  case tok::less:                 Opc = BinaryOperator::LT; break;
6368  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
6369  case tok::greater:              Opc = BinaryOperator::GT; break;
6370  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
6371  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
6372  case tok::amp:                  Opc = BinaryOperator::And; break;
6373  case tok::caret:                Opc = BinaryOperator::Xor; break;
6374  case tok::pipe:                 Opc = BinaryOperator::Or; break;
6375  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
6376  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
6377  case tok::equal:                Opc = BinaryOperator::Assign; break;
6378  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
6379  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
6380  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
6381  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
6382  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
6383  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
6384  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
6385  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
6386  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
6387  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
6388  case tok::comma:                Opc = BinaryOperator::Comma; break;
6389  }
6390  return Opc;
6391}
6392
6393static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6394  tok::TokenKind Kind) {
6395  UnaryOperator::Opcode Opc;
6396  switch (Kind) {
6397  default: assert(0 && "Unknown unary op!");
6398  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
6399  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
6400  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
6401  case tok::star:         Opc = UnaryOperator::Deref; break;
6402  case tok::plus:         Opc = UnaryOperator::Plus; break;
6403  case tok::minus:        Opc = UnaryOperator::Minus; break;
6404  case tok::tilde:        Opc = UnaryOperator::Not; break;
6405  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
6406  case tok::kw___real:    Opc = UnaryOperator::Real; break;
6407  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
6408  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6409  }
6410  return Opc;
6411}
6412
6413/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6414/// operator @p Opc at location @c TokLoc. This routine only supports
6415/// built-in operations; ActOnBinOp handles overloaded operators.
6416Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6417                                                  unsigned Op,
6418                                                  Expr *lhs, Expr *rhs) {
6419  QualType ResultTy;     // Result type of the binary operator.
6420  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
6421  // The following two variables are used for compound assignment operators
6422  QualType CompLHSTy;    // Type of LHS after promotions for computation
6423  QualType CompResultTy; // Type of computation result
6424
6425  switch (Opc) {
6426  case BinaryOperator::Assign:
6427    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6428    break;
6429  case BinaryOperator::PtrMemD:
6430  case BinaryOperator::PtrMemI:
6431    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6432                                            Opc == BinaryOperator::PtrMemI);
6433    break;
6434  case BinaryOperator::Mul:
6435  case BinaryOperator::Div:
6436    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6437                                           Opc == BinaryOperator::Div);
6438    break;
6439  case BinaryOperator::Rem:
6440    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6441    break;
6442  case BinaryOperator::Add:
6443    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6444    break;
6445  case BinaryOperator::Sub:
6446    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6447    break;
6448  case BinaryOperator::Shl:
6449  case BinaryOperator::Shr:
6450    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6451    break;
6452  case BinaryOperator::LE:
6453  case BinaryOperator::LT:
6454  case BinaryOperator::GE:
6455  case BinaryOperator::GT:
6456    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
6457    break;
6458  case BinaryOperator::EQ:
6459  case BinaryOperator::NE:
6460    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
6461    break;
6462  case BinaryOperator::And:
6463  case BinaryOperator::Xor:
6464  case BinaryOperator::Or:
6465    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6466    break;
6467  case BinaryOperator::LAnd:
6468  case BinaryOperator::LOr:
6469    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
6470    break;
6471  case BinaryOperator::MulAssign:
6472  case BinaryOperator::DivAssign:
6473    CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6474                                              Opc == BinaryOperator::DivAssign);
6475    CompLHSTy = CompResultTy;
6476    if (!CompResultTy.isNull())
6477      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6478    break;
6479  case BinaryOperator::RemAssign:
6480    CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6481    CompLHSTy = CompResultTy;
6482    if (!CompResultTy.isNull())
6483      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6484    break;
6485  case BinaryOperator::AddAssign:
6486    CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6487    if (!CompResultTy.isNull())
6488      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6489    break;
6490  case BinaryOperator::SubAssign:
6491    CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6492    if (!CompResultTy.isNull())
6493      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6494    break;
6495  case BinaryOperator::ShlAssign:
6496  case BinaryOperator::ShrAssign:
6497    CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6498    CompLHSTy = CompResultTy;
6499    if (!CompResultTy.isNull())
6500      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6501    break;
6502  case BinaryOperator::AndAssign:
6503  case BinaryOperator::XorAssign:
6504  case BinaryOperator::OrAssign:
6505    CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6506    CompLHSTy = CompResultTy;
6507    if (!CompResultTy.isNull())
6508      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6509    break;
6510  case BinaryOperator::Comma:
6511    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6512    break;
6513  }
6514  if (ResultTy.isNull())
6515    return ExprError();
6516  if (CompResultTy.isNull())
6517    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6518  else
6519    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
6520                                                      CompLHSTy, CompResultTy,
6521                                                      OpLoc));
6522}
6523
6524/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6525/// ParenRange in parentheses.
6526static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6527                               const PartialDiagnostic &PD,
6528                               const PartialDiagnostic &FirstNote,
6529                               SourceRange FirstParenRange,
6530                               const PartialDiagnostic &SecondNote,
6531                               SourceRange SecondParenRange) {
6532  Self.Diag(Loc, PD);
6533
6534  if (!FirstNote.getDiagID())
6535    return;
6536
6537  SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6538  if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6539    // We can't display the parentheses, so just return.
6540    return;
6541  }
6542
6543  Self.Diag(Loc, FirstNote)
6544    << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
6545    << FixItHint::CreateInsertion(EndLoc, ")");
6546
6547  if (!SecondNote.getDiagID())
6548    return;
6549
6550  EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6551  if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6552    // We can't display the parentheses, so just dig the
6553    // warning/error and return.
6554    Self.Diag(Loc, SecondNote);
6555    return;
6556  }
6557
6558  Self.Diag(Loc, SecondNote)
6559    << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6560    << FixItHint::CreateInsertion(EndLoc, ")");
6561}
6562
6563/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6564/// operators are mixed in a way that suggests that the programmer forgot that
6565/// comparison operators have higher precedence. The most typical example of
6566/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
6567static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6568                                      SourceLocation OpLoc,Expr *lhs,Expr *rhs){
6569  typedef BinaryOperator BinOp;
6570  BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6571                rhsopc = static_cast<BinOp::Opcode>(-1);
6572  if (BinOp *BO = dyn_cast<BinOp>(lhs))
6573    lhsopc = BO->getOpcode();
6574  if (BinOp *BO = dyn_cast<BinOp>(rhs))
6575    rhsopc = BO->getOpcode();
6576
6577  // Subs are not binary operators.
6578  if (lhsopc == -1 && rhsopc == -1)
6579    return;
6580
6581  // Bitwise operations are sometimes used as eager logical ops.
6582  // Don't diagnose this.
6583  if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6584      (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
6585    return;
6586
6587  if (BinOp::isComparisonOp(lhsopc))
6588    SuggestParentheses(Self, OpLoc,
6589      Self.PDiag(diag::warn_precedence_bitwise_rel)
6590          << SourceRange(lhs->getLocStart(), OpLoc)
6591          << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6592      Self.PDiag(diag::note_precedence_bitwise_first)
6593          << BinOp::getOpcodeStr(Opc),
6594      SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
6595      Self.PDiag(diag::note_precedence_bitwise_silence)
6596          << BinOp::getOpcodeStr(lhsopc),
6597                       lhs->getSourceRange());
6598  else if (BinOp::isComparisonOp(rhsopc))
6599    SuggestParentheses(Self, OpLoc,
6600      Self.PDiag(diag::warn_precedence_bitwise_rel)
6601          << SourceRange(OpLoc, rhs->getLocEnd())
6602          << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6603      Self.PDiag(diag::note_precedence_bitwise_first)
6604        << BinOp::getOpcodeStr(Opc),
6605      SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
6606      Self.PDiag(diag::note_precedence_bitwise_silence)
6607        << BinOp::getOpcodeStr(rhsopc),
6608                       rhs->getSourceRange());
6609}
6610
6611/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6612/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6613/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6614static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6615                                    SourceLocation OpLoc, Expr *lhs, Expr *rhs){
6616  if (BinaryOperator::isBitwiseOp(Opc))
6617    DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6618}
6619
6620// Binary Operators.  'Tok' is the token for the operator.
6621Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6622                                          tok::TokenKind Kind,
6623                                          ExprArg LHS, ExprArg RHS) {
6624  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
6625  Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
6626
6627  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6628  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
6629
6630  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6631  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6632
6633  return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6634}
6635
6636Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6637                                          BinaryOperator::Opcode Opc,
6638                                          Expr *lhs, Expr *rhs) {
6639  if (getLangOptions().CPlusPlus &&
6640      (lhs->getType()->isOverloadableType() ||
6641       rhs->getType()->isOverloadableType())) {
6642    // Find all of the overloaded operators visible from this
6643    // point. We perform both an operator-name lookup from the local
6644    // scope and an argument-dependent lookup based on the types of
6645    // the arguments.
6646    UnresolvedSet<16> Functions;
6647    OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6648    if (S && OverOp != OO_None)
6649      LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6650                                   Functions);
6651
6652    // Build the (potentially-overloaded, potentially-dependent)
6653    // binary operation.
6654    return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
6655  }
6656
6657  // Build a built-in binary operation.
6658  return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
6659}
6660
6661Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
6662                                                    unsigned OpcIn,
6663                                                    ExprArg InputArg) {
6664  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6665
6666  // FIXME: Input is modified below, but InputArg is not updated appropriately.
6667  Expr *Input = (Expr *)InputArg.get();
6668  QualType resultType;
6669  switch (Opc) {
6670  case UnaryOperator::OffsetOf:
6671    assert(false && "Invalid unary operator");
6672    break;
6673
6674  case UnaryOperator::PreInc:
6675  case UnaryOperator::PreDec:
6676  case UnaryOperator::PostInc:
6677  case UnaryOperator::PostDec:
6678    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
6679                                                Opc == UnaryOperator::PreInc ||
6680                                                Opc == UnaryOperator::PostInc,
6681                                                Opc == UnaryOperator::PreInc ||
6682                                                Opc == UnaryOperator::PreDec);
6683    break;
6684  case UnaryOperator::AddrOf:
6685    resultType = CheckAddressOfOperand(Input, OpLoc);
6686    break;
6687  case UnaryOperator::Deref:
6688    DefaultFunctionArrayLvalueConversion(Input);
6689    resultType = CheckIndirectionOperand(Input, OpLoc);
6690    break;
6691  case UnaryOperator::Plus:
6692  case UnaryOperator::Minus:
6693    UsualUnaryConversions(Input);
6694    resultType = Input->getType();
6695    if (resultType->isDependentType())
6696      break;
6697    if (resultType->isArithmeticType() || // C99 6.5.3.3p1
6698        resultType->isVectorType())
6699      break;
6700    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6701             resultType->isEnumeralType())
6702      break;
6703    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6704             Opc == UnaryOperator::Plus &&
6705             resultType->isPointerType())
6706      break;
6707
6708    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6709      << resultType << Input->getSourceRange());
6710  case UnaryOperator::Not: // bitwise complement
6711    UsualUnaryConversions(Input);
6712    resultType = Input->getType();
6713    if (resultType->isDependentType())
6714      break;
6715    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6716    if (resultType->isComplexType() || resultType->isComplexIntegerType())
6717      // C99 does not support '~' for complex conjugation.
6718      Diag(OpLoc, diag::ext_integer_complement_complex)
6719        << resultType << Input->getSourceRange();
6720    else if (!resultType->hasIntegerRepresentation())
6721      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6722        << resultType << Input->getSourceRange());
6723    break;
6724  case UnaryOperator::LNot: // logical negation
6725    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
6726    DefaultFunctionArrayLvalueConversion(Input);
6727    resultType = Input->getType();
6728    if (resultType->isDependentType())
6729      break;
6730    if (!resultType->isScalarType()) // C99 6.5.3.3p1
6731      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6732        << resultType << Input->getSourceRange());
6733    // LNot always has type int. C99 6.5.3.3p5.
6734    // In C++, it's bool. C++ 5.3.1p8
6735    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
6736    break;
6737  case UnaryOperator::Real:
6738  case UnaryOperator::Imag:
6739    resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
6740    break;
6741  case UnaryOperator::Extension:
6742    resultType = Input->getType();
6743    break;
6744  }
6745  if (resultType.isNull())
6746    return ExprError();
6747
6748  InputArg.release();
6749  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
6750}
6751
6752Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6753                                            UnaryOperator::Opcode Opc,
6754                                            ExprArg input) {
6755  Expr *Input = (Expr*)input.get();
6756  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6757      Opc != UnaryOperator::Extension) {
6758    // Find all of the overloaded operators visible from this
6759    // point. We perform both an operator-name lookup from the local
6760    // scope and an argument-dependent lookup based on the types of
6761    // the arguments.
6762    UnresolvedSet<16> Functions;
6763    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6764    if (S && OverOp != OO_None)
6765      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6766                                   Functions);
6767
6768    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6769  }
6770
6771  return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6772}
6773
6774// Unary Operators.  'Tok' is the token for the operator.
6775Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6776                                            tok::TokenKind Op, ExprArg input) {
6777  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6778}
6779
6780/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
6781Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6782                                            SourceLocation LabLoc,
6783                                            IdentifierInfo *LabelII) {
6784  // Look up the record for this label identifier.
6785  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
6786
6787  // If we haven't seen this label yet, create a forward reference. It
6788  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
6789  if (LabelDecl == 0)
6790    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
6791
6792  // Create the AST node.  The address of a label always has type 'void*'.
6793  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6794                                       Context.getPointerType(Context.VoidTy)));
6795}
6796
6797Sema::OwningExprResult
6798Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6799                    SourceLocation RPLoc) { // "({..})"
6800  Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
6801  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6802  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6803
6804  bool isFileScope
6805    = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
6806  if (isFileScope)
6807    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
6808
6809  // FIXME: there are a variety of strange constraints to enforce here, for
6810  // example, it is not possible to goto into a stmt expression apparently.
6811  // More semantic analysis is needed.
6812
6813  // If there are sub stmts in the compound stmt, take the type of the last one
6814  // as the type of the stmtexpr.
6815  QualType Ty = Context.VoidTy;
6816
6817  if (!Compound->body_empty()) {
6818    Stmt *LastStmt = Compound->body_back();
6819    // If LastStmt is a label, skip down through into the body.
6820    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6821      LastStmt = Label->getSubStmt();
6822
6823    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
6824      Ty = LastExpr->getType();
6825  }
6826
6827  // FIXME: Check that expression type is complete/non-abstract; statement
6828  // expressions are not lvalues.
6829
6830  substmt.release();
6831  return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
6832}
6833
6834Sema::OwningExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
6835                                                  TypeSourceInfo *TInfo,
6836                                                  OffsetOfComponent *CompPtr,
6837                                                  unsigned NumComponents,
6838                                                  SourceLocation RParenLoc) {
6839  QualType ArgTy = TInfo->getType();
6840  bool Dependent = ArgTy->isDependentType();
6841  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
6842
6843  // We must have at least one component that refers to the type, and the first
6844  // one is known to be a field designator.  Verify that the ArgTy represents
6845  // a struct/union/class.
6846  if (!Dependent && !ArgTy->isRecordType())
6847    return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
6848                       << ArgTy << TypeRange);
6849
6850  // Type must be complete per C99 7.17p3 because a declaring a variable
6851  // with an incomplete type would be ill-formed.
6852  if (!Dependent
6853      && RequireCompleteType(BuiltinLoc, ArgTy,
6854                             PDiag(diag::err_offsetof_incomplete_type)
6855                               << TypeRange))
6856    return ExprError();
6857
6858  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6859  // GCC extension, diagnose them.
6860  // FIXME: This diagnostic isn't actually visible because the location is in
6861  // a system header!
6862  if (NumComponents != 1)
6863    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6864      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
6865
6866  bool DidWarnAboutNonPOD = false;
6867  QualType CurrentType = ArgTy;
6868  typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
6869  llvm::SmallVector<OffsetOfNode, 4> Comps;
6870  llvm::SmallVector<Expr*, 4> Exprs;
6871  for (unsigned i = 0; i != NumComponents; ++i) {
6872    const OffsetOfComponent &OC = CompPtr[i];
6873    if (OC.isBrackets) {
6874      // Offset of an array sub-field.  TODO: Should we allow vector elements?
6875      if (!CurrentType->isDependentType()) {
6876        const ArrayType *AT = Context.getAsArrayType(CurrentType);
6877        if(!AT)
6878          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6879                           << CurrentType);
6880        CurrentType = AT->getElementType();
6881      } else
6882        CurrentType = Context.DependentTy;
6883
6884      // The expression must be an integral expression.
6885      // FIXME: An integral constant expression?
6886      Expr *Idx = static_cast<Expr*>(OC.U.E);
6887      if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
6888          !Idx->getType()->isIntegerType())
6889        return ExprError(Diag(Idx->getLocStart(),
6890                              diag::err_typecheck_subscript_not_integer)
6891                         << Idx->getSourceRange());
6892
6893      // Record this array index.
6894      Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
6895      Exprs.push_back(Idx);
6896      continue;
6897    }
6898
6899    // Offset of a field.
6900    if (CurrentType->isDependentType()) {
6901      // We have the offset of a field, but we can't look into the dependent
6902      // type. Just record the identifier of the field.
6903      Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
6904      CurrentType = Context.DependentTy;
6905      continue;
6906    }
6907
6908    // We need to have a complete type to look into.
6909    if (RequireCompleteType(OC.LocStart, CurrentType,
6910                            diag::err_offsetof_incomplete_type))
6911      return ExprError();
6912
6913    // Look for the designated field.
6914    const RecordType *RC = CurrentType->getAs<RecordType>();
6915    if (!RC)
6916      return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6917                       << CurrentType);
6918    RecordDecl *RD = RC->getDecl();
6919
6920    // C++ [lib.support.types]p5:
6921    //   The macro offsetof accepts a restricted set of type arguments in this
6922    //   International Standard. type shall be a POD structure or a POD union
6923    //   (clause 9).
6924    if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6925      if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6926          DiagRuntimeBehavior(BuiltinLoc,
6927                              PDiag(diag::warn_offsetof_non_pod_type)
6928                              << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6929                              << CurrentType))
6930        DidWarnAboutNonPOD = true;
6931    }
6932
6933    // Look for the field.
6934    LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6935    LookupQualifiedName(R, RD);
6936    FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
6937    if (!MemberDecl)
6938      return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6939                       << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
6940                                                              OC.LocEnd));
6941
6942    // C99 7.17p3:
6943    //   (If the specified member is a bit-field, the behavior is undefined.)
6944    //
6945    // We diagnose this as an error.
6946    if (MemberDecl->getBitWidth()) {
6947      Diag(OC.LocEnd, diag::err_offsetof_bitfield)
6948        << MemberDecl->getDeclName()
6949        << SourceRange(BuiltinLoc, RParenLoc);
6950      Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
6951      return ExprError();
6952    }
6953
6954    RecordDecl *Parent = MemberDecl->getParent();
6955    bool AnonStructUnion = Parent->isAnonymousStructOrUnion();
6956    if (AnonStructUnion) {
6957      do {
6958        Parent = cast<RecordDecl>(Parent->getParent());
6959      } while (Parent->isAnonymousStructOrUnion());
6960    }
6961
6962    // If the member was found in a base class, introduce OffsetOfNodes for
6963    // the base class indirections.
6964    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
6965                       /*DetectVirtual=*/false);
6966    if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
6967      CXXBasePath &Path = Paths.front();
6968      for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
6969           B != BEnd; ++B)
6970        Comps.push_back(OffsetOfNode(B->Base));
6971    }
6972
6973    if (AnonStructUnion) {
6974      llvm::SmallVector<FieldDecl*, 4> Path;
6975      BuildAnonymousStructUnionMemberPath(MemberDecl, Path);
6976      unsigned n = Path.size();
6977      for (int j = n - 1; j > -1; --j)
6978        Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd));
6979    } else {
6980      Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
6981    }
6982    CurrentType = MemberDecl->getType().getNonReferenceType();
6983  }
6984
6985  return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
6986                                    TInfo, Comps.data(), Comps.size(),
6987                                    Exprs.data(), Exprs.size(), RParenLoc));
6988}
6989
6990Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6991                                                  SourceLocation BuiltinLoc,
6992                                                  SourceLocation TypeLoc,
6993                                                  TypeTy *argty,
6994                                                  OffsetOfComponent *CompPtr,
6995                                                  unsigned NumComponents,
6996                                                  SourceLocation RPLoc) {
6997
6998  TypeSourceInfo *ArgTInfo;
6999  QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
7000  if (ArgTy.isNull())
7001    return ExprError();
7002
7003  if (!ArgTInfo)
7004    ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
7005
7006  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
7007                              RPLoc);
7008}
7009
7010
7011Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
7012                                                      TypeTy *arg1,TypeTy *arg2,
7013                                                      SourceLocation RPLoc) {
7014  // FIXME: Preserve type source info.
7015  QualType argT1 = GetTypeFromParser(arg1);
7016  QualType argT2 = GetTypeFromParser(arg2);
7017
7018  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
7019
7020  if (getLangOptions().CPlusPlus) {
7021    Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
7022      << SourceRange(BuiltinLoc, RPLoc);
7023    return ExprError();
7024  }
7025
7026  return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
7027                                                 argT1, argT2, RPLoc));
7028}
7029
7030Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
7031                                             ExprArg cond,
7032                                             ExprArg expr1, ExprArg expr2,
7033                                             SourceLocation RPLoc) {
7034  Expr *CondExpr = static_cast<Expr*>(cond.get());
7035  Expr *LHSExpr = static_cast<Expr*>(expr1.get());
7036  Expr *RHSExpr = static_cast<Expr*>(expr2.get());
7037
7038  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
7039
7040  QualType resType;
7041  bool ValueDependent = false;
7042  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
7043    resType = Context.DependentTy;
7044    ValueDependent = true;
7045  } else {
7046    // The conditional expression is required to be a constant expression.
7047    llvm::APSInt condEval(32);
7048    SourceLocation ExpLoc;
7049    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
7050      return ExprError(Diag(ExpLoc,
7051                       diag::err_typecheck_choose_expr_requires_constant)
7052        << CondExpr->getSourceRange());
7053
7054    // If the condition is > zero, then the AST type is the same as the LSHExpr.
7055    resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
7056    ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
7057                                             : RHSExpr->isValueDependent();
7058  }
7059
7060  cond.release(); expr1.release(); expr2.release();
7061  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
7062                                        resType, RPLoc,
7063                                        resType->isDependentType(),
7064                                        ValueDependent));
7065}
7066
7067//===----------------------------------------------------------------------===//
7068// Clang Extensions.
7069//===----------------------------------------------------------------------===//
7070
7071/// ActOnBlockStart - This callback is invoked when a block literal is started.
7072void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
7073  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
7074  PushBlockScope(BlockScope, Block);
7075  CurContext->addDecl(Block);
7076  if (BlockScope)
7077    PushDeclContext(BlockScope, Block);
7078  else
7079    CurContext = Block;
7080}
7081
7082void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
7083  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
7084  BlockScopeInfo *CurBlock = getCurBlock();
7085
7086  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
7087  CurBlock->TheDecl->setSignatureAsWritten(Sig);
7088  QualType T = Sig->getType();
7089
7090  bool isVariadic;
7091  QualType RetTy;
7092  if (const FunctionType *Fn = T->getAs<FunctionType>()) {
7093    CurBlock->FunctionType = T;
7094    RetTy = Fn->getResultType();
7095    isVariadic =
7096      !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
7097  } else {
7098    RetTy = T;
7099    isVariadic = false;
7100  }
7101
7102  CurBlock->TheDecl->setIsVariadic(isVariadic);
7103
7104  // Don't allow returning an array by value.
7105  if (RetTy->isArrayType()) {
7106    Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
7107    return;
7108  }
7109
7110  // Don't allow returning a objc interface by value.
7111  if (RetTy->isObjCObjectType()) {
7112    Diag(ParamInfo.getSourceRange().getBegin(),
7113         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
7114    return;
7115  }
7116
7117  // Context.DependentTy is used as a placeholder for a missing block
7118  // return type.  TODO:  what should we do with declarators like:
7119  //   ^ * { ... }
7120  // If the answer is "apply template argument deduction"....
7121  if (RetTy != Context.DependentTy)
7122    CurBlock->ReturnType = RetTy;
7123
7124  // Push block parameters from the declarator if we had them.
7125  llvm::SmallVector<ParmVarDecl*, 8> Params;
7126  if (isa<FunctionProtoType>(T)) {
7127    FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc());
7128    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
7129      ParmVarDecl *Param = TL.getArg(I);
7130      if (Param->getIdentifier() == 0 &&
7131          !Param->isImplicit() &&
7132          !Param->isInvalidDecl() &&
7133          !getLangOptions().CPlusPlus)
7134        Diag(Param->getLocation(), diag::err_parameter_name_omitted);
7135      Params.push_back(Param);
7136    }
7137
7138  // Fake up parameter variables if we have a typedef, like
7139  //   ^ fntype { ... }
7140  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
7141    for (FunctionProtoType::arg_type_iterator
7142           I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
7143      ParmVarDecl *Param =
7144        BuildParmVarDeclForTypedef(CurBlock->TheDecl,
7145                                   ParamInfo.getSourceRange().getBegin(),
7146                                   *I);
7147      Params.push_back(Param);
7148    }
7149  }
7150
7151  // Set the parameters on the block decl.
7152  if (!Params.empty())
7153    CurBlock->TheDecl->setParams(Params.data(), Params.size());
7154
7155  // Finally we can process decl attributes.
7156  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
7157
7158  if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
7159    Diag(ParamInfo.getAttributes()->getLoc(),
7160         diag::warn_attribute_sentinel_not_variadic) << 1;
7161    // FIXME: remove the attribute.
7162  }
7163
7164  // Put the parameter variables in scope.  We can bail out immediately
7165  // if we don't have any.
7166  if (Params.empty())
7167    return;
7168
7169  bool ShouldCheckShadow =
7170    Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
7171
7172  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
7173         E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
7174    (*AI)->setOwningFunction(CurBlock->TheDecl);
7175
7176    // If this has an identifier, add it to the scope stack.
7177    if ((*AI)->getIdentifier()) {
7178      if (ShouldCheckShadow)
7179        CheckShadow(CurBlock->TheScope, *AI);
7180
7181      PushOnScopeChains(*AI, CurBlock->TheScope);
7182    }
7183  }
7184}
7185
7186/// ActOnBlockError - If there is an error parsing a block, this callback
7187/// is invoked to pop the information about the block from the action impl.
7188void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
7189  // Pop off CurBlock, handle nested blocks.
7190  PopDeclContext();
7191  PopFunctionOrBlockScope();
7192  // FIXME: Delete the ParmVarDecl objects as well???
7193}
7194
7195/// ActOnBlockStmtExpr - This is called when the body of a block statement
7196/// literal was successfully completed.  ^(int x){...}
7197Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
7198                                                StmtArg body, Scope *CurScope) {
7199  // If blocks are disabled, emit an error.
7200  if (!LangOpts.Blocks)
7201    Diag(CaretLoc, diag::err_blocks_disable);
7202
7203  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
7204
7205  PopDeclContext();
7206
7207  QualType RetTy = Context.VoidTy;
7208  if (!BSI->ReturnType.isNull())
7209    RetTy = BSI->ReturnType;
7210
7211  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
7212  QualType BlockTy;
7213
7214  // If the user wrote a function type in some form, try to use that.
7215  if (!BSI->FunctionType.isNull()) {
7216    const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
7217
7218    FunctionType::ExtInfo Ext = FTy->getExtInfo();
7219    if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
7220
7221    // Turn protoless block types into nullary block types.
7222    if (isa<FunctionNoProtoType>(FTy)) {
7223      BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7224                                        false, false, 0, 0, Ext);
7225
7226    // Otherwise, if we don't need to change anything about the function type,
7227    // preserve its sugar structure.
7228    } else if (FTy->getResultType() == RetTy &&
7229               (!NoReturn || FTy->getNoReturnAttr())) {
7230      BlockTy = BSI->FunctionType;
7231
7232    // Otherwise, make the minimal modifications to the function type.
7233    } else {
7234      const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
7235      BlockTy = Context.getFunctionType(RetTy,
7236                                        FPT->arg_type_begin(),
7237                                        FPT->getNumArgs(),
7238                                        FPT->isVariadic(),
7239                                        /*quals*/ 0,
7240                                        FPT->hasExceptionSpec(),
7241                                        FPT->hasAnyExceptionSpec(),
7242                                        FPT->getNumExceptions(),
7243                                        FPT->exception_begin(),
7244                                        Ext);
7245    }
7246
7247  // If we don't have a function type, just build one from nothing.
7248  } else {
7249    BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7250                                      false, false, 0, 0,
7251                             FunctionType::ExtInfo(NoReturn, 0, CC_Default));
7252  }
7253
7254  // FIXME: Check that return/parameter types are complete/non-abstract
7255  DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
7256                           BSI->TheDecl->param_end());
7257  BlockTy = Context.getBlockPointerType(BlockTy);
7258
7259  // If needed, diagnose invalid gotos and switches in the block.
7260  if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
7261    DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
7262
7263  BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
7264
7265  bool Good = true;
7266  // Check goto/label use.
7267  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
7268         I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
7269    LabelStmt *L = I->second;
7270
7271    // Verify that we have no forward references left.  If so, there was a goto
7272    // or address of a label taken, but no definition of it.
7273    if (L->getSubStmt() != 0)
7274      continue;
7275
7276    // Emit error.
7277    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
7278    Good = false;
7279  }
7280  if (!Good) {
7281    PopFunctionOrBlockScope();
7282    return ExprError();
7283  }
7284
7285  // Issue any analysis-based warnings.
7286  const sema::AnalysisBasedWarnings::Policy &WP =
7287    AnalysisWarnings.getDefaultPolicy();
7288  AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
7289
7290  Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
7291                                         BSI->hasBlockDeclRefExprs);
7292  PopFunctionOrBlockScope();
7293  return Owned(Result);
7294}
7295
7296Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
7297                                        ExprArg expr, TypeTy *type,
7298                                        SourceLocation RPLoc) {
7299  QualType T = GetTypeFromParser(type);
7300  Expr *E = static_cast<Expr*>(expr.get());
7301  Expr *OrigExpr = E;
7302
7303  InitBuiltinVaListType();
7304
7305  // Get the va_list type
7306  QualType VaListType = Context.getBuiltinVaListType();
7307  if (VaListType->isArrayType()) {
7308    // Deal with implicit array decay; for example, on x86-64,
7309    // va_list is an array, but it's supposed to decay to
7310    // a pointer for va_arg.
7311    VaListType = Context.getArrayDecayedType(VaListType);
7312    // Make sure the input expression also decays appropriately.
7313    UsualUnaryConversions(E);
7314  } else {
7315    // Otherwise, the va_list argument must be an l-value because
7316    // it is modified by va_arg.
7317    if (!E->isTypeDependent() &&
7318        CheckForModifiableLvalue(E, BuiltinLoc, *this))
7319      return ExprError();
7320  }
7321
7322  if (!E->isTypeDependent() &&
7323      !Context.hasSameType(VaListType, E->getType())) {
7324    return ExprError(Diag(E->getLocStart(),
7325                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
7326      << OrigExpr->getType() << E->getSourceRange());
7327  }
7328
7329  // FIXME: Check that type is complete/non-abstract
7330  // FIXME: Warn if a non-POD type is passed in.
7331
7332  expr.release();
7333  return Owned(new (Context) VAArgExpr(BuiltinLoc, E,
7334                                       T.getNonLValueExprType(Context),
7335                                       RPLoc));
7336}
7337
7338Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
7339  // The type of __null will be int or long, depending on the size of
7340  // pointers on the target.
7341  QualType Ty;
7342  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7343    Ty = Context.IntTy;
7344  else
7345    Ty = Context.LongTy;
7346
7347  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
7348}
7349
7350static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
7351                                           Expr *SrcExpr, FixItHint &Hint) {
7352  if (!SemaRef.getLangOptions().ObjC1)
7353    return;
7354
7355  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7356  if (!PT)
7357    return;
7358
7359  // Check if the destination is of type 'id'.
7360  if (!PT->isObjCIdType()) {
7361    // Check if the destination is the 'NSString' interface.
7362    const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7363    if (!ID || !ID->getIdentifier()->isStr("NSString"))
7364      return;
7365  }
7366
7367  // Strip off any parens and casts.
7368  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7369  if (!SL || SL->isWide())
7370    return;
7371
7372  Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
7373}
7374
7375bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7376                                    SourceLocation Loc,
7377                                    QualType DstType, QualType SrcType,
7378                                    Expr *SrcExpr, AssignmentAction Action,
7379                                    bool *Complained) {
7380  if (Complained)
7381    *Complained = false;
7382
7383  // Decode the result (notice that AST's are still created for extensions).
7384  bool isInvalid = false;
7385  unsigned DiagKind;
7386  FixItHint Hint;
7387
7388  switch (ConvTy) {
7389  default: assert(0 && "Unknown conversion type");
7390  case Compatible: return false;
7391  case PointerToInt:
7392    DiagKind = diag::ext_typecheck_convert_pointer_int;
7393    break;
7394  case IntToPointer:
7395    DiagKind = diag::ext_typecheck_convert_int_pointer;
7396    break;
7397  case IncompatiblePointer:
7398    MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
7399    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7400    break;
7401  case IncompatiblePointerSign:
7402    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7403    break;
7404  case FunctionVoidPointer:
7405    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7406    break;
7407  case CompatiblePointerDiscardsQualifiers:
7408    // If the qualifiers lost were because we were applying the
7409    // (deprecated) C++ conversion from a string literal to a char*
7410    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
7411    // Ideally, this check would be performed in
7412    // CheckPointerTypesForAssignment. However, that would require a
7413    // bit of refactoring (so that the second argument is an
7414    // expression, rather than a type), which should be done as part
7415    // of a larger effort to fix CheckPointerTypesForAssignment for
7416    // C++ semantics.
7417    if (getLangOptions().CPlusPlus &&
7418        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7419      return false;
7420    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7421    break;
7422  case IncompatibleNestedPointerQualifiers:
7423    DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
7424    break;
7425  case IntToBlockPointer:
7426    DiagKind = diag::err_int_to_block_pointer;
7427    break;
7428  case IncompatibleBlockPointer:
7429    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
7430    break;
7431  case IncompatibleObjCQualifiedId:
7432    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
7433    // it can give a more specific diagnostic.
7434    DiagKind = diag::warn_incompatible_qualified_id;
7435    break;
7436  case IncompatibleVectors:
7437    DiagKind = diag::warn_incompatible_vectors;
7438    break;
7439  case Incompatible:
7440    DiagKind = diag::err_typecheck_convert_incompatible;
7441    isInvalid = true;
7442    break;
7443  }
7444
7445  QualType FirstType, SecondType;
7446  switch (Action) {
7447  case AA_Assigning:
7448  case AA_Initializing:
7449    // The destination type comes first.
7450    FirstType = DstType;
7451    SecondType = SrcType;
7452    break;
7453
7454  case AA_Returning:
7455  case AA_Passing:
7456  case AA_Converting:
7457  case AA_Sending:
7458  case AA_Casting:
7459    // The source type comes first.
7460    FirstType = SrcType;
7461    SecondType = DstType;
7462    break;
7463  }
7464
7465  Diag(Loc, DiagKind) << FirstType << SecondType << Action
7466    << SrcExpr->getSourceRange() << Hint;
7467  if (Complained)
7468    *Complained = true;
7469  return isInvalid;
7470}
7471
7472bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
7473  llvm::APSInt ICEResult;
7474  if (E->isIntegerConstantExpr(ICEResult, Context)) {
7475    if (Result)
7476      *Result = ICEResult;
7477    return false;
7478  }
7479
7480  Expr::EvalResult EvalResult;
7481
7482  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
7483      EvalResult.HasSideEffects) {
7484    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7485
7486    if (EvalResult.Diag) {
7487      // We only show the note if it's not the usual "invalid subexpression"
7488      // or if it's actually in a subexpression.
7489      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7490          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7491        Diag(EvalResult.DiagLoc, EvalResult.Diag);
7492    }
7493
7494    return true;
7495  }
7496
7497  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7498    E->getSourceRange();
7499
7500  if (EvalResult.Diag &&
7501      Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7502    Diag(EvalResult.DiagLoc, EvalResult.Diag);
7503
7504  if (Result)
7505    *Result = EvalResult.Val.getInt();
7506  return false;
7507}
7508
7509void
7510Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
7511  ExprEvalContexts.push_back(
7512        ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
7513}
7514
7515void
7516Sema::PopExpressionEvaluationContext() {
7517  // Pop the current expression evaluation context off the stack.
7518  ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7519  ExprEvalContexts.pop_back();
7520
7521  if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7522    if (Rec.PotentiallyReferenced) {
7523      // Mark any remaining declarations in the current position of the stack
7524      // as "referenced". If they were not meant to be referenced, semantic
7525      // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7526      for (PotentiallyReferencedDecls::iterator
7527             I = Rec.PotentiallyReferenced->begin(),
7528             IEnd = Rec.PotentiallyReferenced->end();
7529           I != IEnd; ++I)
7530        MarkDeclarationReferenced(I->first, I->second);
7531    }
7532
7533    if (Rec.PotentiallyDiagnosed) {
7534      // Emit any pending diagnostics.
7535      for (PotentiallyEmittedDiagnostics::iterator
7536                I = Rec.PotentiallyDiagnosed->begin(),
7537             IEnd = Rec.PotentiallyDiagnosed->end();
7538           I != IEnd; ++I)
7539        Diag(I->first, I->second);
7540    }
7541  }
7542
7543  // When are coming out of an unevaluated context, clear out any
7544  // temporaries that we may have created as part of the evaluation of
7545  // the expression in that context: they aren't relevant because they
7546  // will never be constructed.
7547  if (Rec.Context == Unevaluated &&
7548      ExprTemporaries.size() > Rec.NumTemporaries)
7549    ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7550                          ExprTemporaries.end());
7551
7552  // Destroy the popped expression evaluation record.
7553  Rec.Destroy();
7554}
7555
7556/// \brief Note that the given declaration was referenced in the source code.
7557///
7558/// This routine should be invoke whenever a given declaration is referenced
7559/// in the source code, and where that reference occurred. If this declaration
7560/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7561/// C99 6.9p3), then the declaration will be marked as used.
7562///
7563/// \param Loc the location where the declaration was referenced.
7564///
7565/// \param D the declaration that has been referenced by the source code.
7566void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7567  assert(D && "No declaration?");
7568
7569  if (D->isUsed(false))
7570    return;
7571
7572  // Mark a parameter or variable declaration "used", regardless of whether we're in a
7573  // template or not. The reason for this is that unevaluated expressions
7574  // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7575  // -Wunused-parameters)
7576  if (isa<ParmVarDecl>(D) ||
7577      (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
7578    D->setUsed(true);
7579    return;
7580  }
7581
7582  if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
7583    return;
7584
7585  // Do not mark anything as "used" within a dependent context; wait for
7586  // an instantiation.
7587  if (CurContext->isDependentContext())
7588    return;
7589
7590  switch (ExprEvalContexts.back().Context) {
7591    case Unevaluated:
7592      // We are in an expression that is not potentially evaluated; do nothing.
7593      return;
7594
7595    case PotentiallyEvaluated:
7596      // We are in a potentially-evaluated expression, so this declaration is
7597      // "used"; handle this below.
7598      break;
7599
7600    case PotentiallyPotentiallyEvaluated:
7601      // We are in an expression that may be potentially evaluated; queue this
7602      // declaration reference until we know whether the expression is
7603      // potentially evaluated.
7604      ExprEvalContexts.back().addReferencedDecl(Loc, D);
7605      return;
7606  }
7607
7608  // Note that this declaration has been used.
7609  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
7610    unsigned TypeQuals;
7611    if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7612        if (!Constructor->isUsed(false))
7613          DefineImplicitDefaultConstructor(Loc, Constructor);
7614    } else if (Constructor->isImplicit() &&
7615               Constructor->isCopyConstructor(TypeQuals)) {
7616      if (!Constructor->isUsed(false))
7617        DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7618    }
7619
7620    MarkVTableUsed(Loc, Constructor->getParent());
7621  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7622    if (Destructor->isImplicit() && !Destructor->isUsed(false))
7623      DefineImplicitDestructor(Loc, Destructor);
7624    if (Destructor->isVirtual())
7625      MarkVTableUsed(Loc, Destructor->getParent());
7626  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7627    if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7628        MethodDecl->getOverloadedOperator() == OO_Equal) {
7629      if (!MethodDecl->isUsed(false))
7630        DefineImplicitCopyAssignment(Loc, MethodDecl);
7631    } else if (MethodDecl->isVirtual())
7632      MarkVTableUsed(Loc, MethodDecl->getParent());
7633  }
7634  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
7635    // Implicit instantiation of function templates and member functions of
7636    // class templates.
7637    if (Function->isImplicitlyInstantiable()) {
7638      bool AlreadyInstantiated = false;
7639      if (FunctionTemplateSpecializationInfo *SpecInfo
7640                                = Function->getTemplateSpecializationInfo()) {
7641        if (SpecInfo->getPointOfInstantiation().isInvalid())
7642          SpecInfo->setPointOfInstantiation(Loc);
7643        else if (SpecInfo->getTemplateSpecializationKind()
7644                   == TSK_ImplicitInstantiation)
7645          AlreadyInstantiated = true;
7646      } else if (MemberSpecializationInfo *MSInfo
7647                                  = Function->getMemberSpecializationInfo()) {
7648        if (MSInfo->getPointOfInstantiation().isInvalid())
7649          MSInfo->setPointOfInstantiation(Loc);
7650        else if (MSInfo->getTemplateSpecializationKind()
7651                   == TSK_ImplicitInstantiation)
7652          AlreadyInstantiated = true;
7653      }
7654
7655      if (!AlreadyInstantiated) {
7656        if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7657            cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7658          PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7659                                                                      Loc));
7660        else
7661          PendingImplicitInstantiations.push_back(std::make_pair(Function,
7662                                                                 Loc));
7663      }
7664    }
7665
7666    // FIXME: keep track of references to static functions
7667    Function->setUsed(true);
7668
7669    return;
7670  }
7671
7672  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
7673    // Implicit instantiation of static data members of class templates.
7674    if (Var->isStaticDataMember() &&
7675        Var->getInstantiatedFromStaticDataMember()) {
7676      MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7677      assert(MSInfo && "Missing member specialization information?");
7678      if (MSInfo->getPointOfInstantiation().isInvalid() &&
7679          MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7680        MSInfo->setPointOfInstantiation(Loc);
7681        PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7682      }
7683    }
7684
7685    // FIXME: keep track of references to static data?
7686
7687    D->setUsed(true);
7688    return;
7689  }
7690}
7691
7692namespace {
7693  // Mark all of the declarations referenced
7694  // FIXME: Not fully implemented yet! We need to have a better understanding
7695  // of when we're entering
7696  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
7697    Sema &S;
7698    SourceLocation Loc;
7699
7700  public:
7701    typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
7702
7703    MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
7704
7705    bool TraverseTemplateArgument(const TemplateArgument &Arg);
7706    bool TraverseRecordType(RecordType *T);
7707  };
7708}
7709
7710bool MarkReferencedDecls::TraverseTemplateArgument(
7711  const TemplateArgument &Arg) {
7712  if (Arg.getKind() == TemplateArgument::Declaration) {
7713    S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
7714  }
7715
7716  return Inherited::TraverseTemplateArgument(Arg);
7717}
7718
7719bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
7720  if (ClassTemplateSpecializationDecl *Spec
7721                  = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
7722    const TemplateArgumentList &Args = Spec->getTemplateArgs();
7723    return TraverseTemplateArguments(Args.getFlatArgumentList(),
7724                                     Args.flat_size());
7725  }
7726
7727  return true;
7728}
7729
7730void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
7731  MarkReferencedDecls Marker(*this, Loc);
7732  Marker.TraverseType(Context.getCanonicalType(T));
7733}
7734
7735/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7736/// of the program being compiled.
7737///
7738/// This routine emits the given diagnostic when the code currently being
7739/// type-checked is "potentially evaluated", meaning that there is a
7740/// possibility that the code will actually be executable. Code in sizeof()
7741/// expressions, code used only during overload resolution, etc., are not
7742/// potentially evaluated. This routine will suppress such diagnostics or,
7743/// in the absolutely nutty case of potentially potentially evaluated
7744/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7745/// later.
7746///
7747/// This routine should be used for all diagnostics that describe the run-time
7748/// behavior of a program, such as passing a non-POD value through an ellipsis.
7749/// Failure to do so will likely result in spurious diagnostics or failures
7750/// during overload resolution or within sizeof/alignof/typeof/typeid.
7751bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7752                               const PartialDiagnostic &PD) {
7753  switch (ExprEvalContexts.back().Context ) {
7754  case Unevaluated:
7755    // The argument will never be evaluated, so don't complain.
7756    break;
7757
7758  case PotentiallyEvaluated:
7759    Diag(Loc, PD);
7760    return true;
7761
7762  case PotentiallyPotentiallyEvaluated:
7763    ExprEvalContexts.back().addDiagnostic(Loc, PD);
7764    break;
7765  }
7766
7767  return false;
7768}
7769
7770bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7771                               CallExpr *CE, FunctionDecl *FD) {
7772  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7773    return false;
7774
7775  PartialDiagnostic Note =
7776    FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7777    << FD->getDeclName() : PDiag();
7778  SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7779
7780  if (RequireCompleteType(Loc, ReturnType,
7781                          FD ?
7782                          PDiag(diag::err_call_function_incomplete_return)
7783                            << CE->getSourceRange() << FD->getDeclName() :
7784                          PDiag(diag::err_call_incomplete_return)
7785                            << CE->getSourceRange(),
7786                          std::make_pair(NoteLoc, Note)))
7787    return true;
7788
7789  return false;
7790}
7791
7792// Diagnose the common s/=/==/ typo.  Note that adding parentheses
7793// will prevent this condition from triggering, which is what we want.
7794void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7795  SourceLocation Loc;
7796
7797  unsigned diagnostic = diag::warn_condition_is_assignment;
7798
7799  if (isa<BinaryOperator>(E)) {
7800    BinaryOperator *Op = cast<BinaryOperator>(E);
7801    if (Op->getOpcode() != BinaryOperator::Assign)
7802      return;
7803
7804    // Greylist some idioms by putting them into a warning subcategory.
7805    if (ObjCMessageExpr *ME
7806          = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7807      Selector Sel = ME->getSelector();
7808
7809      // self = [<foo> init...]
7810      if (isSelfExpr(Op->getLHS())
7811          && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7812        diagnostic = diag::warn_condition_is_idiomatic_assignment;
7813
7814      // <foo> = [<bar> nextObject]
7815      else if (Sel.isUnarySelector() &&
7816               Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7817        diagnostic = diag::warn_condition_is_idiomatic_assignment;
7818    }
7819
7820    Loc = Op->getOperatorLoc();
7821  } else if (isa<CXXOperatorCallExpr>(E)) {
7822    CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7823    if (Op->getOperator() != OO_Equal)
7824      return;
7825
7826    Loc = Op->getOperatorLoc();
7827  } else {
7828    // Not an assignment.
7829    return;
7830  }
7831
7832  SourceLocation Open = E->getSourceRange().getBegin();
7833  SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
7834
7835  Diag(Loc, diagnostic) << E->getSourceRange();
7836  Diag(Loc, diag::note_condition_assign_to_comparison)
7837    << FixItHint::CreateReplacement(Loc, "==");
7838  Diag(Loc, diag::note_condition_assign_silence)
7839    << FixItHint::CreateInsertion(Open, "(")
7840    << FixItHint::CreateInsertion(Close, ")");
7841}
7842
7843bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7844  DiagnoseAssignmentAsCondition(E);
7845
7846  if (!E->isTypeDependent()) {
7847    DefaultFunctionArrayLvalueConversion(E);
7848
7849    QualType T = E->getType();
7850
7851    if (getLangOptions().CPlusPlus) {
7852      if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7853        return true;
7854    } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7855      Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7856        << T << E->getSourceRange();
7857      return true;
7858    }
7859  }
7860
7861  return false;
7862}
7863
7864Sema::OwningExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7865                                                   ExprArg SubExpr) {
7866  Expr *Sub = SubExpr.takeAs<Expr>();
7867  if (!Sub)
7868    return ExprError();
7869
7870  if (CheckBooleanCondition(Sub, Loc))
7871    return ExprError();
7872
7873  return Owned(Sub);
7874}
7875