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