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