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