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