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