SemaExpr.cpp revision a982c71ef2d7b2307171784eb278330a349fa222
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/Scope.h"
26using namespace clang;
27
28//===----------------------------------------------------------------------===//
29//  Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
32/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34  QualType Ty = E->getType();
35  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
37  if (const ReferenceType *ref = Ty->getAsReferenceType()) {
38    ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
39    Ty = E->getType();
40  }
41  if (Ty->isFunctionType())
42    ImpCastExprToType(E, Context.getPointerType(Ty));
43  else if (Ty->isArrayType()) {
44    // In C90 mode, arrays only promote to pointers if the array expression is
45    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
46    // type 'array of type' is converted to an expression that has type 'pointer
47    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
48    // that has type 'array of type' ...".  The relevant change is "an lvalue"
49    // (C90) to "an expression" (C99).
50    //
51    // C++ 4.2p1:
52    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
53    // T" can be converted to an rvalue of type "pointer to T".
54    //
55    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
56        E->isLvalue(Context) == Expr::LV_Valid)
57      ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
58  }
59}
60
61/// UsualUnaryConversions - Performs various conversions that are common to most
62/// operators (C99 6.3). The conversions of array and function types are
63/// sometimes surpressed. For example, the array->pointer conversion doesn't
64/// apply if the array is an argument to the sizeof or address (&) operators.
65/// In these instances, this routine should *not* be called.
66Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
67  QualType Ty = Expr->getType();
68  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
69
70  if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
71    ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
72    Ty = Expr->getType();
73  }
74  if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
75    ImpCastExprToType(Expr, Context.IntTy);
76  else
77    DefaultFunctionArrayConversion(Expr);
78
79  return Expr;
80}
81
82/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
83/// do not have a prototype. Arguments that have type float are promoted to
84/// double. All other argument types are converted by UsualUnaryConversions().
85void Sema::DefaultArgumentPromotion(Expr *&Expr) {
86  QualType Ty = Expr->getType();
87  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
88
89  // If this is a 'float' (CVR qualified or typedef) promote to double.
90  if (const BuiltinType *BT = Ty->getAsBuiltinType())
91    if (BT->getKind() == BuiltinType::Float)
92      return ImpCastExprToType(Expr, Context.DoubleTy);
93
94  UsualUnaryConversions(Expr);
95}
96
97/// UsualArithmeticConversions - Performs various conversions that are common to
98/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
99/// routine returns the first non-arithmetic type found. The client is
100/// responsible for emitting appropriate error diagnostics.
101/// FIXME: verify the conversion rules for "complex int" are consistent with
102/// GCC.
103QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
104                                          bool isCompAssign) {
105  if (!isCompAssign) {
106    UsualUnaryConversions(lhsExpr);
107    UsualUnaryConversions(rhsExpr);
108  }
109  // For conversion purposes, we ignore any qualifiers.
110  // For example, "const float" and "float" are equivalent.
111  QualType lhs =
112    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
113  QualType rhs =
114    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
115
116  // If both types are identical, no conversion is needed.
117  if (lhs == rhs)
118    return lhs;
119
120  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
121  // The caller can deal with this (e.g. pointer + int).
122  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
123    return lhs;
124
125  // At this point, we have two different arithmetic types.
126
127  // Handle complex types first (C99 6.3.1.8p1).
128  if (lhs->isComplexType() || rhs->isComplexType()) {
129    // if we have an integer operand, the result is the complex type.
130    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
131      // convert the rhs to the lhs complex type.
132      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
133      return lhs;
134    }
135    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
136      // convert the lhs to the rhs complex type.
137      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
138      return rhs;
139    }
140    // This handles complex/complex, complex/float, or float/complex.
141    // When both operands are complex, the shorter operand is converted to the
142    // type of the longer, and that is the type of the result. This corresponds
143    // to what is done when combining two real floating-point operands.
144    // The fun begins when size promotion occur across type domains.
145    // From H&S 6.3.4: When one operand is complex and the other is a real
146    // floating-point type, the less precise type is converted, within it's
147    // real or complex domain, to the precision of the other type. For example,
148    // when combining a "long double" with a "double _Complex", the
149    // "double _Complex" is promoted to "long double _Complex".
150    int result = Context.getFloatingTypeOrder(lhs, rhs);
151
152    if (result > 0) { // The left side is bigger, convert rhs.
153      rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
154      if (!isCompAssign)
155        ImpCastExprToType(rhsExpr, rhs);
156    } else if (result < 0) { // The right side is bigger, convert lhs.
157      lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
158      if (!isCompAssign)
159        ImpCastExprToType(lhsExpr, lhs);
160    }
161    // At this point, lhs and rhs have the same rank/size. Now, make sure the
162    // domains match. This is a requirement for our implementation, C99
163    // does not require this promotion.
164    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
165      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
166        if (!isCompAssign)
167          ImpCastExprToType(lhsExpr, rhs);
168        return rhs;
169      } else { // handle "_Complex double, double".
170        if (!isCompAssign)
171          ImpCastExprToType(rhsExpr, lhs);
172        return lhs;
173      }
174    }
175    return lhs; // The domain/size match exactly.
176  }
177  // Now handle "real" floating types (i.e. float, double, long double).
178  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
179    // if we have an integer operand, the result is the real floating type.
180    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
181      // convert rhs to the lhs floating point type.
182      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
183      return lhs;
184    }
185    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
186      // convert lhs to the rhs floating point type.
187      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
188      return rhs;
189    }
190    // We have two real floating types, float/complex combos were handled above.
191    // Convert the smaller operand to the bigger result.
192    int result = Context.getFloatingTypeOrder(lhs, rhs);
193
194    if (result > 0) { // convert the rhs
195      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
196      return lhs;
197    }
198    if (result < 0) { // convert the lhs
199      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
200      return rhs;
201    }
202    assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
203  }
204  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
205    // Handle GCC complex int extension.
206    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
207    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
208
209    if (lhsComplexInt && rhsComplexInt) {
210      if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
211                                      rhsComplexInt->getElementType()) >= 0) {
212        // convert the rhs
213        if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
214        return lhs;
215      }
216      if (!isCompAssign)
217        ImpCastExprToType(lhsExpr, rhs); // convert the lhs
218      return rhs;
219    } else if (lhsComplexInt && rhs->isIntegerType()) {
220      // convert the rhs to the lhs complex type.
221      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
222      return lhs;
223    } else if (rhsComplexInt && lhs->isIntegerType()) {
224      // convert the lhs to the rhs complex type.
225      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
226      return rhs;
227    }
228  }
229  // Finally, we have two differing integer types.
230  // The rules for this case are in C99 6.3.1.8
231  int compare = Context.getIntegerTypeOrder(lhs, rhs);
232  bool lhsSigned = lhs->isSignedIntegerType(),
233       rhsSigned = rhs->isSignedIntegerType();
234  QualType destType;
235  if (lhsSigned == rhsSigned) {
236    // Same signedness; use the higher-ranked type
237    destType = compare >= 0 ? lhs : rhs;
238  } else if (compare != (lhsSigned ? 1 : -1)) {
239    // The unsigned type has greater than or equal rank to the
240    // signed type, so use the unsigned type
241    destType = lhsSigned ? rhs : lhs;
242  } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
243    // The two types are different widths; if we are here, that
244    // means the signed type is larger than the unsigned type, so
245    // use the signed type.
246    destType = lhsSigned ? lhs : rhs;
247  } else {
248    // The signed type is higher-ranked than the unsigned type,
249    // but isn't actually any bigger (like unsigned int and long
250    // on most 32-bit systems).  Use the unsigned type corresponding
251    // to the signed type.
252    destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
253  }
254  if (!isCompAssign) {
255    ImpCastExprToType(lhsExpr, destType);
256    ImpCastExprToType(rhsExpr, destType);
257  }
258  return destType;
259}
260
261//===----------------------------------------------------------------------===//
262//  Semantic Analysis for various Expression Types
263//===----------------------------------------------------------------------===//
264
265
266/// ActOnStringLiteral - The specified tokens were lexed as pasted string
267/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
268/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
269/// multiple tokens.  However, the common case is that StringToks points to one
270/// string.
271///
272Action::ExprResult
273Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
274  assert(NumStringToks && "Must have at least one string!");
275
276  StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
277  if (Literal.hadError)
278    return ExprResult(true);
279
280  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
281  for (unsigned i = 0; i != NumStringToks; ++i)
282    StringTokLocs.push_back(StringToks[i].getLocation());
283
284  // Verify that pascal strings aren't too large.
285  if (Literal.Pascal && Literal.GetStringLength() > 256)
286    return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
287                SourceRange(StringToks[0].getLocation(),
288                            StringToks[NumStringToks-1].getLocation()));
289
290  QualType StrTy = Context.CharTy;
291  if (Literal.AnyWide) StrTy = Context.getWCharType();
292  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
293
294  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
295  if (getLangOptions().CPlusPlus)
296    StrTy.addConst();
297
298  // Get an array type for the string, according to C99 6.4.5.  This includes
299  // the nul terminator character as well as the string length for pascal
300  // strings.
301  StrTy = Context.getConstantArrayType(StrTy,
302                                   llvm::APInt(32, Literal.GetStringLength()+1),
303                                       ArrayType::Normal, 0);
304
305  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
306  return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
307                           Literal.AnyWide, StrTy,
308                           StringToks[0].getLocation(),
309                           StringToks[NumStringToks-1].getLocation());
310}
311
312/// DeclDefinedWithinScope - Return true if the specified decl is defined at or
313/// within the 'Within' scope.  The current Scope is CurScope.
314///
315/// FIXME: This method is extremely inefficient (linear scan), this should not
316/// be used in common cases. Replace with the more modern DeclContext. We need
317/// to make sure both assignments below produce an error.
318///
319/// int main(int argc) {
320///   int xx;
321///   ^(int X) {
322///     xx = 4; // error (variable is not assignable)
323///     argc = 3; // no error.
324///   };
325/// }
326///
327static bool DeclDefinedWithinScope(ScopedDecl *D, Scope *Within,
328                                   Scope *CurScope) {
329  while (1) {
330    assert(CurScope && "CurScope not nested within 'Within'?");
331
332    // Check this scope for the decl.
333    if (CurScope->isDeclScope(D)) return true;
334
335    if (CurScope == Within) return false;
336    CurScope = CurScope->getParent();
337  }
338}
339
340/// ActOnIdentifierExpr - The parser read an identifier in expression context,
341/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
342/// identifier is used in a function call context.
343Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
344                                           IdentifierInfo &II,
345                                           bool HasTrailingLParen) {
346  // Could be enum-constant, value decl, instance variable, etc.
347  Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
348
349  // If this reference is in an Objective-C method, then ivar lookup happens as
350  // well.
351  if (getCurMethodDecl()) {
352    ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
353    // There are two cases to handle here.  1) scoped lookup could have failed,
354    // in which case we should look for an ivar.  2) scoped lookup could have
355    // found a decl, but that decl is outside the current method (i.e. a global
356    // variable).  In these two cases, we do a lookup for an ivar with this
357    // name, if the lookup suceeds, we replace it our current decl.
358    if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
359      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
360      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
361        // FIXME: This should use a new expr for a direct reference, don't turn
362        // this into Self->ivar, just return a BareIVarExpr or something.
363        IdentifierInfo &II = Context.Idents.get("self");
364        ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
365        return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
366                                 static_cast<Expr*>(SelfExpr.Val), true, true);
367      }
368    }
369    // Needed to implement property "super.method" notation.
370    if (SD == 0 && &II == SuperID) {
371      QualType T = Context.getPointerType(Context.getObjCInterfaceType(
372                     getCurMethodDecl()->getClassInterface()));
373      return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
374    }
375  }
376  // If we are parsing a block, check the block parameter list.
377  if (CurBlock) {
378    BlockSemaInfo *BLK = CurBlock;
379    do {
380      for (unsigned i = 0, e = BLK->Params.size(); i != e && D == 0; ++i)
381        if (BLK->Params[i]->getIdentifier() == &II)
382          D = BLK->Params[i];
383      if (D)
384        break; // Found!
385    } while ((BLK = BLK->PrevBlockInfo));  // Look through any enclosing blocks.
386  }
387  if (D == 0) {
388    // Otherwise, this could be an implicitly declared function reference (legal
389    // in C90, extension in C99).
390    if (HasTrailingLParen &&
391        !getLangOptions().CPlusPlus) // Not in C++.
392      D = ImplicitlyDefineFunction(Loc, II, S);
393    else {
394      // If this name wasn't predeclared and if this is not a function call,
395      // diagnose the problem.
396      return Diag(Loc, diag::err_undeclared_var_use, II.getName());
397    }
398  }
399
400  if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
401    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
402      if (MD->isStatic())
403        // "invalid use of member 'x' in static member function"
404        return Diag(Loc, diag::err_invalid_member_use_in_static_method,
405                    FD->getName());
406      if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
407        // "invalid use of nonstatic data member 'x'"
408        return Diag(Loc, diag::err_invalid_non_static_member_use,
409                    FD->getName());
410
411      if (FD->isInvalidDecl())
412        return true;
413
414      // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
415      ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
416      return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
417                            true, FD, Loc, FD->getType());
418    }
419
420    return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
421  }
422  if (isa<TypedefDecl>(D))
423    return Diag(Loc, diag::err_unexpected_typedef, II.getName());
424  if (isa<ObjCInterfaceDecl>(D))
425    return Diag(Loc, diag::err_unexpected_interface, II.getName());
426  if (isa<NamespaceDecl>(D))
427    return Diag(Loc, diag::err_unexpected_namespace, II.getName());
428
429  // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
430  ValueDecl *VD = cast<ValueDecl>(D);
431
432  // check if referencing an identifier with __attribute__((deprecated)).
433  if (VD->getAttr<DeprecatedAttr>())
434    Diag(Loc, diag::warn_deprecated, VD->getName());
435
436  // Only create DeclRefExpr's for valid Decl's.
437  if (VD->isInvalidDecl())
438    return true;
439
440  // If this reference is not in a block or if the referenced variable is
441  // within the block, create a normal DeclRefExpr.
442  //
443  // FIXME: This will create BlockDeclRefExprs for global variables,
444  // function references, etc which is suboptimal :) and breaks
445  // things like "integer constant expression" tests.
446  //
447  if (!CurBlock || DeclDefinedWithinScope(VD, CurBlock->TheScope, S) ||
448      isa<EnumConstantDecl>(VD) || isa<ParmVarDecl>(VD))
449    return new DeclRefExpr(VD, VD->getType(), Loc);
450
451  // If we are in a block and the variable is outside the current block,
452  // bind the variable reference with a BlockDeclRefExpr.
453
454  // The BlocksAttr indicates the variable is bound by-reference.
455  if (VD->getAttr<BlocksAttr>())
456    return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
457
458  // Variable will be bound by-copy, make it const within the closure.
459  VD->getType().addConst();
460  return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
461}
462
463Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
464                                           tok::TokenKind Kind) {
465  PredefinedExpr::IdentType IT;
466
467  switch (Kind) {
468  default: assert(0 && "Unknown simple primary expr!");
469  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
470  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
471  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
472  }
473
474  // Verify that this is in a function context.
475  if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
476    return Diag(Loc, diag::err_predef_outside_function);
477
478  // Pre-defined identifiers are of type char[x], where x is the length of the
479  // string.
480  unsigned Length;
481  if (getCurFunctionDecl())
482    Length = getCurFunctionDecl()->getIdentifier()->getLength();
483  else
484    Length = getCurMethodDecl()->getSynthesizedMethodSize();
485
486  llvm::APInt LengthI(32, Length + 1);
487  QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
488  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
489  return new PredefinedExpr(Loc, ResTy, IT);
490}
491
492Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
493  llvm::SmallString<16> CharBuffer;
494  CharBuffer.resize(Tok.getLength());
495  const char *ThisTokBegin = &CharBuffer[0];
496  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
497
498  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
499                            Tok.getLocation(), PP);
500  if (Literal.hadError())
501    return ExprResult(true);
502
503  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
504
505  return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
506                              Tok.getLocation());
507}
508
509Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
510  // fast path for a single digit (which is quite common). A single digit
511  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
512  if (Tok.getLength() == 1) {
513    const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
514
515    unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
516    return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
517                                         Context.IntTy,
518                                         Tok.getLocation()));
519  }
520  llvm::SmallString<512> IntegerBuffer;
521  IntegerBuffer.resize(Tok.getLength());
522  const char *ThisTokBegin = &IntegerBuffer[0];
523
524  // Get the spelling of the token, which eliminates trigraphs, etc.
525  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
526  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
527                               Tok.getLocation(), PP);
528  if (Literal.hadError)
529    return ExprResult(true);
530
531  Expr *Res;
532
533  if (Literal.isFloatingLiteral()) {
534    QualType Ty;
535    if (Literal.isFloat)
536      Ty = Context.FloatTy;
537    else if (!Literal.isLong)
538      Ty = Context.DoubleTy;
539    else
540      Ty = Context.LongDoubleTy;
541
542    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
543
544    // isExact will be set by GetFloatValue().
545    bool isExact = false;
546    Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
547                              Ty, Tok.getLocation());
548
549  } else if (!Literal.isIntegerLiteral()) {
550    return ExprResult(true);
551  } else {
552    QualType Ty;
553
554    // long long is a C99 feature.
555    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
556        Literal.isLongLong)
557      Diag(Tok.getLocation(), diag::ext_longlong);
558
559    // Get the value in the widest-possible width.
560    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
561
562    if (Literal.GetIntegerValue(ResultVal)) {
563      // If this value didn't fit into uintmax_t, warn and force to ull.
564      Diag(Tok.getLocation(), diag::warn_integer_too_large);
565      Ty = Context.UnsignedLongLongTy;
566      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
567             "long long is not intmax_t?");
568    } else {
569      // If this value fits into a ULL, try to figure out what else it fits into
570      // according to the rules of C99 6.4.4.1p5.
571
572      // Octal, Hexadecimal, and integers with a U suffix are allowed to
573      // be an unsigned int.
574      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
575
576      // Check from smallest to largest, picking the smallest type we can.
577      unsigned Width = 0;
578      if (!Literal.isLong && !Literal.isLongLong) {
579        // Are int/unsigned possibilities?
580        unsigned IntSize = Context.Target.getIntWidth();
581
582        // Does it fit in a unsigned int?
583        if (ResultVal.isIntN(IntSize)) {
584          // Does it fit in a signed int?
585          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
586            Ty = Context.IntTy;
587          else if (AllowUnsigned)
588            Ty = Context.UnsignedIntTy;
589          Width = IntSize;
590        }
591      }
592
593      // Are long/unsigned long possibilities?
594      if (Ty.isNull() && !Literal.isLongLong) {
595        unsigned LongSize = Context.Target.getLongWidth();
596
597        // Does it fit in a unsigned long?
598        if (ResultVal.isIntN(LongSize)) {
599          // Does it fit in a signed long?
600          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
601            Ty = Context.LongTy;
602          else if (AllowUnsigned)
603            Ty = Context.UnsignedLongTy;
604          Width = LongSize;
605        }
606      }
607
608      // Finally, check long long if needed.
609      if (Ty.isNull()) {
610        unsigned LongLongSize = Context.Target.getLongLongWidth();
611
612        // Does it fit in a unsigned long long?
613        if (ResultVal.isIntN(LongLongSize)) {
614          // Does it fit in a signed long long?
615          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
616            Ty = Context.LongLongTy;
617          else if (AllowUnsigned)
618            Ty = Context.UnsignedLongLongTy;
619          Width = LongLongSize;
620        }
621      }
622
623      // If we still couldn't decide a type, we probably have something that
624      // does not fit in a signed long long, but has no U suffix.
625      if (Ty.isNull()) {
626        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
627        Ty = Context.UnsignedLongLongTy;
628        Width = Context.Target.getLongLongWidth();
629      }
630
631      if (ResultVal.getBitWidth() != Width)
632        ResultVal.trunc(Width);
633    }
634
635    Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
636  }
637
638  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
639  if (Literal.isImaginary)
640    Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
641
642  return Res;
643}
644
645Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
646                                        ExprTy *Val) {
647  Expr *E = (Expr *)Val;
648  assert((E != 0) && "ActOnParenExpr() missing expr");
649  return new ParenExpr(L, R, E);
650}
651
652/// The UsualUnaryConversions() function is *not* called by this routine.
653/// See C99 6.3.2.1p[2-4] for more details.
654QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
655                                         SourceLocation OpLoc,
656                                         const SourceRange &ExprRange,
657                                         bool isSizeof) {
658  // C99 6.5.3.4p1:
659  if (isa<FunctionType>(exprType) && isSizeof)
660    // alignof(function) is allowed.
661    Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
662  else if (exprType->isVoidType())
663    Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
664         ExprRange);
665  else if (exprType->isIncompleteType()) {
666    Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
667                           diag::err_alignof_incomplete_type,
668         exprType.getAsString(), ExprRange);
669    return QualType(); // error
670  }
671  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
672  return Context.getSizeType();
673}
674
675Action::ExprResult Sema::
676ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
677                           SourceLocation LPLoc, TypeTy *Ty,
678                           SourceLocation RPLoc) {
679  // If error parsing type, ignore.
680  if (Ty == 0) return true;
681
682  // Verify that this is a valid expression.
683  QualType ArgTy = QualType::getFromOpaquePtr(Ty);
684
685  QualType resultType =
686    CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
687
688  if (resultType.isNull())
689    return true;
690  return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
691}
692
693QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
694  DefaultFunctionArrayConversion(V);
695
696  // These operators return the element type of a complex type.
697  if (const ComplexType *CT = V->getType()->getAsComplexType())
698    return CT->getElementType();
699
700  // Otherwise they pass through real integer and floating point types here.
701  if (V->getType()->isArithmeticType())
702    return V->getType();
703
704  // Reject anything else.
705  Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
706  return QualType();
707}
708
709
710
711Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
712                                             tok::TokenKind Kind,
713                                             ExprTy *Input) {
714  UnaryOperator::Opcode Opc;
715  switch (Kind) {
716  default: assert(0 && "Unknown unary op!");
717  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
718  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
719  }
720  QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
721  if (result.isNull())
722    return true;
723  return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
724}
725
726Action::ExprResult Sema::
727ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
728                        ExprTy *Idx, SourceLocation RLoc) {
729  Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
730
731  // Perform default conversions.
732  DefaultFunctionArrayConversion(LHSExp);
733  DefaultFunctionArrayConversion(RHSExp);
734
735  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
736
737  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
738  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
739  // in the subscript position. As a result, we need to derive the array base
740  // and index from the expression types.
741  Expr *BaseExpr, *IndexExpr;
742  QualType ResultType;
743  if (const PointerType *PTy = LHSTy->getAsPointerType()) {
744    BaseExpr = LHSExp;
745    IndexExpr = RHSExp;
746    // FIXME: need to deal with const...
747    ResultType = PTy->getPointeeType();
748  } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
749     // Handle the uncommon case of "123[Ptr]".
750    BaseExpr = RHSExp;
751    IndexExpr = LHSExp;
752    // FIXME: need to deal with const...
753    ResultType = PTy->getPointeeType();
754  } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
755    BaseExpr = LHSExp;    // vectors: V[123]
756    IndexExpr = RHSExp;
757
758    // Component access limited to variables (reject vec4.rg[1]).
759    if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
760        !isa<ExtVectorElementExpr>(BaseExpr))
761      return Diag(LLoc, diag::err_ext_vector_component_access,
762                  SourceRange(LLoc, RLoc));
763    // FIXME: need to deal with const...
764    ResultType = VTy->getElementType();
765  } else {
766    return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
767                RHSExp->getSourceRange());
768  }
769  // C99 6.5.2.1p1
770  if (!IndexExpr->getType()->isIntegerType())
771    return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
772                IndexExpr->getSourceRange());
773
774  // C99 6.5.2.1p1: "shall have type "pointer to *object* type".  In practice,
775  // the following check catches trying to index a pointer to a function (e.g.
776  // void (*)(int)) and pointers to incomplete types.  Functions are not
777  // objects in C99.
778  if (!ResultType->isObjectType())
779    return Diag(BaseExpr->getLocStart(),
780                diag::err_typecheck_subscript_not_object,
781                BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
782
783  return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
784}
785
786QualType Sema::
787CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
788                        IdentifierInfo &CompName, SourceLocation CompLoc) {
789  const ExtVectorType *vecType = baseType->getAsExtVectorType();
790
791  // This flag determines whether or not the component is to be treated as a
792  // special name, or a regular GLSL-style component access.
793  bool SpecialComponent = false;
794
795  // The vector accessor can't exceed the number of elements.
796  const char *compStr = CompName.getName();
797  if (strlen(compStr) > vecType->getNumElements()) {
798    Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
799                baseType.getAsString(), SourceRange(CompLoc));
800    return QualType();
801  }
802
803  // Check that we've found one of the special components, or that the component
804  // names must come from the same set.
805  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
806      !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
807    SpecialComponent = true;
808  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
809    do
810      compStr++;
811    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
812  } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
813    do
814      compStr++;
815    while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
816  } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
817    do
818      compStr++;
819    while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
820  }
821
822  if (!SpecialComponent && *compStr) {
823    // We didn't get to the end of the string. This means the component names
824    // didn't come from the same set *or* we encountered an illegal name.
825    Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
826         std::string(compStr,compStr+1), SourceRange(CompLoc));
827    return QualType();
828  }
829  // Each component accessor can't exceed the vector type.
830  compStr = CompName.getName();
831  while (*compStr) {
832    if (vecType->isAccessorWithinNumElements(*compStr))
833      compStr++;
834    else
835      break;
836  }
837  if (!SpecialComponent && *compStr) {
838    // We didn't get to the end of the string. This means a component accessor
839    // exceeds the number of elements in the vector.
840    Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
841                baseType.getAsString(), SourceRange(CompLoc));
842    return QualType();
843  }
844
845  // If we have a special component name, verify that the current vector length
846  // is an even number, since all special component names return exactly half
847  // the elements.
848  if (SpecialComponent && (vecType->getNumElements() & 1U)) {
849    return QualType();
850  }
851
852  // The component accessor looks fine - now we need to compute the actual type.
853  // The vector type is implied by the component accessor. For example,
854  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
855  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
856  unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
857                                       : strlen(CompName.getName());
858  if (CompSize == 1)
859    return vecType->getElementType();
860
861  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
862  // Now look up the TypeDefDecl from the vector type. Without this,
863  // diagostics look bad. We want extended vector types to appear built-in.
864  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
865    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
866      return Context.getTypedefType(ExtVectorDecls[i]);
867  }
868  return VT; // should never get here (a typedef type should always be found).
869}
870
871/// constructSetterName - Return the setter name for the given
872/// identifier, i.e. "set" + Name where the initial character of Name
873/// has been capitalized.
874// FIXME: Merge with same routine in Parser. But where should this
875// live?
876static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
877                                           const IdentifierInfo *Name) {
878  unsigned N = Name->getLength();
879  char *SelectorName = new char[3 + N];
880  memcpy(SelectorName, "set", 3);
881  memcpy(&SelectorName[3], Name->getName(), N);
882  SelectorName[3] = toupper(SelectorName[3]);
883
884  IdentifierInfo *Setter =
885    &Idents.get(SelectorName, &SelectorName[3 + N]);
886  delete[] SelectorName;
887  return Setter;
888}
889
890Action::ExprResult Sema::
891ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
892                         tok::TokenKind OpKind, SourceLocation MemberLoc,
893                         IdentifierInfo &Member) {
894  Expr *BaseExpr = static_cast<Expr *>(Base);
895  assert(BaseExpr && "no record expression");
896
897  // Perform default conversions.
898  DefaultFunctionArrayConversion(BaseExpr);
899
900  QualType BaseType = BaseExpr->getType();
901  assert(!BaseType.isNull() && "no type for member expression");
902
903  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
904  // must have pointer type, and the accessed type is the pointee.
905  if (OpKind == tok::arrow) {
906    if (const PointerType *PT = BaseType->getAsPointerType())
907      BaseType = PT->getPointeeType();
908    else
909      return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
910                  BaseType.getAsString(), BaseExpr->getSourceRange());
911  }
912
913  // Handle field access to simple records.  This also handles access to fields
914  // of the ObjC 'id' struct.
915  if (const RecordType *RTy = BaseType->getAsRecordType()) {
916    RecordDecl *RDecl = RTy->getDecl();
917    if (RTy->isIncompleteType())
918      return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
919                  BaseExpr->getSourceRange());
920    // The record definition is complete, now make sure the member is valid.
921    FieldDecl *MemberDecl = RDecl->getMember(&Member);
922    if (!MemberDecl)
923      return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
924                  BaseExpr->getSourceRange());
925
926    // Figure out the type of the member; see C99 6.5.2.3p3
927    // FIXME: Handle address space modifiers
928    QualType MemberType = MemberDecl->getType();
929    unsigned combinedQualifiers =
930        MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
931    MemberType = MemberType.getQualifiedType(combinedQualifiers);
932
933    return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
934                          MemberLoc, MemberType);
935  }
936
937  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
938  // (*Obj).ivar.
939  if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
940    if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
941      return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
942                                 OpKind == tok::arrow);
943    return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
944                IFTy->getDecl()->getName(), Member.getName(),
945                BaseExpr->getSourceRange());
946  }
947
948  // Handle Objective-C property access, which is "Obj.property" where Obj is a
949  // pointer to a (potentially qualified) interface type.
950  const PointerType *PTy;
951  const ObjCInterfaceType *IFTy;
952  if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
953      (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
954    ObjCInterfaceDecl *IFace = IFTy->getDecl();
955
956    // Search for a declared property first.
957    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
958      return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
959
960    // Check protocols on qualified interfaces.
961    for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
962         E = IFTy->qual_end(); I != E; ++I)
963      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
964        return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
965
966    // If that failed, look for an "implicit" property by seeing if the nullary
967    // selector is implemented.
968
969    // FIXME: The logic for looking up nullary and unary selectors should be
970    // shared with the code in ActOnInstanceMessage.
971
972    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
973    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
974
975    // If this reference is in an @implementation, check for 'private' methods.
976    if (!Getter)
977      if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
978        if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
979          if (ObjCImplementationDecl *ImpDecl =
980              ObjCImplementations[ClassDecl->getIdentifier()])
981            Getter = ImpDecl->getInstanceMethod(Sel);
982
983    if (Getter) {
984      // If we found a getter then this may be a valid dot-reference, we
985      // need to also look for the matching setter.
986      IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
987                                                       &Member);
988      Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
989      ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
990
991      if (!Setter) {
992        if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
993          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
994            if (ObjCImplementationDecl *ImpDecl =
995                ObjCImplementations[ClassDecl->getIdentifier()])
996              Setter = ImpDecl->getInstanceMethod(SetterSel);
997      }
998
999      // FIXME: There are some issues here. First, we are not
1000      // diagnosing accesses to read-only properties because we do not
1001      // know if this is a getter or setter yet. Second, we are
1002      // checking that the type of the setter matches the type we
1003      // expect.
1004      return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1005                                     MemberLoc, BaseExpr);
1006    }
1007  }
1008
1009  // Handle 'field access' to vectors, such as 'V.xx'.
1010  if (BaseType->isExtVectorType() && OpKind == tok::period) {
1011    // Component access limited to variables (reject vec4.rg.g).
1012    if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1013        !isa<ExtVectorElementExpr>(BaseExpr))
1014      return Diag(MemberLoc, diag::err_ext_vector_component_access,
1015                  BaseExpr->getSourceRange());
1016    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1017    if (ret.isNull())
1018      return true;
1019    return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1020  }
1021
1022  return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1023              BaseType.getAsString(), BaseExpr->getSourceRange());
1024}
1025
1026/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
1027/// This provides the location of the left/right parens and a list of comma
1028/// locations.
1029Action::ExprResult Sema::
1030ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
1031              ExprTy **args, unsigned NumArgs,
1032              SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1033  Expr *Fn = static_cast<Expr *>(fn);
1034  Expr **Args = reinterpret_cast<Expr**>(args);
1035  assert(Fn && "no function call expression");
1036  FunctionDecl *FDecl = NULL;
1037
1038  // Promote the function operand.
1039  UsualUnaryConversions(Fn);
1040
1041  // If we're directly calling a function, get the declaration for
1042  // that function.
1043  if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1044    if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
1045      FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1046
1047  // Make the call expr early, before semantic checks.  This guarantees cleanup
1048  // of arguments and function on error.
1049  llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
1050                                                 Context.BoolTy, RParenLoc));
1051  const FunctionType *FuncT;
1052  if (!Fn->getType()->isBlockPointerType()) {
1053    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1054    // have type pointer to function".
1055    const PointerType *PT = Fn->getType()->getAsPointerType();
1056    if (PT == 0)
1057      return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1058                  Fn->getSourceRange());
1059    FuncT = PT->getPointeeType()->getAsFunctionType();
1060  } else { // This is a block call.
1061    FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1062                getAsFunctionType();
1063  }
1064  if (FuncT == 0)
1065    return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1066                Fn->getSourceRange());
1067
1068  // We know the result type of the call, set it.
1069  TheCall->setType(FuncT->getResultType());
1070
1071  if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
1072    // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1073    // assignment, to the types of the corresponding parameter, ...
1074    unsigned NumArgsInProto = Proto->getNumArgs();
1075    unsigned NumArgsToCheck = NumArgs;
1076
1077    // If too few arguments are available (and we don't have default
1078    // arguments for the remaining parameters), don't make the call.
1079    if (NumArgs < NumArgsInProto) {
1080      if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
1081        // Use default arguments for missing arguments
1082        NumArgsToCheck = NumArgsInProto;
1083        TheCall->setNumArgs(NumArgsInProto);
1084      } else
1085        return Diag(RParenLoc,
1086                    !Fn->getType()->isBlockPointerType()
1087                      ? diag::err_typecheck_call_too_few_args
1088                      : diag::err_typecheck_block_too_few_args,
1089                    Fn->getSourceRange());
1090    }
1091
1092    // If too many are passed and not variadic, error on the extras and drop
1093    // them.
1094    if (NumArgs > NumArgsInProto) {
1095      if (!Proto->isVariadic()) {
1096        Diag(Args[NumArgsInProto]->getLocStart(),
1097               !Fn->getType()->isBlockPointerType()
1098                 ? diag::err_typecheck_call_too_many_args
1099                 : diag::err_typecheck_block_too_many_args,
1100             Fn->getSourceRange(),
1101             SourceRange(Args[NumArgsInProto]->getLocStart(),
1102                         Args[NumArgs-1]->getLocEnd()));
1103        // This deletes the extra arguments.
1104        TheCall->setNumArgs(NumArgsInProto);
1105      }
1106      NumArgsToCheck = NumArgsInProto;
1107    }
1108
1109    // Continue to check argument types (even if we have too few/many args).
1110    for (unsigned i = 0; i != NumArgsToCheck; i++) {
1111      QualType ProtoArgType = Proto->getArgType(i);
1112
1113      Expr *Arg;
1114      if (i < NumArgs)
1115        Arg = Args[i];
1116      else
1117        Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1118      QualType ArgType = Arg->getType();
1119
1120      // Compute implicit casts from the operand to the formal argument type.
1121      AssignConvertType ConvTy =
1122        CheckSingleAssignmentConstraints(ProtoArgType, Arg);
1123      TheCall->setArg(i, Arg);
1124
1125      if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1126                                   ArgType, Arg, "passing"))
1127        return true;
1128    }
1129
1130    // If this is a variadic call, handle args passed through "...".
1131    if (Proto->isVariadic()) {
1132      // Promote the arguments (C99 6.5.2.2p7).
1133      for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1134        Expr *Arg = Args[i];
1135        DefaultArgumentPromotion(Arg);
1136        TheCall->setArg(i, Arg);
1137      }
1138    }
1139  } else {
1140    assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1141
1142    // Promote the arguments (C99 6.5.2.2p6).
1143    for (unsigned i = 0; i != NumArgs; i++) {
1144      Expr *Arg = Args[i];
1145      DefaultArgumentPromotion(Arg);
1146      TheCall->setArg(i, Arg);
1147    }
1148  }
1149
1150  // Do special checking on direct calls to functions.
1151  if (FDecl)
1152    return CheckFunctionCall(FDecl, TheCall.take());
1153
1154  return TheCall.take();
1155}
1156
1157Action::ExprResult Sema::
1158ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1159                     SourceLocation RParenLoc, ExprTy *InitExpr) {
1160  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
1161  QualType literalType = QualType::getFromOpaquePtr(Ty);
1162  // FIXME: put back this assert when initializers are worked out.
1163  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
1164  Expr *literalExpr = static_cast<Expr*>(InitExpr);
1165
1166  if (literalType->isArrayType()) {
1167    if (literalType->isVariableArrayType())
1168      return Diag(LParenLoc,
1169                  diag::err_variable_object_no_init,
1170                  SourceRange(LParenLoc,
1171                              literalExpr->getSourceRange().getEnd()));
1172  } else if (literalType->isIncompleteType()) {
1173    return Diag(LParenLoc,
1174                diag::err_typecheck_decl_incomplete_type,
1175                literalType.getAsString(),
1176                SourceRange(LParenLoc,
1177                            literalExpr->getSourceRange().getEnd()));
1178  }
1179
1180  if (CheckInitializerTypes(literalExpr, literalType))
1181    return true;
1182
1183  bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
1184  if (isFileScope) { // 6.5.2.5p3
1185    if (CheckForConstantInitializer(literalExpr, literalType))
1186      return true;
1187  }
1188  return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
1189}
1190
1191Action::ExprResult Sema::
1192ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
1193              SourceLocation RBraceLoc) {
1194  Expr **InitList = reinterpret_cast<Expr**>(initlist);
1195
1196  // Semantic analysis for initializers is done by ActOnDeclarator() and
1197  // CheckInitializer() - it requires knowledge of the object being intialized.
1198
1199  InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1200  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1201  return E;
1202}
1203
1204/// CheckCastTypes - Check type constraints for casting between types.
1205bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
1206  UsualUnaryConversions(castExpr);
1207
1208  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1209  // type needs to be scalar.
1210  if (castType->isVoidType()) {
1211    // Cast to void allows any expr type.
1212  } else if (!castType->isScalarType() && !castType->isVectorType()) {
1213    // GCC struct/union extension: allow cast to self.
1214    if (Context.getCanonicalType(castType) !=
1215        Context.getCanonicalType(castExpr->getType()) ||
1216        (!castType->isStructureType() && !castType->isUnionType())) {
1217      // Reject any other conversions to non-scalar types.
1218      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1219                  castType.getAsString(), castExpr->getSourceRange());
1220    }
1221
1222    // accept this, but emit an ext-warn.
1223    Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1224         castType.getAsString(), castExpr->getSourceRange());
1225  } else if (!castExpr->getType()->isScalarType() &&
1226             !castExpr->getType()->isVectorType()) {
1227    return Diag(castExpr->getLocStart(),
1228                diag::err_typecheck_expect_scalar_operand,
1229                castExpr->getType().getAsString(),castExpr->getSourceRange());
1230  } else if (castExpr->getType()->isVectorType()) {
1231    if (CheckVectorCast(TyR, castExpr->getType(), castType))
1232      return true;
1233  } else if (castType->isVectorType()) {
1234    if (CheckVectorCast(TyR, castType, castExpr->getType()))
1235      return true;
1236  }
1237  return false;
1238}
1239
1240bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
1241  assert(VectorTy->isVectorType() && "Not a vector type!");
1242
1243  if (Ty->isVectorType() || Ty->isIntegerType()) {
1244    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
1245      return Diag(R.getBegin(),
1246                  Ty->isVectorType() ?
1247                  diag::err_invalid_conversion_between_vectors :
1248                  diag::err_invalid_conversion_between_vector_and_integer,
1249                  VectorTy.getAsString().c_str(),
1250                  Ty.getAsString().c_str(), R);
1251  } else
1252    return Diag(R.getBegin(),
1253                diag::err_invalid_conversion_between_vector_and_scalar,
1254                VectorTy.getAsString().c_str(),
1255                Ty.getAsString().c_str(), R);
1256
1257  return false;
1258}
1259
1260Action::ExprResult Sema::
1261ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
1262              SourceLocation RParenLoc, ExprTy *Op) {
1263  assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
1264
1265  Expr *castExpr = static_cast<Expr*>(Op);
1266  QualType castType = QualType::getFromOpaquePtr(Ty);
1267
1268  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1269    return true;
1270  return new ExplicitCastExpr(castType, castExpr, LParenLoc);
1271}
1272
1273/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1274/// In that case, lex = cond.
1275inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1276  Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1277  UsualUnaryConversions(cond);
1278  UsualUnaryConversions(lex);
1279  UsualUnaryConversions(rex);
1280  QualType condT = cond->getType();
1281  QualType lexT = lex->getType();
1282  QualType rexT = rex->getType();
1283
1284  // first, check the condition.
1285  if (!condT->isScalarType()) { // C99 6.5.15p2
1286    Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1287         condT.getAsString());
1288    return QualType();
1289  }
1290
1291  // Now check the two expressions.
1292
1293  // If both operands have arithmetic type, do the usual arithmetic conversions
1294  // to find a common type: C99 6.5.15p3,5.
1295  if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
1296    UsualArithmeticConversions(lex, rex);
1297    return lex->getType();
1298  }
1299
1300  // If both operands are the same structure or union type, the result is that
1301  // type.
1302  if (const RecordType *LHSRT = lexT->getAsRecordType()) {    // C99 6.5.15p3
1303    if (const RecordType *RHSRT = rexT->getAsRecordType())
1304      if (LHSRT->getDecl() == RHSRT->getDecl())
1305        // "If both the operands have structure or union type, the result has
1306        // that type."  This implies that CV qualifiers are dropped.
1307        return lexT.getUnqualifiedType();
1308  }
1309
1310  // C99 6.5.15p5: "If both operands have void type, the result has void type."
1311  // The following || allows only one side to be void (a GCC-ism).
1312  if (lexT->isVoidType() || rexT->isVoidType()) {
1313    if (!lexT->isVoidType())
1314      Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1315           rex->getSourceRange());
1316    if (!rexT->isVoidType())
1317      Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
1318           lex->getSourceRange());
1319    ImpCastExprToType(lex, Context.VoidTy);
1320    ImpCastExprToType(rex, Context.VoidTy);
1321    return Context.VoidTy;
1322  }
1323  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1324  // the type of the other operand."
1325  if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1326       Context.isObjCObjectPointerType(lexT)) &&
1327      rex->isNullPointerConstant(Context)) {
1328    ImpCastExprToType(rex, lexT); // promote the null to a pointer.
1329    return lexT;
1330  }
1331  if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1332       Context.isObjCObjectPointerType(rexT)) &&
1333      lex->isNullPointerConstant(Context)) {
1334    ImpCastExprToType(lex, rexT); // promote the null to a pointer.
1335    return rexT;
1336  }
1337  // Handle the case where both operands are pointers before we handle null
1338  // pointer constants in case both operands are null pointer constants.
1339  if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1340    if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1341      // get the "pointed to" types
1342      QualType lhptee = LHSPT->getPointeeType();
1343      QualType rhptee = RHSPT->getPointeeType();
1344
1345      // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1346      if (lhptee->isVoidType() &&
1347          rhptee->isIncompleteOrObjectType()) {
1348        // Figure out necessary qualifiers (C99 6.5.15p6)
1349        QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
1350        QualType destType = Context.getPointerType(destPointee);
1351        ImpCastExprToType(lex, destType); // add qualifiers if necessary
1352        ImpCastExprToType(rex, destType); // promote to void*
1353        return destType;
1354      }
1355      if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
1356        QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
1357        QualType destType = Context.getPointerType(destPointee);
1358        ImpCastExprToType(lex, destType); // add qualifiers if necessary
1359        ImpCastExprToType(rex, destType); // promote to void*
1360        return destType;
1361      }
1362
1363      QualType compositeType = lexT;
1364
1365      // If either type is an Objective-C object type then check
1366      // compatibility according to Objective-C.
1367      if (Context.isObjCObjectPointerType(lexT) ||
1368          Context.isObjCObjectPointerType(rexT)) {
1369        // If both operands are interfaces and either operand can be
1370        // assigned to the other, use that type as the composite
1371        // type. This allows
1372        //   xxx ? (A*) a : (B*) b
1373        // where B is a subclass of A.
1374        //
1375        // Additionally, as for assignment, if either type is 'id'
1376        // allow silent coercion. Finally, if the types are
1377        // incompatible then make sure to use 'id' as the composite
1378        // type so the result is acceptable for sending messages to.
1379
1380        // FIXME: This code should not be localized to here. Also this
1381        // should use a compatible check instead of abusing the
1382        // canAssignObjCInterfaces code.
1383        const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1384        const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1385        if (LHSIface && RHSIface &&
1386            Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1387          compositeType = lexT;
1388        } else if (LHSIface && RHSIface &&
1389                   Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1390          compositeType = rexT;
1391        } else if (Context.isObjCIdType(lhptee) ||
1392                   Context.isObjCIdType(rhptee)) {
1393          // FIXME: This code looks wrong, because isObjCIdType checks
1394          // the struct but getObjCIdType returns the pointer to
1395          // struct. This is horrible and should be fixed.
1396          compositeType = Context.getObjCIdType();
1397        } else {
1398          QualType incompatTy = Context.getObjCIdType();
1399          ImpCastExprToType(lex, incompatTy);
1400          ImpCastExprToType(rex, incompatTy);
1401          return incompatTy;
1402        }
1403      } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1404                                             rhptee.getUnqualifiedType())) {
1405        Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
1406             lexT.getAsString(), rexT.getAsString(),
1407             lex->getSourceRange(), rex->getSourceRange());
1408        // In this situation, we assume void* type. No especially good
1409        // reason, but this is what gcc does, and we do have to pick
1410        // to get a consistent AST.
1411        QualType incompatTy = Context.getPointerType(Context.VoidTy);
1412        ImpCastExprToType(lex, incompatTy);
1413        ImpCastExprToType(rex, incompatTy);
1414        return incompatTy;
1415      }
1416      // The pointer types are compatible.
1417      // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1418      // differently qualified versions of compatible types, the result type is
1419      // a pointer to an appropriately qualified version of the *composite*
1420      // type.
1421      // FIXME: Need to calculate the composite type.
1422      // FIXME: Need to add qualifiers
1423      ImpCastExprToType(lex, compositeType);
1424      ImpCastExprToType(rex, compositeType);
1425      return compositeType;
1426    }
1427  }
1428  // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1429  // evaluates to "struct objc_object *" (and is handled above when comparing
1430  // id with statically typed objects).
1431  if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1432    // GCC allows qualified id and any Objective-C type to devolve to
1433    // id. Currently localizing to here until clear this should be
1434    // part of ObjCQualifiedIdTypesAreCompatible.
1435    if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1436        (lexT->isObjCQualifiedIdType() &&
1437         Context.isObjCObjectPointerType(rexT)) ||
1438        (rexT->isObjCQualifiedIdType() &&
1439         Context.isObjCObjectPointerType(lexT))) {
1440      // FIXME: This is not the correct composite type. This only
1441      // happens to work because id can more or less be used anywhere,
1442      // however this may change the type of method sends.
1443      // FIXME: gcc adds some type-checking of the arguments and emits
1444      // (confusing) incompatible comparison warnings in some
1445      // cases. Investigate.
1446      QualType compositeType = Context.getObjCIdType();
1447      ImpCastExprToType(lex, compositeType);
1448      ImpCastExprToType(rex, compositeType);
1449      return compositeType;
1450    }
1451  }
1452
1453  // Selection between block pointer types is ok as long as they are the same.
1454  if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1455      Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1456    return lexT;
1457
1458  // Otherwise, the operands are not compatible.
1459  Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1460       lexT.getAsString(), rexT.getAsString(),
1461       lex->getSourceRange(), rex->getSourceRange());
1462  return QualType();
1463}
1464
1465/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
1466/// in the case of a the GNU conditional expr extension.
1467Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
1468                                            SourceLocation ColonLoc,
1469                                            ExprTy *Cond, ExprTy *LHS,
1470                                            ExprTy *RHS) {
1471  Expr *CondExpr = (Expr *) Cond;
1472  Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
1473
1474  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1475  // was the condition.
1476  bool isLHSNull = LHSExpr == 0;
1477  if (isLHSNull)
1478    LHSExpr = CondExpr;
1479
1480  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1481                                             RHSExpr, QuestionLoc);
1482  if (result.isNull())
1483    return true;
1484  return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1485                                 RHSExpr, result);
1486}
1487
1488
1489// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1490// being closely modeled after the C99 spec:-). The odd characteristic of this
1491// routine is it effectively iqnores the qualifiers on the top level pointee.
1492// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1493// FIXME: add a couple examples in this comment.
1494Sema::AssignConvertType
1495Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1496  QualType lhptee, rhptee;
1497
1498  // get the "pointed to" type (ignoring qualifiers at the top level)
1499  lhptee = lhsType->getAsPointerType()->getPointeeType();
1500  rhptee = rhsType->getAsPointerType()->getPointeeType();
1501
1502  // make sure we operate on the canonical type
1503  lhptee = Context.getCanonicalType(lhptee);
1504  rhptee = Context.getCanonicalType(rhptee);
1505
1506  AssignConvertType ConvTy = Compatible;
1507
1508  // C99 6.5.16.1p1: This following citation is common to constraints
1509  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1510  // qualifiers of the type *pointed to* by the right;
1511  // FIXME: Handle ASQualType
1512  if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1513       rhptee.getCVRQualifiers())
1514    ConvTy = CompatiblePointerDiscardsQualifiers;
1515
1516  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1517  // incomplete type and the other is a pointer to a qualified or unqualified
1518  // version of void...
1519  if (lhptee->isVoidType()) {
1520    if (rhptee->isIncompleteOrObjectType())
1521      return ConvTy;
1522
1523    // As an extension, we allow cast to/from void* to function pointer.
1524    assert(rhptee->isFunctionType());
1525    return FunctionVoidPointer;
1526  }
1527
1528  if (rhptee->isVoidType()) {
1529    if (lhptee->isIncompleteOrObjectType())
1530      return ConvTy;
1531
1532    // As an extension, we allow cast to/from void* to function pointer.
1533    assert(lhptee->isFunctionType());
1534    return FunctionVoidPointer;
1535  }
1536
1537  // Check for ObjC interfaces
1538  const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1539  const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1540  if (LHSIface && RHSIface &&
1541      Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1542    return ConvTy;
1543
1544  // ID acts sort of like void* for ObjC interfaces
1545  if (LHSIface && Context.isObjCIdType(rhptee))
1546    return ConvTy;
1547  if (RHSIface && Context.isObjCIdType(lhptee))
1548    return ConvTy;
1549
1550  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1551  // unqualified versions of compatible types, ...
1552  if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1553                                  rhptee.getUnqualifiedType()))
1554    return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1555  return ConvTy;
1556}
1557
1558/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1559/// block pointer types are compatible or whether a block and normal pointer
1560/// are compatible. It is more restrict than comparing two function pointer
1561// types.
1562Sema::AssignConvertType
1563Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1564                                          QualType rhsType) {
1565  QualType lhptee, rhptee;
1566
1567  // get the "pointed to" type (ignoring qualifiers at the top level)
1568  lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1569  rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1570
1571  // make sure we operate on the canonical type
1572  lhptee = Context.getCanonicalType(lhptee);
1573  rhptee = Context.getCanonicalType(rhptee);
1574
1575  AssignConvertType ConvTy = Compatible;
1576
1577  // For blocks we enforce that qualifiers are identical.
1578  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1579    ConvTy = CompatiblePointerDiscardsQualifiers;
1580
1581  if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1582    return IncompatibleBlockPointer;
1583  return ConvTy;
1584}
1585
1586/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1587/// has code to accommodate several GCC extensions when type checking
1588/// pointers. Here are some objectionable examples that GCC considers warnings:
1589///
1590///  int a, *pint;
1591///  short *pshort;
1592///  struct foo *pfoo;
1593///
1594///  pint = pshort; // warning: assignment from incompatible pointer type
1595///  a = pint; // warning: assignment makes integer from pointer without a cast
1596///  pint = a; // warning: assignment makes pointer from integer without a cast
1597///  pint = pfoo; // warning: assignment from incompatible pointer type
1598///
1599/// As a result, the code for dealing with pointers is more complex than the
1600/// C99 spec dictates.
1601///
1602Sema::AssignConvertType
1603Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
1604  // Get canonical types.  We're not formatting these types, just comparing
1605  // them.
1606  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1607  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
1608
1609  if (lhsType == rhsType)
1610    return Compatible; // Common case: fast path an exact match.
1611
1612  if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1613    if (Context.typesAreCompatible(lhsType, rhsType))
1614      return Compatible;
1615    return Incompatible;
1616  }
1617
1618  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1619    if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
1620      return Compatible;
1621    // Relax integer conversions like we do for pointers below.
1622    if (rhsType->isIntegerType())
1623      return IntToPointer;
1624    if (lhsType->isIntegerType())
1625      return PointerToInt;
1626    return Incompatible;
1627  }
1628
1629  if (lhsType->isVectorType() || rhsType->isVectorType()) {
1630    // For ExtVector, allow vector splats; float -> <n x float>
1631    if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1632      if (LV->getElementType() == rhsType)
1633        return Compatible;
1634
1635    // If we are allowing lax vector conversions, and LHS and RHS are both
1636    // vectors, the total size only needs to be the same. This is a bitcast;
1637    // no bits are changed but the result type is different.
1638    if (getLangOptions().LaxVectorConversions &&
1639        lhsType->isVectorType() && rhsType->isVectorType()) {
1640      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1641        return Compatible;
1642    }
1643    return Incompatible;
1644  }
1645
1646  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
1647    return Compatible;
1648
1649  if (isa<PointerType>(lhsType)) {
1650    if (rhsType->isIntegerType())
1651      return IntToPointer;
1652
1653    if (isa<PointerType>(rhsType))
1654      return CheckPointerTypesForAssignment(lhsType, rhsType);
1655
1656    if (rhsType->getAsBlockPointerType()) {
1657      if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
1658        return BlockVoidPointer;
1659
1660      // Treat block pointers as objects.
1661      if (getLangOptions().ObjC1 &&
1662          lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1663        return Compatible;
1664    }
1665    return Incompatible;
1666  }
1667
1668  if (isa<BlockPointerType>(lhsType)) {
1669    if (rhsType->isIntegerType())
1670      return IntToPointer;
1671
1672    // Treat block pointers as objects.
1673    if (getLangOptions().ObjC1 &&
1674        rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1675      return Compatible;
1676
1677    if (rhsType->isBlockPointerType())
1678      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1679
1680    if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1681      if (RHSPT->getPointeeType()->isVoidType())
1682        return BlockVoidPointer;
1683    }
1684    return Incompatible;
1685  }
1686
1687  if (isa<PointerType>(rhsType)) {
1688    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1689    if (lhsType == Context.BoolTy)
1690      return Compatible;
1691
1692    if (lhsType->isIntegerType())
1693      return PointerToInt;
1694
1695    if (isa<PointerType>(lhsType))
1696      return CheckPointerTypesForAssignment(lhsType, rhsType);
1697
1698    if (isa<BlockPointerType>(lhsType) &&
1699        rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1700      return BlockVoidPointer;
1701    return Incompatible;
1702  }
1703
1704  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1705    if (Context.typesAreCompatible(lhsType, rhsType))
1706      return Compatible;
1707  }
1708  return Incompatible;
1709}
1710
1711Sema::AssignConvertType
1712Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1713  // C99 6.5.16.1p1: the left operand is a pointer and the right is
1714  // a null pointer constant.
1715  if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1716       lhsType->isBlockPointerType())
1717      && rExpr->isNullPointerConstant(Context)) {
1718    ImpCastExprToType(rExpr, lhsType);
1719    return Compatible;
1720  }
1721
1722  // We don't allow conversion of non-null-pointer constants to integers.
1723  if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1724    return IntToBlockPointer;
1725
1726  // This check seems unnatural, however it is necessary to ensure the proper
1727  // conversion of functions/arrays. If the conversion were done for all
1728  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
1729  // expressions that surpress this implicit conversion (&, sizeof).
1730  //
1731  // Suppress this for references: C99 8.5.3p5.  FIXME: revisit when references
1732  // are better understood.
1733  if (!lhsType->isReferenceType())
1734    DefaultFunctionArrayConversion(rExpr);
1735
1736  Sema::AssignConvertType result =
1737    CheckAssignmentConstraints(lhsType, rExpr->getType());
1738
1739  // C99 6.5.16.1p2: The value of the right operand is converted to the
1740  // type of the assignment expression.
1741  if (rExpr->getType() != lhsType)
1742    ImpCastExprToType(rExpr, lhsType);
1743  return result;
1744}
1745
1746Sema::AssignConvertType
1747Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1748  return CheckAssignmentConstraints(lhsType, rhsType);
1749}
1750
1751QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1752  Diag(loc, diag::err_typecheck_invalid_operands,
1753       lex->getType().getAsString(), rex->getType().getAsString(),
1754       lex->getSourceRange(), rex->getSourceRange());
1755  return QualType();
1756}
1757
1758inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1759                                                              Expr *&rex) {
1760  // For conversion purposes, we ignore any qualifiers.
1761  // For example, "const float" and "float" are equivalent.
1762  QualType lhsType =
1763    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1764  QualType rhsType =
1765    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
1766
1767  // If the vector types are identical, return.
1768  if (lhsType == rhsType)
1769    return lhsType;
1770
1771  // Handle the case of a vector & extvector type of the same size and element
1772  // type.  It would be nice if we only had one vector type someday.
1773  if (getLangOptions().LaxVectorConversions)
1774    if (const VectorType *LV = lhsType->getAsVectorType())
1775      if (const VectorType *RV = rhsType->getAsVectorType())
1776        if (LV->getElementType() == RV->getElementType() &&
1777            LV->getNumElements() == RV->getNumElements())
1778          return lhsType->isExtVectorType() ? lhsType : rhsType;
1779
1780  // If the lhs is an extended vector and the rhs is a scalar of the same type
1781  // or a literal, promote the rhs to the vector type.
1782  if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
1783    QualType eltType = V->getElementType();
1784
1785    if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1786        (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1787        (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
1788      ImpCastExprToType(rex, lhsType);
1789      return lhsType;
1790    }
1791  }
1792
1793  // If the rhs is an extended vector and the lhs is a scalar of the same type,
1794  // promote the lhs to the vector type.
1795  if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
1796    QualType eltType = V->getElementType();
1797
1798    if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1799        (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1800        (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
1801      ImpCastExprToType(lex, rhsType);
1802      return rhsType;
1803    }
1804  }
1805
1806  // You cannot convert between vector values of different size.
1807  Diag(loc, diag::err_typecheck_vector_not_convertable,
1808       lex->getType().getAsString(), rex->getType().getAsString(),
1809       lex->getSourceRange(), rex->getSourceRange());
1810  return QualType();
1811}
1812
1813inline QualType Sema::CheckMultiplyDivideOperands(
1814  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1815{
1816  QualType lhsType = lex->getType(), rhsType = rex->getType();
1817
1818  if (lhsType->isVectorType() || rhsType->isVectorType())
1819    return CheckVectorOperands(loc, lex, rex);
1820
1821  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1822
1823  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1824    return compType;
1825  return InvalidOperands(loc, lex, rex);
1826}
1827
1828inline QualType Sema::CheckRemainderOperands(
1829  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1830{
1831  QualType lhsType = lex->getType(), rhsType = rex->getType();
1832
1833  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1834
1835  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1836    return compType;
1837  return InvalidOperands(loc, lex, rex);
1838}
1839
1840inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
1841  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1842{
1843  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1844    return CheckVectorOperands(loc, lex, rex);
1845
1846  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1847
1848  // handle the common case first (both operands are arithmetic).
1849  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1850    return compType;
1851
1852  // Put any potential pointer into PExp
1853  Expr* PExp = lex, *IExp = rex;
1854  if (IExp->getType()->isPointerType())
1855    std::swap(PExp, IExp);
1856
1857  if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1858    if (IExp->getType()->isIntegerType()) {
1859      // Check for arithmetic on pointers to incomplete types
1860      if (!PTy->getPointeeType()->isObjectType()) {
1861        if (PTy->getPointeeType()->isVoidType()) {
1862          Diag(loc, diag::ext_gnu_void_ptr,
1863               lex->getSourceRange(), rex->getSourceRange());
1864        } else {
1865          Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1866               lex->getType().getAsString(), lex->getSourceRange());
1867          return QualType();
1868        }
1869      }
1870      return PExp->getType();
1871    }
1872  }
1873
1874  return InvalidOperands(loc, lex, rex);
1875}
1876
1877// C99 6.5.6
1878QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1879                                        SourceLocation loc, bool isCompAssign) {
1880  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1881    return CheckVectorOperands(loc, lex, rex);
1882
1883  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1884
1885  // Enforce type constraints: C99 6.5.6p3.
1886
1887  // Handle the common case first (both operands are arithmetic).
1888  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1889    return compType;
1890
1891  // Either ptr - int   or   ptr - ptr.
1892  if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1893    QualType lpointee = LHSPTy->getPointeeType();
1894
1895    // The LHS must be an object type, not incomplete, function, etc.
1896    if (!lpointee->isObjectType()) {
1897      // Handle the GNU void* extension.
1898      if (lpointee->isVoidType()) {
1899        Diag(loc, diag::ext_gnu_void_ptr,
1900             lex->getSourceRange(), rex->getSourceRange());
1901      } else {
1902        Diag(loc, diag::err_typecheck_sub_ptr_object,
1903             lex->getType().getAsString(), lex->getSourceRange());
1904        return QualType();
1905      }
1906    }
1907
1908    // The result type of a pointer-int computation is the pointer type.
1909    if (rex->getType()->isIntegerType())
1910      return lex->getType();
1911
1912    // Handle pointer-pointer subtractions.
1913    if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1914      QualType rpointee = RHSPTy->getPointeeType();
1915
1916      // RHS must be an object type, unless void (GNU).
1917      if (!rpointee->isObjectType()) {
1918        // Handle the GNU void* extension.
1919        if (rpointee->isVoidType()) {
1920          if (!lpointee->isVoidType())
1921            Diag(loc, diag::ext_gnu_void_ptr,
1922                 lex->getSourceRange(), rex->getSourceRange());
1923        } else {
1924          Diag(loc, diag::err_typecheck_sub_ptr_object,
1925               rex->getType().getAsString(), rex->getSourceRange());
1926          return QualType();
1927        }
1928      }
1929
1930      // Pointee types must be compatible.
1931      if (!Context.typesAreCompatible(
1932              Context.getCanonicalType(lpointee).getUnqualifiedType(),
1933              Context.getCanonicalType(rpointee).getUnqualifiedType())) {
1934        Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1935             lex->getType().getAsString(), rex->getType().getAsString(),
1936             lex->getSourceRange(), rex->getSourceRange());
1937        return QualType();
1938      }
1939
1940      return Context.getPointerDiffType();
1941    }
1942  }
1943
1944  return InvalidOperands(loc, lex, rex);
1945}
1946
1947// C99 6.5.7
1948QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1949                                  bool isCompAssign) {
1950  // C99 6.5.7p2: Each of the operands shall have integer type.
1951  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1952    return InvalidOperands(loc, lex, rex);
1953
1954  // Shifts don't perform usual arithmetic conversions, they just do integer
1955  // promotions on each operand. C99 6.5.7p3
1956  if (!isCompAssign)
1957    UsualUnaryConversions(lex);
1958  UsualUnaryConversions(rex);
1959
1960  // "The type of the result is that of the promoted left operand."
1961  return lex->getType();
1962}
1963
1964static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1965                                        ASTContext& Context) {
1966  const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1967  const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1968  // ID acts sort of like void* for ObjC interfaces
1969  if (LHSIface && Context.isObjCIdType(RHS))
1970    return true;
1971  if (RHSIface && Context.isObjCIdType(LHS))
1972    return true;
1973  if (!LHSIface || !RHSIface)
1974    return false;
1975  return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1976         Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1977}
1978
1979// C99 6.5.8
1980QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1981                                    bool isRelational) {
1982  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1983    return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1984
1985  // C99 6.5.8p3 / C99 6.5.9p4
1986  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1987    UsualArithmeticConversions(lex, rex);
1988  else {
1989    UsualUnaryConversions(lex);
1990    UsualUnaryConversions(rex);
1991  }
1992  QualType lType = lex->getType();
1993  QualType rType = rex->getType();
1994
1995  // For non-floating point types, check for self-comparisons of the form
1996  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
1997  // often indicate logic errors in the program.
1998  if (!lType->isFloatingType()) {
1999    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2000      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2001        if (DRL->getDecl() == DRR->getDecl())
2002          Diag(loc, diag::warn_selfcomparison);
2003  }
2004
2005  if (isRelational) {
2006    if (lType->isRealType() && rType->isRealType())
2007      return Context.IntTy;
2008  } else {
2009    // Check for comparisons of floating point operands using != and ==.
2010    if (lType->isFloatingType()) {
2011      assert (rType->isFloatingType());
2012      CheckFloatComparison(loc,lex,rex);
2013    }
2014
2015    if (lType->isArithmeticType() && rType->isArithmeticType())
2016      return Context.IntTy;
2017  }
2018
2019  bool LHSIsNull = lex->isNullPointerConstant(Context);
2020  bool RHSIsNull = rex->isNullPointerConstant(Context);
2021
2022  // All of the following pointer related warnings are GCC extensions, except
2023  // when handling null pointer constants. One day, we can consider making them
2024  // errors (when -pedantic-errors is enabled).
2025  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
2026    QualType LCanPointeeTy =
2027      Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
2028    QualType RCanPointeeTy =
2029      Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
2030
2031    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
2032        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2033        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
2034                                    RCanPointeeTy.getUnqualifiedType()) &&
2035        !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
2036      Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2037           lType.getAsString(), rType.getAsString(),
2038           lex->getSourceRange(), rex->getSourceRange());
2039    }
2040    ImpCastExprToType(rex, lType); // promote the pointer to pointer
2041    return Context.IntTy;
2042  }
2043  // Handle block pointer types.
2044  if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2045    QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2046    QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2047
2048    if (!LHSIsNull && !RHSIsNull &&
2049        !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2050      Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2051           lType.getAsString(), rType.getAsString(),
2052           lex->getSourceRange(), rex->getSourceRange());
2053    }
2054    ImpCastExprToType(rex, lType); // promote the pointer to pointer
2055    return Context.IntTy;
2056  }
2057  // Allow block pointers to be compared with null pointer constants.
2058  if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2059      (lType->isPointerType() && rType->isBlockPointerType())) {
2060    if (!LHSIsNull && !RHSIsNull) {
2061      Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2062           lType.getAsString(), rType.getAsString(),
2063           lex->getSourceRange(), rex->getSourceRange());
2064    }
2065    ImpCastExprToType(rex, lType); // promote the pointer to pointer
2066    return Context.IntTy;
2067  }
2068
2069  if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
2070    if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2071      ImpCastExprToType(rex, lType);
2072      return Context.IntTy;
2073    }
2074  }
2075  if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2076       rType->isIntegerType()) {
2077    if (!RHSIsNull)
2078      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2079           lType.getAsString(), rType.getAsString(),
2080           lex->getSourceRange(), rex->getSourceRange());
2081    ImpCastExprToType(rex, lType); // promote the integer to pointer
2082    return Context.IntTy;
2083  }
2084  if (lType->isIntegerType() &&
2085      (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
2086    if (!LHSIsNull)
2087      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2088           lType.getAsString(), rType.getAsString(),
2089           lex->getSourceRange(), rex->getSourceRange());
2090    ImpCastExprToType(lex, rType); // promote the integer to pointer
2091    return Context.IntTy;
2092  }
2093  // Handle block pointers.
2094  if (lType->isBlockPointerType() && rType->isIntegerType()) {
2095    if (!RHSIsNull)
2096      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2097           lType.getAsString(), rType.getAsString(),
2098           lex->getSourceRange(), rex->getSourceRange());
2099    ImpCastExprToType(rex, lType); // promote the integer to pointer
2100    return Context.IntTy;
2101  }
2102  if (lType->isIntegerType() && rType->isBlockPointerType()) {
2103    if (!LHSIsNull)
2104      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2105           lType.getAsString(), rType.getAsString(),
2106           lex->getSourceRange(), rex->getSourceRange());
2107    ImpCastExprToType(lex, rType); // promote the integer to pointer
2108    return Context.IntTy;
2109  }
2110  return InvalidOperands(loc, lex, rex);
2111}
2112
2113/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2114/// operates on extended vector types.  Instead of producing an IntTy result,
2115/// like a scalar comparison, a vector comparison produces a vector of integer
2116/// types.
2117QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2118                                          SourceLocation loc,
2119                                          bool isRelational) {
2120  // Check to make sure we're operating on vectors of the same type and width,
2121  // Allowing one side to be a scalar of element type.
2122  QualType vType = CheckVectorOperands(loc, lex, rex);
2123  if (vType.isNull())
2124    return vType;
2125
2126  QualType lType = lex->getType();
2127  QualType rType = rex->getType();
2128
2129  // For non-floating point types, check for self-comparisons of the form
2130  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
2131  // often indicate logic errors in the program.
2132  if (!lType->isFloatingType()) {
2133    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2134      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2135        if (DRL->getDecl() == DRR->getDecl())
2136          Diag(loc, diag::warn_selfcomparison);
2137  }
2138
2139  // Check for comparisons of floating point operands using != and ==.
2140  if (!isRelational && lType->isFloatingType()) {
2141    assert (rType->isFloatingType());
2142    CheckFloatComparison(loc,lex,rex);
2143  }
2144
2145  // Return the type for the comparison, which is the same as vector type for
2146  // integer vectors, or an integer type of identical size and number of
2147  // elements for floating point vectors.
2148  if (lType->isIntegerType())
2149    return lType;
2150
2151  const VectorType *VTy = lType->getAsVectorType();
2152
2153  // FIXME: need to deal with non-32b int / non-64b long long
2154  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2155  if (TypeSize == 32) {
2156    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2157  }
2158  assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2159  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2160}
2161
2162inline QualType Sema::CheckBitwiseOperands(
2163  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
2164{
2165  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2166    return CheckVectorOperands(loc, lex, rex);
2167
2168  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2169
2170  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2171    return compType;
2172  return InvalidOperands(loc, lex, rex);
2173}
2174
2175inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2176  Expr *&lex, Expr *&rex, SourceLocation loc)
2177{
2178  UsualUnaryConversions(lex);
2179  UsualUnaryConversions(rex);
2180
2181  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
2182    return Context.IntTy;
2183  return InvalidOperands(loc, lex, rex);
2184}
2185
2186inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
2187  Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
2188{
2189  QualType lhsType = lex->getType();
2190  QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
2191  Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
2192
2193  switch (mlval) { // C99 6.5.16p2
2194  case Expr::MLV_Valid:
2195    break;
2196  case Expr::MLV_ConstQualified:
2197    Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2198    return QualType();
2199  case Expr::MLV_ArrayType:
2200    Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2201         lhsType.getAsString(), lex->getSourceRange());
2202    return QualType();
2203  case Expr::MLV_NotObjectType:
2204    Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2205         lhsType.getAsString(), lex->getSourceRange());
2206    return QualType();
2207  case Expr::MLV_InvalidExpression:
2208    Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2209         lex->getSourceRange());
2210    return QualType();
2211  case Expr::MLV_IncompleteType:
2212  case Expr::MLV_IncompleteVoidType:
2213    Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2214         lhsType.getAsString(), lex->getSourceRange());
2215    return QualType();
2216  case Expr::MLV_DuplicateVectorComponents:
2217    Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2218         lex->getSourceRange());
2219    return QualType();
2220  case Expr::MLV_NotBlockQualified:
2221    Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2222         lex->getSourceRange());
2223    return QualType();
2224  }
2225
2226  AssignConvertType ConvTy;
2227  if (compoundType.isNull()) {
2228    // Simple assignment "x = y".
2229    ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
2230
2231    // If the RHS is a unary plus or minus, check to see if they = and + are
2232    // right next to each other.  If so, the user may have typo'd "x =+ 4"
2233    // instead of "x += 4".
2234    Expr *RHSCheck = rex;
2235    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2236      RHSCheck = ICE->getSubExpr();
2237    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2238      if ((UO->getOpcode() == UnaryOperator::Plus ||
2239           UO->getOpcode() == UnaryOperator::Minus) &&
2240          loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2241          // Only if the two operators are exactly adjacent.
2242          loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2243        Diag(loc, diag::warn_not_compound_assign,
2244             UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2245             SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2246    }
2247  } else {
2248    // Compound assignment "x += y"
2249    ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
2250  }
2251
2252  if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2253                               rex, "assigning"))
2254    return QualType();
2255
2256  // C99 6.5.16p3: The type of an assignment expression is the type of the
2257  // left operand unless the left operand has qualified type, in which case
2258  // it is the unqualified version of the type of the left operand.
2259  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2260  // is converted to the type of the assignment expression (above).
2261  // C++ 5.17p1: the type of the assignment expression is that of its left
2262  // oprdu.
2263  return lhsType.getUnqualifiedType();
2264}
2265
2266inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2267  Expr *&lex, Expr *&rex, SourceLocation loc) {
2268
2269  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2270  DefaultFunctionArrayConversion(rex);
2271  return rex->getType();
2272}
2273
2274/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2275/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2276QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2277  QualType resType = op->getType();
2278  assert(!resType.isNull() && "no type for increment/decrement expression");
2279
2280  // C99 6.5.2.4p1: We allow complex as a GCC extension.
2281  if (const PointerType *pt = resType->getAsPointerType()) {
2282    if (pt->getPointeeType()->isVoidType()) {
2283      Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2284    } else if (!pt->getPointeeType()->isObjectType()) {
2285      // C99 6.5.2.4p2, 6.5.6p2
2286      Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2287           resType.getAsString(), op->getSourceRange());
2288      return QualType();
2289    }
2290  } else if (!resType->isRealType()) {
2291    if (resType->isComplexType())
2292      // C99 does not support ++/-- on complex types.
2293      Diag(OpLoc, diag::ext_integer_increment_complex,
2294           resType.getAsString(), op->getSourceRange());
2295    else {
2296      Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2297           resType.getAsString(), op->getSourceRange());
2298      return QualType();
2299    }
2300  }
2301  // At this point, we know we have a real, complex or pointer type.
2302  // Now make sure the operand is a modifiable lvalue.
2303  Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
2304  if (mlval != Expr::MLV_Valid) {
2305    // FIXME: emit a more precise diagnostic...
2306    Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2307         op->getSourceRange());
2308    return QualType();
2309  }
2310  return resType;
2311}
2312
2313/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
2314/// This routine allows us to typecheck complex/recursive expressions
2315/// where the declaration is needed for type checking. We only need to
2316/// handle cases when the expression references a function designator
2317/// or is an lvalue. Here are some examples:
2318///  - &(x) => x
2319///  - &*****f => f for f a function designator.
2320///  - &s.xx => s
2321///  - &s.zz[1].yy -> s, if zz is an array
2322///  - *(x + 1) -> x, if x is an array
2323///  - &"123"[2] -> 0
2324///  - & __real__ x -> x
2325static ValueDecl *getPrimaryDecl(Expr *E) {
2326  switch (E->getStmtClass()) {
2327  case Stmt::DeclRefExprClass:
2328    return cast<DeclRefExpr>(E)->getDecl();
2329  case Stmt::MemberExprClass:
2330    // Fields cannot be declared with a 'register' storage class.
2331    // &X->f is always ok, even if X is declared register.
2332    if (cast<MemberExpr>(E)->isArrow())
2333      return 0;
2334    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
2335  case Stmt::ArraySubscriptExprClass: {
2336    // &X[4] and &4[X] refers to X if X is not a pointer.
2337
2338    ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
2339    if (!VD || VD->getType()->isPointerType())
2340      return 0;
2341    else
2342      return VD;
2343  }
2344  case Stmt::UnaryOperatorClass: {
2345    UnaryOperator *UO = cast<UnaryOperator>(E);
2346
2347    switch(UO->getOpcode()) {
2348    case UnaryOperator::Deref: {
2349      // *(X + 1) refers to X if X is not a pointer.
2350      ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2351      if (!VD || VD->getType()->isPointerType())
2352        return 0;
2353      return VD;
2354    }
2355    case UnaryOperator::Real:
2356    case UnaryOperator::Imag:
2357    case UnaryOperator::Extension:
2358      return getPrimaryDecl(UO->getSubExpr());
2359    default:
2360      return 0;
2361    }
2362  }
2363  case Stmt::BinaryOperatorClass: {
2364    BinaryOperator *BO = cast<BinaryOperator>(E);
2365
2366    // Handle cases involving pointer arithmetic. The result of an
2367    // Assign or AddAssign is not an lvalue so they can be ignored.
2368
2369    // (x + n) or (n + x) => x
2370    if (BO->getOpcode() == BinaryOperator::Add) {
2371      if (BO->getLHS()->getType()->isPointerType()) {
2372        return getPrimaryDecl(BO->getLHS());
2373      } else if (BO->getRHS()->getType()->isPointerType()) {
2374        return getPrimaryDecl(BO->getRHS());
2375      }
2376    }
2377
2378    return 0;
2379  }
2380  case Stmt::ParenExprClass:
2381    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
2382  case Stmt::ImplicitCastExprClass:
2383    // &X[4] when X is an array, has an implicit cast from array to pointer.
2384    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
2385  default:
2386    return 0;
2387  }
2388}
2389
2390/// CheckAddressOfOperand - The operand of & must be either a function
2391/// designator or an lvalue designating an object. If it is an lvalue, the
2392/// object cannot be declared with storage class register or be a bit field.
2393/// Note: The usual conversions are *not* applied to the operand of the &
2394/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2395QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
2396  if (getLangOptions().C99) {
2397    // Implement C99-only parts of addressof rules.
2398    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2399      if (uOp->getOpcode() == UnaryOperator::Deref)
2400        // Per C99 6.5.3.2, the address of a deref always returns a valid result
2401        // (assuming the deref expression is valid).
2402        return uOp->getSubExpr()->getType();
2403    }
2404    // Technically, there should be a check for array subscript
2405    // expressions here, but the result of one is always an lvalue anyway.
2406  }
2407  ValueDecl *dcl = getPrimaryDecl(op);
2408  Expr::isLvalueResult lval = op->isLvalue(Context);
2409
2410  if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
2411    if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2412      // FIXME: emit more specific diag...
2413      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2414           op->getSourceRange());
2415      return QualType();
2416    }
2417  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2418    if (MemExpr->getMemberDecl()->isBitField()) {
2419      Diag(OpLoc, diag::err_typecheck_address_of,
2420           std::string("bit-field"), op->getSourceRange());
2421      return QualType();
2422    }
2423  // Check for Apple extension for accessing vector components.
2424  } else if (isa<ArraySubscriptExpr>(op) &&
2425           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2426    Diag(OpLoc, diag::err_typecheck_address_of,
2427         std::string("vector"), op->getSourceRange());
2428    return QualType();
2429  } else if (dcl) { // C99 6.5.3.2p1
2430    // We have an lvalue with a decl. Make sure the decl is not declared
2431    // with the register storage-class specifier.
2432    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2433      if (vd->getStorageClass() == VarDecl::Register) {
2434        Diag(OpLoc, diag::err_typecheck_address_of,
2435             std::string("register variable"), op->getSourceRange());
2436        return QualType();
2437      }
2438    } else
2439      assert(0 && "Unknown/unexpected decl type");
2440  }
2441
2442  // If the operand has type "type", the result has type "pointer to type".
2443  return Context.getPointerType(op->getType());
2444}
2445
2446QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2447  UsualUnaryConversions(op);
2448  QualType qType = op->getType();
2449
2450  if (const PointerType *PT = qType->getAsPointerType()) {
2451    // Note that per both C89 and C99, this is always legal, even
2452    // if ptype is an incomplete type or void.
2453    // It would be possible to warn about dereferencing a
2454    // void pointer, but it's completely well-defined,
2455    // and such a warning is unlikely to catch any mistakes.
2456    return PT->getPointeeType();
2457  }
2458  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2459       qType.getAsString(), op->getSourceRange());
2460  return QualType();
2461}
2462
2463static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2464  tok::TokenKind Kind) {
2465  BinaryOperator::Opcode Opc;
2466  switch (Kind) {
2467  default: assert(0 && "Unknown binop!");
2468  case tok::star:                 Opc = BinaryOperator::Mul; break;
2469  case tok::slash:                Opc = BinaryOperator::Div; break;
2470  case tok::percent:              Opc = BinaryOperator::Rem; break;
2471  case tok::plus:                 Opc = BinaryOperator::Add; break;
2472  case tok::minus:                Opc = BinaryOperator::Sub; break;
2473  case tok::lessless:             Opc = BinaryOperator::Shl; break;
2474  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
2475  case tok::lessequal:            Opc = BinaryOperator::LE; break;
2476  case tok::less:                 Opc = BinaryOperator::LT; break;
2477  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
2478  case tok::greater:              Opc = BinaryOperator::GT; break;
2479  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
2480  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
2481  case tok::amp:                  Opc = BinaryOperator::And; break;
2482  case tok::caret:                Opc = BinaryOperator::Xor; break;
2483  case tok::pipe:                 Opc = BinaryOperator::Or; break;
2484  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
2485  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
2486  case tok::equal:                Opc = BinaryOperator::Assign; break;
2487  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
2488  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
2489  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
2490  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
2491  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
2492  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
2493  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
2494  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
2495  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
2496  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
2497  case tok::comma:                Opc = BinaryOperator::Comma; break;
2498  }
2499  return Opc;
2500}
2501
2502static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2503  tok::TokenKind Kind) {
2504  UnaryOperator::Opcode Opc;
2505  switch (Kind) {
2506  default: assert(0 && "Unknown unary op!");
2507  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
2508  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
2509  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
2510  case tok::star:         Opc = UnaryOperator::Deref; break;
2511  case tok::plus:         Opc = UnaryOperator::Plus; break;
2512  case tok::minus:        Opc = UnaryOperator::Minus; break;
2513  case tok::tilde:        Opc = UnaryOperator::Not; break;
2514  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
2515  case tok::kw_sizeof:    Opc = UnaryOperator::SizeOf; break;
2516  case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2517  case tok::kw___real:    Opc = UnaryOperator::Real; break;
2518  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
2519  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2520  }
2521  return Opc;
2522}
2523
2524// Binary Operators.  'Tok' is the token for the operator.
2525Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
2526                                    ExprTy *LHS, ExprTy *RHS) {
2527  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2528  Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2529
2530  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2531  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
2532
2533  QualType ResultTy;  // Result type of the binary operator.
2534  QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
2535
2536  switch (Opc) {
2537  default:
2538    assert(0 && "Unknown binary expr!");
2539  case BinaryOperator::Assign:
2540    ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2541    break;
2542  case BinaryOperator::Mul:
2543  case BinaryOperator::Div:
2544    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2545    break;
2546  case BinaryOperator::Rem:
2547    ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2548    break;
2549  case BinaryOperator::Add:
2550    ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2551    break;
2552  case BinaryOperator::Sub:
2553    ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2554    break;
2555  case BinaryOperator::Shl:
2556  case BinaryOperator::Shr:
2557    ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2558    break;
2559  case BinaryOperator::LE:
2560  case BinaryOperator::LT:
2561  case BinaryOperator::GE:
2562  case BinaryOperator::GT:
2563    ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
2564    break;
2565  case BinaryOperator::EQ:
2566  case BinaryOperator::NE:
2567    ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
2568    break;
2569  case BinaryOperator::And:
2570  case BinaryOperator::Xor:
2571  case BinaryOperator::Or:
2572    ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2573    break;
2574  case BinaryOperator::LAnd:
2575  case BinaryOperator::LOr:
2576    ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2577    break;
2578  case BinaryOperator::MulAssign:
2579  case BinaryOperator::DivAssign:
2580    CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
2581    if (!CompTy.isNull())
2582      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2583    break;
2584  case BinaryOperator::RemAssign:
2585    CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
2586    if (!CompTy.isNull())
2587      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2588    break;
2589  case BinaryOperator::AddAssign:
2590    CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
2591    if (!CompTy.isNull())
2592      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2593    break;
2594  case BinaryOperator::SubAssign:
2595    CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
2596    if (!CompTy.isNull())
2597      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2598    break;
2599  case BinaryOperator::ShlAssign:
2600  case BinaryOperator::ShrAssign:
2601    CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
2602    if (!CompTy.isNull())
2603      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2604    break;
2605  case BinaryOperator::AndAssign:
2606  case BinaryOperator::XorAssign:
2607  case BinaryOperator::OrAssign:
2608    CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
2609    if (!CompTy.isNull())
2610      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2611    break;
2612  case BinaryOperator::Comma:
2613    ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2614    break;
2615  }
2616  if (ResultTy.isNull())
2617    return true;
2618  if (CompTy.isNull())
2619    return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
2620  else
2621    return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
2622}
2623
2624// Unary Operators.  'Tok' is the token for the operator.
2625Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
2626                                      ExprTy *input) {
2627  Expr *Input = (Expr*)input;
2628  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2629  QualType resultType;
2630  switch (Opc) {
2631  default:
2632    assert(0 && "Unimplemented unary expr!");
2633  case UnaryOperator::PreInc:
2634  case UnaryOperator::PreDec:
2635    resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2636    break;
2637  case UnaryOperator::AddrOf:
2638    resultType = CheckAddressOfOperand(Input, OpLoc);
2639    break;
2640  case UnaryOperator::Deref:
2641    DefaultFunctionArrayConversion(Input);
2642    resultType = CheckIndirectionOperand(Input, OpLoc);
2643    break;
2644  case UnaryOperator::Plus:
2645  case UnaryOperator::Minus:
2646    UsualUnaryConversions(Input);
2647    resultType = Input->getType();
2648    if (!resultType->isArithmeticType())  // C99 6.5.3.3p1
2649      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2650                  resultType.getAsString());
2651    break;
2652  case UnaryOperator::Not: // bitwise complement
2653    UsualUnaryConversions(Input);
2654    resultType = Input->getType();
2655    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2656    if (resultType->isComplexType() || resultType->isComplexIntegerType())
2657      // C99 does not support '~' for complex conjugation.
2658      Diag(OpLoc, diag::ext_integer_complement_complex,
2659           resultType.getAsString(), Input->getSourceRange());
2660    else if (!resultType->isIntegerType())
2661      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2662                  resultType.getAsString(), Input->getSourceRange());
2663    break;
2664  case UnaryOperator::LNot: // logical negation
2665    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2666    DefaultFunctionArrayConversion(Input);
2667    resultType = Input->getType();
2668    if (!resultType->isScalarType()) // C99 6.5.3.3p1
2669      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2670                  resultType.getAsString());
2671    // LNot always has type int. C99 6.5.3.3p5.
2672    resultType = Context.IntTy;
2673    break;
2674  case UnaryOperator::SizeOf:
2675    resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2676                                           Input->getSourceRange(), true);
2677    break;
2678  case UnaryOperator::AlignOf:
2679    resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2680                                           Input->getSourceRange(), false);
2681    break;
2682  case UnaryOperator::Real:
2683  case UnaryOperator::Imag:
2684    resultType = CheckRealImagOperand(Input, OpLoc);
2685    break;
2686  case UnaryOperator::Extension:
2687    resultType = Input->getType();
2688    break;
2689  }
2690  if (resultType.isNull())
2691    return true;
2692  return new UnaryOperator(Input, Opc, resultType, OpLoc);
2693}
2694
2695/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2696Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
2697                                      SourceLocation LabLoc,
2698                                      IdentifierInfo *LabelII) {
2699  // Look up the record for this label identifier.
2700  LabelStmt *&LabelDecl = LabelMap[LabelII];
2701
2702  // If we haven't seen this label yet, create a forward reference. It
2703  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
2704  if (LabelDecl == 0)
2705    LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2706
2707  // Create the AST node.  The address of a label always has type 'void*'.
2708  return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2709                           Context.getPointerType(Context.VoidTy));
2710}
2711
2712Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
2713                                     SourceLocation RPLoc) { // "({..})"
2714  Stmt *SubStmt = static_cast<Stmt*>(substmt);
2715  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2716  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2717
2718  // FIXME: there are a variety of strange constraints to enforce here, for
2719  // example, it is not possible to goto into a stmt expression apparently.
2720  // More semantic analysis is needed.
2721
2722  // FIXME: the last statement in the compount stmt has its value used.  We
2723  // should not warn about it being unused.
2724
2725  // If there are sub stmts in the compound stmt, take the type of the last one
2726  // as the type of the stmtexpr.
2727  QualType Ty = Context.VoidTy;
2728
2729  if (!Compound->body_empty()) {
2730    Stmt *LastStmt = Compound->body_back();
2731    // If LastStmt is a label, skip down through into the body.
2732    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2733      LastStmt = Label->getSubStmt();
2734
2735    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
2736      Ty = LastExpr->getType();
2737  }
2738
2739  return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2740}
2741
2742Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
2743                                            SourceLocation TypeLoc,
2744                                            TypeTy *argty,
2745                                            OffsetOfComponent *CompPtr,
2746                                            unsigned NumComponents,
2747                                            SourceLocation RPLoc) {
2748  QualType ArgTy = QualType::getFromOpaquePtr(argty);
2749  assert(!ArgTy.isNull() && "Missing type argument!");
2750
2751  // We must have at least one component that refers to the type, and the first
2752  // one is known to be a field designator.  Verify that the ArgTy represents
2753  // a struct/union/class.
2754  if (!ArgTy->isRecordType())
2755    return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2756
2757  // Otherwise, create a compound literal expression as the base, and
2758  // iteratively process the offsetof designators.
2759  Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
2760
2761  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2762  // GCC extension, diagnose them.
2763  if (NumComponents != 1)
2764    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2765         SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2766
2767  for (unsigned i = 0; i != NumComponents; ++i) {
2768    const OffsetOfComponent &OC = CompPtr[i];
2769    if (OC.isBrackets) {
2770      // Offset of an array sub-field.  TODO: Should we allow vector elements?
2771      const ArrayType *AT = Context.getAsArrayType(Res->getType());
2772      if (!AT) {
2773        delete Res;
2774        return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2775                    Res->getType().getAsString());
2776      }
2777
2778      // FIXME: C++: Verify that operator[] isn't overloaded.
2779
2780      // C99 6.5.2.1p1
2781      Expr *Idx = static_cast<Expr*>(OC.U.E);
2782      if (!Idx->getType()->isIntegerType())
2783        return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2784                    Idx->getSourceRange());
2785
2786      Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2787      continue;
2788    }
2789
2790    const RecordType *RC = Res->getType()->getAsRecordType();
2791    if (!RC) {
2792      delete Res;
2793      return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2794                  Res->getType().getAsString());
2795    }
2796
2797    // Get the decl corresponding to this.
2798    RecordDecl *RD = RC->getDecl();
2799    FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2800    if (!MemberDecl)
2801      return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2802                  OC.U.IdentInfo->getName(),
2803                  SourceRange(OC.LocStart, OC.LocEnd));
2804
2805    // FIXME: C++: Verify that MemberDecl isn't a static field.
2806    // FIXME: Verify that MemberDecl isn't a bitfield.
2807    // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2808    // matter here.
2809    Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
2810  }
2811
2812  return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2813                           BuiltinLoc);
2814}
2815
2816
2817Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
2818                                                TypeTy *arg1, TypeTy *arg2,
2819                                                SourceLocation RPLoc) {
2820  QualType argT1 = QualType::getFromOpaquePtr(arg1);
2821  QualType argT2 = QualType::getFromOpaquePtr(arg2);
2822
2823  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2824
2825  return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
2826}
2827
2828Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
2829                                       ExprTy *expr1, ExprTy *expr2,
2830                                       SourceLocation RPLoc) {
2831  Expr *CondExpr = static_cast<Expr*>(cond);
2832  Expr *LHSExpr = static_cast<Expr*>(expr1);
2833  Expr *RHSExpr = static_cast<Expr*>(expr2);
2834
2835  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2836
2837  // The conditional expression is required to be a constant expression.
2838  llvm::APSInt condEval(32);
2839  SourceLocation ExpLoc;
2840  if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2841    return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2842                 CondExpr->getSourceRange());
2843
2844  // If the condition is > zero, then the AST type is the same as the LSHExpr.
2845  QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2846                                               RHSExpr->getType();
2847  return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2848}
2849
2850//===----------------------------------------------------------------------===//
2851// Clang Extensions.
2852//===----------------------------------------------------------------------===//
2853
2854/// ActOnBlockStart - This callback is invoked when a block literal is started.
2855void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope,
2856                           Declarator &ParamInfo) {
2857  // Analyze block parameters.
2858  BlockSemaInfo *BSI = new BlockSemaInfo();
2859
2860  // Add BSI to CurBlock.
2861  BSI->PrevBlockInfo = CurBlock;
2862  CurBlock = BSI;
2863
2864  BSI->ReturnType = 0;
2865  BSI->TheScope = BlockScope;
2866
2867  // Analyze arguments to block.
2868  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2869         "Not a function declarator!");
2870  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2871
2872  BSI->hasPrototype = FTI.hasPrototype;
2873  BSI->isVariadic = true;
2874
2875  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2876  // no arguments, not a function that takes a single void argument.
2877  if (FTI.hasPrototype &&
2878      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2879      (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2880        ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2881    // empty arg list, don't push any params.
2882    BSI->isVariadic = false;
2883  } else if (FTI.hasPrototype) {
2884    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2885      BSI->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2886    BSI->isVariadic = FTI.isVariadic;
2887  }
2888}
2889
2890/// ActOnBlockError - If there is an error parsing a block, this callback
2891/// is invoked to pop the information about the block from the action impl.
2892void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2893  // Ensure that CurBlock is deleted.
2894  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2895
2896  // Pop off CurBlock, handle nested blocks.
2897  CurBlock = CurBlock->PrevBlockInfo;
2898
2899  // FIXME: Delete the ParmVarDecl objects as well???
2900
2901}
2902
2903/// ActOnBlockStmtExpr - This is called when the body of a block statement
2904/// literal was successfully completed.  ^(int x){...}
2905Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2906                                          Scope *CurScope) {
2907  // Ensure that CurBlock is deleted.
2908  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2909  llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2910
2911  // Pop off CurBlock, handle nested blocks.
2912  CurBlock = CurBlock->PrevBlockInfo;
2913
2914  QualType RetTy = Context.VoidTy;
2915  if (BSI->ReturnType)
2916    RetTy = QualType(BSI->ReturnType, 0);
2917
2918  llvm::SmallVector<QualType, 8> ArgTypes;
2919  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2920    ArgTypes.push_back(BSI->Params[i]->getType());
2921
2922  QualType BlockTy;
2923  if (!BSI->hasPrototype)
2924    BlockTy = Context.getFunctionTypeNoProto(RetTy);
2925  else
2926    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2927                                      BSI->isVariadic);
2928
2929  BlockTy = Context.getBlockPointerType(BlockTy);
2930  return new BlockExpr(CaretLoc, BlockTy, &BSI->Params[0], BSI->Params.size(),
2931                       Body.take());
2932}
2933
2934/// ExprsMatchFnType - return true if the Exprs in array Args have
2935/// QualTypes that match the QualTypes of the arguments of the FnType.
2936/// The number of arguments has already been validated to match the number of
2937/// arguments in FnType.
2938static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2939                             ASTContext &Context) {
2940  unsigned NumParams = FnType->getNumArgs();
2941  for (unsigned i = 0; i != NumParams; ++i) {
2942    QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2943    QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
2944
2945    if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
2946      return false;
2947  }
2948  return true;
2949}
2950
2951Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2952                                         SourceLocation *CommaLocs,
2953                                         SourceLocation BuiltinLoc,
2954                                         SourceLocation RParenLoc) {
2955  // __builtin_overload requires at least 2 arguments
2956  if (NumArgs < 2)
2957    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2958                SourceRange(BuiltinLoc, RParenLoc));
2959
2960  // The first argument is required to be a constant expression.  It tells us
2961  // the number of arguments to pass to each of the functions to be overloaded.
2962  Expr **Args = reinterpret_cast<Expr**>(args);
2963  Expr *NParamsExpr = Args[0];
2964  llvm::APSInt constEval(32);
2965  SourceLocation ExpLoc;
2966  if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2967    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2968                NParamsExpr->getSourceRange());
2969
2970  // Verify that the number of parameters is > 0
2971  unsigned NumParams = constEval.getZExtValue();
2972  if (NumParams == 0)
2973    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2974                NParamsExpr->getSourceRange());
2975  // Verify that we have at least 1 + NumParams arguments to the builtin.
2976  if ((NumParams + 1) > NumArgs)
2977    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2978                SourceRange(BuiltinLoc, RParenLoc));
2979
2980  // Figure out the return type, by matching the args to one of the functions
2981  // listed after the parameters.
2982  OverloadExpr *OE = 0;
2983  for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2984    // UsualUnaryConversions will convert the function DeclRefExpr into a
2985    // pointer to function.
2986    Expr *Fn = UsualUnaryConversions(Args[i]);
2987    const FunctionTypeProto *FnType = 0;
2988    if (const PointerType *PT = Fn->getType()->getAsPointerType())
2989      FnType = PT->getPointeeType()->getAsFunctionTypeProto();
2990
2991    // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2992    // parameters, and the number of parameters must match the value passed to
2993    // the builtin.
2994    if (!FnType || (FnType->getNumArgs() != NumParams))
2995      return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2996                  Fn->getSourceRange());
2997
2998    // Scan the parameter list for the FunctionType, checking the QualType of
2999    // each parameter against the QualTypes of the arguments to the builtin.
3000    // If they match, return a new OverloadExpr.
3001    if (ExprsMatchFnType(Args+1, FnType, Context)) {
3002      if (OE)
3003        return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3004                    OE->getFn()->getSourceRange());
3005      // Remember our match, and continue processing the remaining arguments
3006      // to catch any errors.
3007      OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
3008                            BuiltinLoc, RParenLoc);
3009    }
3010  }
3011  // Return the newly created OverloadExpr node, if we succeded in matching
3012  // exactly one of the candidate functions.
3013  if (OE)
3014    return OE;
3015
3016  // If we didn't find a matching function Expr in the __builtin_overload list
3017  // the return an error.
3018  std::string typeNames;
3019  for (unsigned i = 0; i != NumParams; ++i) {
3020    if (i != 0) typeNames += ", ";
3021    typeNames += Args[i+1]->getType().getAsString();
3022  }
3023
3024  return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3025              SourceRange(BuiltinLoc, RParenLoc));
3026}
3027
3028Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3029                                  ExprTy *expr, TypeTy *type,
3030                                  SourceLocation RPLoc) {
3031  Expr *E = static_cast<Expr*>(expr);
3032  QualType T = QualType::getFromOpaquePtr(type);
3033
3034  InitBuiltinVaListType();
3035
3036  // Get the va_list type
3037  QualType VaListType = Context.getBuiltinVaListType();
3038  // Deal with implicit array decay; for example, on x86-64,
3039  // va_list is an array, but it's supposed to decay to
3040  // a pointer for va_arg.
3041  if (VaListType->isArrayType())
3042    VaListType = Context.getArrayDecayedType(VaListType);
3043  // Make sure the input expression also decays appropriately.
3044  UsualUnaryConversions(E);
3045
3046  if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
3047    return Diag(E->getLocStart(),
3048                diag::err_first_argument_to_va_arg_not_of_type_va_list,
3049                E->getType().getAsString(),
3050                E->getSourceRange());
3051
3052  // FIXME: Warn if a non-POD type is passed in.
3053
3054  return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3055}
3056
3057bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3058                                    SourceLocation Loc,
3059                                    QualType DstType, QualType SrcType,
3060                                    Expr *SrcExpr, const char *Flavor) {
3061  // Decode the result (notice that AST's are still created for extensions).
3062  bool isInvalid = false;
3063  unsigned DiagKind;
3064  switch (ConvTy) {
3065  default: assert(0 && "Unknown conversion type");
3066  case Compatible: return false;
3067  case PointerToInt:
3068    DiagKind = diag::ext_typecheck_convert_pointer_int;
3069    break;
3070  case IntToPointer:
3071    DiagKind = diag::ext_typecheck_convert_int_pointer;
3072    break;
3073  case IncompatiblePointer:
3074    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3075    break;
3076  case FunctionVoidPointer:
3077    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3078    break;
3079  case CompatiblePointerDiscardsQualifiers:
3080    // If the qualifiers lost were because we were applying the
3081    // (deprecated) C++ conversion from a string literal to a char*
3082    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
3083    // Ideally, this check would be performed in
3084    // CheckPointerTypesForAssignment. However, that would require a
3085    // bit of refactoring (so that the second argument is an
3086    // expression, rather than a type), which should be done as part
3087    // of a larger effort to fix CheckPointerTypesForAssignment for
3088    // C++ semantics.
3089    if (getLangOptions().CPlusPlus &&
3090        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3091      return false;
3092    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3093    break;
3094  case IntToBlockPointer:
3095    DiagKind = diag::err_int_to_block_pointer;
3096    break;
3097  case IncompatibleBlockPointer:
3098    DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
3099    break;
3100  case BlockVoidPointer:
3101    DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3102    break;
3103  case Incompatible:
3104    DiagKind = diag::err_typecheck_convert_incompatible;
3105    isInvalid = true;
3106    break;
3107  }
3108
3109  Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3110       SrcExpr->getSourceRange());
3111  return isInvalid;
3112}
3113