SemaExpr.cpp revision b104b1f6ca76cefab25c6ecb5df3bf87a0f875d3
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 "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Designator.h"
26#include "clang/Parse/Scope.h"
27using namespace clang;
28
29
30/// DiagnoseUseOfDeprecatedDeclImpl - If the specified decl is deprecated or
31// unavailable, emit the corresponding diagnostics.
32void Sema::DiagnoseUseOfDeprecatedDeclImpl(NamedDecl *D, SourceLocation Loc) {
33  // See if the decl is deprecated.
34  if (D->getAttr<DeprecatedAttr>()) {
35    // If this reference happens *in* a deprecated function or method, don't
36    // warn.  Implementing deprecated stuff requires referencing depreated
37    // stuff.
38    NamedDecl *ND = getCurFunctionOrMethodDecl();
39    if (ND == 0 || !ND->getAttr<DeprecatedAttr>())
40      Diag(Loc, diag::warn_deprecated) << D->getDeclName();
41  }
42
43  // See if hte decl is unavailable.
44  if (D->getAttr<UnavailableAttr>())
45    Diag(Loc, diag::warn_unavailable) << D->getDeclName();
46}
47
48//===----------------------------------------------------------------------===//
49//  Standard Promotions and Conversions
50//===----------------------------------------------------------------------===//
51
52/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
53void Sema::DefaultFunctionArrayConversion(Expr *&E) {
54  QualType Ty = E->getType();
55  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
56
57  if (Ty->isFunctionType())
58    ImpCastExprToType(E, Context.getPointerType(Ty));
59  else if (Ty->isArrayType()) {
60    // In C90 mode, arrays only promote to pointers if the array expression is
61    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
62    // type 'array of type' is converted to an expression that has type 'pointer
63    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
64    // that has type 'array of type' ...".  The relevant change is "an lvalue"
65    // (C90) to "an expression" (C99).
66    //
67    // C++ 4.2p1:
68    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
69    // T" can be converted to an rvalue of type "pointer to T".
70    //
71    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
72        E->isLvalue(Context) == Expr::LV_Valid)
73      ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
74  }
75}
76
77/// UsualUnaryConversions - Performs various conversions that are common to most
78/// operators (C99 6.3). The conversions of array and function types are
79/// sometimes surpressed. For example, the array->pointer conversion doesn't
80/// apply if the array is an argument to the sizeof or address (&) operators.
81/// In these instances, this routine should *not* be called.
82Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
83  QualType Ty = Expr->getType();
84  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
85
86  if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
87    ImpCastExprToType(Expr, Context.IntTy);
88  else
89    DefaultFunctionArrayConversion(Expr);
90
91  return Expr;
92}
93
94/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
95/// do not have a prototype. Arguments that have type float are promoted to
96/// double. All other argument types are converted by UsualUnaryConversions().
97void Sema::DefaultArgumentPromotion(Expr *&Expr) {
98  QualType Ty = Expr->getType();
99  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
100
101  // If this is a 'float' (CVR qualified or typedef) promote to double.
102  if (const BuiltinType *BT = Ty->getAsBuiltinType())
103    if (BT->getKind() == BuiltinType::Float)
104      return ImpCastExprToType(Expr, Context.DoubleTy);
105
106  UsualUnaryConversions(Expr);
107}
108
109// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
110// will warn if the resulting type is not a POD type.
111void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
112  DefaultArgumentPromotion(Expr);
113
114  if (!Expr->getType()->isPODType()) {
115    Diag(Expr->getLocStart(),
116         diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
117    Expr->getType() << CT;
118  }
119}
120
121
122/// UsualArithmeticConversions - Performs various conversions that are common to
123/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
124/// routine returns the first non-arithmetic type found. The client is
125/// responsible for emitting appropriate error diagnostics.
126/// FIXME: verify the conversion rules for "complex int" are consistent with
127/// GCC.
128QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
129                                          bool isCompAssign) {
130  if (!isCompAssign) {
131    UsualUnaryConversions(lhsExpr);
132    UsualUnaryConversions(rhsExpr);
133  }
134
135  // For conversion purposes, we ignore any qualifiers.
136  // For example, "const float" and "float" are equivalent.
137  QualType lhs =
138    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
139  QualType rhs =
140    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
141
142  // If both types are identical, no conversion is needed.
143  if (lhs == rhs)
144    return lhs;
145
146  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
147  // The caller can deal with this (e.g. pointer + int).
148  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
149    return lhs;
150
151  QualType destType = UsualArithmeticConversionsType(lhs, rhs);
152  if (!isCompAssign) {
153    ImpCastExprToType(lhsExpr, destType);
154    ImpCastExprToType(rhsExpr, destType);
155  }
156  return destType;
157}
158
159QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
160  // Perform the usual unary conversions. We do this early so that
161  // integral promotions to "int" can allow us to exit early, in the
162  // lhs == rhs check. Also, for conversion purposes, we ignore any
163  // qualifiers.  For example, "const float" and "float" are
164  // equivalent.
165  if (lhs->isPromotableIntegerType())
166    lhs = Context.IntTy;
167  else
168    lhs = lhs.getUnqualifiedType();
169  if (rhs->isPromotableIntegerType())
170    rhs = Context.IntTy;
171  else
172    rhs = rhs.getUnqualifiedType();
173
174  // If both types are identical, no conversion is needed.
175  if (lhs == rhs)
176    return lhs;
177
178  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
179  // The caller can deal with this (e.g. pointer + int).
180  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
181    return lhs;
182
183  // At this point, we have two different arithmetic types.
184
185  // Handle complex types first (C99 6.3.1.8p1).
186  if (lhs->isComplexType() || rhs->isComplexType()) {
187    // if we have an integer operand, the result is the complex type.
188    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
189      // convert the rhs to the lhs complex type.
190      return lhs;
191    }
192    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
193      // convert the lhs to the rhs complex type.
194      return rhs;
195    }
196    // This handles complex/complex, complex/float, or float/complex.
197    // When both operands are complex, the shorter operand is converted to the
198    // type of the longer, and that is the type of the result. This corresponds
199    // to what is done when combining two real floating-point operands.
200    // The fun begins when size promotion occur across type domains.
201    // From H&S 6.3.4: When one operand is complex and the other is a real
202    // floating-point type, the less precise type is converted, within it's
203    // real or complex domain, to the precision of the other type. For example,
204    // when combining a "long double" with a "double _Complex", the
205    // "double _Complex" is promoted to "long double _Complex".
206    int result = Context.getFloatingTypeOrder(lhs, rhs);
207
208    if (result > 0) { // The left side is bigger, convert rhs.
209      rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
210    } else if (result < 0) { // The right side is bigger, convert lhs.
211      lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
212    }
213    // At this point, lhs and rhs have the same rank/size. Now, make sure the
214    // domains match. This is a requirement for our implementation, C99
215    // does not require this promotion.
216    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
217      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
218        return rhs;
219      } else { // handle "_Complex double, double".
220        return lhs;
221      }
222    }
223    return lhs; // The domain/size match exactly.
224  }
225  // Now handle "real" floating types (i.e. float, double, long double).
226  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
227    // if we have an integer operand, the result is the real floating type.
228    if (rhs->isIntegerType()) {
229      // convert rhs to the lhs floating point type.
230      return lhs;
231    }
232    if (rhs->isComplexIntegerType()) {
233      // convert rhs to the complex floating point type.
234      return Context.getComplexType(lhs);
235    }
236    if (lhs->isIntegerType()) {
237      // convert lhs to the rhs floating point type.
238      return rhs;
239    }
240    if (lhs->isComplexIntegerType()) {
241      // convert lhs to the complex floating point type.
242      return Context.getComplexType(rhs);
243    }
244    // We have two real floating types, float/complex combos were handled above.
245    // Convert the smaller operand to the bigger result.
246    int result = Context.getFloatingTypeOrder(lhs, rhs);
247    if (result > 0) // convert the rhs
248      return lhs;
249    assert(result < 0 && "illegal float comparison");
250    return rhs;   // convert the lhs
251  }
252  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
253    // Handle GCC complex int extension.
254    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
255    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
256
257    if (lhsComplexInt && rhsComplexInt) {
258      if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
259                                      rhsComplexInt->getElementType()) >= 0)
260        return lhs; // convert the rhs
261      return rhs;
262    } else if (lhsComplexInt && rhs->isIntegerType()) {
263      // convert the rhs to the lhs complex type.
264      return lhs;
265    } else if (rhsComplexInt && lhs->isIntegerType()) {
266      // convert the lhs to the rhs complex type.
267      return rhs;
268    }
269  }
270  // Finally, we have two differing integer types.
271  // The rules for this case are in C99 6.3.1.8
272  int compare = Context.getIntegerTypeOrder(lhs, rhs);
273  bool lhsSigned = lhs->isSignedIntegerType(),
274       rhsSigned = rhs->isSignedIntegerType();
275  QualType destType;
276  if (lhsSigned == rhsSigned) {
277    // Same signedness; use the higher-ranked type
278    destType = compare >= 0 ? lhs : rhs;
279  } else if (compare != (lhsSigned ? 1 : -1)) {
280    // The unsigned type has greater than or equal rank to the
281    // signed type, so use the unsigned type
282    destType = lhsSigned ? rhs : lhs;
283  } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
284    // The two types are different widths; if we are here, that
285    // means the signed type is larger than the unsigned type, so
286    // use the signed type.
287    destType = lhsSigned ? lhs : rhs;
288  } else {
289    // The signed type is higher-ranked than the unsigned type,
290    // but isn't actually any bigger (like unsigned int and long
291    // on most 32-bit systems).  Use the unsigned type corresponding
292    // to the signed type.
293    destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
294  }
295  return destType;
296}
297
298//===----------------------------------------------------------------------===//
299//  Semantic Analysis for various Expression Types
300//===----------------------------------------------------------------------===//
301
302
303/// ActOnStringLiteral - The specified tokens were lexed as pasted string
304/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
305/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
306/// multiple tokens.  However, the common case is that StringToks points to one
307/// string.
308///
309Action::OwningExprResult
310Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
311  assert(NumStringToks && "Must have at least one string!");
312
313  StringLiteralParser Literal(StringToks, NumStringToks, PP);
314  if (Literal.hadError)
315    return ExprError();
316
317  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
318  for (unsigned i = 0; i != NumStringToks; ++i)
319    StringTokLocs.push_back(StringToks[i].getLocation());
320
321  QualType StrTy = Context.CharTy;
322  if (Literal.AnyWide) StrTy = Context.getWCharType();
323  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
324
325  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
326  if (getLangOptions().CPlusPlus)
327    StrTy.addConst();
328
329  // Get an array type for the string, according to C99 6.4.5.  This includes
330  // the nul terminator character as well as the string length for pascal
331  // strings.
332  StrTy = Context.getConstantArrayType(StrTy,
333                                   llvm::APInt(32, Literal.GetStringLength()+1),
334                                       ArrayType::Normal, 0);
335
336  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
337  return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
338                                 Literal.GetStringLength(),
339                                 Literal.AnyWide, StrTy,
340                                 StringToks[0].getLocation(),
341                                 StringToks[NumStringToks-1].getLocation()));
342}
343
344/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
345/// CurBlock to VD should cause it to be snapshotted (as we do for auto
346/// variables defined outside the block) or false if this is not needed (e.g.
347/// for values inside the block or for globals).
348///
349/// FIXME: This will create BlockDeclRefExprs for global variables,
350/// function references, etc which is suboptimal :) and breaks
351/// things like "integer constant expression" tests.
352static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
353                                              ValueDecl *VD) {
354  // If the value is defined inside the block, we couldn't snapshot it even if
355  // we wanted to.
356  if (CurBlock->TheDecl == VD->getDeclContext())
357    return false;
358
359  // If this is an enum constant or function, it is constant, don't snapshot.
360  if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
361    return false;
362
363  // If this is a reference to an extern, static, or global variable, no need to
364  // snapshot it.
365  // FIXME: What about 'const' variables in C++?
366  if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
367    return Var->hasLocalStorage();
368
369  return true;
370}
371
372
373
374/// ActOnIdentifierExpr - The parser read an identifier in expression context,
375/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
376/// identifier is used in a function call context.
377/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
378/// class or namespace that the identifier must be a member of.
379Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
380                                                 IdentifierInfo &II,
381                                                 bool HasTrailingLParen,
382                                                 const CXXScopeSpec *SS,
383                                                 bool isAddressOfOperand) {
384  return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
385                                  isAddressOfOperand);
386}
387
388/// BuildDeclRefExpr - Build either a DeclRefExpr or a
389/// QualifiedDeclRefExpr based on whether or not SS is a
390/// nested-name-specifier.
391DeclRefExpr *
392Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
393                       bool TypeDependent, bool ValueDependent,
394                       const CXXScopeSpec *SS) {
395  if (SS && !SS->isEmpty())
396    return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
397                       ValueDependent, SS->getRange().getBegin());
398  else
399    return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
400}
401
402/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
403/// variable corresponding to the anonymous union or struct whose type
404/// is Record.
405static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
406  assert(Record->isAnonymousStructOrUnion() &&
407         "Record must be an anonymous struct or union!");
408
409  // FIXME: Once Decls are directly linked together, this will
410  // be an O(1) operation rather than a slow walk through DeclContext's
411  // vector (which itself will be eliminated). DeclGroups might make
412  // this even better.
413  DeclContext *Ctx = Record->getDeclContext();
414  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
415                               DEnd = Ctx->decls_end();
416       D != DEnd; ++D) {
417    if (*D == Record) {
418      // The object for the anonymous struct/union directly
419      // follows its type in the list of declarations.
420      ++D;
421      assert(D != DEnd && "Missing object for anonymous record");
422      assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
423      return *D;
424    }
425  }
426
427  assert(false && "Missing object for anonymous record");
428  return 0;
429}
430
431Sema::OwningExprResult
432Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
433                                               FieldDecl *Field,
434                                               Expr *BaseObjectExpr,
435                                               SourceLocation OpLoc) {
436  assert(Field->getDeclContext()->isRecord() &&
437         cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
438         && "Field must be stored inside an anonymous struct or union");
439
440  // Construct the sequence of field member references
441  // we'll have to perform to get to the field in the anonymous
442  // union/struct. The list of members is built from the field
443  // outward, so traverse it backwards to go from an object in
444  // the current context to the field we found.
445  llvm::SmallVector<FieldDecl *, 4> AnonFields;
446  AnonFields.push_back(Field);
447  VarDecl *BaseObject = 0;
448  DeclContext *Ctx = Field->getDeclContext();
449  do {
450    RecordDecl *Record = cast<RecordDecl>(Ctx);
451    Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
452    if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
453      AnonFields.push_back(AnonField);
454    else {
455      BaseObject = cast<VarDecl>(AnonObject);
456      break;
457    }
458    Ctx = Ctx->getParent();
459  } while (Ctx->isRecord() &&
460           cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
461
462  // Build the expression that refers to the base object, from
463  // which we will build a sequence of member references to each
464  // of the anonymous union objects and, eventually, the field we
465  // found via name lookup.
466  bool BaseObjectIsPointer = false;
467  unsigned ExtraQuals = 0;
468  if (BaseObject) {
469    // BaseObject is an anonymous struct/union variable (and is,
470    // therefore, not part of another non-anonymous record).
471    if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
472    BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
473                                     SourceLocation());
474    ExtraQuals
475      = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
476  } else if (BaseObjectExpr) {
477    // The caller provided the base object expression. Determine
478    // whether its a pointer and whether it adds any qualifiers to the
479    // anonymous struct/union fields we're looking into.
480    QualType ObjectType = BaseObjectExpr->getType();
481    if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
482      BaseObjectIsPointer = true;
483      ObjectType = ObjectPtr->getPointeeType();
484    }
485    ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
486  } else {
487    // We've found a member of an anonymous struct/union that is
488    // inside a non-anonymous struct/union, so in a well-formed
489    // program our base object expression is "this".
490    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
491      if (!MD->isStatic()) {
492        QualType AnonFieldType
493          = Context.getTagDeclType(
494                     cast<RecordDecl>(AnonFields.back()->getDeclContext()));
495        QualType ThisType = Context.getTagDeclType(MD->getParent());
496        if ((Context.getCanonicalType(AnonFieldType)
497               == Context.getCanonicalType(ThisType)) ||
498            IsDerivedFrom(ThisType, AnonFieldType)) {
499          // Our base object expression is "this".
500          BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
501                                           MD->getThisType(Context));
502          BaseObjectIsPointer = true;
503        }
504      } else {
505        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
506          << Field->getDeclName());
507      }
508      ExtraQuals = MD->getTypeQualifiers();
509    }
510
511    if (!BaseObjectExpr)
512      return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
513        << Field->getDeclName());
514  }
515
516  // Build the implicit member references to the field of the
517  // anonymous struct/union.
518  Expr *Result = BaseObjectExpr;
519  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
520         FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
521       FI != FIEnd; ++FI) {
522    QualType MemberType = (*FI)->getType();
523    if (!(*FI)->isMutable()) {
524      unsigned combinedQualifiers
525        = MemberType.getCVRQualifiers() | ExtraQuals;
526      MemberType = MemberType.getQualifiedType(combinedQualifiers);
527    }
528    Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
529                                      OpLoc, MemberType);
530    BaseObjectIsPointer = false;
531    ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
532    OpLoc = SourceLocation();
533  }
534
535  return Owned(Result);
536}
537
538/// ActOnDeclarationNameExpr - The parser has read some kind of name
539/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
540/// performs lookup on that name and returns an expression that refers
541/// to that name. This routine isn't directly called from the parser,
542/// because the parser doesn't know about DeclarationName. Rather,
543/// this routine is called by ActOnIdentifierExpr,
544/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
545/// which form the DeclarationName from the corresponding syntactic
546/// forms.
547///
548/// HasTrailingLParen indicates whether this identifier is used in a
549/// function call context.  LookupCtx is only used for a C++
550/// qualified-id (foo::bar) to indicate the class or namespace that
551/// the identifier must be a member of.
552///
553/// isAddressOfOperand means that this expression is the direct operand
554/// of an address-of operator. This matters because this is the only
555/// situation where a qualified name referencing a non-static member may
556/// appear outside a member function of this class.
557Sema::OwningExprResult
558Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
559                               DeclarationName Name, bool HasTrailingLParen,
560                               const CXXScopeSpec *SS,
561                               bool isAddressOfOperand) {
562  // Could be enum-constant, value decl, instance variable, etc.
563  if (SS && SS->isInvalid())
564    return ExprError();
565  LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
566                                         false, true, Loc);
567
568  if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
569      HasTrailingLParen && Lookup.getKind() == LookupResult::NotFound) {
570    // We've seen something of the form
571    //
572    //   identifier(
573    //
574    // and we did not find any entity by the name
575    // "identifier". However, this identifier is still subject to
576    // argument-dependent lookup, so keep track of the name.
577    return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
578                                                          Context.OverloadTy,
579                                                          Loc));
580  }
581
582  NamedDecl *D = 0;
583  if (Lookup.isAmbiguous()) {
584    DiagnoseAmbiguousLookup(Lookup, Name, Loc,
585                            SS && SS->isSet() ? SS->getRange()
586                                              : SourceRange());
587    return ExprError();
588  } else
589    D = Lookup.getAsDecl();
590
591  // If this reference is in an Objective-C method, then ivar lookup happens as
592  // well.
593  IdentifierInfo *II = Name.getAsIdentifierInfo();
594  if (II && getCurMethodDecl()) {
595    // There are two cases to handle here.  1) scoped lookup could have failed,
596    // in which case we should look for an ivar.  2) scoped lookup could have
597    // found a decl, but that decl is outside the current method (i.e. a global
598    // variable).  In these two cases, we do a lookup for an ivar with this
599    // name, if the lookup suceeds, we replace it our current decl.
600    if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
601      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
602      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
603        // FIXME: This should use a new expr for a direct reference, don't turn
604        // this into Self->ivar, just return a BareIVarExpr or something.
605        IdentifierInfo &II = Context.Idents.get("self");
606        OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
607        ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
608                                  Loc, static_cast<Expr*>(SelfExpr.release()),
609                                  true, true);
610        Context.setFieldDecl(IFace, IV, MRef);
611        return Owned(MRef);
612      }
613    }
614    // Needed to implement property "super.method" notation.
615    if (D == 0 && II->isStr("super")) {
616      QualType T = Context.getPointerType(Context.getObjCInterfaceType(
617                     getCurMethodDecl()->getClassInterface()));
618      return Owned(new (Context) ObjCSuperExpr(Loc, T));
619    }
620  }
621  if (D == 0) {
622    // Otherwise, this could be an implicitly declared function reference (legal
623    // in C90, extension in C99).
624    if (HasTrailingLParen && II &&
625        !getLangOptions().CPlusPlus) // Not in C++.
626      D = ImplicitlyDefineFunction(Loc, *II, S);
627    else {
628      // If this name wasn't predeclared and if this is not a function call,
629      // diagnose the problem.
630      if (SS && !SS->isEmpty())
631        return ExprError(Diag(Loc, diag::err_typecheck_no_member)
632          << Name << SS->getRange());
633      else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
634               Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
635        return ExprError(Diag(Loc, diag::err_undeclared_use)
636          << Name.getAsString());
637      else
638        return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
639    }
640  }
641
642  // If this is an expression of the form &Class::member, don't build an
643  // implicit member ref, because we want a pointer to the member in general,
644  // not any specific instance's member.
645  if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
646    DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
647    if (D && isa<CXXRecordDecl>(DC)) {
648      QualType DType;
649      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
650        DType = FD->getType().getNonReferenceType();
651      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
652        DType = Method->getType();
653      } else if (isa<OverloadedFunctionDecl>(D)) {
654        DType = Context.OverloadTy;
655      }
656      // Could be an inner type. That's diagnosed below, so ignore it here.
657      if (!DType.isNull()) {
658        // The pointer is type- and value-dependent if it points into something
659        // dependent.
660        bool Dependent = false;
661        for (; DC; DC = DC->getParent()) {
662          // FIXME: could stop early at namespace scope.
663          if (DC->isRecord()) {
664            CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
665            if (Context.getTypeDeclType(Record)->isDependentType()) {
666              Dependent = true;
667              break;
668            }
669          }
670        }
671        return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
672      }
673    }
674  }
675
676  // We may have found a field within an anonymous union or struct
677  // (C++ [class.union]).
678  if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
679    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
680      return BuildAnonymousStructUnionMemberReference(Loc, FD);
681
682  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
683    if (!MD->isStatic()) {
684      // C++ [class.mfct.nonstatic]p2:
685      //   [...] if name lookup (3.4.1) resolves the name in the
686      //   id-expression to a nonstatic nontype member of class X or of
687      //   a base class of X, the id-expression is transformed into a
688      //   class member access expression (5.2.5) using (*this) (9.3.2)
689      //   as the postfix-expression to the left of the '.' operator.
690      DeclContext *Ctx = 0;
691      QualType MemberType;
692      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
693        Ctx = FD->getDeclContext();
694        MemberType = FD->getType();
695
696        if (const ReferenceType *RefType = MemberType->getAsReferenceType())
697          MemberType = RefType->getPointeeType();
698        else if (!FD->isMutable()) {
699          unsigned combinedQualifiers
700            = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
701          MemberType = MemberType.getQualifiedType(combinedQualifiers);
702        }
703      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
704        if (!Method->isStatic()) {
705          Ctx = Method->getParent();
706          MemberType = Method->getType();
707        }
708      } else if (OverloadedFunctionDecl *Ovl
709                   = dyn_cast<OverloadedFunctionDecl>(D)) {
710        for (OverloadedFunctionDecl::function_iterator
711               Func = Ovl->function_begin(),
712               FuncEnd = Ovl->function_end();
713             Func != FuncEnd; ++Func) {
714          if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
715            if (!DMethod->isStatic()) {
716              Ctx = Ovl->getDeclContext();
717              MemberType = Context.OverloadTy;
718              break;
719            }
720        }
721      }
722
723      if (Ctx && Ctx->isRecord()) {
724        QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
725        QualType ThisType = Context.getTagDeclType(MD->getParent());
726        if ((Context.getCanonicalType(CtxType)
727               == Context.getCanonicalType(ThisType)) ||
728            IsDerivedFrom(ThisType, CtxType)) {
729          // Build the implicit member access expression.
730          Expr *This = new (Context) CXXThisExpr(SourceLocation(),
731                                       MD->getThisType(Context));
732          return Owned(new (Context) MemberExpr(This, true, D,
733                                      SourceLocation(), MemberType));
734        }
735      }
736    }
737  }
738
739  if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
740    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
741      if (MD->isStatic())
742        // "invalid use of member 'x' in static member function"
743        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
744          << FD->getDeclName());
745    }
746
747    // Any other ways we could have found the field in a well-formed
748    // program would have been turned into implicit member expressions
749    // above.
750    return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
751      << FD->getDeclName());
752  }
753
754  if (isa<TypedefDecl>(D))
755    return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
756  if (isa<ObjCInterfaceDecl>(D))
757    return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
758  if (isa<NamespaceDecl>(D))
759    return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
760
761  // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
762  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
763    return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
764                                  false, false, SS));
765  else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
766    return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
767                                  false, false, SS));
768  ValueDecl *VD = cast<ValueDecl>(D);
769
770  // Check if referencing an identifier with __attribute__((deprecated)).
771  DiagnoseUseOfDeprecatedDecl(VD, Loc);
772
773  if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
774    if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
775      Scope *CheckS = S;
776      while (CheckS) {
777        if (CheckS->isWithinElse() &&
778            CheckS->getControlParent()->isDeclScope(Var)) {
779          if (Var->getType()->isBooleanType())
780            ExprError(Diag(Loc, diag::warn_value_always_false)
781              << Var->getDeclName());
782          else
783            ExprError(Diag(Loc, diag::warn_value_always_zero)
784              << Var->getDeclName());
785          break;
786        }
787
788        // Move up one more control parent to check again.
789        CheckS = CheckS->getControlParent();
790        if (CheckS)
791          CheckS = CheckS->getParent();
792      }
793    }
794  }
795
796  // Only create DeclRefExpr's for valid Decl's.
797  if (VD->isInvalidDecl())
798    return ExprError();
799
800  // If the identifier reference is inside a block, and it refers to a value
801  // that is outside the block, create a BlockDeclRefExpr instead of a
802  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
803  // the block is formed.
804  //
805  // We do not do this for things like enum constants, global variables, etc,
806  // as they do not get snapshotted.
807  //
808  if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
809    // The BlocksAttr indicates the variable is bound by-reference.
810    if (VD->getAttr<BlocksAttr>())
811      return Owned(new (Context) BlockDeclRefExpr(VD,
812                               VD->getType().getNonReferenceType(), Loc, true));
813
814    // Variable will be bound by-copy, make it const within the closure.
815    VD->getType().addConst();
816    return Owned(new (Context) BlockDeclRefExpr(VD,
817                             VD->getType().getNonReferenceType(), Loc, false));
818  }
819  // If this reference is not in a block or if the referenced variable is
820  // within the block, create a normal DeclRefExpr.
821
822  bool TypeDependent = false;
823  bool ValueDependent = false;
824  if (getLangOptions().CPlusPlus) {
825    // C++ [temp.dep.expr]p3:
826    //   An id-expression is type-dependent if it contains:
827    //     - an identifier that was declared with a dependent type,
828    if (VD->getType()->isDependentType())
829      TypeDependent = true;
830    //     - FIXME: a template-id that is dependent,
831    //     - a conversion-function-id that specifies a dependent type,
832    else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
833             Name.getCXXNameType()->isDependentType())
834      TypeDependent = true;
835    //     - a nested-name-specifier that contains a class-name that
836    //       names a dependent type.
837    else if (SS && !SS->isEmpty()) {
838      for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
839           DC; DC = DC->getParent()) {
840        // FIXME: could stop early at namespace scope.
841        if (DC->isRecord()) {
842          CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
843          if (Context.getTypeDeclType(Record)->isDependentType()) {
844            TypeDependent = true;
845            break;
846          }
847        }
848      }
849    }
850
851    // C++ [temp.dep.constexpr]p2:
852    //
853    //   An identifier is value-dependent if it is:
854    //     - a name declared with a dependent type,
855    if (TypeDependent)
856      ValueDependent = true;
857    //     - the name of a non-type template parameter,
858    else if (isa<NonTypeTemplateParmDecl>(VD))
859      ValueDependent = true;
860    //    - a constant with integral or enumeration type and is
861    //      initialized with an expression that is value-dependent
862    //      (FIXME!).
863  }
864
865  return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
866                                TypeDependent, ValueDependent, SS));
867}
868
869Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
870                                                 tok::TokenKind Kind) {
871  PredefinedExpr::IdentType IT;
872
873  switch (Kind) {
874  default: assert(0 && "Unknown simple primary expr!");
875  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
876  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
877  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
878  }
879
880  // Pre-defined identifiers are of type char[x], where x is the length of the
881  // string.
882  unsigned Length;
883  if (FunctionDecl *FD = getCurFunctionDecl())
884    Length = FD->getIdentifier()->getLength();
885  else if (ObjCMethodDecl *MD = getCurMethodDecl())
886    Length = MD->getSynthesizedMethodSize();
887  else {
888    Diag(Loc, diag::ext_predef_outside_function);
889    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
890    Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
891  }
892
893
894  llvm::APInt LengthI(32, Length + 1);
895  QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
896  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
897  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
898}
899
900Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
901  llvm::SmallString<16> CharBuffer;
902  CharBuffer.resize(Tok.getLength());
903  const char *ThisTokBegin = &CharBuffer[0];
904  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
905
906  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
907                            Tok.getLocation(), PP);
908  if (Literal.hadError())
909    return ExprError();
910
911  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
912
913  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
914                                              Literal.isWide(),
915                                              type, Tok.getLocation()));
916}
917
918Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
919  // Fast path for a single digit (which is quite common).  A single digit
920  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
921  if (Tok.getLength() == 1) {
922    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
923    unsigned IntSize = Context.Target.getIntWidth();
924    return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
925                    Context.IntTy, Tok.getLocation()));
926  }
927
928  llvm::SmallString<512> IntegerBuffer;
929  // Add padding so that NumericLiteralParser can overread by one character.
930  IntegerBuffer.resize(Tok.getLength()+1);
931  const char *ThisTokBegin = &IntegerBuffer[0];
932
933  // Get the spelling of the token, which eliminates trigraphs, etc.
934  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
935
936  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
937                               Tok.getLocation(), PP);
938  if (Literal.hadError)
939    return ExprError();
940
941  Expr *Res;
942
943  if (Literal.isFloatingLiteral()) {
944    QualType Ty;
945    if (Literal.isFloat)
946      Ty = Context.FloatTy;
947    else if (!Literal.isLong)
948      Ty = Context.DoubleTy;
949    else
950      Ty = Context.LongDoubleTy;
951
952    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
953
954    // isExact will be set by GetFloatValue().
955    bool isExact = false;
956    Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
957                                        &isExact, Ty, Tok.getLocation());
958
959  } else if (!Literal.isIntegerLiteral()) {
960    return ExprError();
961  } else {
962    QualType Ty;
963
964    // long long is a C99 feature.
965    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
966        Literal.isLongLong)
967      Diag(Tok.getLocation(), diag::ext_longlong);
968
969    // Get the value in the widest-possible width.
970    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
971
972    if (Literal.GetIntegerValue(ResultVal)) {
973      // If this value didn't fit into uintmax_t, warn and force to ull.
974      Diag(Tok.getLocation(), diag::warn_integer_too_large);
975      Ty = Context.UnsignedLongLongTy;
976      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
977             "long long is not intmax_t?");
978    } else {
979      // If this value fits into a ULL, try to figure out what else it fits into
980      // according to the rules of C99 6.4.4.1p5.
981
982      // Octal, Hexadecimal, and integers with a U suffix are allowed to
983      // be an unsigned int.
984      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
985
986      // Check from smallest to largest, picking the smallest type we can.
987      unsigned Width = 0;
988      if (!Literal.isLong && !Literal.isLongLong) {
989        // Are int/unsigned possibilities?
990        unsigned IntSize = Context.Target.getIntWidth();
991
992        // Does it fit in a unsigned int?
993        if (ResultVal.isIntN(IntSize)) {
994          // Does it fit in a signed int?
995          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
996            Ty = Context.IntTy;
997          else if (AllowUnsigned)
998            Ty = Context.UnsignedIntTy;
999          Width = IntSize;
1000        }
1001      }
1002
1003      // Are long/unsigned long possibilities?
1004      if (Ty.isNull() && !Literal.isLongLong) {
1005        unsigned LongSize = Context.Target.getLongWidth();
1006
1007        // Does it fit in a unsigned long?
1008        if (ResultVal.isIntN(LongSize)) {
1009          // Does it fit in a signed long?
1010          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1011            Ty = Context.LongTy;
1012          else if (AllowUnsigned)
1013            Ty = Context.UnsignedLongTy;
1014          Width = LongSize;
1015        }
1016      }
1017
1018      // Finally, check long long if needed.
1019      if (Ty.isNull()) {
1020        unsigned LongLongSize = Context.Target.getLongLongWidth();
1021
1022        // Does it fit in a unsigned long long?
1023        if (ResultVal.isIntN(LongLongSize)) {
1024          // Does it fit in a signed long long?
1025          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1026            Ty = Context.LongLongTy;
1027          else if (AllowUnsigned)
1028            Ty = Context.UnsignedLongLongTy;
1029          Width = LongLongSize;
1030        }
1031      }
1032
1033      // If we still couldn't decide a type, we probably have something that
1034      // does not fit in a signed long long, but has no U suffix.
1035      if (Ty.isNull()) {
1036        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1037        Ty = Context.UnsignedLongLongTy;
1038        Width = Context.Target.getLongLongWidth();
1039      }
1040
1041      if (ResultVal.getBitWidth() != Width)
1042        ResultVal.trunc(Width);
1043    }
1044    Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1045  }
1046
1047  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1048  if (Literal.isImaginary)
1049    Res = new (Context) ImaginaryLiteral(Res,
1050                                        Context.getComplexType(Res->getType()));
1051
1052  return Owned(Res);
1053}
1054
1055Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1056                                              SourceLocation R, ExprArg Val) {
1057  Expr *E = (Expr *)Val.release();
1058  assert((E != 0) && "ActOnParenExpr() missing expr");
1059  return Owned(new (Context) ParenExpr(L, R, E));
1060}
1061
1062/// The UsualUnaryConversions() function is *not* called by this routine.
1063/// See C99 6.3.2.1p[2-4] for more details.
1064bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1065                                     SourceLocation OpLoc,
1066                                     const SourceRange &ExprRange,
1067                                     bool isSizeof) {
1068  // C99 6.5.3.4p1:
1069  if (isa<FunctionType>(exprType)) {
1070    // alignof(function) is allowed.
1071    if (isSizeof)
1072      Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1073    return false;
1074  }
1075
1076  if (exprType->isVoidType()) {
1077    Diag(OpLoc, diag::ext_sizeof_void_type)
1078      << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1079    return false;
1080  }
1081
1082  return DiagnoseIncompleteType(OpLoc, exprType,
1083                                isSizeof ? diag::err_sizeof_incomplete_type :
1084                                           diag::err_alignof_incomplete_type,
1085                                ExprRange);
1086}
1087
1088bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1089                            const SourceRange &ExprRange) {
1090  E = E->IgnoreParens();
1091
1092  // alignof decl is always ok.
1093  if (isa<DeclRefExpr>(E))
1094    return false;
1095
1096  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1097    if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1098      if (FD->isBitField()) {
1099        Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1100        return true;
1101      }
1102      // Other fields are ok.
1103      return false;
1104    }
1105  }
1106  return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1107}
1108
1109/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1110/// the same for @c alignof and @c __alignof
1111/// Note that the ArgRange is invalid if isType is false.
1112Action::OwningExprResult
1113Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1114                             void *TyOrEx, const SourceRange &ArgRange) {
1115  // If error parsing type, ignore.
1116  if (TyOrEx == 0) return ExprError();
1117
1118  QualType ArgTy;
1119  SourceRange Range;
1120  if (isType) {
1121    ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1122    Range = ArgRange;
1123
1124    // Verify that the operand is valid.
1125    if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1126      return ExprError();
1127  } else {
1128    // Get the end location.
1129    Expr *ArgEx = (Expr *)TyOrEx;
1130    Range = ArgEx->getSourceRange();
1131    ArgTy = ArgEx->getType();
1132
1133    // Verify that the operand is valid.
1134    bool isInvalid;
1135    if (!isSizeof) {
1136      isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
1137    } else if (ArgEx->isBitField()) {  // C99 6.5.3.4p1.
1138      Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1139      isInvalid = true;
1140    } else {
1141      isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1142    }
1143
1144    if (isInvalid) {
1145      DeleteExpr(ArgEx);
1146      return ExprError();
1147    }
1148  }
1149
1150  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1151  return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
1152                                               Context.getSizeType(), OpLoc,
1153                                               Range.getEnd()));
1154}
1155
1156QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
1157  DefaultFunctionArrayConversion(V);
1158
1159  // These operators return the element type of a complex type.
1160  if (const ComplexType *CT = V->getType()->getAsComplexType())
1161    return CT->getElementType();
1162
1163  // Otherwise they pass through real integer and floating point types here.
1164  if (V->getType()->isArithmeticType())
1165    return V->getType();
1166
1167  // Reject anything else.
1168  Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
1169  return QualType();
1170}
1171
1172
1173
1174Action::OwningExprResult
1175Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1176                          tok::TokenKind Kind, ExprArg Input) {
1177  Expr *Arg = (Expr *)Input.get();
1178
1179  UnaryOperator::Opcode Opc;
1180  switch (Kind) {
1181  default: assert(0 && "Unknown unary op!");
1182  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
1183  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1184  }
1185
1186  if (getLangOptions().CPlusPlus &&
1187      (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1188    // Which overloaded operator?
1189    OverloadedOperatorKind OverOp =
1190      (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1191
1192    // C++ [over.inc]p1:
1193    //
1194    //     [...] If the function is a member function with one
1195    //     parameter (which shall be of type int) or a non-member
1196    //     function with two parameters (the second of which shall be
1197    //     of type int), it defines the postfix increment operator ++
1198    //     for objects of that type. When the postfix increment is
1199    //     called as a result of using the ++ operator, the int
1200    //     argument will have value zero.
1201    Expr *Args[2] = {
1202      Arg,
1203      new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1204                          /*isSigned=*/true), Context.IntTy, SourceLocation())
1205    };
1206
1207    // Build the candidate set for overloading
1208    OverloadCandidateSet CandidateSet;
1209    if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1210      return ExprError();
1211
1212    // Perform overload resolution.
1213    OverloadCandidateSet::iterator Best;
1214    switch (BestViableFunction(CandidateSet, Best)) {
1215    case OR_Success: {
1216      // We found a built-in operator or an overloaded operator.
1217      FunctionDecl *FnDecl = Best->Function;
1218
1219      if (FnDecl) {
1220        // We matched an overloaded operator. Build a call to that
1221        // operator.
1222
1223        // Convert the arguments.
1224        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1225          if (PerformObjectArgumentInitialization(Arg, Method))
1226            return ExprError();
1227        } else {
1228          // Convert the arguments.
1229          if (PerformCopyInitialization(Arg,
1230                                        FnDecl->getParamDecl(0)->getType(),
1231                                        "passing"))
1232            return ExprError();
1233        }
1234
1235        // Determine the result type
1236        QualType ResultTy
1237          = FnDecl->getType()->getAsFunctionType()->getResultType();
1238        ResultTy = ResultTy.getNonReferenceType();
1239
1240        // Build the actual expression node.
1241        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1242                                       SourceLocation());
1243        UsualUnaryConversions(FnExpr);
1244
1245        Input.release();
1246        return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1247                                                       ResultTy, OpLoc));
1248      } else {
1249        // We matched a built-in operator. Convert the arguments, then
1250        // break out so that we will build the appropriate built-in
1251        // operator node.
1252        if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1253                                      "passing"))
1254          return ExprError();
1255
1256        break;
1257      }
1258    }
1259
1260    case OR_No_Viable_Function:
1261      // No viable function; fall through to handling this as a
1262      // built-in operator, which will produce an error message for us.
1263      break;
1264
1265    case OR_Ambiguous:
1266      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
1267          << UnaryOperator::getOpcodeStr(Opc)
1268          << Arg->getSourceRange();
1269      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1270      return ExprError();
1271    }
1272
1273    // Either we found no viable overloaded operator or we matched a
1274    // built-in operator. In either case, fall through to trying to
1275    // build a built-in operation.
1276  }
1277
1278  QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1279                                                 Opc == UnaryOperator::PostInc);
1280  if (result.isNull())
1281    return ExprError();
1282  Input.release();
1283  return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
1284}
1285
1286Action::OwningExprResult
1287Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1288                              ExprArg Idx, SourceLocation RLoc) {
1289  Expr *LHSExp = static_cast<Expr*>(Base.get()),
1290       *RHSExp = static_cast<Expr*>(Idx.get());
1291
1292  if (getLangOptions().CPlusPlus &&
1293      (LHSExp->getType()->isRecordType() ||
1294       LHSExp->getType()->isEnumeralType() ||
1295       RHSExp->getType()->isRecordType() ||
1296       RHSExp->getType()->isEnumeralType())) {
1297    // Add the appropriate overloaded operators (C++ [over.match.oper])
1298    // to the candidate set.
1299    OverloadCandidateSet CandidateSet;
1300    Expr *Args[2] = { LHSExp, RHSExp };
1301    if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1302                              SourceRange(LLoc, RLoc)))
1303      return ExprError();
1304
1305    // Perform overload resolution.
1306    OverloadCandidateSet::iterator Best;
1307    switch (BestViableFunction(CandidateSet, Best)) {
1308    case OR_Success: {
1309      // We found a built-in operator or an overloaded operator.
1310      FunctionDecl *FnDecl = Best->Function;
1311
1312      if (FnDecl) {
1313        // We matched an overloaded operator. Build a call to that
1314        // operator.
1315
1316        // Convert the arguments.
1317        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1318          if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1319              PerformCopyInitialization(RHSExp,
1320                                        FnDecl->getParamDecl(0)->getType(),
1321                                        "passing"))
1322            return ExprError();
1323        } else {
1324          // Convert the arguments.
1325          if (PerformCopyInitialization(LHSExp,
1326                                        FnDecl->getParamDecl(0)->getType(),
1327                                        "passing") ||
1328              PerformCopyInitialization(RHSExp,
1329                                        FnDecl->getParamDecl(1)->getType(),
1330                                        "passing"))
1331            return ExprError();
1332        }
1333
1334        // Determine the result type
1335        QualType ResultTy
1336          = FnDecl->getType()->getAsFunctionType()->getResultType();
1337        ResultTy = ResultTy.getNonReferenceType();
1338
1339        // Build the actual expression node.
1340        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1341                                       SourceLocation());
1342        UsualUnaryConversions(FnExpr);
1343
1344        Base.release();
1345        Idx.release();
1346        return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1347                                                       ResultTy, LLoc));
1348      } else {
1349        // We matched a built-in operator. Convert the arguments, then
1350        // break out so that we will build the appropriate built-in
1351        // operator node.
1352        if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1353                                      "passing") ||
1354            PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1355                                      "passing"))
1356          return ExprError();
1357
1358        break;
1359      }
1360    }
1361
1362    case OR_No_Viable_Function:
1363      // No viable function; fall through to handling this as a
1364      // built-in operator, which will produce an error message for us.
1365      break;
1366
1367    case OR_Ambiguous:
1368      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
1369          << "[]"
1370          << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1371      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1372      return ExprError();
1373    }
1374
1375    // Either we found no viable overloaded operator or we matched a
1376    // built-in operator. In either case, fall through to trying to
1377    // build a built-in operation.
1378  }
1379
1380  // Perform default conversions.
1381  DefaultFunctionArrayConversion(LHSExp);
1382  DefaultFunctionArrayConversion(RHSExp);
1383
1384  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1385
1386  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1387  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1388  // in the subscript position. As a result, we need to derive the array base
1389  // and index from the expression types.
1390  Expr *BaseExpr, *IndexExpr;
1391  QualType ResultType;
1392  if (const PointerType *PTy = LHSTy->getAsPointerType()) {
1393    BaseExpr = LHSExp;
1394    IndexExpr = RHSExp;
1395    // FIXME: need to deal with const...
1396    ResultType = PTy->getPointeeType();
1397  } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
1398     // Handle the uncommon case of "123[Ptr]".
1399    BaseExpr = RHSExp;
1400    IndexExpr = LHSExp;
1401    // FIXME: need to deal with const...
1402    ResultType = PTy->getPointeeType();
1403  } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1404    BaseExpr = LHSExp;    // vectors: V[123]
1405    IndexExpr = RHSExp;
1406
1407    // FIXME: need to deal with const...
1408    ResultType = VTy->getElementType();
1409  } else {
1410    return ExprError(Diag(LHSExp->getLocStart(),
1411      diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1412  }
1413  // C99 6.5.2.1p1
1414  if (!IndexExpr->getType()->isIntegerType())
1415    return ExprError(Diag(IndexExpr->getLocStart(),
1416      diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
1417
1418  // C99 6.5.2.1p1: "shall have type "pointer to *object* type".  In practice,
1419  // the following check catches trying to index a pointer to a function (e.g.
1420  // void (*)(int)) and pointers to incomplete types.  Functions are not
1421  // objects in C99.
1422  if (!ResultType->isObjectType())
1423    return ExprError(Diag(BaseExpr->getLocStart(),
1424                diag::err_typecheck_subscript_not_object)
1425      << BaseExpr->getType() << BaseExpr->getSourceRange());
1426
1427  Base.release();
1428  Idx.release();
1429  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1430                                                ResultType, RLoc));
1431}
1432
1433QualType Sema::
1434CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
1435                        IdentifierInfo &CompName, SourceLocation CompLoc) {
1436  const ExtVectorType *vecType = baseType->getAsExtVectorType();
1437
1438  // The vector accessor can't exceed the number of elements.
1439  const char *compStr = CompName.getName();
1440
1441  // This flag determines whether or not the component is one of the four
1442  // special names that indicate a subset of exactly half the elements are
1443  // to be selected.
1444  bool HalvingSwizzle = false;
1445
1446  // This flag determines whether or not CompName has an 's' char prefix,
1447  // indicating that it is a string of hex values to be used as vector indices.
1448  bool HexSwizzle = *compStr == 's';
1449
1450  // Check that we've found one of the special components, or that the component
1451  // names must come from the same set.
1452  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1453      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1454    HalvingSwizzle = true;
1455  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1456    do
1457      compStr++;
1458    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1459  } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1460    do
1461      compStr++;
1462    while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1463  }
1464
1465  if (!HalvingSwizzle && *compStr) {
1466    // We didn't get to the end of the string. This means the component names
1467    // didn't come from the same set *or* we encountered an illegal name.
1468    Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1469      << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1470    return QualType();
1471  }
1472
1473  // Ensure no component accessor exceeds the width of the vector type it
1474  // operates on.
1475  if (!HalvingSwizzle) {
1476    compStr = CompName.getName();
1477
1478    if (HexSwizzle)
1479      compStr++;
1480
1481    while (*compStr) {
1482      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1483        Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1484          << baseType << SourceRange(CompLoc);
1485        return QualType();
1486      }
1487    }
1488  }
1489
1490  // If this is a halving swizzle, verify that the base type has an even
1491  // number of elements.
1492  if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1493    Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1494      << baseType << SourceRange(CompLoc);
1495    return QualType();
1496  }
1497
1498  // The component accessor looks fine - now we need to compute the actual type.
1499  // The vector type is implied by the component accessor. For example,
1500  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1501  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1502  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1503  unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1504                                     : CompName.getLength();
1505  if (HexSwizzle)
1506    CompSize--;
1507
1508  if (CompSize == 1)
1509    return vecType->getElementType();
1510
1511  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1512  // Now look up the TypeDefDecl from the vector type. Without this,
1513  // diagostics look bad. We want extended vector types to appear built-in.
1514  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1515    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1516      return Context.getTypedefType(ExtVectorDecls[i]);
1517  }
1518  return VT; // should never get here (a typedef type should always be found).
1519}
1520
1521
1522/// constructSetterName - Return the setter name for the given
1523/// identifier, i.e. "set" + Name where the initial character of Name
1524/// has been capitalized.
1525// FIXME: Merge with same routine in Parser. But where should this
1526// live?
1527static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1528                                           const IdentifierInfo *Name) {
1529  llvm::SmallString<100> SelectorName;
1530  SelectorName = "set";
1531  SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1532  SelectorName[3] = toupper(SelectorName[3]);
1533  return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1534}
1535
1536Action::OwningExprResult
1537Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1538                               tok::TokenKind OpKind, SourceLocation MemberLoc,
1539                               IdentifierInfo &Member) {
1540  Expr *BaseExpr = static_cast<Expr *>(Base.release());
1541  assert(BaseExpr && "no record expression");
1542
1543  // Perform default conversions.
1544  DefaultFunctionArrayConversion(BaseExpr);
1545
1546  QualType BaseType = BaseExpr->getType();
1547  assert(!BaseType.isNull() && "no type for member expression");
1548
1549  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
1550  // must have pointer type, and the accessed type is the pointee.
1551  if (OpKind == tok::arrow) {
1552    if (const PointerType *PT = BaseType->getAsPointerType())
1553      BaseType = PT->getPointeeType();
1554    else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1555      return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1556                                            MemberLoc, Member));
1557    else
1558      return ExprError(Diag(MemberLoc,
1559                            diag::err_typecheck_member_reference_arrow)
1560        << BaseType << BaseExpr->getSourceRange());
1561  }
1562
1563  // Handle field access to simple records.  This also handles access to fields
1564  // of the ObjC 'id' struct.
1565  if (const RecordType *RTy = BaseType->getAsRecordType()) {
1566    RecordDecl *RDecl = RTy->getDecl();
1567    if (DiagnoseIncompleteType(OpLoc, BaseType,
1568                               diag::err_typecheck_incomplete_tag,
1569                               BaseExpr->getSourceRange()))
1570      return ExprError();
1571
1572    // The record definition is complete, now make sure the member is valid.
1573    // FIXME: Qualified name lookup for C++ is a bit more complicated
1574    // than this.
1575    LookupResult Result
1576      = LookupQualifiedName(RDecl, DeclarationName(&Member),
1577                            LookupMemberName, false);
1578
1579    NamedDecl *MemberDecl = 0;
1580    if (!Result)
1581      return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1582               << &Member << BaseExpr->getSourceRange());
1583    else if (Result.isAmbiguous()) {
1584      DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1585                              MemberLoc, BaseExpr->getSourceRange());
1586      return ExprError();
1587    } else
1588      MemberDecl = Result;
1589
1590    // If the decl being referenced had an error, return an error for this
1591    // sub-expr without emitting another error, in order to avoid cascading
1592    // error cases.
1593    if (MemberDecl->isInvalidDecl())
1594      return ExprError();
1595
1596    if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
1597      // We may have found a field within an anonymous union or struct
1598      // (C++ [class.union]).
1599      if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1600        return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1601                                                        BaseExpr, OpLoc);
1602
1603      // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1604      // FIXME: Handle address space modifiers
1605      QualType MemberType = FD->getType();
1606      if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1607        MemberType = Ref->getPointeeType();
1608      else {
1609        unsigned combinedQualifiers =
1610          MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
1611        if (FD->isMutable())
1612          combinedQualifiers &= ~QualType::Const;
1613        MemberType = MemberType.getQualifiedType(combinedQualifiers);
1614      }
1615
1616      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1617                                            MemberLoc, MemberType));
1618    } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
1619      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1620                                  Var, MemberLoc,
1621                                  Var->getType().getNonReferenceType()));
1622    else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
1623      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1624                                  MemberFn, MemberLoc, MemberFn->getType()));
1625    else if (OverloadedFunctionDecl *Ovl
1626             = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
1627      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
1628                                  MemberLoc, Context.OverloadTy));
1629    else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
1630      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
1631                                  MemberLoc, Enum->getType()));
1632    else if (isa<TypeDecl>(MemberDecl))
1633      return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1634        << DeclarationName(&Member) << int(OpKind == tok::arrow));
1635
1636    // We found a declaration kind that we didn't expect. This is a
1637    // generic error message that tells the user that she can't refer
1638    // to this member with '.' or '->'.
1639    return ExprError(Diag(MemberLoc,
1640                          diag::err_typecheck_member_reference_unknown)
1641      << DeclarationName(&Member) << int(OpKind == tok::arrow));
1642  }
1643
1644  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1645  // (*Obj).ivar.
1646  if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1647    if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
1648      // If the decl being referenced had an error, return an error for this
1649      // sub-expr without emitting another error, in order to avoid cascading
1650      // error cases.
1651      if (IV->isInvalidDecl())
1652        return ExprError();
1653
1654      ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1655                                                 MemberLoc, BaseExpr,
1656                                                 OpKind == tok::arrow);
1657      Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1658      return Owned(MRef);
1659    }
1660    return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1661                       << IFTy->getDecl()->getDeclName() << &Member
1662                       << BaseExpr->getSourceRange());
1663  }
1664
1665  // Handle Objective-C property access, which is "Obj.property" where Obj is a
1666  // pointer to a (potentially qualified) interface type.
1667  const PointerType *PTy;
1668  const ObjCInterfaceType *IFTy;
1669  if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1670      (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1671    ObjCInterfaceDecl *IFace = IFTy->getDecl();
1672
1673    // Search for a declared property first.
1674    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1675      return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1676                                           MemberLoc, BaseExpr));
1677
1678    // Check protocols on qualified interfaces.
1679    for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1680         E = IFTy->qual_end(); I != E; ++I)
1681      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1682        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1683                                             MemberLoc, BaseExpr));
1684
1685    // If that failed, look for an "implicit" property by seeing if the nullary
1686    // selector is implemented.
1687
1688    // FIXME: The logic for looking up nullary and unary selectors should be
1689    // shared with the code in ActOnInstanceMessage.
1690
1691    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1692    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1693
1694    // If this reference is in an @implementation, check for 'private' methods.
1695    if (!Getter)
1696      if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1697        if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1698          if (ObjCImplementationDecl *ImpDecl =
1699              ObjCImplementations[ClassDecl->getIdentifier()])
1700            Getter = ImpDecl->getInstanceMethod(Sel);
1701
1702    // Look through local category implementations associated with the class.
1703    if (!Getter) {
1704      for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1705        if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1706          Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1707      }
1708    }
1709    if (Getter) {
1710      // If we found a getter then this may be a valid dot-reference, we
1711      // will look for the matching setter, in case it is needed.
1712      IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1713                                                       &Member);
1714      Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1715      ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1716      if (!Setter) {
1717        // If this reference is in an @implementation, also check for 'private'
1718        // methods.
1719        if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1720          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1721            if (ObjCImplementationDecl *ImpDecl =
1722                  ObjCImplementations[ClassDecl->getIdentifier()])
1723              Setter = ImpDecl->getInstanceMethod(SetterSel);
1724      }
1725      // Look through local category implementations associated with the class.
1726      if (!Setter) {
1727        for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1728          if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1729            Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1730        }
1731      }
1732
1733      // FIXME: we must check that the setter has property type.
1734      return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1735                                      Setter, MemberLoc, BaseExpr));
1736    }
1737
1738    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1739      << &Member << BaseType);
1740  }
1741  // Handle properties on qualified "id" protocols.
1742  const ObjCQualifiedIdType *QIdTy;
1743  if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1744    // Check protocols on qualified interfaces.
1745    for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1746         E = QIdTy->qual_end(); I != E; ++I) {
1747      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1748        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1749                                             MemberLoc, BaseExpr));
1750      // Also must look for a getter name which uses property syntax.
1751      Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1752      if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1753        return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1754                        OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
1755      }
1756    }
1757
1758    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1759                       << &Member << BaseType);
1760  }
1761  // Handle 'field access' to vectors, such as 'V.xx'.
1762  if (BaseType->isExtVectorType() && OpKind == tok::period) {
1763    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1764    if (ret.isNull())
1765      return ExprError();
1766    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1767                                                    MemberLoc));
1768  }
1769
1770  return ExprError(Diag(MemberLoc,
1771                        diag::err_typecheck_member_reference_struct_union)
1772                     << BaseType << BaseExpr->getSourceRange());
1773}
1774
1775/// ConvertArgumentsForCall - Converts the arguments specified in
1776/// Args/NumArgs to the parameter types of the function FDecl with
1777/// function prototype Proto. Call is the call expression itself, and
1778/// Fn is the function expression. For a C++ member function, this
1779/// routine does not attempt to convert the object argument. Returns
1780/// true if the call is ill-formed.
1781bool
1782Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1783                              FunctionDecl *FDecl,
1784                              const FunctionTypeProto *Proto,
1785                              Expr **Args, unsigned NumArgs,
1786                              SourceLocation RParenLoc) {
1787  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1788  // assignment, to the types of the corresponding parameter, ...
1789  unsigned NumArgsInProto = Proto->getNumArgs();
1790  unsigned NumArgsToCheck = NumArgs;
1791  bool Invalid = false;
1792
1793  // If too few arguments are available (and we don't have default
1794  // arguments for the remaining parameters), don't make the call.
1795  if (NumArgs < NumArgsInProto) {
1796    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1797      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1798        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1799    // Use default arguments for missing arguments
1800    NumArgsToCheck = NumArgsInProto;
1801    Call->setNumArgs(Context, NumArgsInProto);
1802  }
1803
1804  // If too many are passed and not variadic, error on the extras and drop
1805  // them.
1806  if (NumArgs > NumArgsInProto) {
1807    if (!Proto->isVariadic()) {
1808      Diag(Args[NumArgsInProto]->getLocStart(),
1809           diag::err_typecheck_call_too_many_args)
1810        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1811        << SourceRange(Args[NumArgsInProto]->getLocStart(),
1812                       Args[NumArgs-1]->getLocEnd());
1813      // This deletes the extra arguments.
1814      Call->setNumArgs(Context, NumArgsInProto);
1815      Invalid = true;
1816    }
1817    NumArgsToCheck = NumArgsInProto;
1818  }
1819
1820  // Continue to check argument types (even if we have too few/many args).
1821  for (unsigned i = 0; i != NumArgsToCheck; i++) {
1822    QualType ProtoArgType = Proto->getArgType(i);
1823
1824    Expr *Arg;
1825    if (i < NumArgs) {
1826      Arg = Args[i];
1827
1828      // Pass the argument.
1829      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1830        return true;
1831    } else
1832      // We already type-checked the argument, so we know it works.
1833      Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
1834    QualType ArgType = Arg->getType();
1835
1836    Call->setArg(i, Arg);
1837  }
1838
1839  // If this is a variadic call, handle args passed through "...".
1840  if (Proto->isVariadic()) {
1841    VariadicCallType CallType = VariadicFunction;
1842    if (Fn->getType()->isBlockPointerType())
1843      CallType = VariadicBlock; // Block
1844    else if (isa<MemberExpr>(Fn))
1845      CallType = VariadicMethod;
1846
1847    // Promote the arguments (C99 6.5.2.2p7).
1848    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1849      Expr *Arg = Args[i];
1850      DefaultVariadicArgumentPromotion(Arg, CallType);
1851      Call->setArg(i, Arg);
1852    }
1853  }
1854
1855  return Invalid;
1856}
1857
1858/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
1859/// This provides the location of the left/right parens and a list of comma
1860/// locations.
1861Action::OwningExprResult
1862Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1863                    MultiExprArg args,
1864                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1865  unsigned NumArgs = args.size();
1866  Expr *Fn = static_cast<Expr *>(fn.release());
1867  Expr **Args = reinterpret_cast<Expr**>(args.release());
1868  assert(Fn && "no function call expression");
1869  FunctionDecl *FDecl = NULL;
1870  DeclarationName UnqualifiedName;
1871
1872  if (getLangOptions().CPlusPlus) {
1873    // Determine whether this is a dependent call inside a C++ template,
1874    // in which case we won't do any semantic analysis now.
1875    // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1876    bool Dependent = false;
1877    if (Fn->isTypeDependent())
1878      Dependent = true;
1879    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1880      Dependent = true;
1881
1882    if (Dependent)
1883      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
1884                                          Context.DependentTy, RParenLoc));
1885
1886    // Determine whether this is a call to an object (C++ [over.call.object]).
1887    if (Fn->getType()->isRecordType())
1888      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1889                                                CommaLocs, RParenLoc));
1890
1891    // Determine whether this is a call to a member function.
1892    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1893      if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1894          isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1895        return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1896                                               CommaLocs, RParenLoc));
1897  }
1898
1899  // If we're directly calling a function, get the appropriate declaration.
1900  DeclRefExpr *DRExpr = NULL;
1901  Expr *FnExpr = Fn;
1902  bool ADL = true;
1903  while (true) {
1904    if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1905      FnExpr = IcExpr->getSubExpr();
1906    else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
1907      // Parentheses around a function disable ADL
1908      // (C++0x [basic.lookup.argdep]p1).
1909      ADL = false;
1910      FnExpr = PExpr->getSubExpr();
1911    } else if (isa<UnaryOperator>(FnExpr) &&
1912               cast<UnaryOperator>(FnExpr)->getOpcode()
1913                 == UnaryOperator::AddrOf) {
1914      FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
1915    } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1916      // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1917      ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1918      break;
1919    } else if (UnresolvedFunctionNameExpr *DepName
1920                 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1921      UnqualifiedName = DepName->getName();
1922      break;
1923    } else {
1924      // Any kind of name that does not refer to a declaration (or
1925      // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1926      ADL = false;
1927      break;
1928    }
1929  }
1930
1931  OverloadedFunctionDecl *Ovl = 0;
1932  if (DRExpr) {
1933    FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1934    Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1935  }
1936
1937  if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
1938    // We don't perform ADL for implicit declarations of builtins.
1939    if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
1940      ADL = false;
1941
1942    // We don't perform ADL in C.
1943    if (!getLangOptions().CPlusPlus)
1944      ADL = false;
1945
1946    if (Ovl || ADL) {
1947      FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1948                                      UnqualifiedName, LParenLoc, Args,
1949                                      NumArgs, CommaLocs, RParenLoc, ADL);
1950      if (!FDecl)
1951        return ExprError();
1952
1953      // Update Fn to refer to the actual function selected.
1954      Expr *NewFn = 0;
1955      if (QualifiedDeclRefExpr *QDRExpr
1956            = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
1957        NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1958                                                   QDRExpr->getLocation(),
1959                                                   false, false,
1960                                          QDRExpr->getSourceRange().getBegin());
1961      else
1962        NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1963                                          Fn->getSourceRange().getBegin());
1964      Fn->Destroy(Context);
1965      Fn = NewFn;
1966    }
1967  }
1968
1969  // Promote the function operand.
1970  UsualUnaryConversions(Fn);
1971
1972  // Make the call expr early, before semantic checks.  This guarantees cleanup
1973  // of arguments and function on error.
1974  // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1975  // Destroy(), or nothing gets cleaned up.
1976  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
1977                                                               Args, NumArgs,
1978                                                               Context.BoolTy,
1979                                                               RParenLoc));
1980
1981  const FunctionType *FuncT;
1982  if (!Fn->getType()->isBlockPointerType()) {
1983    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1984    // have type pointer to function".
1985    const PointerType *PT = Fn->getType()->getAsPointerType();
1986    if (PT == 0)
1987      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1988        << Fn->getType() << Fn->getSourceRange());
1989    FuncT = PT->getPointeeType()->getAsFunctionType();
1990  } else { // This is a block call.
1991    FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1992                getAsFunctionType();
1993  }
1994  if (FuncT == 0)
1995    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1996      << Fn->getType() << Fn->getSourceRange());
1997
1998  // We know the result type of the call, set it.
1999  TheCall->setType(FuncT->getResultType().getNonReferenceType());
2000
2001  if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
2002    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2003                                RParenLoc))
2004      return ExprError();
2005  } else {
2006    assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
2007
2008    // Promote the arguments (C99 6.5.2.2p6).
2009    for (unsigned i = 0; i != NumArgs; i++) {
2010      Expr *Arg = Args[i];
2011      DefaultArgumentPromotion(Arg);
2012      TheCall->setArg(i, Arg);
2013    }
2014  }
2015
2016  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2017    if (!Method->isStatic())
2018      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2019        << Fn->getSourceRange());
2020
2021  // Do special checking on direct calls to functions.
2022  if (FDecl)
2023    return CheckFunctionCall(FDecl, TheCall.take());
2024
2025  return Owned(TheCall.take());
2026}
2027
2028Action::OwningExprResult
2029Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2030                           SourceLocation RParenLoc, ExprArg InitExpr) {
2031  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
2032  QualType literalType = QualType::getFromOpaquePtr(Ty);
2033  // FIXME: put back this assert when initializers are worked out.
2034  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
2035  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
2036
2037  if (literalType->isArrayType()) {
2038    if (literalType->isVariableArrayType())
2039      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2040        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
2041  } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2042                                    diag::err_typecheck_decl_incomplete_type,
2043                SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
2044    return ExprError();
2045
2046  if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
2047                            DeclarationName(), /*FIXME:DirectInit=*/false))
2048    return ExprError();
2049
2050  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
2051  if (isFileScope) { // 6.5.2.5p3
2052    if (CheckForConstantInitializer(literalExpr, literalType))
2053      return ExprError();
2054  }
2055  InitExpr.release();
2056  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2057                                                 literalExpr, isFileScope));
2058}
2059
2060Action::OwningExprResult
2061Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2062                    InitListDesignations &Designators,
2063                    SourceLocation RBraceLoc) {
2064  unsigned NumInit = initlist.size();
2065  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
2066
2067  // Semantic analysis for initializers is done by ActOnDeclarator() and
2068  // CheckInitializer() - it requires knowledge of the object being intialized.
2069
2070  InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
2071                                               RBraceLoc);
2072  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
2073  return Owned(E);
2074}
2075
2076/// CheckCastTypes - Check type constraints for casting between types.
2077bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
2078  UsualUnaryConversions(castExpr);
2079
2080  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2081  // type needs to be scalar.
2082  if (castType->isVoidType()) {
2083    // Cast to void allows any expr type.
2084  } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2085    // We can't check any more until template instantiation time.
2086  } else if (!castType->isScalarType() && !castType->isVectorType()) {
2087    if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2088        Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2089        (castType->isStructureType() || castType->isUnionType())) {
2090      // GCC struct/union extension: allow cast to self.
2091      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2092        << castType << castExpr->getSourceRange();
2093    } else if (castType->isUnionType()) {
2094      // GCC cast to union extension
2095      RecordDecl *RD = castType->getAsRecordType()->getDecl();
2096      RecordDecl::field_iterator Field, FieldEnd;
2097      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2098           Field != FieldEnd; ++Field) {
2099        if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2100            Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2101          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2102            << castExpr->getSourceRange();
2103          break;
2104        }
2105      }
2106      if (Field == FieldEnd)
2107        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2108          << castExpr->getType() << castExpr->getSourceRange();
2109    } else {
2110      // Reject any other conversions to non-scalar types.
2111      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
2112        << castType << castExpr->getSourceRange();
2113    }
2114  } else if (!castExpr->getType()->isScalarType() &&
2115             !castExpr->getType()->isVectorType()) {
2116    return Diag(castExpr->getLocStart(),
2117                diag::err_typecheck_expect_scalar_operand)
2118      << castExpr->getType() << castExpr->getSourceRange();
2119  } else if (castExpr->getType()->isVectorType()) {
2120    if (CheckVectorCast(TyR, castExpr->getType(), castType))
2121      return true;
2122  } else if (castType->isVectorType()) {
2123    if (CheckVectorCast(TyR, castType, castExpr->getType()))
2124      return true;
2125  }
2126  return false;
2127}
2128
2129bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
2130  assert(VectorTy->isVectorType() && "Not a vector type!");
2131
2132  if (Ty->isVectorType() || Ty->isIntegerType()) {
2133    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
2134      return Diag(R.getBegin(),
2135                  Ty->isVectorType() ?
2136                  diag::err_invalid_conversion_between_vectors :
2137                  diag::err_invalid_conversion_between_vector_and_integer)
2138        << VectorTy << Ty << R;
2139  } else
2140    return Diag(R.getBegin(),
2141                diag::err_invalid_conversion_between_vector_and_scalar)
2142      << VectorTy << Ty << R;
2143
2144  return false;
2145}
2146
2147Action::OwningExprResult
2148Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2149                    SourceLocation RParenLoc, ExprArg Op) {
2150  assert((Ty != 0) && (Op.get() != 0) &&
2151         "ActOnCastExpr(): missing type or expr");
2152
2153  Expr *castExpr = static_cast<Expr*>(Op.release());
2154  QualType castType = QualType::getFromOpaquePtr(Ty);
2155
2156  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
2157    return ExprError();
2158  return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
2159                                  LParenLoc, RParenLoc));
2160}
2161
2162/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2163/// In that case, lex = cond.
2164inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2165  Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2166  UsualUnaryConversions(cond);
2167  UsualUnaryConversions(lex);
2168  UsualUnaryConversions(rex);
2169  QualType condT = cond->getType();
2170  QualType lexT = lex->getType();
2171  QualType rexT = rex->getType();
2172
2173  // first, check the condition.
2174  if (!cond->isTypeDependent()) {
2175    if (!condT->isScalarType()) { // C99 6.5.15p2
2176      Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2177      return QualType();
2178    }
2179  }
2180
2181  // Now check the two expressions.
2182  if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2183    return Context.DependentTy;
2184
2185  // If both operands have arithmetic type, do the usual arithmetic conversions
2186  // to find a common type: C99 6.5.15p3,5.
2187  if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
2188    UsualArithmeticConversions(lex, rex);
2189    return lex->getType();
2190  }
2191
2192  // If both operands are the same structure or union type, the result is that
2193  // type.
2194  if (const RecordType *LHSRT = lexT->getAsRecordType()) {    // C99 6.5.15p3
2195    if (const RecordType *RHSRT = rexT->getAsRecordType())
2196      if (LHSRT->getDecl() == RHSRT->getDecl())
2197        // "If both the operands have structure or union type, the result has
2198        // that type."  This implies that CV qualifiers are dropped.
2199        return lexT.getUnqualifiedType();
2200  }
2201
2202  // C99 6.5.15p5: "If both operands have void type, the result has void type."
2203  // The following || allows only one side to be void (a GCC-ism).
2204  if (lexT->isVoidType() || rexT->isVoidType()) {
2205    if (!lexT->isVoidType())
2206      Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2207        << rex->getSourceRange();
2208    if (!rexT->isVoidType())
2209      Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2210        << lex->getSourceRange();
2211    ImpCastExprToType(lex, Context.VoidTy);
2212    ImpCastExprToType(rex, Context.VoidTy);
2213    return Context.VoidTy;
2214  }
2215  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2216  // the type of the other operand."
2217  if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2218       Context.isObjCObjectPointerType(lexT)) &&
2219      rex->isNullPointerConstant(Context)) {
2220    ImpCastExprToType(rex, lexT); // promote the null to a pointer.
2221    return lexT;
2222  }
2223  if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2224       Context.isObjCObjectPointerType(rexT)) &&
2225      lex->isNullPointerConstant(Context)) {
2226    ImpCastExprToType(lex, rexT); // promote the null to a pointer.
2227    return rexT;
2228  }
2229  // Handle the case where both operands are pointers before we handle null
2230  // pointer constants in case both operands are null pointer constants.
2231  if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2232    if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2233      // get the "pointed to" types
2234      QualType lhptee = LHSPT->getPointeeType();
2235      QualType rhptee = RHSPT->getPointeeType();
2236
2237      // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2238      if (lhptee->isVoidType() &&
2239          rhptee->isIncompleteOrObjectType()) {
2240        // Figure out necessary qualifiers (C99 6.5.15p6)
2241        QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
2242        QualType destType = Context.getPointerType(destPointee);
2243        ImpCastExprToType(lex, destType); // add qualifiers if necessary
2244        ImpCastExprToType(rex, destType); // promote to void*
2245        return destType;
2246      }
2247      if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
2248        QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
2249        QualType destType = Context.getPointerType(destPointee);
2250        ImpCastExprToType(lex, destType); // add qualifiers if necessary
2251        ImpCastExprToType(rex, destType); // promote to void*
2252        return destType;
2253      }
2254
2255      QualType compositeType = lexT;
2256
2257      // If either type is an Objective-C object type then check
2258      // compatibility according to Objective-C.
2259      if (Context.isObjCObjectPointerType(lexT) ||
2260          Context.isObjCObjectPointerType(rexT)) {
2261        // If both operands are interfaces and either operand can be
2262        // assigned to the other, use that type as the composite
2263        // type. This allows
2264        //   xxx ? (A*) a : (B*) b
2265        // where B is a subclass of A.
2266        //
2267        // Additionally, as for assignment, if either type is 'id'
2268        // allow silent coercion. Finally, if the types are
2269        // incompatible then make sure to use 'id' as the composite
2270        // type so the result is acceptable for sending messages to.
2271
2272        // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2273        // It could return the composite type.
2274        const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2275        const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2276        if (LHSIface && RHSIface &&
2277            Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2278          compositeType = lexT;
2279        } else if (LHSIface && RHSIface &&
2280                   Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
2281          compositeType = rexT;
2282        } else if (Context.isObjCIdStructType(lhptee) ||
2283                   Context.isObjCIdStructType(rhptee)) {
2284          compositeType = Context.getObjCIdType();
2285        } else {
2286          Diag(questionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2287               << lexT << rexT
2288               << lex->getSourceRange() << rex->getSourceRange();
2289          QualType incompatTy = Context.getObjCIdType();
2290          ImpCastExprToType(lex, incompatTy);
2291          ImpCastExprToType(rex, incompatTy);
2292          return incompatTy;
2293        }
2294      } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2295                                             rhptee.getUnqualifiedType())) {
2296        Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2297          << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
2298        // In this situation, we assume void* type. No especially good
2299        // reason, but this is what gcc does, and we do have to pick
2300        // to get a consistent AST.
2301        QualType incompatTy = Context.getPointerType(Context.VoidTy);
2302        ImpCastExprToType(lex, incompatTy);
2303        ImpCastExprToType(rex, incompatTy);
2304        return incompatTy;
2305      }
2306      // The pointer types are compatible.
2307      // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2308      // differently qualified versions of compatible types, the result type is
2309      // a pointer to an appropriately qualified version of the *composite*
2310      // type.
2311      // FIXME: Need to calculate the composite type.
2312      // FIXME: Need to add qualifiers
2313      ImpCastExprToType(lex, compositeType);
2314      ImpCastExprToType(rex, compositeType);
2315      return compositeType;
2316    }
2317  }
2318  // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2319  // evaluates to "struct objc_object *" (and is handled above when comparing
2320  // id with statically typed objects).
2321  if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2322    // GCC allows qualified id and any Objective-C type to devolve to
2323    // id. Currently localizing to here until clear this should be
2324    // part of ObjCQualifiedIdTypesAreCompatible.
2325    if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2326        (lexT->isObjCQualifiedIdType() &&
2327         Context.isObjCObjectPointerType(rexT)) ||
2328        (rexT->isObjCQualifiedIdType() &&
2329         Context.isObjCObjectPointerType(lexT))) {
2330      // FIXME: This is not the correct composite type. This only
2331      // happens to work because id can more or less be used anywhere,
2332      // however this may change the type of method sends.
2333      // FIXME: gcc adds some type-checking of the arguments and emits
2334      // (confusing) incompatible comparison warnings in some
2335      // cases. Investigate.
2336      QualType compositeType = Context.getObjCIdType();
2337      ImpCastExprToType(lex, compositeType);
2338      ImpCastExprToType(rex, compositeType);
2339      return compositeType;
2340    }
2341  }
2342
2343  // Selection between block pointer types is ok as long as they are the same.
2344  if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2345      Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2346    return lexT;
2347
2348  // Otherwise, the operands are not compatible.
2349  Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
2350    << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
2351  return QualType();
2352}
2353
2354/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
2355/// in the case of a the GNU conditional expr extension.
2356Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2357                                                  SourceLocation ColonLoc,
2358                                                  ExprArg Cond, ExprArg LHS,
2359                                                  ExprArg RHS) {
2360  Expr *CondExpr = (Expr *) Cond.get();
2361  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
2362
2363  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2364  // was the condition.
2365  bool isLHSNull = LHSExpr == 0;
2366  if (isLHSNull)
2367    LHSExpr = CondExpr;
2368
2369  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2370                                             RHSExpr, QuestionLoc);
2371  if (result.isNull())
2372    return ExprError();
2373
2374  Cond.release();
2375  LHS.release();
2376  RHS.release();
2377  return Owned(new (Context) ConditionalOperator(CondExpr,
2378                                                 isLHSNull ? 0 : LHSExpr,
2379                                                 RHSExpr, result));
2380}
2381
2382
2383// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2384// being closely modeled after the C99 spec:-). The odd characteristic of this
2385// routine is it effectively iqnores the qualifiers on the top level pointee.
2386// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2387// FIXME: add a couple examples in this comment.
2388Sema::AssignConvertType
2389Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2390  QualType lhptee, rhptee;
2391
2392  // get the "pointed to" type (ignoring qualifiers at the top level)
2393  lhptee = lhsType->getAsPointerType()->getPointeeType();
2394  rhptee = rhsType->getAsPointerType()->getPointeeType();
2395
2396  // make sure we operate on the canonical type
2397  lhptee = Context.getCanonicalType(lhptee);
2398  rhptee = Context.getCanonicalType(rhptee);
2399
2400  AssignConvertType ConvTy = Compatible;
2401
2402  // C99 6.5.16.1p1: This following citation is common to constraints
2403  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2404  // qualifiers of the type *pointed to* by the right;
2405  // FIXME: Handle ASQualType
2406  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
2407    ConvTy = CompatiblePointerDiscardsQualifiers;
2408
2409  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2410  // incomplete type and the other is a pointer to a qualified or unqualified
2411  // version of void...
2412  if (lhptee->isVoidType()) {
2413    if (rhptee->isIncompleteOrObjectType())
2414      return ConvTy;
2415
2416    // As an extension, we allow cast to/from void* to function pointer.
2417    assert(rhptee->isFunctionType());
2418    return FunctionVoidPointer;
2419  }
2420
2421  if (rhptee->isVoidType()) {
2422    if (lhptee->isIncompleteOrObjectType())
2423      return ConvTy;
2424
2425    // As an extension, we allow cast to/from void* to function pointer.
2426    assert(lhptee->isFunctionType());
2427    return FunctionVoidPointer;
2428  }
2429
2430  // Check for ObjC interfaces
2431  const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2432  const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2433  if (LHSIface && RHSIface &&
2434      Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2435    return ConvTy;
2436
2437  // ID acts sort of like void* for ObjC interfaces
2438  if (LHSIface && Context.isObjCIdStructType(rhptee))
2439    return ConvTy;
2440  if (RHSIface && Context.isObjCIdStructType(lhptee))
2441    return ConvTy;
2442
2443  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2444  // unqualified versions of compatible types, ...
2445  if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2446                                  rhptee.getUnqualifiedType()))
2447    return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
2448  return ConvTy;
2449}
2450
2451/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2452/// block pointer types are compatible or whether a block and normal pointer
2453/// are compatible. It is more restrict than comparing two function pointer
2454// types.
2455Sema::AssignConvertType
2456Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2457                                          QualType rhsType) {
2458  QualType lhptee, rhptee;
2459
2460  // get the "pointed to" type (ignoring qualifiers at the top level)
2461  lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2462  rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2463
2464  // make sure we operate on the canonical type
2465  lhptee = Context.getCanonicalType(lhptee);
2466  rhptee = Context.getCanonicalType(rhptee);
2467
2468  AssignConvertType ConvTy = Compatible;
2469
2470  // For blocks we enforce that qualifiers are identical.
2471  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2472    ConvTy = CompatiblePointerDiscardsQualifiers;
2473
2474  if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2475    return IncompatibleBlockPointer;
2476  return ConvTy;
2477}
2478
2479/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2480/// has code to accommodate several GCC extensions when type checking
2481/// pointers. Here are some objectionable examples that GCC considers warnings:
2482///
2483///  int a, *pint;
2484///  short *pshort;
2485///  struct foo *pfoo;
2486///
2487///  pint = pshort; // warning: assignment from incompatible pointer type
2488///  a = pint; // warning: assignment makes integer from pointer without a cast
2489///  pint = a; // warning: assignment makes pointer from integer without a cast
2490///  pint = pfoo; // warning: assignment from incompatible pointer type
2491///
2492/// As a result, the code for dealing with pointers is more complex than the
2493/// C99 spec dictates.
2494///
2495Sema::AssignConvertType
2496Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
2497  // Get canonical types.  We're not formatting these types, just comparing
2498  // them.
2499  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2500  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
2501
2502  if (lhsType == rhsType)
2503    return Compatible; // Common case: fast path an exact match.
2504
2505  // If the left-hand side is a reference type, then we are in a
2506  // (rare!) case where we've allowed the use of references in C,
2507  // e.g., as a parameter type in a built-in function. In this case,
2508  // just make sure that the type referenced is compatible with the
2509  // right-hand side type. The caller is responsible for adjusting
2510  // lhsType so that the resulting expression does not have reference
2511  // type.
2512  if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2513    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
2514      return Compatible;
2515    return Incompatible;
2516  }
2517
2518  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2519    if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
2520      return Compatible;
2521    // Relax integer conversions like we do for pointers below.
2522    if (rhsType->isIntegerType())
2523      return IntToPointer;
2524    if (lhsType->isIntegerType())
2525      return PointerToInt;
2526    return IncompatibleObjCQualifiedId;
2527  }
2528
2529  if (lhsType->isVectorType() || rhsType->isVectorType()) {
2530    // For ExtVector, allow vector splats; float -> <n x float>
2531    if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2532      if (LV->getElementType() == rhsType)
2533        return Compatible;
2534
2535    // If we are allowing lax vector conversions, and LHS and RHS are both
2536    // vectors, the total size only needs to be the same. This is a bitcast;
2537    // no bits are changed but the result type is different.
2538    if (getLangOptions().LaxVectorConversions &&
2539        lhsType->isVectorType() && rhsType->isVectorType()) {
2540      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2541        return IncompatibleVectors;
2542    }
2543    return Incompatible;
2544  }
2545
2546  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
2547    return Compatible;
2548
2549  if (isa<PointerType>(lhsType)) {
2550    if (rhsType->isIntegerType())
2551      return IntToPointer;
2552
2553    if (isa<PointerType>(rhsType))
2554      return CheckPointerTypesForAssignment(lhsType, rhsType);
2555
2556    if (rhsType->getAsBlockPointerType()) {
2557      if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
2558        return Compatible;
2559
2560      // Treat block pointers as objects.
2561      if (getLangOptions().ObjC1 &&
2562          lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2563        return Compatible;
2564    }
2565    return Incompatible;
2566  }
2567
2568  if (isa<BlockPointerType>(lhsType)) {
2569    if (rhsType->isIntegerType())
2570      return IntToPointer;
2571
2572    // Treat block pointers as objects.
2573    if (getLangOptions().ObjC1 &&
2574        rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2575      return Compatible;
2576
2577    if (rhsType->isBlockPointerType())
2578      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2579
2580    if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2581      if (RHSPT->getPointeeType()->isVoidType())
2582        return Compatible;
2583    }
2584    return Incompatible;
2585  }
2586
2587  if (isa<PointerType>(rhsType)) {
2588    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
2589    if (lhsType == Context.BoolTy)
2590      return Compatible;
2591
2592    if (lhsType->isIntegerType())
2593      return PointerToInt;
2594
2595    if (isa<PointerType>(lhsType))
2596      return CheckPointerTypesForAssignment(lhsType, rhsType);
2597
2598    if (isa<BlockPointerType>(lhsType) &&
2599        rhsType->getAsPointerType()->getPointeeType()->isVoidType())
2600      return Compatible;
2601    return Incompatible;
2602  }
2603
2604  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
2605    if (Context.typesAreCompatible(lhsType, rhsType))
2606      return Compatible;
2607  }
2608  return Incompatible;
2609}
2610
2611Sema::AssignConvertType
2612Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
2613  if (getLangOptions().CPlusPlus) {
2614    if (!lhsType->isRecordType()) {
2615      // C++ 5.17p3: If the left operand is not of class type, the
2616      // expression is implicitly converted (C++ 4) to the
2617      // cv-unqualified type of the left operand.
2618      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2619                                    "assigning"))
2620        return Incompatible;
2621      else
2622        return Compatible;
2623    }
2624
2625    // FIXME: Currently, we fall through and treat C++ classes like C
2626    // structures.
2627  }
2628
2629  // C99 6.5.16.1p1: the left operand is a pointer and the right is
2630  // a null pointer constant.
2631  if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2632       lhsType->isBlockPointerType())
2633      && rExpr->isNullPointerConstant(Context)) {
2634    ImpCastExprToType(rExpr, lhsType);
2635    return Compatible;
2636  }
2637
2638  // We don't allow conversion of non-null-pointer constants to integers.
2639  if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2640    return IntToBlockPointer;
2641
2642  // This check seems unnatural, however it is necessary to ensure the proper
2643  // conversion of functions/arrays. If the conversion were done for all
2644  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
2645  // expressions that surpress this implicit conversion (&, sizeof).
2646  //
2647  // Suppress this for references: C++ 8.5.3p5.
2648  if (!lhsType->isReferenceType())
2649    DefaultFunctionArrayConversion(rExpr);
2650
2651  Sema::AssignConvertType result =
2652    CheckAssignmentConstraints(lhsType, rExpr->getType());
2653
2654  // C99 6.5.16.1p2: The value of the right operand is converted to the
2655  // type of the assignment expression.
2656  // CheckAssignmentConstraints allows the left-hand side to be a reference,
2657  // so that we can use references in built-in functions even in C.
2658  // The getNonReferenceType() call makes sure that the resulting expression
2659  // does not have reference type.
2660  if (rExpr->getType() != lhsType)
2661    ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
2662  return result;
2663}
2664
2665Sema::AssignConvertType
2666Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2667  return CheckAssignmentConstraints(lhsType, rhsType);
2668}
2669
2670QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
2671  Diag(Loc, diag::err_typecheck_invalid_operands)
2672    << lex->getType() << rex->getType()
2673    << lex->getSourceRange() << rex->getSourceRange();
2674  return QualType();
2675}
2676
2677inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
2678                                                              Expr *&rex) {
2679  // For conversion purposes, we ignore any qualifiers.
2680  // For example, "const float" and "float" are equivalent.
2681  QualType lhsType =
2682    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2683  QualType rhsType =
2684    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
2685
2686  // If the vector types are identical, return.
2687  if (lhsType == rhsType)
2688    return lhsType;
2689
2690  // Handle the case of a vector & extvector type of the same size and element
2691  // type.  It would be nice if we only had one vector type someday.
2692  if (getLangOptions().LaxVectorConversions) {
2693    // FIXME: Should we warn here?
2694    if (const VectorType *LV = lhsType->getAsVectorType()) {
2695      if (const VectorType *RV = rhsType->getAsVectorType())
2696        if (LV->getElementType() == RV->getElementType() &&
2697            LV->getNumElements() == RV->getNumElements()) {
2698          return lhsType->isExtVectorType() ? lhsType : rhsType;
2699        }
2700    }
2701  }
2702
2703  // If the lhs is an extended vector and the rhs is a scalar of the same type
2704  // or a literal, promote the rhs to the vector type.
2705  if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
2706    QualType eltType = V->getElementType();
2707
2708    if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2709        (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2710        (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
2711      ImpCastExprToType(rex, lhsType);
2712      return lhsType;
2713    }
2714  }
2715
2716  // If the rhs is an extended vector and the lhs is a scalar of the same type,
2717  // promote the lhs to the vector type.
2718  if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
2719    QualType eltType = V->getElementType();
2720
2721    if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2722        (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2723        (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
2724      ImpCastExprToType(lex, rhsType);
2725      return rhsType;
2726    }
2727  }
2728
2729  // You cannot convert between vector values of different size.
2730  Diag(Loc, diag::err_typecheck_vector_not_convertable)
2731    << lex->getType() << rex->getType()
2732    << lex->getSourceRange() << rex->getSourceRange();
2733  return QualType();
2734}
2735
2736inline QualType Sema::CheckMultiplyDivideOperands(
2737  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
2738{
2739  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2740    return CheckVectorOperands(Loc, lex, rex);
2741
2742  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2743
2744  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2745    return compType;
2746  return InvalidOperands(Loc, lex, rex);
2747}
2748
2749inline QualType Sema::CheckRemainderOperands(
2750  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
2751{
2752  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2753    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2754      return CheckVectorOperands(Loc, lex, rex);
2755    return InvalidOperands(Loc, lex, rex);
2756  }
2757
2758  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2759
2760  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2761    return compType;
2762  return InvalidOperands(Loc, lex, rex);
2763}
2764
2765inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
2766  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
2767{
2768  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2769    return CheckVectorOperands(Loc, lex, rex);
2770
2771  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2772
2773  // handle the common case first (both operands are arithmetic).
2774  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2775    return compType;
2776
2777  // Put any potential pointer into PExp
2778  Expr* PExp = lex, *IExp = rex;
2779  if (IExp->getType()->isPointerType())
2780    std::swap(PExp, IExp);
2781
2782  if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2783    if (IExp->getType()->isIntegerType()) {
2784      // Check for arithmetic on pointers to incomplete types
2785      if (!PTy->getPointeeType()->isObjectType()) {
2786        if (PTy->getPointeeType()->isVoidType()) {
2787          if (getLangOptions().CPlusPlus) {
2788            Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2789              << lex->getSourceRange() << rex->getSourceRange();
2790            return QualType();
2791          }
2792
2793          // GNU extension: arithmetic on pointer to void
2794          Diag(Loc, diag::ext_gnu_void_ptr)
2795            << lex->getSourceRange() << rex->getSourceRange();
2796        } else if (PTy->getPointeeType()->isFunctionType()) {
2797          if (getLangOptions().CPlusPlus) {
2798            Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2799              << lex->getType() << lex->getSourceRange();
2800            return QualType();
2801          }
2802
2803          // GNU extension: arithmetic on pointer to function
2804          Diag(Loc, diag::ext_gnu_ptr_func_arith)
2805            << lex->getType() << lex->getSourceRange();
2806        } else {
2807          DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2808                                 diag::err_typecheck_arithmetic_incomplete_type,
2809                                 lex->getSourceRange(), SourceRange(),
2810                                 lex->getType());
2811          return QualType();
2812        }
2813      }
2814      return PExp->getType();
2815    }
2816  }
2817
2818  return InvalidOperands(Loc, lex, rex);
2819}
2820
2821// C99 6.5.6
2822QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
2823                                        SourceLocation Loc, bool isCompAssign) {
2824  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2825    return CheckVectorOperands(Loc, lex, rex);
2826
2827  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2828
2829  // Enforce type constraints: C99 6.5.6p3.
2830
2831  // Handle the common case first (both operands are arithmetic).
2832  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2833    return compType;
2834
2835  // Either ptr - int   or   ptr - ptr.
2836  if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
2837    QualType lpointee = LHSPTy->getPointeeType();
2838
2839    // The LHS must be an object type, not incomplete, function, etc.
2840    if (!lpointee->isObjectType()) {
2841      // Handle the GNU void* extension.
2842      if (lpointee->isVoidType()) {
2843        Diag(Loc, diag::ext_gnu_void_ptr)
2844          << lex->getSourceRange() << rex->getSourceRange();
2845      } else if (lpointee->isFunctionType()) {
2846        if (getLangOptions().CPlusPlus) {
2847          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2848            << lex->getType() << lex->getSourceRange();
2849          return QualType();
2850        }
2851
2852        // GNU extension: arithmetic on pointer to function
2853        Diag(Loc, diag::ext_gnu_ptr_func_arith)
2854          << lex->getType() << lex->getSourceRange();
2855      } else {
2856        Diag(Loc, diag::err_typecheck_sub_ptr_object)
2857          << lex->getType() << lex->getSourceRange();
2858        return QualType();
2859      }
2860    }
2861
2862    // The result type of a pointer-int computation is the pointer type.
2863    if (rex->getType()->isIntegerType())
2864      return lex->getType();
2865
2866    // Handle pointer-pointer subtractions.
2867    if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
2868      QualType rpointee = RHSPTy->getPointeeType();
2869
2870      // RHS must be an object type, unless void (GNU).
2871      if (!rpointee->isObjectType()) {
2872        // Handle the GNU void* extension.
2873        if (rpointee->isVoidType()) {
2874          if (!lpointee->isVoidType())
2875            Diag(Loc, diag::ext_gnu_void_ptr)
2876              << lex->getSourceRange() << rex->getSourceRange();
2877        } else if (rpointee->isFunctionType()) {
2878          if (getLangOptions().CPlusPlus) {
2879            Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2880              << rex->getType() << rex->getSourceRange();
2881            return QualType();
2882          }
2883
2884          // GNU extension: arithmetic on pointer to function
2885          if (!lpointee->isFunctionType())
2886            Diag(Loc, diag::ext_gnu_ptr_func_arith)
2887              << lex->getType() << lex->getSourceRange();
2888        } else {
2889          Diag(Loc, diag::err_typecheck_sub_ptr_object)
2890            << rex->getType() << rex->getSourceRange();
2891          return QualType();
2892        }
2893      }
2894
2895      // Pointee types must be compatible.
2896      if (!Context.typesAreCompatible(
2897              Context.getCanonicalType(lpointee).getUnqualifiedType(),
2898              Context.getCanonicalType(rpointee).getUnqualifiedType())) {
2899        Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
2900          << lex->getType() << rex->getType()
2901          << lex->getSourceRange() << rex->getSourceRange();
2902        return QualType();
2903      }
2904
2905      return Context.getPointerDiffType();
2906    }
2907  }
2908
2909  return InvalidOperands(Loc, lex, rex);
2910}
2911
2912// C99 6.5.7
2913QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
2914                                  bool isCompAssign) {
2915  // C99 6.5.7p2: Each of the operands shall have integer type.
2916  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2917    return InvalidOperands(Loc, lex, rex);
2918
2919  // Shifts don't perform usual arithmetic conversions, they just do integer
2920  // promotions on each operand. C99 6.5.7p3
2921  if (!isCompAssign)
2922    UsualUnaryConversions(lex);
2923  UsualUnaryConversions(rex);
2924
2925  // "The type of the result is that of the promoted left operand."
2926  return lex->getType();
2927}
2928
2929// C99 6.5.8
2930QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
2931                                    bool isRelational) {
2932  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2933    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
2934
2935  // C99 6.5.8p3 / C99 6.5.9p4
2936  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2937    UsualArithmeticConversions(lex, rex);
2938  else {
2939    UsualUnaryConversions(lex);
2940    UsualUnaryConversions(rex);
2941  }
2942  QualType lType = lex->getType();
2943  QualType rType = rex->getType();
2944
2945  // For non-floating point types, check for self-comparisons of the form
2946  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
2947  // often indicate logic errors in the program.
2948  if (!lType->isFloatingType()) {
2949    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2950      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2951        if (DRL->getDecl() == DRR->getDecl())
2952          Diag(Loc, diag::warn_selfcomparison);
2953  }
2954
2955  // The result of comparisons is 'bool' in C++, 'int' in C.
2956  QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2957
2958  if (isRelational) {
2959    if (lType->isRealType() && rType->isRealType())
2960      return ResultTy;
2961  } else {
2962    // Check for comparisons of floating point operands using != and ==.
2963    if (lType->isFloatingType()) {
2964      assert (rType->isFloatingType());
2965      CheckFloatComparison(Loc,lex,rex);
2966    }
2967
2968    if (lType->isArithmeticType() && rType->isArithmeticType())
2969      return ResultTy;
2970  }
2971
2972  bool LHSIsNull = lex->isNullPointerConstant(Context);
2973  bool RHSIsNull = rex->isNullPointerConstant(Context);
2974
2975  // All of the following pointer related warnings are GCC extensions, except
2976  // when handling null pointer constants. One day, we can consider making them
2977  // errors (when -pedantic-errors is enabled).
2978  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
2979    QualType LCanPointeeTy =
2980      Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
2981    QualType RCanPointeeTy =
2982      Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
2983
2984    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
2985        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2986        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
2987                                    RCanPointeeTy.getUnqualifiedType()) &&
2988        !Context.areComparableObjCPointerTypes(lType, rType)) {
2989      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
2990        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
2991    }
2992    ImpCastExprToType(rex, lType); // promote the pointer to pointer
2993    return ResultTy;
2994  }
2995  // Handle block pointer types.
2996  if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2997    QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2998    QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2999
3000    if (!LHSIsNull && !RHSIsNull &&
3001        !Context.typesAreBlockCompatible(lpointee, rpointee)) {
3002      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3003        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3004    }
3005    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3006    return ResultTy;
3007  }
3008  // Allow block pointers to be compared with null pointer constants.
3009  if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3010      (lType->isPointerType() && rType->isBlockPointerType())) {
3011    if (!LHSIsNull && !RHSIsNull) {
3012      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3013        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3014    }
3015    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3016    return ResultTy;
3017  }
3018
3019  if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
3020    if (lType->isPointerType() || rType->isPointerType()) {
3021      const PointerType *LPT = lType->getAsPointerType();
3022      const PointerType *RPT = rType->getAsPointerType();
3023      bool LPtrToVoid = LPT ?
3024        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3025      bool RPtrToVoid = RPT ?
3026        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3027
3028      if (!LPtrToVoid && !RPtrToVoid &&
3029          !Context.typesAreCompatible(lType, rType)) {
3030        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
3031          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3032        ImpCastExprToType(rex, lType);
3033        return ResultTy;
3034      }
3035      ImpCastExprToType(rex, lType);
3036      return ResultTy;
3037    }
3038    if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3039      ImpCastExprToType(rex, lType);
3040      return ResultTy;
3041    } else {
3042      if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
3043        Diag(Loc, diag::warn_incompatible_qualified_id_operands)
3044          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3045        ImpCastExprToType(rex, lType);
3046        return ResultTy;
3047      }
3048    }
3049  }
3050  if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3051       rType->isIntegerType()) {
3052    if (!RHSIsNull)
3053      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3054        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3055    ImpCastExprToType(rex, lType); // promote the integer to pointer
3056    return ResultTy;
3057  }
3058  if (lType->isIntegerType() &&
3059      (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
3060    if (!LHSIsNull)
3061      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3062        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3063    ImpCastExprToType(lex, rType); // promote the integer to pointer
3064    return ResultTy;
3065  }
3066  // Handle block pointers.
3067  if (lType->isBlockPointerType() && rType->isIntegerType()) {
3068    if (!RHSIsNull)
3069      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3070        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3071    ImpCastExprToType(rex, lType); // promote the integer to pointer
3072    return ResultTy;
3073  }
3074  if (lType->isIntegerType() && rType->isBlockPointerType()) {
3075    if (!LHSIsNull)
3076      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3077        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3078    ImpCastExprToType(lex, rType); // promote the integer to pointer
3079    return ResultTy;
3080  }
3081  return InvalidOperands(Loc, lex, rex);
3082}
3083
3084/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3085/// operates on extended vector types.  Instead of producing an IntTy result,
3086/// like a scalar comparison, a vector comparison produces a vector of integer
3087/// types.
3088QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
3089                                          SourceLocation Loc,
3090                                          bool isRelational) {
3091  // Check to make sure we're operating on vectors of the same type and width,
3092  // Allowing one side to be a scalar of element type.
3093  QualType vType = CheckVectorOperands(Loc, lex, rex);
3094  if (vType.isNull())
3095    return vType;
3096
3097  QualType lType = lex->getType();
3098  QualType rType = rex->getType();
3099
3100  // For non-floating point types, check for self-comparisons of the form
3101  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
3102  // often indicate logic errors in the program.
3103  if (!lType->isFloatingType()) {
3104    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3105      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3106        if (DRL->getDecl() == DRR->getDecl())
3107          Diag(Loc, diag::warn_selfcomparison);
3108  }
3109
3110  // Check for comparisons of floating point operands using != and ==.
3111  if (!isRelational && lType->isFloatingType()) {
3112    assert (rType->isFloatingType());
3113    CheckFloatComparison(Loc,lex,rex);
3114  }
3115
3116  // Return the type for the comparison, which is the same as vector type for
3117  // integer vectors, or an integer type of identical size and number of
3118  // elements for floating point vectors.
3119  if (lType->isIntegerType())
3120    return lType;
3121
3122  const VectorType *VTy = lType->getAsVectorType();
3123  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
3124  if (TypeSize == Context.getTypeSize(Context.IntTy))
3125    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
3126  else if (TypeSize == Context.getTypeSize(Context.LongTy))
3127    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3128
3129  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3130         "Unhandled vector element size in vector compare");
3131  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3132}
3133
3134inline QualType Sema::CheckBitwiseOperands(
3135  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3136{
3137  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3138    return CheckVectorOperands(Loc, lex, rex);
3139
3140  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3141
3142  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3143    return compType;
3144  return InvalidOperands(Loc, lex, rex);
3145}
3146
3147inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
3148  Expr *&lex, Expr *&rex, SourceLocation Loc)
3149{
3150  UsualUnaryConversions(lex);
3151  UsualUnaryConversions(rex);
3152
3153  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
3154    return Context.IntTy;
3155  return InvalidOperands(Loc, lex, rex);
3156}
3157
3158/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3159/// is a read-only property; return true if so. A readonly property expression
3160/// depends on various declarations and thus must be treated specially.
3161///
3162static bool IsReadonlyProperty(Expr *E, Sema &S)
3163{
3164  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3165    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3166    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3167      QualType BaseType = PropExpr->getBase()->getType();
3168      if (const PointerType *PTy = BaseType->getAsPointerType())
3169        if (const ObjCInterfaceType *IFTy =
3170            PTy->getPointeeType()->getAsObjCInterfaceType())
3171          if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3172            if (S.isPropertyReadonly(PDecl, IFace))
3173              return true;
3174    }
3175  }
3176  return false;
3177}
3178
3179/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
3180/// emit an error and return true.  If so, return false.
3181static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
3182  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3183  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3184    IsLV = Expr::MLV_ReadonlyProperty;
3185  if (IsLV == Expr::MLV_Valid)
3186    return false;
3187
3188  unsigned Diag = 0;
3189  bool NeedType = false;
3190  switch (IsLV) { // C99 6.5.16p2
3191  default: assert(0 && "Unknown result from isModifiableLvalue!");
3192  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
3193  case Expr::MLV_ArrayType:
3194    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3195    NeedType = true;
3196    break;
3197  case Expr::MLV_NotObjectType:
3198    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3199    NeedType = true;
3200    break;
3201  case Expr::MLV_LValueCast:
3202    Diag = diag::err_typecheck_lvalue_casts_not_supported;
3203    break;
3204  case Expr::MLV_InvalidExpression:
3205    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3206    break;
3207  case Expr::MLV_IncompleteType:
3208  case Expr::MLV_IncompleteVoidType:
3209    return S.DiagnoseIncompleteType(Loc, E->getType(),
3210                      diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3211                                    E->getSourceRange());
3212  case Expr::MLV_DuplicateVectorComponents:
3213    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3214    break;
3215  case Expr::MLV_NotBlockQualified:
3216    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3217    break;
3218  case Expr::MLV_ReadonlyProperty:
3219    Diag = diag::error_readonly_property_assignment;
3220    break;
3221  case Expr::MLV_NoSetterProperty:
3222    Diag = diag::error_nosetter_property_assignment;
3223    break;
3224  }
3225
3226  if (NeedType)
3227    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
3228  else
3229    S.Diag(Loc, Diag) << E->getSourceRange();
3230  return true;
3231}
3232
3233
3234
3235// C99 6.5.16.1
3236QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3237                                       SourceLocation Loc,
3238                                       QualType CompoundType) {
3239  // Verify that LHS is a modifiable lvalue, and emit error if not.
3240  if (CheckForModifiableLvalue(LHS, Loc, *this))
3241    return QualType();
3242
3243  QualType LHSType = LHS->getType();
3244  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
3245
3246  AssignConvertType ConvTy;
3247  if (CompoundType.isNull()) {
3248    // Simple assignment "x = y".
3249    ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
3250    // Special case of NSObject attributes on c-style pointer types.
3251    if (ConvTy == IncompatiblePointer &&
3252        ((Context.isObjCNSObjectType(LHSType) &&
3253          Context.isObjCObjectPointerType(RHSType)) ||
3254         (Context.isObjCNSObjectType(RHSType) &&
3255          Context.isObjCObjectPointerType(LHSType))))
3256      ConvTy = Compatible;
3257
3258    // If the RHS is a unary plus or minus, check to see if they = and + are
3259    // right next to each other.  If so, the user may have typo'd "x =+ 4"
3260    // instead of "x += 4".
3261    Expr *RHSCheck = RHS;
3262    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3263      RHSCheck = ICE->getSubExpr();
3264    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3265      if ((UO->getOpcode() == UnaryOperator::Plus ||
3266           UO->getOpcode() == UnaryOperator::Minus) &&
3267          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
3268          // Only if the two operators are exactly adjacent.
3269          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
3270        Diag(Loc, diag::warn_not_compound_assign)
3271          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3272          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
3273    }
3274  } else {
3275    // Compound assignment "x += y"
3276    ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
3277  }
3278
3279  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3280                               RHS, "assigning"))
3281    return QualType();
3282
3283  // C99 6.5.16p3: The type of an assignment expression is the type of the
3284  // left operand unless the left operand has qualified type, in which case
3285  // it is the unqualified version of the type of the left operand.
3286  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3287  // is converted to the type of the assignment expression (above).
3288  // C++ 5.17p1: the type of the assignment expression is that of its left
3289  // oprdu.
3290  return LHSType.getUnqualifiedType();
3291}
3292
3293// C99 6.5.17
3294QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3295  // FIXME: what is required for LHS?
3296
3297  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
3298  DefaultFunctionArrayConversion(RHS);
3299  return RHS->getType();
3300}
3301
3302/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3303/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
3304QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3305                                              bool isInc) {
3306  QualType ResType = Op->getType();
3307  assert(!ResType.isNull() && "no type for increment/decrement expression");
3308
3309  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3310    // Decrement of bool is not allowed.
3311    if (!isInc) {
3312      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3313      return QualType();
3314    }
3315    // Increment of bool sets it to true, but is deprecated.
3316    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3317  } else if (ResType->isRealType()) {
3318    // OK!
3319  } else if (const PointerType *PT = ResType->getAsPointerType()) {
3320    // C99 6.5.2.4p2, 6.5.6p2
3321    if (PT->getPointeeType()->isObjectType()) {
3322      // Pointer to object is ok!
3323    } else if (PT->getPointeeType()->isVoidType()) {
3324      if (getLangOptions().CPlusPlus) {
3325        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3326          << Op->getSourceRange();
3327        return QualType();
3328      }
3329
3330      // Pointer to void is a GNU extension in C.
3331      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3332    } else if (PT->getPointeeType()->isFunctionType()) {
3333      if (getLangOptions().CPlusPlus) {
3334        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3335          << Op->getType() << Op->getSourceRange();
3336        return QualType();
3337      }
3338
3339      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
3340        << ResType << Op->getSourceRange();
3341      return QualType();
3342    } else {
3343      DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3344                             diag::err_typecheck_arithmetic_incomplete_type,
3345                             Op->getSourceRange(), SourceRange(),
3346                             ResType);
3347      return QualType();
3348    }
3349  } else if (ResType->isComplexType()) {
3350    // C99 does not support ++/-- on complex types, we allow as an extension.
3351    Diag(OpLoc, diag::ext_integer_increment_complex)
3352      << ResType << Op->getSourceRange();
3353  } else {
3354    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
3355      << ResType << Op->getSourceRange();
3356    return QualType();
3357  }
3358  // At this point, we know we have a real, complex or pointer type.
3359  // Now make sure the operand is a modifiable lvalue.
3360  if (CheckForModifiableLvalue(Op, OpLoc, *this))
3361    return QualType();
3362  return ResType;
3363}
3364
3365/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
3366/// This routine allows us to typecheck complex/recursive expressions
3367/// where the declaration is needed for type checking. We only need to
3368/// handle cases when the expression references a function designator
3369/// or is an lvalue. Here are some examples:
3370///  - &(x) => x
3371///  - &*****f => f for f a function designator.
3372///  - &s.xx => s
3373///  - &s.zz[1].yy -> s, if zz is an array
3374///  - *(x + 1) -> x, if x is an array
3375///  - &"123"[2] -> 0
3376///  - & __real__ x -> x
3377static NamedDecl *getPrimaryDecl(Expr *E) {
3378  switch (E->getStmtClass()) {
3379  case Stmt::DeclRefExprClass:
3380  case Stmt::QualifiedDeclRefExprClass:
3381    return cast<DeclRefExpr>(E)->getDecl();
3382  case Stmt::MemberExprClass:
3383    // Fields cannot be declared with a 'register' storage class.
3384    // &X->f is always ok, even if X is declared register.
3385    if (cast<MemberExpr>(E)->isArrow())
3386      return 0;
3387    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
3388  case Stmt::ArraySubscriptExprClass: {
3389    // &X[4] and &4[X] refers to X if X is not a pointer.
3390
3391    NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
3392    ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
3393    if (!VD || VD->getType()->isPointerType())
3394      return 0;
3395    else
3396      return VD;
3397  }
3398  case Stmt::UnaryOperatorClass: {
3399    UnaryOperator *UO = cast<UnaryOperator>(E);
3400
3401    switch(UO->getOpcode()) {
3402    case UnaryOperator::Deref: {
3403      // *(X + 1) refers to X if X is not a pointer.
3404      if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3405        ValueDecl *VD = dyn_cast<ValueDecl>(D);
3406        if (!VD || VD->getType()->isPointerType())
3407          return 0;
3408        return VD;
3409      }
3410      return 0;
3411    }
3412    case UnaryOperator::Real:
3413    case UnaryOperator::Imag:
3414    case UnaryOperator::Extension:
3415      return getPrimaryDecl(UO->getSubExpr());
3416    default:
3417      return 0;
3418    }
3419  }
3420  case Stmt::BinaryOperatorClass: {
3421    BinaryOperator *BO = cast<BinaryOperator>(E);
3422
3423    // Handle cases involving pointer arithmetic. The result of an
3424    // Assign or AddAssign is not an lvalue so they can be ignored.
3425
3426    // (x + n) or (n + x) => x
3427    if (BO->getOpcode() == BinaryOperator::Add) {
3428      if (BO->getLHS()->getType()->isPointerType()) {
3429        return getPrimaryDecl(BO->getLHS());
3430      } else if (BO->getRHS()->getType()->isPointerType()) {
3431        return getPrimaryDecl(BO->getRHS());
3432      }
3433    }
3434
3435    return 0;
3436  }
3437  case Stmt::ParenExprClass:
3438    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
3439  case Stmt::ImplicitCastExprClass:
3440    // &X[4] when X is an array, has an implicit cast from array to pointer.
3441    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
3442  default:
3443    return 0;
3444  }
3445}
3446
3447/// CheckAddressOfOperand - The operand of & must be either a function
3448/// designator or an lvalue designating an object. If it is an lvalue, the
3449/// object cannot be declared with storage class register or be a bit field.
3450/// Note: The usual conversions are *not* applied to the operand of the &
3451/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
3452/// In C++, the operand might be an overloaded function name, in which case
3453/// we allow the '&' but retain the overloaded-function type.
3454QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
3455  if (op->isTypeDependent())
3456    return Context.DependentTy;
3457
3458  if (getLangOptions().C99) {
3459    // Implement C99-only parts of addressof rules.
3460    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3461      if (uOp->getOpcode() == UnaryOperator::Deref)
3462        // Per C99 6.5.3.2, the address of a deref always returns a valid result
3463        // (assuming the deref expression is valid).
3464        return uOp->getSubExpr()->getType();
3465    }
3466    // Technically, there should be a check for array subscript
3467    // expressions here, but the result of one is always an lvalue anyway.
3468  }
3469  NamedDecl *dcl = getPrimaryDecl(op);
3470  Expr::isLvalueResult lval = op->isLvalue(Context);
3471
3472  if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
3473    if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3474      // FIXME: emit more specific diag...
3475      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3476        << op->getSourceRange();
3477      return QualType();
3478    }
3479  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
3480    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3481      if (Field->isBitField()) {
3482        Diag(OpLoc, diag::err_typecheck_address_of)
3483          << "bit-field" << op->getSourceRange();
3484        return QualType();
3485      }
3486    }
3487  // Check for Apple extension for accessing vector components.
3488  } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3489           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
3490    Diag(OpLoc, diag::err_typecheck_address_of)
3491      << "vector element" << op->getSourceRange();
3492    return QualType();
3493  } else if (dcl) { // C99 6.5.3.2p1
3494    // We have an lvalue with a decl. Make sure the decl is not declared
3495    // with the register storage-class specifier.
3496    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3497      if (vd->getStorageClass() == VarDecl::Register) {
3498        Diag(OpLoc, diag::err_typecheck_address_of)
3499          << "register variable" << op->getSourceRange();
3500        return QualType();
3501      }
3502    } else if (isa<OverloadedFunctionDecl>(dcl)) {
3503      return Context.OverloadTy;
3504    } else if (isa<FieldDecl>(dcl)) {
3505      // Okay: we can take the address of a field.
3506      // Could be a pointer to member, though, if there is an explicit
3507      // scope qualifier for the class.
3508      if (isa<QualifiedDeclRefExpr>(op)) {
3509        DeclContext *Ctx = dcl->getDeclContext();
3510        if (Ctx && Ctx->isRecord())
3511          return Context.getMemberPointerType(op->getType(),
3512                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3513      }
3514    } else if (isa<FunctionDecl>(dcl)) {
3515      // Okay: we can take the address of a function.
3516      // As above.
3517      if (isa<QualifiedDeclRefExpr>(op)) {
3518        DeclContext *Ctx = dcl->getDeclContext();
3519        if (Ctx && Ctx->isRecord())
3520          return Context.getMemberPointerType(op->getType(),
3521                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3522      }
3523    }
3524    else
3525      assert(0 && "Unknown/unexpected decl type");
3526  }
3527
3528  // If the operand has type "type", the result has type "pointer to type".
3529  return Context.getPointerType(op->getType());
3530}
3531
3532QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3533  UsualUnaryConversions(Op);
3534  QualType Ty = Op->getType();
3535
3536  // Note that per both C89 and C99, this is always legal, even if ptype is an
3537  // incomplete type or void.  It would be possible to warn about dereferencing
3538  // a void pointer, but it's completely well-defined, and such a warning is
3539  // unlikely to catch any mistakes.
3540  if (const PointerType *PT = Ty->getAsPointerType())
3541    return PT->getPointeeType();
3542
3543  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
3544    << Ty << Op->getSourceRange();
3545  return QualType();
3546}
3547
3548static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3549  tok::TokenKind Kind) {
3550  BinaryOperator::Opcode Opc;
3551  switch (Kind) {
3552  default: assert(0 && "Unknown binop!");
3553  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
3554  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
3555  case tok::star:                 Opc = BinaryOperator::Mul; break;
3556  case tok::slash:                Opc = BinaryOperator::Div; break;
3557  case tok::percent:              Opc = BinaryOperator::Rem; break;
3558  case tok::plus:                 Opc = BinaryOperator::Add; break;
3559  case tok::minus:                Opc = BinaryOperator::Sub; break;
3560  case tok::lessless:             Opc = BinaryOperator::Shl; break;
3561  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
3562  case tok::lessequal:            Opc = BinaryOperator::LE; break;
3563  case tok::less:                 Opc = BinaryOperator::LT; break;
3564  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
3565  case tok::greater:              Opc = BinaryOperator::GT; break;
3566  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
3567  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
3568  case tok::amp:                  Opc = BinaryOperator::And; break;
3569  case tok::caret:                Opc = BinaryOperator::Xor; break;
3570  case tok::pipe:                 Opc = BinaryOperator::Or; break;
3571  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
3572  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
3573  case tok::equal:                Opc = BinaryOperator::Assign; break;
3574  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
3575  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
3576  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
3577  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
3578  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
3579  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
3580  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
3581  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
3582  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
3583  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
3584  case tok::comma:                Opc = BinaryOperator::Comma; break;
3585  }
3586  return Opc;
3587}
3588
3589static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3590  tok::TokenKind Kind) {
3591  UnaryOperator::Opcode Opc;
3592  switch (Kind) {
3593  default: assert(0 && "Unknown unary op!");
3594  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
3595  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
3596  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
3597  case tok::star:         Opc = UnaryOperator::Deref; break;
3598  case tok::plus:         Opc = UnaryOperator::Plus; break;
3599  case tok::minus:        Opc = UnaryOperator::Minus; break;
3600  case tok::tilde:        Opc = UnaryOperator::Not; break;
3601  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
3602  case tok::kw___real:    Opc = UnaryOperator::Real; break;
3603  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
3604  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3605  }
3606  return Opc;
3607}
3608
3609/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3610/// operator @p Opc at location @c TokLoc. This routine only supports
3611/// built-in operations; ActOnBinOp handles overloaded operators.
3612Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3613                                                  unsigned Op,
3614                                                  Expr *lhs, Expr *rhs) {
3615  QualType ResultTy;  // Result type of the binary operator.
3616  QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
3617  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3618
3619  switch (Opc) {
3620  default:
3621    assert(0 && "Unknown binary expr!");
3622  case BinaryOperator::Assign:
3623    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3624    break;
3625  case BinaryOperator::PtrMemD:
3626  case BinaryOperator::PtrMemI:
3627    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3628                                            Opc == BinaryOperator::PtrMemI);
3629    break;
3630  case BinaryOperator::Mul:
3631  case BinaryOperator::Div:
3632    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3633    break;
3634  case BinaryOperator::Rem:
3635    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3636    break;
3637  case BinaryOperator::Add:
3638    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3639    break;
3640  case BinaryOperator::Sub:
3641    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3642    break;
3643  case BinaryOperator::Shl:
3644  case BinaryOperator::Shr:
3645    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3646    break;
3647  case BinaryOperator::LE:
3648  case BinaryOperator::LT:
3649  case BinaryOperator::GE:
3650  case BinaryOperator::GT:
3651    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3652    break;
3653  case BinaryOperator::EQ:
3654  case BinaryOperator::NE:
3655    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3656    break;
3657  case BinaryOperator::And:
3658  case BinaryOperator::Xor:
3659  case BinaryOperator::Or:
3660    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3661    break;
3662  case BinaryOperator::LAnd:
3663  case BinaryOperator::LOr:
3664    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3665    break;
3666  case BinaryOperator::MulAssign:
3667  case BinaryOperator::DivAssign:
3668    CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3669    if (!CompTy.isNull())
3670      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3671    break;
3672  case BinaryOperator::RemAssign:
3673    CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3674    if (!CompTy.isNull())
3675      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3676    break;
3677  case BinaryOperator::AddAssign:
3678    CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3679    if (!CompTy.isNull())
3680      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3681    break;
3682  case BinaryOperator::SubAssign:
3683    CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3684    if (!CompTy.isNull())
3685      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3686    break;
3687  case BinaryOperator::ShlAssign:
3688  case BinaryOperator::ShrAssign:
3689    CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3690    if (!CompTy.isNull())
3691      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3692    break;
3693  case BinaryOperator::AndAssign:
3694  case BinaryOperator::XorAssign:
3695  case BinaryOperator::OrAssign:
3696    CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3697    if (!CompTy.isNull())
3698      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3699    break;
3700  case BinaryOperator::Comma:
3701    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3702    break;
3703  }
3704  if (ResultTy.isNull())
3705    return ExprError();
3706  if (CompTy.isNull())
3707    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3708  else
3709    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
3710                                                  CompTy, OpLoc));
3711}
3712
3713// Binary Operators.  'Tok' is the token for the operator.
3714Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3715                                          tok::TokenKind Kind,
3716                                          ExprArg LHS, ExprArg RHS) {
3717  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3718  Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
3719
3720  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3721  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
3722
3723  // If either expression is type-dependent, just build the AST.
3724  // FIXME: We'll need to perform some caching of the result of name
3725  // lookup for operator+.
3726  if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3727    if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3728      return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
3729                                              Context.DependentTy,
3730                                              Context.DependentTy, TokLoc));
3731    else
3732      return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3733                                                Context.DependentTy, TokLoc));
3734  }
3735
3736  if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
3737      (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3738       rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
3739    // If this is one of the assignment operators, we only perform
3740    // overload resolution if the left-hand side is a class or
3741    // enumeration type (C++ [expr.ass]p3).
3742    if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3743        !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3744      return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3745    }
3746
3747    // Determine which overloaded operator we're dealing with.
3748    static const OverloadedOperatorKind OverOps[] = {
3749      // Overloading .* is not possible.
3750      static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
3751      OO_Star, OO_Slash, OO_Percent,
3752      OO_Plus, OO_Minus,
3753      OO_LessLess, OO_GreaterGreater,
3754      OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3755      OO_EqualEqual, OO_ExclaimEqual,
3756      OO_Amp,
3757      OO_Caret,
3758      OO_Pipe,
3759      OO_AmpAmp,
3760      OO_PipePipe,
3761      OO_Equal, OO_StarEqual,
3762      OO_SlashEqual, OO_PercentEqual,
3763      OO_PlusEqual, OO_MinusEqual,
3764      OO_LessLessEqual, OO_GreaterGreaterEqual,
3765      OO_AmpEqual, OO_CaretEqual,
3766      OO_PipeEqual,
3767      OO_Comma
3768    };
3769    OverloadedOperatorKind OverOp = OverOps[Opc];
3770
3771    // Add the appropriate overloaded operators (C++ [over.match.oper])
3772    // to the candidate set.
3773    OverloadCandidateSet CandidateSet;
3774    Expr *Args[2] = { lhs, rhs };
3775    if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3776      return ExprError();
3777
3778    // Perform overload resolution.
3779    OverloadCandidateSet::iterator Best;
3780    switch (BestViableFunction(CandidateSet, Best)) {
3781    case OR_Success: {
3782      // We found a built-in operator or an overloaded operator.
3783      FunctionDecl *FnDecl = Best->Function;
3784
3785      if (FnDecl) {
3786        // We matched an overloaded operator. Build a call to that
3787        // operator.
3788
3789        // Convert the arguments.
3790        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3791          if (PerformObjectArgumentInitialization(lhs, Method) ||
3792              PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3793                                        "passing"))
3794            return ExprError();
3795        } else {
3796          // Convert the arguments.
3797          if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3798                                        "passing") ||
3799              PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3800                                        "passing"))
3801            return ExprError();
3802        }
3803
3804        // Determine the result type
3805        QualType ResultTy
3806          = FnDecl->getType()->getAsFunctionType()->getResultType();
3807        ResultTy = ResultTy.getNonReferenceType();
3808
3809        // Build the actual expression node.
3810        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3811                                                 SourceLocation());
3812        UsualUnaryConversions(FnExpr);
3813
3814        return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
3815                                                       ResultTy, TokLoc));
3816      } else {
3817        // We matched a built-in operator. Convert the arguments, then
3818        // break out so that we will build the appropriate built-in
3819        // operator node.
3820        if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3821                                      Best->Conversions[0], "passing") ||
3822            PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3823                                      Best->Conversions[1], "passing"))
3824          return ExprError();
3825
3826        break;
3827      }
3828    }
3829
3830    case OR_No_Viable_Function:
3831      // No viable function; fall through to handling this as a
3832      // built-in operator, which will produce an error message for us.
3833      break;
3834
3835    case OR_Ambiguous:
3836      Diag(TokLoc,  diag::err_ovl_ambiguous_oper)
3837          << BinaryOperator::getOpcodeStr(Opc)
3838          << lhs->getSourceRange() << rhs->getSourceRange();
3839      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3840      return ExprError();
3841    }
3842
3843    // Either we found no viable overloaded operator or we matched a
3844    // built-in operator. In either case, fall through to trying to
3845    // build a built-in operation.
3846  }
3847
3848  // Build a built-in binary operation.
3849  return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3850}
3851
3852// Unary Operators.  'Tok' is the token for the operator.
3853Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3854                                            tok::TokenKind Op, ExprArg input) {
3855  // FIXME: Input is modified later, but smart pointer not reassigned.
3856  Expr *Input = (Expr*)input.get();
3857  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
3858
3859  if (getLangOptions().CPlusPlus &&
3860      (Input->getType()->isRecordType()
3861       || Input->getType()->isEnumeralType())) {
3862    // Determine which overloaded operator we're dealing with.
3863    static const OverloadedOperatorKind OverOps[] = {
3864      OO_None, OO_None,
3865      OO_PlusPlus, OO_MinusMinus,
3866      OO_Amp, OO_Star,
3867      OO_Plus, OO_Minus,
3868      OO_Tilde, OO_Exclaim,
3869      OO_None, OO_None,
3870      OO_None,
3871      OO_None
3872    };
3873    OverloadedOperatorKind OverOp = OverOps[Opc];
3874
3875    // Add the appropriate overloaded operators (C++ [over.match.oper])
3876    // to the candidate set.
3877    OverloadCandidateSet CandidateSet;
3878    if (OverOp != OO_None &&
3879        AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3880      return ExprError();
3881
3882    // Perform overload resolution.
3883    OverloadCandidateSet::iterator Best;
3884    switch (BestViableFunction(CandidateSet, Best)) {
3885    case OR_Success: {
3886      // We found a built-in operator or an overloaded operator.
3887      FunctionDecl *FnDecl = Best->Function;
3888
3889      if (FnDecl) {
3890        // We matched an overloaded operator. Build a call to that
3891        // operator.
3892
3893        // Convert the arguments.
3894        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3895          if (PerformObjectArgumentInitialization(Input, Method))
3896            return ExprError();
3897        } else {
3898          // Convert the arguments.
3899          if (PerformCopyInitialization(Input,
3900                                        FnDecl->getParamDecl(0)->getType(),
3901                                        "passing"))
3902            return ExprError();
3903        }
3904
3905        // Determine the result type
3906        QualType ResultTy
3907          = FnDecl->getType()->getAsFunctionType()->getResultType();
3908        ResultTy = ResultTy.getNonReferenceType();
3909
3910        // Build the actual expression node.
3911        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3912                                                 SourceLocation());
3913        UsualUnaryConversions(FnExpr);
3914
3915        input.release();
3916        return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
3917                                                       ResultTy, OpLoc));
3918      } else {
3919        // We matched a built-in operator. Convert the arguments, then
3920        // break out so that we will build the appropriate built-in
3921        // operator node.
3922        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3923                                      Best->Conversions[0], "passing"))
3924          return ExprError();
3925
3926        break;
3927      }
3928    }
3929
3930    case OR_No_Viable_Function:
3931      // No viable function; fall through to handling this as a
3932      // built-in operator, which will produce an error message for us.
3933      break;
3934
3935    case OR_Ambiguous:
3936      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
3937          << UnaryOperator::getOpcodeStr(Opc)
3938          << Input->getSourceRange();
3939      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3940      return ExprError();
3941    }
3942
3943    // Either we found no viable overloaded operator or we matched a
3944    // built-in operator. In either case, fall through to trying to
3945    // build a built-in operation.
3946  }
3947
3948  QualType resultType;
3949  switch (Opc) {
3950  default:
3951    assert(0 && "Unimplemented unary expr!");
3952  case UnaryOperator::PreInc:
3953  case UnaryOperator::PreDec:
3954    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3955                                                Opc == UnaryOperator::PreInc);
3956    break;
3957  case UnaryOperator::AddrOf:
3958    resultType = CheckAddressOfOperand(Input, OpLoc);
3959    break;
3960  case UnaryOperator::Deref:
3961    DefaultFunctionArrayConversion(Input);
3962    resultType = CheckIndirectionOperand(Input, OpLoc);
3963    break;
3964  case UnaryOperator::Plus:
3965  case UnaryOperator::Minus:
3966    UsualUnaryConversions(Input);
3967    resultType = Input->getType();
3968    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3969      break;
3970    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3971             resultType->isEnumeralType())
3972      break;
3973    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3974             Opc == UnaryOperator::Plus &&
3975             resultType->isPointerType())
3976      break;
3977
3978    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3979      << resultType << Input->getSourceRange());
3980  case UnaryOperator::Not: // bitwise complement
3981    UsualUnaryConversions(Input);
3982    resultType = Input->getType();
3983    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3984    if (resultType->isComplexType() || resultType->isComplexIntegerType())
3985      // C99 does not support '~' for complex conjugation.
3986      Diag(OpLoc, diag::ext_integer_complement_complex)
3987        << resultType << Input->getSourceRange();
3988    else if (!resultType->isIntegerType())
3989      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3990        << resultType << Input->getSourceRange());
3991    break;
3992  case UnaryOperator::LNot: // logical negation
3993    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3994    DefaultFunctionArrayConversion(Input);
3995    resultType = Input->getType();
3996    if (!resultType->isScalarType()) // C99 6.5.3.3p1
3997      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3998        << resultType << Input->getSourceRange());
3999    // LNot always has type int. C99 6.5.3.3p5.
4000    // In C++, it's bool. C++ 5.3.1p8
4001    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
4002    break;
4003  case UnaryOperator::Real:
4004  case UnaryOperator::Imag:
4005    resultType = CheckRealImagOperand(Input, OpLoc);
4006    break;
4007  case UnaryOperator::Extension:
4008    resultType = Input->getType();
4009    break;
4010  }
4011  if (resultType.isNull())
4012    return ExprError();
4013  input.release();
4014  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
4015}
4016
4017/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4018Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4019                                      SourceLocation LabLoc,
4020                                      IdentifierInfo *LabelII) {
4021  // Look up the record for this label identifier.
4022  LabelStmt *&LabelDecl = LabelMap[LabelII];
4023
4024  // If we haven't seen this label yet, create a forward reference. It
4025  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
4026  if (LabelDecl == 0)
4027    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
4028
4029  // Create the AST node.  The address of a label always has type 'void*'.
4030  return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4031                                     Context.getPointerType(Context.VoidTy));
4032}
4033
4034Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
4035                                     SourceLocation RPLoc) { // "({..})"
4036  Stmt *SubStmt = static_cast<Stmt*>(substmt);
4037  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4038  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4039
4040  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4041  if (isFileScope) {
4042    return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4043  }
4044
4045  // FIXME: there are a variety of strange constraints to enforce here, for
4046  // example, it is not possible to goto into a stmt expression apparently.
4047  // More semantic analysis is needed.
4048
4049  // FIXME: the last statement in the compount stmt has its value used.  We
4050  // should not warn about it being unused.
4051
4052  // If there are sub stmts in the compound stmt, take the type of the last one
4053  // as the type of the stmtexpr.
4054  QualType Ty = Context.VoidTy;
4055
4056  if (!Compound->body_empty()) {
4057    Stmt *LastStmt = Compound->body_back();
4058    // If LastStmt is a label, skip down through into the body.
4059    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4060      LastStmt = Label->getSubStmt();
4061
4062    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
4063      Ty = LastExpr->getType();
4064  }
4065
4066  return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
4067}
4068
4069Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4070                                            SourceLocation BuiltinLoc,
4071                                            SourceLocation TypeLoc,
4072                                            TypeTy *argty,
4073                                            OffsetOfComponent *CompPtr,
4074                                            unsigned NumComponents,
4075                                            SourceLocation RPLoc) {
4076  QualType ArgTy = QualType::getFromOpaquePtr(argty);
4077  assert(!ArgTy.isNull() && "Missing type argument!");
4078
4079  // We must have at least one component that refers to the type, and the first
4080  // one is known to be a field designator.  Verify that the ArgTy represents
4081  // a struct/union/class.
4082  if (!ArgTy->isRecordType())
4083    return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
4084
4085  // Otherwise, create a compound literal expression as the base, and
4086  // iteratively process the offsetof designators.
4087  InitListExpr *IList =
4088      new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
4089  IList->setType(ArgTy);
4090  Expr *Res =
4091      new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4092
4093  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4094  // GCC extension, diagnose them.
4095  if (NumComponents != 1)
4096    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4097      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
4098
4099  for (unsigned i = 0; i != NumComponents; ++i) {
4100    const OffsetOfComponent &OC = CompPtr[i];
4101    if (OC.isBrackets) {
4102      // Offset of an array sub-field.  TODO: Should we allow vector elements?
4103      const ArrayType *AT = Context.getAsArrayType(Res->getType());
4104      if (!AT) {
4105        Res->Destroy(Context);
4106        return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
4107      }
4108
4109      // FIXME: C++: Verify that operator[] isn't overloaded.
4110
4111      // C99 6.5.2.1p1
4112      Expr *Idx = static_cast<Expr*>(OC.U.E);
4113      if (!Idx->getType()->isIntegerType())
4114        return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4115          << Idx->getSourceRange();
4116
4117      Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4118                                             OC.LocEnd);
4119      continue;
4120    }
4121
4122    const RecordType *RC = Res->getType()->getAsRecordType();
4123    if (!RC) {
4124      Res->Destroy(Context);
4125      return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
4126    }
4127
4128    // Get the decl corresponding to this.
4129    RecordDecl *RD = RC->getDecl();
4130    FieldDecl *MemberDecl
4131      = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4132                                                        LookupMemberName)
4133                                      .getAsDecl());
4134    if (!MemberDecl)
4135      return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4136       << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
4137
4138    // FIXME: C++: Verify that MemberDecl isn't a static field.
4139    // FIXME: Verify that MemberDecl isn't a bitfield.
4140    // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4141    // matter here.
4142    Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4143                                   MemberDecl->getType().getNonReferenceType());
4144  }
4145
4146  return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4147                                     Context.getSizeType(), BuiltinLoc);
4148}
4149
4150
4151Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4152                                                TypeTy *arg1, TypeTy *arg2,
4153                                                SourceLocation RPLoc) {
4154  QualType argT1 = QualType::getFromOpaquePtr(arg1);
4155  QualType argT2 = QualType::getFromOpaquePtr(arg2);
4156
4157  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4158
4159  return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4160                                           argT2, RPLoc);
4161}
4162
4163Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
4164                                       ExprTy *expr1, ExprTy *expr2,
4165                                       SourceLocation RPLoc) {
4166  Expr *CondExpr = static_cast<Expr*>(cond);
4167  Expr *LHSExpr = static_cast<Expr*>(expr1);
4168  Expr *RHSExpr = static_cast<Expr*>(expr2);
4169
4170  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4171
4172  // The conditional expression is required to be a constant expression.
4173  llvm::APSInt condEval(32);
4174  SourceLocation ExpLoc;
4175  if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4176    return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4177      << CondExpr->getSourceRange();
4178
4179  // If the condition is > zero, then the AST type is the same as the LSHExpr.
4180  QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4181                                               RHSExpr->getType();
4182  return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4183                                  resType, RPLoc);
4184}
4185
4186//===----------------------------------------------------------------------===//
4187// Clang Extensions.
4188//===----------------------------------------------------------------------===//
4189
4190/// ActOnBlockStart - This callback is invoked when a block literal is started.
4191void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
4192  // Analyze block parameters.
4193  BlockSemaInfo *BSI = new BlockSemaInfo();
4194
4195  // Add BSI to CurBlock.
4196  BSI->PrevBlockInfo = CurBlock;
4197  CurBlock = BSI;
4198
4199  BSI->ReturnType = 0;
4200  BSI->TheScope = BlockScope;
4201
4202  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
4203  PushDeclContext(BlockScope, BSI->TheDecl);
4204}
4205
4206void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4207  assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4208
4209  if (ParamInfo.getNumTypeObjects() == 0
4210      || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4211    QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4212
4213    // The type is entirely optional as well, if none, use DependentTy.
4214    if (T.isNull())
4215      T = Context.DependentTy;
4216
4217    // The parameter list is optional, if there was none, assume ().
4218    if (!T->isFunctionType())
4219      T = Context.getFunctionType(T, NULL, 0, 0, 0);
4220
4221    CurBlock->hasPrototype = true;
4222    CurBlock->isVariadic = false;
4223    Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4224      .getTypePtr();
4225
4226    if (!RetTy->isDependentType())
4227      CurBlock->ReturnType = RetTy;
4228    return;
4229  }
4230
4231  // Analyze arguments to block.
4232  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4233         "Not a function declarator!");
4234  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4235
4236  CurBlock->hasPrototype = FTI.hasPrototype;
4237  CurBlock->isVariadic = true;
4238
4239  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4240  // no arguments, not a function that takes a single void argument.
4241  if (FTI.hasPrototype &&
4242      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4243      (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4244        ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4245    // empty arg list, don't push any params.
4246    CurBlock->isVariadic = false;
4247  } else if (FTI.hasPrototype) {
4248    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
4249      CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4250    CurBlock->isVariadic = FTI.isVariadic;
4251    QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4252
4253    Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4254      .getTypePtr();
4255
4256    if (!RetTy->isDependentType())
4257      CurBlock->ReturnType = RetTy;
4258  }
4259  CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4260
4261  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4262       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4263    // If this has an identifier, add it to the scope stack.
4264    if ((*AI)->getIdentifier())
4265      PushOnScopeChains(*AI, CurBlock->TheScope);
4266}
4267
4268/// ActOnBlockError - If there is an error parsing a block, this callback
4269/// is invoked to pop the information about the block from the action impl.
4270void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4271  // Ensure that CurBlock is deleted.
4272  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4273
4274  // Pop off CurBlock, handle nested blocks.
4275  CurBlock = CurBlock->PrevBlockInfo;
4276
4277  // FIXME: Delete the ParmVarDecl objects as well???
4278
4279}
4280
4281/// ActOnBlockStmtExpr - This is called when the body of a block statement
4282/// literal was successfully completed.  ^(int x){...}
4283Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4284                                          Scope *CurScope) {
4285  // Ensure that CurBlock is deleted.
4286  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4287  ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
4288
4289  PopDeclContext();
4290
4291  // Pop off CurBlock, handle nested blocks.
4292  CurBlock = CurBlock->PrevBlockInfo;
4293
4294  QualType RetTy = Context.VoidTy;
4295  if (BSI->ReturnType)
4296    RetTy = QualType(BSI->ReturnType, 0);
4297
4298  llvm::SmallVector<QualType, 8> ArgTypes;
4299  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4300    ArgTypes.push_back(BSI->Params[i]->getType());
4301
4302  QualType BlockTy;
4303  if (!BSI->hasPrototype)
4304    BlockTy = Context.getFunctionTypeNoProto(RetTy);
4305  else
4306    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
4307                                      BSI->isVariadic, 0);
4308
4309  BlockTy = Context.getBlockPointerType(BlockTy);
4310
4311  BSI->TheDecl->setBody(Body.take());
4312  return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
4313}
4314
4315/// ExprsMatchFnType - return true if the Exprs in array Args have
4316/// QualTypes that match the QualTypes of the arguments of the FnType.
4317/// The number of arguments has already been validated to match the number of
4318/// arguments in FnType.
4319static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4320                             ASTContext &Context) {
4321  unsigned NumParams = FnType->getNumArgs();
4322  for (unsigned i = 0; i != NumParams; ++i) {
4323    QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4324    QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
4325
4326    if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
4327      return false;
4328  }
4329  return true;
4330}
4331
4332Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4333                                         SourceLocation *CommaLocs,
4334                                         SourceLocation BuiltinLoc,
4335                                         SourceLocation RParenLoc) {
4336  // __builtin_overload requires at least 2 arguments
4337  if (NumArgs < 2)
4338    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4339      << SourceRange(BuiltinLoc, RParenLoc);
4340
4341  // The first argument is required to be a constant expression.  It tells us
4342  // the number of arguments to pass to each of the functions to be overloaded.
4343  Expr **Args = reinterpret_cast<Expr**>(args);
4344  Expr *NParamsExpr = Args[0];
4345  llvm::APSInt constEval(32);
4346  SourceLocation ExpLoc;
4347  if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
4348    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4349      << NParamsExpr->getSourceRange();
4350
4351  // Verify that the number of parameters is > 0
4352  unsigned NumParams = constEval.getZExtValue();
4353  if (NumParams == 0)
4354    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4355      << NParamsExpr->getSourceRange();
4356  // Verify that we have at least 1 + NumParams arguments to the builtin.
4357  if ((NumParams + 1) > NumArgs)
4358    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4359      << SourceRange(BuiltinLoc, RParenLoc);
4360
4361  // Figure out the return type, by matching the args to one of the functions
4362  // listed after the parameters.
4363  OverloadExpr *OE = 0;
4364  for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4365    // UsualUnaryConversions will convert the function DeclRefExpr into a
4366    // pointer to function.
4367    Expr *Fn = UsualUnaryConversions(Args[i]);
4368    const FunctionTypeProto *FnType = 0;
4369    if (const PointerType *PT = Fn->getType()->getAsPointerType())
4370      FnType = PT->getPointeeType()->getAsFunctionTypeProto();
4371
4372    // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4373    // parameters, and the number of parameters must match the value passed to
4374    // the builtin.
4375    if (!FnType || (FnType->getNumArgs() != NumParams))
4376      return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4377        << Fn->getSourceRange();
4378
4379    // Scan the parameter list for the FunctionType, checking the QualType of
4380    // each parameter against the QualTypes of the arguments to the builtin.
4381    // If they match, return a new OverloadExpr.
4382    if (ExprsMatchFnType(Args+1, FnType, Context)) {
4383      if (OE)
4384        return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4385          << OE->getFn()->getSourceRange();
4386      // Remember our match, and continue processing the remaining arguments
4387      // to catch any errors.
4388      OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
4389                            FnType->getResultType().getNonReferenceType(),
4390                            BuiltinLoc, RParenLoc);
4391    }
4392  }
4393  // Return the newly created OverloadExpr node, if we succeded in matching
4394  // exactly one of the candidate functions.
4395  if (OE)
4396    return OE;
4397
4398  // If we didn't find a matching function Expr in the __builtin_overload list
4399  // the return an error.
4400  std::string typeNames;
4401  for (unsigned i = 0; i != NumParams; ++i) {
4402    if (i != 0) typeNames += ", ";
4403    typeNames += Args[i+1]->getType().getAsString();
4404  }
4405
4406  return Diag(BuiltinLoc, diag::err_overload_no_match)
4407    << typeNames << SourceRange(BuiltinLoc, RParenLoc);
4408}
4409
4410Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4411                                  ExprTy *expr, TypeTy *type,
4412                                  SourceLocation RPLoc) {
4413  Expr *E = static_cast<Expr*>(expr);
4414  QualType T = QualType::getFromOpaquePtr(type);
4415
4416  InitBuiltinVaListType();
4417
4418  // Get the va_list type
4419  QualType VaListType = Context.getBuiltinVaListType();
4420  // Deal with implicit array decay; for example, on x86-64,
4421  // va_list is an array, but it's supposed to decay to
4422  // a pointer for va_arg.
4423  if (VaListType->isArrayType())
4424    VaListType = Context.getArrayDecayedType(VaListType);
4425  // Make sure the input expression also decays appropriately.
4426  UsualUnaryConversions(E);
4427
4428  if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
4429    return Diag(E->getLocStart(),
4430                diag::err_first_argument_to_va_arg_not_of_type_va_list)
4431      << E->getType() << E->getSourceRange();
4432
4433  // FIXME: Warn if a non-POD type is passed in.
4434
4435  return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
4436}
4437
4438Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4439  // The type of __null will be int or long, depending on the size of
4440  // pointers on the target.
4441  QualType Ty;
4442  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4443    Ty = Context.IntTy;
4444  else
4445    Ty = Context.LongTy;
4446
4447  return new (Context) GNUNullExpr(Ty, TokenLoc);
4448}
4449
4450bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4451                                    SourceLocation Loc,
4452                                    QualType DstType, QualType SrcType,
4453                                    Expr *SrcExpr, const char *Flavor) {
4454  // Decode the result (notice that AST's are still created for extensions).
4455  bool isInvalid = false;
4456  unsigned DiagKind;
4457  switch (ConvTy) {
4458  default: assert(0 && "Unknown conversion type");
4459  case Compatible: return false;
4460  case PointerToInt:
4461    DiagKind = diag::ext_typecheck_convert_pointer_int;
4462    break;
4463  case IntToPointer:
4464    DiagKind = diag::ext_typecheck_convert_int_pointer;
4465    break;
4466  case IncompatiblePointer:
4467    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4468    break;
4469  case FunctionVoidPointer:
4470    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4471    break;
4472  case CompatiblePointerDiscardsQualifiers:
4473    // If the qualifiers lost were because we were applying the
4474    // (deprecated) C++ conversion from a string literal to a char*
4475    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
4476    // Ideally, this check would be performed in
4477    // CheckPointerTypesForAssignment. However, that would require a
4478    // bit of refactoring (so that the second argument is an
4479    // expression, rather than a type), which should be done as part
4480    // of a larger effort to fix CheckPointerTypesForAssignment for
4481    // C++ semantics.
4482    if (getLangOptions().CPlusPlus &&
4483        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4484      return false;
4485    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4486    break;
4487  case IntToBlockPointer:
4488    DiagKind = diag::err_int_to_block_pointer;
4489    break;
4490  case IncompatibleBlockPointer:
4491    DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
4492    break;
4493  case IncompatibleObjCQualifiedId:
4494    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4495    // it can give a more specific diagnostic.
4496    DiagKind = diag::warn_incompatible_qualified_id;
4497    break;
4498  case IncompatibleVectors:
4499    DiagKind = diag::warn_incompatible_vectors;
4500    break;
4501  case Incompatible:
4502    DiagKind = diag::err_typecheck_convert_incompatible;
4503    isInvalid = true;
4504    break;
4505  }
4506
4507  Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4508    << SrcExpr->getSourceRange();
4509  return isInvalid;
4510}
4511
4512bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4513{
4514  Expr::EvalResult EvalResult;
4515
4516  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4517      EvalResult.HasSideEffects) {
4518    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4519
4520    if (EvalResult.Diag) {
4521      // We only show the note if it's not the usual "invalid subexpression"
4522      // or if it's actually in a subexpression.
4523      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4524          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4525        Diag(EvalResult.DiagLoc, EvalResult.Diag);
4526    }
4527
4528    return true;
4529  }
4530
4531  if (EvalResult.Diag) {
4532    Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4533      E->getSourceRange();
4534
4535    // Print the reason it's not a constant.
4536    if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4537      Diag(EvalResult.DiagLoc, EvalResult.Diag);
4538  }
4539
4540  if (Result)
4541    *Result = EvalResult.Val.getInt();
4542  return false;
4543}
4544