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