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 "clang/Sema/SemaInternal.h"
15#include "TreeTransform.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/RecursiveASTVisitor.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Sema/AnalysisBasedWarnings.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/DelayedDiagnostic.h"
36#include "clang/Sema/Designator.h"
37#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/ScopeInfo.h"
42#include "clang/Sema/SemaFixItUtils.h"
43#include "clang/Sema/Template.h"
44using namespace clang;
45using namespace sema;
46
47/// \brief Determine whether the use of this declaration is valid, without
48/// emitting diagnostics.
49bool Sema::CanUseDecl(NamedDecl *D) {
50  // See if this is an auto-typed variable whose initializer we are parsing.
51  if (ParsingInitForAutoVars.count(D))
52    return false;
53
54  // See if this is a deleted function.
55  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
56    if (FD->isDeleted())
57      return false;
58
59    // If the function has a deduced return type, and we can't deduce it,
60    // then we can't use it either.
61    if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
62        DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false))
63      return false;
64  }
65
66  // See if this function is unavailable.
67  if (D->getAvailability() == AR_Unavailable &&
68      cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
69    return false;
70
71  return true;
72}
73
74static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
75  // Warn if this is used but marked unused.
76  if (D->hasAttr<UnusedAttr>()) {
77    const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
78    if (!DC->hasAttr<UnusedAttr>())
79      S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
80  }
81}
82
83static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
84                              NamedDecl *D, SourceLocation Loc,
85                              const ObjCInterfaceDecl *UnknownObjCClass) {
86  // See if this declaration is unavailable or deprecated.
87  std::string Message;
88  AvailabilityResult Result = D->getAvailability(&Message);
89  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
90    if (Result == AR_Available) {
91      const DeclContext *DC = ECD->getDeclContext();
92      if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
93        Result = TheEnumDecl->getAvailability(&Message);
94    }
95
96  const ObjCPropertyDecl *ObjCPDecl = 0;
97  if (Result == AR_Deprecated || Result == AR_Unavailable) {
98    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
99      if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
100        AvailabilityResult PDeclResult = PD->getAvailability(0);
101        if (PDeclResult == Result)
102          ObjCPDecl = PD;
103      }
104    }
105  }
106
107  switch (Result) {
108    case AR_Available:
109    case AR_NotYetIntroduced:
110      break;
111
112    case AR_Deprecated:
113      S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
114      break;
115
116    case AR_Unavailable:
117      if (S.getCurContextAvailability() != AR_Unavailable) {
118        if (Message.empty()) {
119          if (!UnknownObjCClass) {
120            S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
121            if (ObjCPDecl)
122              S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
123                << ObjCPDecl->getDeclName() << 1;
124          }
125          else
126            S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
127              << D->getDeclName();
128        }
129        else
130          S.Diag(Loc, diag::err_unavailable_message)
131            << D->getDeclName() << Message;
132        S.Diag(D->getLocation(), diag::note_unavailable_here)
133                  << isa<FunctionDecl>(D) << false;
134        if (ObjCPDecl)
135          S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
136          << ObjCPDecl->getDeclName() << 1;
137      }
138      break;
139    }
140    return Result;
141}
142
143/// \brief Emit a note explaining that this function is deleted.
144void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
145  assert(Decl->isDeleted());
146
147  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
148
149  if (Method && Method->isDeleted() && Method->isDefaulted()) {
150    // If the method was explicitly defaulted, point at that declaration.
151    if (!Method->isImplicit())
152      Diag(Decl->getLocation(), diag::note_implicitly_deleted);
153
154    // Try to diagnose why this special member function was implicitly
155    // deleted. This might fail, if that reason no longer applies.
156    CXXSpecialMember CSM = getSpecialMember(Method);
157    if (CSM != CXXInvalid)
158      ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
159
160    return;
161  }
162
163  if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
164    if (CXXConstructorDecl *BaseCD =
165            const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
166      Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
167      if (BaseCD->isDeleted()) {
168        NoteDeletedFunction(BaseCD);
169      } else {
170        // FIXME: An explanation of why exactly it can't be inherited
171        // would be nice.
172        Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
173      }
174      return;
175    }
176  }
177
178  Diag(Decl->getLocation(), diag::note_unavailable_here)
179    << 1 << true;
180}
181
182/// \brief Determine whether a FunctionDecl was ever declared with an
183/// explicit storage class.
184static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
185  for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
186                                     E = D->redecls_end();
187       I != E; ++I) {
188    if (I->getStorageClass() != SC_None)
189      return true;
190  }
191  return false;
192}
193
194/// \brief Check whether we're in an extern inline function and referring to a
195/// variable or function with internal linkage (C11 6.7.4p3).
196///
197/// This is only a warning because we used to silently accept this code, but
198/// in many cases it will not behave correctly. This is not enabled in C++ mode
199/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
200/// and so while there may still be user mistakes, most of the time we can't
201/// prove that there are errors.
202static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
203                                                      const NamedDecl *D,
204                                                      SourceLocation Loc) {
205  // This is disabled under C++; there are too many ways for this to fire in
206  // contexts where the warning is a false positive, or where it is technically
207  // correct but benign.
208  if (S.getLangOpts().CPlusPlus)
209    return;
210
211  // Check if this is an inlined function or method.
212  FunctionDecl *Current = S.getCurFunctionDecl();
213  if (!Current)
214    return;
215  if (!Current->isInlined())
216    return;
217  if (!Current->isExternallyVisible())
218    return;
219
220  // Check if the decl has internal linkage.
221  if (D->getFormalLinkage() != InternalLinkage)
222    return;
223
224  // Downgrade from ExtWarn to Extension if
225  //  (1) the supposedly external inline function is in the main file,
226  //      and probably won't be included anywhere else.
227  //  (2) the thing we're referencing is a pure function.
228  //  (3) the thing we're referencing is another inline function.
229  // This last can give us false negatives, but it's better than warning on
230  // wrappers for simple C library functions.
231  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
232  bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
233  if (!DowngradeWarning && UsedFn)
234    DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
235
236  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
237                               : diag::warn_internal_in_extern_inline)
238    << /*IsVar=*/!UsedFn << D;
239
240  S.MaybeSuggestAddingStaticToDecl(Current);
241
242  S.Diag(D->getCanonicalDecl()->getLocation(),
243         diag::note_internal_decl_declared_here)
244    << D;
245}
246
247void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
248  const FunctionDecl *First = Cur->getFirstDeclaration();
249
250  // Suggest "static" on the function, if possible.
251  if (!hasAnyExplicitStorageClass(First)) {
252    SourceLocation DeclBegin = First->getSourceRange().getBegin();
253    Diag(DeclBegin, diag::note_convert_inline_to_static)
254      << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
255  }
256}
257
258/// \brief Determine whether the use of this declaration is valid, and
259/// emit any corresponding diagnostics.
260///
261/// This routine diagnoses various problems with referencing
262/// declarations that can occur when using a declaration. For example,
263/// it might warn if a deprecated or unavailable declaration is being
264/// used, or produce an error (and return true) if a C++0x deleted
265/// function is being used.
266///
267/// \returns true if there was an error (this declaration cannot be
268/// referenced), false otherwise.
269///
270bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
271                             const ObjCInterfaceDecl *UnknownObjCClass) {
272  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
273    // If there were any diagnostics suppressed by template argument deduction,
274    // emit them now.
275    SuppressedDiagnosticsMap::iterator
276      Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
277    if (Pos != SuppressedDiagnostics.end()) {
278      SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
279      for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
280        Diag(Suppressed[I].first, Suppressed[I].second);
281
282      // Clear out the list of suppressed diagnostics, so that we don't emit
283      // them again for this specialization. However, we don't obsolete this
284      // entry from the table, because we want to avoid ever emitting these
285      // diagnostics again.
286      Suppressed.clear();
287    }
288  }
289
290  // See if this is an auto-typed variable whose initializer we are parsing.
291  if (ParsingInitForAutoVars.count(D)) {
292    Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
293      << D->getDeclName();
294    return true;
295  }
296
297  // See if this is a deleted function.
298  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
299    if (FD->isDeleted()) {
300      Diag(Loc, diag::err_deleted_function_use);
301      NoteDeletedFunction(FD);
302      return true;
303    }
304
305    // If the function has a deduced return type, and we can't deduce it,
306    // then we can't use it either.
307    if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
308        DeduceReturnType(FD, Loc))
309      return true;
310  }
311  DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
312
313  DiagnoseUnusedOfDecl(*this, D, Loc);
314
315  diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
316
317  return false;
318}
319
320/// \brief Retrieve the message suffix that should be added to a
321/// diagnostic complaining about the given function being deleted or
322/// unavailable.
323std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
324  std::string Message;
325  if (FD->getAvailability(&Message))
326    return ": " + Message;
327
328  return std::string();
329}
330
331/// DiagnoseSentinelCalls - This routine checks whether a call or
332/// message-send is to a declaration with the sentinel attribute, and
333/// if so, it checks that the requirements of the sentinel are
334/// satisfied.
335void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
336                                 ArrayRef<Expr *> Args) {
337  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
338  if (!attr)
339    return;
340
341  // The number of formal parameters of the declaration.
342  unsigned numFormalParams;
343
344  // The kind of declaration.  This is also an index into a %select in
345  // the diagnostic.
346  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
347
348  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
349    numFormalParams = MD->param_size();
350    calleeType = CT_Method;
351  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
352    numFormalParams = FD->param_size();
353    calleeType = CT_Function;
354  } else if (isa<VarDecl>(D)) {
355    QualType type = cast<ValueDecl>(D)->getType();
356    const FunctionType *fn = 0;
357    if (const PointerType *ptr = type->getAs<PointerType>()) {
358      fn = ptr->getPointeeType()->getAs<FunctionType>();
359      if (!fn) return;
360      calleeType = CT_Function;
361    } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
362      fn = ptr->getPointeeType()->castAs<FunctionType>();
363      calleeType = CT_Block;
364    } else {
365      return;
366    }
367
368    if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
369      numFormalParams = proto->getNumArgs();
370    } else {
371      numFormalParams = 0;
372    }
373  } else {
374    return;
375  }
376
377  // "nullPos" is the number of formal parameters at the end which
378  // effectively count as part of the variadic arguments.  This is
379  // useful if you would prefer to not have *any* formal parameters,
380  // but the language forces you to have at least one.
381  unsigned nullPos = attr->getNullPos();
382  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
383  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
384
385  // The number of arguments which should follow the sentinel.
386  unsigned numArgsAfterSentinel = attr->getSentinel();
387
388  // If there aren't enough arguments for all the formal parameters,
389  // the sentinel, and the args after the sentinel, complain.
390  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
391    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
392    Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
393    return;
394  }
395
396  // Otherwise, find the sentinel expression.
397  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
398  if (!sentinelExpr) return;
399  if (sentinelExpr->isValueDependent()) return;
400  if (Context.isSentinelNullExpr(sentinelExpr)) return;
401
402  // Pick a reasonable string to insert.  Optimistically use 'nil' or
403  // 'NULL' if those are actually defined in the context.  Only use
404  // 'nil' for ObjC methods, where it's much more likely that the
405  // variadic arguments form a list of object pointers.
406  SourceLocation MissingNilLoc
407    = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
408  std::string NullValue;
409  if (calleeType == CT_Method &&
410      PP.getIdentifierInfo("nil")->hasMacroDefinition())
411    NullValue = "nil";
412  else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
413    NullValue = "NULL";
414  else
415    NullValue = "(void*) 0";
416
417  if (MissingNilLoc.isInvalid())
418    Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
419  else
420    Diag(MissingNilLoc, diag::warn_missing_sentinel)
421      << int(calleeType)
422      << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
423  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
424}
425
426SourceRange Sema::getExprRange(Expr *E) const {
427  return E ? E->getSourceRange() : SourceRange();
428}
429
430//===----------------------------------------------------------------------===//
431//  Standard Promotions and Conversions
432//===----------------------------------------------------------------------===//
433
434/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
435ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
436  // Handle any placeholder expressions which made it here.
437  if (E->getType()->isPlaceholderType()) {
438    ExprResult result = CheckPlaceholderExpr(E);
439    if (result.isInvalid()) return ExprError();
440    E = result.take();
441  }
442
443  QualType Ty = E->getType();
444  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
445
446  if (Ty->isFunctionType())
447    E = ImpCastExprToType(E, Context.getPointerType(Ty),
448                          CK_FunctionToPointerDecay).take();
449  else if (Ty->isArrayType()) {
450    // In C90 mode, arrays only promote to pointers if the array expression is
451    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
452    // type 'array of type' is converted to an expression that has type 'pointer
453    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
454    // that has type 'array of type' ...".  The relevant change is "an lvalue"
455    // (C90) to "an expression" (C99).
456    //
457    // C++ 4.2p1:
458    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
459    // T" can be converted to an rvalue of type "pointer to T".
460    //
461    if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
462      E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
463                            CK_ArrayToPointerDecay).take();
464  }
465  return Owned(E);
466}
467
468static void CheckForNullPointerDereference(Sema &S, Expr *E) {
469  // Check to see if we are dereferencing a null pointer.  If so,
470  // and if not volatile-qualified, this is undefined behavior that the
471  // optimizer will delete, so warn about it.  People sometimes try to use this
472  // to get a deterministic trap and are surprised by clang's behavior.  This
473  // only handles the pattern "*null", which is a very syntactic check.
474  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
475    if (UO->getOpcode() == UO_Deref &&
476        UO->getSubExpr()->IgnoreParenCasts()->
477          isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
478        !UO->getType().isVolatileQualified()) {
479    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
480                          S.PDiag(diag::warn_indirection_through_null)
481                            << UO->getSubExpr()->getSourceRange());
482    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
483                        S.PDiag(diag::note_indirection_through_null));
484  }
485}
486
487static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
488                                    SourceLocation AssignLoc,
489                                    const Expr* RHS) {
490  const ObjCIvarDecl *IV = OIRE->getDecl();
491  if (!IV)
492    return;
493
494  DeclarationName MemberName = IV->getDeclName();
495  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
496  if (!Member || !Member->isStr("isa"))
497    return;
498
499  const Expr *Base = OIRE->getBase();
500  QualType BaseType = Base->getType();
501  if (OIRE->isArrow())
502    BaseType = BaseType->getPointeeType();
503  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
504    if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
505      ObjCInterfaceDecl *ClassDeclared = 0;
506      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
507      if (!ClassDeclared->getSuperClass()
508          && (*ClassDeclared->ivar_begin()) == IV) {
509        if (RHS) {
510          NamedDecl *ObjectSetClass =
511            S.LookupSingleName(S.TUScope,
512                               &S.Context.Idents.get("object_setClass"),
513                               SourceLocation(), S.LookupOrdinaryName);
514          if (ObjectSetClass) {
515            SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
516            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
517            FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
518            FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
519                                                     AssignLoc), ",") <<
520            FixItHint::CreateInsertion(RHSLocEnd, ")");
521          }
522          else
523            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
524        } else {
525          NamedDecl *ObjectGetClass =
526            S.LookupSingleName(S.TUScope,
527                               &S.Context.Idents.get("object_getClass"),
528                               SourceLocation(), S.LookupOrdinaryName);
529          if (ObjectGetClass)
530            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
531            FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
532            FixItHint::CreateReplacement(
533                                         SourceRange(OIRE->getOpLoc(),
534                                                     OIRE->getLocEnd()), ")");
535          else
536            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
537        }
538        S.Diag(IV->getLocation(), diag::note_ivar_decl);
539      }
540    }
541}
542
543ExprResult Sema::DefaultLvalueConversion(Expr *E) {
544  // Handle any placeholder expressions which made it here.
545  if (E->getType()->isPlaceholderType()) {
546    ExprResult result = CheckPlaceholderExpr(E);
547    if (result.isInvalid()) return ExprError();
548    E = result.take();
549  }
550
551  // C++ [conv.lval]p1:
552  //   A glvalue of a non-function, non-array type T can be
553  //   converted to a prvalue.
554  if (!E->isGLValue()) return Owned(E);
555
556  QualType T = E->getType();
557  assert(!T.isNull() && "r-value conversion on typeless expression?");
558
559  // We don't want to throw lvalue-to-rvalue casts on top of
560  // expressions of certain types in C++.
561  if (getLangOpts().CPlusPlus &&
562      (E->getType() == Context.OverloadTy ||
563       T->isDependentType() ||
564       T->isRecordType()))
565    return Owned(E);
566
567  // The C standard is actually really unclear on this point, and
568  // DR106 tells us what the result should be but not why.  It's
569  // generally best to say that void types just doesn't undergo
570  // lvalue-to-rvalue at all.  Note that expressions of unqualified
571  // 'void' type are never l-values, but qualified void can be.
572  if (T->isVoidType())
573    return Owned(E);
574
575  // OpenCL usually rejects direct accesses to values of 'half' type.
576  if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
577      T->isHalfType()) {
578    Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
579      << 0 << T;
580    return ExprError();
581  }
582
583  CheckForNullPointerDereference(*this, E);
584  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
585    NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
586                                     &Context.Idents.get("object_getClass"),
587                                     SourceLocation(), LookupOrdinaryName);
588    if (ObjectGetClass)
589      Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
590        FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
591        FixItHint::CreateReplacement(
592                    SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
593    else
594      Diag(E->getExprLoc(), diag::warn_objc_isa_use);
595  }
596  else if (const ObjCIvarRefExpr *OIRE =
597            dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
598    DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
599
600  // C++ [conv.lval]p1:
601  //   [...] If T is a non-class type, the type of the prvalue is the
602  //   cv-unqualified version of T. Otherwise, the type of the
603  //   rvalue is T.
604  //
605  // C99 6.3.2.1p2:
606  //   If the lvalue has qualified type, the value has the unqualified
607  //   version of the type of the lvalue; otherwise, the value has the
608  //   type of the lvalue.
609  if (T.hasQualifiers())
610    T = T.getUnqualifiedType();
611
612  UpdateMarkingForLValueToRValue(E);
613
614  // Loading a __weak object implicitly retains the value, so we need a cleanup to
615  // balance that.
616  if (getLangOpts().ObjCAutoRefCount &&
617      E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
618    ExprNeedsCleanups = true;
619
620  ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
621                                                  E, 0, VK_RValue));
622
623  // C11 6.3.2.1p2:
624  //   ... if the lvalue has atomic type, the value has the non-atomic version
625  //   of the type of the lvalue ...
626  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
627    T = Atomic->getValueType().getUnqualifiedType();
628    Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
629                                         Res.get(), 0, VK_RValue));
630  }
631
632  return Res;
633}
634
635ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
636  ExprResult Res = DefaultFunctionArrayConversion(E);
637  if (Res.isInvalid())
638    return ExprError();
639  Res = DefaultLvalueConversion(Res.take());
640  if (Res.isInvalid())
641    return ExprError();
642  return Res;
643}
644
645
646/// UsualUnaryConversions - Performs various conversions that are common to most
647/// operators (C99 6.3). The conversions of array and function types are
648/// sometimes suppressed. For example, the array->pointer conversion doesn't
649/// apply if the array is an argument to the sizeof or address (&) operators.
650/// In these instances, this routine should *not* be called.
651ExprResult Sema::UsualUnaryConversions(Expr *E) {
652  // First, convert to an r-value.
653  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
654  if (Res.isInvalid())
655    return ExprError();
656  E = Res.take();
657
658  QualType Ty = E->getType();
659  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
660
661  // Half FP have to be promoted to float unless it is natively supported
662  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
663    return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
664
665  // Try to perform integral promotions if the object has a theoretically
666  // promotable type.
667  if (Ty->isIntegralOrUnscopedEnumerationType()) {
668    // C99 6.3.1.1p2:
669    //
670    //   The following may be used in an expression wherever an int or
671    //   unsigned int may be used:
672    //     - an object or expression with an integer type whose integer
673    //       conversion rank is less than or equal to the rank of int
674    //       and unsigned int.
675    //     - A bit-field of type _Bool, int, signed int, or unsigned int.
676    //
677    //   If an int can represent all values of the original type, the
678    //   value is converted to an int; otherwise, it is converted to an
679    //   unsigned int. These are called the integer promotions. All
680    //   other types are unchanged by the integer promotions.
681
682    QualType PTy = Context.isPromotableBitField(E);
683    if (!PTy.isNull()) {
684      E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
685      return Owned(E);
686    }
687    if (Ty->isPromotableIntegerType()) {
688      QualType PT = Context.getPromotedIntegerType(Ty);
689      E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
690      return Owned(E);
691    }
692  }
693  return Owned(E);
694}
695
696/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
697/// do not have a prototype. Arguments that have type float or __fp16
698/// are promoted to double. All other argument types are converted by
699/// UsualUnaryConversions().
700ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
701  QualType Ty = E->getType();
702  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
703
704  ExprResult Res = UsualUnaryConversions(E);
705  if (Res.isInvalid())
706    return ExprError();
707  E = Res.take();
708
709  // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
710  // double.
711  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
712  if (BTy && (BTy->getKind() == BuiltinType::Half ||
713              BTy->getKind() == BuiltinType::Float))
714    E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
715
716  // C++ performs lvalue-to-rvalue conversion as a default argument
717  // promotion, even on class types, but note:
718  //   C++11 [conv.lval]p2:
719  //     When an lvalue-to-rvalue conversion occurs in an unevaluated
720  //     operand or a subexpression thereof the value contained in the
721  //     referenced object is not accessed. Otherwise, if the glvalue
722  //     has a class type, the conversion copy-initializes a temporary
723  //     of type T from the glvalue and the result of the conversion
724  //     is a prvalue for the temporary.
725  // FIXME: add some way to gate this entire thing for correctness in
726  // potentially potentially evaluated contexts.
727  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
728    ExprResult Temp = PerformCopyInitialization(
729                       InitializedEntity::InitializeTemporary(E->getType()),
730                                                E->getExprLoc(),
731                                                Owned(E));
732    if (Temp.isInvalid())
733      return ExprError();
734    E = Temp.get();
735  }
736
737  return Owned(E);
738}
739
740/// Determine the degree of POD-ness for an expression.
741/// Incomplete types are considered POD, since this check can be performed
742/// when we're in an unevaluated context.
743Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
744  if (Ty->isIncompleteType()) {
745    // C++11 [expr.call]p7:
746    //   After these conversions, if the argument does not have arithmetic,
747    //   enumeration, pointer, pointer to member, or class type, the program
748    //   is ill-formed.
749    //
750    // Since we've already performed array-to-pointer and function-to-pointer
751    // decay, the only such type in C++ is cv void. This also handles
752    // initializer lists as variadic arguments.
753    if (Ty->isVoidType())
754      return VAK_Invalid;
755
756    if (Ty->isObjCObjectType())
757      return VAK_Invalid;
758    return VAK_Valid;
759  }
760
761  if (Ty.isCXX98PODType(Context))
762    return VAK_Valid;
763
764  // C++11 [expr.call]p7:
765  //   Passing a potentially-evaluated argument of class type (Clause 9)
766  //   having a non-trivial copy constructor, a non-trivial move constructor,
767  //   or a non-trivial destructor, with no corresponding parameter,
768  //   is conditionally-supported with implementation-defined semantics.
769  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
770    if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
771      if (!Record->hasNonTrivialCopyConstructor() &&
772          !Record->hasNonTrivialMoveConstructor() &&
773          !Record->hasNonTrivialDestructor())
774        return VAK_ValidInCXX11;
775
776  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
777    return VAK_Valid;
778
779  if (Ty->isObjCObjectType())
780    return VAK_Invalid;
781
782  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
783  // permitted to reject them. We should consider doing so.
784  return VAK_Undefined;
785}
786
787void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
788  // Don't allow one to pass an Objective-C interface to a vararg.
789  const QualType &Ty = E->getType();
790  VarArgKind VAK = isValidVarArgType(Ty);
791
792  // Complain about passing non-POD types through varargs.
793  switch (VAK) {
794  case VAK_Valid:
795    break;
796
797  case VAK_ValidInCXX11:
798    DiagRuntimeBehavior(
799        E->getLocStart(), 0,
800        PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
801          << E->getType() << CT);
802    break;
803
804  case VAK_Undefined:
805    DiagRuntimeBehavior(
806        E->getLocStart(), 0,
807        PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
808          << getLangOpts().CPlusPlus11 << Ty << CT);
809    break;
810
811  case VAK_Invalid:
812    if (Ty->isObjCObjectType())
813      DiagRuntimeBehavior(
814          E->getLocStart(), 0,
815          PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
816            << Ty << CT);
817    else
818      Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
819        << isa<InitListExpr>(E) << Ty << CT;
820    break;
821  }
822}
823
824/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
825/// will create a trap if the resulting type is not a POD type.
826ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
827                                                  FunctionDecl *FDecl) {
828  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
829    // Strip the unbridged-cast placeholder expression off, if applicable.
830    if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
831        (CT == VariadicMethod ||
832         (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
833      E = stripARCUnbridgedCast(E);
834
835    // Otherwise, do normal placeholder checking.
836    } else {
837      ExprResult ExprRes = CheckPlaceholderExpr(E);
838      if (ExprRes.isInvalid())
839        return ExprError();
840      E = ExprRes.take();
841    }
842  }
843
844  ExprResult ExprRes = DefaultArgumentPromotion(E);
845  if (ExprRes.isInvalid())
846    return ExprError();
847  E = ExprRes.take();
848
849  // Diagnostics regarding non-POD argument types are
850  // emitted along with format string checking in Sema::CheckFunctionCall().
851  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
852    // Turn this into a trap.
853    CXXScopeSpec SS;
854    SourceLocation TemplateKWLoc;
855    UnqualifiedId Name;
856    Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
857                       E->getLocStart());
858    ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
859                                          Name, true, false);
860    if (TrapFn.isInvalid())
861      return ExprError();
862
863    ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
864                                    E->getLocStart(), None,
865                                    E->getLocEnd());
866    if (Call.isInvalid())
867      return ExprError();
868
869    ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
870                                  Call.get(), E);
871    if (Comma.isInvalid())
872      return ExprError();
873    return Comma.get();
874  }
875
876  if (!getLangOpts().CPlusPlus &&
877      RequireCompleteType(E->getExprLoc(), E->getType(),
878                          diag::err_call_incomplete_argument))
879    return ExprError();
880
881  return Owned(E);
882}
883
884/// \brief Converts an integer to complex float type.  Helper function of
885/// UsualArithmeticConversions()
886///
887/// \return false if the integer expression is an integer type and is
888/// successfully converted to the complex type.
889static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
890                                                  ExprResult &ComplexExpr,
891                                                  QualType IntTy,
892                                                  QualType ComplexTy,
893                                                  bool SkipCast) {
894  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
895  if (SkipCast) return false;
896  if (IntTy->isIntegerType()) {
897    QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
898    IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
899    IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
900                                  CK_FloatingRealToComplex);
901  } else {
902    assert(IntTy->isComplexIntegerType());
903    IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
904                                  CK_IntegralComplexToFloatingComplex);
905  }
906  return false;
907}
908
909/// \brief Takes two complex float types and converts them to the same type.
910/// Helper function of UsualArithmeticConversions()
911static QualType
912handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
913                                            ExprResult &RHS, QualType LHSType,
914                                            QualType RHSType,
915                                            bool IsCompAssign) {
916  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
917
918  if (order < 0) {
919    // _Complex float -> _Complex double
920    if (!IsCompAssign)
921      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
922    return RHSType;
923  }
924  if (order > 0)
925    // _Complex float -> _Complex double
926    RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
927  return LHSType;
928}
929
930/// \brief Converts otherExpr to complex float and promotes complexExpr if
931/// necessary.  Helper function of UsualArithmeticConversions()
932static QualType handleOtherComplexFloatConversion(Sema &S,
933                                                  ExprResult &ComplexExpr,
934                                                  ExprResult &OtherExpr,
935                                                  QualType ComplexTy,
936                                                  QualType OtherTy,
937                                                  bool ConvertComplexExpr,
938                                                  bool ConvertOtherExpr) {
939  int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
940
941  // If just the complexExpr is complex, the otherExpr needs to be converted,
942  // and the complexExpr might need to be promoted.
943  if (order > 0) { // complexExpr is wider
944    // float -> _Complex double
945    if (ConvertOtherExpr) {
946      QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
947      OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
948      OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
949                                      CK_FloatingRealToComplex);
950    }
951    return ComplexTy;
952  }
953
954  // otherTy is at least as wide.  Find its corresponding complex type.
955  QualType result = (order == 0 ? ComplexTy :
956                                  S.Context.getComplexType(OtherTy));
957
958  // double -> _Complex double
959  if (ConvertOtherExpr)
960    OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
961                                    CK_FloatingRealToComplex);
962
963  // _Complex float -> _Complex double
964  if (ConvertComplexExpr && order < 0)
965    ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
966                                      CK_FloatingComplexCast);
967
968  return result;
969}
970
971/// \brief Handle arithmetic conversion with complex types.  Helper function of
972/// UsualArithmeticConversions()
973static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
974                                             ExprResult &RHS, QualType LHSType,
975                                             QualType RHSType,
976                                             bool IsCompAssign) {
977  // if we have an integer operand, the result is the complex type.
978  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
979                                             /*skipCast*/false))
980    return LHSType;
981  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
982                                             /*skipCast*/IsCompAssign))
983    return RHSType;
984
985  // This handles complex/complex, complex/float, or float/complex.
986  // When both operands are complex, the shorter operand is converted to the
987  // type of the longer, and that is the type of the result. This corresponds
988  // to what is done when combining two real floating-point operands.
989  // The fun begins when size promotion occur across type domains.
990  // From H&S 6.3.4: When one operand is complex and the other is a real
991  // floating-point type, the less precise type is converted, within it's
992  // real or complex domain, to the precision of the other type. For example,
993  // when combining a "long double" with a "double _Complex", the
994  // "double _Complex" is promoted to "long double _Complex".
995
996  bool LHSComplexFloat = LHSType->isComplexType();
997  bool RHSComplexFloat = RHSType->isComplexType();
998
999  // If both are complex, just cast to the more precise type.
1000  if (LHSComplexFloat && RHSComplexFloat)
1001    return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1002                                                       LHSType, RHSType,
1003                                                       IsCompAssign);
1004
1005  // If only one operand is complex, promote it if necessary and convert the
1006  // other operand to complex.
1007  if (LHSComplexFloat)
1008    return handleOtherComplexFloatConversion(
1009        S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1010        /*convertOtherExpr*/ true);
1011
1012  assert(RHSComplexFloat);
1013  return handleOtherComplexFloatConversion(
1014      S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1015      /*convertOtherExpr*/ !IsCompAssign);
1016}
1017
1018/// \brief Hande arithmetic conversion from integer to float.  Helper function
1019/// of UsualArithmeticConversions()
1020static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1021                                           ExprResult &IntExpr,
1022                                           QualType FloatTy, QualType IntTy,
1023                                           bool ConvertFloat, bool ConvertInt) {
1024  if (IntTy->isIntegerType()) {
1025    if (ConvertInt)
1026      // Convert intExpr to the lhs floating point type.
1027      IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
1028                                    CK_IntegralToFloating);
1029    return FloatTy;
1030  }
1031
1032  // Convert both sides to the appropriate complex float.
1033  assert(IntTy->isComplexIntegerType());
1034  QualType result = S.Context.getComplexType(FloatTy);
1035
1036  // _Complex int -> _Complex float
1037  if (ConvertInt)
1038    IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
1039                                  CK_IntegralComplexToFloatingComplex);
1040
1041  // float -> _Complex float
1042  if (ConvertFloat)
1043    FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
1044                                    CK_FloatingRealToComplex);
1045
1046  return result;
1047}
1048
1049/// \brief Handle arithmethic conversion with floating point types.  Helper
1050/// function of UsualArithmeticConversions()
1051static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1052                                      ExprResult &RHS, QualType LHSType,
1053                                      QualType RHSType, bool IsCompAssign) {
1054  bool LHSFloat = LHSType->isRealFloatingType();
1055  bool RHSFloat = RHSType->isRealFloatingType();
1056
1057  // If we have two real floating types, convert the smaller operand
1058  // to the bigger result.
1059  if (LHSFloat && RHSFloat) {
1060    int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1061    if (order > 0) {
1062      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1063      return LHSType;
1064    }
1065
1066    assert(order < 0 && "illegal float comparison");
1067    if (!IsCompAssign)
1068      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1069    return RHSType;
1070  }
1071
1072  if (LHSFloat)
1073    return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1074                                      /*convertFloat=*/!IsCompAssign,
1075                                      /*convertInt=*/ true);
1076  assert(RHSFloat);
1077  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1078                                    /*convertInt=*/ true,
1079                                    /*convertFloat=*/!IsCompAssign);
1080}
1081
1082typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1083
1084namespace {
1085/// These helper callbacks are placed in an anonymous namespace to
1086/// permit their use as function template parameters.
1087ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1088  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1089}
1090
1091ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1092  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1093                             CK_IntegralComplexCast);
1094}
1095}
1096
1097/// \brief Handle integer arithmetic conversions.  Helper function of
1098/// UsualArithmeticConversions()
1099template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1100static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1101                                        ExprResult &RHS, QualType LHSType,
1102                                        QualType RHSType, bool IsCompAssign) {
1103  // The rules for this case are in C99 6.3.1.8
1104  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1105  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1106  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1107  if (LHSSigned == RHSSigned) {
1108    // Same signedness; use the higher-ranked type
1109    if (order >= 0) {
1110      RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1111      return LHSType;
1112    } else if (!IsCompAssign)
1113      LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1114    return RHSType;
1115  } else if (order != (LHSSigned ? 1 : -1)) {
1116    // The unsigned type has greater than or equal rank to the
1117    // signed type, so use the unsigned type
1118    if (RHSSigned) {
1119      RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1120      return LHSType;
1121    } else if (!IsCompAssign)
1122      LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1123    return RHSType;
1124  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1125    // The two types are different widths; if we are here, that
1126    // means the signed type is larger than the unsigned type, so
1127    // use the signed type.
1128    if (LHSSigned) {
1129      RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1130      return LHSType;
1131    } else if (!IsCompAssign)
1132      LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1133    return RHSType;
1134  } else {
1135    // The signed type is higher-ranked than the unsigned type,
1136    // but isn't actually any bigger (like unsigned int and long
1137    // on most 32-bit systems).  Use the unsigned type corresponding
1138    // to the signed type.
1139    QualType result =
1140      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1141    RHS = (*doRHSCast)(S, RHS.take(), result);
1142    if (!IsCompAssign)
1143      LHS = (*doLHSCast)(S, LHS.take(), result);
1144    return result;
1145  }
1146}
1147
1148/// \brief Handle conversions with GCC complex int extension.  Helper function
1149/// of UsualArithmeticConversions()
1150static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1151                                           ExprResult &RHS, QualType LHSType,
1152                                           QualType RHSType,
1153                                           bool IsCompAssign) {
1154  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1155  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1156
1157  if (LHSComplexInt && RHSComplexInt) {
1158    QualType LHSEltType = LHSComplexInt->getElementType();
1159    QualType RHSEltType = RHSComplexInt->getElementType();
1160    QualType ScalarType =
1161      handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1162        (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1163
1164    return S.Context.getComplexType(ScalarType);
1165  }
1166
1167  if (LHSComplexInt) {
1168    QualType LHSEltType = LHSComplexInt->getElementType();
1169    QualType ScalarType =
1170      handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1171        (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1172    QualType ComplexType = S.Context.getComplexType(ScalarType);
1173    RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1174                              CK_IntegralRealToComplex);
1175
1176    return ComplexType;
1177  }
1178
1179  assert(RHSComplexInt);
1180
1181  QualType RHSEltType = RHSComplexInt->getElementType();
1182  QualType ScalarType =
1183    handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1184      (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1185  QualType ComplexType = S.Context.getComplexType(ScalarType);
1186
1187  if (!IsCompAssign)
1188    LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1189                              CK_IntegralRealToComplex);
1190  return ComplexType;
1191}
1192
1193/// UsualArithmeticConversions - Performs various conversions that are common to
1194/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1195/// routine returns the first non-arithmetic type found. The client is
1196/// responsible for emitting appropriate error diagnostics.
1197QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1198                                          bool IsCompAssign) {
1199  if (!IsCompAssign) {
1200    LHS = UsualUnaryConversions(LHS.take());
1201    if (LHS.isInvalid())
1202      return QualType();
1203  }
1204
1205  RHS = UsualUnaryConversions(RHS.take());
1206  if (RHS.isInvalid())
1207    return QualType();
1208
1209  // For conversion purposes, we ignore any qualifiers.
1210  // For example, "const float" and "float" are equivalent.
1211  QualType LHSType =
1212    Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1213  QualType RHSType =
1214    Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1215
1216  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1217  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1218    LHSType = AtomicLHS->getValueType();
1219
1220  // If both types are identical, no conversion is needed.
1221  if (LHSType == RHSType)
1222    return LHSType;
1223
1224  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1225  // The caller can deal with this (e.g. pointer + int).
1226  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1227    return QualType();
1228
1229  // Apply unary and bitfield promotions to the LHS's type.
1230  QualType LHSUnpromotedType = LHSType;
1231  if (LHSType->isPromotableIntegerType())
1232    LHSType = Context.getPromotedIntegerType(LHSType);
1233  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1234  if (!LHSBitfieldPromoteTy.isNull())
1235    LHSType = LHSBitfieldPromoteTy;
1236  if (LHSType != LHSUnpromotedType && !IsCompAssign)
1237    LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1238
1239  // If both types are identical, no conversion is needed.
1240  if (LHSType == RHSType)
1241    return LHSType;
1242
1243  // At this point, we have two different arithmetic types.
1244
1245  // Handle complex types first (C99 6.3.1.8p1).
1246  if (LHSType->isComplexType() || RHSType->isComplexType())
1247    return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1248                                        IsCompAssign);
1249
1250  // Now handle "real" floating types (i.e. float, double, long double).
1251  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1252    return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1253                                 IsCompAssign);
1254
1255  // Handle GCC complex int extension.
1256  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1257    return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1258                                      IsCompAssign);
1259
1260  // Finally, we have two differing integer types.
1261  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1262           (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1263}
1264
1265
1266//===----------------------------------------------------------------------===//
1267//  Semantic Analysis for various Expression Types
1268//===----------------------------------------------------------------------===//
1269
1270
1271ExprResult
1272Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1273                                SourceLocation DefaultLoc,
1274                                SourceLocation RParenLoc,
1275                                Expr *ControllingExpr,
1276                                ArrayRef<ParsedType> ArgTypes,
1277                                ArrayRef<Expr *> ArgExprs) {
1278  unsigned NumAssocs = ArgTypes.size();
1279  assert(NumAssocs == ArgExprs.size());
1280
1281  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1282  for (unsigned i = 0; i < NumAssocs; ++i) {
1283    if (ArgTypes[i])
1284      (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1285    else
1286      Types[i] = 0;
1287  }
1288
1289  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1290                                             ControllingExpr,
1291                                             llvm::makeArrayRef(Types, NumAssocs),
1292                                             ArgExprs);
1293  delete [] Types;
1294  return ER;
1295}
1296
1297ExprResult
1298Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1299                                 SourceLocation DefaultLoc,
1300                                 SourceLocation RParenLoc,
1301                                 Expr *ControllingExpr,
1302                                 ArrayRef<TypeSourceInfo *> Types,
1303                                 ArrayRef<Expr *> Exprs) {
1304  unsigned NumAssocs = Types.size();
1305  assert(NumAssocs == Exprs.size());
1306  if (ControllingExpr->getType()->isPlaceholderType()) {
1307    ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1308    if (result.isInvalid()) return ExprError();
1309    ControllingExpr = result.take();
1310  }
1311
1312  bool TypeErrorFound = false,
1313       IsResultDependent = ControllingExpr->isTypeDependent(),
1314       ContainsUnexpandedParameterPack
1315         = ControllingExpr->containsUnexpandedParameterPack();
1316
1317  for (unsigned i = 0; i < NumAssocs; ++i) {
1318    if (Exprs[i]->containsUnexpandedParameterPack())
1319      ContainsUnexpandedParameterPack = true;
1320
1321    if (Types[i]) {
1322      if (Types[i]->getType()->containsUnexpandedParameterPack())
1323        ContainsUnexpandedParameterPack = true;
1324
1325      if (Types[i]->getType()->isDependentType()) {
1326        IsResultDependent = true;
1327      } else {
1328        // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1329        // complete object type other than a variably modified type."
1330        unsigned D = 0;
1331        if (Types[i]->getType()->isIncompleteType())
1332          D = diag::err_assoc_type_incomplete;
1333        else if (!Types[i]->getType()->isObjectType())
1334          D = diag::err_assoc_type_nonobject;
1335        else if (Types[i]->getType()->isVariablyModifiedType())
1336          D = diag::err_assoc_type_variably_modified;
1337
1338        if (D != 0) {
1339          Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1340            << Types[i]->getTypeLoc().getSourceRange()
1341            << Types[i]->getType();
1342          TypeErrorFound = true;
1343        }
1344
1345        // C11 6.5.1.1p2 "No two generic associations in the same generic
1346        // selection shall specify compatible types."
1347        for (unsigned j = i+1; j < NumAssocs; ++j)
1348          if (Types[j] && !Types[j]->getType()->isDependentType() &&
1349              Context.typesAreCompatible(Types[i]->getType(),
1350                                         Types[j]->getType())) {
1351            Diag(Types[j]->getTypeLoc().getBeginLoc(),
1352                 diag::err_assoc_compatible_types)
1353              << Types[j]->getTypeLoc().getSourceRange()
1354              << Types[j]->getType()
1355              << Types[i]->getType();
1356            Diag(Types[i]->getTypeLoc().getBeginLoc(),
1357                 diag::note_compat_assoc)
1358              << Types[i]->getTypeLoc().getSourceRange()
1359              << Types[i]->getType();
1360            TypeErrorFound = true;
1361          }
1362      }
1363    }
1364  }
1365  if (TypeErrorFound)
1366    return ExprError();
1367
1368  // If we determined that the generic selection is result-dependent, don't
1369  // try to compute the result expression.
1370  if (IsResultDependent)
1371    return Owned(new (Context) GenericSelectionExpr(
1372                   Context, KeyLoc, ControllingExpr,
1373                   Types, Exprs,
1374                   DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1375
1376  SmallVector<unsigned, 1> CompatIndices;
1377  unsigned DefaultIndex = -1U;
1378  for (unsigned i = 0; i < NumAssocs; ++i) {
1379    if (!Types[i])
1380      DefaultIndex = i;
1381    else if (Context.typesAreCompatible(ControllingExpr->getType(),
1382                                        Types[i]->getType()))
1383      CompatIndices.push_back(i);
1384  }
1385
1386  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1387  // type compatible with at most one of the types named in its generic
1388  // association list."
1389  if (CompatIndices.size() > 1) {
1390    // We strip parens here because the controlling expression is typically
1391    // parenthesized in macro definitions.
1392    ControllingExpr = ControllingExpr->IgnoreParens();
1393    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1394      << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1395      << (unsigned) CompatIndices.size();
1396    for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1397         E = CompatIndices.end(); I != E; ++I) {
1398      Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1399           diag::note_compat_assoc)
1400        << Types[*I]->getTypeLoc().getSourceRange()
1401        << Types[*I]->getType();
1402    }
1403    return ExprError();
1404  }
1405
1406  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1407  // its controlling expression shall have type compatible with exactly one of
1408  // the types named in its generic association list."
1409  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1410    // We strip parens here because the controlling expression is typically
1411    // parenthesized in macro definitions.
1412    ControllingExpr = ControllingExpr->IgnoreParens();
1413    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1414      << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1415    return ExprError();
1416  }
1417
1418  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1419  // type name that is compatible with the type of the controlling expression,
1420  // then the result expression of the generic selection is the expression
1421  // in that generic association. Otherwise, the result expression of the
1422  // generic selection is the expression in the default generic association."
1423  unsigned ResultIndex =
1424    CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1425
1426  return Owned(new (Context) GenericSelectionExpr(
1427                 Context, KeyLoc, ControllingExpr,
1428                 Types, Exprs,
1429                 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1430                 ResultIndex));
1431}
1432
1433/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1434/// location of the token and the offset of the ud-suffix within it.
1435static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1436                                     unsigned Offset) {
1437  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1438                                        S.getLangOpts());
1439}
1440
1441/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1442/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1443static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1444                                                 IdentifierInfo *UDSuffix,
1445                                                 SourceLocation UDSuffixLoc,
1446                                                 ArrayRef<Expr*> Args,
1447                                                 SourceLocation LitEndLoc) {
1448  assert(Args.size() <= 2 && "too many arguments for literal operator");
1449
1450  QualType ArgTy[2];
1451  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1452    ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1453    if (ArgTy[ArgIdx]->isArrayType())
1454      ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1455  }
1456
1457  DeclarationName OpName =
1458    S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1459  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1460  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1461
1462  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1463  if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1464                              /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1465    return ExprError();
1466
1467  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1468}
1469
1470/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1471/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1472/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1473/// multiple tokens.  However, the common case is that StringToks points to one
1474/// string.
1475///
1476ExprResult
1477Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1478                         Scope *UDLScope) {
1479  assert(NumStringToks && "Must have at least one string!");
1480
1481  StringLiteralParser Literal(StringToks, NumStringToks, PP);
1482  if (Literal.hadError)
1483    return ExprError();
1484
1485  SmallVector<SourceLocation, 4> StringTokLocs;
1486  for (unsigned i = 0; i != NumStringToks; ++i)
1487    StringTokLocs.push_back(StringToks[i].getLocation());
1488
1489  QualType StrTy = Context.CharTy;
1490  if (Literal.isWide())
1491    StrTy = Context.getWideCharType();
1492  else if (Literal.isUTF16())
1493    StrTy = Context.Char16Ty;
1494  else if (Literal.isUTF32())
1495    StrTy = Context.Char32Ty;
1496  else if (Literal.isPascal())
1497    StrTy = Context.UnsignedCharTy;
1498
1499  StringLiteral::StringKind Kind = StringLiteral::Ascii;
1500  if (Literal.isWide())
1501    Kind = StringLiteral::Wide;
1502  else if (Literal.isUTF8())
1503    Kind = StringLiteral::UTF8;
1504  else if (Literal.isUTF16())
1505    Kind = StringLiteral::UTF16;
1506  else if (Literal.isUTF32())
1507    Kind = StringLiteral::UTF32;
1508
1509  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1510  if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1511    StrTy.addConst();
1512
1513  // Get an array type for the string, according to C99 6.4.5.  This includes
1514  // the nul terminator character as well as the string length for pascal
1515  // strings.
1516  StrTy = Context.getConstantArrayType(StrTy,
1517                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
1518                                       ArrayType::Normal, 0);
1519
1520  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1521  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1522                                             Kind, Literal.Pascal, StrTy,
1523                                             &StringTokLocs[0],
1524                                             StringTokLocs.size());
1525  if (Literal.getUDSuffix().empty())
1526    return Owned(Lit);
1527
1528  // We're building a user-defined literal.
1529  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1530  SourceLocation UDSuffixLoc =
1531    getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1532                   Literal.getUDSuffixOffset());
1533
1534  // Make sure we're allowed user-defined literals here.
1535  if (!UDLScope)
1536    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1537
1538  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1539  //   operator "" X (str, len)
1540  QualType SizeType = Context.getSizeType();
1541  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1542  IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1543                                                  StringTokLocs[0]);
1544  Expr *Args[] = { Lit, LenArg };
1545  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1546                                        Args, StringTokLocs.back());
1547}
1548
1549ExprResult
1550Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1551                       SourceLocation Loc,
1552                       const CXXScopeSpec *SS) {
1553  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1554  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1555}
1556
1557/// BuildDeclRefExpr - Build an expression that references a
1558/// declaration that does not require a closure capture.
1559ExprResult
1560Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1561                       const DeclarationNameInfo &NameInfo,
1562                       const CXXScopeSpec *SS, NamedDecl *FoundD,
1563                       const TemplateArgumentListInfo *TemplateArgs) {
1564  if (getLangOpts().CUDA)
1565    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1566      if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1567        CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1568                           CalleeTarget = IdentifyCUDATarget(Callee);
1569        if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1570          Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1571            << CalleeTarget << D->getIdentifier() << CallerTarget;
1572          Diag(D->getLocation(), diag::note_previous_decl)
1573            << D->getIdentifier();
1574          return ExprError();
1575        }
1576      }
1577
1578  bool refersToEnclosingScope =
1579    (CurContext != D->getDeclContext() &&
1580     D->getDeclContext()->isFunctionOrMethod());
1581
1582  DeclRefExpr *E;
1583  if (isa<VarTemplateSpecializationDecl>(D)) {
1584    VarTemplateSpecializationDecl *VarSpec =
1585        cast<VarTemplateSpecializationDecl>(D);
1586
1587    E = DeclRefExpr::Create(
1588        Context,
1589        SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1590        VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1591        NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1592  } else {
1593    assert(!TemplateArgs && "No template arguments for non-variable"
1594                            " template specialization referrences");
1595    E = DeclRefExpr::Create(
1596        Context,
1597        SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1598        SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1599  }
1600
1601  MarkDeclRefReferenced(E);
1602
1603  if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1604      Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1605    DiagnosticsEngine::Level Level =
1606      Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1607                               E->getLocStart());
1608    if (Level != DiagnosticsEngine::Ignored)
1609      recordUseOfEvaluatedWeak(E);
1610  }
1611
1612  // Just in case we're building an illegal pointer-to-member.
1613  FieldDecl *FD = dyn_cast<FieldDecl>(D);
1614  if (FD && FD->isBitField())
1615    E->setObjectKind(OK_BitField);
1616
1617  return Owned(E);
1618}
1619
1620/// Decomposes the given name into a DeclarationNameInfo, its location, and
1621/// possibly a list of template arguments.
1622///
1623/// If this produces template arguments, it is permitted to call
1624/// DecomposeTemplateName.
1625///
1626/// This actually loses a lot of source location information for
1627/// non-standard name kinds; we should consider preserving that in
1628/// some way.
1629void
1630Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1631                             TemplateArgumentListInfo &Buffer,
1632                             DeclarationNameInfo &NameInfo,
1633                             const TemplateArgumentListInfo *&TemplateArgs) {
1634  if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1635    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1636    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1637
1638    ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1639                                       Id.TemplateId->NumArgs);
1640    translateTemplateArguments(TemplateArgsPtr, Buffer);
1641
1642    TemplateName TName = Id.TemplateId->Template.get();
1643    SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1644    NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1645    TemplateArgs = &Buffer;
1646  } else {
1647    NameInfo = GetNameFromUnqualifiedId(Id);
1648    TemplateArgs = 0;
1649  }
1650}
1651
1652/// Diagnose an empty lookup.
1653///
1654/// \return false if new lookup candidates were found
1655bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1656                               CorrectionCandidateCallback &CCC,
1657                               TemplateArgumentListInfo *ExplicitTemplateArgs,
1658                               llvm::ArrayRef<Expr *> Args) {
1659  DeclarationName Name = R.getLookupName();
1660
1661  unsigned diagnostic = diag::err_undeclared_var_use;
1662  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1663  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1664      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1665      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1666    diagnostic = diag::err_undeclared_use;
1667    diagnostic_suggest = diag::err_undeclared_use_suggest;
1668  }
1669
1670  // If the original lookup was an unqualified lookup, fake an
1671  // unqualified lookup.  This is useful when (for example) the
1672  // original lookup would not have found something because it was a
1673  // dependent name.
1674  DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1675    ? CurContext : 0;
1676  while (DC) {
1677    if (isa<CXXRecordDecl>(DC)) {
1678      LookupQualifiedName(R, DC);
1679
1680      if (!R.empty()) {
1681        // Don't give errors about ambiguities in this lookup.
1682        R.suppressDiagnostics();
1683
1684        // During a default argument instantiation the CurContext points
1685        // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1686        // function parameter list, hence add an explicit check.
1687        bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1688                              ActiveTemplateInstantiations.back().Kind ==
1689            ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1690        CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1691        bool isInstance = CurMethod &&
1692                          CurMethod->isInstance() &&
1693                          DC == CurMethod->getParent() && !isDefaultArgument;
1694
1695
1696        // Give a code modification hint to insert 'this->'.
1697        // TODO: fixit for inserting 'Base<T>::' in the other cases.
1698        // Actually quite difficult!
1699        if (getLangOpts().MicrosoftMode)
1700          diagnostic = diag::warn_found_via_dependent_bases_lookup;
1701        if (isInstance) {
1702          Diag(R.getNameLoc(), diagnostic) << Name
1703            << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1704          UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1705              CallsUndergoingInstantiation.back()->getCallee());
1706
1707          CXXMethodDecl *DepMethod;
1708          if (CurMethod->isDependentContext())
1709            DepMethod = CurMethod;
1710          else if (CurMethod->getTemplatedKind() ==
1711              FunctionDecl::TK_FunctionTemplateSpecialization)
1712            DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1713                getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1714          else
1715            DepMethod = cast<CXXMethodDecl>(
1716                CurMethod->getInstantiatedFromMemberFunction());
1717          assert(DepMethod && "No template pattern found");
1718
1719          QualType DepThisType = DepMethod->getThisType(Context);
1720          CheckCXXThisCapture(R.getNameLoc());
1721          CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1722                                     R.getNameLoc(), DepThisType, false);
1723          TemplateArgumentListInfo TList;
1724          if (ULE->hasExplicitTemplateArgs())
1725            ULE->copyTemplateArgumentsInto(TList);
1726
1727          CXXScopeSpec SS;
1728          SS.Adopt(ULE->getQualifierLoc());
1729          CXXDependentScopeMemberExpr *DepExpr =
1730              CXXDependentScopeMemberExpr::Create(
1731                  Context, DepThis, DepThisType, true, SourceLocation(),
1732                  SS.getWithLocInContext(Context),
1733                  ULE->getTemplateKeywordLoc(), 0,
1734                  R.getLookupNameInfo(),
1735                  ULE->hasExplicitTemplateArgs() ? &TList : 0);
1736          CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1737        } else {
1738          Diag(R.getNameLoc(), diagnostic) << Name;
1739        }
1740
1741        // Do we really want to note all of these?
1742        for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1743          Diag((*I)->getLocation(), diag::note_dependent_var_use);
1744
1745        // Return true if we are inside a default argument instantiation
1746        // and the found name refers to an instance member function, otherwise
1747        // the function calling DiagnoseEmptyLookup will try to create an
1748        // implicit member call and this is wrong for default argument.
1749        if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1750          Diag(R.getNameLoc(), diag::err_member_call_without_object);
1751          return true;
1752        }
1753
1754        // Tell the callee to try to recover.
1755        return false;
1756      }
1757
1758      R.clear();
1759    }
1760
1761    // In Microsoft mode, if we are performing lookup from within a friend
1762    // function definition declared at class scope then we must set
1763    // DC to the lexical parent to be able to search into the parent
1764    // class.
1765    if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1766        cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1767        DC->getLexicalParent()->isRecord())
1768      DC = DC->getLexicalParent();
1769    else
1770      DC = DC->getParent();
1771  }
1772
1773  // We didn't find anything, so try to correct for a typo.
1774  TypoCorrection Corrected;
1775  if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1776                                    S, &SS, CCC))) {
1777    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1778    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1779    bool droppedSpecifier =
1780        Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1781    R.setLookupName(Corrected.getCorrection());
1782
1783    if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1784      if (Corrected.isOverloaded()) {
1785        OverloadCandidateSet OCS(R.getNameLoc());
1786        OverloadCandidateSet::iterator Best;
1787        for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1788                                        CDEnd = Corrected.end();
1789             CD != CDEnd; ++CD) {
1790          if (FunctionTemplateDecl *FTD =
1791                   dyn_cast<FunctionTemplateDecl>(*CD))
1792            AddTemplateOverloadCandidate(
1793                FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1794                Args, OCS);
1795          else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1796            if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1797              AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1798                                   Args, OCS);
1799        }
1800        switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1801          case OR_Success:
1802            ND = Best->Function;
1803            break;
1804          default:
1805            break;
1806        }
1807      }
1808      R.addDecl(ND);
1809      if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1810        if (SS.isEmpty())
1811          Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1812            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1813        else
1814          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1815            << Name << computeDeclContext(SS, false) << droppedSpecifier
1816            << CorrectedQuotedStr << SS.getRange()
1817            << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1818                                            CorrectedStr);
1819
1820        unsigned diag = isa<ImplicitParamDecl>(ND)
1821          ? diag::note_implicit_param_decl
1822          : diag::note_previous_decl;
1823
1824        Diag(ND->getLocation(), diag)
1825          << CorrectedQuotedStr;
1826
1827        // Tell the callee to try to recover.
1828        return false;
1829      }
1830
1831      if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1832        // FIXME: If we ended up with a typo for a type name or
1833        // Objective-C class name, we're in trouble because the parser
1834        // is in the wrong place to recover. Suggest the typo
1835        // correction, but don't make it a fix-it since we're not going
1836        // to recover well anyway.
1837        if (SS.isEmpty())
1838          Diag(R.getNameLoc(), diagnostic_suggest)
1839            << Name << CorrectedQuotedStr;
1840        else
1841          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1842            << Name << computeDeclContext(SS, false) << droppedSpecifier
1843            << CorrectedQuotedStr << SS.getRange();
1844
1845        // Don't try to recover; it won't work.
1846        return true;
1847      }
1848    } else {
1849      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1850      // because we aren't able to recover.
1851      if (SS.isEmpty())
1852        Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1853      else
1854        Diag(R.getNameLoc(), diag::err_no_member_suggest)
1855          << Name << computeDeclContext(SS, false) << droppedSpecifier
1856          << CorrectedQuotedStr << SS.getRange();
1857      return true;
1858    }
1859  }
1860  R.clear();
1861
1862  // Emit a special diagnostic for failed member lookups.
1863  // FIXME: computing the declaration context might fail here (?)
1864  if (!SS.isEmpty()) {
1865    Diag(R.getNameLoc(), diag::err_no_member)
1866      << Name << computeDeclContext(SS, false)
1867      << SS.getRange();
1868    return true;
1869  }
1870
1871  // Give up, we can't recover.
1872  Diag(R.getNameLoc(), diagnostic) << Name;
1873  return true;
1874}
1875
1876ExprResult Sema::ActOnIdExpression(Scope *S,
1877                                   CXXScopeSpec &SS,
1878                                   SourceLocation TemplateKWLoc,
1879                                   UnqualifiedId &Id,
1880                                   bool HasTrailingLParen,
1881                                   bool IsAddressOfOperand,
1882                                   CorrectionCandidateCallback *CCC,
1883                                   bool IsInlineAsmIdentifier) {
1884  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1885         "cannot be direct & operand and have a trailing lparen");
1886  if (SS.isInvalid())
1887    return ExprError();
1888
1889  TemplateArgumentListInfo TemplateArgsBuffer;
1890
1891  // Decompose the UnqualifiedId into the following data.
1892  DeclarationNameInfo NameInfo;
1893  const TemplateArgumentListInfo *TemplateArgs;
1894  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1895
1896  DeclarationName Name = NameInfo.getName();
1897  IdentifierInfo *II = Name.getAsIdentifierInfo();
1898  SourceLocation NameLoc = NameInfo.getLoc();
1899
1900  // C++ [temp.dep.expr]p3:
1901  //   An id-expression is type-dependent if it contains:
1902  //     -- an identifier that was declared with a dependent type,
1903  //        (note: handled after lookup)
1904  //     -- a template-id that is dependent,
1905  //        (note: handled in BuildTemplateIdExpr)
1906  //     -- a conversion-function-id that specifies a dependent type,
1907  //     -- a nested-name-specifier that contains a class-name that
1908  //        names a dependent type.
1909  // Determine whether this is a member of an unknown specialization;
1910  // we need to handle these differently.
1911  bool DependentID = false;
1912  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1913      Name.getCXXNameType()->isDependentType()) {
1914    DependentID = true;
1915  } else if (SS.isSet()) {
1916    if (DeclContext *DC = computeDeclContext(SS, false)) {
1917      if (RequireCompleteDeclContext(SS, DC))
1918        return ExprError();
1919    } else {
1920      DependentID = true;
1921    }
1922  }
1923
1924  if (DependentID)
1925    return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1926                                      IsAddressOfOperand, TemplateArgs);
1927
1928  // Perform the required lookup.
1929  LookupResult R(*this, NameInfo,
1930                 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1931                  ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1932  if (TemplateArgs) {
1933    // Lookup the template name again to correctly establish the context in
1934    // which it was found. This is really unfortunate as we already did the
1935    // lookup to determine that it was a template name in the first place. If
1936    // this becomes a performance hit, we can work harder to preserve those
1937    // results until we get here but it's likely not worth it.
1938    bool MemberOfUnknownSpecialization;
1939    LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1940                       MemberOfUnknownSpecialization);
1941
1942    if (MemberOfUnknownSpecialization ||
1943        (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1944      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1945                                        IsAddressOfOperand, TemplateArgs);
1946  } else {
1947    bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1948    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1949
1950    // If the result might be in a dependent base class, this is a dependent
1951    // id-expression.
1952    if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1953      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1954                                        IsAddressOfOperand, TemplateArgs);
1955
1956    // If this reference is in an Objective-C method, then we need to do
1957    // some special Objective-C lookup, too.
1958    if (IvarLookupFollowUp) {
1959      ExprResult E(LookupInObjCMethod(R, S, II, true));
1960      if (E.isInvalid())
1961        return ExprError();
1962
1963      if (Expr *Ex = E.takeAs<Expr>())
1964        return Owned(Ex);
1965    }
1966  }
1967
1968  if (R.isAmbiguous())
1969    return ExprError();
1970
1971  // Determine whether this name might be a candidate for
1972  // argument-dependent lookup.
1973  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1974
1975  if (R.empty() && !ADL) {
1976
1977    // Otherwise, this could be an implicitly declared function reference (legal
1978    // in C90, extension in C99, forbidden in C++).
1979    if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1980      NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1981      if (D) R.addDecl(D);
1982    }
1983
1984    // If this name wasn't predeclared and if this is not a function
1985    // call, diagnose the problem.
1986    if (R.empty()) {
1987      // In Microsoft mode, if we are inside a template class member function
1988      // whose parent class has dependent base classes, and we can't resolve
1989      // an identifier, then assume the identifier is type dependent.  The
1990      // goal is to postpone name lookup to instantiation time to be able to
1991      // search into the type dependent base classes.
1992      if (getLangOpts().MicrosoftMode) {
1993        CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
1994        if (MD && MD->getParent()->hasAnyDependentBases())
1995          return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1996                                            IsAddressOfOperand, TemplateArgs);
1997      }
1998
1999      // Don't diagnose an empty lookup for inline assmebly.
2000      if (IsInlineAsmIdentifier)
2001        return ExprError();
2002
2003      CorrectionCandidateCallback DefaultValidator;
2004      if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2005        return ExprError();
2006
2007      assert(!R.empty() &&
2008             "DiagnoseEmptyLookup returned false but added no results");
2009
2010      // If we found an Objective-C instance variable, let
2011      // LookupInObjCMethod build the appropriate expression to
2012      // reference the ivar.
2013      if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2014        R.clear();
2015        ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2016        // In a hopelessly buggy code, Objective-C instance variable
2017        // lookup fails and no expression will be built to reference it.
2018        if (!E.isInvalid() && !E.get())
2019          return ExprError();
2020        return E;
2021      }
2022    }
2023  }
2024
2025  // This is guaranteed from this point on.
2026  assert(!R.empty() || ADL);
2027
2028  // Check whether this might be a C++ implicit instance member access.
2029  // C++ [class.mfct.non-static]p3:
2030  //   When an id-expression that is not part of a class member access
2031  //   syntax and not used to form a pointer to member is used in the
2032  //   body of a non-static member function of class X, if name lookup
2033  //   resolves the name in the id-expression to a non-static non-type
2034  //   member of some class C, the id-expression is transformed into a
2035  //   class member access expression using (*this) as the
2036  //   postfix-expression to the left of the . operator.
2037  //
2038  // But we don't actually need to do this for '&' operands if R
2039  // resolved to a function or overloaded function set, because the
2040  // expression is ill-formed if it actually works out to be a
2041  // non-static member function:
2042  //
2043  // C++ [expr.ref]p4:
2044  //   Otherwise, if E1.E2 refers to a non-static member function. . .
2045  //   [t]he expression can be used only as the left-hand operand of a
2046  //   member function call.
2047  //
2048  // There are other safeguards against such uses, but it's important
2049  // to get this right here so that we don't end up making a
2050  // spuriously dependent expression if we're inside a dependent
2051  // instance method.
2052  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2053    bool MightBeImplicitMember;
2054    if (!IsAddressOfOperand)
2055      MightBeImplicitMember = true;
2056    else if (!SS.isEmpty())
2057      MightBeImplicitMember = false;
2058    else if (R.isOverloadedResult())
2059      MightBeImplicitMember = false;
2060    else if (R.isUnresolvableResult())
2061      MightBeImplicitMember = true;
2062    else
2063      MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2064                              isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2065                              isa<MSPropertyDecl>(R.getFoundDecl());
2066
2067    if (MightBeImplicitMember)
2068      return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2069                                             R, TemplateArgs);
2070  }
2071
2072  if (TemplateArgs || TemplateKWLoc.isValid()) {
2073
2074    // In C++1y, if this is a variable template id, then check it
2075    // in BuildTemplateIdExpr().
2076    // The single lookup result must be a variable template declaration.
2077    if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2078        Id.TemplateId->Kind == TNK_Var_template) {
2079      assert(R.getAsSingle<VarTemplateDecl>() &&
2080             "There should only be one declaration found.");
2081    }
2082
2083    return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2084  }
2085
2086  return BuildDeclarationNameExpr(SS, R, ADL);
2087}
2088
2089/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2090/// declaration name, generally during template instantiation.
2091/// There's a large number of things which don't need to be done along
2092/// this path.
2093ExprResult
2094Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2095                                        const DeclarationNameInfo &NameInfo,
2096                                        bool IsAddressOfOperand) {
2097  DeclContext *DC = computeDeclContext(SS, false);
2098  if (!DC)
2099    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2100                                     NameInfo, /*TemplateArgs=*/0);
2101
2102  if (RequireCompleteDeclContext(SS, DC))
2103    return ExprError();
2104
2105  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2106  LookupQualifiedName(R, DC);
2107
2108  if (R.isAmbiguous())
2109    return ExprError();
2110
2111  if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2112    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2113                                     NameInfo, /*TemplateArgs=*/0);
2114
2115  if (R.empty()) {
2116    Diag(NameInfo.getLoc(), diag::err_no_member)
2117      << NameInfo.getName() << DC << SS.getRange();
2118    return ExprError();
2119  }
2120
2121  // Defend against this resolving to an implicit member access. We usually
2122  // won't get here if this might be a legitimate a class member (we end up in
2123  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2124  // a pointer-to-member or in an unevaluated context in C++11.
2125  if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2126    return BuildPossibleImplicitMemberExpr(SS,
2127                                           /*TemplateKWLoc=*/SourceLocation(),
2128                                           R, /*TemplateArgs=*/0);
2129
2130  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2131}
2132
2133/// LookupInObjCMethod - The parser has read a name in, and Sema has
2134/// detected that we're currently inside an ObjC method.  Perform some
2135/// additional lookup.
2136///
2137/// Ideally, most of this would be done by lookup, but there's
2138/// actually quite a lot of extra work involved.
2139///
2140/// Returns a null sentinel to indicate trivial success.
2141ExprResult
2142Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2143                         IdentifierInfo *II, bool AllowBuiltinCreation) {
2144  SourceLocation Loc = Lookup.getNameLoc();
2145  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2146
2147  // Check for error condition which is already reported.
2148  if (!CurMethod)
2149    return ExprError();
2150
2151  // There are two cases to handle here.  1) scoped lookup could have failed,
2152  // in which case we should look for an ivar.  2) scoped lookup could have
2153  // found a decl, but that decl is outside the current instance method (i.e.
2154  // a global variable).  In these two cases, we do a lookup for an ivar with
2155  // this name, if the lookup sucedes, we replace it our current decl.
2156
2157  // If we're in a class method, we don't normally want to look for
2158  // ivars.  But if we don't find anything else, and there's an
2159  // ivar, that's an error.
2160  bool IsClassMethod = CurMethod->isClassMethod();
2161
2162  bool LookForIvars;
2163  if (Lookup.empty())
2164    LookForIvars = true;
2165  else if (IsClassMethod)
2166    LookForIvars = false;
2167  else
2168    LookForIvars = (Lookup.isSingleResult() &&
2169                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2170  ObjCInterfaceDecl *IFace = 0;
2171  if (LookForIvars) {
2172    IFace = CurMethod->getClassInterface();
2173    ObjCInterfaceDecl *ClassDeclared;
2174    ObjCIvarDecl *IV = 0;
2175    if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2176      // Diagnose using an ivar in a class method.
2177      if (IsClassMethod)
2178        return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2179                         << IV->getDeclName());
2180
2181      // If we're referencing an invalid decl, just return this as a silent
2182      // error node.  The error diagnostic was already emitted on the decl.
2183      if (IV->isInvalidDecl())
2184        return ExprError();
2185
2186      // Check if referencing a field with __attribute__((deprecated)).
2187      if (DiagnoseUseOfDecl(IV, Loc))
2188        return ExprError();
2189
2190      // Diagnose the use of an ivar outside of the declaring class.
2191      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2192          !declaresSameEntity(ClassDeclared, IFace) &&
2193          !getLangOpts().DebuggerSupport)
2194        Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2195
2196      // FIXME: This should use a new expr for a direct reference, don't
2197      // turn this into Self->ivar, just return a BareIVarExpr or something.
2198      IdentifierInfo &II = Context.Idents.get("self");
2199      UnqualifiedId SelfName;
2200      SelfName.setIdentifier(&II, SourceLocation());
2201      SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2202      CXXScopeSpec SelfScopeSpec;
2203      SourceLocation TemplateKWLoc;
2204      ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2205                                              SelfName, false, false);
2206      if (SelfExpr.isInvalid())
2207        return ExprError();
2208
2209      SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2210      if (SelfExpr.isInvalid())
2211        return ExprError();
2212
2213      MarkAnyDeclReferenced(Loc, IV, true);
2214
2215      ObjCMethodFamily MF = CurMethod->getMethodFamily();
2216      if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2217          !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2218        Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2219
2220      ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2221                                                              Loc, IV->getLocation(),
2222                                                              SelfExpr.take(),
2223                                                              true, true);
2224
2225      if (getLangOpts().ObjCAutoRefCount) {
2226        if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2227          DiagnosticsEngine::Level Level =
2228            Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2229          if (Level != DiagnosticsEngine::Ignored)
2230            recordUseOfEvaluatedWeak(Result);
2231        }
2232        if (CurContext->isClosure())
2233          Diag(Loc, diag::warn_implicitly_retains_self)
2234            << FixItHint::CreateInsertion(Loc, "self->");
2235      }
2236
2237      return Owned(Result);
2238    }
2239  } else if (CurMethod->isInstanceMethod()) {
2240    // We should warn if a local variable hides an ivar.
2241    if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2242      ObjCInterfaceDecl *ClassDeclared;
2243      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2244        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2245            declaresSameEntity(IFace, ClassDeclared))
2246          Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2247      }
2248    }
2249  } else if (Lookup.isSingleResult() &&
2250             Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2251    // If accessing a stand-alone ivar in a class method, this is an error.
2252    if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2253      return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2254                       << IV->getDeclName());
2255  }
2256
2257  if (Lookup.empty() && II && AllowBuiltinCreation) {
2258    // FIXME. Consolidate this with similar code in LookupName.
2259    if (unsigned BuiltinID = II->getBuiltinID()) {
2260      if (!(getLangOpts().CPlusPlus &&
2261            Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2262        NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2263                                           S, Lookup.isForRedeclaration(),
2264                                           Lookup.getNameLoc());
2265        if (D) Lookup.addDecl(D);
2266      }
2267    }
2268  }
2269  // Sentinel value saying that we didn't do anything special.
2270  return Owned((Expr*) 0);
2271}
2272
2273/// \brief Cast a base object to a member's actual type.
2274///
2275/// Logically this happens in three phases:
2276///
2277/// * First we cast from the base type to the naming class.
2278///   The naming class is the class into which we were looking
2279///   when we found the member;  it's the qualifier type if a
2280///   qualifier was provided, and otherwise it's the base type.
2281///
2282/// * Next we cast from the naming class to the declaring class.
2283///   If the member we found was brought into a class's scope by
2284///   a using declaration, this is that class;  otherwise it's
2285///   the class declaring the member.
2286///
2287/// * Finally we cast from the declaring class to the "true"
2288///   declaring class of the member.  This conversion does not
2289///   obey access control.
2290ExprResult
2291Sema::PerformObjectMemberConversion(Expr *From,
2292                                    NestedNameSpecifier *Qualifier,
2293                                    NamedDecl *FoundDecl,
2294                                    NamedDecl *Member) {
2295  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2296  if (!RD)
2297    return Owned(From);
2298
2299  QualType DestRecordType;
2300  QualType DestType;
2301  QualType FromRecordType;
2302  QualType FromType = From->getType();
2303  bool PointerConversions = false;
2304  if (isa<FieldDecl>(Member)) {
2305    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2306
2307    if (FromType->getAs<PointerType>()) {
2308      DestType = Context.getPointerType(DestRecordType);
2309      FromRecordType = FromType->getPointeeType();
2310      PointerConversions = true;
2311    } else {
2312      DestType = DestRecordType;
2313      FromRecordType = FromType;
2314    }
2315  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2316    if (Method->isStatic())
2317      return Owned(From);
2318
2319    DestType = Method->getThisType(Context);
2320    DestRecordType = DestType->getPointeeType();
2321
2322    if (FromType->getAs<PointerType>()) {
2323      FromRecordType = FromType->getPointeeType();
2324      PointerConversions = true;
2325    } else {
2326      FromRecordType = FromType;
2327      DestType = DestRecordType;
2328    }
2329  } else {
2330    // No conversion necessary.
2331    return Owned(From);
2332  }
2333
2334  if (DestType->isDependentType() || FromType->isDependentType())
2335    return Owned(From);
2336
2337  // If the unqualified types are the same, no conversion is necessary.
2338  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2339    return Owned(From);
2340
2341  SourceRange FromRange = From->getSourceRange();
2342  SourceLocation FromLoc = FromRange.getBegin();
2343
2344  ExprValueKind VK = From->getValueKind();
2345
2346  // C++ [class.member.lookup]p8:
2347  //   [...] Ambiguities can often be resolved by qualifying a name with its
2348  //   class name.
2349  //
2350  // If the member was a qualified name and the qualified referred to a
2351  // specific base subobject type, we'll cast to that intermediate type
2352  // first and then to the object in which the member is declared. That allows
2353  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2354  //
2355  //   class Base { public: int x; };
2356  //   class Derived1 : public Base { };
2357  //   class Derived2 : public Base { };
2358  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2359  //
2360  //   void VeryDerived::f() {
2361  //     x = 17; // error: ambiguous base subobjects
2362  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2363  //   }
2364  if (Qualifier && Qualifier->getAsType()) {
2365    QualType QType = QualType(Qualifier->getAsType(), 0);
2366    assert(QType->isRecordType() && "lookup done with non-record type");
2367
2368    QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2369
2370    // In C++98, the qualifier type doesn't actually have to be a base
2371    // type of the object type, in which case we just ignore it.
2372    // Otherwise build the appropriate casts.
2373    if (IsDerivedFrom(FromRecordType, QRecordType)) {
2374      CXXCastPath BasePath;
2375      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2376                                       FromLoc, FromRange, &BasePath))
2377        return ExprError();
2378
2379      if (PointerConversions)
2380        QType = Context.getPointerType(QType);
2381      From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2382                               VK, &BasePath).take();
2383
2384      FromType = QType;
2385      FromRecordType = QRecordType;
2386
2387      // If the qualifier type was the same as the destination type,
2388      // we're done.
2389      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2390        return Owned(From);
2391    }
2392  }
2393
2394  bool IgnoreAccess = false;
2395
2396  // If we actually found the member through a using declaration, cast
2397  // down to the using declaration's type.
2398  //
2399  // Pointer equality is fine here because only one declaration of a
2400  // class ever has member declarations.
2401  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2402    assert(isa<UsingShadowDecl>(FoundDecl));
2403    QualType URecordType = Context.getTypeDeclType(
2404                           cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2405
2406    // We only need to do this if the naming-class to declaring-class
2407    // conversion is non-trivial.
2408    if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2409      assert(IsDerivedFrom(FromRecordType, URecordType));
2410      CXXCastPath BasePath;
2411      if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2412                                       FromLoc, FromRange, &BasePath))
2413        return ExprError();
2414
2415      QualType UType = URecordType;
2416      if (PointerConversions)
2417        UType = Context.getPointerType(UType);
2418      From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2419                               VK, &BasePath).take();
2420      FromType = UType;
2421      FromRecordType = URecordType;
2422    }
2423
2424    // We don't do access control for the conversion from the
2425    // declaring class to the true declaring class.
2426    IgnoreAccess = true;
2427  }
2428
2429  CXXCastPath BasePath;
2430  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2431                                   FromLoc, FromRange, &BasePath,
2432                                   IgnoreAccess))
2433    return ExprError();
2434
2435  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2436                           VK, &BasePath);
2437}
2438
2439bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2440                                      const LookupResult &R,
2441                                      bool HasTrailingLParen) {
2442  // Only when used directly as the postfix-expression of a call.
2443  if (!HasTrailingLParen)
2444    return false;
2445
2446  // Never if a scope specifier was provided.
2447  if (SS.isSet())
2448    return false;
2449
2450  // Only in C++ or ObjC++.
2451  if (!getLangOpts().CPlusPlus)
2452    return false;
2453
2454  // Turn off ADL when we find certain kinds of declarations during
2455  // normal lookup:
2456  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2457    NamedDecl *D = *I;
2458
2459    // C++0x [basic.lookup.argdep]p3:
2460    //     -- a declaration of a class member
2461    // Since using decls preserve this property, we check this on the
2462    // original decl.
2463    if (D->isCXXClassMember())
2464      return false;
2465
2466    // C++0x [basic.lookup.argdep]p3:
2467    //     -- a block-scope function declaration that is not a
2468    //        using-declaration
2469    // NOTE: we also trigger this for function templates (in fact, we
2470    // don't check the decl type at all, since all other decl types
2471    // turn off ADL anyway).
2472    if (isa<UsingShadowDecl>(D))
2473      D = cast<UsingShadowDecl>(D)->getTargetDecl();
2474    else if (D->getDeclContext()->isFunctionOrMethod())
2475      return false;
2476
2477    // C++0x [basic.lookup.argdep]p3:
2478    //     -- a declaration that is neither a function or a function
2479    //        template
2480    // And also for builtin functions.
2481    if (isa<FunctionDecl>(D)) {
2482      FunctionDecl *FDecl = cast<FunctionDecl>(D);
2483
2484      // But also builtin functions.
2485      if (FDecl->getBuiltinID() && FDecl->isImplicit())
2486        return false;
2487    } else if (!isa<FunctionTemplateDecl>(D))
2488      return false;
2489  }
2490
2491  return true;
2492}
2493
2494
2495/// Diagnoses obvious problems with the use of the given declaration
2496/// as an expression.  This is only actually called for lookups that
2497/// were not overloaded, and it doesn't promise that the declaration
2498/// will in fact be used.
2499static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2500  if (isa<TypedefNameDecl>(D)) {
2501    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2502    return true;
2503  }
2504
2505  if (isa<ObjCInterfaceDecl>(D)) {
2506    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2507    return true;
2508  }
2509
2510  if (isa<NamespaceDecl>(D)) {
2511    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2512    return true;
2513  }
2514
2515  return false;
2516}
2517
2518ExprResult
2519Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2520                               LookupResult &R,
2521                               bool NeedsADL) {
2522  // If this is a single, fully-resolved result and we don't need ADL,
2523  // just build an ordinary singleton decl ref.
2524  if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2525    return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2526                                    R.getRepresentativeDecl());
2527
2528  // We only need to check the declaration if there's exactly one
2529  // result, because in the overloaded case the results can only be
2530  // functions and function templates.
2531  if (R.isSingleResult() &&
2532      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2533    return ExprError();
2534
2535  // Otherwise, just build an unresolved lookup expression.  Suppress
2536  // any lookup-related diagnostics; we'll hash these out later, when
2537  // we've picked a target.
2538  R.suppressDiagnostics();
2539
2540  UnresolvedLookupExpr *ULE
2541    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2542                                   SS.getWithLocInContext(Context),
2543                                   R.getLookupNameInfo(),
2544                                   NeedsADL, R.isOverloadedResult(),
2545                                   R.begin(), R.end());
2546
2547  return Owned(ULE);
2548}
2549
2550/// \brief Complete semantic analysis for a reference to the given declaration.
2551ExprResult Sema::BuildDeclarationNameExpr(
2552    const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2553    NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2554  assert(D && "Cannot refer to a NULL declaration");
2555  assert(!isa<FunctionTemplateDecl>(D) &&
2556         "Cannot refer unambiguously to a function template");
2557
2558  SourceLocation Loc = NameInfo.getLoc();
2559  if (CheckDeclInExpr(*this, Loc, D))
2560    return ExprError();
2561
2562  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2563    // Specifically diagnose references to class templates that are missing
2564    // a template argument list.
2565    Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2566                                           << Template << SS.getRange();
2567    Diag(Template->getLocation(), diag::note_template_decl_here);
2568    return ExprError();
2569  }
2570
2571  // Make sure that we're referring to a value.
2572  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2573  if (!VD) {
2574    Diag(Loc, diag::err_ref_non_value)
2575      << D << SS.getRange();
2576    Diag(D->getLocation(), diag::note_declared_at);
2577    return ExprError();
2578  }
2579
2580  // Check whether this declaration can be used. Note that we suppress
2581  // this check when we're going to perform argument-dependent lookup
2582  // on this function name, because this might not be the function
2583  // that overload resolution actually selects.
2584  if (DiagnoseUseOfDecl(VD, Loc))
2585    return ExprError();
2586
2587  // Only create DeclRefExpr's for valid Decl's.
2588  if (VD->isInvalidDecl())
2589    return ExprError();
2590
2591  // Handle members of anonymous structs and unions.  If we got here,
2592  // and the reference is to a class member indirect field, then this
2593  // must be the subject of a pointer-to-member expression.
2594  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2595    if (!indirectField->isCXXClassMember())
2596      return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2597                                                      indirectField);
2598
2599  {
2600    QualType type = VD->getType();
2601    ExprValueKind valueKind = VK_RValue;
2602
2603    switch (D->getKind()) {
2604    // Ignore all the non-ValueDecl kinds.
2605#define ABSTRACT_DECL(kind)
2606#define VALUE(type, base)
2607#define DECL(type, base) \
2608    case Decl::type:
2609#include "clang/AST/DeclNodes.inc"
2610      llvm_unreachable("invalid value decl kind");
2611
2612    // These shouldn't make it here.
2613    case Decl::ObjCAtDefsField:
2614    case Decl::ObjCIvar:
2615      llvm_unreachable("forming non-member reference to ivar?");
2616
2617    // Enum constants are always r-values and never references.
2618    // Unresolved using declarations are dependent.
2619    case Decl::EnumConstant:
2620    case Decl::UnresolvedUsingValue:
2621      valueKind = VK_RValue;
2622      break;
2623
2624    // Fields and indirect fields that got here must be for
2625    // pointer-to-member expressions; we just call them l-values for
2626    // internal consistency, because this subexpression doesn't really
2627    // exist in the high-level semantics.
2628    case Decl::Field:
2629    case Decl::IndirectField:
2630      assert(getLangOpts().CPlusPlus &&
2631             "building reference to field in C?");
2632
2633      // These can't have reference type in well-formed programs, but
2634      // for internal consistency we do this anyway.
2635      type = type.getNonReferenceType();
2636      valueKind = VK_LValue;
2637      break;
2638
2639    // Non-type template parameters are either l-values or r-values
2640    // depending on the type.
2641    case Decl::NonTypeTemplateParm: {
2642      if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2643        type = reftype->getPointeeType();
2644        valueKind = VK_LValue; // even if the parameter is an r-value reference
2645        break;
2646      }
2647
2648      // For non-references, we need to strip qualifiers just in case
2649      // the template parameter was declared as 'const int' or whatever.
2650      valueKind = VK_RValue;
2651      type = type.getUnqualifiedType();
2652      break;
2653    }
2654
2655    case Decl::Var:
2656    case Decl::VarTemplateSpecialization:
2657    case Decl::VarTemplatePartialSpecialization:
2658      // In C, "extern void blah;" is valid and is an r-value.
2659      if (!getLangOpts().CPlusPlus &&
2660          !type.hasQualifiers() &&
2661          type->isVoidType()) {
2662        valueKind = VK_RValue;
2663        break;
2664      }
2665      // fallthrough
2666
2667    case Decl::ImplicitParam:
2668    case Decl::ParmVar: {
2669      // These are always l-values.
2670      valueKind = VK_LValue;
2671      type = type.getNonReferenceType();
2672
2673      // FIXME: Does the addition of const really only apply in
2674      // potentially-evaluated contexts? Since the variable isn't actually
2675      // captured in an unevaluated context, it seems that the answer is no.
2676      if (!isUnevaluatedContext()) {
2677        QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2678        if (!CapturedType.isNull())
2679          type = CapturedType;
2680      }
2681
2682      break;
2683    }
2684
2685    case Decl::Function: {
2686      if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2687        if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2688          type = Context.BuiltinFnTy;
2689          valueKind = VK_RValue;
2690          break;
2691        }
2692      }
2693
2694      const FunctionType *fty = type->castAs<FunctionType>();
2695
2696      // If we're referring to a function with an __unknown_anytype
2697      // result type, make the entire expression __unknown_anytype.
2698      if (fty->getResultType() == Context.UnknownAnyTy) {
2699        type = Context.UnknownAnyTy;
2700        valueKind = VK_RValue;
2701        break;
2702      }
2703
2704      // Functions are l-values in C++.
2705      if (getLangOpts().CPlusPlus) {
2706        valueKind = VK_LValue;
2707        break;
2708      }
2709
2710      // C99 DR 316 says that, if a function type comes from a
2711      // function definition (without a prototype), that type is only
2712      // used for checking compatibility. Therefore, when referencing
2713      // the function, we pretend that we don't have the full function
2714      // type.
2715      if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2716          isa<FunctionProtoType>(fty))
2717        type = Context.getFunctionNoProtoType(fty->getResultType(),
2718                                              fty->getExtInfo());
2719
2720      // Functions are r-values in C.
2721      valueKind = VK_RValue;
2722      break;
2723    }
2724
2725    case Decl::MSProperty:
2726      valueKind = VK_LValue;
2727      break;
2728
2729    case Decl::CXXMethod:
2730      // If we're referring to a method with an __unknown_anytype
2731      // result type, make the entire expression __unknown_anytype.
2732      // This should only be possible with a type written directly.
2733      if (const FunctionProtoType *proto
2734            = dyn_cast<FunctionProtoType>(VD->getType()))
2735        if (proto->getResultType() == Context.UnknownAnyTy) {
2736          type = Context.UnknownAnyTy;
2737          valueKind = VK_RValue;
2738          break;
2739        }
2740
2741      // C++ methods are l-values if static, r-values if non-static.
2742      if (cast<CXXMethodDecl>(VD)->isStatic()) {
2743        valueKind = VK_LValue;
2744        break;
2745      }
2746      // fallthrough
2747
2748    case Decl::CXXConversion:
2749    case Decl::CXXDestructor:
2750    case Decl::CXXConstructor:
2751      valueKind = VK_RValue;
2752      break;
2753    }
2754
2755    return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2756                            TemplateArgs);
2757  }
2758}
2759
2760ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2761  PredefinedExpr::IdentType IT;
2762
2763  switch (Kind) {
2764  default: llvm_unreachable("Unknown simple primary expr!");
2765  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2766  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2767  case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2768  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2769  }
2770
2771  // Pre-defined identifiers are of type char[x], where x is the length of the
2772  // string.
2773
2774  Decl *currentDecl = getCurFunctionOrMethodDecl();
2775  // Blocks and lambdas can occur at global scope. Don't emit a warning.
2776  if (!currentDecl) {
2777    if (const BlockScopeInfo *BSI = getCurBlock())
2778      currentDecl = BSI->TheDecl;
2779    else if (const LambdaScopeInfo *LSI = getCurLambda())
2780      currentDecl = LSI->CallOperator;
2781  }
2782
2783  if (!currentDecl) {
2784    Diag(Loc, diag::ext_predef_outside_function);
2785    currentDecl = Context.getTranslationUnitDecl();
2786  }
2787
2788  QualType ResTy;
2789  if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2790    ResTy = Context.DependentTy;
2791  } else {
2792    unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2793
2794    llvm::APInt LengthI(32, Length + 1);
2795    if (IT == PredefinedExpr::LFunction)
2796      ResTy = Context.WideCharTy.withConst();
2797    else
2798      ResTy = Context.CharTy.withConst();
2799    ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2800  }
2801  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2802}
2803
2804ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2805  SmallString<16> CharBuffer;
2806  bool Invalid = false;
2807  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2808  if (Invalid)
2809    return ExprError();
2810
2811  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2812                            PP, Tok.getKind());
2813  if (Literal.hadError())
2814    return ExprError();
2815
2816  QualType Ty;
2817  if (Literal.isWide())
2818    Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2819  else if (Literal.isUTF16())
2820    Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2821  else if (Literal.isUTF32())
2822    Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2823  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2824    Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2825  else
2826    Ty = Context.CharTy;  // 'x' -> char in C++
2827
2828  CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2829  if (Literal.isWide())
2830    Kind = CharacterLiteral::Wide;
2831  else if (Literal.isUTF16())
2832    Kind = CharacterLiteral::UTF16;
2833  else if (Literal.isUTF32())
2834    Kind = CharacterLiteral::UTF32;
2835
2836  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2837                                             Tok.getLocation());
2838
2839  if (Literal.getUDSuffix().empty())
2840    return Owned(Lit);
2841
2842  // We're building a user-defined literal.
2843  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2844  SourceLocation UDSuffixLoc =
2845    getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2846
2847  // Make sure we're allowed user-defined literals here.
2848  if (!UDLScope)
2849    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2850
2851  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2852  //   operator "" X (ch)
2853  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2854                                        Lit, Tok.getLocation());
2855}
2856
2857ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2858  unsigned IntSize = Context.getTargetInfo().getIntWidth();
2859  return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2860                                      Context.IntTy, Loc));
2861}
2862
2863static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2864                                  QualType Ty, SourceLocation Loc) {
2865  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2866
2867  using llvm::APFloat;
2868  APFloat Val(Format);
2869
2870  APFloat::opStatus result = Literal.GetFloatValue(Val);
2871
2872  // Overflow is always an error, but underflow is only an error if
2873  // we underflowed to zero (APFloat reports denormals as underflow).
2874  if ((result & APFloat::opOverflow) ||
2875      ((result & APFloat::opUnderflow) && Val.isZero())) {
2876    unsigned diagnostic;
2877    SmallString<20> buffer;
2878    if (result & APFloat::opOverflow) {
2879      diagnostic = diag::warn_float_overflow;
2880      APFloat::getLargest(Format).toString(buffer);
2881    } else {
2882      diagnostic = diag::warn_float_underflow;
2883      APFloat::getSmallest(Format).toString(buffer);
2884    }
2885
2886    S.Diag(Loc, diagnostic)
2887      << Ty
2888      << StringRef(buffer.data(), buffer.size());
2889  }
2890
2891  bool isExact = (result == APFloat::opOK);
2892  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2893}
2894
2895ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2896  // Fast path for a single digit (which is quite common).  A single digit
2897  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2898  if (Tok.getLength() == 1) {
2899    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2900    return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2901  }
2902
2903  SmallString<128> SpellingBuffer;
2904  // NumericLiteralParser wants to overread by one character.  Add padding to
2905  // the buffer in case the token is copied to the buffer.  If getSpelling()
2906  // returns a StringRef to the memory buffer, it should have a null char at
2907  // the EOF, so it is also safe.
2908  SpellingBuffer.resize(Tok.getLength() + 1);
2909
2910  // Get the spelling of the token, which eliminates trigraphs, etc.
2911  bool Invalid = false;
2912  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2913  if (Invalid)
2914    return ExprError();
2915
2916  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2917  if (Literal.hadError)
2918    return ExprError();
2919
2920  if (Literal.hasUDSuffix()) {
2921    // We're building a user-defined literal.
2922    IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2923    SourceLocation UDSuffixLoc =
2924      getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2925
2926    // Make sure we're allowed user-defined literals here.
2927    if (!UDLScope)
2928      return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2929
2930    QualType CookedTy;
2931    if (Literal.isFloatingLiteral()) {
2932      // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2933      // long double, the literal is treated as a call of the form
2934      //   operator "" X (f L)
2935      CookedTy = Context.LongDoubleTy;
2936    } else {
2937      // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2938      // unsigned long long, the literal is treated as a call of the form
2939      //   operator "" X (n ULL)
2940      CookedTy = Context.UnsignedLongLongTy;
2941    }
2942
2943    DeclarationName OpName =
2944      Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2945    DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2946    OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2947
2948    // Perform literal operator lookup to determine if we're building a raw
2949    // literal or a cooked one.
2950    LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2951    switch (LookupLiteralOperator(UDLScope, R, CookedTy,
2952                                  /*AllowRawAndTemplate*/true)) {
2953    case LOLR_Error:
2954      return ExprError();
2955
2956    case LOLR_Cooked: {
2957      Expr *Lit;
2958      if (Literal.isFloatingLiteral()) {
2959        Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2960      } else {
2961        llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2962        if (Literal.GetIntegerValue(ResultVal))
2963          Diag(Tok.getLocation(), diag::err_integer_too_large);
2964        Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2965                                     Tok.getLocation());
2966      }
2967      return BuildLiteralOperatorCall(R, OpNameInfo, Lit,
2968                                      Tok.getLocation());
2969    }
2970
2971    case LOLR_Raw: {
2972      // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2973      // literal is treated as a call of the form
2974      //   operator "" X ("n")
2975      SourceLocation TokLoc = Tok.getLocation();
2976      unsigned Length = Literal.getUDSuffixOffset();
2977      QualType StrTy = Context.getConstantArrayType(
2978          Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
2979          ArrayType::Normal, 0);
2980      Expr *Lit = StringLiteral::Create(
2981          Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
2982          /*Pascal*/false, StrTy, &TokLoc, 1);
2983      return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
2984    }
2985
2986    case LOLR_Template:
2987      // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2988      // template), L is treated as a call fo the form
2989      //   operator "" X <'c1', 'c2', ... 'ck'>()
2990      // where n is the source character sequence c1 c2 ... ck.
2991      TemplateArgumentListInfo ExplicitArgs;
2992      unsigned CharBits = Context.getIntWidth(Context.CharTy);
2993      bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2994      llvm::APSInt Value(CharBits, CharIsUnsigned);
2995      for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2996        Value = TokSpelling[I];
2997        TemplateArgument Arg(Context, Value, Context.CharTy);
2998        TemplateArgumentLocInfo ArgInfo;
2999        ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3000      }
3001      return BuildLiteralOperatorCall(R, OpNameInfo, None, Tok.getLocation(),
3002                                      &ExplicitArgs);
3003    }
3004
3005    llvm_unreachable("unexpected literal operator lookup result");
3006  }
3007
3008  Expr *Res;
3009
3010  if (Literal.isFloatingLiteral()) {
3011    QualType Ty;
3012    if (Literal.isFloat)
3013      Ty = Context.FloatTy;
3014    else if (!Literal.isLong)
3015      Ty = Context.DoubleTy;
3016    else
3017      Ty = Context.LongDoubleTy;
3018
3019    Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3020
3021    if (Ty == Context.DoubleTy) {
3022      if (getLangOpts().SinglePrecisionConstants) {
3023        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3024      } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3025        Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3026        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3027      }
3028    }
3029  } else if (!Literal.isIntegerLiteral()) {
3030    return ExprError();
3031  } else {
3032    QualType Ty;
3033
3034    // 'long long' is a C99 or C++11 feature.
3035    if (!getLangOpts().C99 && Literal.isLongLong) {
3036      if (getLangOpts().CPlusPlus)
3037        Diag(Tok.getLocation(),
3038             getLangOpts().CPlusPlus11 ?
3039             diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3040      else
3041        Diag(Tok.getLocation(), diag::ext_c99_longlong);
3042    }
3043
3044    // Get the value in the widest-possible width.
3045    unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3046    // The microsoft literal suffix extensions support 128-bit literals, which
3047    // may be wider than [u]intmax_t.
3048    // FIXME: Actually, they don't. We seem to have accidentally invented the
3049    //        i128 suffix.
3050    if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3051        PP.getTargetInfo().hasInt128Type())
3052      MaxWidth = 128;
3053    llvm::APInt ResultVal(MaxWidth, 0);
3054
3055    if (Literal.GetIntegerValue(ResultVal)) {
3056      // If this value didn't fit into uintmax_t, error and force to ull.
3057      Diag(Tok.getLocation(), diag::err_integer_too_large);
3058      Ty = Context.UnsignedLongLongTy;
3059      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3060             "long long is not intmax_t?");
3061    } else {
3062      // If this value fits into a ULL, try to figure out what else it fits into
3063      // according to the rules of C99 6.4.4.1p5.
3064
3065      // Octal, Hexadecimal, and integers with a U suffix are allowed to
3066      // be an unsigned int.
3067      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3068
3069      // Check from smallest to largest, picking the smallest type we can.
3070      unsigned Width = 0;
3071      if (!Literal.isLong && !Literal.isLongLong) {
3072        // Are int/unsigned possibilities?
3073        unsigned IntSize = Context.getTargetInfo().getIntWidth();
3074
3075        // Does it fit in a unsigned int?
3076        if (ResultVal.isIntN(IntSize)) {
3077          // Does it fit in a signed int?
3078          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3079            Ty = Context.IntTy;
3080          else if (AllowUnsigned)
3081            Ty = Context.UnsignedIntTy;
3082          Width = IntSize;
3083        }
3084      }
3085
3086      // Are long/unsigned long possibilities?
3087      if (Ty.isNull() && !Literal.isLongLong) {
3088        unsigned LongSize = Context.getTargetInfo().getLongWidth();
3089
3090        // Does it fit in a unsigned long?
3091        if (ResultVal.isIntN(LongSize)) {
3092          // Does it fit in a signed long?
3093          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3094            Ty = Context.LongTy;
3095          else if (AllowUnsigned)
3096            Ty = Context.UnsignedLongTy;
3097          Width = LongSize;
3098        }
3099      }
3100
3101      // Check long long if needed.
3102      if (Ty.isNull()) {
3103        unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3104
3105        // Does it fit in a unsigned long long?
3106        if (ResultVal.isIntN(LongLongSize)) {
3107          // Does it fit in a signed long long?
3108          // To be compatible with MSVC, hex integer literals ending with the
3109          // LL or i64 suffix are always signed in Microsoft mode.
3110          if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3111              (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3112            Ty = Context.LongLongTy;
3113          else if (AllowUnsigned)
3114            Ty = Context.UnsignedLongLongTy;
3115          Width = LongLongSize;
3116        }
3117      }
3118
3119      // If it doesn't fit in unsigned long long, and we're using Microsoft
3120      // extensions, then its a 128-bit integer literal.
3121      if (Ty.isNull() && Literal.isMicrosoftInteger &&
3122          PP.getTargetInfo().hasInt128Type()) {
3123        if (Literal.isUnsigned)
3124          Ty = Context.UnsignedInt128Ty;
3125        else
3126          Ty = Context.Int128Ty;
3127        Width = 128;
3128      }
3129
3130      // If we still couldn't decide a type, we probably have something that
3131      // does not fit in a signed long long, but has no U suffix.
3132      if (Ty.isNull()) {
3133        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3134        Ty = Context.UnsignedLongLongTy;
3135        Width = Context.getTargetInfo().getLongLongWidth();
3136      }
3137
3138      if (ResultVal.getBitWidth() != Width)
3139        ResultVal = ResultVal.trunc(Width);
3140    }
3141    Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3142  }
3143
3144  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3145  if (Literal.isImaginary)
3146    Res = new (Context) ImaginaryLiteral(Res,
3147                                        Context.getComplexType(Res->getType()));
3148
3149  return Owned(Res);
3150}
3151
3152ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3153  assert((E != 0) && "ActOnParenExpr() missing expr");
3154  return Owned(new (Context) ParenExpr(L, R, E));
3155}
3156
3157static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3158                                         SourceLocation Loc,
3159                                         SourceRange ArgRange) {
3160  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3161  // scalar or vector data type argument..."
3162  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3163  // type (C99 6.2.5p18) or void.
3164  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3165    S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3166      << T << ArgRange;
3167    return true;
3168  }
3169
3170  assert((T->isVoidType() || !T->isIncompleteType()) &&
3171         "Scalar types should always be complete");
3172  return false;
3173}
3174
3175static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3176                                           SourceLocation Loc,
3177                                           SourceRange ArgRange,
3178                                           UnaryExprOrTypeTrait TraitKind) {
3179  // C99 6.5.3.4p1:
3180  if (T->isFunctionType() &&
3181      (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3182    // sizeof(function)/alignof(function) is allowed as an extension.
3183    S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3184      << TraitKind << ArgRange;
3185    return false;
3186  }
3187
3188  // Allow sizeof(void)/alignof(void) as an extension.
3189  if (T->isVoidType()) {
3190    S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
3191    return false;
3192  }
3193
3194  return true;
3195}
3196
3197static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3198                                             SourceLocation Loc,
3199                                             SourceRange ArgRange,
3200                                             UnaryExprOrTypeTrait TraitKind) {
3201  // Reject sizeof(interface) and sizeof(interface<proto>) if the
3202  // runtime doesn't allow it.
3203  if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3204    S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3205      << T << (TraitKind == UETT_SizeOf)
3206      << ArgRange;
3207    return true;
3208  }
3209
3210  return false;
3211}
3212
3213/// \brief Check whether E is a pointer from a decayed array type (the decayed
3214/// pointer type is equal to T) and emit a warning if it is.
3215static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3216                                     Expr *E) {
3217  // Don't warn if the operation changed the type.
3218  if (T != E->getType())
3219    return;
3220
3221  // Now look for array decays.
3222  ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3223  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3224    return;
3225
3226  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3227                                             << ICE->getType()
3228                                             << ICE->getSubExpr()->getType();
3229}
3230
3231/// \brief Check the constrains on expression operands to unary type expression
3232/// and type traits.
3233///
3234/// Completes any types necessary and validates the constraints on the operand
3235/// expression. The logic mostly mirrors the type-based overload, but may modify
3236/// the expression as it completes the type for that expression through template
3237/// instantiation, etc.
3238bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3239                                            UnaryExprOrTypeTrait ExprKind) {
3240  QualType ExprTy = E->getType();
3241  assert(!ExprTy->isReferenceType());
3242
3243  if (ExprKind == UETT_VecStep)
3244    return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3245                                        E->getSourceRange());
3246
3247  // Whitelist some types as extensions
3248  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3249                                      E->getSourceRange(), ExprKind))
3250    return false;
3251
3252  if (RequireCompleteExprType(E,
3253                              diag::err_sizeof_alignof_incomplete_type,
3254                              ExprKind, E->getSourceRange()))
3255    return true;
3256
3257  // Completing the expression's type may have changed it.
3258  ExprTy = E->getType();
3259  assert(!ExprTy->isReferenceType());
3260
3261  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3262                                       E->getSourceRange(), ExprKind))
3263    return true;
3264
3265  if (ExprKind == UETT_SizeOf) {
3266    if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3267      if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3268        QualType OType = PVD->getOriginalType();
3269        QualType Type = PVD->getType();
3270        if (Type->isPointerType() && OType->isArrayType()) {
3271          Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3272            << Type << OType;
3273          Diag(PVD->getLocation(), diag::note_declared_at);
3274        }
3275      }
3276    }
3277
3278    // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3279    // decays into a pointer and returns an unintended result. This is most
3280    // likely a typo for "sizeof(array) op x".
3281    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3282      warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3283                               BO->getLHS());
3284      warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3285                               BO->getRHS());
3286    }
3287  }
3288
3289  return false;
3290}
3291
3292/// \brief Check the constraints on operands to unary expression and type
3293/// traits.
3294///
3295/// This will complete any types necessary, and validate the various constraints
3296/// on those operands.
3297///
3298/// The UsualUnaryConversions() function is *not* called by this routine.
3299/// C99 6.3.2.1p[2-4] all state:
3300///   Except when it is the operand of the sizeof operator ...
3301///
3302/// C++ [expr.sizeof]p4
3303///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3304///   standard conversions are not applied to the operand of sizeof.
3305///
3306/// This policy is followed for all of the unary trait expressions.
3307bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3308                                            SourceLocation OpLoc,
3309                                            SourceRange ExprRange,
3310                                            UnaryExprOrTypeTrait ExprKind) {
3311  if (ExprType->isDependentType())
3312    return false;
3313
3314  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3315  //   the result is the size of the referenced type."
3316  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3317  //   result shall be the alignment of the referenced type."
3318  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3319    ExprType = Ref->getPointeeType();
3320
3321  if (ExprKind == UETT_VecStep)
3322    return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3323
3324  // Whitelist some types as extensions
3325  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3326                                      ExprKind))
3327    return false;
3328
3329  if (RequireCompleteType(OpLoc, ExprType,
3330                          diag::err_sizeof_alignof_incomplete_type,
3331                          ExprKind, ExprRange))
3332    return true;
3333
3334  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3335                                       ExprKind))
3336    return true;
3337
3338  return false;
3339}
3340
3341static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3342  E = E->IgnoreParens();
3343
3344  // Cannot know anything else if the expression is dependent.
3345  if (E->isTypeDependent())
3346    return false;
3347
3348  if (E->getObjectKind() == OK_BitField) {
3349    S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3350       << 1 << E->getSourceRange();
3351    return true;
3352  }
3353
3354  ValueDecl *D = 0;
3355  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3356    D = DRE->getDecl();
3357  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3358    D = ME->getMemberDecl();
3359  }
3360
3361  // If it's a field, require the containing struct to have a
3362  // complete definition so that we can compute the layout.
3363  //
3364  // This requires a very particular set of circumstances.  For a
3365  // field to be contained within an incomplete type, we must in the
3366  // process of parsing that type.  To have an expression refer to a
3367  // field, it must be an id-expression or a member-expression, but
3368  // the latter are always ill-formed when the base type is
3369  // incomplete, including only being partially complete.  An
3370  // id-expression can never refer to a field in C because fields
3371  // are not in the ordinary namespace.  In C++, an id-expression
3372  // can implicitly be a member access, but only if there's an
3373  // implicit 'this' value, and all such contexts are subject to
3374  // delayed parsing --- except for trailing return types in C++11.
3375  // And if an id-expression referring to a field occurs in a
3376  // context that lacks a 'this' value, it's ill-formed --- except,
3377  // agian, in C++11, where such references are allowed in an
3378  // unevaluated context.  So C++11 introduces some new complexity.
3379  //
3380  // For the record, since __alignof__ on expressions is a GCC
3381  // extension, GCC seems to permit this but always gives the
3382  // nonsensical answer 0.
3383  //
3384  // We don't really need the layout here --- we could instead just
3385  // directly check for all the appropriate alignment-lowing
3386  // attributes --- but that would require duplicating a lot of
3387  // logic that just isn't worth duplicating for such a marginal
3388  // use-case.
3389  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3390    // Fast path this check, since we at least know the record has a
3391    // definition if we can find a member of it.
3392    if (!FD->getParent()->isCompleteDefinition()) {
3393      S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3394        << E->getSourceRange();
3395      return true;
3396    }
3397
3398    // Otherwise, if it's a field, and the field doesn't have
3399    // reference type, then it must have a complete type (or be a
3400    // flexible array member, which we explicitly want to
3401    // white-list anyway), which makes the following checks trivial.
3402    if (!FD->getType()->isReferenceType())
3403      return false;
3404  }
3405
3406  return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3407}
3408
3409bool Sema::CheckVecStepExpr(Expr *E) {
3410  E = E->IgnoreParens();
3411
3412  // Cannot know anything else if the expression is dependent.
3413  if (E->isTypeDependent())
3414    return false;
3415
3416  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3417}
3418
3419/// \brief Build a sizeof or alignof expression given a type operand.
3420ExprResult
3421Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3422                                     SourceLocation OpLoc,
3423                                     UnaryExprOrTypeTrait ExprKind,
3424                                     SourceRange R) {
3425  if (!TInfo)
3426    return ExprError();
3427
3428  QualType T = TInfo->getType();
3429
3430  if (!T->isDependentType() &&
3431      CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3432    return ExprError();
3433
3434  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3435  return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3436                                                      Context.getSizeType(),
3437                                                      OpLoc, R.getEnd()));
3438}
3439
3440/// \brief Build a sizeof or alignof expression given an expression
3441/// operand.
3442ExprResult
3443Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3444                                     UnaryExprOrTypeTrait ExprKind) {
3445  ExprResult PE = CheckPlaceholderExpr(E);
3446  if (PE.isInvalid())
3447    return ExprError();
3448
3449  E = PE.get();
3450
3451  // Verify that the operand is valid.
3452  bool isInvalid = false;
3453  if (E->isTypeDependent()) {
3454    // Delay type-checking for type-dependent expressions.
3455  } else if (ExprKind == UETT_AlignOf) {
3456    isInvalid = CheckAlignOfExpr(*this, E);
3457  } else if (ExprKind == UETT_VecStep) {
3458    isInvalid = CheckVecStepExpr(E);
3459  } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3460    Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3461    isInvalid = true;
3462  } else {
3463    isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3464  }
3465
3466  if (isInvalid)
3467    return ExprError();
3468
3469  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3470    PE = TransformToPotentiallyEvaluated(E);
3471    if (PE.isInvalid()) return ExprError();
3472    E = PE.take();
3473  }
3474
3475  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3476  return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3477      ExprKind, E, Context.getSizeType(), OpLoc,
3478      E->getSourceRange().getEnd()));
3479}
3480
3481/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3482/// expr and the same for @c alignof and @c __alignof
3483/// Note that the ArgRange is invalid if isType is false.
3484ExprResult
3485Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3486                                    UnaryExprOrTypeTrait ExprKind, bool IsType,
3487                                    void *TyOrEx, const SourceRange &ArgRange) {
3488  // If error parsing type, ignore.
3489  if (TyOrEx == 0) return ExprError();
3490
3491  if (IsType) {
3492    TypeSourceInfo *TInfo;
3493    (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3494    return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3495  }
3496
3497  Expr *ArgEx = (Expr *)TyOrEx;
3498  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3499  return Result;
3500}
3501
3502static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3503                                     bool IsReal) {
3504  if (V.get()->isTypeDependent())
3505    return S.Context.DependentTy;
3506
3507  // _Real and _Imag are only l-values for normal l-values.
3508  if (V.get()->getObjectKind() != OK_Ordinary) {
3509    V = S.DefaultLvalueConversion(V.take());
3510    if (V.isInvalid())
3511      return QualType();
3512  }
3513
3514  // These operators return the element type of a complex type.
3515  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3516    return CT->getElementType();
3517
3518  // Otherwise they pass through real integer and floating point types here.
3519  if (V.get()->getType()->isArithmeticType())
3520    return V.get()->getType();
3521
3522  // Test for placeholders.
3523  ExprResult PR = S.CheckPlaceholderExpr(V.get());
3524  if (PR.isInvalid()) return QualType();
3525  if (PR.get() != V.get()) {
3526    V = PR;
3527    return CheckRealImagOperand(S, V, Loc, IsReal);
3528  }
3529
3530  // Reject anything else.
3531  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3532    << (IsReal ? "__real" : "__imag");
3533  return QualType();
3534}
3535
3536
3537
3538ExprResult
3539Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3540                          tok::TokenKind Kind, Expr *Input) {
3541  UnaryOperatorKind Opc;
3542  switch (Kind) {
3543  default: llvm_unreachable("Unknown unary op!");
3544  case tok::plusplus:   Opc = UO_PostInc; break;
3545  case tok::minusminus: Opc = UO_PostDec; break;
3546  }
3547
3548  // Since this might is a postfix expression, get rid of ParenListExprs.
3549  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3550  if (Result.isInvalid()) return ExprError();
3551  Input = Result.take();
3552
3553  return BuildUnaryOp(S, OpLoc, Opc, Input);
3554}
3555
3556/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3557///
3558/// \return true on error
3559static bool checkArithmeticOnObjCPointer(Sema &S,
3560                                         SourceLocation opLoc,
3561                                         Expr *op) {
3562  assert(op->getType()->isObjCObjectPointerType());
3563  if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3564    return false;
3565
3566  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3567    << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3568    << op->getSourceRange();
3569  return true;
3570}
3571
3572ExprResult
3573Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3574                              Expr *idx, SourceLocation rbLoc) {
3575  // Since this might be a postfix expression, get rid of ParenListExprs.
3576  if (isa<ParenListExpr>(base)) {
3577    ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3578    if (result.isInvalid()) return ExprError();
3579    base = result.take();
3580  }
3581
3582  // Handle any non-overload placeholder types in the base and index
3583  // expressions.  We can't handle overloads here because the other
3584  // operand might be an overloadable type, in which case the overload
3585  // resolution for the operator overload should get the first crack
3586  // at the overload.
3587  if (base->getType()->isNonOverloadPlaceholderType()) {
3588    ExprResult result = CheckPlaceholderExpr(base);
3589    if (result.isInvalid()) return ExprError();
3590    base = result.take();
3591  }
3592  if (idx->getType()->isNonOverloadPlaceholderType()) {
3593    ExprResult result = CheckPlaceholderExpr(idx);
3594    if (result.isInvalid()) return ExprError();
3595    idx = result.take();
3596  }
3597
3598  // Build an unanalyzed expression if either operand is type-dependent.
3599  if (getLangOpts().CPlusPlus &&
3600      (base->isTypeDependent() || idx->isTypeDependent())) {
3601    return Owned(new (Context) ArraySubscriptExpr(base, idx,
3602                                                  Context.DependentTy,
3603                                                  VK_LValue, OK_Ordinary,
3604                                                  rbLoc));
3605  }
3606
3607  // Use C++ overloaded-operator rules if either operand has record
3608  // type.  The spec says to do this if either type is *overloadable*,
3609  // but enum types can't declare subscript operators or conversion
3610  // operators, so there's nothing interesting for overload resolution
3611  // to do if there aren't any record types involved.
3612  //
3613  // ObjC pointers have their own subscripting logic that is not tied
3614  // to overload resolution and so should not take this path.
3615  if (getLangOpts().CPlusPlus &&
3616      (base->getType()->isRecordType() ||
3617       (!base->getType()->isObjCObjectPointerType() &&
3618        idx->getType()->isRecordType()))) {
3619    return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3620  }
3621
3622  return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3623}
3624
3625ExprResult
3626Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3627                                      Expr *Idx, SourceLocation RLoc) {
3628  Expr *LHSExp = Base;
3629  Expr *RHSExp = Idx;
3630
3631  // Perform default conversions.
3632  if (!LHSExp->getType()->getAs<VectorType>()) {
3633    ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3634    if (Result.isInvalid())
3635      return ExprError();
3636    LHSExp = Result.take();
3637  }
3638  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3639  if (Result.isInvalid())
3640    return ExprError();
3641  RHSExp = Result.take();
3642
3643  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3644  ExprValueKind VK = VK_LValue;
3645  ExprObjectKind OK = OK_Ordinary;
3646
3647  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3648  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3649  // in the subscript position. As a result, we need to derive the array base
3650  // and index from the expression types.
3651  Expr *BaseExpr, *IndexExpr;
3652  QualType ResultType;
3653  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3654    BaseExpr = LHSExp;
3655    IndexExpr = RHSExp;
3656    ResultType = Context.DependentTy;
3657  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3658    BaseExpr = LHSExp;
3659    IndexExpr = RHSExp;
3660    ResultType = PTy->getPointeeType();
3661  } else if (const ObjCObjectPointerType *PTy =
3662               LHSTy->getAs<ObjCObjectPointerType>()) {
3663    BaseExpr = LHSExp;
3664    IndexExpr = RHSExp;
3665
3666    // Use custom logic if this should be the pseudo-object subscript
3667    // expression.
3668    if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3669      return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3670
3671    ResultType = PTy->getPointeeType();
3672    if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3673      Diag(LLoc, diag::err_subscript_nonfragile_interface)
3674        << ResultType << BaseExpr->getSourceRange();
3675      return ExprError();
3676    }
3677  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3678     // Handle the uncommon case of "123[Ptr]".
3679    BaseExpr = RHSExp;
3680    IndexExpr = LHSExp;
3681    ResultType = PTy->getPointeeType();
3682  } else if (const ObjCObjectPointerType *PTy =
3683               RHSTy->getAs<ObjCObjectPointerType>()) {
3684     // Handle the uncommon case of "123[Ptr]".
3685    BaseExpr = RHSExp;
3686    IndexExpr = LHSExp;
3687    ResultType = PTy->getPointeeType();
3688    if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3689      Diag(LLoc, diag::err_subscript_nonfragile_interface)
3690        << ResultType << BaseExpr->getSourceRange();
3691      return ExprError();
3692    }
3693  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3694    BaseExpr = LHSExp;    // vectors: V[123]
3695    IndexExpr = RHSExp;
3696    VK = LHSExp->getValueKind();
3697    if (VK != VK_RValue)
3698      OK = OK_VectorComponent;
3699
3700    // FIXME: need to deal with const...
3701    ResultType = VTy->getElementType();
3702  } else if (LHSTy->isArrayType()) {
3703    // If we see an array that wasn't promoted by
3704    // DefaultFunctionArrayLvalueConversion, it must be an array that
3705    // wasn't promoted because of the C90 rule that doesn't
3706    // allow promoting non-lvalue arrays.  Warn, then
3707    // force the promotion here.
3708    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3709        LHSExp->getSourceRange();
3710    LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3711                               CK_ArrayToPointerDecay).take();
3712    LHSTy = LHSExp->getType();
3713
3714    BaseExpr = LHSExp;
3715    IndexExpr = RHSExp;
3716    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3717  } else if (RHSTy->isArrayType()) {
3718    // Same as previous, except for 123[f().a] case
3719    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3720        RHSExp->getSourceRange();
3721    RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3722                               CK_ArrayToPointerDecay).take();
3723    RHSTy = RHSExp->getType();
3724
3725    BaseExpr = RHSExp;
3726    IndexExpr = LHSExp;
3727    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3728  } else {
3729    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3730       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3731  }
3732  // C99 6.5.2.1p1
3733  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3734    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3735                     << IndexExpr->getSourceRange());
3736
3737  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3738       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3739         && !IndexExpr->isTypeDependent())
3740    Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3741
3742  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3743  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3744  // type. Note that Functions are not objects, and that (in C99 parlance)
3745  // incomplete types are not object types.
3746  if (ResultType->isFunctionType()) {
3747    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3748      << ResultType << BaseExpr->getSourceRange();
3749    return ExprError();
3750  }
3751
3752  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3753    // GNU extension: subscripting on pointer to void
3754    Diag(LLoc, diag::ext_gnu_subscript_void_type)
3755      << BaseExpr->getSourceRange();
3756
3757    // C forbids expressions of unqualified void type from being l-values.
3758    // See IsCForbiddenLValueType.
3759    if (!ResultType.hasQualifiers()) VK = VK_RValue;
3760  } else if (!ResultType->isDependentType() &&
3761      RequireCompleteType(LLoc, ResultType,
3762                          diag::err_subscript_incomplete_type, BaseExpr))
3763    return ExprError();
3764
3765  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3766         !ResultType.isCForbiddenLValueType());
3767
3768  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3769                                                ResultType, VK, OK, RLoc));
3770}
3771
3772ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3773                                        FunctionDecl *FD,
3774                                        ParmVarDecl *Param) {
3775  if (Param->hasUnparsedDefaultArg()) {
3776    Diag(CallLoc,
3777         diag::err_use_of_default_argument_to_function_declared_later) <<
3778      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3779    Diag(UnparsedDefaultArgLocs[Param],
3780         diag::note_default_argument_declared_here);
3781    return ExprError();
3782  }
3783
3784  if (Param->hasUninstantiatedDefaultArg()) {
3785    Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3786
3787    EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3788                                                 Param);
3789
3790    // Instantiate the expression.
3791    MultiLevelTemplateArgumentList MutiLevelArgList
3792      = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3793
3794    InstantiatingTemplate Inst(*this, CallLoc, Param,
3795                               MutiLevelArgList.getInnermost());
3796    if (Inst)
3797      return ExprError();
3798
3799    ExprResult Result;
3800    {
3801      // C++ [dcl.fct.default]p5:
3802      //   The names in the [default argument] expression are bound, and
3803      //   the semantic constraints are checked, at the point where the
3804      //   default argument expression appears.
3805      ContextRAII SavedContext(*this, FD);
3806      LocalInstantiationScope Local(*this);
3807      Result = SubstExpr(UninstExpr, MutiLevelArgList);
3808    }
3809    if (Result.isInvalid())
3810      return ExprError();
3811
3812    // Check the expression as an initializer for the parameter.
3813    InitializedEntity Entity
3814      = InitializedEntity::InitializeParameter(Context, Param);
3815    InitializationKind Kind
3816      = InitializationKind::CreateCopy(Param->getLocation(),
3817             /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3818    Expr *ResultE = Result.takeAs<Expr>();
3819
3820    InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3821    Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3822    if (Result.isInvalid())
3823      return ExprError();
3824
3825    Expr *Arg = Result.takeAs<Expr>();
3826    CheckCompletedExpr(Arg, Param->getOuterLocStart());
3827    // Build the default argument expression.
3828    return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3829  }
3830
3831  // If the default expression creates temporaries, we need to
3832  // push them to the current stack of expression temporaries so they'll
3833  // be properly destroyed.
3834  // FIXME: We should really be rebuilding the default argument with new
3835  // bound temporaries; see the comment in PR5810.
3836  // We don't need to do that with block decls, though, because
3837  // blocks in default argument expression can never capture anything.
3838  if (isa<ExprWithCleanups>(Param->getInit())) {
3839    // Set the "needs cleanups" bit regardless of whether there are
3840    // any explicit objects.
3841    ExprNeedsCleanups = true;
3842
3843    // Append all the objects to the cleanup list.  Right now, this
3844    // should always be a no-op, because blocks in default argument
3845    // expressions should never be able to capture anything.
3846    assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3847           "default argument expression has capturing blocks?");
3848  }
3849
3850  // We already type-checked the argument, so we know it works.
3851  // Just mark all of the declarations in this potentially-evaluated expression
3852  // as being "referenced".
3853  MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3854                                   /*SkipLocalVariables=*/true);
3855  return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3856}
3857
3858
3859Sema::VariadicCallType
3860Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3861                          Expr *Fn) {
3862  if (Proto && Proto->isVariadic()) {
3863    if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3864      return VariadicConstructor;
3865    else if (Fn && Fn->getType()->isBlockPointerType())
3866      return VariadicBlock;
3867    else if (FDecl) {
3868      if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3869        if (Method->isInstance())
3870          return VariadicMethod;
3871    } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3872      return VariadicMethod;
3873    return VariadicFunction;
3874  }
3875  return VariadicDoesNotApply;
3876}
3877
3878namespace {
3879class FunctionCallCCC : public FunctionCallFilterCCC {
3880public:
3881  FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3882                  unsigned NumArgs, bool HasExplicitTemplateArgs)
3883      : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs),
3884        FunctionName(FuncName) {}
3885
3886  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
3887    if (!candidate.getCorrectionSpecifier() ||
3888        candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3889      return false;
3890    }
3891
3892    return FunctionCallFilterCCC::ValidateCandidate(candidate);
3893  }
3894
3895private:
3896  const IdentifierInfo *const FunctionName;
3897};
3898}
3899
3900static TypoCorrection TryTypoCorrectionForCall(Sema &S,
3901                                               DeclarationNameInfo FuncName,
3902                                               ArrayRef<Expr *> Args) {
3903  FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(),
3904                      Args.size(), false);
3905  if (TypoCorrection Corrected =
3906          S.CorrectTypo(FuncName, Sema::LookupOrdinaryName,
3907                        S.getScopeForContext(S.CurContext), NULL, CCC)) {
3908    if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
3909      if (Corrected.isOverloaded()) {
3910        OverloadCandidateSet OCS(FuncName.getLoc());
3911        OverloadCandidateSet::iterator Best;
3912        for (TypoCorrection::decl_iterator CD = Corrected.begin(),
3913                                           CDEnd = Corrected.end();
3914             CD != CDEnd; ++CD) {
3915          if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
3916            S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
3917                                   OCS);
3918        }
3919        switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) {
3920        case OR_Success:
3921          ND = Best->Function;
3922          Corrected.setCorrectionDecl(ND);
3923          break;
3924        default:
3925          break;
3926        }
3927      }
3928      if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
3929        return Corrected;
3930      }
3931    }
3932  }
3933  return TypoCorrection();
3934}
3935
3936/// ConvertArgumentsForCall - Converts the arguments specified in
3937/// Args/NumArgs to the parameter types of the function FDecl with
3938/// function prototype Proto. Call is the call expression itself, and
3939/// Fn is the function expression. For a C++ member function, this
3940/// routine does not attempt to convert the object argument. Returns
3941/// true if the call is ill-formed.
3942bool
3943Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3944                              FunctionDecl *FDecl,
3945                              const FunctionProtoType *Proto,
3946                              ArrayRef<Expr *> Args,
3947                              SourceLocation RParenLoc,
3948                              bool IsExecConfig) {
3949  // Bail out early if calling a builtin with custom typechecking.
3950  // We don't need to do this in the
3951  if (FDecl)
3952    if (unsigned ID = FDecl->getBuiltinID())
3953      if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3954        return false;
3955
3956  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3957  // assignment, to the types of the corresponding parameter, ...
3958  unsigned NumArgsInProto = Proto->getNumArgs();
3959  bool Invalid = false;
3960  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3961  unsigned FnKind = Fn->getType()->isBlockPointerType()
3962                       ? 1 /* block */
3963                       : (IsExecConfig ? 3 /* kernel function (exec config) */
3964                                       : 0 /* function */);
3965
3966  // If too few arguments are available (and we don't have default
3967  // arguments for the remaining parameters), don't make the call.
3968  if (Args.size() < NumArgsInProto) {
3969    if (Args.size() < MinArgs) {
3970      TypoCorrection TC;
3971      if (FDecl && (TC = TryTypoCorrectionForCall(
3972                        *this, DeclarationNameInfo(FDecl->getDeclName(),
3973                                                   Fn->getLocStart()),
3974                        Args))) {
3975        std::string CorrectedStr(TC.getAsString(getLangOpts()));
3976        std::string CorrectedQuotedStr(TC.getQuoted(getLangOpts()));
3977        unsigned diag_id =
3978            MinArgs == NumArgsInProto && !Proto->isVariadic()
3979                ? diag::err_typecheck_call_too_few_args_suggest
3980                : diag::err_typecheck_call_too_few_args_at_least_suggest;
3981        Diag(RParenLoc, diag_id)
3982            << FnKind << MinArgs << static_cast<unsigned>(Args.size())
3983            << Fn->getSourceRange() << CorrectedQuotedStr
3984            << FixItHint::CreateReplacement(TC.getCorrectionRange(),
3985                                            CorrectedStr);
3986        Diag(TC.getCorrectionDecl()->getLocStart(),
3987             diag::note_previous_decl) << CorrectedQuotedStr;
3988      } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3989        Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3990                          ? diag::err_typecheck_call_too_few_args_one
3991                          : diag::err_typecheck_call_too_few_args_at_least_one)
3992          << FnKind
3993          << FDecl->getParamDecl(0) << Fn->getSourceRange();
3994      else
3995        Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3996                          ? diag::err_typecheck_call_too_few_args
3997                          : diag::err_typecheck_call_too_few_args_at_least)
3998          << FnKind
3999          << MinArgs << static_cast<unsigned>(Args.size())
4000          << Fn->getSourceRange();
4001
4002      // Emit the location of the prototype.
4003      if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4004        Diag(FDecl->getLocStart(), diag::note_callee_decl)
4005          << FDecl;
4006
4007      return true;
4008    }
4009    Call->setNumArgs(Context, NumArgsInProto);
4010  }
4011
4012  // If too many are passed and not variadic, error on the extras and drop
4013  // them.
4014  if (Args.size() > NumArgsInProto) {
4015    if (!Proto->isVariadic()) {
4016      TypoCorrection TC;
4017      if (FDecl && (TC = TryTypoCorrectionForCall(
4018                        *this, DeclarationNameInfo(FDecl->getDeclName(),
4019                                                   Fn->getLocStart()),
4020                        Args))) {
4021        std::string CorrectedStr(TC.getAsString(getLangOpts()));
4022        std::string CorrectedQuotedStr(TC.getQuoted(getLangOpts()));
4023        unsigned diag_id =
4024            MinArgs == NumArgsInProto && !Proto->isVariadic()
4025                ? diag::err_typecheck_call_too_many_args_suggest
4026                : diag::err_typecheck_call_too_many_args_at_most_suggest;
4027        Diag(Args[NumArgsInProto]->getLocStart(), diag_id)
4028            << FnKind << NumArgsInProto << static_cast<unsigned>(Args.size())
4029            << Fn->getSourceRange() << CorrectedQuotedStr
4030            << FixItHint::CreateReplacement(TC.getCorrectionRange(),
4031                                            CorrectedStr);
4032        Diag(TC.getCorrectionDecl()->getLocStart(),
4033             diag::note_previous_decl) << CorrectedQuotedStr;
4034      } else if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4035        Diag(Args[NumArgsInProto]->getLocStart(),
4036             MinArgs == NumArgsInProto
4037               ? diag::err_typecheck_call_too_many_args_one
4038               : diag::err_typecheck_call_too_many_args_at_most_one)
4039          << FnKind
4040          << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size())
4041          << Fn->getSourceRange()
4042          << SourceRange(Args[NumArgsInProto]->getLocStart(),
4043                         Args.back()->getLocEnd());
4044      else
4045        Diag(Args[NumArgsInProto]->getLocStart(),
4046             MinArgs == NumArgsInProto
4047               ? diag::err_typecheck_call_too_many_args
4048               : diag::err_typecheck_call_too_many_args_at_most)
4049          << FnKind
4050          << NumArgsInProto << static_cast<unsigned>(Args.size())
4051          << Fn->getSourceRange()
4052          << SourceRange(Args[NumArgsInProto]->getLocStart(),
4053                         Args.back()->getLocEnd());
4054
4055      // Emit the location of the prototype.
4056      if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4057        Diag(FDecl->getLocStart(), diag::note_callee_decl)
4058          << FDecl;
4059
4060      // This deletes the extra arguments.
4061      Call->setNumArgs(Context, NumArgsInProto);
4062      return true;
4063    }
4064  }
4065  SmallVector<Expr *, 8> AllArgs;
4066  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4067
4068  Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4069                                   Proto, 0, Args, AllArgs, CallType);
4070  if (Invalid)
4071    return true;
4072  unsigned TotalNumArgs = AllArgs.size();
4073  for (unsigned i = 0; i < TotalNumArgs; ++i)
4074    Call->setArg(i, AllArgs[i]);
4075
4076  return false;
4077}
4078
4079bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4080                                  FunctionDecl *FDecl,
4081                                  const FunctionProtoType *Proto,
4082                                  unsigned FirstProtoArg,
4083                                  ArrayRef<Expr *> Args,
4084                                  SmallVectorImpl<Expr *> &AllArgs,
4085                                  VariadicCallType CallType,
4086                                  bool AllowExplicit,
4087                                  bool IsListInitialization) {
4088  unsigned NumArgsInProto = Proto->getNumArgs();
4089  unsigned NumArgsToCheck = Args.size();
4090  bool Invalid = false;
4091  if (Args.size() != NumArgsInProto)
4092    // Use default arguments for missing arguments
4093    NumArgsToCheck = NumArgsInProto;
4094  unsigned ArgIx = 0;
4095  // Continue to check argument types (even if we have too few/many args).
4096  for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4097    QualType ProtoArgType = Proto->getArgType(i);
4098
4099    Expr *Arg;
4100    ParmVarDecl *Param;
4101    if (ArgIx < Args.size()) {
4102      Arg = Args[ArgIx++];
4103
4104      if (RequireCompleteType(Arg->getLocStart(),
4105                              ProtoArgType,
4106                              diag::err_call_incomplete_argument, Arg))
4107        return true;
4108
4109      // Pass the argument
4110      Param = 0;
4111      if (FDecl && i < FDecl->getNumParams())
4112        Param = FDecl->getParamDecl(i);
4113
4114      // Strip the unbridged-cast placeholder expression off, if applicable.
4115      bool CFAudited = false;
4116      if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4117          FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4118          (!Param || !Param->hasAttr<CFConsumedAttr>()))
4119        Arg = stripARCUnbridgedCast(Arg);
4120      else if (getLangOpts().ObjCAutoRefCount &&
4121               FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4122               (!Param || !Param->hasAttr<CFConsumedAttr>()))
4123        CFAudited = true;
4124
4125      InitializedEntity Entity = Param ?
4126          InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
4127        : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4128                                                 Proto->isArgConsumed(i));
4129
4130      // Remember that parameter belongs to a CF audited API.
4131      if (CFAudited)
4132        Entity.setParameterCFAudited();
4133
4134      ExprResult ArgE = PerformCopyInitialization(Entity,
4135                                                  SourceLocation(),
4136                                                  Owned(Arg),
4137                                                  IsListInitialization,
4138                                                  AllowExplicit);
4139      if (ArgE.isInvalid())
4140        return true;
4141
4142      Arg = ArgE.takeAs<Expr>();
4143    } else {
4144      assert(FDecl && "can't use default arguments without a known callee");
4145      Param = FDecl->getParamDecl(i);
4146
4147      ExprResult ArgExpr =
4148        BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4149      if (ArgExpr.isInvalid())
4150        return true;
4151
4152      Arg = ArgExpr.takeAs<Expr>();
4153    }
4154
4155    // Check for array bounds violations for each argument to the call. This
4156    // check only triggers warnings when the argument isn't a more complex Expr
4157    // with its own checking, such as a BinaryOperator.
4158    CheckArrayAccess(Arg);
4159
4160    // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4161    CheckStaticArrayArgument(CallLoc, Param, Arg);
4162
4163    AllArgs.push_back(Arg);
4164  }
4165
4166  // If this is a variadic call, handle args passed through "...".
4167  if (CallType != VariadicDoesNotApply) {
4168    // Assume that extern "C" functions with variadic arguments that
4169    // return __unknown_anytype aren't *really* variadic.
4170    if (Proto->getResultType() == Context.UnknownAnyTy &&
4171        FDecl && FDecl->isExternC()) {
4172      for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4173        QualType paramType; // ignored
4174        ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4175        Invalid |= arg.isInvalid();
4176        AllArgs.push_back(arg.take());
4177      }
4178
4179    // Otherwise do argument promotion, (C99 6.5.2.2p7).
4180    } else {
4181      for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4182        ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4183                                                          FDecl);
4184        Invalid |= Arg.isInvalid();
4185        AllArgs.push_back(Arg.take());
4186      }
4187    }
4188
4189    // Check for array bounds violations.
4190    for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4191      CheckArrayAccess(Args[i]);
4192  }
4193  return Invalid;
4194}
4195
4196static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4197  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4198  if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4199    TL = DTL.getOriginalLoc();
4200  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4201    S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4202      << ATL.getLocalSourceRange();
4203}
4204
4205/// CheckStaticArrayArgument - If the given argument corresponds to a static
4206/// array parameter, check that it is non-null, and that if it is formed by
4207/// array-to-pointer decay, the underlying array is sufficiently large.
4208///
4209/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4210/// array type derivation, then for each call to the function, the value of the
4211/// corresponding actual argument shall provide access to the first element of
4212/// an array with at least as many elements as specified by the size expression.
4213void
4214Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4215                               ParmVarDecl *Param,
4216                               const Expr *ArgExpr) {
4217  // Static array parameters are not supported in C++.
4218  if (!Param || getLangOpts().CPlusPlus)
4219    return;
4220
4221  QualType OrigTy = Param->getOriginalType();
4222
4223  const ArrayType *AT = Context.getAsArrayType(OrigTy);
4224  if (!AT || AT->getSizeModifier() != ArrayType::Static)
4225    return;
4226
4227  if (ArgExpr->isNullPointerConstant(Context,
4228                                     Expr::NPC_NeverValueDependent)) {
4229    Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4230    DiagnoseCalleeStaticArrayParam(*this, Param);
4231    return;
4232  }
4233
4234  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4235  if (!CAT)
4236    return;
4237
4238  const ConstantArrayType *ArgCAT =
4239    Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4240  if (!ArgCAT)
4241    return;
4242
4243  if (ArgCAT->getSize().ult(CAT->getSize())) {
4244    Diag(CallLoc, diag::warn_static_array_too_small)
4245      << ArgExpr->getSourceRange()
4246      << (unsigned) ArgCAT->getSize().getZExtValue()
4247      << (unsigned) CAT->getSize().getZExtValue();
4248    DiagnoseCalleeStaticArrayParam(*this, Param);
4249  }
4250}
4251
4252/// Given a function expression of unknown-any type, try to rebuild it
4253/// to have a function type.
4254static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4255
4256/// Is the given type a placeholder that we need to lower out
4257/// immediately during argument processing?
4258static bool isPlaceholderToRemoveAsArg(QualType type) {
4259  // Placeholders are never sugared.
4260  const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4261  if (!placeholder) return false;
4262
4263  switch (placeholder->getKind()) {
4264  // Ignore all the non-placeholder types.
4265#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4266#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4267#include "clang/AST/BuiltinTypes.def"
4268    return false;
4269
4270  // We cannot lower out overload sets; they might validly be resolved
4271  // by the call machinery.
4272  case BuiltinType::Overload:
4273    return false;
4274
4275  // Unbridged casts in ARC can be handled in some call positions and
4276  // should be left in place.
4277  case BuiltinType::ARCUnbridgedCast:
4278    return false;
4279
4280  // Pseudo-objects should be converted as soon as possible.
4281  case BuiltinType::PseudoObject:
4282    return true;
4283
4284  // The debugger mode could theoretically but currently does not try
4285  // to resolve unknown-typed arguments based on known parameter types.
4286  case BuiltinType::UnknownAny:
4287    return true;
4288
4289  // These are always invalid as call arguments and should be reported.
4290  case BuiltinType::BoundMember:
4291  case BuiltinType::BuiltinFn:
4292    return true;
4293  }
4294  llvm_unreachable("bad builtin type kind");
4295}
4296
4297/// Check an argument list for placeholders that we won't try to
4298/// handle later.
4299static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4300  // Apply this processing to all the arguments at once instead of
4301  // dying at the first failure.
4302  bool hasInvalid = false;
4303  for (size_t i = 0, e = args.size(); i != e; i++) {
4304    if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4305      ExprResult result = S.CheckPlaceholderExpr(args[i]);
4306      if (result.isInvalid()) hasInvalid = true;
4307      else args[i] = result.take();
4308    }
4309  }
4310  return hasInvalid;
4311}
4312
4313/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4314/// This provides the location of the left/right parens and a list of comma
4315/// locations.
4316ExprResult
4317Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4318                    MultiExprArg ArgExprs, SourceLocation RParenLoc,
4319                    Expr *ExecConfig, bool IsExecConfig) {
4320  // Since this might be a postfix expression, get rid of ParenListExprs.
4321  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4322  if (Result.isInvalid()) return ExprError();
4323  Fn = Result.take();
4324
4325  if (checkArgsForPlaceholders(*this, ArgExprs))
4326    return ExprError();
4327
4328  if (getLangOpts().CPlusPlus) {
4329    // If this is a pseudo-destructor expression, build the call immediately.
4330    if (isa<CXXPseudoDestructorExpr>(Fn)) {
4331      if (!ArgExprs.empty()) {
4332        // Pseudo-destructor calls should not have any arguments.
4333        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4334          << FixItHint::CreateRemoval(
4335                                    SourceRange(ArgExprs[0]->getLocStart(),
4336                                                ArgExprs.back()->getLocEnd()));
4337      }
4338
4339      return Owned(new (Context) CallExpr(Context, Fn, None,
4340                                          Context.VoidTy, VK_RValue,
4341                                          RParenLoc));
4342    }
4343    if (Fn->getType() == Context.PseudoObjectTy) {
4344      ExprResult result = CheckPlaceholderExpr(Fn);
4345      if (result.isInvalid()) return ExprError();
4346      Fn = result.take();
4347    }
4348
4349    // Determine whether this is a dependent call inside a C++ template,
4350    // in which case we won't do any semantic analysis now.
4351    // FIXME: Will need to cache the results of name lookup (including ADL) in
4352    // Fn.
4353    bool Dependent = false;
4354    if (Fn->isTypeDependent())
4355      Dependent = true;
4356    else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4357      Dependent = true;
4358
4359    if (Dependent) {
4360      if (ExecConfig) {
4361        return Owned(new (Context) CUDAKernelCallExpr(
4362            Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4363            Context.DependentTy, VK_RValue, RParenLoc));
4364      } else {
4365        return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4366                                            Context.DependentTy, VK_RValue,
4367                                            RParenLoc));
4368      }
4369    }
4370
4371    // Determine whether this is a call to an object (C++ [over.call.object]).
4372    if (Fn->getType()->isRecordType())
4373      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4374                                                ArgExprs, RParenLoc));
4375
4376    if (Fn->getType() == Context.UnknownAnyTy) {
4377      ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4378      if (result.isInvalid()) return ExprError();
4379      Fn = result.take();
4380    }
4381
4382    if (Fn->getType() == Context.BoundMemberTy) {
4383      return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4384    }
4385  }
4386
4387  // Check for overloaded calls.  This can happen even in C due to extensions.
4388  if (Fn->getType() == Context.OverloadTy) {
4389    OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4390
4391    // We aren't supposed to apply this logic for if there's an '&' involved.
4392    if (!find.HasFormOfMemberPointer) {
4393      OverloadExpr *ovl = find.Expression;
4394      if (isa<UnresolvedLookupExpr>(ovl)) {
4395        UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4396        return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4397                                       RParenLoc, ExecConfig);
4398      } else {
4399        return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4400                                         RParenLoc);
4401      }
4402    }
4403  }
4404
4405  // If we're directly calling a function, get the appropriate declaration.
4406  if (Fn->getType() == Context.UnknownAnyTy) {
4407    ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4408    if (result.isInvalid()) return ExprError();
4409    Fn = result.take();
4410  }
4411
4412  Expr *NakedFn = Fn->IgnoreParens();
4413
4414  NamedDecl *NDecl = 0;
4415  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4416    if (UnOp->getOpcode() == UO_AddrOf)
4417      NakedFn = UnOp->getSubExpr()->IgnoreParens();
4418
4419  if (isa<DeclRefExpr>(NakedFn))
4420    NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4421  else if (isa<MemberExpr>(NakedFn))
4422    NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4423
4424  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4425                               ExecConfig, IsExecConfig);
4426}
4427
4428ExprResult
4429Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4430                              MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4431  FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4432  if (!ConfigDecl)
4433    return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4434                          << "cudaConfigureCall");
4435  QualType ConfigQTy = ConfigDecl->getType();
4436
4437  DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4438      ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4439  MarkFunctionReferenced(LLLLoc, ConfigDecl);
4440
4441  return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4442                       /*IsExecConfig=*/true);
4443}
4444
4445/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4446///
4447/// __builtin_astype( value, dst type )
4448///
4449ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4450                                 SourceLocation BuiltinLoc,
4451                                 SourceLocation RParenLoc) {
4452  ExprValueKind VK = VK_RValue;
4453  ExprObjectKind OK = OK_Ordinary;
4454  QualType DstTy = GetTypeFromParser(ParsedDestTy);
4455  QualType SrcTy = E->getType();
4456  if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4457    return ExprError(Diag(BuiltinLoc,
4458                          diag::err_invalid_astype_of_different_size)
4459                     << DstTy
4460                     << SrcTy
4461                     << E->getSourceRange());
4462  return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4463               RParenLoc));
4464}
4465
4466/// BuildResolvedCallExpr - Build a call to a resolved expression,
4467/// i.e. an expression not of \p OverloadTy.  The expression should
4468/// unary-convert to an expression of function-pointer or
4469/// block-pointer type.
4470///
4471/// \param NDecl the declaration being called, if available
4472ExprResult
4473Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4474                            SourceLocation LParenLoc,
4475                            ArrayRef<Expr *> Args,
4476                            SourceLocation RParenLoc,
4477                            Expr *Config, bool IsExecConfig) {
4478  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4479  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4480
4481  // Promote the function operand.
4482  // We special-case function promotion here because we only allow promoting
4483  // builtin functions to function pointers in the callee of a call.
4484  ExprResult Result;
4485  if (BuiltinID &&
4486      Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4487    Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4488                               CK_BuiltinFnToFnPtr).take();
4489  } else {
4490    Result = UsualUnaryConversions(Fn);
4491  }
4492  if (Result.isInvalid())
4493    return ExprError();
4494  Fn = Result.take();
4495
4496  // Make the call expr early, before semantic checks.  This guarantees cleanup
4497  // of arguments and function on error.
4498  CallExpr *TheCall;
4499  if (Config)
4500    TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4501                                               cast<CallExpr>(Config), Args,
4502                                               Context.BoolTy, VK_RValue,
4503                                               RParenLoc);
4504  else
4505    TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4506                                     VK_RValue, RParenLoc);
4507
4508  // Bail out early if calling a builtin with custom typechecking.
4509  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4510    return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4511
4512 retry:
4513  const FunctionType *FuncT;
4514  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4515    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4516    // have type pointer to function".
4517    FuncT = PT->getPointeeType()->getAs<FunctionType>();
4518    if (FuncT == 0)
4519      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4520                         << Fn->getType() << Fn->getSourceRange());
4521  } else if (const BlockPointerType *BPT =
4522               Fn->getType()->getAs<BlockPointerType>()) {
4523    FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4524  } else {
4525    // Handle calls to expressions of unknown-any type.
4526    if (Fn->getType() == Context.UnknownAnyTy) {
4527      ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4528      if (rewrite.isInvalid()) return ExprError();
4529      Fn = rewrite.take();
4530      TheCall->setCallee(Fn);
4531      goto retry;
4532    }
4533
4534    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4535      << Fn->getType() << Fn->getSourceRange());
4536  }
4537
4538  if (getLangOpts().CUDA) {
4539    if (Config) {
4540      // CUDA: Kernel calls must be to global functions
4541      if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4542        return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4543            << FDecl->getName() << Fn->getSourceRange());
4544
4545      // CUDA: Kernel function must have 'void' return type
4546      if (!FuncT->getResultType()->isVoidType())
4547        return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4548            << Fn->getType() << Fn->getSourceRange());
4549    } else {
4550      // CUDA: Calls to global functions must be configured
4551      if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4552        return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4553            << FDecl->getName() << Fn->getSourceRange());
4554    }
4555  }
4556
4557  // Check for a valid return type
4558  if (CheckCallReturnType(FuncT->getResultType(),
4559                          Fn->getLocStart(), TheCall,
4560                          FDecl))
4561    return ExprError();
4562
4563  // We know the result type of the call, set it.
4564  TheCall->setType(FuncT->getCallResultType(Context));
4565  TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4566
4567  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4568  if (Proto) {
4569    if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4570                                IsExecConfig))
4571      return ExprError();
4572  } else {
4573    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4574
4575    if (FDecl) {
4576      // Check if we have too few/too many template arguments, based
4577      // on our knowledge of the function definition.
4578      const FunctionDecl *Def = 0;
4579      if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4580        Proto = Def->getType()->getAs<FunctionProtoType>();
4581       if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4582          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4583          << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4584      }
4585
4586      // If the function we're calling isn't a function prototype, but we have
4587      // a function prototype from a prior declaratiom, use that prototype.
4588      if (!FDecl->hasPrototype())
4589        Proto = FDecl->getType()->getAs<FunctionProtoType>();
4590    }
4591
4592    // Promote the arguments (C99 6.5.2.2p6).
4593    for (unsigned i = 0, e = Args.size(); i != e; i++) {
4594      Expr *Arg = Args[i];
4595
4596      if (Proto && i < Proto->getNumArgs()) {
4597        InitializedEntity Entity
4598          = InitializedEntity::InitializeParameter(Context,
4599                                                   Proto->getArgType(i),
4600                                                   Proto->isArgConsumed(i));
4601        ExprResult ArgE = PerformCopyInitialization(Entity,
4602                                                    SourceLocation(),
4603                                                    Owned(Arg));
4604        if (ArgE.isInvalid())
4605          return true;
4606
4607        Arg = ArgE.takeAs<Expr>();
4608
4609      } else {
4610        ExprResult ArgE = DefaultArgumentPromotion(Arg);
4611
4612        if (ArgE.isInvalid())
4613          return true;
4614
4615        Arg = ArgE.takeAs<Expr>();
4616      }
4617
4618      if (RequireCompleteType(Arg->getLocStart(),
4619                              Arg->getType(),
4620                              diag::err_call_incomplete_argument, Arg))
4621        return ExprError();
4622
4623      TheCall->setArg(i, Arg);
4624    }
4625  }
4626
4627  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4628    if (!Method->isStatic())
4629      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4630        << Fn->getSourceRange());
4631
4632  // Check for sentinels
4633  if (NDecl)
4634    DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4635
4636  // Do special checking on direct calls to functions.
4637  if (FDecl) {
4638    if (CheckFunctionCall(FDecl, TheCall, Proto))
4639      return ExprError();
4640
4641    if (BuiltinID)
4642      return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4643  } else if (NDecl) {
4644    if (CheckPointerCall(NDecl, TheCall, Proto))
4645      return ExprError();
4646  } else {
4647    if (CheckOtherCall(TheCall, Proto))
4648      return ExprError();
4649  }
4650
4651  return MaybeBindToTemporary(TheCall);
4652}
4653
4654ExprResult
4655Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4656                           SourceLocation RParenLoc, Expr *InitExpr) {
4657  assert(Ty && "ActOnCompoundLiteral(): missing type");
4658  // FIXME: put back this assert when initializers are worked out.
4659  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4660
4661  TypeSourceInfo *TInfo;
4662  QualType literalType = GetTypeFromParser(Ty, &TInfo);
4663  if (!TInfo)
4664    TInfo = Context.getTrivialTypeSourceInfo(literalType);
4665
4666  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4667}
4668
4669ExprResult
4670Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4671                               SourceLocation RParenLoc, Expr *LiteralExpr) {
4672  QualType literalType = TInfo->getType();
4673
4674  if (literalType->isArrayType()) {
4675    if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4676          diag::err_illegal_decl_array_incomplete_type,
4677          SourceRange(LParenLoc,
4678                      LiteralExpr->getSourceRange().getEnd())))
4679      return ExprError();
4680    if (literalType->isVariableArrayType())
4681      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4682        << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4683  } else if (!literalType->isDependentType() &&
4684             RequireCompleteType(LParenLoc, literalType,
4685               diag::err_typecheck_decl_incomplete_type,
4686               SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4687    return ExprError();
4688
4689  InitializedEntity Entity
4690    = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4691  InitializationKind Kind
4692    = InitializationKind::CreateCStyleCast(LParenLoc,
4693                                           SourceRange(LParenLoc, RParenLoc),
4694                                           /*InitList=*/true);
4695  InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4696  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4697                                      &literalType);
4698  if (Result.isInvalid())
4699    return ExprError();
4700  LiteralExpr = Result.get();
4701
4702  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4703  if (!getLangOpts().CPlusPlus && isFileScope) { // 6.5.2.5p3
4704    if (CheckForConstantInitializer(LiteralExpr, literalType))
4705      return ExprError();
4706  }
4707
4708  // In C, compound literals are l-values for some reason.
4709  ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4710
4711  return MaybeBindToTemporary(
4712           new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4713                                             VK, LiteralExpr, isFileScope));
4714}
4715
4716ExprResult
4717Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4718                    SourceLocation RBraceLoc) {
4719  // Immediately handle non-overload placeholders.  Overloads can be
4720  // resolved contextually, but everything else here can't.
4721  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4722    if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4723      ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4724
4725      // Ignore failures; dropping the entire initializer list because
4726      // of one failure would be terrible for indexing/etc.
4727      if (result.isInvalid()) continue;
4728
4729      InitArgList[I] = result.take();
4730    }
4731  }
4732
4733  // Semantic analysis for initializers is done by ActOnDeclarator() and
4734  // CheckInitializer() - it requires knowledge of the object being intialized.
4735
4736  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4737                                               RBraceLoc);
4738  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4739  return Owned(E);
4740}
4741
4742/// Do an explicit extend of the given block pointer if we're in ARC.
4743static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4744  assert(E.get()->getType()->isBlockPointerType());
4745  assert(E.get()->isRValue());
4746
4747  // Only do this in an r-value context.
4748  if (!S.getLangOpts().ObjCAutoRefCount) return;
4749
4750  E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4751                               CK_ARCExtendBlockObject, E.get(),
4752                               /*base path*/ 0, VK_RValue);
4753  S.ExprNeedsCleanups = true;
4754}
4755
4756/// Prepare a conversion of the given expression to an ObjC object
4757/// pointer type.
4758CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4759  QualType type = E.get()->getType();
4760  if (type->isObjCObjectPointerType()) {
4761    return CK_BitCast;
4762  } else if (type->isBlockPointerType()) {
4763    maybeExtendBlockObject(*this, E);
4764    return CK_BlockPointerToObjCPointerCast;
4765  } else {
4766    assert(type->isPointerType());
4767    return CK_CPointerToObjCPointerCast;
4768  }
4769}
4770
4771/// Prepares for a scalar cast, performing all the necessary stages
4772/// except the final cast and returning the kind required.
4773CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4774  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4775  // Also, callers should have filtered out the invalid cases with
4776  // pointers.  Everything else should be possible.
4777
4778  QualType SrcTy = Src.get()->getType();
4779  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4780    return CK_NoOp;
4781
4782  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4783  case Type::STK_MemberPointer:
4784    llvm_unreachable("member pointer type in C");
4785
4786  case Type::STK_CPointer:
4787  case Type::STK_BlockPointer:
4788  case Type::STK_ObjCObjectPointer:
4789    switch (DestTy->getScalarTypeKind()) {
4790    case Type::STK_CPointer:
4791      return CK_BitCast;
4792    case Type::STK_BlockPointer:
4793      return (SrcKind == Type::STK_BlockPointer
4794                ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4795    case Type::STK_ObjCObjectPointer:
4796      if (SrcKind == Type::STK_ObjCObjectPointer)
4797        return CK_BitCast;
4798      if (SrcKind == Type::STK_CPointer)
4799        return CK_CPointerToObjCPointerCast;
4800      maybeExtendBlockObject(*this, Src);
4801      return CK_BlockPointerToObjCPointerCast;
4802    case Type::STK_Bool:
4803      return CK_PointerToBoolean;
4804    case Type::STK_Integral:
4805      return CK_PointerToIntegral;
4806    case Type::STK_Floating:
4807    case Type::STK_FloatingComplex:
4808    case Type::STK_IntegralComplex:
4809    case Type::STK_MemberPointer:
4810      llvm_unreachable("illegal cast from pointer");
4811    }
4812    llvm_unreachable("Should have returned before this");
4813
4814  case Type::STK_Bool: // casting from bool is like casting from an integer
4815  case Type::STK_Integral:
4816    switch (DestTy->getScalarTypeKind()) {
4817    case Type::STK_CPointer:
4818    case Type::STK_ObjCObjectPointer:
4819    case Type::STK_BlockPointer:
4820      if (Src.get()->isNullPointerConstant(Context,
4821                                           Expr::NPC_ValueDependentIsNull))
4822        return CK_NullToPointer;
4823      return CK_IntegralToPointer;
4824    case Type::STK_Bool:
4825      return CK_IntegralToBoolean;
4826    case Type::STK_Integral:
4827      return CK_IntegralCast;
4828    case Type::STK_Floating:
4829      return CK_IntegralToFloating;
4830    case Type::STK_IntegralComplex:
4831      Src = ImpCastExprToType(Src.take(),
4832                              DestTy->castAs<ComplexType>()->getElementType(),
4833                              CK_IntegralCast);
4834      return CK_IntegralRealToComplex;
4835    case Type::STK_FloatingComplex:
4836      Src = ImpCastExprToType(Src.take(),
4837                              DestTy->castAs<ComplexType>()->getElementType(),
4838                              CK_IntegralToFloating);
4839      return CK_FloatingRealToComplex;
4840    case Type::STK_MemberPointer:
4841      llvm_unreachable("member pointer type in C");
4842    }
4843    llvm_unreachable("Should have returned before this");
4844
4845  case Type::STK_Floating:
4846    switch (DestTy->getScalarTypeKind()) {
4847    case Type::STK_Floating:
4848      return CK_FloatingCast;
4849    case Type::STK_Bool:
4850      return CK_FloatingToBoolean;
4851    case Type::STK_Integral:
4852      return CK_FloatingToIntegral;
4853    case Type::STK_FloatingComplex:
4854      Src = ImpCastExprToType(Src.take(),
4855                              DestTy->castAs<ComplexType>()->getElementType(),
4856                              CK_FloatingCast);
4857      return CK_FloatingRealToComplex;
4858    case Type::STK_IntegralComplex:
4859      Src = ImpCastExprToType(Src.take(),
4860                              DestTy->castAs<ComplexType>()->getElementType(),
4861                              CK_FloatingToIntegral);
4862      return CK_IntegralRealToComplex;
4863    case Type::STK_CPointer:
4864    case Type::STK_ObjCObjectPointer:
4865    case Type::STK_BlockPointer:
4866      llvm_unreachable("valid float->pointer cast?");
4867    case Type::STK_MemberPointer:
4868      llvm_unreachable("member pointer type in C");
4869    }
4870    llvm_unreachable("Should have returned before this");
4871
4872  case Type::STK_FloatingComplex:
4873    switch (DestTy->getScalarTypeKind()) {
4874    case Type::STK_FloatingComplex:
4875      return CK_FloatingComplexCast;
4876    case Type::STK_IntegralComplex:
4877      return CK_FloatingComplexToIntegralComplex;
4878    case Type::STK_Floating: {
4879      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4880      if (Context.hasSameType(ET, DestTy))
4881        return CK_FloatingComplexToReal;
4882      Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4883      return CK_FloatingCast;
4884    }
4885    case Type::STK_Bool:
4886      return CK_FloatingComplexToBoolean;
4887    case Type::STK_Integral:
4888      Src = ImpCastExprToType(Src.take(),
4889                              SrcTy->castAs<ComplexType>()->getElementType(),
4890                              CK_FloatingComplexToReal);
4891      return CK_FloatingToIntegral;
4892    case Type::STK_CPointer:
4893    case Type::STK_ObjCObjectPointer:
4894    case Type::STK_BlockPointer:
4895      llvm_unreachable("valid complex float->pointer cast?");
4896    case Type::STK_MemberPointer:
4897      llvm_unreachable("member pointer type in C");
4898    }
4899    llvm_unreachable("Should have returned before this");
4900
4901  case Type::STK_IntegralComplex:
4902    switch (DestTy->getScalarTypeKind()) {
4903    case Type::STK_FloatingComplex:
4904      return CK_IntegralComplexToFloatingComplex;
4905    case Type::STK_IntegralComplex:
4906      return CK_IntegralComplexCast;
4907    case Type::STK_Integral: {
4908      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4909      if (Context.hasSameType(ET, DestTy))
4910        return CK_IntegralComplexToReal;
4911      Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4912      return CK_IntegralCast;
4913    }
4914    case Type::STK_Bool:
4915      return CK_IntegralComplexToBoolean;
4916    case Type::STK_Floating:
4917      Src = ImpCastExprToType(Src.take(),
4918                              SrcTy->castAs<ComplexType>()->getElementType(),
4919                              CK_IntegralComplexToReal);
4920      return CK_IntegralToFloating;
4921    case Type::STK_CPointer:
4922    case Type::STK_ObjCObjectPointer:
4923    case Type::STK_BlockPointer:
4924      llvm_unreachable("valid complex int->pointer cast?");
4925    case Type::STK_MemberPointer:
4926      llvm_unreachable("member pointer type in C");
4927    }
4928    llvm_unreachable("Should have returned before this");
4929  }
4930
4931  llvm_unreachable("Unhandled scalar cast");
4932}
4933
4934bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4935                           CastKind &Kind) {
4936  assert(VectorTy->isVectorType() && "Not a vector type!");
4937
4938  if (Ty->isVectorType() || Ty->isIntegerType()) {
4939    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4940      return Diag(R.getBegin(),
4941                  Ty->isVectorType() ?
4942                  diag::err_invalid_conversion_between_vectors :
4943                  diag::err_invalid_conversion_between_vector_and_integer)
4944        << VectorTy << Ty << R;
4945  } else
4946    return Diag(R.getBegin(),
4947                diag::err_invalid_conversion_between_vector_and_scalar)
4948      << VectorTy << Ty << R;
4949
4950  Kind = CK_BitCast;
4951  return false;
4952}
4953
4954ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4955                                    Expr *CastExpr, CastKind &Kind) {
4956  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4957
4958  QualType SrcTy = CastExpr->getType();
4959
4960  // If SrcTy is a VectorType, the total size must match to explicitly cast to
4961  // an ExtVectorType.
4962  // In OpenCL, casts between vectors of different types are not allowed.
4963  // (See OpenCL 6.2).
4964  if (SrcTy->isVectorType()) {
4965    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4966        || (getLangOpts().OpenCL &&
4967            (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4968      Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4969        << DestTy << SrcTy << R;
4970      return ExprError();
4971    }
4972    Kind = CK_BitCast;
4973    return Owned(CastExpr);
4974  }
4975
4976  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4977  // conversion will take place first from scalar to elt type, and then
4978  // splat from elt type to vector.
4979  if (SrcTy->isPointerType())
4980    return Diag(R.getBegin(),
4981                diag::err_invalid_conversion_between_vector_and_scalar)
4982      << DestTy << SrcTy << R;
4983
4984  QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4985  ExprResult CastExprRes = Owned(CastExpr);
4986  CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4987  if (CastExprRes.isInvalid())
4988    return ExprError();
4989  CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4990
4991  Kind = CK_VectorSplat;
4992  return Owned(CastExpr);
4993}
4994
4995ExprResult
4996Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4997                    Declarator &D, ParsedType &Ty,
4998                    SourceLocation RParenLoc, Expr *CastExpr) {
4999  assert(!D.isInvalidType() && (CastExpr != 0) &&
5000         "ActOnCastExpr(): missing type or expr");
5001
5002  TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5003  if (D.isInvalidType())
5004    return ExprError();
5005
5006  if (getLangOpts().CPlusPlus) {
5007    // Check that there are no default arguments (C++ only).
5008    CheckExtraCXXDefaultArguments(D);
5009  }
5010
5011  checkUnusedDeclAttributes(D);
5012
5013  QualType castType = castTInfo->getType();
5014  Ty = CreateParsedType(castType, castTInfo);
5015
5016  bool isVectorLiteral = false;
5017
5018  // Check for an altivec or OpenCL literal,
5019  // i.e. all the elements are integer constants.
5020  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5021  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5022  if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5023       && castType->isVectorType() && (PE || PLE)) {
5024    if (PLE && PLE->getNumExprs() == 0) {
5025      Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5026      return ExprError();
5027    }
5028    if (PE || PLE->getNumExprs() == 1) {
5029      Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5030      if (!E->getType()->isVectorType())
5031        isVectorLiteral = true;
5032    }
5033    else
5034      isVectorLiteral = true;
5035  }
5036
5037  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5038  // then handle it as such.
5039  if (isVectorLiteral)
5040    return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5041
5042  // If the Expr being casted is a ParenListExpr, handle it specially.
5043  // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5044  // sequence of BinOp comma operators.
5045  if (isa<ParenListExpr>(CastExpr)) {
5046    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5047    if (Result.isInvalid()) return ExprError();
5048    CastExpr = Result.take();
5049  }
5050
5051  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5052}
5053
5054ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5055                                    SourceLocation RParenLoc, Expr *E,
5056                                    TypeSourceInfo *TInfo) {
5057  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5058         "Expected paren or paren list expression");
5059
5060  Expr **exprs;
5061  unsigned numExprs;
5062  Expr *subExpr;
5063  SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5064  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5065    LiteralLParenLoc = PE->getLParenLoc();
5066    LiteralRParenLoc = PE->getRParenLoc();
5067    exprs = PE->getExprs();
5068    numExprs = PE->getNumExprs();
5069  } else { // isa<ParenExpr> by assertion at function entrance
5070    LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5071    LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5072    subExpr = cast<ParenExpr>(E)->getSubExpr();
5073    exprs = &subExpr;
5074    numExprs = 1;
5075  }
5076
5077  QualType Ty = TInfo->getType();
5078  assert(Ty->isVectorType() && "Expected vector type");
5079
5080  SmallVector<Expr *, 8> initExprs;
5081  const VectorType *VTy = Ty->getAs<VectorType>();
5082  unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5083
5084  // '(...)' form of vector initialization in AltiVec: the number of
5085  // initializers must be one or must match the size of the vector.
5086  // If a single value is specified in the initializer then it will be
5087  // replicated to all the components of the vector
5088  if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5089    // The number of initializers must be one or must match the size of the
5090    // vector. If a single value is specified in the initializer then it will
5091    // be replicated to all the components of the vector
5092    if (numExprs == 1) {
5093      QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5094      ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5095      if (Literal.isInvalid())
5096        return ExprError();
5097      Literal = ImpCastExprToType(Literal.take(), ElemTy,
5098                                  PrepareScalarCast(Literal, ElemTy));
5099      return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5100    }
5101    else if (numExprs < numElems) {
5102      Diag(E->getExprLoc(),
5103           diag::err_incorrect_number_of_vector_initializers);
5104      return ExprError();
5105    }
5106    else
5107      initExprs.append(exprs, exprs + numExprs);
5108  }
5109  else {
5110    // For OpenCL, when the number of initializers is a single value,
5111    // it will be replicated to all components of the vector.
5112    if (getLangOpts().OpenCL &&
5113        VTy->getVectorKind() == VectorType::GenericVector &&
5114        numExprs == 1) {
5115        QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5116        ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5117        if (Literal.isInvalid())
5118          return ExprError();
5119        Literal = ImpCastExprToType(Literal.take(), ElemTy,
5120                                    PrepareScalarCast(Literal, ElemTy));
5121        return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5122    }
5123
5124    initExprs.append(exprs, exprs + numExprs);
5125  }
5126  // FIXME: This means that pretty-printing the final AST will produce curly
5127  // braces instead of the original commas.
5128  InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5129                                                   initExprs, LiteralRParenLoc);
5130  initE->setType(Ty);
5131  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5132}
5133
5134/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5135/// the ParenListExpr into a sequence of comma binary operators.
5136ExprResult
5137Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5138  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5139  if (!E)
5140    return Owned(OrigExpr);
5141
5142  ExprResult Result(E->getExpr(0));
5143
5144  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5145    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5146                        E->getExpr(i));
5147
5148  if (Result.isInvalid()) return ExprError();
5149
5150  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5151}
5152
5153ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5154                                    SourceLocation R,
5155                                    MultiExprArg Val) {
5156  Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5157  return Owned(expr);
5158}
5159
5160/// \brief Emit a specialized diagnostic when one expression is a null pointer
5161/// constant and the other is not a pointer.  Returns true if a diagnostic is
5162/// emitted.
5163bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5164                                      SourceLocation QuestionLoc) {
5165  Expr *NullExpr = LHSExpr;
5166  Expr *NonPointerExpr = RHSExpr;
5167  Expr::NullPointerConstantKind NullKind =
5168      NullExpr->isNullPointerConstant(Context,
5169                                      Expr::NPC_ValueDependentIsNotNull);
5170
5171  if (NullKind == Expr::NPCK_NotNull) {
5172    NullExpr = RHSExpr;
5173    NonPointerExpr = LHSExpr;
5174    NullKind =
5175        NullExpr->isNullPointerConstant(Context,
5176                                        Expr::NPC_ValueDependentIsNotNull);
5177  }
5178
5179  if (NullKind == Expr::NPCK_NotNull)
5180    return false;
5181
5182  if (NullKind == Expr::NPCK_ZeroExpression)
5183    return false;
5184
5185  if (NullKind == Expr::NPCK_ZeroLiteral) {
5186    // In this case, check to make sure that we got here from a "NULL"
5187    // string in the source code.
5188    NullExpr = NullExpr->IgnoreParenImpCasts();
5189    SourceLocation loc = NullExpr->getExprLoc();
5190    if (!findMacroSpelling(loc, "NULL"))
5191      return false;
5192  }
5193
5194  int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5195  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5196      << NonPointerExpr->getType() << DiagType
5197      << NonPointerExpr->getSourceRange();
5198  return true;
5199}
5200
5201/// \brief Return false if the condition expression is valid, true otherwise.
5202static bool checkCondition(Sema &S, Expr *Cond) {
5203  QualType CondTy = Cond->getType();
5204
5205  // C99 6.5.15p2
5206  if (CondTy->isScalarType()) return false;
5207
5208  // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5209  if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5210    return false;
5211
5212  // Emit the proper error message.
5213  S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5214                              diag::err_typecheck_cond_expect_scalar :
5215                              diag::err_typecheck_cond_expect_scalar_or_vector)
5216    << CondTy;
5217  return true;
5218}
5219
5220/// \brief Return false if the two expressions can be converted to a vector,
5221/// true otherwise
5222static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5223                                                    ExprResult &RHS,
5224                                                    QualType CondTy) {
5225  // Both operands should be of scalar type.
5226  if (!LHS.get()->getType()->isScalarType()) {
5227    S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5228      << CondTy;
5229    return true;
5230  }
5231  if (!RHS.get()->getType()->isScalarType()) {
5232    S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5233      << CondTy;
5234    return true;
5235  }
5236
5237  // Implicity convert these scalars to the type of the condition.
5238  LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5239  RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5240  return false;
5241}
5242
5243/// \brief Handle when one or both operands are void type.
5244static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5245                                         ExprResult &RHS) {
5246    Expr *LHSExpr = LHS.get();
5247    Expr *RHSExpr = RHS.get();
5248
5249    if (!LHSExpr->getType()->isVoidType())
5250      S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5251        << RHSExpr->getSourceRange();
5252    if (!RHSExpr->getType()->isVoidType())
5253      S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5254        << LHSExpr->getSourceRange();
5255    LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5256    RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5257    return S.Context.VoidTy;
5258}
5259
5260/// \brief Return false if the NullExpr can be promoted to PointerTy,
5261/// true otherwise.
5262static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5263                                        QualType PointerTy) {
5264  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5265      !NullExpr.get()->isNullPointerConstant(S.Context,
5266                                            Expr::NPC_ValueDependentIsNull))
5267    return true;
5268
5269  NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5270  return false;
5271}
5272
5273/// \brief Checks compatibility between two pointers and return the resulting
5274/// type.
5275static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5276                                                     ExprResult &RHS,
5277                                                     SourceLocation Loc) {
5278  QualType LHSTy = LHS.get()->getType();
5279  QualType RHSTy = RHS.get()->getType();
5280
5281  if (S.Context.hasSameType(LHSTy, RHSTy)) {
5282    // Two identical pointers types are always compatible.
5283    return LHSTy;
5284  }
5285
5286  QualType lhptee, rhptee;
5287
5288  // Get the pointee types.
5289  bool IsBlockPointer = false;
5290  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5291    lhptee = LHSBTy->getPointeeType();
5292    rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5293    IsBlockPointer = true;
5294  } else {
5295    lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5296    rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5297  }
5298
5299  // C99 6.5.15p6: If both operands are pointers to compatible types or to
5300  // differently qualified versions of compatible types, the result type is
5301  // a pointer to an appropriately qualified version of the composite
5302  // type.
5303
5304  // Only CVR-qualifiers exist in the standard, and the differently-qualified
5305  // clause doesn't make sense for our extensions. E.g. address space 2 should
5306  // be incompatible with address space 3: they may live on different devices or
5307  // anything.
5308  Qualifiers lhQual = lhptee.getQualifiers();
5309  Qualifiers rhQual = rhptee.getQualifiers();
5310
5311  unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5312  lhQual.removeCVRQualifiers();
5313  rhQual.removeCVRQualifiers();
5314
5315  lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5316  rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5317
5318  QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5319
5320  if (CompositeTy.isNull()) {
5321    S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5322      << LHSTy << RHSTy << LHS.get()->getSourceRange()
5323      << RHS.get()->getSourceRange();
5324    // In this situation, we assume void* type. No especially good
5325    // reason, but this is what gcc does, and we do have to pick
5326    // to get a consistent AST.
5327    QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5328    LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5329    RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5330    return incompatTy;
5331  }
5332
5333  // The pointer types are compatible.
5334  QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5335  if (IsBlockPointer)
5336    ResultTy = S.Context.getBlockPointerType(ResultTy);
5337  else
5338    ResultTy = S.Context.getPointerType(ResultTy);
5339
5340  LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5341  RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5342  return ResultTy;
5343}
5344
5345/// \brief Return the resulting type when the operands are both block pointers.
5346static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5347                                                          ExprResult &LHS,
5348                                                          ExprResult &RHS,
5349                                                          SourceLocation Loc) {
5350  QualType LHSTy = LHS.get()->getType();
5351  QualType RHSTy = RHS.get()->getType();
5352
5353  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5354    if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5355      QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5356      LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5357      RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5358      return destType;
5359    }
5360    S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5361      << LHSTy << RHSTy << LHS.get()->getSourceRange()
5362      << RHS.get()->getSourceRange();
5363    return QualType();
5364  }
5365
5366  // We have 2 block pointer types.
5367  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5368}
5369
5370/// \brief Return the resulting type when the operands are both pointers.
5371static QualType
5372checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5373                                            ExprResult &RHS,
5374                                            SourceLocation Loc) {
5375  // get the pointer types
5376  QualType LHSTy = LHS.get()->getType();
5377  QualType RHSTy = RHS.get()->getType();
5378
5379  // get the "pointed to" types
5380  QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5381  QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5382
5383  // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5384  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5385    // Figure out necessary qualifiers (C99 6.5.15p6)
5386    QualType destPointee
5387      = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5388    QualType destType = S.Context.getPointerType(destPointee);
5389    // Add qualifiers if necessary.
5390    LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5391    // Promote to void*.
5392    RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5393    return destType;
5394  }
5395  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5396    QualType destPointee
5397      = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5398    QualType destType = S.Context.getPointerType(destPointee);
5399    // Add qualifiers if necessary.
5400    RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5401    // Promote to void*.
5402    LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5403    return destType;
5404  }
5405
5406  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5407}
5408
5409/// \brief Return false if the first expression is not an integer and the second
5410/// expression is not a pointer, true otherwise.
5411static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5412                                        Expr* PointerExpr, SourceLocation Loc,
5413                                        bool IsIntFirstExpr) {
5414  if (!PointerExpr->getType()->isPointerType() ||
5415      !Int.get()->getType()->isIntegerType())
5416    return false;
5417
5418  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5419  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5420
5421  S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5422    << Expr1->getType() << Expr2->getType()
5423    << Expr1->getSourceRange() << Expr2->getSourceRange();
5424  Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5425                            CK_IntegralToPointer);
5426  return true;
5427}
5428
5429/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5430/// In that case, LHS = cond.
5431/// C99 6.5.15
5432QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5433                                        ExprResult &RHS, ExprValueKind &VK,
5434                                        ExprObjectKind &OK,
5435                                        SourceLocation QuestionLoc) {
5436
5437  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5438  if (!LHSResult.isUsable()) return QualType();
5439  LHS = LHSResult;
5440
5441  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5442  if (!RHSResult.isUsable()) return QualType();
5443  RHS = RHSResult;
5444
5445  // C++ is sufficiently different to merit its own checker.
5446  if (getLangOpts().CPlusPlus)
5447    return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5448
5449  VK = VK_RValue;
5450  OK = OK_Ordinary;
5451
5452  Cond = UsualUnaryConversions(Cond.take());
5453  if (Cond.isInvalid())
5454    return QualType();
5455  UsualArithmeticConversions(LHS, RHS);
5456  if (LHS.isInvalid() || RHS.isInvalid())
5457    return QualType();
5458
5459  QualType CondTy = Cond.get()->getType();
5460  QualType LHSTy = LHS.get()->getType();
5461  QualType RHSTy = RHS.get()->getType();
5462
5463  // first, check the condition.
5464  if (checkCondition(*this, Cond.get()))
5465    return QualType();
5466
5467  // Now check the two expressions.
5468  if (LHSTy->isVectorType() || RHSTy->isVectorType())
5469    return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5470
5471  // If the condition is a vector, and both operands are scalar,
5472  // attempt to implicity convert them to the vector type to act like the
5473  // built in select. (OpenCL v1.1 s6.3.i)
5474  if (getLangOpts().OpenCL && CondTy->isVectorType())
5475    if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5476      return QualType();
5477
5478  // If both operands have arithmetic type, do the usual arithmetic conversions
5479  // to find a common type: C99 6.5.15p3,5.
5480  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5481    return LHS.get()->getType();
5482
5483  // If both operands are the same structure or union type, the result is that
5484  // type.
5485  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5486    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5487      if (LHSRT->getDecl() == RHSRT->getDecl())
5488        // "If both the operands have structure or union type, the result has
5489        // that type."  This implies that CV qualifiers are dropped.
5490        return LHSTy.getUnqualifiedType();
5491    // FIXME: Type of conditional expression must be complete in C mode.
5492  }
5493
5494  // C99 6.5.15p5: "If both operands have void type, the result has void type."
5495  // The following || allows only one side to be void (a GCC-ism).
5496  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5497    return checkConditionalVoidType(*this, LHS, RHS);
5498  }
5499
5500  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5501  // the type of the other operand."
5502  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5503  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5504
5505  // All objective-c pointer type analysis is done here.
5506  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5507                                                        QuestionLoc);
5508  if (LHS.isInvalid() || RHS.isInvalid())
5509    return QualType();
5510  if (!compositeType.isNull())
5511    return compositeType;
5512
5513
5514  // Handle block pointer types.
5515  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5516    return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5517                                                     QuestionLoc);
5518
5519  // Check constraints for C object pointers types (C99 6.5.15p3,6).
5520  if (LHSTy->isPointerType() && RHSTy->isPointerType())
5521    return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5522                                                       QuestionLoc);
5523
5524  // GCC compatibility: soften pointer/integer mismatch.  Note that
5525  // null pointers have been filtered out by this point.
5526  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5527      /*isIntFirstExpr=*/true))
5528    return RHSTy;
5529  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5530      /*isIntFirstExpr=*/false))
5531    return LHSTy;
5532
5533  // Emit a better diagnostic if one of the expressions is a null pointer
5534  // constant and the other is not a pointer type. In this case, the user most
5535  // likely forgot to take the address of the other expression.
5536  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5537    return QualType();
5538
5539  // Otherwise, the operands are not compatible.
5540  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5541    << LHSTy << RHSTy << LHS.get()->getSourceRange()
5542    << RHS.get()->getSourceRange();
5543  return QualType();
5544}
5545
5546/// FindCompositeObjCPointerType - Helper method to find composite type of
5547/// two objective-c pointer types of the two input expressions.
5548QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5549                                            SourceLocation QuestionLoc) {
5550  QualType LHSTy = LHS.get()->getType();
5551  QualType RHSTy = RHS.get()->getType();
5552
5553  // Handle things like Class and struct objc_class*.  Here we case the result
5554  // to the pseudo-builtin, because that will be implicitly cast back to the
5555  // redefinition type if an attempt is made to access its fields.
5556  if (LHSTy->isObjCClassType() &&
5557      (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5558    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5559    return LHSTy;
5560  }
5561  if (RHSTy->isObjCClassType() &&
5562      (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5563    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5564    return RHSTy;
5565  }
5566  // And the same for struct objc_object* / id
5567  if (LHSTy->isObjCIdType() &&
5568      (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5569    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5570    return LHSTy;
5571  }
5572  if (RHSTy->isObjCIdType() &&
5573      (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5574    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5575    return RHSTy;
5576  }
5577  // And the same for struct objc_selector* / SEL
5578  if (Context.isObjCSelType(LHSTy) &&
5579      (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5580    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5581    return LHSTy;
5582  }
5583  if (Context.isObjCSelType(RHSTy) &&
5584      (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5585    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5586    return RHSTy;
5587  }
5588  // Check constraints for Objective-C object pointers types.
5589  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5590
5591    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5592      // Two identical object pointer types are always compatible.
5593      return LHSTy;
5594    }
5595    const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5596    const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5597    QualType compositeType = LHSTy;
5598
5599    // If both operands are interfaces and either operand can be
5600    // assigned to the other, use that type as the composite
5601    // type. This allows
5602    //   xxx ? (A*) a : (B*) b
5603    // where B is a subclass of A.
5604    //
5605    // Additionally, as for assignment, if either type is 'id'
5606    // allow silent coercion. Finally, if the types are
5607    // incompatible then make sure to use 'id' as the composite
5608    // type so the result is acceptable for sending messages to.
5609
5610    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5611    // It could return the composite type.
5612    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5613      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5614    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5615      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5616    } else if ((LHSTy->isObjCQualifiedIdType() ||
5617                RHSTy->isObjCQualifiedIdType()) &&
5618               Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5619      // Need to handle "id<xx>" explicitly.
5620      // GCC allows qualified id and any Objective-C type to devolve to
5621      // id. Currently localizing to here until clear this should be
5622      // part of ObjCQualifiedIdTypesAreCompatible.
5623      compositeType = Context.getObjCIdType();
5624    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5625      compositeType = Context.getObjCIdType();
5626    } else if (!(compositeType =
5627                 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5628      ;
5629    else {
5630      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5631      << LHSTy << RHSTy
5632      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5633      QualType incompatTy = Context.getObjCIdType();
5634      LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5635      RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5636      return incompatTy;
5637    }
5638    // The object pointer types are compatible.
5639    LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5640    RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5641    return compositeType;
5642  }
5643  // Check Objective-C object pointer types and 'void *'
5644  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5645    if (getLangOpts().ObjCAutoRefCount) {
5646      // ARC forbids the implicit conversion of object pointers to 'void *',
5647      // so these types are not compatible.
5648      Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5649          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5650      LHS = RHS = true;
5651      return QualType();
5652    }
5653    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5654    QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5655    QualType destPointee
5656    = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5657    QualType destType = Context.getPointerType(destPointee);
5658    // Add qualifiers if necessary.
5659    LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5660    // Promote to void*.
5661    RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5662    return destType;
5663  }
5664  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5665    if (getLangOpts().ObjCAutoRefCount) {
5666      // ARC forbids the implicit conversion of object pointers to 'void *',
5667      // so these types are not compatible.
5668      Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5669          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5670      LHS = RHS = true;
5671      return QualType();
5672    }
5673    QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5674    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5675    QualType destPointee
5676    = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5677    QualType destType = Context.getPointerType(destPointee);
5678    // Add qualifiers if necessary.
5679    RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5680    // Promote to void*.
5681    LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5682    return destType;
5683  }
5684  return QualType();
5685}
5686
5687/// SuggestParentheses - Emit a note with a fixit hint that wraps
5688/// ParenRange in parentheses.
5689static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5690                               const PartialDiagnostic &Note,
5691                               SourceRange ParenRange) {
5692  SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5693  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5694      EndLoc.isValid()) {
5695    Self.Diag(Loc, Note)
5696      << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5697      << FixItHint::CreateInsertion(EndLoc, ")");
5698  } else {
5699    // We can't display the parentheses, so just show the bare note.
5700    Self.Diag(Loc, Note) << ParenRange;
5701  }
5702}
5703
5704static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5705  return Opc >= BO_Mul && Opc <= BO_Shr;
5706}
5707
5708/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5709/// expression, either using a built-in or overloaded operator,
5710/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5711/// expression.
5712static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5713                                   Expr **RHSExprs) {
5714  // Don't strip parenthesis: we should not warn if E is in parenthesis.
5715  E = E->IgnoreImpCasts();
5716  E = E->IgnoreConversionOperator();
5717  E = E->IgnoreImpCasts();
5718
5719  // Built-in binary operator.
5720  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5721    if (IsArithmeticOp(OP->getOpcode())) {
5722      *Opcode = OP->getOpcode();
5723      *RHSExprs = OP->getRHS();
5724      return true;
5725    }
5726  }
5727
5728  // Overloaded operator.
5729  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5730    if (Call->getNumArgs() != 2)
5731      return false;
5732
5733    // Make sure this is really a binary operator that is safe to pass into
5734    // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5735    OverloadedOperatorKind OO = Call->getOperator();
5736    if (OO < OO_Plus || OO > OO_Arrow ||
5737        OO == OO_PlusPlus || OO == OO_MinusMinus)
5738      return false;
5739
5740    BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5741    if (IsArithmeticOp(OpKind)) {
5742      *Opcode = OpKind;
5743      *RHSExprs = Call->getArg(1);
5744      return true;
5745    }
5746  }
5747
5748  return false;
5749}
5750
5751static bool IsLogicOp(BinaryOperatorKind Opc) {
5752  return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5753}
5754
5755/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5756/// or is a logical expression such as (x==y) which has int type, but is
5757/// commonly interpreted as boolean.
5758static bool ExprLooksBoolean(Expr *E) {
5759  E = E->IgnoreParenImpCasts();
5760
5761  if (E->getType()->isBooleanType())
5762    return true;
5763  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5764    return IsLogicOp(OP->getOpcode());
5765  if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5766    return OP->getOpcode() == UO_LNot;
5767
5768  return false;
5769}
5770
5771/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5772/// and binary operator are mixed in a way that suggests the programmer assumed
5773/// the conditional operator has higher precedence, for example:
5774/// "int x = a + someBinaryCondition ? 1 : 2".
5775static void DiagnoseConditionalPrecedence(Sema &Self,
5776                                          SourceLocation OpLoc,
5777                                          Expr *Condition,
5778                                          Expr *LHSExpr,
5779                                          Expr *RHSExpr) {
5780  BinaryOperatorKind CondOpcode;
5781  Expr *CondRHS;
5782
5783  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5784    return;
5785  if (!ExprLooksBoolean(CondRHS))
5786    return;
5787
5788  // The condition is an arithmetic binary expression, with a right-
5789  // hand side that looks boolean, so warn.
5790
5791  Self.Diag(OpLoc, diag::warn_precedence_conditional)
5792      << Condition->getSourceRange()
5793      << BinaryOperator::getOpcodeStr(CondOpcode);
5794
5795  SuggestParentheses(Self, OpLoc,
5796    Self.PDiag(diag::note_precedence_silence)
5797      << BinaryOperator::getOpcodeStr(CondOpcode),
5798    SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5799
5800  SuggestParentheses(Self, OpLoc,
5801    Self.PDiag(diag::note_precedence_conditional_first),
5802    SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5803}
5804
5805/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5806/// in the case of a the GNU conditional expr extension.
5807ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5808                                    SourceLocation ColonLoc,
5809                                    Expr *CondExpr, Expr *LHSExpr,
5810                                    Expr *RHSExpr) {
5811  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5812  // was the condition.
5813  OpaqueValueExpr *opaqueValue = 0;
5814  Expr *commonExpr = 0;
5815  if (LHSExpr == 0) {
5816    commonExpr = CondExpr;
5817    // Lower out placeholder types first.  This is important so that we don't
5818    // try to capture a placeholder. This happens in few cases in C++; such
5819    // as Objective-C++'s dictionary subscripting syntax.
5820    if (commonExpr->hasPlaceholderType()) {
5821      ExprResult result = CheckPlaceholderExpr(commonExpr);
5822      if (!result.isUsable()) return ExprError();
5823      commonExpr = result.take();
5824    }
5825    // We usually want to apply unary conversions *before* saving, except
5826    // in the special case of a C++ l-value conditional.
5827    if (!(getLangOpts().CPlusPlus
5828          && !commonExpr->isTypeDependent()
5829          && commonExpr->getValueKind() == RHSExpr->getValueKind()
5830          && commonExpr->isGLValue()
5831          && commonExpr->isOrdinaryOrBitFieldObject()
5832          && RHSExpr->isOrdinaryOrBitFieldObject()
5833          && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5834      ExprResult commonRes = UsualUnaryConversions(commonExpr);
5835      if (commonRes.isInvalid())
5836        return ExprError();
5837      commonExpr = commonRes.take();
5838    }
5839
5840    opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5841                                                commonExpr->getType(),
5842                                                commonExpr->getValueKind(),
5843                                                commonExpr->getObjectKind(),
5844                                                commonExpr);
5845    LHSExpr = CondExpr = opaqueValue;
5846  }
5847
5848  ExprValueKind VK = VK_RValue;
5849  ExprObjectKind OK = OK_Ordinary;
5850  ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5851  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5852                                             VK, OK, QuestionLoc);
5853  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5854      RHS.isInvalid())
5855    return ExprError();
5856
5857  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5858                                RHS.get());
5859
5860  if (!commonExpr)
5861    return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5862                                                   LHS.take(), ColonLoc,
5863                                                   RHS.take(), result, VK, OK));
5864
5865  return Owned(new (Context)
5866    BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5867                              RHS.take(), QuestionLoc, ColonLoc, result, VK,
5868                              OK));
5869}
5870
5871// checkPointerTypesForAssignment - This is a very tricky routine (despite
5872// being closely modeled after the C99 spec:-). The odd characteristic of this
5873// routine is it effectively iqnores the qualifiers on the top level pointee.
5874// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5875// FIXME: add a couple examples in this comment.
5876static Sema::AssignConvertType
5877checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5878  assert(LHSType.isCanonical() && "LHS not canonicalized!");
5879  assert(RHSType.isCanonical() && "RHS not canonicalized!");
5880
5881  // get the "pointed to" type (ignoring qualifiers at the top level)
5882  const Type *lhptee, *rhptee;
5883  Qualifiers lhq, rhq;
5884  llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5885  llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5886
5887  Sema::AssignConvertType ConvTy = Sema::Compatible;
5888
5889  // C99 6.5.16.1p1: This following citation is common to constraints
5890  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5891  // qualifiers of the type *pointed to* by the right;
5892  Qualifiers lq;
5893
5894  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5895  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5896      lhq.compatiblyIncludesObjCLifetime(rhq)) {
5897    // Ignore lifetime for further calculation.
5898    lhq.removeObjCLifetime();
5899    rhq.removeObjCLifetime();
5900  }
5901
5902  if (!lhq.compatiblyIncludes(rhq)) {
5903    // Treat address-space mismatches as fatal.  TODO: address subspaces
5904    if (lhq.getAddressSpace() != rhq.getAddressSpace())
5905      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5906
5907    // It's okay to add or remove GC or lifetime qualifiers when converting to
5908    // and from void*.
5909    else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5910                        .compatiblyIncludes(
5911                                rhq.withoutObjCGCAttr().withoutObjCLifetime())
5912             && (lhptee->isVoidType() || rhptee->isVoidType()))
5913      ; // keep old
5914
5915    // Treat lifetime mismatches as fatal.
5916    else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5917      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5918
5919    // For GCC compatibility, other qualifier mismatches are treated
5920    // as still compatible in C.
5921    else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5922  }
5923
5924  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5925  // incomplete type and the other is a pointer to a qualified or unqualified
5926  // version of void...
5927  if (lhptee->isVoidType()) {
5928    if (rhptee->isIncompleteOrObjectType())
5929      return ConvTy;
5930
5931    // As an extension, we allow cast to/from void* to function pointer.
5932    assert(rhptee->isFunctionType());
5933    return Sema::FunctionVoidPointer;
5934  }
5935
5936  if (rhptee->isVoidType()) {
5937    if (lhptee->isIncompleteOrObjectType())
5938      return ConvTy;
5939
5940    // As an extension, we allow cast to/from void* to function pointer.
5941    assert(lhptee->isFunctionType());
5942    return Sema::FunctionVoidPointer;
5943  }
5944
5945  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5946  // unqualified versions of compatible types, ...
5947  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5948  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5949    // Check if the pointee types are compatible ignoring the sign.
5950    // We explicitly check for char so that we catch "char" vs
5951    // "unsigned char" on systems where "char" is unsigned.
5952    if (lhptee->isCharType())
5953      ltrans = S.Context.UnsignedCharTy;
5954    else if (lhptee->hasSignedIntegerRepresentation())
5955      ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5956
5957    if (rhptee->isCharType())
5958      rtrans = S.Context.UnsignedCharTy;
5959    else if (rhptee->hasSignedIntegerRepresentation())
5960      rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5961
5962    if (ltrans == rtrans) {
5963      // Types are compatible ignoring the sign. Qualifier incompatibility
5964      // takes priority over sign incompatibility because the sign
5965      // warning can be disabled.
5966      if (ConvTy != Sema::Compatible)
5967        return ConvTy;
5968
5969      return Sema::IncompatiblePointerSign;
5970    }
5971
5972    // If we are a multi-level pointer, it's possible that our issue is simply
5973    // one of qualification - e.g. char ** -> const char ** is not allowed. If
5974    // the eventual target type is the same and the pointers have the same
5975    // level of indirection, this must be the issue.
5976    if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5977      do {
5978        lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5979        rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5980      } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5981
5982      if (lhptee == rhptee)
5983        return Sema::IncompatibleNestedPointerQualifiers;
5984    }
5985
5986    // General pointer incompatibility takes priority over qualifiers.
5987    return Sema::IncompatiblePointer;
5988  }
5989  if (!S.getLangOpts().CPlusPlus &&
5990      S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5991    return Sema::IncompatiblePointer;
5992  return ConvTy;
5993}
5994
5995/// checkBlockPointerTypesForAssignment - This routine determines whether two
5996/// block pointer types are compatible or whether a block and normal pointer
5997/// are compatible. It is more restrict than comparing two function pointer
5998// types.
5999static Sema::AssignConvertType
6000checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6001                                    QualType RHSType) {
6002  assert(LHSType.isCanonical() && "LHS not canonicalized!");
6003  assert(RHSType.isCanonical() && "RHS not canonicalized!");
6004
6005  QualType lhptee, rhptee;
6006
6007  // get the "pointed to" type (ignoring qualifiers at the top level)
6008  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6009  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6010
6011  // In C++, the types have to match exactly.
6012  if (S.getLangOpts().CPlusPlus)
6013    return Sema::IncompatibleBlockPointer;
6014
6015  Sema::AssignConvertType ConvTy = Sema::Compatible;
6016
6017  // For blocks we enforce that qualifiers are identical.
6018  if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6019    ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6020
6021  if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6022    return Sema::IncompatibleBlockPointer;
6023
6024  return ConvTy;
6025}
6026
6027/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6028/// for assignment compatibility.
6029static Sema::AssignConvertType
6030checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6031                                   QualType RHSType) {
6032  assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6033  assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6034
6035  if (LHSType->isObjCBuiltinType()) {
6036    // Class is not compatible with ObjC object pointers.
6037    if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6038        !RHSType->isObjCQualifiedClassType())
6039      return Sema::IncompatiblePointer;
6040    return Sema::Compatible;
6041  }
6042  if (RHSType->isObjCBuiltinType()) {
6043    if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6044        !LHSType->isObjCQualifiedClassType())
6045      return Sema::IncompatiblePointer;
6046    return Sema::Compatible;
6047  }
6048  QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6049  QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6050
6051  if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6052      // make an exception for id<P>
6053      !LHSType->isObjCQualifiedIdType())
6054    return Sema::CompatiblePointerDiscardsQualifiers;
6055
6056  if (S.Context.typesAreCompatible(LHSType, RHSType))
6057    return Sema::Compatible;
6058  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6059    return Sema::IncompatibleObjCQualifiedId;
6060  return Sema::IncompatiblePointer;
6061}
6062
6063Sema::AssignConvertType
6064Sema::CheckAssignmentConstraints(SourceLocation Loc,
6065                                 QualType LHSType, QualType RHSType) {
6066  // Fake up an opaque expression.  We don't actually care about what
6067  // cast operations are required, so if CheckAssignmentConstraints
6068  // adds casts to this they'll be wasted, but fortunately that doesn't
6069  // usually happen on valid code.
6070  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6071  ExprResult RHSPtr = &RHSExpr;
6072  CastKind K = CK_Invalid;
6073
6074  return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6075}
6076
6077/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6078/// has code to accommodate several GCC extensions when type checking
6079/// pointers. Here are some objectionable examples that GCC considers warnings:
6080///
6081///  int a, *pint;
6082///  short *pshort;
6083///  struct foo *pfoo;
6084///
6085///  pint = pshort; // warning: assignment from incompatible pointer type
6086///  a = pint; // warning: assignment makes integer from pointer without a cast
6087///  pint = a; // warning: assignment makes pointer from integer without a cast
6088///  pint = pfoo; // warning: assignment from incompatible pointer type
6089///
6090/// As a result, the code for dealing with pointers is more complex than the
6091/// C99 spec dictates.
6092///
6093/// Sets 'Kind' for any result kind except Incompatible.
6094Sema::AssignConvertType
6095Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6096                                 CastKind &Kind) {
6097  QualType RHSType = RHS.get()->getType();
6098  QualType OrigLHSType = LHSType;
6099
6100  // Get canonical types.  We're not formatting these types, just comparing
6101  // them.
6102  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6103  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6104
6105  // Common case: no conversion required.
6106  if (LHSType == RHSType) {
6107    Kind = CK_NoOp;
6108    return Compatible;
6109  }
6110
6111  // If we have an atomic type, try a non-atomic assignment, then just add an
6112  // atomic qualification step.
6113  if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6114    Sema::AssignConvertType result =
6115      CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6116    if (result != Compatible)
6117      return result;
6118    if (Kind != CK_NoOp)
6119      RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
6120    Kind = CK_NonAtomicToAtomic;
6121    return Compatible;
6122  }
6123
6124  // If the left-hand side is a reference type, then we are in a
6125  // (rare!) case where we've allowed the use of references in C,
6126  // e.g., as a parameter type in a built-in function. In this case,
6127  // just make sure that the type referenced is compatible with the
6128  // right-hand side type. The caller is responsible for adjusting
6129  // LHSType so that the resulting expression does not have reference
6130  // type.
6131  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6132    if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6133      Kind = CK_LValueBitCast;
6134      return Compatible;
6135    }
6136    return Incompatible;
6137  }
6138
6139  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6140  // to the same ExtVector type.
6141  if (LHSType->isExtVectorType()) {
6142    if (RHSType->isExtVectorType())
6143      return Incompatible;
6144    if (RHSType->isArithmeticType()) {
6145      // CK_VectorSplat does T -> vector T, so first cast to the
6146      // element type.
6147      QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6148      if (elType != RHSType) {
6149        Kind = PrepareScalarCast(RHS, elType);
6150        RHS = ImpCastExprToType(RHS.take(), elType, Kind);
6151      }
6152      Kind = CK_VectorSplat;
6153      return Compatible;
6154    }
6155  }
6156
6157  // Conversions to or from vector type.
6158  if (LHSType->isVectorType() || RHSType->isVectorType()) {
6159    if (LHSType->isVectorType() && RHSType->isVectorType()) {
6160      // Allow assignments of an AltiVec vector type to an equivalent GCC
6161      // vector type and vice versa
6162      if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6163        Kind = CK_BitCast;
6164        return Compatible;
6165      }
6166
6167      // If we are allowing lax vector conversions, and LHS and RHS are both
6168      // vectors, the total size only needs to be the same. This is a bitcast;
6169      // no bits are changed but the result type is different.
6170      if (getLangOpts().LaxVectorConversions &&
6171          (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
6172        Kind = CK_BitCast;
6173        return IncompatibleVectors;
6174      }
6175    }
6176    return Incompatible;
6177  }
6178
6179  // Arithmetic conversions.
6180  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6181      !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6182    Kind = PrepareScalarCast(RHS, LHSType);
6183    return Compatible;
6184  }
6185
6186  // Conversions to normal pointers.
6187  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6188    // U* -> T*
6189    if (isa<PointerType>(RHSType)) {
6190      Kind = CK_BitCast;
6191      return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6192    }
6193
6194    // int -> T*
6195    if (RHSType->isIntegerType()) {
6196      Kind = CK_IntegralToPointer; // FIXME: null?
6197      return IntToPointer;
6198    }
6199
6200    // C pointers are not compatible with ObjC object pointers,
6201    // with two exceptions:
6202    if (isa<ObjCObjectPointerType>(RHSType)) {
6203      //  - conversions to void*
6204      if (LHSPointer->getPointeeType()->isVoidType()) {
6205        Kind = CK_BitCast;
6206        return Compatible;
6207      }
6208
6209      //  - conversions from 'Class' to the redefinition type
6210      if (RHSType->isObjCClassType() &&
6211          Context.hasSameType(LHSType,
6212                              Context.getObjCClassRedefinitionType())) {
6213        Kind = CK_BitCast;
6214        return Compatible;
6215      }
6216
6217      Kind = CK_BitCast;
6218      return IncompatiblePointer;
6219    }
6220
6221    // U^ -> void*
6222    if (RHSType->getAs<BlockPointerType>()) {
6223      if (LHSPointer->getPointeeType()->isVoidType()) {
6224        Kind = CK_BitCast;
6225        return Compatible;
6226      }
6227    }
6228
6229    return Incompatible;
6230  }
6231
6232  // Conversions to block pointers.
6233  if (isa<BlockPointerType>(LHSType)) {
6234    // U^ -> T^
6235    if (RHSType->isBlockPointerType()) {
6236      Kind = CK_BitCast;
6237      return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6238    }
6239
6240    // int or null -> T^
6241    if (RHSType->isIntegerType()) {
6242      Kind = CK_IntegralToPointer; // FIXME: null
6243      return IntToBlockPointer;
6244    }
6245
6246    // id -> T^
6247    if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6248      Kind = CK_AnyPointerToBlockPointerCast;
6249      return Compatible;
6250    }
6251
6252    // void* -> T^
6253    if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6254      if (RHSPT->getPointeeType()->isVoidType()) {
6255        Kind = CK_AnyPointerToBlockPointerCast;
6256        return Compatible;
6257      }
6258
6259    return Incompatible;
6260  }
6261
6262  // Conversions to Objective-C pointers.
6263  if (isa<ObjCObjectPointerType>(LHSType)) {
6264    // A* -> B*
6265    if (RHSType->isObjCObjectPointerType()) {
6266      Kind = CK_BitCast;
6267      Sema::AssignConvertType result =
6268        checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6269      if (getLangOpts().ObjCAutoRefCount &&
6270          result == Compatible &&
6271          !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6272        result = IncompatibleObjCWeakRef;
6273      return result;
6274    }
6275
6276    // int or null -> A*
6277    if (RHSType->isIntegerType()) {
6278      Kind = CK_IntegralToPointer; // FIXME: null
6279      return IntToPointer;
6280    }
6281
6282    // In general, C pointers are not compatible with ObjC object pointers,
6283    // with two exceptions:
6284    if (isa<PointerType>(RHSType)) {
6285      Kind = CK_CPointerToObjCPointerCast;
6286
6287      //  - conversions from 'void*'
6288      if (RHSType->isVoidPointerType()) {
6289        return Compatible;
6290      }
6291
6292      //  - conversions to 'Class' from its redefinition type
6293      if (LHSType->isObjCClassType() &&
6294          Context.hasSameType(RHSType,
6295                              Context.getObjCClassRedefinitionType())) {
6296        return Compatible;
6297      }
6298
6299      return IncompatiblePointer;
6300    }
6301
6302    // T^ -> A*
6303    if (RHSType->isBlockPointerType()) {
6304      maybeExtendBlockObject(*this, RHS);
6305      Kind = CK_BlockPointerToObjCPointerCast;
6306      return Compatible;
6307    }
6308
6309    return Incompatible;
6310  }
6311
6312  // Conversions from pointers that are not covered by the above.
6313  if (isa<PointerType>(RHSType)) {
6314    // T* -> _Bool
6315    if (LHSType == Context.BoolTy) {
6316      Kind = CK_PointerToBoolean;
6317      return Compatible;
6318    }
6319
6320    // T* -> int
6321    if (LHSType->isIntegerType()) {
6322      Kind = CK_PointerToIntegral;
6323      return PointerToInt;
6324    }
6325
6326    return Incompatible;
6327  }
6328
6329  // Conversions from Objective-C pointers that are not covered by the above.
6330  if (isa<ObjCObjectPointerType>(RHSType)) {
6331    // T* -> _Bool
6332    if (LHSType == Context.BoolTy) {
6333      Kind = CK_PointerToBoolean;
6334      return Compatible;
6335    }
6336
6337    // T* -> int
6338    if (LHSType->isIntegerType()) {
6339      Kind = CK_PointerToIntegral;
6340      return PointerToInt;
6341    }
6342
6343    return Incompatible;
6344  }
6345
6346  // struct A -> struct B
6347  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6348    if (Context.typesAreCompatible(LHSType, RHSType)) {
6349      Kind = CK_NoOp;
6350      return Compatible;
6351    }
6352  }
6353
6354  return Incompatible;
6355}
6356
6357/// \brief Constructs a transparent union from an expression that is
6358/// used to initialize the transparent union.
6359static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6360                                      ExprResult &EResult, QualType UnionType,
6361                                      FieldDecl *Field) {
6362  // Build an initializer list that designates the appropriate member
6363  // of the transparent union.
6364  Expr *E = EResult.take();
6365  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6366                                                   E, SourceLocation());
6367  Initializer->setType(UnionType);
6368  Initializer->setInitializedFieldInUnion(Field);
6369
6370  // Build a compound literal constructing a value of the transparent
6371  // union type from this initializer list.
6372  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6373  EResult = S.Owned(
6374    new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6375                                VK_RValue, Initializer, false));
6376}
6377
6378Sema::AssignConvertType
6379Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6380                                               ExprResult &RHS) {
6381  QualType RHSType = RHS.get()->getType();
6382
6383  // If the ArgType is a Union type, we want to handle a potential
6384  // transparent_union GCC extension.
6385  const RecordType *UT = ArgType->getAsUnionType();
6386  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6387    return Incompatible;
6388
6389  // The field to initialize within the transparent union.
6390  RecordDecl *UD = UT->getDecl();
6391  FieldDecl *InitField = 0;
6392  // It's compatible if the expression matches any of the fields.
6393  for (RecordDecl::field_iterator it = UD->field_begin(),
6394         itend = UD->field_end();
6395       it != itend; ++it) {
6396    if (it->getType()->isPointerType()) {
6397      // If the transparent union contains a pointer type, we allow:
6398      // 1) void pointer
6399      // 2) null pointer constant
6400      if (RHSType->isPointerType())
6401        if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6402          RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6403          InitField = *it;
6404          break;
6405        }
6406
6407      if (RHS.get()->isNullPointerConstant(Context,
6408                                           Expr::NPC_ValueDependentIsNull)) {
6409        RHS = ImpCastExprToType(RHS.take(), it->getType(),
6410                                CK_NullToPointer);
6411        InitField = *it;
6412        break;
6413      }
6414    }
6415
6416    CastKind Kind = CK_Invalid;
6417    if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6418          == Compatible) {
6419      RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6420      InitField = *it;
6421      break;
6422    }
6423  }
6424
6425  if (!InitField)
6426    return Incompatible;
6427
6428  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6429  return Compatible;
6430}
6431
6432Sema::AssignConvertType
6433Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6434                                       bool Diagnose,
6435                                       bool DiagnoseCFAudited) {
6436  if (getLangOpts().CPlusPlus) {
6437    if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6438      // C++ 5.17p3: If the left operand is not of class type, the
6439      // expression is implicitly converted (C++ 4) to the
6440      // cv-unqualified type of the left operand.
6441      ExprResult Res;
6442      if (Diagnose) {
6443        Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6444                                        AA_Assigning);
6445      } else {
6446        ImplicitConversionSequence ICS =
6447            TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6448                                  /*SuppressUserConversions=*/false,
6449                                  /*AllowExplicit=*/false,
6450                                  /*InOverloadResolution=*/false,
6451                                  /*CStyle=*/false,
6452                                  /*AllowObjCWritebackConversion=*/false);
6453        if (ICS.isFailure())
6454          return Incompatible;
6455        Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6456                                        ICS, AA_Assigning);
6457      }
6458      if (Res.isInvalid())
6459        return Incompatible;
6460      Sema::AssignConvertType result = Compatible;
6461      if (getLangOpts().ObjCAutoRefCount &&
6462          !CheckObjCARCUnavailableWeakConversion(LHSType,
6463                                                 RHS.get()->getType()))
6464        result = IncompatibleObjCWeakRef;
6465      RHS = Res;
6466      return result;
6467    }
6468
6469    // FIXME: Currently, we fall through and treat C++ classes like C
6470    // structures.
6471    // FIXME: We also fall through for atomics; not sure what should
6472    // happen there, though.
6473  }
6474
6475  // C99 6.5.16.1p1: the left operand is a pointer and the right is
6476  // a null pointer constant.
6477  if ((LHSType->isPointerType() ||
6478       LHSType->isObjCObjectPointerType() ||
6479       LHSType->isBlockPointerType())
6480      && RHS.get()->isNullPointerConstant(Context,
6481                                          Expr::NPC_ValueDependentIsNull)) {
6482    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6483    return Compatible;
6484  }
6485
6486  // This check seems unnatural, however it is necessary to ensure the proper
6487  // conversion of functions/arrays. If the conversion were done for all
6488  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6489  // expressions that suppress this implicit conversion (&, sizeof).
6490  //
6491  // Suppress this for references: C++ 8.5.3p5.
6492  if (!LHSType->isReferenceType()) {
6493    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6494    if (RHS.isInvalid())
6495      return Incompatible;
6496  }
6497
6498  CastKind Kind = CK_Invalid;
6499  Sema::AssignConvertType result =
6500    CheckAssignmentConstraints(LHSType, RHS, Kind);
6501
6502  // C99 6.5.16.1p2: The value of the right operand is converted to the
6503  // type of the assignment expression.
6504  // CheckAssignmentConstraints allows the left-hand side to be a reference,
6505  // so that we can use references in built-in functions even in C.
6506  // The getNonReferenceType() call makes sure that the resulting expression
6507  // does not have reference type.
6508  if (result != Incompatible && RHS.get()->getType() != LHSType) {
6509    QualType Ty = LHSType.getNonLValueExprType(Context);
6510    Expr *E = RHS.take();
6511    if (getLangOpts().ObjCAutoRefCount)
6512      CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6513                             DiagnoseCFAudited);
6514    RHS = ImpCastExprToType(E, Ty, Kind);
6515  }
6516  return result;
6517}
6518
6519QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6520                               ExprResult &RHS) {
6521  Diag(Loc, diag::err_typecheck_invalid_operands)
6522    << LHS.get()->getType() << RHS.get()->getType()
6523    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6524  return QualType();
6525}
6526
6527QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6528                                   SourceLocation Loc, bool IsCompAssign) {
6529  if (!IsCompAssign) {
6530    LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6531    if (LHS.isInvalid())
6532      return QualType();
6533  }
6534  RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6535  if (RHS.isInvalid())
6536    return QualType();
6537
6538  // For conversion purposes, we ignore any qualifiers.
6539  // For example, "const float" and "float" are equivalent.
6540  QualType LHSType =
6541    Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6542  QualType RHSType =
6543    Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6544
6545  // If the vector types are identical, return.
6546  if (LHSType == RHSType)
6547    return LHSType;
6548
6549  // Handle the case of equivalent AltiVec and GCC vector types
6550  if (LHSType->isVectorType() && RHSType->isVectorType() &&
6551      Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6552    if (LHSType->isExtVectorType()) {
6553      RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6554      return LHSType;
6555    }
6556
6557    if (!IsCompAssign)
6558      LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6559    return RHSType;
6560  }
6561
6562  if (getLangOpts().LaxVectorConversions &&
6563      Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6564    // If we are allowing lax vector conversions, and LHS and RHS are both
6565    // vectors, the total size only needs to be the same. This is a
6566    // bitcast; no bits are changed but the result type is different.
6567    // FIXME: Should we really be allowing this?
6568    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6569    return LHSType;
6570  }
6571
6572  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6573  // swap back (so that we don't reverse the inputs to a subtract, for instance.
6574  bool swapped = false;
6575  if (RHSType->isExtVectorType() && !IsCompAssign) {
6576    swapped = true;
6577    std::swap(RHS, LHS);
6578    std::swap(RHSType, LHSType);
6579  }
6580
6581  // Handle the case of an ext vector and scalar.
6582  if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6583    QualType EltTy = LV->getElementType();
6584    if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6585      int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6586      if (order > 0)
6587        RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6588      if (order >= 0) {
6589        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6590        if (swapped) std::swap(RHS, LHS);
6591        return LHSType;
6592      }
6593    }
6594    if (EltTy->isRealFloatingType() && RHSType->isScalarType()) {
6595      if (RHSType->isRealFloatingType()) {
6596        int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6597        if (order > 0)
6598          RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6599        if (order >= 0) {
6600          RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6601          if (swapped) std::swap(RHS, LHS);
6602          return LHSType;
6603        }
6604      }
6605      if (RHSType->isIntegralType(Context)) {
6606        RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating);
6607        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6608        if (swapped) std::swap(RHS, LHS);
6609        return LHSType;
6610      }
6611    }
6612  }
6613
6614  // Vectors of different size or scalar and non-ext-vector are errors.
6615  if (swapped) std::swap(RHS, LHS);
6616  Diag(Loc, diag::err_typecheck_vector_not_convertable)
6617    << LHS.get()->getType() << RHS.get()->getType()
6618    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6619  return QualType();
6620}
6621
6622// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6623// expression.  These are mainly cases where the null pointer is used as an
6624// integer instead of a pointer.
6625static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6626                                SourceLocation Loc, bool IsCompare) {
6627  // The canonical way to check for a GNU null is with isNullPointerConstant,
6628  // but we use a bit of a hack here for speed; this is a relatively
6629  // hot path, and isNullPointerConstant is slow.
6630  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6631  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6632
6633  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6634
6635  // Avoid analyzing cases where the result will either be invalid (and
6636  // diagnosed as such) or entirely valid and not something to warn about.
6637  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6638      NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6639    return;
6640
6641  // Comparison operations would not make sense with a null pointer no matter
6642  // what the other expression is.
6643  if (!IsCompare) {
6644    S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6645        << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6646        << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6647    return;
6648  }
6649
6650  // The rest of the operations only make sense with a null pointer
6651  // if the other expression is a pointer.
6652  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6653      NonNullType->canDecayToPointerType())
6654    return;
6655
6656  S.Diag(Loc, diag::warn_null_in_comparison_operation)
6657      << LHSNull /* LHS is NULL */ << NonNullType
6658      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6659}
6660
6661QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6662                                           SourceLocation Loc,
6663                                           bool IsCompAssign, bool IsDiv) {
6664  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6665
6666  if (LHS.get()->getType()->isVectorType() ||
6667      RHS.get()->getType()->isVectorType())
6668    return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6669
6670  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6671  if (LHS.isInvalid() || RHS.isInvalid())
6672    return QualType();
6673
6674
6675  if (compType.isNull() || !compType->isArithmeticType())
6676    return InvalidOperands(Loc, LHS, RHS);
6677
6678  // Check for division by zero.
6679  llvm::APSInt RHSValue;
6680  if (IsDiv && !RHS.get()->isValueDependent() &&
6681      RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6682    DiagRuntimeBehavior(Loc, RHS.get(),
6683                        PDiag(diag::warn_division_by_zero)
6684                          << RHS.get()->getSourceRange());
6685
6686  return compType;
6687}
6688
6689QualType Sema::CheckRemainderOperands(
6690  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6691  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6692
6693  if (LHS.get()->getType()->isVectorType() ||
6694      RHS.get()->getType()->isVectorType()) {
6695    if (LHS.get()->getType()->hasIntegerRepresentation() &&
6696        RHS.get()->getType()->hasIntegerRepresentation())
6697      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6698    return InvalidOperands(Loc, LHS, RHS);
6699  }
6700
6701  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6702  if (LHS.isInvalid() || RHS.isInvalid())
6703    return QualType();
6704
6705  if (compType.isNull() || !compType->isIntegerType())
6706    return InvalidOperands(Loc, LHS, RHS);
6707
6708  // Check for remainder by zero.
6709  llvm::APSInt RHSValue;
6710  if (!RHS.get()->isValueDependent() &&
6711      RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6712    DiagRuntimeBehavior(Loc, RHS.get(),
6713                        PDiag(diag::warn_remainder_by_zero)
6714                          << RHS.get()->getSourceRange());
6715
6716  return compType;
6717}
6718
6719/// \brief Diagnose invalid arithmetic on two void pointers.
6720static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6721                                                Expr *LHSExpr, Expr *RHSExpr) {
6722  S.Diag(Loc, S.getLangOpts().CPlusPlus
6723                ? diag::err_typecheck_pointer_arith_void_type
6724                : diag::ext_gnu_void_ptr)
6725    << 1 /* two pointers */ << LHSExpr->getSourceRange()
6726                            << RHSExpr->getSourceRange();
6727}
6728
6729/// \brief Diagnose invalid arithmetic on a void pointer.
6730static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6731                                            Expr *Pointer) {
6732  S.Diag(Loc, S.getLangOpts().CPlusPlus
6733                ? diag::err_typecheck_pointer_arith_void_type
6734                : diag::ext_gnu_void_ptr)
6735    << 0 /* one pointer */ << Pointer->getSourceRange();
6736}
6737
6738/// \brief Diagnose invalid arithmetic on two function pointers.
6739static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6740                                                    Expr *LHS, Expr *RHS) {
6741  assert(LHS->getType()->isAnyPointerType());
6742  assert(RHS->getType()->isAnyPointerType());
6743  S.Diag(Loc, S.getLangOpts().CPlusPlus
6744                ? diag::err_typecheck_pointer_arith_function_type
6745                : diag::ext_gnu_ptr_func_arith)
6746    << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6747    // We only show the second type if it differs from the first.
6748    << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6749                                                   RHS->getType())
6750    << RHS->getType()->getPointeeType()
6751    << LHS->getSourceRange() << RHS->getSourceRange();
6752}
6753
6754/// \brief Diagnose invalid arithmetic on a function pointer.
6755static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6756                                                Expr *Pointer) {
6757  assert(Pointer->getType()->isAnyPointerType());
6758  S.Diag(Loc, S.getLangOpts().CPlusPlus
6759                ? diag::err_typecheck_pointer_arith_function_type
6760                : diag::ext_gnu_ptr_func_arith)
6761    << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6762    << 0 /* one pointer, so only one type */
6763    << Pointer->getSourceRange();
6764}
6765
6766/// \brief Emit error if Operand is incomplete pointer type
6767///
6768/// \returns True if pointer has incomplete type
6769static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6770                                                 Expr *Operand) {
6771  assert(Operand->getType()->isAnyPointerType() &&
6772         !Operand->getType()->isDependentType());
6773  QualType PointeeTy = Operand->getType()->getPointeeType();
6774  return S.RequireCompleteType(Loc, PointeeTy,
6775                               diag::err_typecheck_arithmetic_incomplete_type,
6776                               PointeeTy, Operand->getSourceRange());
6777}
6778
6779/// \brief Check the validity of an arithmetic pointer operand.
6780///
6781/// If the operand has pointer type, this code will check for pointer types
6782/// which are invalid in arithmetic operations. These will be diagnosed
6783/// appropriately, including whether or not the use is supported as an
6784/// extension.
6785///
6786/// \returns True when the operand is valid to use (even if as an extension).
6787static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6788                                            Expr *Operand) {
6789  if (!Operand->getType()->isAnyPointerType()) return true;
6790
6791  QualType PointeeTy = Operand->getType()->getPointeeType();
6792  if (PointeeTy->isVoidType()) {
6793    diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6794    return !S.getLangOpts().CPlusPlus;
6795  }
6796  if (PointeeTy->isFunctionType()) {
6797    diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6798    return !S.getLangOpts().CPlusPlus;
6799  }
6800
6801  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6802
6803  return true;
6804}
6805
6806/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6807/// operands.
6808///
6809/// This routine will diagnose any invalid arithmetic on pointer operands much
6810/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6811/// for emitting a single diagnostic even for operations where both LHS and RHS
6812/// are (potentially problematic) pointers.
6813///
6814/// \returns True when the operand is valid to use (even if as an extension).
6815static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6816                                                Expr *LHSExpr, Expr *RHSExpr) {
6817  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6818  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6819  if (!isLHSPointer && !isRHSPointer) return true;
6820
6821  QualType LHSPointeeTy, RHSPointeeTy;
6822  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6823  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6824
6825  // Check for arithmetic on pointers to incomplete types.
6826  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6827  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6828  if (isLHSVoidPtr || isRHSVoidPtr) {
6829    if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6830    else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6831    else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6832
6833    return !S.getLangOpts().CPlusPlus;
6834  }
6835
6836  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6837  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6838  if (isLHSFuncPtr || isRHSFuncPtr) {
6839    if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6840    else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6841                                                                RHSExpr);
6842    else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6843
6844    return !S.getLangOpts().CPlusPlus;
6845  }
6846
6847  if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6848    return false;
6849  if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6850    return false;
6851
6852  return true;
6853}
6854
6855/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6856/// literal.
6857static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6858                                  Expr *LHSExpr, Expr *RHSExpr) {
6859  StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6860  Expr* IndexExpr = RHSExpr;
6861  if (!StrExpr) {
6862    StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6863    IndexExpr = LHSExpr;
6864  }
6865
6866  bool IsStringPlusInt = StrExpr &&
6867      IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6868  if (!IsStringPlusInt)
6869    return;
6870
6871  llvm::APSInt index;
6872  if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6873    unsigned StrLenWithNull = StrExpr->getLength() + 1;
6874    if (index.isNonNegative() &&
6875        index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6876                              index.isUnsigned()))
6877      return;
6878  }
6879
6880  SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6881  Self.Diag(OpLoc, diag::warn_string_plus_int)
6882      << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6883
6884  // Only print a fixit for "str" + int, not for int + "str".
6885  if (IndexExpr == RHSExpr) {
6886    SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6887    Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6888        << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6889        << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6890        << FixItHint::CreateInsertion(EndLoc, "]");
6891  } else
6892    Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6893}
6894
6895/// \brief Emit error when two pointers are incompatible.
6896static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6897                                           Expr *LHSExpr, Expr *RHSExpr) {
6898  assert(LHSExpr->getType()->isAnyPointerType());
6899  assert(RHSExpr->getType()->isAnyPointerType());
6900  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6901    << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6902    << RHSExpr->getSourceRange();
6903}
6904
6905QualType Sema::CheckAdditionOperands( // C99 6.5.6
6906    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6907    QualType* CompLHSTy) {
6908  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6909
6910  if (LHS.get()->getType()->isVectorType() ||
6911      RHS.get()->getType()->isVectorType()) {
6912    QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6913    if (CompLHSTy) *CompLHSTy = compType;
6914    return compType;
6915  }
6916
6917  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6918  if (LHS.isInvalid() || RHS.isInvalid())
6919    return QualType();
6920
6921  // Diagnose "string literal" '+' int.
6922  if (Opc == BO_Add)
6923    diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6924
6925  // handle the common case first (both operands are arithmetic).
6926  if (!compType.isNull() && compType->isArithmeticType()) {
6927    if (CompLHSTy) *CompLHSTy = compType;
6928    return compType;
6929  }
6930
6931  // Type-checking.  Ultimately the pointer's going to be in PExp;
6932  // note that we bias towards the LHS being the pointer.
6933  Expr *PExp = LHS.get(), *IExp = RHS.get();
6934
6935  bool isObjCPointer;
6936  if (PExp->getType()->isPointerType()) {
6937    isObjCPointer = false;
6938  } else if (PExp->getType()->isObjCObjectPointerType()) {
6939    isObjCPointer = true;
6940  } else {
6941    std::swap(PExp, IExp);
6942    if (PExp->getType()->isPointerType()) {
6943      isObjCPointer = false;
6944    } else if (PExp->getType()->isObjCObjectPointerType()) {
6945      isObjCPointer = true;
6946    } else {
6947      return InvalidOperands(Loc, LHS, RHS);
6948    }
6949  }
6950  assert(PExp->getType()->isAnyPointerType());
6951
6952  if (!IExp->getType()->isIntegerType())
6953    return InvalidOperands(Loc, LHS, RHS);
6954
6955  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6956    return QualType();
6957
6958  if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6959    return QualType();
6960
6961  // Check array bounds for pointer arithemtic
6962  CheckArrayAccess(PExp, IExp);
6963
6964  if (CompLHSTy) {
6965    QualType LHSTy = Context.isPromotableBitField(LHS.get());
6966    if (LHSTy.isNull()) {
6967      LHSTy = LHS.get()->getType();
6968      if (LHSTy->isPromotableIntegerType())
6969        LHSTy = Context.getPromotedIntegerType(LHSTy);
6970    }
6971    *CompLHSTy = LHSTy;
6972  }
6973
6974  return PExp->getType();
6975}
6976
6977// C99 6.5.6
6978QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6979                                        SourceLocation Loc,
6980                                        QualType* CompLHSTy) {
6981  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6982
6983  if (LHS.get()->getType()->isVectorType() ||
6984      RHS.get()->getType()->isVectorType()) {
6985    QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6986    if (CompLHSTy) *CompLHSTy = compType;
6987    return compType;
6988  }
6989
6990  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6991  if (LHS.isInvalid() || RHS.isInvalid())
6992    return QualType();
6993
6994  // Enforce type constraints: C99 6.5.6p3.
6995
6996  // Handle the common case first (both operands are arithmetic).
6997  if (!compType.isNull() && compType->isArithmeticType()) {
6998    if (CompLHSTy) *CompLHSTy = compType;
6999    return compType;
7000  }
7001
7002  // Either ptr - int   or   ptr - ptr.
7003  if (LHS.get()->getType()->isAnyPointerType()) {
7004    QualType lpointee = LHS.get()->getType()->getPointeeType();
7005
7006    // Diagnose bad cases where we step over interface counts.
7007    if (LHS.get()->getType()->isObjCObjectPointerType() &&
7008        checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7009      return QualType();
7010
7011    // The result type of a pointer-int computation is the pointer type.
7012    if (RHS.get()->getType()->isIntegerType()) {
7013      if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7014        return QualType();
7015
7016      // Check array bounds for pointer arithemtic
7017      CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
7018                       /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7019
7020      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7021      return LHS.get()->getType();
7022    }
7023
7024    // Handle pointer-pointer subtractions.
7025    if (const PointerType *RHSPTy
7026          = RHS.get()->getType()->getAs<PointerType>()) {
7027      QualType rpointee = RHSPTy->getPointeeType();
7028
7029      if (getLangOpts().CPlusPlus) {
7030        // Pointee types must be the same: C++ [expr.add]
7031        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7032          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7033        }
7034      } else {
7035        // Pointee types must be compatible C99 6.5.6p3
7036        if (!Context.typesAreCompatible(
7037                Context.getCanonicalType(lpointee).getUnqualifiedType(),
7038                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7039          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7040          return QualType();
7041        }
7042      }
7043
7044      if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7045                                               LHS.get(), RHS.get()))
7046        return QualType();
7047
7048      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7049      return Context.getPointerDiffType();
7050    }
7051  }
7052
7053  return InvalidOperands(Loc, LHS, RHS);
7054}
7055
7056static bool isScopedEnumerationType(QualType T) {
7057  if (const EnumType *ET = dyn_cast<EnumType>(T))
7058    return ET->getDecl()->isScoped();
7059  return false;
7060}
7061
7062static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7063                                   SourceLocation Loc, unsigned Opc,
7064                                   QualType LHSType) {
7065  // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7066  // so skip remaining warnings as we don't want to modify values within Sema.
7067  if (S.getLangOpts().OpenCL)
7068    return;
7069
7070  llvm::APSInt Right;
7071  // Check right/shifter operand
7072  if (RHS.get()->isValueDependent() ||
7073      !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7074    return;
7075
7076  if (Right.isNegative()) {
7077    S.DiagRuntimeBehavior(Loc, RHS.get(),
7078                          S.PDiag(diag::warn_shift_negative)
7079                            << RHS.get()->getSourceRange());
7080    return;
7081  }
7082  llvm::APInt LeftBits(Right.getBitWidth(),
7083                       S.Context.getTypeSize(LHS.get()->getType()));
7084  if (Right.uge(LeftBits)) {
7085    S.DiagRuntimeBehavior(Loc, RHS.get(),
7086                          S.PDiag(diag::warn_shift_gt_typewidth)
7087                            << RHS.get()->getSourceRange());
7088    return;
7089  }
7090  if (Opc != BO_Shl)
7091    return;
7092
7093  // When left shifting an ICE which is signed, we can check for overflow which
7094  // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7095  // integers have defined behavior modulo one more than the maximum value
7096  // representable in the result type, so never warn for those.
7097  llvm::APSInt Left;
7098  if (LHS.get()->isValueDependent() ||
7099      !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7100      LHSType->hasUnsignedIntegerRepresentation())
7101    return;
7102  llvm::APInt ResultBits =
7103      static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7104  if (LeftBits.uge(ResultBits))
7105    return;
7106  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7107  Result = Result.shl(Right);
7108
7109  // Print the bit representation of the signed integer as an unsigned
7110  // hexadecimal number.
7111  SmallString<40> HexResult;
7112  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7113
7114  // If we are only missing a sign bit, this is less likely to result in actual
7115  // bugs -- if the result is cast back to an unsigned type, it will have the
7116  // expected value. Thus we place this behind a different warning that can be
7117  // turned off separately if needed.
7118  if (LeftBits == ResultBits - 1) {
7119    S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7120        << HexResult.str() << LHSType
7121        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7122    return;
7123  }
7124
7125  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7126    << HexResult.str() << Result.getMinSignedBits() << LHSType
7127    << Left.getBitWidth() << LHS.get()->getSourceRange()
7128    << RHS.get()->getSourceRange();
7129}
7130
7131// C99 6.5.7
7132QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7133                                  SourceLocation Loc, unsigned Opc,
7134                                  bool IsCompAssign) {
7135  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7136
7137  // Vector shifts promote their scalar inputs to vector type.
7138  if (LHS.get()->getType()->isVectorType() ||
7139      RHS.get()->getType()->isVectorType())
7140    return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7141
7142  // Shifts don't perform usual arithmetic conversions, they just do integer
7143  // promotions on each operand. C99 6.5.7p3
7144
7145  // For the LHS, do usual unary conversions, but then reset them away
7146  // if this is a compound assignment.
7147  ExprResult OldLHS = LHS;
7148  LHS = UsualUnaryConversions(LHS.take());
7149  if (LHS.isInvalid())
7150    return QualType();
7151  QualType LHSType = LHS.get()->getType();
7152  if (IsCompAssign) LHS = OldLHS;
7153
7154  // The RHS is simpler.
7155  RHS = UsualUnaryConversions(RHS.take());
7156  if (RHS.isInvalid())
7157    return QualType();
7158  QualType RHSType = RHS.get()->getType();
7159
7160  // C99 6.5.7p2: Each of the operands shall have integer type.
7161  if (!LHSType->hasIntegerRepresentation() ||
7162      !RHSType->hasIntegerRepresentation())
7163    return InvalidOperands(Loc, LHS, RHS);
7164
7165  // C++0x: Don't allow scoped enums. FIXME: Use something better than
7166  // hasIntegerRepresentation() above instead of this.
7167  if (isScopedEnumerationType(LHSType) ||
7168      isScopedEnumerationType(RHSType)) {
7169    return InvalidOperands(Loc, LHS, RHS);
7170  }
7171  // Sanity-check shift operands
7172  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7173
7174  // "The type of the result is that of the promoted left operand."
7175  return LHSType;
7176}
7177
7178static bool IsWithinTemplateSpecialization(Decl *D) {
7179  if (DeclContext *DC = D->getDeclContext()) {
7180    if (isa<ClassTemplateSpecializationDecl>(DC))
7181      return true;
7182    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7183      return FD->isFunctionTemplateSpecialization();
7184  }
7185  return false;
7186}
7187
7188/// If two different enums are compared, raise a warning.
7189static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7190                                Expr *RHS) {
7191  QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7192  QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7193
7194  const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7195  if (!LHSEnumType)
7196    return;
7197  const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7198  if (!RHSEnumType)
7199    return;
7200
7201  // Ignore anonymous enums.
7202  if (!LHSEnumType->getDecl()->getIdentifier())
7203    return;
7204  if (!RHSEnumType->getDecl()->getIdentifier())
7205    return;
7206
7207  if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7208    return;
7209
7210  S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7211      << LHSStrippedType << RHSStrippedType
7212      << LHS->getSourceRange() << RHS->getSourceRange();
7213}
7214
7215/// \brief Diagnose bad pointer comparisons.
7216static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7217                                              ExprResult &LHS, ExprResult &RHS,
7218                                              bool IsError) {
7219  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7220                      : diag::ext_typecheck_comparison_of_distinct_pointers)
7221    << LHS.get()->getType() << RHS.get()->getType()
7222    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7223}
7224
7225/// \brief Returns false if the pointers are converted to a composite type,
7226/// true otherwise.
7227static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7228                                           ExprResult &LHS, ExprResult &RHS) {
7229  // C++ [expr.rel]p2:
7230  //   [...] Pointer conversions (4.10) and qualification
7231  //   conversions (4.4) are performed on pointer operands (or on
7232  //   a pointer operand and a null pointer constant) to bring
7233  //   them to their composite pointer type. [...]
7234  //
7235  // C++ [expr.eq]p1 uses the same notion for (in)equality
7236  // comparisons of pointers.
7237
7238  // C++ [expr.eq]p2:
7239  //   In addition, pointers to members can be compared, or a pointer to
7240  //   member and a null pointer constant. Pointer to member conversions
7241  //   (4.11) and qualification conversions (4.4) are performed to bring
7242  //   them to a common type. If one operand is a null pointer constant,
7243  //   the common type is the type of the other operand. Otherwise, the
7244  //   common type is a pointer to member type similar (4.4) to the type
7245  //   of one of the operands, with a cv-qualification signature (4.4)
7246  //   that is the union of the cv-qualification signatures of the operand
7247  //   types.
7248
7249  QualType LHSType = LHS.get()->getType();
7250  QualType RHSType = RHS.get()->getType();
7251  assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7252         (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7253
7254  bool NonStandardCompositeType = false;
7255  bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
7256  QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7257  if (T.isNull()) {
7258    diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7259    return true;
7260  }
7261
7262  if (NonStandardCompositeType)
7263    S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7264      << LHSType << RHSType << T << LHS.get()->getSourceRange()
7265      << RHS.get()->getSourceRange();
7266
7267  LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7268  RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
7269  return false;
7270}
7271
7272static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7273                                                    ExprResult &LHS,
7274                                                    ExprResult &RHS,
7275                                                    bool IsError) {
7276  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7277                      : diag::ext_typecheck_comparison_of_fptr_to_void)
7278    << LHS.get()->getType() << RHS.get()->getType()
7279    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7280}
7281
7282static bool isObjCObjectLiteral(ExprResult &E) {
7283  switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7284  case Stmt::ObjCArrayLiteralClass:
7285  case Stmt::ObjCDictionaryLiteralClass:
7286  case Stmt::ObjCStringLiteralClass:
7287  case Stmt::ObjCBoxedExprClass:
7288    return true;
7289  default:
7290    // Note that ObjCBoolLiteral is NOT an object literal!
7291    return false;
7292  }
7293}
7294
7295static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7296  const ObjCObjectPointerType *Type =
7297    LHS->getType()->getAs<ObjCObjectPointerType>();
7298
7299  // If this is not actually an Objective-C object, bail out.
7300  if (!Type)
7301    return false;
7302
7303  // Get the LHS object's interface type.
7304  QualType InterfaceType = Type->getPointeeType();
7305  if (const ObjCObjectType *iQFaceTy =
7306      InterfaceType->getAsObjCQualifiedInterfaceType())
7307    InterfaceType = iQFaceTy->getBaseType();
7308
7309  // If the RHS isn't an Objective-C object, bail out.
7310  if (!RHS->getType()->isObjCObjectPointerType())
7311    return false;
7312
7313  // Try to find the -isEqual: method.
7314  Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7315  ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7316                                                      InterfaceType,
7317                                                      /*instance=*/true);
7318  if (!Method) {
7319    if (Type->isObjCIdType()) {
7320      // For 'id', just check the global pool.
7321      Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7322                                                  /*receiverId=*/true,
7323                                                  /*warn=*/false);
7324    } else {
7325      // Check protocols.
7326      Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7327                                             /*instance=*/true);
7328    }
7329  }
7330
7331  if (!Method)
7332    return false;
7333
7334  QualType T = Method->param_begin()[0]->getType();
7335  if (!T->isObjCObjectPointerType())
7336    return false;
7337
7338  QualType R = Method->getResultType();
7339  if (!R->isScalarType())
7340    return false;
7341
7342  return true;
7343}
7344
7345Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7346  FromE = FromE->IgnoreParenImpCasts();
7347  switch (FromE->getStmtClass()) {
7348    default:
7349      break;
7350    case Stmt::ObjCStringLiteralClass:
7351      // "string literal"
7352      return LK_String;
7353    case Stmt::ObjCArrayLiteralClass:
7354      // "array literal"
7355      return LK_Array;
7356    case Stmt::ObjCDictionaryLiteralClass:
7357      // "dictionary literal"
7358      return LK_Dictionary;
7359    case Stmt::BlockExprClass:
7360      return LK_Block;
7361    case Stmt::ObjCBoxedExprClass: {
7362      Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7363      switch (Inner->getStmtClass()) {
7364        case Stmt::IntegerLiteralClass:
7365        case Stmt::FloatingLiteralClass:
7366        case Stmt::CharacterLiteralClass:
7367        case Stmt::ObjCBoolLiteralExprClass:
7368        case Stmt::CXXBoolLiteralExprClass:
7369          // "numeric literal"
7370          return LK_Numeric;
7371        case Stmt::ImplicitCastExprClass: {
7372          CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7373          // Boolean literals can be represented by implicit casts.
7374          if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7375            return LK_Numeric;
7376          break;
7377        }
7378        default:
7379          break;
7380      }
7381      return LK_Boxed;
7382    }
7383  }
7384  return LK_None;
7385}
7386
7387static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7388                                          ExprResult &LHS, ExprResult &RHS,
7389                                          BinaryOperator::Opcode Opc){
7390  Expr *Literal;
7391  Expr *Other;
7392  if (isObjCObjectLiteral(LHS)) {
7393    Literal = LHS.get();
7394    Other = RHS.get();
7395  } else {
7396    Literal = RHS.get();
7397    Other = LHS.get();
7398  }
7399
7400  // Don't warn on comparisons against nil.
7401  Other = Other->IgnoreParenCasts();
7402  if (Other->isNullPointerConstant(S.getASTContext(),
7403                                   Expr::NPC_ValueDependentIsNotNull))
7404    return;
7405
7406  // This should be kept in sync with warn_objc_literal_comparison.
7407  // LK_String should always be after the other literals, since it has its own
7408  // warning flag.
7409  Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7410  assert(LiteralKind != Sema::LK_Block);
7411  if (LiteralKind == Sema::LK_None) {
7412    llvm_unreachable("Unknown Objective-C object literal kind");
7413  }
7414
7415  if (LiteralKind == Sema::LK_String)
7416    S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7417      << Literal->getSourceRange();
7418  else
7419    S.Diag(Loc, diag::warn_objc_literal_comparison)
7420      << LiteralKind << Literal->getSourceRange();
7421
7422  if (BinaryOperator::isEqualityOp(Opc) &&
7423      hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7424    SourceLocation Start = LHS.get()->getLocStart();
7425    SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7426    CharSourceRange OpRange =
7427      CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7428
7429    S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7430      << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7431      << FixItHint::CreateReplacement(OpRange, " isEqual:")
7432      << FixItHint::CreateInsertion(End, "]");
7433  }
7434}
7435
7436static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7437                                                ExprResult &RHS,
7438                                                SourceLocation Loc,
7439                                                unsigned OpaqueOpc) {
7440  // This checking requires bools.
7441  if (!S.getLangOpts().Bool) return;
7442
7443  // Check that left hand side is !something.
7444  UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7445  if (!UO || UO->getOpcode() != UO_LNot) return;
7446
7447  // Only check if the right hand side is non-bool arithmetic type.
7448  if (RHS.get()->getType()->isBooleanType()) return;
7449
7450  // Make sure that the something in !something is not bool.
7451  Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7452  if (SubExpr->getType()->isBooleanType()) return;
7453
7454  // Emit warning.
7455  S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7456      << Loc;
7457
7458  // First note suggest !(x < y)
7459  SourceLocation FirstOpen = SubExpr->getLocStart();
7460  SourceLocation FirstClose = RHS.get()->getLocEnd();
7461  FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7462  if (FirstClose.isInvalid())
7463    FirstOpen = SourceLocation();
7464  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7465      << FixItHint::CreateInsertion(FirstOpen, "(")
7466      << FixItHint::CreateInsertion(FirstClose, ")");
7467
7468  // Second note suggests (!x) < y
7469  SourceLocation SecondOpen = LHS.get()->getLocStart();
7470  SourceLocation SecondClose = LHS.get()->getLocEnd();
7471  SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7472  if (SecondClose.isInvalid())
7473    SecondOpen = SourceLocation();
7474  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7475      << FixItHint::CreateInsertion(SecondOpen, "(")
7476      << FixItHint::CreateInsertion(SecondClose, ")");
7477}
7478
7479// C99 6.5.8, C++ [expr.rel]
7480QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7481                                    SourceLocation Loc, unsigned OpaqueOpc,
7482                                    bool IsRelational) {
7483  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7484
7485  BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7486
7487  // Handle vector comparisons separately.
7488  if (LHS.get()->getType()->isVectorType() ||
7489      RHS.get()->getType()->isVectorType())
7490    return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7491
7492  QualType LHSType = LHS.get()->getType();
7493  QualType RHSType = RHS.get()->getType();
7494
7495  Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7496  Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7497
7498  checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7499  diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7500
7501  if (!LHSType->hasFloatingRepresentation() &&
7502      !(LHSType->isBlockPointerType() && IsRelational) &&
7503      !LHS.get()->getLocStart().isMacroID() &&
7504      !RHS.get()->getLocStart().isMacroID()) {
7505    // For non-floating point types, check for self-comparisons of the form
7506    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7507    // often indicate logic errors in the program.
7508    //
7509    // NOTE: Don't warn about comparison expressions resulting from macro
7510    // expansion. Also don't warn about comparisons which are only self
7511    // comparisons within a template specialization. The warnings should catch
7512    // obvious cases in the definition of the template anyways. The idea is to
7513    // warn when the typed comparison operator will always evaluate to the same
7514    // result.
7515    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
7516      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
7517        if (DRL->getDecl() == DRR->getDecl() &&
7518            !IsWithinTemplateSpecialization(DRL->getDecl())) {
7519          DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7520                              << 0 // self-
7521                              << (Opc == BO_EQ
7522                                  || Opc == BO_LE
7523                                  || Opc == BO_GE));
7524        } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
7525                   !DRL->getDecl()->getType()->isReferenceType() &&
7526                   !DRR->getDecl()->getType()->isReferenceType()) {
7527            // what is it always going to eval to?
7528            char always_evals_to;
7529            switch(Opc) {
7530            case BO_EQ: // e.g. array1 == array2
7531              always_evals_to = 0; // false
7532              break;
7533            case BO_NE: // e.g. array1 != array2
7534              always_evals_to = 1; // true
7535              break;
7536            default:
7537              // best we can say is 'a constant'
7538              always_evals_to = 2; // e.g. array1 <= array2
7539              break;
7540            }
7541            DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7542                                << 1 // array
7543                                << always_evals_to);
7544        }
7545      }
7546    }
7547
7548    if (isa<CastExpr>(LHSStripped))
7549      LHSStripped = LHSStripped->IgnoreParenCasts();
7550    if (isa<CastExpr>(RHSStripped))
7551      RHSStripped = RHSStripped->IgnoreParenCasts();
7552
7553    // Warn about comparisons against a string constant (unless the other
7554    // operand is null), the user probably wants strcmp.
7555    Expr *literalString = 0;
7556    Expr *literalStringStripped = 0;
7557    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7558        !RHSStripped->isNullPointerConstant(Context,
7559                                            Expr::NPC_ValueDependentIsNull)) {
7560      literalString = LHS.get();
7561      literalStringStripped = LHSStripped;
7562    } else if ((isa<StringLiteral>(RHSStripped) ||
7563                isa<ObjCEncodeExpr>(RHSStripped)) &&
7564               !LHSStripped->isNullPointerConstant(Context,
7565                                            Expr::NPC_ValueDependentIsNull)) {
7566      literalString = RHS.get();
7567      literalStringStripped = RHSStripped;
7568    }
7569
7570    if (literalString) {
7571      DiagRuntimeBehavior(Loc, 0,
7572        PDiag(diag::warn_stringcompare)
7573          << isa<ObjCEncodeExpr>(literalStringStripped)
7574          << literalString->getSourceRange());
7575    }
7576  }
7577
7578  // C99 6.5.8p3 / C99 6.5.9p4
7579  UsualArithmeticConversions(LHS, RHS);
7580  if (LHS.isInvalid() || RHS.isInvalid())
7581    return QualType();
7582
7583  LHSType = LHS.get()->getType();
7584  RHSType = RHS.get()->getType();
7585
7586  // The result of comparisons is 'bool' in C++, 'int' in C.
7587  QualType ResultTy = Context.getLogicalOperationType();
7588
7589  if (IsRelational) {
7590    if (LHSType->isRealType() && RHSType->isRealType())
7591      return ResultTy;
7592  } else {
7593    // Check for comparisons of floating point operands using != and ==.
7594    if (LHSType->hasFloatingRepresentation())
7595      CheckFloatComparison(Loc, LHS.get(), RHS.get());
7596
7597    if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7598      return ResultTy;
7599  }
7600
7601  bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7602                                              Expr::NPC_ValueDependentIsNull);
7603  bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7604                                              Expr::NPC_ValueDependentIsNull);
7605
7606  // All of the following pointer-related warnings are GCC extensions, except
7607  // when handling null pointer constants.
7608  if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7609    QualType LCanPointeeTy =
7610      LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7611    QualType RCanPointeeTy =
7612      RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7613
7614    if (getLangOpts().CPlusPlus) {
7615      if (LCanPointeeTy == RCanPointeeTy)
7616        return ResultTy;
7617      if (!IsRelational &&
7618          (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7619        // Valid unless comparison between non-null pointer and function pointer
7620        // This is a gcc extension compatibility comparison.
7621        // In a SFINAE context, we treat this as a hard error to maintain
7622        // conformance with the C++ standard.
7623        if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7624            && !LHSIsNull && !RHSIsNull) {
7625          diagnoseFunctionPointerToVoidComparison(
7626              *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7627
7628          if (isSFINAEContext())
7629            return QualType();
7630
7631          RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7632          return ResultTy;
7633        }
7634      }
7635
7636      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7637        return QualType();
7638      else
7639        return ResultTy;
7640    }
7641    // C99 6.5.9p2 and C99 6.5.8p2
7642    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7643                                   RCanPointeeTy.getUnqualifiedType())) {
7644      // Valid unless a relational comparison of function pointers
7645      if (IsRelational && LCanPointeeTy->isFunctionType()) {
7646        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7647          << LHSType << RHSType << LHS.get()->getSourceRange()
7648          << RHS.get()->getSourceRange();
7649      }
7650    } else if (!IsRelational &&
7651               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7652      // Valid unless comparison between non-null pointer and function pointer
7653      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7654          && !LHSIsNull && !RHSIsNull)
7655        diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7656                                                /*isError*/false);
7657    } else {
7658      // Invalid
7659      diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7660    }
7661    if (LCanPointeeTy != RCanPointeeTy) {
7662      if (LHSIsNull && !RHSIsNull)
7663        LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7664      else
7665        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7666    }
7667    return ResultTy;
7668  }
7669
7670  if (getLangOpts().CPlusPlus) {
7671    // Comparison of nullptr_t with itself.
7672    if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7673      return ResultTy;
7674
7675    // Comparison of pointers with null pointer constants and equality
7676    // comparisons of member pointers to null pointer constants.
7677    if (RHSIsNull &&
7678        ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7679         (!IsRelational &&
7680          (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7681      RHS = ImpCastExprToType(RHS.take(), LHSType,
7682                        LHSType->isMemberPointerType()
7683                          ? CK_NullToMemberPointer
7684                          : CK_NullToPointer);
7685      return ResultTy;
7686    }
7687    if (LHSIsNull &&
7688        ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7689         (!IsRelational &&
7690          (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7691      LHS = ImpCastExprToType(LHS.take(), RHSType,
7692                        RHSType->isMemberPointerType()
7693                          ? CK_NullToMemberPointer
7694                          : CK_NullToPointer);
7695      return ResultTy;
7696    }
7697
7698    // Comparison of member pointers.
7699    if (!IsRelational &&
7700        LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7701      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7702        return QualType();
7703      else
7704        return ResultTy;
7705    }
7706
7707    // Handle scoped enumeration types specifically, since they don't promote
7708    // to integers.
7709    if (LHS.get()->getType()->isEnumeralType() &&
7710        Context.hasSameUnqualifiedType(LHS.get()->getType(),
7711                                       RHS.get()->getType()))
7712      return ResultTy;
7713  }
7714
7715  // Handle block pointer types.
7716  if (!IsRelational && LHSType->isBlockPointerType() &&
7717      RHSType->isBlockPointerType()) {
7718    QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7719    QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7720
7721    if (!LHSIsNull && !RHSIsNull &&
7722        !Context.typesAreCompatible(lpointee, rpointee)) {
7723      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7724        << LHSType << RHSType << LHS.get()->getSourceRange()
7725        << RHS.get()->getSourceRange();
7726    }
7727    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7728    return ResultTy;
7729  }
7730
7731  // Allow block pointers to be compared with null pointer constants.
7732  if (!IsRelational
7733      && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7734          || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7735    if (!LHSIsNull && !RHSIsNull) {
7736      if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7737             ->getPointeeType()->isVoidType())
7738            || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7739                ->getPointeeType()->isVoidType())))
7740        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7741          << LHSType << RHSType << LHS.get()->getSourceRange()
7742          << RHS.get()->getSourceRange();
7743    }
7744    if (LHSIsNull && !RHSIsNull)
7745      LHS = ImpCastExprToType(LHS.take(), RHSType,
7746                              RHSType->isPointerType() ? CK_BitCast
7747                                : CK_AnyPointerToBlockPointerCast);
7748    else
7749      RHS = ImpCastExprToType(RHS.take(), LHSType,
7750                              LHSType->isPointerType() ? CK_BitCast
7751                                : CK_AnyPointerToBlockPointerCast);
7752    return ResultTy;
7753  }
7754
7755  if (LHSType->isObjCObjectPointerType() ||
7756      RHSType->isObjCObjectPointerType()) {
7757    const PointerType *LPT = LHSType->getAs<PointerType>();
7758    const PointerType *RPT = RHSType->getAs<PointerType>();
7759    if (LPT || RPT) {
7760      bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7761      bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7762
7763      if (!LPtrToVoid && !RPtrToVoid &&
7764          !Context.typesAreCompatible(LHSType, RHSType)) {
7765        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7766                                          /*isError*/false);
7767      }
7768      if (LHSIsNull && !RHSIsNull) {
7769        Expr *E = LHS.take();
7770        if (getLangOpts().ObjCAutoRefCount)
7771          CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
7772        LHS = ImpCastExprToType(E, RHSType,
7773                                RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7774      }
7775      else {
7776        Expr *E = RHS.take();
7777        if (getLangOpts().ObjCAutoRefCount)
7778          CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
7779        RHS = ImpCastExprToType(E, LHSType,
7780                                LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7781      }
7782      return ResultTy;
7783    }
7784    if (LHSType->isObjCObjectPointerType() &&
7785        RHSType->isObjCObjectPointerType()) {
7786      if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7787        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7788                                          /*isError*/false);
7789      if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7790        diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7791
7792      if (LHSIsNull && !RHSIsNull)
7793        LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7794      else
7795        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7796      return ResultTy;
7797    }
7798  }
7799  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7800      (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7801    unsigned DiagID = 0;
7802    bool isError = false;
7803    if (LangOpts.DebuggerSupport) {
7804      // Under a debugger, allow the comparison of pointers to integers,
7805      // since users tend to want to compare addresses.
7806    } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7807        (RHSIsNull && RHSType->isIntegerType())) {
7808      if (IsRelational && !getLangOpts().CPlusPlus)
7809        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7810    } else if (IsRelational && !getLangOpts().CPlusPlus)
7811      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7812    else if (getLangOpts().CPlusPlus) {
7813      DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7814      isError = true;
7815    } else
7816      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7817
7818    if (DiagID) {
7819      Diag(Loc, DiagID)
7820        << LHSType << RHSType << LHS.get()->getSourceRange()
7821        << RHS.get()->getSourceRange();
7822      if (isError)
7823        return QualType();
7824    }
7825
7826    if (LHSType->isIntegerType())
7827      LHS = ImpCastExprToType(LHS.take(), RHSType,
7828                        LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7829    else
7830      RHS = ImpCastExprToType(RHS.take(), LHSType,
7831                        RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7832    return ResultTy;
7833  }
7834
7835  // Handle block pointers.
7836  if (!IsRelational && RHSIsNull
7837      && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7838    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7839    return ResultTy;
7840  }
7841  if (!IsRelational && LHSIsNull
7842      && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7843    LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7844    return ResultTy;
7845  }
7846
7847  return InvalidOperands(Loc, LHS, RHS);
7848}
7849
7850
7851// Return a signed type that is of identical size and number of elements.
7852// For floating point vectors, return an integer type of identical size
7853// and number of elements.
7854QualType Sema::GetSignedVectorType(QualType V) {
7855  const VectorType *VTy = V->getAs<VectorType>();
7856  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7857  if (TypeSize == Context.getTypeSize(Context.CharTy))
7858    return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7859  else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7860    return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7861  else if (TypeSize == Context.getTypeSize(Context.IntTy))
7862    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7863  else if (TypeSize == Context.getTypeSize(Context.LongTy))
7864    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7865  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7866         "Unhandled vector element size in vector compare");
7867  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7868}
7869
7870/// CheckVectorCompareOperands - vector comparisons are a clang extension that
7871/// operates on extended vector types.  Instead of producing an IntTy result,
7872/// like a scalar comparison, a vector comparison produces a vector of integer
7873/// types.
7874QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7875                                          SourceLocation Loc,
7876                                          bool IsRelational) {
7877  // Check to make sure we're operating on vectors of the same type and width,
7878  // Allowing one side to be a scalar of element type.
7879  QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7880  if (vType.isNull())
7881    return vType;
7882
7883  QualType LHSType = LHS.get()->getType();
7884
7885  // If AltiVec, the comparison results in a numeric type, i.e.
7886  // bool for C++, int for C
7887  if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7888    return Context.getLogicalOperationType();
7889
7890  // For non-floating point types, check for self-comparisons of the form
7891  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7892  // often indicate logic errors in the program.
7893  if (!LHSType->hasFloatingRepresentation()) {
7894    if (DeclRefExpr* DRL
7895          = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7896      if (DeclRefExpr* DRR
7897            = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7898        if (DRL->getDecl() == DRR->getDecl())
7899          DiagRuntimeBehavior(Loc, 0,
7900                              PDiag(diag::warn_comparison_always)
7901                                << 0 // self-
7902                                << 2 // "a constant"
7903                              );
7904  }
7905
7906  // Check for comparisons of floating point operands using != and ==.
7907  if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7908    assert (RHS.get()->getType()->hasFloatingRepresentation());
7909    CheckFloatComparison(Loc, LHS.get(), RHS.get());
7910  }
7911
7912  // Return a signed type for the vector.
7913  return GetSignedVectorType(LHSType);
7914}
7915
7916QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7917                                          SourceLocation Loc) {
7918  // Ensure that either both operands are of the same vector type, or
7919  // one operand is of a vector type and the other is of its element type.
7920  QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7921  if (vType.isNull())
7922    return InvalidOperands(Loc, LHS, RHS);
7923  if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
7924      vType->hasFloatingRepresentation())
7925    return InvalidOperands(Loc, LHS, RHS);
7926
7927  return GetSignedVectorType(LHS.get()->getType());
7928}
7929
7930inline QualType Sema::CheckBitwiseOperands(
7931  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7932  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7933
7934  if (LHS.get()->getType()->isVectorType() ||
7935      RHS.get()->getType()->isVectorType()) {
7936    if (LHS.get()->getType()->hasIntegerRepresentation() &&
7937        RHS.get()->getType()->hasIntegerRepresentation())
7938      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7939
7940    return InvalidOperands(Loc, LHS, RHS);
7941  }
7942
7943  ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7944  QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7945                                                 IsCompAssign);
7946  if (LHSResult.isInvalid() || RHSResult.isInvalid())
7947    return QualType();
7948  LHS = LHSResult.take();
7949  RHS = RHSResult.take();
7950
7951  if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7952    return compType;
7953  return InvalidOperands(Loc, LHS, RHS);
7954}
7955
7956inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7957  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7958
7959  // Check vector operands differently.
7960  if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7961    return CheckVectorLogicalOperands(LHS, RHS, Loc);
7962
7963  // Diagnose cases where the user write a logical and/or but probably meant a
7964  // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7965  // is a constant.
7966  if (LHS.get()->getType()->isIntegerType() &&
7967      !LHS.get()->getType()->isBooleanType() &&
7968      RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7969      // Don't warn in macros or template instantiations.
7970      !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7971    // If the RHS can be constant folded, and if it constant folds to something
7972    // that isn't 0 or 1 (which indicate a potential logical operation that
7973    // happened to fold to true/false) then warn.
7974    // Parens on the RHS are ignored.
7975    llvm::APSInt Result;
7976    if (RHS.get()->EvaluateAsInt(Result, Context))
7977      if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7978          (Result != 0 && Result != 1)) {
7979        Diag(Loc, diag::warn_logical_instead_of_bitwise)
7980          << RHS.get()->getSourceRange()
7981          << (Opc == BO_LAnd ? "&&" : "||");
7982        // Suggest replacing the logical operator with the bitwise version
7983        Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7984            << (Opc == BO_LAnd ? "&" : "|")
7985            << FixItHint::CreateReplacement(SourceRange(
7986                Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7987                                                getLangOpts())),
7988                                            Opc == BO_LAnd ? "&" : "|");
7989        if (Opc == BO_LAnd)
7990          // Suggest replacing "Foo() && kNonZero" with "Foo()"
7991          Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7992              << FixItHint::CreateRemoval(
7993                  SourceRange(
7994                      Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7995                                                 0, getSourceManager(),
7996                                                 getLangOpts()),
7997                      RHS.get()->getLocEnd()));
7998      }
7999  }
8000
8001  if (!Context.getLangOpts().CPlusPlus) {
8002    // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8003    // not operate on the built-in scalar and vector float types.
8004    if (Context.getLangOpts().OpenCL &&
8005        Context.getLangOpts().OpenCLVersion < 120) {
8006      if (LHS.get()->getType()->isFloatingType() ||
8007          RHS.get()->getType()->isFloatingType())
8008        return InvalidOperands(Loc, LHS, RHS);
8009    }
8010
8011    LHS = UsualUnaryConversions(LHS.take());
8012    if (LHS.isInvalid())
8013      return QualType();
8014
8015    RHS = UsualUnaryConversions(RHS.take());
8016    if (RHS.isInvalid())
8017      return QualType();
8018
8019    if (!LHS.get()->getType()->isScalarType() ||
8020        !RHS.get()->getType()->isScalarType())
8021      return InvalidOperands(Loc, LHS, RHS);
8022
8023    return Context.IntTy;
8024  }
8025
8026  // The following is safe because we only use this method for
8027  // non-overloadable operands.
8028
8029  // C++ [expr.log.and]p1
8030  // C++ [expr.log.or]p1
8031  // The operands are both contextually converted to type bool.
8032  ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8033  if (LHSRes.isInvalid())
8034    return InvalidOperands(Loc, LHS, RHS);
8035  LHS = LHSRes;
8036
8037  ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8038  if (RHSRes.isInvalid())
8039    return InvalidOperands(Loc, LHS, RHS);
8040  RHS = RHSRes;
8041
8042  // C++ [expr.log.and]p2
8043  // C++ [expr.log.or]p2
8044  // The result is a bool.
8045  return Context.BoolTy;
8046}
8047
8048static bool IsReadonlyMessage(Expr *E, Sema &S) {
8049  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8050  if (!ME) return false;
8051  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8052  ObjCMessageExpr *Base =
8053    dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8054  if (!Base) return false;
8055  return Base->getMethodDecl() != 0;
8056}
8057
8058/// Is the given expression (which must be 'const') a reference to a
8059/// variable which was originally non-const, but which has become
8060/// 'const' due to being captured within a block?
8061enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8062static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8063  assert(E->isLValue() && E->getType().isConstQualified());
8064  E = E->IgnoreParens();
8065
8066  // Must be a reference to a declaration from an enclosing scope.
8067  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8068  if (!DRE) return NCCK_None;
8069  if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8070
8071  // The declaration must be a variable which is not declared 'const'.
8072  VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8073  if (!var) return NCCK_None;
8074  if (var->getType().isConstQualified()) return NCCK_None;
8075  assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8076
8077  // Decide whether the first capture was for a block or a lambda.
8078  DeclContext *DC = S.CurContext;
8079  while (DC->getParent() != var->getDeclContext())
8080    DC = DC->getParent();
8081  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8082}
8083
8084/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8085/// emit an error and return true.  If so, return false.
8086static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8087  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8088  SourceLocation OrigLoc = Loc;
8089  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8090                                                              &Loc);
8091  if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8092    IsLV = Expr::MLV_InvalidMessageExpression;
8093  if (IsLV == Expr::MLV_Valid)
8094    return false;
8095
8096  unsigned Diag = 0;
8097  bool NeedType = false;
8098  switch (IsLV) { // C99 6.5.16p2
8099  case Expr::MLV_ConstQualified:
8100    Diag = diag::err_typecheck_assign_const;
8101
8102    // Use a specialized diagnostic when we're assigning to an object
8103    // from an enclosing function or block.
8104    if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8105      if (NCCK == NCCK_Block)
8106        Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8107      else
8108        Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8109      break;
8110    }
8111
8112    // In ARC, use some specialized diagnostics for occasions where we
8113    // infer 'const'.  These are always pseudo-strong variables.
8114    if (S.getLangOpts().ObjCAutoRefCount) {
8115      DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8116      if (declRef && isa<VarDecl>(declRef->getDecl())) {
8117        VarDecl *var = cast<VarDecl>(declRef->getDecl());
8118
8119        // Use the normal diagnostic if it's pseudo-__strong but the
8120        // user actually wrote 'const'.
8121        if (var->isARCPseudoStrong() &&
8122            (!var->getTypeSourceInfo() ||
8123             !var->getTypeSourceInfo()->getType().isConstQualified())) {
8124          // There are two pseudo-strong cases:
8125          //  - self
8126          ObjCMethodDecl *method = S.getCurMethodDecl();
8127          if (method && var == method->getSelfDecl())
8128            Diag = method->isClassMethod()
8129              ? diag::err_typecheck_arc_assign_self_class_method
8130              : diag::err_typecheck_arc_assign_self;
8131
8132          //  - fast enumeration variables
8133          else
8134            Diag = diag::err_typecheck_arr_assign_enumeration;
8135
8136          SourceRange Assign;
8137          if (Loc != OrigLoc)
8138            Assign = SourceRange(OrigLoc, OrigLoc);
8139          S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8140          // We need to preserve the AST regardless, so migration tool
8141          // can do its job.
8142          return false;
8143        }
8144      }
8145    }
8146
8147    break;
8148  case Expr::MLV_ArrayType:
8149  case Expr::MLV_ArrayTemporary:
8150    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8151    NeedType = true;
8152    break;
8153  case Expr::MLV_NotObjectType:
8154    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8155    NeedType = true;
8156    break;
8157  case Expr::MLV_LValueCast:
8158    Diag = diag::err_typecheck_lvalue_casts_not_supported;
8159    break;
8160  case Expr::MLV_Valid:
8161    llvm_unreachable("did not take early return for MLV_Valid");
8162  case Expr::MLV_InvalidExpression:
8163  case Expr::MLV_MemberFunction:
8164  case Expr::MLV_ClassTemporary:
8165    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8166    break;
8167  case Expr::MLV_IncompleteType:
8168  case Expr::MLV_IncompleteVoidType:
8169    return S.RequireCompleteType(Loc, E->getType(),
8170             diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8171  case Expr::MLV_DuplicateVectorComponents:
8172    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8173    break;
8174  case Expr::MLV_NoSetterProperty:
8175    llvm_unreachable("readonly properties should be processed differently");
8176  case Expr::MLV_InvalidMessageExpression:
8177    Diag = diag::error_readonly_message_assignment;
8178    break;
8179  case Expr::MLV_SubObjCPropertySetting:
8180    Diag = diag::error_no_subobject_property_setting;
8181    break;
8182  }
8183
8184  SourceRange Assign;
8185  if (Loc != OrigLoc)
8186    Assign = SourceRange(OrigLoc, OrigLoc);
8187  if (NeedType)
8188    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8189  else
8190    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8191  return true;
8192}
8193
8194static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8195                                         SourceLocation Loc,
8196                                         Sema &Sema) {
8197  // C / C++ fields
8198  MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8199  MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8200  if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8201    if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8202      Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8203  }
8204
8205  // Objective-C instance variables
8206  ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8207  ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8208  if (OL && OR && OL->getDecl() == OR->getDecl()) {
8209    DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8210    DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8211    if (RL && RR && RL->getDecl() == RR->getDecl())
8212      Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8213  }
8214}
8215
8216// C99 6.5.16.1
8217QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8218                                       SourceLocation Loc,
8219                                       QualType CompoundType) {
8220  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8221
8222  // Verify that LHS is a modifiable lvalue, and emit error if not.
8223  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8224    return QualType();
8225
8226  QualType LHSType = LHSExpr->getType();
8227  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8228                                             CompoundType;
8229  AssignConvertType ConvTy;
8230  if (CompoundType.isNull()) {
8231    Expr *RHSCheck = RHS.get();
8232
8233    CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8234
8235    QualType LHSTy(LHSType);
8236    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8237    if (RHS.isInvalid())
8238      return QualType();
8239    // Special case of NSObject attributes on c-style pointer types.
8240    if (ConvTy == IncompatiblePointer &&
8241        ((Context.isObjCNSObjectType(LHSType) &&
8242          RHSType->isObjCObjectPointerType()) ||
8243         (Context.isObjCNSObjectType(RHSType) &&
8244          LHSType->isObjCObjectPointerType())))
8245      ConvTy = Compatible;
8246
8247    if (ConvTy == Compatible &&
8248        LHSType->isObjCObjectType())
8249        Diag(Loc, diag::err_objc_object_assignment)
8250          << LHSType;
8251
8252    // If the RHS is a unary plus or minus, check to see if they = and + are
8253    // right next to each other.  If so, the user may have typo'd "x =+ 4"
8254    // instead of "x += 4".
8255    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8256      RHSCheck = ICE->getSubExpr();
8257    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8258      if ((UO->getOpcode() == UO_Plus ||
8259           UO->getOpcode() == UO_Minus) &&
8260          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8261          // Only if the two operators are exactly adjacent.
8262          Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8263          // And there is a space or other character before the subexpr of the
8264          // unary +/-.  We don't want to warn on "x=-1".
8265          Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8266          UO->getSubExpr()->getLocStart().isFileID()) {
8267        Diag(Loc, diag::warn_not_compound_assign)
8268          << (UO->getOpcode() == UO_Plus ? "+" : "-")
8269          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8270      }
8271    }
8272
8273    if (ConvTy == Compatible) {
8274      if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8275        // Warn about retain cycles where a block captures the LHS, but
8276        // not if the LHS is a simple variable into which the block is
8277        // being stored...unless that variable can be captured by reference!
8278        const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8279        const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8280        if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8281          checkRetainCycles(LHSExpr, RHS.get());
8282
8283        // It is safe to assign a weak reference into a strong variable.
8284        // Although this code can still have problems:
8285        //   id x = self.weakProp;
8286        //   id y = self.weakProp;
8287        // we do not warn to warn spuriously when 'x' and 'y' are on separate
8288        // paths through the function. This should be revisited if
8289        // -Wrepeated-use-of-weak is made flow-sensitive.
8290        DiagnosticsEngine::Level Level =
8291          Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8292                                   RHS.get()->getLocStart());
8293        if (Level != DiagnosticsEngine::Ignored)
8294          getCurFunction()->markSafeWeakUse(RHS.get());
8295
8296      } else if (getLangOpts().ObjCAutoRefCount) {
8297        checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8298      }
8299    }
8300  } else {
8301    // Compound assignment "x += y"
8302    ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8303  }
8304
8305  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8306                               RHS.get(), AA_Assigning))
8307    return QualType();
8308
8309  CheckForNullPointerDereference(*this, LHSExpr);
8310
8311  // C99 6.5.16p3: The type of an assignment expression is the type of the
8312  // left operand unless the left operand has qualified type, in which case
8313  // it is the unqualified version of the type of the left operand.
8314  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8315  // is converted to the type of the assignment expression (above).
8316  // C++ 5.17p1: the type of the assignment expression is that of its left
8317  // operand.
8318  return (getLangOpts().CPlusPlus
8319          ? LHSType : LHSType.getUnqualifiedType());
8320}
8321
8322// C99 6.5.17
8323static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8324                                   SourceLocation Loc) {
8325  LHS = S.CheckPlaceholderExpr(LHS.take());
8326  RHS = S.CheckPlaceholderExpr(RHS.take());
8327  if (LHS.isInvalid() || RHS.isInvalid())
8328    return QualType();
8329
8330  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8331  // operands, but not unary promotions.
8332  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8333
8334  // So we treat the LHS as a ignored value, and in C++ we allow the
8335  // containing site to determine what should be done with the RHS.
8336  LHS = S.IgnoredValueConversions(LHS.take());
8337  if (LHS.isInvalid())
8338    return QualType();
8339
8340  S.DiagnoseUnusedExprResult(LHS.get());
8341
8342  if (!S.getLangOpts().CPlusPlus) {
8343    RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8344    if (RHS.isInvalid())
8345      return QualType();
8346    if (!RHS.get()->getType()->isVoidType())
8347      S.RequireCompleteType(Loc, RHS.get()->getType(),
8348                            diag::err_incomplete_type);
8349  }
8350
8351  return RHS.get()->getType();
8352}
8353
8354/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8355/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8356static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8357                                               ExprValueKind &VK,
8358                                               SourceLocation OpLoc,
8359                                               bool IsInc, bool IsPrefix) {
8360  if (Op->isTypeDependent())
8361    return S.Context.DependentTy;
8362
8363  QualType ResType = Op->getType();
8364  // Atomic types can be used for increment / decrement where the non-atomic
8365  // versions can, so ignore the _Atomic() specifier for the purpose of
8366  // checking.
8367  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8368    ResType = ResAtomicType->getValueType();
8369
8370  assert(!ResType.isNull() && "no type for increment/decrement expression");
8371
8372  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8373    // Decrement of bool is not allowed.
8374    if (!IsInc) {
8375      S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8376      return QualType();
8377    }
8378    // Increment of bool sets it to true, but is deprecated.
8379    S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8380  } else if (ResType->isRealType()) {
8381    // OK!
8382  } else if (ResType->isPointerType()) {
8383    // C99 6.5.2.4p2, 6.5.6p2
8384    if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8385      return QualType();
8386  } else if (ResType->isObjCObjectPointerType()) {
8387    // On modern runtimes, ObjC pointer arithmetic is forbidden.
8388    // Otherwise, we just need a complete type.
8389    if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8390        checkArithmeticOnObjCPointer(S, OpLoc, Op))
8391      return QualType();
8392  } else if (ResType->isAnyComplexType()) {
8393    // C99 does not support ++/-- on complex types, we allow as an extension.
8394    S.Diag(OpLoc, diag::ext_integer_increment_complex)
8395      << ResType << Op->getSourceRange();
8396  } else if (ResType->isPlaceholderType()) {
8397    ExprResult PR = S.CheckPlaceholderExpr(Op);
8398    if (PR.isInvalid()) return QualType();
8399    return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8400                                          IsInc, IsPrefix);
8401  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8402    // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8403  } else {
8404    S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8405      << ResType << int(IsInc) << Op->getSourceRange();
8406    return QualType();
8407  }
8408  // At this point, we know we have a real, complex or pointer type.
8409  // Now make sure the operand is a modifiable lvalue.
8410  if (CheckForModifiableLvalue(Op, OpLoc, S))
8411    return QualType();
8412  // In C++, a prefix increment is the same type as the operand. Otherwise
8413  // (in C or with postfix), the increment is the unqualified type of the
8414  // operand.
8415  if (IsPrefix && S.getLangOpts().CPlusPlus) {
8416    VK = VK_LValue;
8417    return ResType;
8418  } else {
8419    VK = VK_RValue;
8420    return ResType.getUnqualifiedType();
8421  }
8422}
8423
8424
8425/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8426/// This routine allows us to typecheck complex/recursive expressions
8427/// where the declaration is needed for type checking. We only need to
8428/// handle cases when the expression references a function designator
8429/// or is an lvalue. Here are some examples:
8430///  - &(x) => x
8431///  - &*****f => f for f a function designator.
8432///  - &s.xx => s
8433///  - &s.zz[1].yy -> s, if zz is an array
8434///  - *(x + 1) -> x, if x is an array
8435///  - &"123"[2] -> 0
8436///  - & __real__ x -> x
8437static ValueDecl *getPrimaryDecl(Expr *E) {
8438  switch (E->getStmtClass()) {
8439  case Stmt::DeclRefExprClass:
8440    return cast<DeclRefExpr>(E)->getDecl();
8441  case Stmt::MemberExprClass:
8442    // If this is an arrow operator, the address is an offset from
8443    // the base's value, so the object the base refers to is
8444    // irrelevant.
8445    if (cast<MemberExpr>(E)->isArrow())
8446      return 0;
8447    // Otherwise, the expression refers to a part of the base
8448    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8449  case Stmt::ArraySubscriptExprClass: {
8450    // FIXME: This code shouldn't be necessary!  We should catch the implicit
8451    // promotion of register arrays earlier.
8452    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8453    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8454      if (ICE->getSubExpr()->getType()->isArrayType())
8455        return getPrimaryDecl(ICE->getSubExpr());
8456    }
8457    return 0;
8458  }
8459  case Stmt::UnaryOperatorClass: {
8460    UnaryOperator *UO = cast<UnaryOperator>(E);
8461
8462    switch(UO->getOpcode()) {
8463    case UO_Real:
8464    case UO_Imag:
8465    case UO_Extension:
8466      return getPrimaryDecl(UO->getSubExpr());
8467    default:
8468      return 0;
8469    }
8470  }
8471  case Stmt::ParenExprClass:
8472    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8473  case Stmt::ImplicitCastExprClass:
8474    // If the result of an implicit cast is an l-value, we care about
8475    // the sub-expression; otherwise, the result here doesn't matter.
8476    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8477  default:
8478    return 0;
8479  }
8480}
8481
8482namespace {
8483  enum {
8484    AO_Bit_Field = 0,
8485    AO_Vector_Element = 1,
8486    AO_Property_Expansion = 2,
8487    AO_Register_Variable = 3,
8488    AO_No_Error = 4
8489  };
8490}
8491/// \brief Diagnose invalid operand for address of operations.
8492///
8493/// \param Type The type of operand which cannot have its address taken.
8494static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8495                                         Expr *E, unsigned Type) {
8496  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8497}
8498
8499/// CheckAddressOfOperand - The operand of & must be either a function
8500/// designator or an lvalue designating an object. If it is an lvalue, the
8501/// object cannot be declared with storage class register or be a bit field.
8502/// Note: The usual conversions are *not* applied to the operand of the &
8503/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8504/// In C++, the operand might be an overloaded function name, in which case
8505/// we allow the '&' but retain the overloaded-function type.
8506QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8507  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8508    if (PTy->getKind() == BuiltinType::Overload) {
8509      Expr *E = OrigOp.get()->IgnoreParens();
8510      if (!isa<OverloadExpr>(E)) {
8511        assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8512        Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8513          << OrigOp.get()->getSourceRange();
8514        return QualType();
8515      }
8516
8517      OverloadExpr *Ovl = cast<OverloadExpr>(E);
8518      if (isa<UnresolvedMemberExpr>(Ovl))
8519        if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8520          Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8521            << OrigOp.get()->getSourceRange();
8522          return QualType();
8523        }
8524
8525      return Context.OverloadTy;
8526    }
8527
8528    if (PTy->getKind() == BuiltinType::UnknownAny)
8529      return Context.UnknownAnyTy;
8530
8531    if (PTy->getKind() == BuiltinType::BoundMember) {
8532      Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8533        << OrigOp.get()->getSourceRange();
8534      return QualType();
8535    }
8536
8537    OrigOp = CheckPlaceholderExpr(OrigOp.take());
8538    if (OrigOp.isInvalid()) return QualType();
8539  }
8540
8541  if (OrigOp.get()->isTypeDependent())
8542    return Context.DependentTy;
8543
8544  assert(!OrigOp.get()->getType()->isPlaceholderType());
8545
8546  // Make sure to ignore parentheses in subsequent checks
8547  Expr *op = OrigOp.get()->IgnoreParens();
8548
8549  if (getLangOpts().C99) {
8550    // Implement C99-only parts of addressof rules.
8551    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8552      if (uOp->getOpcode() == UO_Deref)
8553        // Per C99 6.5.3.2, the address of a deref always returns a valid result
8554        // (assuming the deref expression is valid).
8555        return uOp->getSubExpr()->getType();
8556    }
8557    // Technically, there should be a check for array subscript
8558    // expressions here, but the result of one is always an lvalue anyway.
8559  }
8560  ValueDecl *dcl = getPrimaryDecl(op);
8561  Expr::LValueClassification lval = op->ClassifyLValue(Context);
8562  unsigned AddressOfError = AO_No_Error;
8563
8564  if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8565    bool sfinae = (bool)isSFINAEContext();
8566    Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8567                                  : diag::ext_typecheck_addrof_temporary)
8568      << op->getType() << op->getSourceRange();
8569    if (sfinae)
8570      return QualType();
8571    // Materialize the temporary as an lvalue so that we can take its address.
8572    OrigOp = op = new (Context)
8573        MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
8574  } else if (isa<ObjCSelectorExpr>(op)) {
8575    return Context.getPointerType(op->getType());
8576  } else if (lval == Expr::LV_MemberFunction) {
8577    // If it's an instance method, make a member pointer.
8578    // The expression must have exactly the form &A::foo.
8579
8580    // If the underlying expression isn't a decl ref, give up.
8581    if (!isa<DeclRefExpr>(op)) {
8582      Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8583        << OrigOp.get()->getSourceRange();
8584      return QualType();
8585    }
8586    DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8587    CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8588
8589    // The id-expression was parenthesized.
8590    if (OrigOp.get() != DRE) {
8591      Diag(OpLoc, diag::err_parens_pointer_member_function)
8592        << OrigOp.get()->getSourceRange();
8593
8594    // The method was named without a qualifier.
8595    } else if (!DRE->getQualifier()) {
8596      if (MD->getParent()->getName().empty())
8597        Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8598          << op->getSourceRange();
8599      else {
8600        SmallString<32> Str;
8601        StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8602        Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8603          << op->getSourceRange()
8604          << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8605      }
8606    }
8607
8608    return Context.getMemberPointerType(op->getType(),
8609              Context.getTypeDeclType(MD->getParent()).getTypePtr());
8610  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8611    // C99 6.5.3.2p1
8612    // The operand must be either an l-value or a function designator
8613    if (!op->getType()->isFunctionType()) {
8614      // Use a special diagnostic for loads from property references.
8615      if (isa<PseudoObjectExpr>(op)) {
8616        AddressOfError = AO_Property_Expansion;
8617      } else {
8618        Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8619          << op->getType() << op->getSourceRange();
8620        return QualType();
8621      }
8622    }
8623  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8624    // The operand cannot be a bit-field
8625    AddressOfError = AO_Bit_Field;
8626  } else if (op->getObjectKind() == OK_VectorComponent) {
8627    // The operand cannot be an element of a vector
8628    AddressOfError = AO_Vector_Element;
8629  } else if (dcl) { // C99 6.5.3.2p1
8630    // We have an lvalue with a decl. Make sure the decl is not declared
8631    // with the register storage-class specifier.
8632    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8633      // in C++ it is not error to take address of a register
8634      // variable (c++03 7.1.1P3)
8635      if (vd->getStorageClass() == SC_Register &&
8636          !getLangOpts().CPlusPlus) {
8637        AddressOfError = AO_Register_Variable;
8638      }
8639    } else if (isa<FunctionTemplateDecl>(dcl)) {
8640      return Context.OverloadTy;
8641    } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8642      // Okay: we can take the address of a field.
8643      // Could be a pointer to member, though, if there is an explicit
8644      // scope qualifier for the class.
8645      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8646        DeclContext *Ctx = dcl->getDeclContext();
8647        if (Ctx && Ctx->isRecord()) {
8648          if (dcl->getType()->isReferenceType()) {
8649            Diag(OpLoc,
8650                 diag::err_cannot_form_pointer_to_member_of_reference_type)
8651              << dcl->getDeclName() << dcl->getType();
8652            return QualType();
8653          }
8654
8655          while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8656            Ctx = Ctx->getParent();
8657          return Context.getMemberPointerType(op->getType(),
8658                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8659        }
8660      }
8661    } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8662      llvm_unreachable("Unknown/unexpected decl type");
8663  }
8664
8665  if (AddressOfError != AO_No_Error) {
8666    diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
8667    return QualType();
8668  }
8669
8670  if (lval == Expr::LV_IncompleteVoidType) {
8671    // Taking the address of a void variable is technically illegal, but we
8672    // allow it in cases which are otherwise valid.
8673    // Example: "extern void x; void* y = &x;".
8674    Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8675  }
8676
8677  // If the operand has type "type", the result has type "pointer to type".
8678  if (op->getType()->isObjCObjectType())
8679    return Context.getObjCObjectPointerType(op->getType());
8680  return Context.getPointerType(op->getType());
8681}
8682
8683/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8684static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8685                                        SourceLocation OpLoc) {
8686  if (Op->isTypeDependent())
8687    return S.Context.DependentTy;
8688
8689  ExprResult ConvResult = S.UsualUnaryConversions(Op);
8690  if (ConvResult.isInvalid())
8691    return QualType();
8692  Op = ConvResult.take();
8693  QualType OpTy = Op->getType();
8694  QualType Result;
8695
8696  if (isa<CXXReinterpretCastExpr>(Op)) {
8697    QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8698    S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8699                                     Op->getSourceRange());
8700  }
8701
8702  // Note that per both C89 and C99, indirection is always legal, even if OpTy
8703  // is an incomplete type or void.  It would be possible to warn about
8704  // dereferencing a void pointer, but it's completely well-defined, and such a
8705  // warning is unlikely to catch any mistakes.
8706  if (const PointerType *PT = OpTy->getAs<PointerType>())
8707    Result = PT->getPointeeType();
8708  else if (const ObjCObjectPointerType *OPT =
8709             OpTy->getAs<ObjCObjectPointerType>())
8710    Result = OPT->getPointeeType();
8711  else {
8712    ExprResult PR = S.CheckPlaceholderExpr(Op);
8713    if (PR.isInvalid()) return QualType();
8714    if (PR.take() != Op)
8715      return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8716  }
8717
8718  if (Result.isNull()) {
8719    S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8720      << OpTy << Op->getSourceRange();
8721    return QualType();
8722  }
8723
8724  // Dereferences are usually l-values...
8725  VK = VK_LValue;
8726
8727  // ...except that certain expressions are never l-values in C.
8728  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8729    VK = VK_RValue;
8730
8731  return Result;
8732}
8733
8734static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8735  tok::TokenKind Kind) {
8736  BinaryOperatorKind Opc;
8737  switch (Kind) {
8738  default: llvm_unreachable("Unknown binop!");
8739  case tok::periodstar:           Opc = BO_PtrMemD; break;
8740  case tok::arrowstar:            Opc = BO_PtrMemI; break;
8741  case tok::star:                 Opc = BO_Mul; break;
8742  case tok::slash:                Opc = BO_Div; break;
8743  case tok::percent:              Opc = BO_Rem; break;
8744  case tok::plus:                 Opc = BO_Add; break;
8745  case tok::minus:                Opc = BO_Sub; break;
8746  case tok::lessless:             Opc = BO_Shl; break;
8747  case tok::greatergreater:       Opc = BO_Shr; break;
8748  case tok::lessequal:            Opc = BO_LE; break;
8749  case tok::less:                 Opc = BO_LT; break;
8750  case tok::greaterequal:         Opc = BO_GE; break;
8751  case tok::greater:              Opc = BO_GT; break;
8752  case tok::exclaimequal:         Opc = BO_NE; break;
8753  case tok::equalequal:           Opc = BO_EQ; break;
8754  case tok::amp:                  Opc = BO_And; break;
8755  case tok::caret:                Opc = BO_Xor; break;
8756  case tok::pipe:                 Opc = BO_Or; break;
8757  case tok::ampamp:               Opc = BO_LAnd; break;
8758  case tok::pipepipe:             Opc = BO_LOr; break;
8759  case tok::equal:                Opc = BO_Assign; break;
8760  case tok::starequal:            Opc = BO_MulAssign; break;
8761  case tok::slashequal:           Opc = BO_DivAssign; break;
8762  case tok::percentequal:         Opc = BO_RemAssign; break;
8763  case tok::plusequal:            Opc = BO_AddAssign; break;
8764  case tok::minusequal:           Opc = BO_SubAssign; break;
8765  case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8766  case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8767  case tok::ampequal:             Opc = BO_AndAssign; break;
8768  case tok::caretequal:           Opc = BO_XorAssign; break;
8769  case tok::pipeequal:            Opc = BO_OrAssign; break;
8770  case tok::comma:                Opc = BO_Comma; break;
8771  }
8772  return Opc;
8773}
8774
8775static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8776  tok::TokenKind Kind) {
8777  UnaryOperatorKind Opc;
8778  switch (Kind) {
8779  default: llvm_unreachable("Unknown unary op!");
8780  case tok::plusplus:     Opc = UO_PreInc; break;
8781  case tok::minusminus:   Opc = UO_PreDec; break;
8782  case tok::amp:          Opc = UO_AddrOf; break;
8783  case tok::star:         Opc = UO_Deref; break;
8784  case tok::plus:         Opc = UO_Plus; break;
8785  case tok::minus:        Opc = UO_Minus; break;
8786  case tok::tilde:        Opc = UO_Not; break;
8787  case tok::exclaim:      Opc = UO_LNot; break;
8788  case tok::kw___real:    Opc = UO_Real; break;
8789  case tok::kw___imag:    Opc = UO_Imag; break;
8790  case tok::kw___extension__: Opc = UO_Extension; break;
8791  }
8792  return Opc;
8793}
8794
8795/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8796/// This warning is only emitted for builtin assignment operations. It is also
8797/// suppressed in the event of macro expansions.
8798static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8799                                   SourceLocation OpLoc) {
8800  if (!S.ActiveTemplateInstantiations.empty())
8801    return;
8802  if (OpLoc.isInvalid() || OpLoc.isMacroID())
8803    return;
8804  LHSExpr = LHSExpr->IgnoreParenImpCasts();
8805  RHSExpr = RHSExpr->IgnoreParenImpCasts();
8806  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8807  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8808  if (!LHSDeclRef || !RHSDeclRef ||
8809      LHSDeclRef->getLocation().isMacroID() ||
8810      RHSDeclRef->getLocation().isMacroID())
8811    return;
8812  const ValueDecl *LHSDecl =
8813    cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8814  const ValueDecl *RHSDecl =
8815    cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8816  if (LHSDecl != RHSDecl)
8817    return;
8818  if (LHSDecl->getType().isVolatileQualified())
8819    return;
8820  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8821    if (RefTy->getPointeeType().isVolatileQualified())
8822      return;
8823
8824  S.Diag(OpLoc, diag::warn_self_assignment)
8825      << LHSDeclRef->getType()
8826      << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8827}
8828
8829/// Check if a bitwise-& is performed on an Objective-C pointer.  This
8830/// is usually indicative of introspection within the Objective-C pointer.
8831static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
8832                                          SourceLocation OpLoc) {
8833  if (!S.getLangOpts().ObjC1)
8834    return;
8835
8836  const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
8837  const Expr *LHS = L.get();
8838  const Expr *RHS = R.get();
8839
8840  if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8841    ObjCPointerExpr = LHS;
8842    OtherExpr = RHS;
8843  }
8844  else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8845    ObjCPointerExpr = RHS;
8846    OtherExpr = LHS;
8847  }
8848
8849  // This warning is deliberately made very specific to reduce false
8850  // positives with logic that uses '&' for hashing.  This logic mainly
8851  // looks for code trying to introspect into tagged pointers, which
8852  // code should generally never do.
8853  if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
8854    unsigned Diag = diag::warn_objc_pointer_masking;
8855    // Determine if we are introspecting the result of performSelectorXXX.
8856    const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
8857    // Special case messages to -performSelector and friends, which
8858    // can return non-pointer values boxed in a pointer value.
8859    // Some clients may wish to silence warnings in this subcase.
8860    if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
8861      Selector S = ME->getSelector();
8862      StringRef SelArg0 = S.getNameForSlot(0);
8863      if (SelArg0.startswith("performSelector"))
8864        Diag = diag::warn_objc_pointer_masking_performSelector;
8865    }
8866
8867    S.Diag(OpLoc, Diag)
8868      << ObjCPointerExpr->getSourceRange();
8869  }
8870}
8871
8872/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8873/// operator @p Opc at location @c TokLoc. This routine only supports
8874/// built-in operations; ActOnBinOp handles overloaded operators.
8875ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8876                                    BinaryOperatorKind Opc,
8877                                    Expr *LHSExpr, Expr *RHSExpr) {
8878  if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
8879    // The syntax only allows initializer lists on the RHS of assignment,
8880    // so we don't need to worry about accepting invalid code for
8881    // non-assignment operators.
8882    // C++11 5.17p9:
8883    //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8884    //   of x = {} is x = T().
8885    InitializationKind Kind =
8886        InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8887    InitializedEntity Entity =
8888        InitializedEntity::InitializeTemporary(LHSExpr->getType());
8889    InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
8890    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8891    if (Init.isInvalid())
8892      return Init;
8893    RHSExpr = Init.take();
8894  }
8895
8896  ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8897  QualType ResultTy;     // Result type of the binary operator.
8898  // The following two variables are used for compound assignment operators
8899  QualType CompLHSTy;    // Type of LHS after promotions for computation
8900  QualType CompResultTy; // Type of computation result
8901  ExprValueKind VK = VK_RValue;
8902  ExprObjectKind OK = OK_Ordinary;
8903
8904  switch (Opc) {
8905  case BO_Assign:
8906    ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8907    if (getLangOpts().CPlusPlus &&
8908        LHS.get()->getObjectKind() != OK_ObjCProperty) {
8909      VK = LHS.get()->getValueKind();
8910      OK = LHS.get()->getObjectKind();
8911    }
8912    if (!ResultTy.isNull())
8913      DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8914    break;
8915  case BO_PtrMemD:
8916  case BO_PtrMemI:
8917    ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8918                                            Opc == BO_PtrMemI);
8919    break;
8920  case BO_Mul:
8921  case BO_Div:
8922    ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8923                                           Opc == BO_Div);
8924    break;
8925  case BO_Rem:
8926    ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8927    break;
8928  case BO_Add:
8929    ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8930    break;
8931  case BO_Sub:
8932    ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8933    break;
8934  case BO_Shl:
8935  case BO_Shr:
8936    ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8937    break;
8938  case BO_LE:
8939  case BO_LT:
8940  case BO_GE:
8941  case BO_GT:
8942    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8943    break;
8944  case BO_EQ:
8945  case BO_NE:
8946    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8947    break;
8948  case BO_And:
8949    checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
8950  case BO_Xor:
8951  case BO_Or:
8952    ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8953    break;
8954  case BO_LAnd:
8955  case BO_LOr:
8956    ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8957    break;
8958  case BO_MulAssign:
8959  case BO_DivAssign:
8960    CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8961                                               Opc == BO_DivAssign);
8962    CompLHSTy = CompResultTy;
8963    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8964      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8965    break;
8966  case BO_RemAssign:
8967    CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8968    CompLHSTy = CompResultTy;
8969    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8970      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8971    break;
8972  case BO_AddAssign:
8973    CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8974    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8975      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8976    break;
8977  case BO_SubAssign:
8978    CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8979    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8980      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8981    break;
8982  case BO_ShlAssign:
8983  case BO_ShrAssign:
8984    CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8985    CompLHSTy = CompResultTy;
8986    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8987      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8988    break;
8989  case BO_AndAssign:
8990  case BO_XorAssign:
8991  case BO_OrAssign:
8992    CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8993    CompLHSTy = CompResultTy;
8994    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8995      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8996    break;
8997  case BO_Comma:
8998    ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8999    if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9000      VK = RHS.get()->getValueKind();
9001      OK = RHS.get()->getObjectKind();
9002    }
9003    break;
9004  }
9005  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9006    return ExprError();
9007
9008  // Check for array bounds violations for both sides of the BinaryOperator
9009  CheckArrayAccess(LHS.get());
9010  CheckArrayAccess(RHS.get());
9011
9012  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9013    NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9014                                                 &Context.Idents.get("object_setClass"),
9015                                                 SourceLocation(), LookupOrdinaryName);
9016    if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9017      SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9018      Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9019      FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9020      FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9021      FixItHint::CreateInsertion(RHSLocEnd, ")");
9022    }
9023    else
9024      Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9025  }
9026  else if (const ObjCIvarRefExpr *OIRE =
9027           dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9028    DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9029
9030  if (CompResultTy.isNull())
9031    return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
9032                                              ResultTy, VK, OK, OpLoc,
9033                                              FPFeatures.fp_contract));
9034  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9035      OK_ObjCProperty) {
9036    VK = VK_LValue;
9037    OK = LHS.get()->getObjectKind();
9038  }
9039  return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
9040                                                    ResultTy, VK, OK, CompLHSTy,
9041                                                    CompResultTy, OpLoc,
9042                                                    FPFeatures.fp_contract));
9043}
9044
9045/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9046/// operators are mixed in a way that suggests that the programmer forgot that
9047/// comparison operators have higher precedence. The most typical example of
9048/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9049static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9050                                      SourceLocation OpLoc, Expr *LHSExpr,
9051                                      Expr *RHSExpr) {
9052  BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9053  BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9054
9055  // Check that one of the sides is a comparison operator.
9056  bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9057  bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9058  if (!isLeftComp && !isRightComp)
9059    return;
9060
9061  // Bitwise operations are sometimes used as eager logical ops.
9062  // Don't diagnose this.
9063  bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9064  bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9065  if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9066    return;
9067
9068  SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9069                                                   OpLoc)
9070                                     : SourceRange(OpLoc, RHSExpr->getLocEnd());
9071  StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9072  SourceRange ParensRange = isLeftComp ?
9073      SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9074    : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9075
9076  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9077    << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9078  SuggestParentheses(Self, OpLoc,
9079    Self.PDiag(diag::note_precedence_silence) << OpStr,
9080    (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9081  SuggestParentheses(Self, OpLoc,
9082    Self.PDiag(diag::note_precedence_bitwise_first)
9083      << BinaryOperator::getOpcodeStr(Opc),
9084    ParensRange);
9085}
9086
9087/// \brief It accepts a '&' expr that is inside a '|' one.
9088/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9089/// in parentheses.
9090static void
9091EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9092                                       BinaryOperator *Bop) {
9093  assert(Bop->getOpcode() == BO_And);
9094  Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9095      << Bop->getSourceRange() << OpLoc;
9096  SuggestParentheses(Self, Bop->getOperatorLoc(),
9097    Self.PDiag(diag::note_precedence_silence)
9098      << Bop->getOpcodeStr(),
9099    Bop->getSourceRange());
9100}
9101
9102/// \brief It accepts a '&&' expr that is inside a '||' one.
9103/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9104/// in parentheses.
9105static void
9106EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9107                                       BinaryOperator *Bop) {
9108  assert(Bop->getOpcode() == BO_LAnd);
9109  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9110      << Bop->getSourceRange() << OpLoc;
9111  SuggestParentheses(Self, Bop->getOperatorLoc(),
9112    Self.PDiag(diag::note_precedence_silence)
9113      << Bop->getOpcodeStr(),
9114    Bop->getSourceRange());
9115}
9116
9117/// \brief Returns true if the given expression can be evaluated as a constant
9118/// 'true'.
9119static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9120  bool Res;
9121  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9122}
9123
9124/// \brief Returns true if the given expression can be evaluated as a constant
9125/// 'false'.
9126static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9127  bool Res;
9128  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9129}
9130
9131/// \brief Look for '&&' in the left hand of a '||' expr.
9132static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9133                                             Expr *LHSExpr, Expr *RHSExpr) {
9134  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9135    if (Bop->getOpcode() == BO_LAnd) {
9136      // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9137      if (EvaluatesAsFalse(S, RHSExpr))
9138        return;
9139      // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9140      if (!EvaluatesAsTrue(S, Bop->getLHS()))
9141        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9142    } else if (Bop->getOpcode() == BO_LOr) {
9143      if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9144        // If it's "a || b && 1 || c" we didn't warn earlier for
9145        // "a || b && 1", but warn now.
9146        if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9147          return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9148      }
9149    }
9150  }
9151}
9152
9153/// \brief Look for '&&' in the right hand of a '||' expr.
9154static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9155                                             Expr *LHSExpr, Expr *RHSExpr) {
9156  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9157    if (Bop->getOpcode() == BO_LAnd) {
9158      // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9159      if (EvaluatesAsFalse(S, LHSExpr))
9160        return;
9161      // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9162      if (!EvaluatesAsTrue(S, Bop->getRHS()))
9163        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9164    }
9165  }
9166}
9167
9168/// \brief Look for '&' in the left or right hand of a '|' expr.
9169static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9170                                             Expr *OrArg) {
9171  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9172    if (Bop->getOpcode() == BO_And)
9173      return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9174  }
9175}
9176
9177static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9178                                    Expr *SubExpr, StringRef Shift) {
9179  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9180    if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9181      StringRef Op = Bop->getOpcodeStr();
9182      S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9183          << Bop->getSourceRange() << OpLoc << Shift << Op;
9184      SuggestParentheses(S, Bop->getOperatorLoc(),
9185          S.PDiag(diag::note_precedence_silence) << Op,
9186          Bop->getSourceRange());
9187    }
9188  }
9189}
9190
9191static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9192                                 Expr *LHSExpr, Expr *RHSExpr) {
9193  CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9194  if (!OCE)
9195    return;
9196
9197  FunctionDecl *FD = OCE->getDirectCallee();
9198  if (!FD || !FD->isOverloadedOperator())
9199    return;
9200
9201  OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9202  if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9203    return;
9204
9205  S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9206      << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9207      << (Kind == OO_LessLess);
9208  SuggestParentheses(S, OCE->getOperatorLoc(),
9209                     S.PDiag(diag::note_precedence_silence)
9210                         << (Kind == OO_LessLess ? "<<" : ">>"),
9211                     OCE->getSourceRange());
9212  SuggestParentheses(S, OpLoc,
9213                     S.PDiag(diag::note_evaluate_comparison_first),
9214                     SourceRange(OCE->getArg(1)->getLocStart(),
9215                                 RHSExpr->getLocEnd()));
9216}
9217
9218/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9219/// precedence.
9220static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9221                                    SourceLocation OpLoc, Expr *LHSExpr,
9222                                    Expr *RHSExpr){
9223  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9224  if (BinaryOperator::isBitwiseOp(Opc))
9225    DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9226
9227  // Diagnose "arg1 & arg2 | arg3"
9228  if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9229    DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9230    DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9231  }
9232
9233  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9234  // We don't warn for 'assert(a || b && "bad")' since this is safe.
9235  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9236    DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9237    DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9238  }
9239
9240  if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9241      || Opc == BO_Shr) {
9242    StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9243    DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9244    DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9245  }
9246
9247  // Warn on overloaded shift operators and comparisons, such as:
9248  // cout << 5 == 4;
9249  if (BinaryOperator::isComparisonOp(Opc))
9250    DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9251}
9252
9253// Binary Operators.  'Tok' is the token for the operator.
9254ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9255                            tok::TokenKind Kind,
9256                            Expr *LHSExpr, Expr *RHSExpr) {
9257  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9258  assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9259  assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
9260
9261  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9262  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9263
9264  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9265}
9266
9267/// Build an overloaded binary operator expression in the given scope.
9268static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9269                                       BinaryOperatorKind Opc,
9270                                       Expr *LHS, Expr *RHS) {
9271  // Find all of the overloaded operators visible from this
9272  // point. We perform both an operator-name lookup from the local
9273  // scope and an argument-dependent lookup based on the types of
9274  // the arguments.
9275  UnresolvedSet<16> Functions;
9276  OverloadedOperatorKind OverOp
9277    = BinaryOperator::getOverloadedOperator(Opc);
9278  if (Sc && OverOp != OO_None)
9279    S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9280                                   RHS->getType(), Functions);
9281
9282  // Build the (potentially-overloaded, potentially-dependent)
9283  // binary operation.
9284  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9285}
9286
9287ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9288                            BinaryOperatorKind Opc,
9289                            Expr *LHSExpr, Expr *RHSExpr) {
9290  // We want to end up calling one of checkPseudoObjectAssignment
9291  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9292  // both expressions are overloadable or either is type-dependent),
9293  // or CreateBuiltinBinOp (in any other case).  We also want to get
9294  // any placeholder types out of the way.
9295
9296  // Handle pseudo-objects in the LHS.
9297  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9298    // Assignments with a pseudo-object l-value need special analysis.
9299    if (pty->getKind() == BuiltinType::PseudoObject &&
9300        BinaryOperator::isAssignmentOp(Opc))
9301      return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9302
9303    // Don't resolve overloads if the other type is overloadable.
9304    if (pty->getKind() == BuiltinType::Overload) {
9305      // We can't actually test that if we still have a placeholder,
9306      // though.  Fortunately, none of the exceptions we see in that
9307      // code below are valid when the LHS is an overload set.  Note
9308      // that an overload set can be dependently-typed, but it never
9309      // instantiates to having an overloadable type.
9310      ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9311      if (resolvedRHS.isInvalid()) return ExprError();
9312      RHSExpr = resolvedRHS.take();
9313
9314      if (RHSExpr->isTypeDependent() ||
9315          RHSExpr->getType()->isOverloadableType())
9316        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9317    }
9318
9319    ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9320    if (LHS.isInvalid()) return ExprError();
9321    LHSExpr = LHS.take();
9322  }
9323
9324  // Handle pseudo-objects in the RHS.
9325  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9326    // An overload in the RHS can potentially be resolved by the type
9327    // being assigned to.
9328    if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9329      if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9330        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9331
9332      if (LHSExpr->getType()->isOverloadableType())
9333        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9334
9335      return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9336    }
9337
9338    // Don't resolve overloads if the other type is overloadable.
9339    if (pty->getKind() == BuiltinType::Overload &&
9340        LHSExpr->getType()->isOverloadableType())
9341      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9342
9343    ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9344    if (!resolvedRHS.isUsable()) return ExprError();
9345    RHSExpr = resolvedRHS.take();
9346  }
9347
9348  if (getLangOpts().CPlusPlus) {
9349    // If either expression is type-dependent, always build an
9350    // overloaded op.
9351    if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9352      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9353
9354    // Otherwise, build an overloaded op if either expression has an
9355    // overloadable type.
9356    if (LHSExpr->getType()->isOverloadableType() ||
9357        RHSExpr->getType()->isOverloadableType())
9358      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9359  }
9360
9361  // Build a built-in binary operation.
9362  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9363}
9364
9365ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9366                                      UnaryOperatorKind Opc,
9367                                      Expr *InputExpr) {
9368  ExprResult Input = Owned(InputExpr);
9369  ExprValueKind VK = VK_RValue;
9370  ExprObjectKind OK = OK_Ordinary;
9371  QualType resultType;
9372  switch (Opc) {
9373  case UO_PreInc:
9374  case UO_PreDec:
9375  case UO_PostInc:
9376  case UO_PostDec:
9377    resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9378                                                Opc == UO_PreInc ||
9379                                                Opc == UO_PostInc,
9380                                                Opc == UO_PreInc ||
9381                                                Opc == UO_PreDec);
9382    break;
9383  case UO_AddrOf:
9384    resultType = CheckAddressOfOperand(Input, OpLoc);
9385    break;
9386  case UO_Deref: {
9387    Input = DefaultFunctionArrayLvalueConversion(Input.take());
9388    if (Input.isInvalid()) return ExprError();
9389    resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9390    break;
9391  }
9392  case UO_Plus:
9393  case UO_Minus:
9394    Input = UsualUnaryConversions(Input.take());
9395    if (Input.isInvalid()) return ExprError();
9396    resultType = Input.get()->getType();
9397    if (resultType->isDependentType())
9398      break;
9399    if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9400        resultType->isVectorType())
9401      break;
9402    else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
9403             resultType->isEnumeralType())
9404      break;
9405    else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9406             Opc == UO_Plus &&
9407             resultType->isPointerType())
9408      break;
9409
9410    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9411      << resultType << Input.get()->getSourceRange());
9412
9413  case UO_Not: // bitwise complement
9414    Input = UsualUnaryConversions(Input.take());
9415    if (Input.isInvalid())
9416      return ExprError();
9417    resultType = Input.get()->getType();
9418    if (resultType->isDependentType())
9419      break;
9420    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9421    if (resultType->isComplexType() || resultType->isComplexIntegerType())
9422      // C99 does not support '~' for complex conjugation.
9423      Diag(OpLoc, diag::ext_integer_complement_complex)
9424          << resultType << Input.get()->getSourceRange();
9425    else if (resultType->hasIntegerRepresentation())
9426      break;
9427    else if (resultType->isExtVectorType()) {
9428      if (Context.getLangOpts().OpenCL) {
9429        // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9430        // on vector float types.
9431        QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9432        if (!T->isIntegerType())
9433          return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9434                           << resultType << Input.get()->getSourceRange());
9435      }
9436      break;
9437    } else {
9438      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9439                       << resultType << Input.get()->getSourceRange());
9440    }
9441    break;
9442
9443  case UO_LNot: // logical negation
9444    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9445    Input = DefaultFunctionArrayLvalueConversion(Input.take());
9446    if (Input.isInvalid()) return ExprError();
9447    resultType = Input.get()->getType();
9448
9449    // Though we still have to promote half FP to float...
9450    if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9451      Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9452      resultType = Context.FloatTy;
9453    }
9454
9455    if (resultType->isDependentType())
9456      break;
9457    if (resultType->isScalarType()) {
9458      // C99 6.5.3.3p1: ok, fallthrough;
9459      if (Context.getLangOpts().CPlusPlus) {
9460        // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9461        // operand contextually converted to bool.
9462        Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9463                                  ScalarTypeToBooleanCastKind(resultType));
9464      } else if (Context.getLangOpts().OpenCL &&
9465                 Context.getLangOpts().OpenCLVersion < 120) {
9466        // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9467        // operate on scalar float types.
9468        if (!resultType->isIntegerType())
9469          return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9470                           << resultType << Input.get()->getSourceRange());
9471      }
9472    } else if (resultType->isExtVectorType()) {
9473      if (Context.getLangOpts().OpenCL &&
9474          Context.getLangOpts().OpenCLVersion < 120) {
9475        // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9476        // operate on vector float types.
9477        QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9478        if (!T->isIntegerType())
9479          return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9480                           << resultType << Input.get()->getSourceRange());
9481      }
9482      // Vector logical not returns the signed variant of the operand type.
9483      resultType = GetSignedVectorType(resultType);
9484      break;
9485    } else {
9486      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9487        << resultType << Input.get()->getSourceRange());
9488    }
9489
9490    // LNot always has type int. C99 6.5.3.3p5.
9491    // In C++, it's bool. C++ 5.3.1p8
9492    resultType = Context.getLogicalOperationType();
9493    break;
9494  case UO_Real:
9495  case UO_Imag:
9496    resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9497    // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9498    // complex l-values to ordinary l-values and all other values to r-values.
9499    if (Input.isInvalid()) return ExprError();
9500    if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9501      if (Input.get()->getValueKind() != VK_RValue &&
9502          Input.get()->getObjectKind() == OK_Ordinary)
9503        VK = Input.get()->getValueKind();
9504    } else if (!getLangOpts().CPlusPlus) {
9505      // In C, a volatile scalar is read by __imag. In C++, it is not.
9506      Input = DefaultLvalueConversion(Input.take());
9507    }
9508    break;
9509  case UO_Extension:
9510    resultType = Input.get()->getType();
9511    VK = Input.get()->getValueKind();
9512    OK = Input.get()->getObjectKind();
9513    break;
9514  }
9515  if (resultType.isNull() || Input.isInvalid())
9516    return ExprError();
9517
9518  // Check for array bounds violations in the operand of the UnaryOperator,
9519  // except for the '*' and '&' operators that have to be handled specially
9520  // by CheckArrayAccess (as there are special cases like &array[arraysize]
9521  // that are explicitly defined as valid by the standard).
9522  if (Opc != UO_AddrOf && Opc != UO_Deref)
9523    CheckArrayAccess(Input.get());
9524
9525  return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9526                                           VK, OK, OpLoc));
9527}
9528
9529/// \brief Determine whether the given expression is a qualified member
9530/// access expression, of a form that could be turned into a pointer to member
9531/// with the address-of operator.
9532static bool isQualifiedMemberAccess(Expr *E) {
9533  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9534    if (!DRE->getQualifier())
9535      return false;
9536
9537    ValueDecl *VD = DRE->getDecl();
9538    if (!VD->isCXXClassMember())
9539      return false;
9540
9541    if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9542      return true;
9543    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9544      return Method->isInstance();
9545
9546    return false;
9547  }
9548
9549  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9550    if (!ULE->getQualifier())
9551      return false;
9552
9553    for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9554                                           DEnd = ULE->decls_end();
9555         D != DEnd; ++D) {
9556      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9557        if (Method->isInstance())
9558          return true;
9559      } else {
9560        // Overload set does not contain methods.
9561        break;
9562      }
9563    }
9564
9565    return false;
9566  }
9567
9568  return false;
9569}
9570
9571ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9572                              UnaryOperatorKind Opc, Expr *Input) {
9573  // First things first: handle placeholders so that the
9574  // overloaded-operator check considers the right type.
9575  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9576    // Increment and decrement of pseudo-object references.
9577    if (pty->getKind() == BuiltinType::PseudoObject &&
9578        UnaryOperator::isIncrementDecrementOp(Opc))
9579      return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9580
9581    // extension is always a builtin operator.
9582    if (Opc == UO_Extension)
9583      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9584
9585    // & gets special logic for several kinds of placeholder.
9586    // The builtin code knows what to do.
9587    if (Opc == UO_AddrOf &&
9588        (pty->getKind() == BuiltinType::Overload ||
9589         pty->getKind() == BuiltinType::UnknownAny ||
9590         pty->getKind() == BuiltinType::BoundMember))
9591      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9592
9593    // Anything else needs to be handled now.
9594    ExprResult Result = CheckPlaceholderExpr(Input);
9595    if (Result.isInvalid()) return ExprError();
9596    Input = Result.take();
9597  }
9598
9599  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9600      UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9601      !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9602    // Find all of the overloaded operators visible from this
9603    // point. We perform both an operator-name lookup from the local
9604    // scope and an argument-dependent lookup based on the types of
9605    // the arguments.
9606    UnresolvedSet<16> Functions;
9607    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9608    if (S && OverOp != OO_None)
9609      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9610                                   Functions);
9611
9612    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9613  }
9614
9615  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9616}
9617
9618// Unary Operators.  'Tok' is the token for the operator.
9619ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9620                              tok::TokenKind Op, Expr *Input) {
9621  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9622}
9623
9624/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9625ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9626                                LabelDecl *TheDecl) {
9627  TheDecl->setUsed();
9628  // Create the AST node.  The address of a label always has type 'void*'.
9629  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9630                                       Context.getPointerType(Context.VoidTy)));
9631}
9632
9633/// Given the last statement in a statement-expression, check whether
9634/// the result is a producing expression (like a call to an
9635/// ns_returns_retained function) and, if so, rebuild it to hoist the
9636/// release out of the full-expression.  Otherwise, return null.
9637/// Cannot fail.
9638static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9639  // Should always be wrapped with one of these.
9640  ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9641  if (!cleanups) return 0;
9642
9643  ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9644  if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9645    return 0;
9646
9647  // Splice out the cast.  This shouldn't modify any interesting
9648  // features of the statement.
9649  Expr *producer = cast->getSubExpr();
9650  assert(producer->getType() == cast->getType());
9651  assert(producer->getValueKind() == cast->getValueKind());
9652  cleanups->setSubExpr(producer);
9653  return cleanups;
9654}
9655
9656void Sema::ActOnStartStmtExpr() {
9657  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9658}
9659
9660void Sema::ActOnStmtExprError() {
9661  // Note that function is also called by TreeTransform when leaving a
9662  // StmtExpr scope without rebuilding anything.
9663
9664  DiscardCleanupsInEvaluationContext();
9665  PopExpressionEvaluationContext();
9666}
9667
9668ExprResult
9669Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9670                    SourceLocation RPLoc) { // "({..})"
9671  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9672  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9673
9674  if (hasAnyUnrecoverableErrorsInThisFunction())
9675    DiscardCleanupsInEvaluationContext();
9676  assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9677  PopExpressionEvaluationContext();
9678
9679  bool isFileScope
9680    = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9681  if (isFileScope)
9682    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9683
9684  // FIXME: there are a variety of strange constraints to enforce here, for
9685  // example, it is not possible to goto into a stmt expression apparently.
9686  // More semantic analysis is needed.
9687
9688  // If there are sub stmts in the compound stmt, take the type of the last one
9689  // as the type of the stmtexpr.
9690  QualType Ty = Context.VoidTy;
9691  bool StmtExprMayBindToTemp = false;
9692  if (!Compound->body_empty()) {
9693    Stmt *LastStmt = Compound->body_back();
9694    LabelStmt *LastLabelStmt = 0;
9695    // If LastStmt is a label, skip down through into the body.
9696    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9697      LastLabelStmt = Label;
9698      LastStmt = Label->getSubStmt();
9699    }
9700
9701    if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9702      // Do function/array conversion on the last expression, but not
9703      // lvalue-to-rvalue.  However, initialize an unqualified type.
9704      ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9705      if (LastExpr.isInvalid())
9706        return ExprError();
9707      Ty = LastExpr.get()->getType().getUnqualifiedType();
9708
9709      if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9710        // In ARC, if the final expression ends in a consume, splice
9711        // the consume out and bind it later.  In the alternate case
9712        // (when dealing with a retainable type), the result
9713        // initialization will create a produce.  In both cases the
9714        // result will be +1, and we'll need to balance that out with
9715        // a bind.
9716        if (Expr *rebuiltLastStmt
9717              = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9718          LastExpr = rebuiltLastStmt;
9719        } else {
9720          LastExpr = PerformCopyInitialization(
9721                            InitializedEntity::InitializeResult(LPLoc,
9722                                                                Ty,
9723                                                                false),
9724                                                   SourceLocation(),
9725                                               LastExpr);
9726        }
9727
9728        if (LastExpr.isInvalid())
9729          return ExprError();
9730        if (LastExpr.get() != 0) {
9731          if (!LastLabelStmt)
9732            Compound->setLastStmt(LastExpr.take());
9733          else
9734            LastLabelStmt->setSubStmt(LastExpr.take());
9735          StmtExprMayBindToTemp = true;
9736        }
9737      }
9738    }
9739  }
9740
9741  // FIXME: Check that expression type is complete/non-abstract; statement
9742  // expressions are not lvalues.
9743  Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9744  if (StmtExprMayBindToTemp)
9745    return MaybeBindToTemporary(ResStmtExpr);
9746  return Owned(ResStmtExpr);
9747}
9748
9749ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9750                                      TypeSourceInfo *TInfo,
9751                                      OffsetOfComponent *CompPtr,
9752                                      unsigned NumComponents,
9753                                      SourceLocation RParenLoc) {
9754  QualType ArgTy = TInfo->getType();
9755  bool Dependent = ArgTy->isDependentType();
9756  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9757
9758  // We must have at least one component that refers to the type, and the first
9759  // one is known to be a field designator.  Verify that the ArgTy represents
9760  // a struct/union/class.
9761  if (!Dependent && !ArgTy->isRecordType())
9762    return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9763                       << ArgTy << TypeRange);
9764
9765  // Type must be complete per C99 7.17p3 because a declaring a variable
9766  // with an incomplete type would be ill-formed.
9767  if (!Dependent
9768      && RequireCompleteType(BuiltinLoc, ArgTy,
9769                             diag::err_offsetof_incomplete_type, TypeRange))
9770    return ExprError();
9771
9772  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9773  // GCC extension, diagnose them.
9774  // FIXME: This diagnostic isn't actually visible because the location is in
9775  // a system header!
9776  if (NumComponents != 1)
9777    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9778      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9779
9780  bool DidWarnAboutNonPOD = false;
9781  QualType CurrentType = ArgTy;
9782  typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9783  SmallVector<OffsetOfNode, 4> Comps;
9784  SmallVector<Expr*, 4> Exprs;
9785  for (unsigned i = 0; i != NumComponents; ++i) {
9786    const OffsetOfComponent &OC = CompPtr[i];
9787    if (OC.isBrackets) {
9788      // Offset of an array sub-field.  TODO: Should we allow vector elements?
9789      if (!CurrentType->isDependentType()) {
9790        const ArrayType *AT = Context.getAsArrayType(CurrentType);
9791        if(!AT)
9792          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9793                           << CurrentType);
9794        CurrentType = AT->getElementType();
9795      } else
9796        CurrentType = Context.DependentTy;
9797
9798      ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9799      if (IdxRval.isInvalid())
9800        return ExprError();
9801      Expr *Idx = IdxRval.take();
9802
9803      // The expression must be an integral expression.
9804      // FIXME: An integral constant expression?
9805      if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9806          !Idx->getType()->isIntegerType())
9807        return ExprError(Diag(Idx->getLocStart(),
9808                              diag::err_typecheck_subscript_not_integer)
9809                         << Idx->getSourceRange());
9810
9811      // Record this array index.
9812      Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9813      Exprs.push_back(Idx);
9814      continue;
9815    }
9816
9817    // Offset of a field.
9818    if (CurrentType->isDependentType()) {
9819      // We have the offset of a field, but we can't look into the dependent
9820      // type. Just record the identifier of the field.
9821      Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9822      CurrentType = Context.DependentTy;
9823      continue;
9824    }
9825
9826    // We need to have a complete type to look into.
9827    if (RequireCompleteType(OC.LocStart, CurrentType,
9828                            diag::err_offsetof_incomplete_type))
9829      return ExprError();
9830
9831    // Look for the designated field.
9832    const RecordType *RC = CurrentType->getAs<RecordType>();
9833    if (!RC)
9834      return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9835                       << CurrentType);
9836    RecordDecl *RD = RC->getDecl();
9837
9838    // C++ [lib.support.types]p5:
9839    //   The macro offsetof accepts a restricted set of type arguments in this
9840    //   International Standard. type shall be a POD structure or a POD union
9841    //   (clause 9).
9842    // C++11 [support.types]p4:
9843    //   If type is not a standard-layout class (Clause 9), the results are
9844    //   undefined.
9845    if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9846      bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
9847      unsigned DiagID =
9848        LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
9849                            : diag::warn_offsetof_non_pod_type;
9850
9851      if (!IsSafe && !DidWarnAboutNonPOD &&
9852          DiagRuntimeBehavior(BuiltinLoc, 0,
9853                              PDiag(DiagID)
9854                              << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9855                              << CurrentType))
9856        DidWarnAboutNonPOD = true;
9857    }
9858
9859    // Look for the field.
9860    LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9861    LookupQualifiedName(R, RD);
9862    FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9863    IndirectFieldDecl *IndirectMemberDecl = 0;
9864    if (!MemberDecl) {
9865      if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9866        MemberDecl = IndirectMemberDecl->getAnonField();
9867    }
9868
9869    if (!MemberDecl)
9870      return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9871                       << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9872                                                              OC.LocEnd));
9873
9874    // C99 7.17p3:
9875    //   (If the specified member is a bit-field, the behavior is undefined.)
9876    //
9877    // We diagnose this as an error.
9878    if (MemberDecl->isBitField()) {
9879      Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9880        << MemberDecl->getDeclName()
9881        << SourceRange(BuiltinLoc, RParenLoc);
9882      Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9883      return ExprError();
9884    }
9885
9886    RecordDecl *Parent = MemberDecl->getParent();
9887    if (IndirectMemberDecl)
9888      Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9889
9890    // If the member was found in a base class, introduce OffsetOfNodes for
9891    // the base class indirections.
9892    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9893                       /*DetectVirtual=*/false);
9894    if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9895      CXXBasePath &Path = Paths.front();
9896      for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9897           B != BEnd; ++B)
9898        Comps.push_back(OffsetOfNode(B->Base));
9899    }
9900
9901    if (IndirectMemberDecl) {
9902      for (IndirectFieldDecl::chain_iterator FI =
9903           IndirectMemberDecl->chain_begin(),
9904           FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9905        assert(isa<FieldDecl>(*FI));
9906        Comps.push_back(OffsetOfNode(OC.LocStart,
9907                                     cast<FieldDecl>(*FI), OC.LocEnd));
9908      }
9909    } else
9910      Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9911
9912    CurrentType = MemberDecl->getType().getNonReferenceType();
9913  }
9914
9915  return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9916                                    TInfo, Comps, Exprs, RParenLoc));
9917}
9918
9919ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9920                                      SourceLocation BuiltinLoc,
9921                                      SourceLocation TypeLoc,
9922                                      ParsedType ParsedArgTy,
9923                                      OffsetOfComponent *CompPtr,
9924                                      unsigned NumComponents,
9925                                      SourceLocation RParenLoc) {
9926
9927  TypeSourceInfo *ArgTInfo;
9928  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9929  if (ArgTy.isNull())
9930    return ExprError();
9931
9932  if (!ArgTInfo)
9933    ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9934
9935  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9936                              RParenLoc);
9937}
9938
9939
9940ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9941                                 Expr *CondExpr,
9942                                 Expr *LHSExpr, Expr *RHSExpr,
9943                                 SourceLocation RPLoc) {
9944  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9945
9946  ExprValueKind VK = VK_RValue;
9947  ExprObjectKind OK = OK_Ordinary;
9948  QualType resType;
9949  bool ValueDependent = false;
9950  bool CondIsTrue = false;
9951  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9952    resType = Context.DependentTy;
9953    ValueDependent = true;
9954  } else {
9955    // The conditional expression is required to be a constant expression.
9956    llvm::APSInt condEval(32);
9957    ExprResult CondICE
9958      = VerifyIntegerConstantExpression(CondExpr, &condEval,
9959          diag::err_typecheck_choose_expr_requires_constant, false);
9960    if (CondICE.isInvalid())
9961      return ExprError();
9962    CondExpr = CondICE.take();
9963    CondIsTrue = condEval.getZExtValue();
9964
9965    // If the condition is > zero, then the AST type is the same as the LSHExpr.
9966    Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
9967
9968    resType = ActiveExpr->getType();
9969    ValueDependent = ActiveExpr->isValueDependent();
9970    VK = ActiveExpr->getValueKind();
9971    OK = ActiveExpr->getObjectKind();
9972  }
9973
9974  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9975                                        resType, VK, OK, RPLoc, CondIsTrue,
9976                                        resType->isDependentType(),
9977                                        ValueDependent));
9978}
9979
9980//===----------------------------------------------------------------------===//
9981// Clang Extensions.
9982//===----------------------------------------------------------------------===//
9983
9984/// ActOnBlockStart - This callback is invoked when a block literal is started.
9985void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9986  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9987
9988  {
9989    Decl *ManglingContextDecl;
9990    if (MangleNumberingContext *MCtx =
9991            getCurrentMangleNumberContext(Block->getDeclContext(),
9992                                          ManglingContextDecl)) {
9993      unsigned ManglingNumber = MCtx->getManglingNumber(Block);
9994      Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
9995    }
9996  }
9997
9998  PushBlockScope(CurScope, Block);
9999  CurContext->addDecl(Block);
10000  if (CurScope)
10001    PushDeclContext(CurScope, Block);
10002  else
10003    CurContext = Block;
10004
10005  getCurBlock()->HasImplicitReturnType = true;
10006
10007  // Enter a new evaluation context to insulate the block from any
10008  // cleanups from the enclosing full-expression.
10009  PushExpressionEvaluationContext(PotentiallyEvaluated);
10010}
10011
10012void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10013                               Scope *CurScope) {
10014  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
10015  assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10016  BlockScopeInfo *CurBlock = getCurBlock();
10017
10018  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10019  QualType T = Sig->getType();
10020
10021  // FIXME: We should allow unexpanded parameter packs here, but that would,
10022  // in turn, make the block expression contain unexpanded parameter packs.
10023  if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10024    // Drop the parameters.
10025    FunctionProtoType::ExtProtoInfo EPI;
10026    EPI.HasTrailingReturn = false;
10027    EPI.TypeQuals |= DeclSpec::TQ_const;
10028    T = Context.getFunctionType(Context.DependentTy, None, EPI);
10029    Sig = Context.getTrivialTypeSourceInfo(T);
10030  }
10031
10032  // GetTypeForDeclarator always produces a function type for a block
10033  // literal signature.  Furthermore, it is always a FunctionProtoType
10034  // unless the function was written with a typedef.
10035  assert(T->isFunctionType() &&
10036         "GetTypeForDeclarator made a non-function block signature");
10037
10038  // Look for an explicit signature in that function type.
10039  FunctionProtoTypeLoc ExplicitSignature;
10040
10041  TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10042  if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10043
10044    // Check whether that explicit signature was synthesized by
10045    // GetTypeForDeclarator.  If so, don't save that as part of the
10046    // written signature.
10047    if (ExplicitSignature.getLocalRangeBegin() ==
10048        ExplicitSignature.getLocalRangeEnd()) {
10049      // This would be much cheaper if we stored TypeLocs instead of
10050      // TypeSourceInfos.
10051      TypeLoc Result = ExplicitSignature.getResultLoc();
10052      unsigned Size = Result.getFullDataSize();
10053      Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10054      Sig->getTypeLoc().initializeFullCopy(Result, Size);
10055
10056      ExplicitSignature = FunctionProtoTypeLoc();
10057    }
10058  }
10059
10060  CurBlock->TheDecl->setSignatureAsWritten(Sig);
10061  CurBlock->FunctionType = T;
10062
10063  const FunctionType *Fn = T->getAs<FunctionType>();
10064  QualType RetTy = Fn->getResultType();
10065  bool isVariadic =
10066    (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10067
10068  CurBlock->TheDecl->setIsVariadic(isVariadic);
10069
10070  // Context.DependentTy is used as a placeholder for a missing block
10071  // return type.  TODO:  what should we do with declarators like:
10072  //   ^ * { ... }
10073  // If the answer is "apply template argument deduction"....
10074  if (RetTy != Context.DependentTy) {
10075    CurBlock->ReturnType = RetTy;
10076    CurBlock->TheDecl->setBlockMissingReturnType(false);
10077    CurBlock->HasImplicitReturnType = false;
10078  }
10079
10080  // Push block parameters from the declarator if we had them.
10081  SmallVector<ParmVarDecl*, 8> Params;
10082  if (ExplicitSignature) {
10083    for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
10084      ParmVarDecl *Param = ExplicitSignature.getArg(I);
10085      if (Param->getIdentifier() == 0 &&
10086          !Param->isImplicit() &&
10087          !Param->isInvalidDecl() &&
10088          !getLangOpts().CPlusPlus)
10089        Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10090      Params.push_back(Param);
10091    }
10092
10093  // Fake up parameter variables if we have a typedef, like
10094  //   ^ fntype { ... }
10095  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10096    for (FunctionProtoType::arg_type_iterator
10097           I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
10098      ParmVarDecl *Param =
10099        BuildParmVarDeclForTypedef(CurBlock->TheDecl,
10100                                   ParamInfo.getLocStart(),
10101                                   *I);
10102      Params.push_back(Param);
10103    }
10104  }
10105
10106  // Set the parameters on the block decl.
10107  if (!Params.empty()) {
10108    CurBlock->TheDecl->setParams(Params);
10109    CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10110                             CurBlock->TheDecl->param_end(),
10111                             /*CheckParameterNames=*/false);
10112  }
10113
10114  // Finally we can process decl attributes.
10115  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10116
10117  // Put the parameter variables in scope.
10118  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
10119         E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
10120    (*AI)->setOwningFunction(CurBlock->TheDecl);
10121
10122    // If this has an identifier, add it to the scope stack.
10123    if ((*AI)->getIdentifier()) {
10124      CheckShadow(CurBlock->TheScope, *AI);
10125
10126      PushOnScopeChains(*AI, CurBlock->TheScope);
10127    }
10128  }
10129}
10130
10131/// ActOnBlockError - If there is an error parsing a block, this callback
10132/// is invoked to pop the information about the block from the action impl.
10133void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10134  // Leave the expression-evaluation context.
10135  DiscardCleanupsInEvaluationContext();
10136  PopExpressionEvaluationContext();
10137
10138  // Pop off CurBlock, handle nested blocks.
10139  PopDeclContext();
10140  PopFunctionScopeInfo();
10141}
10142
10143/// ActOnBlockStmtExpr - This is called when the body of a block statement
10144/// literal was successfully completed.  ^(int x){...}
10145ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10146                                    Stmt *Body, Scope *CurScope) {
10147  // If blocks are disabled, emit an error.
10148  if (!LangOpts.Blocks)
10149    Diag(CaretLoc, diag::err_blocks_disable);
10150
10151  // Leave the expression-evaluation context.
10152  if (hasAnyUnrecoverableErrorsInThisFunction())
10153    DiscardCleanupsInEvaluationContext();
10154  assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10155  PopExpressionEvaluationContext();
10156
10157  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10158
10159  if (BSI->HasImplicitReturnType)
10160    deduceClosureReturnType(*BSI);
10161
10162  PopDeclContext();
10163
10164  QualType RetTy = Context.VoidTy;
10165  if (!BSI->ReturnType.isNull())
10166    RetTy = BSI->ReturnType;
10167
10168  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
10169  QualType BlockTy;
10170
10171  // Set the captured variables on the block.
10172  // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10173  SmallVector<BlockDecl::Capture, 4> Captures;
10174  for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10175    CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10176    if (Cap.isThisCapture())
10177      continue;
10178    BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10179                              Cap.isNested(), Cap.getInitExpr());
10180    Captures.push_back(NewCap);
10181  }
10182  BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10183                            BSI->CXXThisCaptureIndex != 0);
10184
10185  // If the user wrote a function type in some form, try to use that.
10186  if (!BSI->FunctionType.isNull()) {
10187    const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10188
10189    FunctionType::ExtInfo Ext = FTy->getExtInfo();
10190    if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10191
10192    // Turn protoless block types into nullary block types.
10193    if (isa<FunctionNoProtoType>(FTy)) {
10194      FunctionProtoType::ExtProtoInfo EPI;
10195      EPI.ExtInfo = Ext;
10196      BlockTy = Context.getFunctionType(RetTy, None, EPI);
10197
10198    // Otherwise, if we don't need to change anything about the function type,
10199    // preserve its sugar structure.
10200    } else if (FTy->getResultType() == RetTy &&
10201               (!NoReturn || FTy->getNoReturnAttr())) {
10202      BlockTy = BSI->FunctionType;
10203
10204    // Otherwise, make the minimal modifications to the function type.
10205    } else {
10206      const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10207      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10208      EPI.TypeQuals = 0; // FIXME: silently?
10209      EPI.ExtInfo = Ext;
10210      BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI);
10211    }
10212
10213  // If we don't have a function type, just build one from nothing.
10214  } else {
10215    FunctionProtoType::ExtProtoInfo EPI;
10216    EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10217    BlockTy = Context.getFunctionType(RetTy, None, EPI);
10218  }
10219
10220  DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10221                           BSI->TheDecl->param_end());
10222  BlockTy = Context.getBlockPointerType(BlockTy);
10223
10224  // If needed, diagnose invalid gotos and switches in the block.
10225  if (getCurFunction()->NeedsScopeChecking() &&
10226      !hasAnyUnrecoverableErrorsInThisFunction() &&
10227      !PP.isCodeCompletionEnabled())
10228    DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10229
10230  BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10231
10232  // Try to apply the named return value optimization. We have to check again
10233  // if we can do this, though, because blocks keep return statements around
10234  // to deduce an implicit return type.
10235  if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10236      !BSI->TheDecl->isDependentContext())
10237    computeNRVO(Body, getCurBlock());
10238
10239  BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10240  const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
10241  PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10242
10243  // If the block isn't obviously global, i.e. it captures anything at
10244  // all, then we need to do a few things in the surrounding context:
10245  if (Result->getBlockDecl()->hasCaptures()) {
10246    // First, this expression has a new cleanup object.
10247    ExprCleanupObjects.push_back(Result->getBlockDecl());
10248    ExprNeedsCleanups = true;
10249
10250    // It also gets a branch-protected scope if any of the captured
10251    // variables needs destruction.
10252    for (BlockDecl::capture_const_iterator
10253           ci = Result->getBlockDecl()->capture_begin(),
10254           ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
10255      const VarDecl *var = ci->getVariable();
10256      if (var->getType().isDestructedType() != QualType::DK_none) {
10257        getCurFunction()->setHasBranchProtectedScope();
10258        break;
10259      }
10260    }
10261  }
10262
10263  return Owned(Result);
10264}
10265
10266ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10267                                        Expr *E, ParsedType Ty,
10268                                        SourceLocation RPLoc) {
10269  TypeSourceInfo *TInfo;
10270  GetTypeFromParser(Ty, &TInfo);
10271  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10272}
10273
10274ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10275                                Expr *E, TypeSourceInfo *TInfo,
10276                                SourceLocation RPLoc) {
10277  Expr *OrigExpr = E;
10278
10279  // Get the va_list type
10280  QualType VaListType = Context.getBuiltinVaListType();
10281  if (VaListType->isArrayType()) {
10282    // Deal with implicit array decay; for example, on x86-64,
10283    // va_list is an array, but it's supposed to decay to
10284    // a pointer for va_arg.
10285    VaListType = Context.getArrayDecayedType(VaListType);
10286    // Make sure the input expression also decays appropriately.
10287    ExprResult Result = UsualUnaryConversions(E);
10288    if (Result.isInvalid())
10289      return ExprError();
10290    E = Result.take();
10291  } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10292    // If va_list is a record type and we are compiling in C++ mode,
10293    // check the argument using reference binding.
10294    InitializedEntity Entity
10295      = InitializedEntity::InitializeParameter(Context,
10296          Context.getLValueReferenceType(VaListType), false);
10297    ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10298    if (Init.isInvalid())
10299      return ExprError();
10300    E = Init.takeAs<Expr>();
10301  } else {
10302    // Otherwise, the va_list argument must be an l-value because
10303    // it is modified by va_arg.
10304    if (!E->isTypeDependent() &&
10305        CheckForModifiableLvalue(E, BuiltinLoc, *this))
10306      return ExprError();
10307  }
10308
10309  if (!E->isTypeDependent() &&
10310      !Context.hasSameType(VaListType, E->getType())) {
10311    return ExprError(Diag(E->getLocStart(),
10312                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
10313      << OrigExpr->getType() << E->getSourceRange());
10314  }
10315
10316  if (!TInfo->getType()->isDependentType()) {
10317    if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10318                            diag::err_second_parameter_to_va_arg_incomplete,
10319                            TInfo->getTypeLoc()))
10320      return ExprError();
10321
10322    if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10323                               TInfo->getType(),
10324                               diag::err_second_parameter_to_va_arg_abstract,
10325                               TInfo->getTypeLoc()))
10326      return ExprError();
10327
10328    if (!TInfo->getType().isPODType(Context)) {
10329      Diag(TInfo->getTypeLoc().getBeginLoc(),
10330           TInfo->getType()->isObjCLifetimeType()
10331             ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10332             : diag::warn_second_parameter_to_va_arg_not_pod)
10333        << TInfo->getType()
10334        << TInfo->getTypeLoc().getSourceRange();
10335    }
10336
10337    // Check for va_arg where arguments of the given type will be promoted
10338    // (i.e. this va_arg is guaranteed to have undefined behavior).
10339    QualType PromoteType;
10340    if (TInfo->getType()->isPromotableIntegerType()) {
10341      PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10342      if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10343        PromoteType = QualType();
10344    }
10345    if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10346      PromoteType = Context.DoubleTy;
10347    if (!PromoteType.isNull())
10348      DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10349                  PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10350                          << TInfo->getType()
10351                          << PromoteType
10352                          << TInfo->getTypeLoc().getSourceRange());
10353  }
10354
10355  QualType T = TInfo->getType().getNonLValueExprType(Context);
10356  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10357}
10358
10359ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10360  // The type of __null will be int or long, depending on the size of
10361  // pointers on the target.
10362  QualType Ty;
10363  unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10364  if (pw == Context.getTargetInfo().getIntWidth())
10365    Ty = Context.IntTy;
10366  else if (pw == Context.getTargetInfo().getLongWidth())
10367    Ty = Context.LongTy;
10368  else if (pw == Context.getTargetInfo().getLongLongWidth())
10369    Ty = Context.LongLongTy;
10370  else {
10371    llvm_unreachable("I don't know size of pointer!");
10372  }
10373
10374  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10375}
10376
10377static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
10378                                           Expr *SrcExpr, FixItHint &Hint,
10379                                           bool &IsNSString) {
10380  if (!SemaRef.getLangOpts().ObjC1)
10381    return;
10382
10383  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10384  if (!PT)
10385    return;
10386
10387  // Check if the destination is of type 'id'.
10388  if (!PT->isObjCIdType()) {
10389    // Check if the destination is the 'NSString' interface.
10390    const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10391    if (!ID || !ID->getIdentifier()->isStr("NSString"))
10392      return;
10393    IsNSString = true;
10394  }
10395
10396  // Ignore any parens, implicit casts (should only be
10397  // array-to-pointer decays), and not-so-opaque values.  The last is
10398  // important for making this trigger for property assignments.
10399  SrcExpr = SrcExpr->IgnoreParenImpCasts();
10400  if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10401    if (OV->getSourceExpr())
10402      SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10403
10404  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10405  if (!SL || !SL->isAscii())
10406    return;
10407
10408  Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
10409}
10410
10411bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10412                                    SourceLocation Loc,
10413                                    QualType DstType, QualType SrcType,
10414                                    Expr *SrcExpr, AssignmentAction Action,
10415                                    bool *Complained) {
10416  if (Complained)
10417    *Complained = false;
10418
10419  // Decode the result (notice that AST's are still created for extensions).
10420  bool CheckInferredResultType = false;
10421  bool isInvalid = false;
10422  unsigned DiagKind = 0;
10423  FixItHint Hint;
10424  ConversionFixItGenerator ConvHints;
10425  bool MayHaveConvFixit = false;
10426  bool MayHaveFunctionDiff = false;
10427  bool IsNSString = false;
10428
10429  switch (ConvTy) {
10430  case Compatible:
10431      DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10432      return false;
10433
10434  case PointerToInt:
10435    DiagKind = diag::ext_typecheck_convert_pointer_int;
10436    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10437    MayHaveConvFixit = true;
10438    break;
10439  case IntToPointer:
10440    DiagKind = diag::ext_typecheck_convert_int_pointer;
10441    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10442    MayHaveConvFixit = true;
10443    break;
10444  case IncompatiblePointer:
10445    MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString);
10446      DiagKind =
10447        (Action == AA_Passing_CFAudited ?
10448          diag::err_arc_typecheck_convert_incompatible_pointer :
10449          diag::ext_typecheck_convert_incompatible_pointer);
10450    CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10451      SrcType->isObjCObjectPointerType();
10452    if (Hint.isNull() && !CheckInferredResultType) {
10453      ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10454    }
10455    else if (CheckInferredResultType) {
10456      SrcType = SrcType.getUnqualifiedType();
10457      DstType = DstType.getUnqualifiedType();
10458    }
10459    else if (IsNSString && !Hint.isNull())
10460      DiagKind = diag::warn_missing_atsign_prefix;
10461    MayHaveConvFixit = true;
10462    break;
10463  case IncompatiblePointerSign:
10464    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10465    break;
10466  case FunctionVoidPointer:
10467    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10468    break;
10469  case IncompatiblePointerDiscardsQualifiers: {
10470    // Perform array-to-pointer decay if necessary.
10471    if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10472
10473    Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10474    Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10475    if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10476      DiagKind = diag::err_typecheck_incompatible_address_space;
10477      break;
10478
10479
10480    } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10481      DiagKind = diag::err_typecheck_incompatible_ownership;
10482      break;
10483    }
10484
10485    llvm_unreachable("unknown error case for discarding qualifiers!");
10486    // fallthrough
10487  }
10488  case CompatiblePointerDiscardsQualifiers:
10489    // If the qualifiers lost were because we were applying the
10490    // (deprecated) C++ conversion from a string literal to a char*
10491    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10492    // Ideally, this check would be performed in
10493    // checkPointerTypesForAssignment. However, that would require a
10494    // bit of refactoring (so that the second argument is an
10495    // expression, rather than a type), which should be done as part
10496    // of a larger effort to fix checkPointerTypesForAssignment for
10497    // C++ semantics.
10498    if (getLangOpts().CPlusPlus &&
10499        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10500      return false;
10501    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10502    break;
10503  case IncompatibleNestedPointerQualifiers:
10504    DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10505    break;
10506  case IntToBlockPointer:
10507    DiagKind = diag::err_int_to_block_pointer;
10508    break;
10509  case IncompatibleBlockPointer:
10510    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10511    break;
10512  case IncompatibleObjCQualifiedId:
10513    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10514    // it can give a more specific diagnostic.
10515    DiagKind = diag::warn_incompatible_qualified_id;
10516    break;
10517  case IncompatibleVectors:
10518    DiagKind = diag::warn_incompatible_vectors;
10519    break;
10520  case IncompatibleObjCWeakRef:
10521    DiagKind = diag::err_arc_weak_unavailable_assign;
10522    break;
10523  case Incompatible:
10524    DiagKind = diag::err_typecheck_convert_incompatible;
10525    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10526    MayHaveConvFixit = true;
10527    isInvalid = true;
10528    MayHaveFunctionDiff = true;
10529    break;
10530  }
10531
10532  QualType FirstType, SecondType;
10533  switch (Action) {
10534  case AA_Assigning:
10535  case AA_Initializing:
10536    // The destination type comes first.
10537    FirstType = DstType;
10538    SecondType = SrcType;
10539    break;
10540
10541  case AA_Returning:
10542  case AA_Passing:
10543  case AA_Passing_CFAudited:
10544  case AA_Converting:
10545  case AA_Sending:
10546  case AA_Casting:
10547    // The source type comes first.
10548    FirstType = SrcType;
10549    SecondType = DstType;
10550    break;
10551  }
10552
10553  PartialDiagnostic FDiag = PDiag(DiagKind);
10554  if (Action == AA_Passing_CFAudited)
10555    FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10556  else
10557    FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10558
10559  // If we can fix the conversion, suggest the FixIts.
10560  assert(ConvHints.isNull() || Hint.isNull());
10561  if (!ConvHints.isNull()) {
10562    for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10563         HE = ConvHints.Hints.end(); HI != HE; ++HI)
10564      FDiag << *HI;
10565  } else {
10566    FDiag << Hint;
10567  }
10568  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10569
10570  if (MayHaveFunctionDiff)
10571    HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10572
10573  Diag(Loc, FDiag);
10574
10575  if (SecondType == Context.OverloadTy)
10576    NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10577                              FirstType);
10578
10579  if (CheckInferredResultType)
10580    EmitRelatedResultTypeNote(SrcExpr);
10581
10582  if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10583    EmitRelatedResultTypeNoteForReturn(DstType);
10584
10585  if (Complained)
10586    *Complained = true;
10587  return isInvalid;
10588}
10589
10590ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10591                                                 llvm::APSInt *Result) {
10592  class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10593  public:
10594    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10595      S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10596    }
10597  } Diagnoser;
10598
10599  return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10600}
10601
10602ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10603                                                 llvm::APSInt *Result,
10604                                                 unsigned DiagID,
10605                                                 bool AllowFold) {
10606  class IDDiagnoser : public VerifyICEDiagnoser {
10607    unsigned DiagID;
10608
10609  public:
10610    IDDiagnoser(unsigned DiagID)
10611      : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10612
10613    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10614      S.Diag(Loc, DiagID) << SR;
10615    }
10616  } Diagnoser(DiagID);
10617
10618  return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10619}
10620
10621void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10622                                            SourceRange SR) {
10623  S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10624}
10625
10626ExprResult
10627Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10628                                      VerifyICEDiagnoser &Diagnoser,
10629                                      bool AllowFold) {
10630  SourceLocation DiagLoc = E->getLocStart();
10631
10632  if (getLangOpts().CPlusPlus11) {
10633    // C++11 [expr.const]p5:
10634    //   If an expression of literal class type is used in a context where an
10635    //   integral constant expression is required, then that class type shall
10636    //   have a single non-explicit conversion function to an integral or
10637    //   unscoped enumeration type
10638    ExprResult Converted;
10639    class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10640    public:
10641      CXX11ConvertDiagnoser(bool Silent)
10642          : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10643                                Silent, true) {}
10644
10645      virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10646                                                   QualType T) {
10647        return S.Diag(Loc, diag::err_ice_not_integral) << T;
10648      }
10649
10650      virtual SemaDiagnosticBuilder diagnoseIncomplete(
10651          Sema &S, SourceLocation Loc, QualType T) {
10652        return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10653      }
10654
10655      virtual SemaDiagnosticBuilder diagnoseExplicitConv(
10656          Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10657        return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10658      }
10659
10660      virtual SemaDiagnosticBuilder noteExplicitConv(
10661          Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10662        return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10663                 << ConvTy->isEnumeralType() << ConvTy;
10664      }
10665
10666      virtual SemaDiagnosticBuilder diagnoseAmbiguous(
10667          Sema &S, SourceLocation Loc, QualType T) {
10668        return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10669      }
10670
10671      virtual SemaDiagnosticBuilder noteAmbiguous(
10672          Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10673        return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10674                 << ConvTy->isEnumeralType() << ConvTy;
10675      }
10676
10677      virtual SemaDiagnosticBuilder diagnoseConversion(
10678          Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10679        llvm_unreachable("conversion functions are permitted");
10680      }
10681    } ConvertDiagnoser(Diagnoser.Suppress);
10682
10683    Converted = PerformContextualImplicitConversion(DiagLoc, E,
10684                                                    ConvertDiagnoser);
10685    if (Converted.isInvalid())
10686      return Converted;
10687    E = Converted.take();
10688    if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10689      return ExprError();
10690  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10691    // An ICE must be of integral or unscoped enumeration type.
10692    if (!Diagnoser.Suppress)
10693      Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10694    return ExprError();
10695  }
10696
10697  // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10698  // in the non-ICE case.
10699  if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10700    if (Result)
10701      *Result = E->EvaluateKnownConstInt(Context);
10702    return Owned(E);
10703  }
10704
10705  Expr::EvalResult EvalResult;
10706  SmallVector<PartialDiagnosticAt, 8> Notes;
10707  EvalResult.Diag = &Notes;
10708
10709  // Try to evaluate the expression, and produce diagnostics explaining why it's
10710  // not a constant expression as a side-effect.
10711  bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10712                EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10713
10714  // In C++11, we can rely on diagnostics being produced for any expression
10715  // which is not a constant expression. If no diagnostics were produced, then
10716  // this is a constant expression.
10717  if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10718    if (Result)
10719      *Result = EvalResult.Val.getInt();
10720    return Owned(E);
10721  }
10722
10723  // If our only note is the usual "invalid subexpression" note, just point
10724  // the caret at its location rather than producing an essentially
10725  // redundant note.
10726  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10727        diag::note_invalid_subexpr_in_const_expr) {
10728    DiagLoc = Notes[0].first;
10729    Notes.clear();
10730  }
10731
10732  if (!Folded || !AllowFold) {
10733    if (!Diagnoser.Suppress) {
10734      Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10735      for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10736        Diag(Notes[I].first, Notes[I].second);
10737    }
10738
10739    return ExprError();
10740  }
10741
10742  Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10743  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10744    Diag(Notes[I].first, Notes[I].second);
10745
10746  if (Result)
10747    *Result = EvalResult.Val.getInt();
10748  return Owned(E);
10749}
10750
10751namespace {
10752  // Handle the case where we conclude a expression which we speculatively
10753  // considered to be unevaluated is actually evaluated.
10754  class TransformToPE : public TreeTransform<TransformToPE> {
10755    typedef TreeTransform<TransformToPE> BaseTransform;
10756
10757  public:
10758    TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10759
10760    // Make sure we redo semantic analysis
10761    bool AlwaysRebuild() { return true; }
10762
10763    // Make sure we handle LabelStmts correctly.
10764    // FIXME: This does the right thing, but maybe we need a more general
10765    // fix to TreeTransform?
10766    StmtResult TransformLabelStmt(LabelStmt *S) {
10767      S->getDecl()->setStmt(0);
10768      return BaseTransform::TransformLabelStmt(S);
10769    }
10770
10771    // We need to special-case DeclRefExprs referring to FieldDecls which
10772    // are not part of a member pointer formation; normal TreeTransforming
10773    // doesn't catch this case because of the way we represent them in the AST.
10774    // FIXME: This is a bit ugly; is it really the best way to handle this
10775    // case?
10776    //
10777    // Error on DeclRefExprs referring to FieldDecls.
10778    ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10779      if (isa<FieldDecl>(E->getDecl()) &&
10780          !SemaRef.isUnevaluatedContext())
10781        return SemaRef.Diag(E->getLocation(),
10782                            diag::err_invalid_non_static_member_use)
10783            << E->getDecl() << E->getSourceRange();
10784
10785      return BaseTransform::TransformDeclRefExpr(E);
10786    }
10787
10788    // Exception: filter out member pointer formation
10789    ExprResult TransformUnaryOperator(UnaryOperator *E) {
10790      if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10791        return E;
10792
10793      return BaseTransform::TransformUnaryOperator(E);
10794    }
10795
10796    ExprResult TransformLambdaExpr(LambdaExpr *E) {
10797      // Lambdas never need to be transformed.
10798      return E;
10799    }
10800  };
10801}
10802
10803ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
10804  assert(isUnevaluatedContext() &&
10805         "Should only transform unevaluated expressions");
10806  ExprEvalContexts.back().Context =
10807      ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10808  if (isUnevaluatedContext())
10809    return E;
10810  return TransformToPE(*this).TransformExpr(E);
10811}
10812
10813void
10814Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10815                                      Decl *LambdaContextDecl,
10816                                      bool IsDecltype) {
10817  ExprEvalContexts.push_back(
10818             ExpressionEvaluationContextRecord(NewContext,
10819                                               ExprCleanupObjects.size(),
10820                                               ExprNeedsCleanups,
10821                                               LambdaContextDecl,
10822                                               IsDecltype));
10823  ExprNeedsCleanups = false;
10824  if (!MaybeODRUseExprs.empty())
10825    std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10826}
10827
10828void
10829Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10830                                      ReuseLambdaContextDecl_t,
10831                                      bool IsDecltype) {
10832  Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
10833  PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
10834}
10835
10836void Sema::PopExpressionEvaluationContext() {
10837  ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10838
10839  if (!Rec.Lambdas.empty()) {
10840    if (Rec.isUnevaluated()) {
10841      // C++11 [expr.prim.lambda]p2:
10842      //   A lambda-expression shall not appear in an unevaluated operand
10843      //   (Clause 5).
10844      for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10845        Diag(Rec.Lambdas[I]->getLocStart(),
10846             diag::err_lambda_unevaluated_operand);
10847    } else {
10848      // Mark the capture expressions odr-used. This was deferred
10849      // during lambda expression creation.
10850      for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10851        LambdaExpr *Lambda = Rec.Lambdas[I];
10852        for (LambdaExpr::capture_init_iterator
10853                  C = Lambda->capture_init_begin(),
10854               CEnd = Lambda->capture_init_end();
10855             C != CEnd; ++C) {
10856          MarkDeclarationsReferencedInExpr(*C);
10857        }
10858      }
10859    }
10860  }
10861
10862  // When are coming out of an unevaluated context, clear out any
10863  // temporaries that we may have created as part of the evaluation of
10864  // the expression in that context: they aren't relevant because they
10865  // will never be constructed.
10866  if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
10867    ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10868                             ExprCleanupObjects.end());
10869    ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10870    CleanupVarDeclMarking();
10871    std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10872  // Otherwise, merge the contexts together.
10873  } else {
10874    ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10875    MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10876                            Rec.SavedMaybeODRUseExprs.end());
10877  }
10878
10879  // Pop the current expression evaluation context off the stack.
10880  ExprEvalContexts.pop_back();
10881}
10882
10883void Sema::DiscardCleanupsInEvaluationContext() {
10884  ExprCleanupObjects.erase(
10885         ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10886         ExprCleanupObjects.end());
10887  ExprNeedsCleanups = false;
10888  MaybeODRUseExprs.clear();
10889}
10890
10891ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10892  if (!E->getType()->isVariablyModifiedType())
10893    return E;
10894  return TransformToPotentiallyEvaluated(E);
10895}
10896
10897static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10898  // Do not mark anything as "used" within a dependent context; wait for
10899  // an instantiation.
10900  if (SemaRef.CurContext->isDependentContext())
10901    return false;
10902
10903  switch (SemaRef.ExprEvalContexts.back().Context) {
10904    case Sema::Unevaluated:
10905    case Sema::UnevaluatedAbstract:
10906      // We are in an expression that is not potentially evaluated; do nothing.
10907      // (Depending on how you read the standard, we actually do need to do
10908      // something here for null pointer constants, but the standard's
10909      // definition of a null pointer constant is completely crazy.)
10910      return false;
10911
10912    case Sema::ConstantEvaluated:
10913    case Sema::PotentiallyEvaluated:
10914      // We are in a potentially evaluated expression (or a constant-expression
10915      // in C++03); we need to do implicit template instantiation, implicitly
10916      // define class members, and mark most declarations as used.
10917      return true;
10918
10919    case Sema::PotentiallyEvaluatedIfUsed:
10920      // Referenced declarations will only be used if the construct in the
10921      // containing expression is used.
10922      return false;
10923  }
10924  llvm_unreachable("Invalid context");
10925}
10926
10927/// \brief Mark a function referenced, and check whether it is odr-used
10928/// (C++ [basic.def.odr]p2, C99 6.9p3)
10929void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10930  assert(Func && "No function?");
10931
10932  Func->setReferenced();
10933
10934  // C++11 [basic.def.odr]p3:
10935  //   A function whose name appears as a potentially-evaluated expression is
10936  //   odr-used if it is the unique lookup result or the selected member of a
10937  //   set of overloaded functions [...].
10938  //
10939  // We (incorrectly) mark overload resolution as an unevaluated context, so we
10940  // can just check that here. Skip the rest of this function if we've already
10941  // marked the function as used.
10942  if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10943    // C++11 [temp.inst]p3:
10944    //   Unless a function template specialization has been explicitly
10945    //   instantiated or explicitly specialized, the function template
10946    //   specialization is implicitly instantiated when the specialization is
10947    //   referenced in a context that requires a function definition to exist.
10948    //
10949    // We consider constexpr function templates to be referenced in a context
10950    // that requires a definition to exist whenever they are referenced.
10951    //
10952    // FIXME: This instantiates constexpr functions too frequently. If this is
10953    // really an unevaluated context (and we're not just in the definition of a
10954    // function template or overload resolution or other cases which we
10955    // incorrectly consider to be unevaluated contexts), and we're not in a
10956    // subexpression which we actually need to evaluate (for instance, a
10957    // template argument, array bound or an expression in a braced-init-list),
10958    // we are not permitted to instantiate this constexpr function definition.
10959    //
10960    // FIXME: This also implicitly defines special members too frequently. They
10961    // are only supposed to be implicitly defined if they are odr-used, but they
10962    // are not odr-used from constant expressions in unevaluated contexts.
10963    // However, they cannot be referenced if they are deleted, and they are
10964    // deleted whenever the implicit definition of the special member would
10965    // fail.
10966    if (!Func->isConstexpr() || Func->getBody())
10967      return;
10968    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10969    if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10970      return;
10971  }
10972
10973  // Note that this declaration has been used.
10974  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10975    if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10976      if (Constructor->isDefaultConstructor()) {
10977        if (Constructor->isTrivial())
10978          return;
10979        if (!Constructor->isUsed(false))
10980          DefineImplicitDefaultConstructor(Loc, Constructor);
10981      } else if (Constructor->isCopyConstructor()) {
10982        if (!Constructor->isUsed(false))
10983          DefineImplicitCopyConstructor(Loc, Constructor);
10984      } else if (Constructor->isMoveConstructor()) {
10985        if (!Constructor->isUsed(false))
10986          DefineImplicitMoveConstructor(Loc, Constructor);
10987      }
10988    } else if (Constructor->getInheritedConstructor()) {
10989      if (!Constructor->isUsed(false))
10990        DefineInheritingConstructor(Loc, Constructor);
10991    }
10992
10993    MarkVTableUsed(Loc, Constructor->getParent());
10994  } else if (CXXDestructorDecl *Destructor =
10995                 dyn_cast<CXXDestructorDecl>(Func)) {
10996    if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10997        !Destructor->isUsed(false))
10998      DefineImplicitDestructor(Loc, Destructor);
10999    if (Destructor->isVirtual())
11000      MarkVTableUsed(Loc, Destructor->getParent());
11001  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11002    if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
11003        MethodDecl->isOverloadedOperator() &&
11004        MethodDecl->getOverloadedOperator() == OO_Equal) {
11005      if (!MethodDecl->isUsed(false)) {
11006        if (MethodDecl->isCopyAssignmentOperator())
11007          DefineImplicitCopyAssignment(Loc, MethodDecl);
11008        else
11009          DefineImplicitMoveAssignment(Loc, MethodDecl);
11010      }
11011    } else if (isa<CXXConversionDecl>(MethodDecl) &&
11012               MethodDecl->getParent()->isLambda()) {
11013      CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
11014      if (Conversion->isLambdaToBlockPointerConversion())
11015        DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11016      else
11017        DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11018    } else if (MethodDecl->isVirtual())
11019      MarkVTableUsed(Loc, MethodDecl->getParent());
11020  }
11021
11022  // Recursive functions should be marked when used from another function.
11023  // FIXME: Is this really right?
11024  if (CurContext == Func) return;
11025
11026  // Resolve the exception specification for any function which is
11027  // used: CodeGen will need it.
11028  const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11029  if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11030    ResolveExceptionSpec(Loc, FPT);
11031
11032  // Implicit instantiation of function templates and member functions of
11033  // class templates.
11034  if (Func->isImplicitlyInstantiable()) {
11035    bool AlreadyInstantiated = false;
11036    SourceLocation PointOfInstantiation = Loc;
11037    if (FunctionTemplateSpecializationInfo *SpecInfo
11038                              = Func->getTemplateSpecializationInfo()) {
11039      if (SpecInfo->getPointOfInstantiation().isInvalid())
11040        SpecInfo->setPointOfInstantiation(Loc);
11041      else if (SpecInfo->getTemplateSpecializationKind()
11042                 == TSK_ImplicitInstantiation) {
11043        AlreadyInstantiated = true;
11044        PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11045      }
11046    } else if (MemberSpecializationInfo *MSInfo
11047                                = Func->getMemberSpecializationInfo()) {
11048      if (MSInfo->getPointOfInstantiation().isInvalid())
11049        MSInfo->setPointOfInstantiation(Loc);
11050      else if (MSInfo->getTemplateSpecializationKind()
11051                 == TSK_ImplicitInstantiation) {
11052        AlreadyInstantiated = true;
11053        PointOfInstantiation = MSInfo->getPointOfInstantiation();
11054      }
11055    }
11056
11057    if (!AlreadyInstantiated || Func->isConstexpr()) {
11058      if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11059          cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11060          ActiveTemplateInstantiations.size())
11061        PendingLocalImplicitInstantiations.push_back(
11062            std::make_pair(Func, PointOfInstantiation));
11063      else if (Func->isConstexpr())
11064        // Do not defer instantiations of constexpr functions, to avoid the
11065        // expression evaluator needing to call back into Sema if it sees a
11066        // call to such a function.
11067        InstantiateFunctionDefinition(PointOfInstantiation, Func);
11068      else {
11069        PendingInstantiations.push_back(std::make_pair(Func,
11070                                                       PointOfInstantiation));
11071        // Notify the consumer that a function was implicitly instantiated.
11072        Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11073      }
11074    }
11075  } else {
11076    // Walk redefinitions, as some of them may be instantiable.
11077    for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
11078         e(Func->redecls_end()); i != e; ++i) {
11079      if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11080        MarkFunctionReferenced(Loc, *i);
11081    }
11082  }
11083
11084  // Keep track of used but undefined functions.
11085  if (!Func->isDefined()) {
11086    if (mightHaveNonExternalLinkage(Func))
11087      UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11088    else if (Func->getMostRecentDecl()->isInlined() &&
11089             (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11090             !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11091      UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11092  }
11093
11094  // Normally the must current decl is marked used while processing the use and
11095  // any subsequent decls are marked used by decl merging. This fails with
11096  // template instantiation since marking can happen at the end of the file
11097  // and, because of the two phase lookup, this function is called with at
11098  // decl in the middle of a decl chain. We loop to maintain the invariant
11099  // that once a decl is used, all decls after it are also used.
11100  for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11101    F->setUsed(true);
11102    if (F == Func)
11103      break;
11104  }
11105}
11106
11107static void
11108diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11109                                   VarDecl *var, DeclContext *DC) {
11110  DeclContext *VarDC = var->getDeclContext();
11111
11112  //  If the parameter still belongs to the translation unit, then
11113  //  we're actually just using one parameter in the declaration of
11114  //  the next.
11115  if (isa<ParmVarDecl>(var) &&
11116      isa<TranslationUnitDecl>(VarDC))
11117    return;
11118
11119  // For C code, don't diagnose about capture if we're not actually in code
11120  // right now; it's impossible to write a non-constant expression outside of
11121  // function context, so we'll get other (more useful) diagnostics later.
11122  //
11123  // For C++, things get a bit more nasty... it would be nice to suppress this
11124  // diagnostic for certain cases like using a local variable in an array bound
11125  // for a member of a local class, but the correct predicate is not obvious.
11126  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11127    return;
11128
11129  if (isa<CXXMethodDecl>(VarDC) &&
11130      cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11131    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11132      << var->getIdentifier();
11133  } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11134    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11135      << var->getIdentifier() << fn->getDeclName();
11136  } else if (isa<BlockDecl>(VarDC)) {
11137    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11138      << var->getIdentifier();
11139  } else {
11140    // FIXME: Is there any other context where a local variable can be
11141    // declared?
11142    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11143      << var->getIdentifier();
11144  }
11145
11146  S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
11147    << var->getIdentifier();
11148
11149  // FIXME: Add additional diagnostic info about class etc. which prevents
11150  // capture.
11151}
11152
11153/// \brief Capture the given variable in the captured region.
11154static ExprResult captureInCapturedRegion(Sema &S, CapturedRegionScopeInfo *RSI,
11155                                          VarDecl *Var, QualType FieldType,
11156                                          QualType DeclRefType,
11157                                          SourceLocation Loc,
11158                                          bool RefersToEnclosingLocal) {
11159  // The current implemention assumes that all variables are captured
11160  // by references. Since there is no capture by copy, no expression evaluation
11161  // will be needed.
11162  //
11163  RecordDecl *RD = RSI->TheRecordDecl;
11164
11165  FieldDecl *Field
11166    = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, FieldType,
11167                        S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11168                        0, false, ICIS_NoInit);
11169  Field->setImplicit(true);
11170  Field->setAccess(AS_private);
11171  RD->addDecl(Field);
11172
11173  Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11174                                          DeclRefType, VK_LValue, Loc);
11175  Var->setReferenced(true);
11176  Var->setUsed(true);
11177
11178  return Ref;
11179}
11180
11181/// \brief Capture the given variable in the given lambda expression.
11182static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
11183                                  VarDecl *Var, QualType FieldType,
11184                                  QualType DeclRefType,
11185                                  SourceLocation Loc,
11186                                  bool RefersToEnclosingLocal) {
11187  CXXRecordDecl *Lambda = LSI->Lambda;
11188
11189  // Build the non-static data member.
11190  FieldDecl *Field
11191    = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11192                        S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11193                        0, false, ICIS_NoInit);
11194  Field->setImplicit(true);
11195  Field->setAccess(AS_private);
11196  Lambda->addDecl(Field);
11197
11198  // C++11 [expr.prim.lambda]p21:
11199  //   When the lambda-expression is evaluated, the entities that
11200  //   are captured by copy are used to direct-initialize each
11201  //   corresponding non-static data member of the resulting closure
11202  //   object. (For array members, the array elements are
11203  //   direct-initialized in increasing subscript order.) These
11204  //   initializations are performed in the (unspecified) order in
11205  //   which the non-static data members are declared.
11206
11207  // Introduce a new evaluation context for the initialization, so
11208  // that temporaries introduced as part of the capture are retained
11209  // to be re-"exported" from the lambda expression itself.
11210  EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11211
11212  // C++ [expr.prim.labda]p12:
11213  //   An entity captured by a lambda-expression is odr-used (3.2) in
11214  //   the scope containing the lambda-expression.
11215  Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11216                                          DeclRefType, VK_LValue, Loc);
11217  Var->setReferenced(true);
11218  Var->setUsed(true);
11219
11220  // When the field has array type, create index variables for each
11221  // dimension of the array. We use these index variables to subscript
11222  // the source array, and other clients (e.g., CodeGen) will perform
11223  // the necessary iteration with these index variables.
11224  SmallVector<VarDecl *, 4> IndexVariables;
11225  QualType BaseType = FieldType;
11226  QualType SizeType = S.Context.getSizeType();
11227  LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11228  while (const ConstantArrayType *Array
11229                        = S.Context.getAsConstantArrayType(BaseType)) {
11230    // Create the iteration variable for this array index.
11231    IdentifierInfo *IterationVarName = 0;
11232    {
11233      SmallString<8> Str;
11234      llvm::raw_svector_ostream OS(Str);
11235      OS << "__i" << IndexVariables.size();
11236      IterationVarName = &S.Context.Idents.get(OS.str());
11237    }
11238    VarDecl *IterationVar
11239      = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11240                        IterationVarName, SizeType,
11241                        S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11242                        SC_None);
11243    IndexVariables.push_back(IterationVar);
11244    LSI->ArrayIndexVars.push_back(IterationVar);
11245
11246    // Create a reference to the iteration variable.
11247    ExprResult IterationVarRef
11248      = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11249    assert(!IterationVarRef.isInvalid() &&
11250           "Reference to invented variable cannot fail!");
11251    IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11252    assert(!IterationVarRef.isInvalid() &&
11253           "Conversion of invented variable cannot fail!");
11254
11255    // Subscript the array with this iteration variable.
11256    ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11257                             Ref, Loc, IterationVarRef.take(), Loc);
11258    if (Subscript.isInvalid()) {
11259      S.CleanupVarDeclMarking();
11260      S.DiscardCleanupsInEvaluationContext();
11261      return ExprError();
11262    }
11263
11264    Ref = Subscript.take();
11265    BaseType = Array->getElementType();
11266  }
11267
11268  // Construct the entity that we will be initializing. For an array, this
11269  // will be first element in the array, which may require several levels
11270  // of array-subscript entities.
11271  SmallVector<InitializedEntity, 4> Entities;
11272  Entities.reserve(1 + IndexVariables.size());
11273  Entities.push_back(
11274    InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
11275  for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11276    Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11277                                                            0,
11278                                                            Entities.back()));
11279
11280  InitializationKind InitKind
11281    = InitializationKind::CreateDirect(Loc, Loc, Loc);
11282  InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11283  ExprResult Result(true);
11284  if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11285    Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11286
11287  // If this initialization requires any cleanups (e.g., due to a
11288  // default argument to a copy constructor), note that for the
11289  // lambda.
11290  if (S.ExprNeedsCleanups)
11291    LSI->ExprNeedsCleanups = true;
11292
11293  // Exit the expression evaluation context used for the capture.
11294  S.CleanupVarDeclMarking();
11295  S.DiscardCleanupsInEvaluationContext();
11296  return Result;
11297}
11298
11299bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11300                              TryCaptureKind Kind, SourceLocation EllipsisLoc,
11301                              bool BuildAndDiagnose,
11302                              QualType &CaptureType,
11303                              QualType &DeclRefType) {
11304  bool Nested = false;
11305
11306  DeclContext *DC = CurContext;
11307  if (Var->getDeclContext() == DC) return true;
11308  if (!Var->hasLocalStorage()) return true;
11309
11310  bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11311
11312  // Walk up the stack to determine whether we can capture the variable,
11313  // performing the "simple" checks that don't depend on type. We stop when
11314  // we've either hit the declared scope of the variable or find an existing
11315  // capture of that variable.
11316  CaptureType = Var->getType();
11317  DeclRefType = CaptureType.getNonReferenceType();
11318  bool Explicit = (Kind != TryCapture_Implicit);
11319  unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
11320  do {
11321    // Only block literals, captured statements, and lambda expressions can
11322    // capture; other scopes don't work.
11323    DeclContext *ParentDC;
11324    if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC))
11325      ParentDC = DC->getParent();
11326    else if (isa<CXXMethodDecl>(DC) &&
11327             cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
11328             cast<CXXRecordDecl>(DC->getParent())->isLambda())
11329      ParentDC = DC->getParent()->getParent();
11330    else {
11331      if (BuildAndDiagnose)
11332        diagnoseUncapturableValueReference(*this, Loc, Var, DC);
11333      return true;
11334    }
11335
11336    CapturingScopeInfo *CSI =
11337      cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
11338
11339    // Check whether we've already captured it.
11340    if (CSI->isCaptured(Var)) {
11341      const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11342
11343      // If we found a capture, any subcaptures are nested.
11344      Nested = true;
11345
11346      // Retrieve the capture type for this variable.
11347      CaptureType = Cap.getCaptureType();
11348
11349      // Compute the type of an expression that refers to this variable.
11350      DeclRefType = CaptureType.getNonReferenceType();
11351
11352      if (Cap.isCopyCapture() &&
11353          !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11354        DeclRefType.addConst();
11355      break;
11356    }
11357
11358    bool IsBlock = isa<BlockScopeInfo>(CSI);
11359    bool IsLambda = isa<LambdaScopeInfo>(CSI);
11360
11361    // Lambdas are not allowed to capture unnamed variables
11362    // (e.g. anonymous unions).
11363    // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11364    // assuming that's the intent.
11365    if (IsLambda && !Var->getDeclName()) {
11366      if (BuildAndDiagnose) {
11367        Diag(Loc, diag::err_lambda_capture_anonymous_var);
11368        Diag(Var->getLocation(), diag::note_declared_at);
11369      }
11370      return true;
11371    }
11372
11373    // Prohibit variably-modified types; they're difficult to deal with.
11374    if (Var->getType()->isVariablyModifiedType()) {
11375      if (BuildAndDiagnose) {
11376        if (IsBlock)
11377          Diag(Loc, diag::err_ref_vm_type);
11378        else
11379          Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11380        Diag(Var->getLocation(), diag::note_previous_decl)
11381          << Var->getDeclName();
11382      }
11383      return true;
11384    }
11385    // Prohibit structs with flexible array members too.
11386    // We cannot capture what is in the tail end of the struct.
11387    if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11388      if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11389        if (BuildAndDiagnose) {
11390          if (IsBlock)
11391            Diag(Loc, diag::err_ref_flexarray_type);
11392          else
11393            Diag(Loc, diag::err_lambda_capture_flexarray_type)
11394              << Var->getDeclName();
11395          Diag(Var->getLocation(), diag::note_previous_decl)
11396            << Var->getDeclName();
11397        }
11398        return true;
11399      }
11400    }
11401    // Lambdas and captured statements are not allowed to capture __block
11402    // variables; they don't support the expected semantics.
11403    if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11404      if (BuildAndDiagnose) {
11405        Diag(Loc, diag::err_capture_block_variable)
11406          << Var->getDeclName() << !IsLambda;
11407        Diag(Var->getLocation(), diag::note_previous_decl)
11408          << Var->getDeclName();
11409      }
11410      return true;
11411    }
11412
11413    if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11414      // No capture-default
11415      if (BuildAndDiagnose) {
11416        Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
11417        Diag(Var->getLocation(), diag::note_previous_decl)
11418          << Var->getDeclName();
11419        Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11420             diag::note_lambda_decl);
11421      }
11422      return true;
11423    }
11424
11425    FunctionScopesIndex--;
11426    DC = ParentDC;
11427    Explicit = false;
11428  } while (!Var->getDeclContext()->Equals(DC));
11429
11430  // Walk back down the scope stack, computing the type of the capture at
11431  // each step, checking type-specific requirements, and adding captures if
11432  // requested.
11433  for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
11434       ++I) {
11435    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
11436
11437    // Compute the type of the capture and of a reference to the capture within
11438    // this scope.
11439    if (isa<BlockScopeInfo>(CSI)) {
11440      Expr *CopyExpr = 0;
11441      bool ByRef = false;
11442
11443      // Blocks are not allowed to capture arrays.
11444      if (CaptureType->isArrayType()) {
11445        if (BuildAndDiagnose) {
11446          Diag(Loc, diag::err_ref_array_type);
11447          Diag(Var->getLocation(), diag::note_previous_decl)
11448          << Var->getDeclName();
11449        }
11450        return true;
11451      }
11452
11453      // Forbid the block-capture of autoreleasing variables.
11454      if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11455        if (BuildAndDiagnose) {
11456          Diag(Loc, diag::err_arc_autoreleasing_capture)
11457            << /*block*/ 0;
11458          Diag(Var->getLocation(), diag::note_previous_decl)
11459            << Var->getDeclName();
11460        }
11461        return true;
11462      }
11463
11464      if (HasBlocksAttr || CaptureType->isReferenceType()) {
11465        // Block capture by reference does not change the capture or
11466        // declaration reference types.
11467        ByRef = true;
11468      } else {
11469        // Block capture by copy introduces 'const'.
11470        CaptureType = CaptureType.getNonReferenceType().withConst();
11471        DeclRefType = CaptureType;
11472
11473        if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
11474          if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11475            // The capture logic needs the destructor, so make sure we mark it.
11476            // Usually this is unnecessary because most local variables have
11477            // their destructors marked at declaration time, but parameters are
11478            // an exception because it's technically only the call site that
11479            // actually requires the destructor.
11480            if (isa<ParmVarDecl>(Var))
11481              FinalizeVarWithDestructor(Var, Record);
11482
11483            // Enter a new evaluation context to insulate the copy
11484            // full-expression.
11485            EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11486
11487            // According to the blocks spec, the capture of a variable from
11488            // the stack requires a const copy constructor.  This is not true
11489            // of the copy/move done to move a __block variable to the heap.
11490            Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
11491                                                      DeclRefType.withConst(),
11492                                                      VK_LValue, Loc);
11493
11494            ExprResult Result
11495              = PerformCopyInitialization(
11496                  InitializedEntity::InitializeBlock(Var->getLocation(),
11497                                                     CaptureType, false),
11498                  Loc, Owned(DeclRef));
11499
11500            // Build a full-expression copy expression if initialization
11501            // succeeded and used a non-trivial constructor.  Recover from
11502            // errors by pretending that the copy isn't necessary.
11503            if (!Result.isInvalid() &&
11504                !cast<CXXConstructExpr>(Result.get())->getConstructor()
11505                   ->isTrivial()) {
11506              Result = MaybeCreateExprWithCleanups(Result);
11507              CopyExpr = Result.take();
11508            }
11509          }
11510        }
11511      }
11512
11513      // Actually capture the variable.
11514      if (BuildAndDiagnose)
11515        CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11516                        SourceLocation(), CaptureType, CopyExpr);
11517      Nested = true;
11518      continue;
11519    }
11520
11521    if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
11522      // By default, capture variables by reference.
11523      bool ByRef = true;
11524      // Using an LValue reference type is consistent with Lambdas (see below).
11525      CaptureType = Context.getLValueReferenceType(DeclRefType);
11526
11527      Expr *CopyExpr = 0;
11528      if (BuildAndDiagnose) {
11529        ExprResult Result = captureInCapturedRegion(*this, RSI, Var,
11530                                                    CaptureType, DeclRefType,
11531                                                    Loc, Nested);
11532        if (!Result.isInvalid())
11533          CopyExpr = Result.take();
11534      }
11535
11536      // Actually capture the variable.
11537      if (BuildAndDiagnose)
11538        CSI->addCapture(Var, /*isBlock*/false, ByRef, Nested, Loc,
11539                        SourceLocation(), CaptureType, CopyExpr);
11540      Nested = true;
11541      continue;
11542    }
11543
11544    LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11545
11546    // Determine whether we are capturing by reference or by value.
11547    bool ByRef = false;
11548    if (I == N - 1 && Kind != TryCapture_Implicit) {
11549      ByRef = (Kind == TryCapture_ExplicitByRef);
11550    } else {
11551      ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11552    }
11553
11554    // Compute the type of the field that will capture this variable.
11555    if (ByRef) {
11556      // C++11 [expr.prim.lambda]p15:
11557      //   An entity is captured by reference if it is implicitly or
11558      //   explicitly captured but not captured by copy. It is
11559      //   unspecified whether additional unnamed non-static data
11560      //   members are declared in the closure type for entities
11561      //   captured by reference.
11562      //
11563      // FIXME: It is not clear whether we want to build an lvalue reference
11564      // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11565      // to do the former, while EDG does the latter. Core issue 1249 will
11566      // clarify, but for now we follow GCC because it's a more permissive and
11567      // easily defensible position.
11568      CaptureType = Context.getLValueReferenceType(DeclRefType);
11569    } else {
11570      // C++11 [expr.prim.lambda]p14:
11571      //   For each entity captured by copy, an unnamed non-static
11572      //   data member is declared in the closure type. The
11573      //   declaration order of these members is unspecified. The type
11574      //   of such a data member is the type of the corresponding
11575      //   captured entity if the entity is not a reference to an
11576      //   object, or the referenced type otherwise. [Note: If the
11577      //   captured entity is a reference to a function, the
11578      //   corresponding data member is also a reference to a
11579      //   function. - end note ]
11580      if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11581        if (!RefType->getPointeeType()->isFunctionType())
11582          CaptureType = RefType->getPointeeType();
11583      }
11584
11585      // Forbid the lambda copy-capture of autoreleasing variables.
11586      if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11587        if (BuildAndDiagnose) {
11588          Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11589          Diag(Var->getLocation(), diag::note_previous_decl)
11590            << Var->getDeclName();
11591        }
11592        return true;
11593      }
11594    }
11595
11596    // Capture this variable in the lambda.
11597    Expr *CopyExpr = 0;
11598    if (BuildAndDiagnose) {
11599      ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
11600                                          DeclRefType, Loc,
11601                                          Nested);
11602      if (!Result.isInvalid())
11603        CopyExpr = Result.take();
11604    }
11605
11606    // Compute the type of a reference to this captured variable.
11607    if (ByRef)
11608      DeclRefType = CaptureType.getNonReferenceType();
11609    else {
11610      // C++ [expr.prim.lambda]p5:
11611      //   The closure type for a lambda-expression has a public inline
11612      //   function call operator [...]. This function call operator is
11613      //   declared const (9.3.1) if and only if the lambda-expression’s
11614      //   parameter-declaration-clause is not followed by mutable.
11615      DeclRefType = CaptureType.getNonReferenceType();
11616      if (!LSI->Mutable && !CaptureType->isReferenceType())
11617        DeclRefType.addConst();
11618    }
11619
11620    // Add the capture.
11621    if (BuildAndDiagnose)
11622      CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
11623                      EllipsisLoc, CaptureType, CopyExpr);
11624    Nested = true;
11625  }
11626
11627  return false;
11628}
11629
11630bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11631                              TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11632  QualType CaptureType;
11633  QualType DeclRefType;
11634  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11635                            /*BuildAndDiagnose=*/true, CaptureType,
11636                            DeclRefType);
11637}
11638
11639QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11640  QualType CaptureType;
11641  QualType DeclRefType;
11642
11643  // Determine whether we can capture this variable.
11644  if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11645                         /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11646    return QualType();
11647
11648  return DeclRefType;
11649}
11650
11651static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11652                               SourceLocation Loc) {
11653  // Keep track of used but undefined variables.
11654  // FIXME: We shouldn't suppress this warning for static data members.
11655  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
11656      !Var->isExternallyVisible() &&
11657      !(Var->isStaticDataMember() && Var->hasInit())) {
11658    SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
11659    if (old.isInvalid()) old = Loc;
11660  }
11661
11662  SemaRef.tryCaptureVariable(Var, Loc);
11663
11664  Var->setUsed(true);
11665}
11666
11667void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11668  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11669  // an object that satisfies the requirements for appearing in a
11670  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11671  // is immediately applied."  This function handles the lvalue-to-rvalue
11672  // conversion part.
11673  MaybeODRUseExprs.erase(E->IgnoreParens());
11674}
11675
11676ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11677  if (!Res.isUsable())
11678    return Res;
11679
11680  // If a constant-expression is a reference to a variable where we delay
11681  // deciding whether it is an odr-use, just assume we will apply the
11682  // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
11683  // (a non-type template argument), we have special handling anyway.
11684  UpdateMarkingForLValueToRValue(Res.get());
11685  return Res;
11686}
11687
11688void Sema::CleanupVarDeclMarking() {
11689  for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11690                                        e = MaybeODRUseExprs.end();
11691       i != e; ++i) {
11692    VarDecl *Var;
11693    SourceLocation Loc;
11694    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
11695      Var = cast<VarDecl>(DRE->getDecl());
11696      Loc = DRE->getLocation();
11697    } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11698      Var = cast<VarDecl>(ME->getMemberDecl());
11699      Loc = ME->getMemberLoc();
11700    } else {
11701      llvm_unreachable("Unexpcted expression");
11702    }
11703
11704    MarkVarDeclODRUsed(*this, Var, Loc);
11705  }
11706
11707  MaybeODRUseExprs.clear();
11708}
11709
11710// Mark a VarDecl referenced, and perform the necessary handling to compute
11711// odr-uses.
11712static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11713                                    VarDecl *Var, Expr *E) {
11714  Var->setReferenced();
11715
11716  if (!IsPotentiallyEvaluatedContext(SemaRef))
11717    return;
11718
11719  VarTemplateSpecializationDecl *VarSpec =
11720      dyn_cast<VarTemplateSpecializationDecl>(Var);
11721
11722  // Implicit instantiation of static data members, static data member
11723  // templates of class templates, and variable template specializations.
11724  // Delay instantiations of variable templates, except for those
11725  // that could be used in a constant expression.
11726  if (VarSpec || (Var->isStaticDataMember() &&
11727                  Var->getInstantiatedFromStaticDataMember())) {
11728    MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11729    if (VarSpec)
11730      assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
11731             "Can't instantiate a partial template specialization.");
11732    if (Var->isStaticDataMember())
11733      assert(MSInfo && "Missing member specialization information?");
11734
11735    SourceLocation PointOfInstantiation;
11736    bool InstantiationIsOkay = true;
11737    if (MSInfo) {
11738      bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11739      TemplateSpecializationKind TSK = MSInfo->getTemplateSpecializationKind();
11740
11741      if (TSK == TSK_ImplicitInstantiation &&
11742          (!AlreadyInstantiated ||
11743           Var->isUsableInConstantExpressions(SemaRef.Context))) {
11744        if (!AlreadyInstantiated) {
11745          // This is a modification of an existing AST node. Notify listeners.
11746          if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11747            L->StaticDataMemberInstantiated(Var);
11748          MSInfo->setPointOfInstantiation(Loc);
11749        }
11750        PointOfInstantiation = MSInfo->getPointOfInstantiation();
11751      } else
11752        InstantiationIsOkay = false;
11753    } else {
11754      if (VarSpec->getPointOfInstantiation().isInvalid())
11755        VarSpec->setPointOfInstantiation(Loc);
11756      PointOfInstantiation = VarSpec->getPointOfInstantiation();
11757    }
11758
11759    if (InstantiationIsOkay) {
11760      bool InstantiationDependent = false;
11761      bool IsNonDependent =
11762          VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
11763                        VarSpec->getTemplateArgsInfo(), InstantiationDependent)
11764                  : true;
11765
11766      // Do not instantiate specializations that are still type-dependent.
11767      if (IsNonDependent) {
11768        if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
11769          // Do not defer instantiations of variables which could be used in a
11770          // constant expression.
11771          SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
11772        } else {
11773          SemaRef.PendingInstantiations
11774              .push_back(std::make_pair(Var, PointOfInstantiation));
11775        }
11776      }
11777    }
11778  }
11779
11780  // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11781  // the requirements for appearing in a constant expression (5.19) and, if
11782  // it is an object, the lvalue-to-rvalue conversion (4.1)
11783  // is immediately applied."  We check the first part here, and
11784  // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11785  // Note that we use the C++11 definition everywhere because nothing in
11786  // C++03 depends on whether we get the C++03 version correct. The second
11787  // part does not apply to references, since they are not objects.
11788  const VarDecl *DefVD;
11789  if (E && !isa<ParmVarDecl>(Var) &&
11790      Var->isUsableInConstantExpressions(SemaRef.Context) &&
11791      Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11792    if (!Var->getType()->isReferenceType())
11793      SemaRef.MaybeODRUseExprs.insert(E);
11794  } else
11795    MarkVarDeclODRUsed(SemaRef, Var, Loc);
11796}
11797
11798/// \brief Mark a variable referenced, and check whether it is odr-used
11799/// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
11800/// used directly for normal expressions referring to VarDecl.
11801void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11802  DoMarkVarDeclReferenced(*this, Loc, Var, 0);
11803}
11804
11805static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11806                               Decl *D, Expr *E, bool OdrUse) {
11807  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11808    DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11809    return;
11810  }
11811
11812  SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
11813
11814  // If this is a call to a method via a cast, also mark the method in the
11815  // derived class used in case codegen can devirtualize the call.
11816  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11817  if (!ME)
11818    return;
11819  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11820  if (!MD)
11821    return;
11822  const Expr *Base = ME->getBase();
11823  const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
11824  if (!MostDerivedClassDecl)
11825    return;
11826  CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
11827  if (!DM || DM->isPure())
11828    return;
11829  SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
11830}
11831
11832/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11833void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11834  // TODO: update this with DR# once a defect report is filed.
11835  // C++11 defect. The address of a pure member should not be an ODR use, even
11836  // if it's a qualified reference.
11837  bool OdrUse = true;
11838  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
11839    if (Method->isVirtual())
11840      OdrUse = false;
11841  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
11842}
11843
11844/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11845void Sema::MarkMemberReferenced(MemberExpr *E) {
11846  // C++11 [basic.def.odr]p2:
11847  //   A non-overloaded function whose name appears as a potentially-evaluated
11848  //   expression or a member of a set of candidate functions, if selected by
11849  //   overload resolution when referred to from a potentially-evaluated
11850  //   expression, is odr-used, unless it is a pure virtual function and its
11851  //   name is not explicitly qualified.
11852  bool OdrUse = true;
11853  if (!E->hasQualifier()) {
11854    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
11855      if (Method->isPure())
11856        OdrUse = false;
11857  }
11858  SourceLocation Loc = E->getMemberLoc().isValid() ?
11859                            E->getMemberLoc() : E->getLocStart();
11860  MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
11861}
11862
11863/// \brief Perform marking for a reference to an arbitrary declaration.  It
11864/// marks the declaration referenced, and performs odr-use checking for functions
11865/// and variables. This method should not be used when building an normal
11866/// expression which refers to a variable.
11867void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
11868  if (OdrUse) {
11869    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11870      MarkVariableReferenced(Loc, VD);
11871      return;
11872    }
11873    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11874      MarkFunctionReferenced(Loc, FD);
11875      return;
11876    }
11877  }
11878  D->setReferenced();
11879}
11880
11881namespace {
11882  // Mark all of the declarations referenced
11883  // FIXME: Not fully implemented yet! We need to have a better understanding
11884  // of when we're entering
11885  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11886    Sema &S;
11887    SourceLocation Loc;
11888
11889  public:
11890    typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
11891
11892    MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
11893
11894    bool TraverseTemplateArgument(const TemplateArgument &Arg);
11895    bool TraverseRecordType(RecordType *T);
11896  };
11897}
11898
11899bool MarkReferencedDecls::TraverseTemplateArgument(
11900  const TemplateArgument &Arg) {
11901  if (Arg.getKind() == TemplateArgument::Declaration) {
11902    if (Decl *D = Arg.getAsDecl())
11903      S.MarkAnyDeclReferenced(Loc, D, true);
11904  }
11905
11906  return Inherited::TraverseTemplateArgument(Arg);
11907}
11908
11909bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11910  if (ClassTemplateSpecializationDecl *Spec
11911                  = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11912    const TemplateArgumentList &Args = Spec->getTemplateArgs();
11913    return TraverseTemplateArguments(Args.data(), Args.size());
11914  }
11915
11916  return true;
11917}
11918
11919void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11920  MarkReferencedDecls Marker(*this, Loc);
11921  Marker.TraverseType(Context.getCanonicalType(T));
11922}
11923
11924namespace {
11925  /// \brief Helper class that marks all of the declarations referenced by
11926  /// potentially-evaluated subexpressions as "referenced".
11927  class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11928    Sema &S;
11929    bool SkipLocalVariables;
11930
11931  public:
11932    typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11933
11934    EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11935      : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11936
11937    void VisitDeclRefExpr(DeclRefExpr *E) {
11938      // If we were asked not to visit local variables, don't.
11939      if (SkipLocalVariables) {
11940        if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11941          if (VD->hasLocalStorage())
11942            return;
11943      }
11944
11945      S.MarkDeclRefReferenced(E);
11946    }
11947
11948    void VisitMemberExpr(MemberExpr *E) {
11949      S.MarkMemberReferenced(E);
11950      Inherited::VisitMemberExpr(E);
11951    }
11952
11953    void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11954      S.MarkFunctionReferenced(E->getLocStart(),
11955            const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11956      Visit(E->getSubExpr());
11957    }
11958
11959    void VisitCXXNewExpr(CXXNewExpr *E) {
11960      if (E->getOperatorNew())
11961        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11962      if (E->getOperatorDelete())
11963        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11964      Inherited::VisitCXXNewExpr(E);
11965    }
11966
11967    void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11968      if (E->getOperatorDelete())
11969        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11970      QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11971      if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11972        CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11973        S.MarkFunctionReferenced(E->getLocStart(),
11974                                    S.LookupDestructor(Record));
11975      }
11976
11977      Inherited::VisitCXXDeleteExpr(E);
11978    }
11979
11980    void VisitCXXConstructExpr(CXXConstructExpr *E) {
11981      S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11982      Inherited::VisitCXXConstructExpr(E);
11983    }
11984
11985    void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11986      Visit(E->getExpr());
11987    }
11988
11989    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11990      Inherited::VisitImplicitCastExpr(E);
11991
11992      if (E->getCastKind() == CK_LValueToRValue)
11993        S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11994    }
11995  };
11996}
11997
11998/// \brief Mark any declarations that appear within this expression or any
11999/// potentially-evaluated subexpressions as "referenced".
12000///
12001/// \param SkipLocalVariables If true, don't mark local variables as
12002/// 'referenced'.
12003void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12004                                            bool SkipLocalVariables) {
12005  EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12006}
12007
12008/// \brief Emit a diagnostic that describes an effect on the run-time behavior
12009/// of the program being compiled.
12010///
12011/// This routine emits the given diagnostic when the code currently being
12012/// type-checked is "potentially evaluated", meaning that there is a
12013/// possibility that the code will actually be executable. Code in sizeof()
12014/// expressions, code used only during overload resolution, etc., are not
12015/// potentially evaluated. This routine will suppress such diagnostics or,
12016/// in the absolutely nutty case of potentially potentially evaluated
12017/// expressions (C++ typeid), queue the diagnostic to potentially emit it
12018/// later.
12019///
12020/// This routine should be used for all diagnostics that describe the run-time
12021/// behavior of a program, such as passing a non-POD value through an ellipsis.
12022/// Failure to do so will likely result in spurious diagnostics or failures
12023/// during overload resolution or within sizeof/alignof/typeof/typeid.
12024bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12025                               const PartialDiagnostic &PD) {
12026  switch (ExprEvalContexts.back().Context) {
12027  case Unevaluated:
12028  case UnevaluatedAbstract:
12029    // The argument will never be evaluated, so don't complain.
12030    break;
12031
12032  case ConstantEvaluated:
12033    // Relevant diagnostics should be produced by constant evaluation.
12034    break;
12035
12036  case PotentiallyEvaluated:
12037  case PotentiallyEvaluatedIfUsed:
12038    if (Statement && getCurFunctionOrMethodDecl()) {
12039      FunctionScopes.back()->PossiblyUnreachableDiags.
12040        push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12041    }
12042    else
12043      Diag(Loc, PD);
12044
12045    return true;
12046  }
12047
12048  return false;
12049}
12050
12051bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12052                               CallExpr *CE, FunctionDecl *FD) {
12053  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12054    return false;
12055
12056  // If we're inside a decltype's expression, don't check for a valid return
12057  // type or construct temporaries until we know whether this is the last call.
12058  if (ExprEvalContexts.back().IsDecltype) {
12059    ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12060    return false;
12061  }
12062
12063  class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12064    FunctionDecl *FD;
12065    CallExpr *CE;
12066
12067  public:
12068    CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12069      : FD(FD), CE(CE) { }
12070
12071    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
12072      if (!FD) {
12073        S.Diag(Loc, diag::err_call_incomplete_return)
12074          << T << CE->getSourceRange();
12075        return;
12076      }
12077
12078      S.Diag(Loc, diag::err_call_function_incomplete_return)
12079        << CE->getSourceRange() << FD->getDeclName() << T;
12080      S.Diag(FD->getLocation(),
12081             diag::note_function_with_incomplete_return_type_declared_here)
12082        << FD->getDeclName();
12083    }
12084  } Diagnoser(FD, CE);
12085
12086  if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12087    return true;
12088
12089  return false;
12090}
12091
12092// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12093// will prevent this condition from triggering, which is what we want.
12094void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12095  SourceLocation Loc;
12096
12097  unsigned diagnostic = diag::warn_condition_is_assignment;
12098  bool IsOrAssign = false;
12099
12100  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12101    if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12102      return;
12103
12104    IsOrAssign = Op->getOpcode() == BO_OrAssign;
12105
12106    // Greylist some idioms by putting them into a warning subcategory.
12107    if (ObjCMessageExpr *ME
12108          = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12109      Selector Sel = ME->getSelector();
12110
12111      // self = [<foo> init...]
12112      if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12113        diagnostic = diag::warn_condition_is_idiomatic_assignment;
12114
12115      // <foo> = [<bar> nextObject]
12116      else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12117        diagnostic = diag::warn_condition_is_idiomatic_assignment;
12118    }
12119
12120    Loc = Op->getOperatorLoc();
12121  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12122    if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12123      return;
12124
12125    IsOrAssign = Op->getOperator() == OO_PipeEqual;
12126    Loc = Op->getOperatorLoc();
12127  } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12128    return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12129  else {
12130    // Not an assignment.
12131    return;
12132  }
12133
12134  Diag(Loc, diagnostic) << E->getSourceRange();
12135
12136  SourceLocation Open = E->getLocStart();
12137  SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12138  Diag(Loc, diag::note_condition_assign_silence)
12139        << FixItHint::CreateInsertion(Open, "(")
12140        << FixItHint::CreateInsertion(Close, ")");
12141
12142  if (IsOrAssign)
12143    Diag(Loc, diag::note_condition_or_assign_to_comparison)
12144      << FixItHint::CreateReplacement(Loc, "!=");
12145  else
12146    Diag(Loc, diag::note_condition_assign_to_comparison)
12147      << FixItHint::CreateReplacement(Loc, "==");
12148}
12149
12150/// \brief Redundant parentheses over an equality comparison can indicate
12151/// that the user intended an assignment used as condition.
12152void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12153  // Don't warn if the parens came from a macro.
12154  SourceLocation parenLoc = ParenE->getLocStart();
12155  if (parenLoc.isInvalid() || parenLoc.isMacroID())
12156    return;
12157  // Don't warn for dependent expressions.
12158  if (ParenE->isTypeDependent())
12159    return;
12160
12161  Expr *E = ParenE->IgnoreParens();
12162
12163  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12164    if (opE->getOpcode() == BO_EQ &&
12165        opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12166                                                           == Expr::MLV_Valid) {
12167      SourceLocation Loc = opE->getOperatorLoc();
12168
12169      Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12170      SourceRange ParenERange = ParenE->getSourceRange();
12171      Diag(Loc, diag::note_equality_comparison_silence)
12172        << FixItHint::CreateRemoval(ParenERange.getBegin())
12173        << FixItHint::CreateRemoval(ParenERange.getEnd());
12174      Diag(Loc, diag::note_equality_comparison_to_assign)
12175        << FixItHint::CreateReplacement(Loc, "=");
12176    }
12177}
12178
12179ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12180  DiagnoseAssignmentAsCondition(E);
12181  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12182    DiagnoseEqualityWithExtraParens(parenE);
12183
12184  ExprResult result = CheckPlaceholderExpr(E);
12185  if (result.isInvalid()) return ExprError();
12186  E = result.take();
12187
12188  if (!E->isTypeDependent()) {
12189    if (getLangOpts().CPlusPlus)
12190      return CheckCXXBooleanCondition(E); // C++ 6.4p4
12191
12192    ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12193    if (ERes.isInvalid())
12194      return ExprError();
12195    E = ERes.take();
12196
12197    QualType T = E->getType();
12198    if (!T->isScalarType()) { // C99 6.8.4.1p1
12199      Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12200        << T << E->getSourceRange();
12201      return ExprError();
12202    }
12203  }
12204
12205  return Owned(E);
12206}
12207
12208ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12209                                       Expr *SubExpr) {
12210  if (!SubExpr)
12211    return ExprError();
12212
12213  return CheckBooleanCondition(SubExpr, Loc);
12214}
12215
12216namespace {
12217  /// A visitor for rebuilding a call to an __unknown_any expression
12218  /// to have an appropriate type.
12219  struct RebuildUnknownAnyFunction
12220    : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12221
12222    Sema &S;
12223
12224    RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12225
12226    ExprResult VisitStmt(Stmt *S) {
12227      llvm_unreachable("unexpected statement!");
12228    }
12229
12230    ExprResult VisitExpr(Expr *E) {
12231      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12232        << E->getSourceRange();
12233      return ExprError();
12234    }
12235
12236    /// Rebuild an expression which simply semantically wraps another
12237    /// expression which it shares the type and value kind of.
12238    template <class T> ExprResult rebuildSugarExpr(T *E) {
12239      ExprResult SubResult = Visit(E->getSubExpr());
12240      if (SubResult.isInvalid()) return ExprError();
12241
12242      Expr *SubExpr = SubResult.take();
12243      E->setSubExpr(SubExpr);
12244      E->setType(SubExpr->getType());
12245      E->setValueKind(SubExpr->getValueKind());
12246      assert(E->getObjectKind() == OK_Ordinary);
12247      return E;
12248    }
12249
12250    ExprResult VisitParenExpr(ParenExpr *E) {
12251      return rebuildSugarExpr(E);
12252    }
12253
12254    ExprResult VisitUnaryExtension(UnaryOperator *E) {
12255      return rebuildSugarExpr(E);
12256    }
12257
12258    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12259      ExprResult SubResult = Visit(E->getSubExpr());
12260      if (SubResult.isInvalid()) return ExprError();
12261
12262      Expr *SubExpr = SubResult.take();
12263      E->setSubExpr(SubExpr);
12264      E->setType(S.Context.getPointerType(SubExpr->getType()));
12265      assert(E->getValueKind() == VK_RValue);
12266      assert(E->getObjectKind() == OK_Ordinary);
12267      return E;
12268    }
12269
12270    ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12271      if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12272
12273      E->setType(VD->getType());
12274
12275      assert(E->getValueKind() == VK_RValue);
12276      if (S.getLangOpts().CPlusPlus &&
12277          !(isa<CXXMethodDecl>(VD) &&
12278            cast<CXXMethodDecl>(VD)->isInstance()))
12279        E->setValueKind(VK_LValue);
12280
12281      return E;
12282    }
12283
12284    ExprResult VisitMemberExpr(MemberExpr *E) {
12285      return resolveDecl(E, E->getMemberDecl());
12286    }
12287
12288    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12289      return resolveDecl(E, E->getDecl());
12290    }
12291  };
12292}
12293
12294/// Given a function expression of unknown-any type, try to rebuild it
12295/// to have a function type.
12296static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12297  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12298  if (Result.isInvalid()) return ExprError();
12299  return S.DefaultFunctionArrayConversion(Result.take());
12300}
12301
12302namespace {
12303  /// A visitor for rebuilding an expression of type __unknown_anytype
12304  /// into one which resolves the type directly on the referring
12305  /// expression.  Strict preservation of the original source
12306  /// structure is not a goal.
12307  struct RebuildUnknownAnyExpr
12308    : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12309
12310    Sema &S;
12311
12312    /// The current destination type.
12313    QualType DestType;
12314
12315    RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12316      : S(S), DestType(CastType) {}
12317
12318    ExprResult VisitStmt(Stmt *S) {
12319      llvm_unreachable("unexpected statement!");
12320    }
12321
12322    ExprResult VisitExpr(Expr *E) {
12323      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12324        << E->getSourceRange();
12325      return ExprError();
12326    }
12327
12328    ExprResult VisitCallExpr(CallExpr *E);
12329    ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12330
12331    /// Rebuild an expression which simply semantically wraps another
12332    /// expression which it shares the type and value kind of.
12333    template <class T> ExprResult rebuildSugarExpr(T *E) {
12334      ExprResult SubResult = Visit(E->getSubExpr());
12335      if (SubResult.isInvalid()) return ExprError();
12336      Expr *SubExpr = SubResult.take();
12337      E->setSubExpr(SubExpr);
12338      E->setType(SubExpr->getType());
12339      E->setValueKind(SubExpr->getValueKind());
12340      assert(E->getObjectKind() == OK_Ordinary);
12341      return E;
12342    }
12343
12344    ExprResult VisitParenExpr(ParenExpr *E) {
12345      return rebuildSugarExpr(E);
12346    }
12347
12348    ExprResult VisitUnaryExtension(UnaryOperator *E) {
12349      return rebuildSugarExpr(E);
12350    }
12351
12352    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12353      const PointerType *Ptr = DestType->getAs<PointerType>();
12354      if (!Ptr) {
12355        S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12356          << E->getSourceRange();
12357        return ExprError();
12358      }
12359      assert(E->getValueKind() == VK_RValue);
12360      assert(E->getObjectKind() == OK_Ordinary);
12361      E->setType(DestType);
12362
12363      // Build the sub-expression as if it were an object of the pointee type.
12364      DestType = Ptr->getPointeeType();
12365      ExprResult SubResult = Visit(E->getSubExpr());
12366      if (SubResult.isInvalid()) return ExprError();
12367      E->setSubExpr(SubResult.take());
12368      return E;
12369    }
12370
12371    ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12372
12373    ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12374
12375    ExprResult VisitMemberExpr(MemberExpr *E) {
12376      return resolveDecl(E, E->getMemberDecl());
12377    }
12378
12379    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12380      return resolveDecl(E, E->getDecl());
12381    }
12382  };
12383}
12384
12385/// Rebuilds a call expression which yielded __unknown_anytype.
12386ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12387  Expr *CalleeExpr = E->getCallee();
12388
12389  enum FnKind {
12390    FK_MemberFunction,
12391    FK_FunctionPointer,
12392    FK_BlockPointer
12393  };
12394
12395  FnKind Kind;
12396  QualType CalleeType = CalleeExpr->getType();
12397  if (CalleeType == S.Context.BoundMemberTy) {
12398    assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12399    Kind = FK_MemberFunction;
12400    CalleeType = Expr::findBoundMemberType(CalleeExpr);
12401  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12402    CalleeType = Ptr->getPointeeType();
12403    Kind = FK_FunctionPointer;
12404  } else {
12405    CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12406    Kind = FK_BlockPointer;
12407  }
12408  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12409
12410  // Verify that this is a legal result type of a function.
12411  if (DestType->isArrayType() || DestType->isFunctionType()) {
12412    unsigned diagID = diag::err_func_returning_array_function;
12413    if (Kind == FK_BlockPointer)
12414      diagID = diag::err_block_returning_array_function;
12415
12416    S.Diag(E->getExprLoc(), diagID)
12417      << DestType->isFunctionType() << DestType;
12418    return ExprError();
12419  }
12420
12421  // Otherwise, go ahead and set DestType as the call's result.
12422  E->setType(DestType.getNonLValueExprType(S.Context));
12423  E->setValueKind(Expr::getValueKindForType(DestType));
12424  assert(E->getObjectKind() == OK_Ordinary);
12425
12426  // Rebuild the function type, replacing the result type with DestType.
12427  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12428  if (Proto) {
12429    // __unknown_anytype(...) is a special case used by the debugger when
12430    // it has no idea what a function's signature is.
12431    //
12432    // We want to build this call essentially under the K&R
12433    // unprototyped rules, but making a FunctionNoProtoType in C++
12434    // would foul up all sorts of assumptions.  However, we cannot
12435    // simply pass all arguments as variadic arguments, nor can we
12436    // portably just call the function under a non-variadic type; see
12437    // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12438    // However, it turns out that in practice it is generally safe to
12439    // call a function declared as "A foo(B,C,D);" under the prototype
12440    // "A foo(B,C,D,...);".  The only known exception is with the
12441    // Windows ABI, where any variadic function is implicitly cdecl
12442    // regardless of its normal CC.  Therefore we change the parameter
12443    // types to match the types of the arguments.
12444    //
12445    // This is a hack, but it is far superior to moving the
12446    // corresponding target-specific code from IR-gen to Sema/AST.
12447
12448    ArrayRef<QualType> ParamTypes = Proto->getArgTypes();
12449    SmallVector<QualType, 8> ArgTypes;
12450    if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12451      ArgTypes.reserve(E->getNumArgs());
12452      for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12453        Expr *Arg = E->getArg(i);
12454        QualType ArgType = Arg->getType();
12455        if (E->isLValue()) {
12456          ArgType = S.Context.getLValueReferenceType(ArgType);
12457        } else if (E->isXValue()) {
12458          ArgType = S.Context.getRValueReferenceType(ArgType);
12459        }
12460        ArgTypes.push_back(ArgType);
12461      }
12462      ParamTypes = ArgTypes;
12463    }
12464    DestType = S.Context.getFunctionType(DestType, ParamTypes,
12465                                         Proto->getExtProtoInfo());
12466  } else {
12467    DestType = S.Context.getFunctionNoProtoType(DestType,
12468                                                FnType->getExtInfo());
12469  }
12470
12471  // Rebuild the appropriate pointer-to-function type.
12472  switch (Kind) {
12473  case FK_MemberFunction:
12474    // Nothing to do.
12475    break;
12476
12477  case FK_FunctionPointer:
12478    DestType = S.Context.getPointerType(DestType);
12479    break;
12480
12481  case FK_BlockPointer:
12482    DestType = S.Context.getBlockPointerType(DestType);
12483    break;
12484  }
12485
12486  // Finally, we can recurse.
12487  ExprResult CalleeResult = Visit(CalleeExpr);
12488  if (!CalleeResult.isUsable()) return ExprError();
12489  E->setCallee(CalleeResult.take());
12490
12491  // Bind a temporary if necessary.
12492  return S.MaybeBindToTemporary(E);
12493}
12494
12495ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12496  // Verify that this is a legal result type of a call.
12497  if (DestType->isArrayType() || DestType->isFunctionType()) {
12498    S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
12499      << DestType->isFunctionType() << DestType;
12500    return ExprError();
12501  }
12502
12503  // Rewrite the method result type if available.
12504  if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12505    assert(Method->getResultType() == S.Context.UnknownAnyTy);
12506    Method->setResultType(DestType);
12507  }
12508
12509  // Change the type of the message.
12510  E->setType(DestType.getNonReferenceType());
12511  E->setValueKind(Expr::getValueKindForType(DestType));
12512
12513  return S.MaybeBindToTemporary(E);
12514}
12515
12516ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
12517  // The only case we should ever see here is a function-to-pointer decay.
12518  if (E->getCastKind() == CK_FunctionToPointerDecay) {
12519    assert(E->getValueKind() == VK_RValue);
12520    assert(E->getObjectKind() == OK_Ordinary);
12521
12522    E->setType(DestType);
12523
12524    // Rebuild the sub-expression as the pointee (function) type.
12525    DestType = DestType->castAs<PointerType>()->getPointeeType();
12526
12527    ExprResult Result = Visit(E->getSubExpr());
12528    if (!Result.isUsable()) return ExprError();
12529
12530    E->setSubExpr(Result.take());
12531    return S.Owned(E);
12532  } else if (E->getCastKind() == CK_LValueToRValue) {
12533    assert(E->getValueKind() == VK_RValue);
12534    assert(E->getObjectKind() == OK_Ordinary);
12535
12536    assert(isa<BlockPointerType>(E->getType()));
12537
12538    E->setType(DestType);
12539
12540    // The sub-expression has to be a lvalue reference, so rebuild it as such.
12541    DestType = S.Context.getLValueReferenceType(DestType);
12542
12543    ExprResult Result = Visit(E->getSubExpr());
12544    if (!Result.isUsable()) return ExprError();
12545
12546    E->setSubExpr(Result.take());
12547    return S.Owned(E);
12548  } else {
12549    llvm_unreachable("Unhandled cast type!");
12550  }
12551}
12552
12553ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12554  ExprValueKind ValueKind = VK_LValue;
12555  QualType Type = DestType;
12556
12557  // We know how to make this work for certain kinds of decls:
12558
12559  //  - functions
12560  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12561    if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12562      DestType = Ptr->getPointeeType();
12563      ExprResult Result = resolveDecl(E, VD);
12564      if (Result.isInvalid()) return ExprError();
12565      return S.ImpCastExprToType(Result.take(), Type,
12566                                 CK_FunctionToPointerDecay, VK_RValue);
12567    }
12568
12569    if (!Type->isFunctionType()) {
12570      S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12571        << VD << E->getSourceRange();
12572      return ExprError();
12573    }
12574
12575    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12576      if (MD->isInstance()) {
12577        ValueKind = VK_RValue;
12578        Type = S.Context.BoundMemberTy;
12579      }
12580
12581    // Function references aren't l-values in C.
12582    if (!S.getLangOpts().CPlusPlus)
12583      ValueKind = VK_RValue;
12584
12585  //  - variables
12586  } else if (isa<VarDecl>(VD)) {
12587    if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12588      Type = RefTy->getPointeeType();
12589    } else if (Type->isFunctionType()) {
12590      S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12591        << VD << E->getSourceRange();
12592      return ExprError();
12593    }
12594
12595  //  - nothing else
12596  } else {
12597    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12598      << VD << E->getSourceRange();
12599    return ExprError();
12600  }
12601
12602  // Modifying the declaration like this is friendly to IR-gen but
12603  // also really dangerous.
12604  VD->setType(DestType);
12605  E->setType(Type);
12606  E->setValueKind(ValueKind);
12607  return S.Owned(E);
12608}
12609
12610/// Check a cast of an unknown-any type.  We intentionally only
12611/// trigger this for C-style casts.
12612ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12613                                     Expr *CastExpr, CastKind &CastKind,
12614                                     ExprValueKind &VK, CXXCastPath &Path) {
12615  // Rewrite the casted expression from scratch.
12616  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
12617  if (!result.isUsable()) return ExprError();
12618
12619  CastExpr = result.take();
12620  VK = CastExpr->getValueKind();
12621  CastKind = CK_NoOp;
12622
12623  return CastExpr;
12624}
12625
12626ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12627  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12628}
12629
12630ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12631                                    Expr *arg, QualType &paramType) {
12632  // If the syntactic form of the argument is not an explicit cast of
12633  // any sort, just do default argument promotion.
12634  ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12635  if (!castArg) {
12636    ExprResult result = DefaultArgumentPromotion(arg);
12637    if (result.isInvalid()) return ExprError();
12638    paramType = result.get()->getType();
12639    return result;
12640  }
12641
12642  // Otherwise, use the type that was written in the explicit cast.
12643  assert(!arg->hasPlaceholderType());
12644  paramType = castArg->getTypeAsWritten();
12645
12646  // Copy-initialize a parameter of that type.
12647  InitializedEntity entity =
12648    InitializedEntity::InitializeParameter(Context, paramType,
12649                                           /*consumed*/ false);
12650  return PerformCopyInitialization(entity, callLoc, Owned(arg));
12651}
12652
12653static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12654  Expr *orig = E;
12655  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
12656  while (true) {
12657    E = E->IgnoreParenImpCasts();
12658    if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12659      E = call->getCallee();
12660      diagID = diag::err_uncasted_call_of_unknown_any;
12661    } else {
12662      break;
12663    }
12664  }
12665
12666  SourceLocation loc;
12667  NamedDecl *d;
12668  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
12669    loc = ref->getLocation();
12670    d = ref->getDecl();
12671  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
12672    loc = mem->getMemberLoc();
12673    d = mem->getMemberDecl();
12674  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
12675    diagID = diag::err_uncasted_call_of_unknown_any;
12676    loc = msg->getSelectorStartLoc();
12677    d = msg->getMethodDecl();
12678    if (!d) {
12679      S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12680        << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12681        << orig->getSourceRange();
12682      return ExprError();
12683    }
12684  } else {
12685    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12686      << E->getSourceRange();
12687    return ExprError();
12688  }
12689
12690  S.Diag(loc, diagID) << d << orig->getSourceRange();
12691
12692  // Never recoverable.
12693  return ExprError();
12694}
12695
12696/// Check for operands with placeholder types and complain if found.
12697/// Returns true if there was an error and no recovery was possible.
12698ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
12699  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12700  if (!placeholderType) return Owned(E);
12701
12702  switch (placeholderType->getKind()) {
12703
12704  // Overloaded expressions.
12705  case BuiltinType::Overload: {
12706    // Try to resolve a single function template specialization.
12707    // This is obligatory.
12708    ExprResult result = Owned(E);
12709    if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12710      return result;
12711
12712    // If that failed, try to recover with a call.
12713    } else {
12714      tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12715                           /*complain*/ true);
12716      return result;
12717    }
12718  }
12719
12720  // Bound member functions.
12721  case BuiltinType::BoundMember: {
12722    ExprResult result = Owned(E);
12723    tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12724                         /*complain*/ true);
12725    return result;
12726  }
12727
12728  // ARC unbridged casts.
12729  case BuiltinType::ARCUnbridgedCast: {
12730    Expr *realCast = stripARCUnbridgedCast(E);
12731    diagnoseARCUnbridgedCast(realCast);
12732    return Owned(realCast);
12733  }
12734
12735  // Expressions of unknown type.
12736  case BuiltinType::UnknownAny:
12737    return diagnoseUnknownAnyExpr(*this, E);
12738
12739  // Pseudo-objects.
12740  case BuiltinType::PseudoObject:
12741    return checkPseudoObjectRValue(E);
12742
12743  case BuiltinType::BuiltinFn:
12744    Diag(E->getLocStart(), diag::err_builtin_fn_use);
12745    return ExprError();
12746
12747  // Everything else should be impossible.
12748#define BUILTIN_TYPE(Id, SingletonId) \
12749  case BuiltinType::Id:
12750#define PLACEHOLDER_TYPE(Id, SingletonId)
12751#include "clang/AST/BuiltinTypes.def"
12752    break;
12753  }
12754
12755  llvm_unreachable("invalid placeholder type!");
12756}
12757
12758bool Sema::CheckCaseExpression(Expr *E) {
12759  if (E->isTypeDependent())
12760    return true;
12761  if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12762    return E->getType()->isIntegralOrEnumerationType();
12763  return false;
12764}
12765
12766/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12767ExprResult
12768Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12769  assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12770         "Unknown Objective-C Boolean value!");
12771  QualType BoolT = Context.ObjCBuiltinBoolTy;
12772  if (!Context.getBOOLDecl()) {
12773    LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
12774                        Sema::LookupOrdinaryName);
12775    if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
12776      NamedDecl *ND = Result.getFoundDecl();
12777      if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12778        Context.setBOOLDecl(TD);
12779    }
12780  }
12781  if (Context.getBOOLDecl())
12782    BoolT = Context.getBOOLType();
12783  return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
12784                                        BoolT, OpLoc));
12785}
12786