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