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