]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / tools / clang / lib / Sema / SemaOverload.cpp
1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
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 provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Template.h"
18 #include "clang/Sema/TemplateDeduction.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CXXInheritance.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include <algorithm>
33
34 namespace clang {
35 using namespace sema;
36
37 /// A convenience routine for creating a decayed reference to a
38 /// function.
39 static ExprResult
40 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
41                       SourceLocation Loc = SourceLocation(), 
42                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
43   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44                                                  VK_LValue, Loc, LocInfo);
45   if (HadMultipleCandidates)
46     DRE->setHadMultipleCandidates(true);
47   ExprResult E = S.Owned(DRE);
48   E = S.DefaultFunctionArrayConversion(E.take());
49   if (E.isInvalid())
50     return ExprError();
51   return move(E);
52 }
53
54 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55                                  bool InOverloadResolution,
56                                  StandardConversionSequence &SCS,
57                                  bool CStyle,
58                                  bool AllowObjCWritebackConversion);
59   
60 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 
61                                                  QualType &ToType,
62                                                  bool InOverloadResolution,
63                                                  StandardConversionSequence &SCS,
64                                                  bool CStyle);
65 static OverloadingResult
66 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67                         UserDefinedConversionSequence& User,
68                         OverloadCandidateSet& Conversions,
69                         bool AllowExplicit);
70
71
72 static ImplicitConversionSequence::CompareKind
73 CompareStandardConversionSequences(Sema &S,
74                                    const StandardConversionSequence& SCS1,
75                                    const StandardConversionSequence& SCS2);
76
77 static ImplicitConversionSequence::CompareKind
78 CompareQualificationConversions(Sema &S,
79                                 const StandardConversionSequence& SCS1,
80                                 const StandardConversionSequence& SCS2);
81
82 static ImplicitConversionSequence::CompareKind
83 CompareDerivedToBaseConversions(Sema &S,
84                                 const StandardConversionSequence& SCS1,
85                                 const StandardConversionSequence& SCS2);
86
87
88
89 /// GetConversionCategory - Retrieve the implicit conversion
90 /// category corresponding to the given implicit conversion kind.
91 ImplicitConversionCategory
92 GetConversionCategory(ImplicitConversionKind Kind) {
93   static const ImplicitConversionCategory
94     Category[(int)ICK_Num_Conversion_Kinds] = {
95     ICC_Identity,
96     ICC_Lvalue_Transformation,
97     ICC_Lvalue_Transformation,
98     ICC_Lvalue_Transformation,
99     ICC_Identity,
100     ICC_Qualification_Adjustment,
101     ICC_Promotion,
102     ICC_Promotion,
103     ICC_Promotion,
104     ICC_Conversion,
105     ICC_Conversion,
106     ICC_Conversion,
107     ICC_Conversion,
108     ICC_Conversion,
109     ICC_Conversion,
110     ICC_Conversion,
111     ICC_Conversion,
112     ICC_Conversion,
113     ICC_Conversion,
114     ICC_Conversion,
115     ICC_Conversion,
116     ICC_Conversion
117   };
118   return Category[(int)Kind];
119 }
120
121 /// GetConversionRank - Retrieve the implicit conversion rank
122 /// corresponding to the given implicit conversion kind.
123 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124   static const ImplicitConversionRank
125     Rank[(int)ICK_Num_Conversion_Kinds] = {
126     ICR_Exact_Match,
127     ICR_Exact_Match,
128     ICR_Exact_Match,
129     ICR_Exact_Match,
130     ICR_Exact_Match,
131     ICR_Exact_Match,
132     ICR_Promotion,
133     ICR_Promotion,
134     ICR_Promotion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Conversion,
146     ICR_Complex_Real_Conversion,
147     ICR_Conversion,
148     ICR_Conversion,
149     ICR_Writeback_Conversion
150   };
151   return Rank[(int)Kind];
152 }
153
154 /// GetImplicitConversionName - Return the name of this kind of
155 /// implicit conversion.
156 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
157   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158     "No conversion",
159     "Lvalue-to-rvalue",
160     "Array-to-pointer",
161     "Function-to-pointer",
162     "Noreturn adjustment",
163     "Qualification",
164     "Integral promotion",
165     "Floating point promotion",
166     "Complex promotion",
167     "Integral conversion",
168     "Floating conversion",
169     "Complex conversion",
170     "Floating-integral conversion",
171     "Pointer conversion",
172     "Pointer-to-member conversion",
173     "Boolean conversion",
174     "Compatible-types conversion",
175     "Derived-to-base conversion",
176     "Vector conversion",
177     "Vector splat",
178     "Complex-real conversion",
179     "Block Pointer conversion",
180     "Transparent Union Conversion"
181     "Writeback conversion"
182   };
183   return Name[Kind];
184 }
185
186 /// StandardConversionSequence - Set the standard conversion
187 /// sequence to the identity conversion.
188 void StandardConversionSequence::setAsIdentityConversion() {
189   First = ICK_Identity;
190   Second = ICK_Identity;
191   Third = ICK_Identity;
192   DeprecatedStringLiteralToCharPtr = false;
193   QualificationIncludesObjCLifetime = false;
194   ReferenceBinding = false;
195   DirectBinding = false;
196   IsLvalueReference = true;
197   BindsToFunctionLvalue = false;
198   BindsToRvalue = false;
199   BindsImplicitObjectArgumentWithoutRefQualifier = false;
200   ObjCLifetimeConversionBinding = false;
201   CopyConstructor = 0;
202 }
203
204 /// getRank - Retrieve the rank of this standard conversion sequence
205 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206 /// implicit conversions.
207 ImplicitConversionRank StandardConversionSequence::getRank() const {
208   ImplicitConversionRank Rank = ICR_Exact_Match;
209   if  (GetConversionRank(First) > Rank)
210     Rank = GetConversionRank(First);
211   if  (GetConversionRank(Second) > Rank)
212     Rank = GetConversionRank(Second);
213   if  (GetConversionRank(Third) > Rank)
214     Rank = GetConversionRank(Third);
215   return Rank;
216 }
217
218 /// isPointerConversionToBool - Determines whether this conversion is
219 /// a conversion of a pointer or pointer-to-member to bool. This is
220 /// used as part of the ranking of standard conversion sequences
221 /// (C++ 13.3.3.2p4).
222 bool StandardConversionSequence::isPointerConversionToBool() const {
223   // Note that FromType has not necessarily been transformed by the
224   // array-to-pointer or function-to-pointer implicit conversions, so
225   // check for their presence as well as checking whether FromType is
226   // a pointer.
227   if (getToType(1)->isBooleanType() &&
228       (getFromType()->isPointerType() ||
229        getFromType()->isObjCObjectPointerType() ||
230        getFromType()->isBlockPointerType() ||
231        getFromType()->isNullPtrType() ||
232        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233     return true;
234
235   return false;
236 }
237
238 /// isPointerConversionToVoidPointer - Determines whether this
239 /// conversion is a conversion of a pointer to a void pointer. This is
240 /// used as part of the ranking of standard conversion sequences (C++
241 /// 13.3.3.2p4).
242 bool
243 StandardConversionSequence::
244 isPointerConversionToVoidPointer(ASTContext& Context) const {
245   QualType FromType = getFromType();
246   QualType ToType = getToType(1);
247
248   // Note that FromType has not necessarily been transformed by the
249   // array-to-pointer implicit conversion, so check for its presence
250   // and redo the conversion to get a pointer.
251   if (First == ICK_Array_To_Pointer)
252     FromType = Context.getArrayDecayedType(FromType);
253
254   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
255     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
256       return ToPtrType->getPointeeType()->isVoidType();
257
258   return false;
259 }
260
261 /// DebugPrint - Print this standard conversion sequence to standard
262 /// error. Useful for debugging overloading issues.
263 void StandardConversionSequence::DebugPrint() const {
264   raw_ostream &OS = llvm::errs();
265   bool PrintedSomething = false;
266   if (First != ICK_Identity) {
267     OS << GetImplicitConversionName(First);
268     PrintedSomething = true;
269   }
270
271   if (Second != ICK_Identity) {
272     if (PrintedSomething) {
273       OS << " -> ";
274     }
275     OS << GetImplicitConversionName(Second);
276
277     if (CopyConstructor) {
278       OS << " (by copy constructor)";
279     } else if (DirectBinding) {
280       OS << " (direct reference binding)";
281     } else if (ReferenceBinding) {
282       OS << " (reference binding)";
283     }
284     PrintedSomething = true;
285   }
286
287   if (Third != ICK_Identity) {
288     if (PrintedSomething) {
289       OS << " -> ";
290     }
291     OS << GetImplicitConversionName(Third);
292     PrintedSomething = true;
293   }
294
295   if (!PrintedSomething) {
296     OS << "No conversions required";
297   }
298 }
299
300 /// DebugPrint - Print this user-defined conversion sequence to standard
301 /// error. Useful for debugging overloading issues.
302 void UserDefinedConversionSequence::DebugPrint() const {
303   raw_ostream &OS = llvm::errs();
304   if (Before.First || Before.Second || Before.Third) {
305     Before.DebugPrint();
306     OS << " -> ";
307   }
308   OS << '\'' << *ConversionFunction << '\'';
309   if (After.First || After.Second || After.Third) {
310     OS << " -> ";
311     After.DebugPrint();
312   }
313 }
314
315 /// DebugPrint - Print this implicit conversion sequence to standard
316 /// error. Useful for debugging overloading issues.
317 void ImplicitConversionSequence::DebugPrint() const {
318   raw_ostream &OS = llvm::errs();
319   switch (ConversionKind) {
320   case StandardConversion:
321     OS << "Standard conversion: ";
322     Standard.DebugPrint();
323     break;
324   case UserDefinedConversion:
325     OS << "User-defined conversion: ";
326     UserDefined.DebugPrint();
327     break;
328   case EllipsisConversion:
329     OS << "Ellipsis conversion";
330     break;
331   case AmbiguousConversion:
332     OS << "Ambiguous conversion";
333     break;
334   case BadConversion:
335     OS << "Bad conversion";
336     break;
337   }
338
339   OS << "\n";
340 }
341
342 void AmbiguousConversionSequence::construct() {
343   new (&conversions()) ConversionSet();
344 }
345
346 void AmbiguousConversionSequence::destruct() {
347   conversions().~ConversionSet();
348 }
349
350 void
351 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
352   FromTypePtr = O.FromTypePtr;
353   ToTypePtr = O.ToTypePtr;
354   new (&conversions()) ConversionSet(O.conversions());
355 }
356
357 namespace {
358   // Structure used by OverloadCandidate::DeductionFailureInfo to store
359   // template parameter and template argument information.
360   struct DFIParamWithArguments {
361     TemplateParameter Param;
362     TemplateArgument FirstArg;
363     TemplateArgument SecondArg;
364   };
365 }
366
367 /// \brief Convert from Sema's representation of template deduction information
368 /// to the form used in overload-candidate information.
369 OverloadCandidate::DeductionFailureInfo
370 static MakeDeductionFailureInfo(ASTContext &Context,
371                                 Sema::TemplateDeductionResult TDK,
372                                 TemplateDeductionInfo &Info) {
373   OverloadCandidate::DeductionFailureInfo Result;
374   Result.Result = static_cast<unsigned>(TDK);
375   Result.Data = 0;
376   switch (TDK) {
377   case Sema::TDK_Success:
378   case Sema::TDK_InstantiationDepth:
379   case Sema::TDK_TooManyArguments:
380   case Sema::TDK_TooFewArguments:
381     break;
382
383   case Sema::TDK_Incomplete:
384   case Sema::TDK_InvalidExplicitArguments:
385     Result.Data = Info.Param.getOpaqueValue();
386     break;
387
388   case Sema::TDK_Inconsistent:
389   case Sema::TDK_Underqualified: {
390     // FIXME: Should allocate from normal heap so that we can free this later.
391     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
392     Saved->Param = Info.Param;
393     Saved->FirstArg = Info.FirstArg;
394     Saved->SecondArg = Info.SecondArg;
395     Result.Data = Saved;
396     break;
397   }
398
399   case Sema::TDK_SubstitutionFailure:
400     Result.Data = Info.take();
401     break;
402
403   case Sema::TDK_NonDeducedMismatch:
404   case Sema::TDK_FailedOverloadResolution:
405     break;
406   }
407
408   return Result;
409 }
410
411 void OverloadCandidate::DeductionFailureInfo::Destroy() {
412   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
413   case Sema::TDK_Success:
414   case Sema::TDK_InstantiationDepth:
415   case Sema::TDK_Incomplete:
416   case Sema::TDK_TooManyArguments:
417   case Sema::TDK_TooFewArguments:
418   case Sema::TDK_InvalidExplicitArguments:
419     break;
420
421   case Sema::TDK_Inconsistent:
422   case Sema::TDK_Underqualified:
423     // FIXME: Destroy the data?
424     Data = 0;
425     break;
426
427   case Sema::TDK_SubstitutionFailure:
428     // FIXME: Destroy the template arugment list?
429     Data = 0;
430     break;
431
432   // Unhandled
433   case Sema::TDK_NonDeducedMismatch:
434   case Sema::TDK_FailedOverloadResolution:
435     break;
436   }
437 }
438
439 TemplateParameter
440 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
441   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
442   case Sema::TDK_Success:
443   case Sema::TDK_InstantiationDepth:
444   case Sema::TDK_TooManyArguments:
445   case Sema::TDK_TooFewArguments:
446   case Sema::TDK_SubstitutionFailure:
447     return TemplateParameter();
448
449   case Sema::TDK_Incomplete:
450   case Sema::TDK_InvalidExplicitArguments:
451     return TemplateParameter::getFromOpaqueValue(Data);
452
453   case Sema::TDK_Inconsistent:
454   case Sema::TDK_Underqualified:
455     return static_cast<DFIParamWithArguments*>(Data)->Param;
456
457   // Unhandled
458   case Sema::TDK_NonDeducedMismatch:
459   case Sema::TDK_FailedOverloadResolution:
460     break;
461   }
462
463   return TemplateParameter();
464 }
465
466 TemplateArgumentList *
467 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
468   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
469     case Sema::TDK_Success:
470     case Sema::TDK_InstantiationDepth:
471     case Sema::TDK_TooManyArguments:
472     case Sema::TDK_TooFewArguments:
473     case Sema::TDK_Incomplete:
474     case Sema::TDK_InvalidExplicitArguments:
475     case Sema::TDK_Inconsistent:
476     case Sema::TDK_Underqualified:
477       return 0;
478
479     case Sema::TDK_SubstitutionFailure:
480       return static_cast<TemplateArgumentList*>(Data);
481
482     // Unhandled
483     case Sema::TDK_NonDeducedMismatch:
484     case Sema::TDK_FailedOverloadResolution:
485       break;
486   }
487
488   return 0;
489 }
490
491 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
492   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
493   case Sema::TDK_Success:
494   case Sema::TDK_InstantiationDepth:
495   case Sema::TDK_Incomplete:
496   case Sema::TDK_TooManyArguments:
497   case Sema::TDK_TooFewArguments:
498   case Sema::TDK_InvalidExplicitArguments:
499   case Sema::TDK_SubstitutionFailure:
500     return 0;
501
502   case Sema::TDK_Inconsistent:
503   case Sema::TDK_Underqualified:
504     return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
505
506   // Unhandled
507   case Sema::TDK_NonDeducedMismatch:
508   case Sema::TDK_FailedOverloadResolution:
509     break;
510   }
511
512   return 0;
513 }
514
515 const TemplateArgument *
516 OverloadCandidate::DeductionFailureInfo::getSecondArg() {
517   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
518   case Sema::TDK_Success:
519   case Sema::TDK_InstantiationDepth:
520   case Sema::TDK_Incomplete:
521   case Sema::TDK_TooManyArguments:
522   case Sema::TDK_TooFewArguments:
523   case Sema::TDK_InvalidExplicitArguments:
524   case Sema::TDK_SubstitutionFailure:
525     return 0;
526
527   case Sema::TDK_Inconsistent:
528   case Sema::TDK_Underqualified:
529     return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
530
531   // Unhandled
532   case Sema::TDK_NonDeducedMismatch:
533   case Sema::TDK_FailedOverloadResolution:
534     break;
535   }
536
537   return 0;
538 }
539
540 void OverloadCandidateSet::clear() {
541   inherited::clear();
542   Functions.clear();
543 }
544
545 // IsOverload - Determine whether the given New declaration is an
546 // overload of the declarations in Old. This routine returns false if
547 // New and Old cannot be overloaded, e.g., if New has the same
548 // signature as some function in Old (C++ 1.3.10) or if the Old
549 // declarations aren't functions (or function templates) at all. When
550 // it does return false, MatchedDecl will point to the decl that New
551 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
552 // top of the underlying declaration.
553 //
554 // Example: Given the following input:
555 //
556 //   void f(int, float); // #1
557 //   void f(int, int); // #2
558 //   int f(int, int); // #3
559 //
560 // When we process #1, there is no previous declaration of "f",
561 // so IsOverload will not be used.
562 //
563 // When we process #2, Old contains only the FunctionDecl for #1.  By
564 // comparing the parameter types, we see that #1 and #2 are overloaded
565 // (since they have different signatures), so this routine returns
566 // false; MatchedDecl is unchanged.
567 //
568 // When we process #3, Old is an overload set containing #1 and #2. We
569 // compare the signatures of #3 to #1 (they're overloaded, so we do
570 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
571 // identical (return types of functions are not part of the
572 // signature), IsOverload returns false and MatchedDecl will be set to
573 // point to the FunctionDecl for #2.
574 //
575 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
576 // into a class by a using declaration.  The rules for whether to hide
577 // shadow declarations ignore some properties which otherwise figure
578 // into a function template's signature.
579 Sema::OverloadKind
580 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
581                     NamedDecl *&Match, bool NewIsUsingDecl) {
582   for (LookupResult::iterator I = Old.begin(), E = Old.end();
583          I != E; ++I) {
584     NamedDecl *OldD = *I;
585
586     bool OldIsUsingDecl = false;
587     if (isa<UsingShadowDecl>(OldD)) {
588       OldIsUsingDecl = true;
589
590       // We can always introduce two using declarations into the same
591       // context, even if they have identical signatures.
592       if (NewIsUsingDecl) continue;
593
594       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
595     }
596
597     // If either declaration was introduced by a using declaration,
598     // we'll need to use slightly different rules for matching.
599     // Essentially, these rules are the normal rules, except that
600     // function templates hide function templates with different
601     // return types or template parameter lists.
602     bool UseMemberUsingDeclRules =
603       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
604
605     if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
606       if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
607         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
608           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
609           continue;
610         }
611
612         Match = *I;
613         return Ovl_Match;
614       }
615     } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
616       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
617         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
618           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
619           continue;
620         }
621
622         Match = *I;
623         return Ovl_Match;
624       }
625     } else if (isa<UsingDecl>(OldD)) {
626       // We can overload with these, which can show up when doing
627       // redeclaration checks for UsingDecls.
628       assert(Old.getLookupKind() == LookupUsingDeclName);
629     } else if (isa<TagDecl>(OldD)) {
630       // We can always overload with tags by hiding them.
631     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
632       // Optimistically assume that an unresolved using decl will
633       // overload; if it doesn't, we'll have to diagnose during
634       // template instantiation.
635     } else {
636       // (C++ 13p1):
637       //   Only function declarations can be overloaded; object and type
638       //   declarations cannot be overloaded.
639       Match = *I;
640       return Ovl_NonFunction;
641     }
642   }
643
644   return Ovl_Overload;
645 }
646
647 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
648                       bool UseUsingDeclRules) {
649   // If both of the functions are extern "C", then they are not
650   // overloads.
651   if (Old->isExternC() && New->isExternC())
652     return false;
653
654   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
655   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
656
657   // C++ [temp.fct]p2:
658   //   A function template can be overloaded with other function templates
659   //   and with normal (non-template) functions.
660   if ((OldTemplate == 0) != (NewTemplate == 0))
661     return true;
662
663   // Is the function New an overload of the function Old?
664   QualType OldQType = Context.getCanonicalType(Old->getType());
665   QualType NewQType = Context.getCanonicalType(New->getType());
666
667   // Compare the signatures (C++ 1.3.10) of the two functions to
668   // determine whether they are overloads. If we find any mismatch
669   // in the signature, they are overloads.
670
671   // If either of these functions is a K&R-style function (no
672   // prototype), then we consider them to have matching signatures.
673   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
674       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
675     return false;
676
677   const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
678   const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
679
680   // The signature of a function includes the types of its
681   // parameters (C++ 1.3.10), which includes the presence or absence
682   // of the ellipsis; see C++ DR 357).
683   if (OldQType != NewQType &&
684       (OldType->getNumArgs() != NewType->getNumArgs() ||
685        OldType->isVariadic() != NewType->isVariadic() ||
686        !FunctionArgTypesAreEqual(OldType, NewType)))
687     return true;
688
689   // C++ [temp.over.link]p4:
690   //   The signature of a function template consists of its function
691   //   signature, its return type and its template parameter list. The names
692   //   of the template parameters are significant only for establishing the
693   //   relationship between the template parameters and the rest of the
694   //   signature.
695   //
696   // We check the return type and template parameter lists for function
697   // templates first; the remaining checks follow.
698   //
699   // However, we don't consider either of these when deciding whether
700   // a member introduced by a shadow declaration is hidden.
701   if (!UseUsingDeclRules && NewTemplate &&
702       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
703                                        OldTemplate->getTemplateParameters(),
704                                        false, TPL_TemplateMatch) ||
705        OldType->getResultType() != NewType->getResultType()))
706     return true;
707
708   // If the function is a class member, its signature includes the
709   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
710   //
711   // As part of this, also check whether one of the member functions
712   // is static, in which case they are not overloads (C++
713   // 13.1p2). While not part of the definition of the signature,
714   // this check is important to determine whether these functions
715   // can be overloaded.
716   CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
717   CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
718   if (OldMethod && NewMethod &&
719       !OldMethod->isStatic() && !NewMethod->isStatic() &&
720       (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
721        OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
722     if (!UseUsingDeclRules &&
723         OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
724         (OldMethod->getRefQualifier() == RQ_None ||
725          NewMethod->getRefQualifier() == RQ_None)) {
726       // C++0x [over.load]p2:
727       //   - Member function declarations with the same name and the same
728       //     parameter-type-list as well as member function template
729       //     declarations with the same name, the same parameter-type-list, and
730       //     the same template parameter lists cannot be overloaded if any of
731       //     them, but not all, have a ref-qualifier (8.3.5).
732       Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
733         << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
734       Diag(OldMethod->getLocation(), diag::note_previous_declaration);
735     }
736
737     return true;
738   }
739
740   // The signatures match; this is not an overload.
741   return false;
742 }
743
744 /// \brief Checks availability of the function depending on the current
745 /// function context. Inside an unavailable function, unavailability is ignored.
746 ///
747 /// \returns true if \arg FD is unavailable and current context is inside
748 /// an available function, false otherwise.
749 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
750   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
751 }
752
753 /// TryImplicitConversion - Attempt to perform an implicit conversion
754 /// from the given expression (Expr) to the given type (ToType). This
755 /// function returns an implicit conversion sequence that can be used
756 /// to perform the initialization. Given
757 ///
758 ///   void f(float f);
759 ///   void g(int i) { f(i); }
760 ///
761 /// this routine would produce an implicit conversion sequence to
762 /// describe the initialization of f from i, which will be a standard
763 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
764 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
765 //
766 /// Note that this routine only determines how the conversion can be
767 /// performed; it does not actually perform the conversion. As such,
768 /// it will not produce any diagnostics if no conversion is available,
769 /// but will instead return an implicit conversion sequence of kind
770 /// "BadConversion".
771 ///
772 /// If @p SuppressUserConversions, then user-defined conversions are
773 /// not permitted.
774 /// If @p AllowExplicit, then explicit user-defined conversions are
775 /// permitted.
776 ///
777 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
778 /// writeback conversion, which allows __autoreleasing id* parameters to
779 /// be initialized with __strong id* or __weak id* arguments.
780 static ImplicitConversionSequence
781 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
782                       bool SuppressUserConversions,
783                       bool AllowExplicit,
784                       bool InOverloadResolution,
785                       bool CStyle,
786                       bool AllowObjCWritebackConversion) {
787   ImplicitConversionSequence ICS;
788   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
789                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
790     ICS.setStandard();
791     return ICS;
792   }
793
794   if (!S.getLangOptions().CPlusPlus) {
795     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
796     return ICS;
797   }
798
799   // C++ [over.ics.user]p4:
800   //   A conversion of an expression of class type to the same class
801   //   type is given Exact Match rank, and a conversion of an
802   //   expression of class type to a base class of that type is
803   //   given Conversion rank, in spite of the fact that a copy/move
804   //   constructor (i.e., a user-defined conversion function) is
805   //   called for those cases.
806   QualType FromType = From->getType();
807   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
808       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
809        S.IsDerivedFrom(FromType, ToType))) {
810     ICS.setStandard();
811     ICS.Standard.setAsIdentityConversion();
812     ICS.Standard.setFromType(FromType);
813     ICS.Standard.setAllToTypes(ToType);
814
815     // We don't actually check at this point whether there is a valid
816     // copy/move constructor, since overloading just assumes that it
817     // exists. When we actually perform initialization, we'll find the
818     // appropriate constructor to copy the returned object, if needed.
819     ICS.Standard.CopyConstructor = 0;
820
821     // Determine whether this is considered a derived-to-base conversion.
822     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
823       ICS.Standard.Second = ICK_Derived_To_Base;
824
825     return ICS;
826   }
827
828   if (SuppressUserConversions) {
829     // We're not in the case above, so there is no conversion that
830     // we can perform.
831     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
832     return ICS;
833   }
834
835   // Attempt user-defined conversion.
836   OverloadCandidateSet Conversions(From->getExprLoc());
837   OverloadingResult UserDefResult
838     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
839                               AllowExplicit);
840
841   if (UserDefResult == OR_Success) {
842     ICS.setUserDefined();
843     // C++ [over.ics.user]p4:
844     //   A conversion of an expression of class type to the same class
845     //   type is given Exact Match rank, and a conversion of an
846     //   expression of class type to a base class of that type is
847     //   given Conversion rank, in spite of the fact that a copy
848     //   constructor (i.e., a user-defined conversion function) is
849     //   called for those cases.
850     if (CXXConstructorDecl *Constructor
851           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
852       QualType FromCanon
853         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
854       QualType ToCanon
855         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
856       if (Constructor->isCopyConstructor() &&
857           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
858         // Turn this into a "standard" conversion sequence, so that it
859         // gets ranked with standard conversion sequences.
860         ICS.setStandard();
861         ICS.Standard.setAsIdentityConversion();
862         ICS.Standard.setFromType(From->getType());
863         ICS.Standard.setAllToTypes(ToType);
864         ICS.Standard.CopyConstructor = Constructor;
865         if (ToCanon != FromCanon)
866           ICS.Standard.Second = ICK_Derived_To_Base;
867       }
868     }
869
870     // C++ [over.best.ics]p4:
871     //   However, when considering the argument of a user-defined
872     //   conversion function that is a candidate by 13.3.1.3 when
873     //   invoked for the copying of the temporary in the second step
874     //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
875     //   13.3.1.6 in all cases, only standard conversion sequences and
876     //   ellipsis conversion sequences are allowed.
877     if (SuppressUserConversions && ICS.isUserDefined()) {
878       ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
879     }
880   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
881     ICS.setAmbiguous();
882     ICS.Ambiguous.setFromType(From->getType());
883     ICS.Ambiguous.setToType(ToType);
884     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
885          Cand != Conversions.end(); ++Cand)
886       if (Cand->Viable)
887         ICS.Ambiguous.addConversion(Cand->Function);
888   } else {
889     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
890   }
891
892   return ICS;
893 }
894
895 ImplicitConversionSequence
896 Sema::TryImplicitConversion(Expr *From, QualType ToType,
897                             bool SuppressUserConversions,
898                             bool AllowExplicit,
899                             bool InOverloadResolution,
900                             bool CStyle,
901                             bool AllowObjCWritebackConversion) {
902   return clang::TryImplicitConversion(*this, From, ToType, 
903                                       SuppressUserConversions, AllowExplicit,
904                                       InOverloadResolution, CStyle, 
905                                       AllowObjCWritebackConversion);
906 }
907
908 /// PerformImplicitConversion - Perform an implicit conversion of the
909 /// expression From to the type ToType. Returns the
910 /// converted expression. Flavor is the kind of conversion we're
911 /// performing, used in the error message. If @p AllowExplicit,
912 /// explicit user-defined conversions are permitted.
913 ExprResult
914 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
915                                 AssignmentAction Action, bool AllowExplicit,
916                                 bool Diagnose) {
917   ImplicitConversionSequence ICS;
918   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS,
919                                    Diagnose);
920 }
921
922 ExprResult
923 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
924                                 AssignmentAction Action, bool AllowExplicit,
925                                 ImplicitConversionSequence& ICS,
926                                 bool Diagnose) {
927   // Objective-C ARC: Determine whether we will allow the writeback conversion.
928   bool AllowObjCWritebackConversion
929     = getLangOptions().ObjCAutoRefCount && 
930       (Action == AA_Passing || Action == AA_Sending);
931
932   ICS = clang::TryImplicitConversion(*this, From, ToType,
933                                      /*SuppressUserConversions=*/false,
934                                      AllowExplicit,
935                                      /*InOverloadResolution=*/false,
936                                      /*CStyle=*/false,
937                                      AllowObjCWritebackConversion);
938   if (!Diagnose && ICS.isFailure())
939     return ExprError();
940   return PerformImplicitConversion(From, ToType, ICS, Action);
941 }
942
943 /// \brief Determine whether the conversion from FromType to ToType is a valid
944 /// conversion that strips "noreturn" off the nested function type.
945 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
946                                 QualType &ResultTy) {
947   if (Context.hasSameUnqualifiedType(FromType, ToType))
948     return false;
949
950   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
951   // where F adds one of the following at most once:
952   //   - a pointer
953   //   - a member pointer
954   //   - a block pointer
955   CanQualType CanTo = Context.getCanonicalType(ToType);
956   CanQualType CanFrom = Context.getCanonicalType(FromType);
957   Type::TypeClass TyClass = CanTo->getTypeClass();
958   if (TyClass != CanFrom->getTypeClass()) return false;
959   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
960     if (TyClass == Type::Pointer) {
961       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
962       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
963     } else if (TyClass == Type::BlockPointer) {
964       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
965       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
966     } else if (TyClass == Type::MemberPointer) {
967       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
968       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
969     } else {
970       return false;
971     }
972
973     TyClass = CanTo->getTypeClass();
974     if (TyClass != CanFrom->getTypeClass()) return false;
975     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
976       return false;
977   }
978
979   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
980   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
981   if (!EInfo.getNoReturn()) return false;
982
983   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
984   assert(QualType(FromFn, 0).isCanonical());
985   if (QualType(FromFn, 0) != CanTo) return false;
986
987   ResultTy = ToType;
988   return true;
989 }
990
991 /// \brief Determine whether the conversion from FromType to ToType is a valid
992 /// vector conversion.
993 ///
994 /// \param ICK Will be set to the vector conversion kind, if this is a vector
995 /// conversion.
996 static bool IsVectorConversion(ASTContext &Context, QualType FromType,
997                                QualType ToType, ImplicitConversionKind &ICK) {
998   // We need at least one of these types to be a vector type to have a vector
999   // conversion.
1000   if (!ToType->isVectorType() && !FromType->isVectorType())
1001     return false;
1002
1003   // Identical types require no conversions.
1004   if (Context.hasSameUnqualifiedType(FromType, ToType))
1005     return false;
1006
1007   // There are no conversions between extended vector types, only identity.
1008   if (ToType->isExtVectorType()) {
1009     // There are no conversions between extended vector types other than the
1010     // identity conversion.
1011     if (FromType->isExtVectorType())
1012       return false;
1013
1014     // Vector splat from any arithmetic type to a vector.
1015     if (FromType->isArithmeticType()) {
1016       ICK = ICK_Vector_Splat;
1017       return true;
1018     }
1019   }
1020
1021   // We can perform the conversion between vector types in the following cases:
1022   // 1)vector types are equivalent AltiVec and GCC vector types
1023   // 2)lax vector conversions are permitted and the vector types are of the
1024   //   same size
1025   if (ToType->isVectorType() && FromType->isVectorType()) {
1026     if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1027         (Context.getLangOptions().LaxVectorConversions &&
1028          (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1029       ICK = ICK_Vector_Conversion;
1030       return true;
1031     }
1032   }
1033
1034   return false;
1035 }
1036
1037 /// IsStandardConversion - Determines whether there is a standard
1038 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1039 /// expression From to the type ToType. Standard conversion sequences
1040 /// only consider non-class types; for conversions that involve class
1041 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1042 /// contain the standard conversion sequence required to perform this
1043 /// conversion and this routine will return true. Otherwise, this
1044 /// routine will return false and the value of SCS is unspecified.
1045 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1046                                  bool InOverloadResolution,
1047                                  StandardConversionSequence &SCS,
1048                                  bool CStyle,
1049                                  bool AllowObjCWritebackConversion) {
1050   QualType FromType = From->getType();
1051
1052   // Standard conversions (C++ [conv])
1053   SCS.setAsIdentityConversion();
1054   SCS.DeprecatedStringLiteralToCharPtr = false;
1055   SCS.IncompatibleObjC = false;
1056   SCS.setFromType(FromType);
1057   SCS.CopyConstructor = 0;
1058
1059   // There are no standard conversions for class types in C++, so
1060   // abort early. When overloading in C, however, we do permit
1061   if (FromType->isRecordType() || ToType->isRecordType()) {
1062     if (S.getLangOptions().CPlusPlus)
1063       return false;
1064
1065     // When we're overloading in C, we allow, as standard conversions,
1066   }
1067
1068   // The first conversion can be an lvalue-to-rvalue conversion,
1069   // array-to-pointer conversion, or function-to-pointer conversion
1070   // (C++ 4p1).
1071
1072   if (FromType == S.Context.OverloadTy) {
1073     DeclAccessPair AccessPair;
1074     if (FunctionDecl *Fn
1075           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1076                                                  AccessPair)) {
1077       // We were able to resolve the address of the overloaded function,
1078       // so we can convert to the type of that function.
1079       FromType = Fn->getType();
1080
1081       // we can sometimes resolve &foo<int> regardless of ToType, so check
1082       // if the type matches (identity) or we are converting to bool
1083       if (!S.Context.hasSameUnqualifiedType(
1084                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1085         QualType resultTy;
1086         // if the function type matches except for [[noreturn]], it's ok
1087         if (!S.IsNoReturnConversion(FromType,
1088               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1089           // otherwise, only a boolean conversion is standard   
1090           if (!ToType->isBooleanType()) 
1091             return false; 
1092       }
1093
1094       // Check if the "from" expression is taking the address of an overloaded
1095       // function and recompute the FromType accordingly. Take advantage of the
1096       // fact that non-static member functions *must* have such an address-of
1097       // expression. 
1098       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1099       if (Method && !Method->isStatic()) {
1100         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1101                "Non-unary operator on non-static member address");
1102         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1103                == UO_AddrOf &&
1104                "Non-address-of operator on non-static member address");
1105         const Type *ClassType
1106           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1107         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1108       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1109         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1110                UO_AddrOf &&
1111                "Non-address-of operator for overloaded function expression");
1112         FromType = S.Context.getPointerType(FromType);
1113       }
1114
1115       // Check that we've computed the proper type after overload resolution.
1116       assert(S.Context.hasSameType(
1117         FromType,
1118         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1119     } else {
1120       return false;
1121     }
1122   }
1123   // Lvalue-to-rvalue conversion (C++11 4.1):
1124   //   A glvalue (3.10) of a non-function, non-array type T can
1125   //   be converted to a prvalue.
1126   bool argIsLValue = From->isGLValue();
1127   if (argIsLValue &&
1128       !FromType->isFunctionType() && !FromType->isArrayType() &&
1129       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1130     SCS.First = ICK_Lvalue_To_Rvalue;
1131
1132     // If T is a non-class type, the type of the rvalue is the
1133     // cv-unqualified version of T. Otherwise, the type of the rvalue
1134     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1135     // just strip the qualifiers because they don't matter.
1136     FromType = FromType.getUnqualifiedType();
1137   } else if (FromType->isArrayType()) {
1138     // Array-to-pointer conversion (C++ 4.2)
1139     SCS.First = ICK_Array_To_Pointer;
1140
1141     // An lvalue or rvalue of type "array of N T" or "array of unknown
1142     // bound of T" can be converted to an rvalue of type "pointer to
1143     // T" (C++ 4.2p1).
1144     FromType = S.Context.getArrayDecayedType(FromType);
1145
1146     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1147       // This conversion is deprecated. (C++ D.4).
1148       SCS.DeprecatedStringLiteralToCharPtr = true;
1149
1150       // For the purpose of ranking in overload resolution
1151       // (13.3.3.1.1), this conversion is considered an
1152       // array-to-pointer conversion followed by a qualification
1153       // conversion (4.4). (C++ 4.2p2)
1154       SCS.Second = ICK_Identity;
1155       SCS.Third = ICK_Qualification;
1156       SCS.QualificationIncludesObjCLifetime = false;
1157       SCS.setAllToTypes(FromType);
1158       return true;
1159     }
1160   } else if (FromType->isFunctionType() && argIsLValue) {
1161     // Function-to-pointer conversion (C++ 4.3).
1162     SCS.First = ICK_Function_To_Pointer;
1163
1164     // An lvalue of function type T can be converted to an rvalue of
1165     // type "pointer to T." The result is a pointer to the
1166     // function. (C++ 4.3p1).
1167     FromType = S.Context.getPointerType(FromType);
1168   } else {
1169     // We don't require any conversions for the first step.
1170     SCS.First = ICK_Identity;
1171   }
1172   SCS.setToType(0, FromType);
1173
1174   // The second conversion can be an integral promotion, floating
1175   // point promotion, integral conversion, floating point conversion,
1176   // floating-integral conversion, pointer conversion,
1177   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1178   // For overloading in C, this can also be a "compatible-type"
1179   // conversion.
1180   bool IncompatibleObjC = false;
1181   ImplicitConversionKind SecondICK = ICK_Identity;
1182   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1183     // The unqualified versions of the types are the same: there's no
1184     // conversion to do.
1185     SCS.Second = ICK_Identity;
1186   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1187     // Integral promotion (C++ 4.5).
1188     SCS.Second = ICK_Integral_Promotion;
1189     FromType = ToType.getUnqualifiedType();
1190   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1191     // Floating point promotion (C++ 4.6).
1192     SCS.Second = ICK_Floating_Promotion;
1193     FromType = ToType.getUnqualifiedType();
1194   } else if (S.IsComplexPromotion(FromType, ToType)) {
1195     // Complex promotion (Clang extension)
1196     SCS.Second = ICK_Complex_Promotion;
1197     FromType = ToType.getUnqualifiedType();
1198   } else if (ToType->isBooleanType() &&
1199              (FromType->isArithmeticType() ||
1200               FromType->isAnyPointerType() ||
1201               FromType->isBlockPointerType() ||
1202               FromType->isMemberPointerType() ||
1203               FromType->isNullPtrType())) {
1204     // Boolean conversions (C++ 4.12).
1205     SCS.Second = ICK_Boolean_Conversion;
1206     FromType = S.Context.BoolTy;
1207   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1208              ToType->isIntegralType(S.Context)) {
1209     // Integral conversions (C++ 4.7).
1210     SCS.Second = ICK_Integral_Conversion;
1211     FromType = ToType.getUnqualifiedType();
1212   } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1213     // Complex conversions (C99 6.3.1.6)
1214     SCS.Second = ICK_Complex_Conversion;
1215     FromType = ToType.getUnqualifiedType();
1216   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1217              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1218     // Complex-real conversions (C99 6.3.1.7)
1219     SCS.Second = ICK_Complex_Real;
1220     FromType = ToType.getUnqualifiedType();
1221   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1222     // Floating point conversions (C++ 4.8).
1223     SCS.Second = ICK_Floating_Conversion;
1224     FromType = ToType.getUnqualifiedType();
1225   } else if ((FromType->isRealFloatingType() &&
1226               ToType->isIntegralType(S.Context)) ||
1227              (FromType->isIntegralOrUnscopedEnumerationType() &&
1228               ToType->isRealFloatingType())) {
1229     // Floating-integral conversions (C++ 4.9).
1230     SCS.Second = ICK_Floating_Integral;
1231     FromType = ToType.getUnqualifiedType();
1232   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1233     SCS.Second = ICK_Block_Pointer_Conversion;
1234   } else if (AllowObjCWritebackConversion &&
1235              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1236     SCS.Second = ICK_Writeback_Conversion;
1237   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1238                                    FromType, IncompatibleObjC)) {
1239     // Pointer conversions (C++ 4.10).
1240     SCS.Second = ICK_Pointer_Conversion;
1241     SCS.IncompatibleObjC = IncompatibleObjC;
1242     FromType = FromType.getUnqualifiedType();
1243   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1244                                          InOverloadResolution, FromType)) {
1245     // Pointer to member conversions (4.11).
1246     SCS.Second = ICK_Pointer_Member;
1247   } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1248     SCS.Second = SecondICK;
1249     FromType = ToType.getUnqualifiedType();
1250   } else if (!S.getLangOptions().CPlusPlus &&
1251              S.Context.typesAreCompatible(ToType, FromType)) {
1252     // Compatible conversions (Clang extension for C function overloading)
1253     SCS.Second = ICK_Compatible_Conversion;
1254     FromType = ToType.getUnqualifiedType();
1255   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1256     // Treat a conversion that strips "noreturn" as an identity conversion.
1257     SCS.Second = ICK_NoReturn_Adjustment;
1258   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1259                                              InOverloadResolution,
1260                                              SCS, CStyle)) {
1261     SCS.Second = ICK_TransparentUnionConversion;
1262     FromType = ToType;
1263   } else {
1264     // No second conversion required.
1265     SCS.Second = ICK_Identity;
1266   }
1267   SCS.setToType(1, FromType);
1268
1269   QualType CanonFrom;
1270   QualType CanonTo;
1271   // The third conversion can be a qualification conversion (C++ 4p1).
1272   bool ObjCLifetimeConversion;
1273   if (S.IsQualificationConversion(FromType, ToType, CStyle, 
1274                                   ObjCLifetimeConversion)) {
1275     SCS.Third = ICK_Qualification;
1276     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1277     FromType = ToType;
1278     CanonFrom = S.Context.getCanonicalType(FromType);
1279     CanonTo = S.Context.getCanonicalType(ToType);
1280   } else {
1281     // No conversion required
1282     SCS.Third = ICK_Identity;
1283
1284     // C++ [over.best.ics]p6:
1285     //   [...] Any difference in top-level cv-qualification is
1286     //   subsumed by the initialization itself and does not constitute
1287     //   a conversion. [...]
1288     CanonFrom = S.Context.getCanonicalType(FromType);
1289     CanonTo = S.Context.getCanonicalType(ToType);
1290     if (CanonFrom.getLocalUnqualifiedType()
1291                                        == CanonTo.getLocalUnqualifiedType() &&
1292         (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1293          || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1294          || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
1295       FromType = ToType;
1296       CanonFrom = CanonTo;
1297     }
1298   }
1299   SCS.setToType(2, FromType);
1300
1301   // If we have not converted the argument type to the parameter type,
1302   // this is a bad conversion sequence.
1303   if (CanonFrom != CanonTo)
1304     return false;
1305
1306   return true;
1307 }
1308   
1309 static bool
1310 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 
1311                                      QualType &ToType,
1312                                      bool InOverloadResolution,
1313                                      StandardConversionSequence &SCS,
1314                                      bool CStyle) {
1315     
1316   const RecordType *UT = ToType->getAsUnionType();
1317   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1318     return false;
1319   // The field to initialize within the transparent union.
1320   RecordDecl *UD = UT->getDecl();
1321   // It's compatible if the expression matches any of the fields.
1322   for (RecordDecl::field_iterator it = UD->field_begin(),
1323        itend = UD->field_end();
1324        it != itend; ++it) {
1325     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1326                              CStyle, /*ObjCWritebackConversion=*/false)) {
1327       ToType = it->getType();
1328       return true;
1329     }
1330   }
1331   return false;
1332 }
1333
1334 /// IsIntegralPromotion - Determines whether the conversion from the
1335 /// expression From (whose potentially-adjusted type is FromType) to
1336 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1337 /// sets PromotedType to the promoted type.
1338 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1339   const BuiltinType *To = ToType->getAs<BuiltinType>();
1340   // All integers are built-in.
1341   if (!To) {
1342     return false;
1343   }
1344
1345   // An rvalue of type char, signed char, unsigned char, short int, or
1346   // unsigned short int can be converted to an rvalue of type int if
1347   // int can represent all the values of the source type; otherwise,
1348   // the source rvalue can be converted to an rvalue of type unsigned
1349   // int (C++ 4.5p1).
1350   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1351       !FromType->isEnumeralType()) {
1352     if (// We can promote any signed, promotable integer type to an int
1353         (FromType->isSignedIntegerType() ||
1354          // We can promote any unsigned integer type whose size is
1355          // less than int to an int.
1356          (!FromType->isSignedIntegerType() &&
1357           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1358       return To->getKind() == BuiltinType::Int;
1359     }
1360
1361     return To->getKind() == BuiltinType::UInt;
1362   }
1363
1364   // C++0x [conv.prom]p3:
1365   //   A prvalue of an unscoped enumeration type whose underlying type is not
1366   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1367   //   following types that can represent all the values of the enumeration
1368   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1369   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1370   //   long long int. If none of the types in that list can represent all the
1371   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1372   //   type can be converted to an rvalue a prvalue of the extended integer type
1373   //   with lowest integer conversion rank (4.13) greater than the rank of long
1374   //   long in which all the values of the enumeration can be represented. If
1375   //   there are two such extended types, the signed one is chosen.
1376   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1377     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1378     // provided for a scoped enumeration.
1379     if (FromEnumType->getDecl()->isScoped())
1380       return false;
1381
1382     // We have already pre-calculated the promotion type, so this is trivial.
1383     if (ToType->isIntegerType() &&
1384         !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
1385       return Context.hasSameUnqualifiedType(ToType,
1386                                 FromEnumType->getDecl()->getPromotionType());
1387   }
1388
1389   // C++0x [conv.prom]p2:
1390   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1391   //   to an rvalue a prvalue of the first of the following types that can
1392   //   represent all the values of its underlying type: int, unsigned int,
1393   //   long int, unsigned long int, long long int, or unsigned long long int.
1394   //   If none of the types in that list can represent all the values of its
1395   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1396   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1397   //   type.
1398   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1399       ToType->isIntegerType()) {
1400     // Determine whether the type we're converting from is signed or
1401     // unsigned.
1402     bool FromIsSigned = FromType->isSignedIntegerType();
1403     uint64_t FromSize = Context.getTypeSize(FromType);
1404
1405     // The types we'll try to promote to, in the appropriate
1406     // order. Try each of these types.
1407     QualType PromoteTypes[6] = {
1408       Context.IntTy, Context.UnsignedIntTy,
1409       Context.LongTy, Context.UnsignedLongTy ,
1410       Context.LongLongTy, Context.UnsignedLongLongTy
1411     };
1412     for (int Idx = 0; Idx < 6; ++Idx) {
1413       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1414       if (FromSize < ToSize ||
1415           (FromSize == ToSize &&
1416            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1417         // We found the type that we can promote to. If this is the
1418         // type we wanted, we have a promotion. Otherwise, no
1419         // promotion.
1420         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1421       }
1422     }
1423   }
1424
1425   // An rvalue for an integral bit-field (9.6) can be converted to an
1426   // rvalue of type int if int can represent all the values of the
1427   // bit-field; otherwise, it can be converted to unsigned int if
1428   // unsigned int can represent all the values of the bit-field. If
1429   // the bit-field is larger yet, no integral promotion applies to
1430   // it. If the bit-field has an enumerated type, it is treated as any
1431   // other value of that type for promotion purposes (C++ 4.5p3).
1432   // FIXME: We should delay checking of bit-fields until we actually perform the
1433   // conversion.
1434   using llvm::APSInt;
1435   if (From)
1436     if (FieldDecl *MemberDecl = From->getBitField()) {
1437       APSInt BitWidth;
1438       if (FromType->isIntegralType(Context) &&
1439           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1440         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1441         ToSize = Context.getTypeSize(ToType);
1442
1443         // Are we promoting to an int from a bitfield that fits in an int?
1444         if (BitWidth < ToSize ||
1445             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1446           return To->getKind() == BuiltinType::Int;
1447         }
1448
1449         // Are we promoting to an unsigned int from an unsigned bitfield
1450         // that fits into an unsigned int?
1451         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1452           return To->getKind() == BuiltinType::UInt;
1453         }
1454
1455         return false;
1456       }
1457     }
1458
1459   // An rvalue of type bool can be converted to an rvalue of type int,
1460   // with false becoming zero and true becoming one (C++ 4.5p4).
1461   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1462     return true;
1463   }
1464
1465   return false;
1466 }
1467
1468 /// IsFloatingPointPromotion - Determines whether the conversion from
1469 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1470 /// returns true and sets PromotedType to the promoted type.
1471 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1472   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1473     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1474       /// An rvalue of type float can be converted to an rvalue of type
1475       /// double. (C++ 4.6p1).
1476       if (FromBuiltin->getKind() == BuiltinType::Float &&
1477           ToBuiltin->getKind() == BuiltinType::Double)
1478         return true;
1479
1480       // C99 6.3.1.5p1:
1481       //   When a float is promoted to double or long double, or a
1482       //   double is promoted to long double [...].
1483       if (!getLangOptions().CPlusPlus &&
1484           (FromBuiltin->getKind() == BuiltinType::Float ||
1485            FromBuiltin->getKind() == BuiltinType::Double) &&
1486           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1487         return true;
1488
1489       // Half can be promoted to float.
1490       if (FromBuiltin->getKind() == BuiltinType::Half &&
1491           ToBuiltin->getKind() == BuiltinType::Float)
1492         return true;
1493     }
1494
1495   return false;
1496 }
1497
1498 /// \brief Determine if a conversion is a complex promotion.
1499 ///
1500 /// A complex promotion is defined as a complex -> complex conversion
1501 /// where the conversion between the underlying real types is a
1502 /// floating-point or integral promotion.
1503 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1504   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1505   if (!FromComplex)
1506     return false;
1507
1508   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1509   if (!ToComplex)
1510     return false;
1511
1512   return IsFloatingPointPromotion(FromComplex->getElementType(),
1513                                   ToComplex->getElementType()) ||
1514     IsIntegralPromotion(0, FromComplex->getElementType(),
1515                         ToComplex->getElementType());
1516 }
1517
1518 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1519 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1520 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1521 /// if non-empty, will be a pointer to ToType that may or may not have
1522 /// the right set of qualifiers on its pointee.
1523 ///
1524 static QualType
1525 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1526                                    QualType ToPointee, QualType ToType,
1527                                    ASTContext &Context,
1528                                    bool StripObjCLifetime = false) {
1529   assert((FromPtr->getTypeClass() == Type::Pointer ||
1530           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1531          "Invalid similarly-qualified pointer type");
1532
1533   /// Conversions to 'id' subsume cv-qualifier conversions.
1534   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 
1535     return ToType.getUnqualifiedType();
1536
1537   QualType CanonFromPointee
1538     = Context.getCanonicalType(FromPtr->getPointeeType());
1539   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1540   Qualifiers Quals = CanonFromPointee.getQualifiers();
1541
1542   if (StripObjCLifetime)
1543     Quals.removeObjCLifetime();
1544   
1545   // Exact qualifier match -> return the pointer type we're converting to.
1546   if (CanonToPointee.getLocalQualifiers() == Quals) {
1547     // ToType is exactly what we need. Return it.
1548     if (!ToType.isNull())
1549       return ToType.getUnqualifiedType();
1550
1551     // Build a pointer to ToPointee. It has the right qualifiers
1552     // already.
1553     if (isa<ObjCObjectPointerType>(ToType))
1554       return Context.getObjCObjectPointerType(ToPointee);
1555     return Context.getPointerType(ToPointee);
1556   }
1557
1558   // Just build a canonical type that has the right qualifiers.
1559   QualType QualifiedCanonToPointee
1560     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1561
1562   if (isa<ObjCObjectPointerType>(ToType))
1563     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1564   return Context.getPointerType(QualifiedCanonToPointee);
1565 }
1566
1567 static bool isNullPointerConstantForConversion(Expr *Expr,
1568                                                bool InOverloadResolution,
1569                                                ASTContext &Context) {
1570   // Handle value-dependent integral null pointer constants correctly.
1571   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1572   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1573       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1574     return !InOverloadResolution;
1575
1576   return Expr->isNullPointerConstant(Context,
1577                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1578                                         : Expr::NPC_ValueDependentIsNull);
1579 }
1580
1581 /// IsPointerConversion - Determines whether the conversion of the
1582 /// expression From, which has the (possibly adjusted) type FromType,
1583 /// can be converted to the type ToType via a pointer conversion (C++
1584 /// 4.10). If so, returns true and places the converted type (that
1585 /// might differ from ToType in its cv-qualifiers at some level) into
1586 /// ConvertedType.
1587 ///
1588 /// This routine also supports conversions to and from block pointers
1589 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1590 /// pointers to interfaces. FIXME: Once we've determined the
1591 /// appropriate overloading rules for Objective-C, we may want to
1592 /// split the Objective-C checks into a different routine; however,
1593 /// GCC seems to consider all of these conversions to be pointer
1594 /// conversions, so for now they live here. IncompatibleObjC will be
1595 /// set if the conversion is an allowed Objective-C conversion that
1596 /// should result in a warning.
1597 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1598                                bool InOverloadResolution,
1599                                QualType& ConvertedType,
1600                                bool &IncompatibleObjC) {
1601   IncompatibleObjC = false;
1602   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1603                               IncompatibleObjC))
1604     return true;
1605
1606   // Conversion from a null pointer constant to any Objective-C pointer type.
1607   if (ToType->isObjCObjectPointerType() &&
1608       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1609     ConvertedType = ToType;
1610     return true;
1611   }
1612
1613   // Blocks: Block pointers can be converted to void*.
1614   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1615       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1616     ConvertedType = ToType;
1617     return true;
1618   }
1619   // Blocks: A null pointer constant can be converted to a block
1620   // pointer type.
1621   if (ToType->isBlockPointerType() &&
1622       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1623     ConvertedType = ToType;
1624     return true;
1625   }
1626
1627   // If the left-hand-side is nullptr_t, the right side can be a null
1628   // pointer constant.
1629   if (ToType->isNullPtrType() &&
1630       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1631     ConvertedType = ToType;
1632     return true;
1633   }
1634
1635   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1636   if (!ToTypePtr)
1637     return false;
1638
1639   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1640   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1641     ConvertedType = ToType;
1642     return true;
1643   }
1644
1645   // Beyond this point, both types need to be pointers
1646   // , including objective-c pointers.
1647   QualType ToPointeeType = ToTypePtr->getPointeeType();
1648   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1649       !getLangOptions().ObjCAutoRefCount) {
1650     ConvertedType = BuildSimilarlyQualifiedPointerType(
1651                                       FromType->getAs<ObjCObjectPointerType>(),
1652                                                        ToPointeeType,
1653                                                        ToType, Context);
1654     return true;
1655   }
1656   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1657   if (!FromTypePtr)
1658     return false;
1659
1660   QualType FromPointeeType = FromTypePtr->getPointeeType();
1661
1662   // If the unqualified pointee types are the same, this can't be a
1663   // pointer conversion, so don't do all of the work below.
1664   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1665     return false;
1666
1667   // An rvalue of type "pointer to cv T," where T is an object type,
1668   // can be converted to an rvalue of type "pointer to cv void" (C++
1669   // 4.10p2).
1670   if (FromPointeeType->isIncompleteOrObjectType() &&
1671       ToPointeeType->isVoidType()) {
1672     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1673                                                        ToPointeeType,
1674                                                        ToType, Context,
1675                                                    /*StripObjCLifetime=*/true);
1676     return true;
1677   }
1678
1679   // MSVC allows implicit function to void* type conversion.
1680   if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
1681       ToPointeeType->isVoidType()) {
1682     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1683                                                        ToPointeeType,
1684                                                        ToType, Context);
1685     return true;
1686   }
1687
1688   // When we're overloading in C, we allow a special kind of pointer
1689   // conversion for compatible-but-not-identical pointee types.
1690   if (!getLangOptions().CPlusPlus &&
1691       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1692     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1693                                                        ToPointeeType,
1694                                                        ToType, Context);
1695     return true;
1696   }
1697
1698   // C++ [conv.ptr]p3:
1699   //
1700   //   An rvalue of type "pointer to cv D," where D is a class type,
1701   //   can be converted to an rvalue of type "pointer to cv B," where
1702   //   B is a base class (clause 10) of D. If B is an inaccessible
1703   //   (clause 11) or ambiguous (10.2) base class of D, a program that
1704   //   necessitates this conversion is ill-formed. The result of the
1705   //   conversion is a pointer to the base class sub-object of the
1706   //   derived class object. The null pointer value is converted to
1707   //   the null pointer value of the destination type.
1708   //
1709   // Note that we do not check for ambiguity or inaccessibility
1710   // here. That is handled by CheckPointerConversion.
1711   if (getLangOptions().CPlusPlus &&
1712       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1713       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
1714       !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1715       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1716     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1717                                                        ToPointeeType,
1718                                                        ToType, Context);
1719     return true;
1720   }
1721
1722   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1723       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1724     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1725                                                        ToPointeeType,
1726                                                        ToType, Context);
1727     return true;
1728   }
1729   
1730   return false;
1731 }
1732  
1733 /// \brief Adopt the given qualifiers for the given type.
1734 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1735   Qualifiers TQs = T.getQualifiers();
1736   
1737   // Check whether qualifiers already match.
1738   if (TQs == Qs)
1739     return T;
1740   
1741   if (Qs.compatiblyIncludes(TQs))
1742     return Context.getQualifiedType(T, Qs);
1743   
1744   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1745 }
1746
1747 /// isObjCPointerConversion - Determines whether this is an
1748 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1749 /// with the same arguments and return values.
1750 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1751                                    QualType& ConvertedType,
1752                                    bool &IncompatibleObjC) {
1753   if (!getLangOptions().ObjC1)
1754     return false;
1755
1756   // The set of qualifiers on the type we're converting from.
1757   Qualifiers FromQualifiers = FromType.getQualifiers();
1758   
1759   // First, we handle all conversions on ObjC object pointer types.
1760   const ObjCObjectPointerType* ToObjCPtr =
1761     ToType->getAs<ObjCObjectPointerType>();
1762   const ObjCObjectPointerType *FromObjCPtr =
1763     FromType->getAs<ObjCObjectPointerType>();
1764
1765   if (ToObjCPtr && FromObjCPtr) {
1766     // If the pointee types are the same (ignoring qualifications),
1767     // then this is not a pointer conversion.
1768     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1769                                        FromObjCPtr->getPointeeType()))
1770       return false;
1771
1772     // Check for compatible 
1773     // Objective C++: We're able to convert between "id" or "Class" and a
1774     // pointer to any interface (in both directions).
1775     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1776       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1777       return true;
1778     }
1779     // Conversions with Objective-C's id<...>.
1780     if ((FromObjCPtr->isObjCQualifiedIdType() ||
1781          ToObjCPtr->isObjCQualifiedIdType()) &&
1782         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1783                                                   /*compare=*/false)) {
1784       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1785       return true;
1786     }
1787     // Objective C++: We're able to convert from a pointer to an
1788     // interface to a pointer to a different interface.
1789     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1790       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1791       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1792       if (getLangOptions().CPlusPlus && LHS && RHS &&
1793           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1794                                                 FromObjCPtr->getPointeeType()))
1795         return false;
1796       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1797                                                    ToObjCPtr->getPointeeType(),
1798                                                          ToType, Context);
1799       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1800       return true;
1801     }
1802
1803     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1804       // Okay: this is some kind of implicit downcast of Objective-C
1805       // interfaces, which is permitted. However, we're going to
1806       // complain about it.
1807       IncompatibleObjC = true;
1808       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1809                                                    ToObjCPtr->getPointeeType(),
1810                                                          ToType, Context);
1811       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1812       return true;
1813     }
1814   }
1815   // Beyond this point, both types need to be C pointers or block pointers.
1816   QualType ToPointeeType;
1817   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1818     ToPointeeType = ToCPtr->getPointeeType();
1819   else if (const BlockPointerType *ToBlockPtr =
1820             ToType->getAs<BlockPointerType>()) {
1821     // Objective C++: We're able to convert from a pointer to any object
1822     // to a block pointer type.
1823     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1824       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1825       return true;
1826     }
1827     ToPointeeType = ToBlockPtr->getPointeeType();
1828   }
1829   else if (FromType->getAs<BlockPointerType>() &&
1830            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1831     // Objective C++: We're able to convert from a block pointer type to a
1832     // pointer to any object.
1833     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1834     return true;
1835   }
1836   else
1837     return false;
1838
1839   QualType FromPointeeType;
1840   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1841     FromPointeeType = FromCPtr->getPointeeType();
1842   else if (const BlockPointerType *FromBlockPtr =
1843            FromType->getAs<BlockPointerType>())
1844     FromPointeeType = FromBlockPtr->getPointeeType();
1845   else
1846     return false;
1847
1848   // If we have pointers to pointers, recursively check whether this
1849   // is an Objective-C conversion.
1850   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1851       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1852                               IncompatibleObjC)) {
1853     // We always complain about this conversion.
1854     IncompatibleObjC = true;
1855     ConvertedType = Context.getPointerType(ConvertedType);
1856     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1857     return true;
1858   }
1859   // Allow conversion of pointee being objective-c pointer to another one;
1860   // as in I* to id.
1861   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1862       ToPointeeType->getAs<ObjCObjectPointerType>() &&
1863       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1864                               IncompatibleObjC)) {
1865         
1866     ConvertedType = Context.getPointerType(ConvertedType);
1867     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1868     return true;
1869   }
1870
1871   // If we have pointers to functions or blocks, check whether the only
1872   // differences in the argument and result types are in Objective-C
1873   // pointer conversions. If so, we permit the conversion (but
1874   // complain about it).
1875   const FunctionProtoType *FromFunctionType
1876     = FromPointeeType->getAs<FunctionProtoType>();
1877   const FunctionProtoType *ToFunctionType
1878     = ToPointeeType->getAs<FunctionProtoType>();
1879   if (FromFunctionType && ToFunctionType) {
1880     // If the function types are exactly the same, this isn't an
1881     // Objective-C pointer conversion.
1882     if (Context.getCanonicalType(FromPointeeType)
1883           == Context.getCanonicalType(ToPointeeType))
1884       return false;
1885
1886     // Perform the quick checks that will tell us whether these
1887     // function types are obviously different.
1888     if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1889         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1890         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1891       return false;
1892
1893     bool HasObjCConversion = false;
1894     if (Context.getCanonicalType(FromFunctionType->getResultType())
1895           == Context.getCanonicalType(ToFunctionType->getResultType())) {
1896       // Okay, the types match exactly. Nothing to do.
1897     } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1898                                        ToFunctionType->getResultType(),
1899                                        ConvertedType, IncompatibleObjC)) {
1900       // Okay, we have an Objective-C pointer conversion.
1901       HasObjCConversion = true;
1902     } else {
1903       // Function types are too different. Abort.
1904       return false;
1905     }
1906
1907     // Check argument types.
1908     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1909          ArgIdx != NumArgs; ++ArgIdx) {
1910       QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1911       QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1912       if (Context.getCanonicalType(FromArgType)
1913             == Context.getCanonicalType(ToArgType)) {
1914         // Okay, the types match exactly. Nothing to do.
1915       } else if (isObjCPointerConversion(FromArgType, ToArgType,
1916                                          ConvertedType, IncompatibleObjC)) {
1917         // Okay, we have an Objective-C pointer conversion.
1918         HasObjCConversion = true;
1919       } else {
1920         // Argument types are too different. Abort.
1921         return false;
1922       }
1923     }
1924
1925     if (HasObjCConversion) {
1926       // We had an Objective-C conversion. Allow this pointer
1927       // conversion, but complain about it.
1928       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1929       IncompatibleObjC = true;
1930       return true;
1931     }
1932   }
1933
1934   return false;
1935 }
1936
1937 /// \brief Determine whether this is an Objective-C writeback conversion,
1938 /// used for parameter passing when performing automatic reference counting.
1939 ///
1940 /// \param FromType The type we're converting form.
1941 ///
1942 /// \param ToType The type we're converting to.
1943 ///
1944 /// \param ConvertedType The type that will be produced after applying
1945 /// this conversion.
1946 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1947                                      QualType &ConvertedType) {
1948   if (!getLangOptions().ObjCAutoRefCount || 
1949       Context.hasSameUnqualifiedType(FromType, ToType))
1950     return false;
1951   
1952   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1953   QualType ToPointee;
1954   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1955     ToPointee = ToPointer->getPointeeType();
1956   else
1957     return false;
1958   
1959   Qualifiers ToQuals = ToPointee.getQualifiers();
1960   if (!ToPointee->isObjCLifetimeType() || 
1961       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1962       !ToQuals.withoutObjCGLifetime().empty())
1963     return false;
1964   
1965   // Argument must be a pointer to __strong to __weak.
1966   QualType FromPointee;
1967   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1968     FromPointee = FromPointer->getPointeeType();
1969   else
1970     return false;
1971   
1972   Qualifiers FromQuals = FromPointee.getQualifiers();
1973   if (!FromPointee->isObjCLifetimeType() ||
1974       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1975        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1976     return false;
1977   
1978   // Make sure that we have compatible qualifiers.
1979   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1980   if (!ToQuals.compatiblyIncludes(FromQuals))
1981     return false;
1982   
1983   // Remove qualifiers from the pointee type we're converting from; they
1984   // aren't used in the compatibility check belong, and we'll be adding back
1985   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1986   FromPointee = FromPointee.getUnqualifiedType();
1987   
1988   // The unqualified form of the pointee types must be compatible.
1989   ToPointee = ToPointee.getUnqualifiedType();
1990   bool IncompatibleObjC;
1991   if (Context.typesAreCompatible(FromPointee, ToPointee))
1992     FromPointee = ToPointee;
1993   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1994                                     IncompatibleObjC))
1995     return false;
1996   
1997   /// \brief Construct the type we're converting to, which is a pointer to
1998   /// __autoreleasing pointee.
1999   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2000   ConvertedType = Context.getPointerType(FromPointee);
2001   return true;
2002 }
2003
2004 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2005                                     QualType& ConvertedType) {
2006   QualType ToPointeeType;
2007   if (const BlockPointerType *ToBlockPtr =
2008         ToType->getAs<BlockPointerType>())
2009     ToPointeeType = ToBlockPtr->getPointeeType();
2010   else
2011     return false;
2012   
2013   QualType FromPointeeType;
2014   if (const BlockPointerType *FromBlockPtr =
2015       FromType->getAs<BlockPointerType>())
2016     FromPointeeType = FromBlockPtr->getPointeeType();
2017   else
2018     return false;
2019   // We have pointer to blocks, check whether the only
2020   // differences in the argument and result types are in Objective-C
2021   // pointer conversions. If so, we permit the conversion.
2022   
2023   const FunctionProtoType *FromFunctionType
2024     = FromPointeeType->getAs<FunctionProtoType>();
2025   const FunctionProtoType *ToFunctionType
2026     = ToPointeeType->getAs<FunctionProtoType>();
2027   
2028   if (!FromFunctionType || !ToFunctionType)
2029     return false;
2030
2031   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2032     return true;
2033     
2034   // Perform the quick checks that will tell us whether these
2035   // function types are obviously different.
2036   if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2037       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2038     return false;
2039     
2040   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2041   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2042   if (FromEInfo != ToEInfo)
2043     return false;
2044
2045   bool IncompatibleObjC = false;
2046   if (Context.hasSameType(FromFunctionType->getResultType(), 
2047                           ToFunctionType->getResultType())) {
2048     // Okay, the types match exactly. Nothing to do.
2049   } else {
2050     QualType RHS = FromFunctionType->getResultType();
2051     QualType LHS = ToFunctionType->getResultType();
2052     if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2053         !RHS.hasQualifiers() && LHS.hasQualifiers())
2054        LHS = LHS.getUnqualifiedType();
2055
2056      if (Context.hasSameType(RHS,LHS)) {
2057        // OK exact match.
2058      } else if (isObjCPointerConversion(RHS, LHS,
2059                                         ConvertedType, IncompatibleObjC)) {
2060      if (IncompatibleObjC)
2061        return false;
2062      // Okay, we have an Objective-C pointer conversion.
2063      }
2064      else
2065        return false;
2066    }
2067     
2068    // Check argument types.
2069    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2070         ArgIdx != NumArgs; ++ArgIdx) {
2071      IncompatibleObjC = false;
2072      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2073      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2074      if (Context.hasSameType(FromArgType, ToArgType)) {
2075        // Okay, the types match exactly. Nothing to do.
2076      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2077                                         ConvertedType, IncompatibleObjC)) {
2078        if (IncompatibleObjC)
2079          return false;
2080        // Okay, we have an Objective-C pointer conversion.
2081      } else
2082        // Argument types are too different. Abort.
2083        return false;
2084    }
2085    if (LangOpts.ObjCAutoRefCount && 
2086        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 
2087                                                     ToFunctionType))
2088      return false;
2089    
2090    ConvertedType = ToType;
2091    return true;
2092 }
2093
2094 /// FunctionArgTypesAreEqual - This routine checks two function proto types
2095 /// for equlity of their argument types. Caller has already checked that
2096 /// they have same number of arguments. This routine assumes that Objective-C
2097 /// pointer types which only differ in their protocol qualifiers are equal.
2098 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2099                                     const FunctionProtoType *NewType) {
2100   if (!getLangOptions().ObjC1)
2101     return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2102                       NewType->arg_type_begin());
2103
2104   for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2105        N = NewType->arg_type_begin(),
2106        E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2107     QualType ToType = (*O);
2108     QualType FromType = (*N);
2109     if (ToType != FromType) {
2110       if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2111         if (const PointerType *PTFr = FromType->getAs<PointerType>())
2112           if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2113                PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2114               (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2115                PTFr->getPointeeType()->isObjCQualifiedClassType()))
2116             continue;
2117       }
2118       else if (const ObjCObjectPointerType *PTTo =
2119                  ToType->getAs<ObjCObjectPointerType>()) {
2120         if (const ObjCObjectPointerType *PTFr =
2121               FromType->getAs<ObjCObjectPointerType>())
2122           if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2123             continue;
2124       }
2125       return false;
2126     }
2127   }
2128   return true;
2129 }
2130
2131 /// CheckPointerConversion - Check the pointer conversion from the
2132 /// expression From to the type ToType. This routine checks for
2133 /// ambiguous or inaccessible derived-to-base pointer
2134 /// conversions for which IsPointerConversion has already returned
2135 /// true. It returns true and produces a diagnostic if there was an
2136 /// error, or returns false otherwise.
2137 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2138                                   CastKind &Kind,
2139                                   CXXCastPath& BasePath,
2140                                   bool IgnoreBaseAccess) {
2141   QualType FromType = From->getType();
2142   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2143
2144   Kind = CK_BitCast;
2145
2146   if (!IsCStyleOrFunctionalCast &&
2147       Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2148       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2149     DiagRuntimeBehavior(From->getExprLoc(), From,
2150                         PDiag(diag::warn_impcast_bool_to_null_pointer)
2151                           << ToType << From->getSourceRange());
2152
2153   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2154     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2155       QualType FromPointeeType = FromPtrType->getPointeeType(),
2156                ToPointeeType   = ToPtrType->getPointeeType();
2157
2158       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2159           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2160         // We must have a derived-to-base conversion. Check an
2161         // ambiguous or inaccessible conversion.
2162         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2163                                          From->getExprLoc(),
2164                                          From->getSourceRange(), &BasePath,
2165                                          IgnoreBaseAccess))
2166           return true;
2167
2168         // The conversion was successful.
2169         Kind = CK_DerivedToBase;
2170       }
2171     }
2172   } else if (const ObjCObjectPointerType *ToPtrType =
2173                ToType->getAs<ObjCObjectPointerType>()) {
2174     if (const ObjCObjectPointerType *FromPtrType =
2175           FromType->getAs<ObjCObjectPointerType>()) {
2176       // Objective-C++ conversions are always okay.
2177       // FIXME: We should have a different class of conversions for the
2178       // Objective-C++ implicit conversions.
2179       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2180         return false;
2181     } else if (FromType->isBlockPointerType()) {
2182       Kind = CK_BlockPointerToObjCPointerCast;
2183     } else {
2184       Kind = CK_CPointerToObjCPointerCast;
2185     }
2186   } else if (ToType->isBlockPointerType()) {
2187     if (!FromType->isBlockPointerType())
2188       Kind = CK_AnyPointerToBlockPointerCast;
2189   }
2190
2191   // We shouldn't fall into this case unless it's valid for other
2192   // reasons.
2193   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2194     Kind = CK_NullToPointer;
2195
2196   return false;
2197 }
2198
2199 /// IsMemberPointerConversion - Determines whether the conversion of the
2200 /// expression From, which has the (possibly adjusted) type FromType, can be
2201 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2202 /// If so, returns true and places the converted type (that might differ from
2203 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2204 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2205                                      QualType ToType,
2206                                      bool InOverloadResolution,
2207                                      QualType &ConvertedType) {
2208   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2209   if (!ToTypePtr)
2210     return false;
2211
2212   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2213   if (From->isNullPointerConstant(Context,
2214                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2215                                         : Expr::NPC_ValueDependentIsNull)) {
2216     ConvertedType = ToType;
2217     return true;
2218   }
2219
2220   // Otherwise, both types have to be member pointers.
2221   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2222   if (!FromTypePtr)
2223     return false;
2224
2225   // A pointer to member of B can be converted to a pointer to member of D,
2226   // where D is derived from B (C++ 4.11p2).
2227   QualType FromClass(FromTypePtr->getClass(), 0);
2228   QualType ToClass(ToTypePtr->getClass(), 0);
2229
2230   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2231       !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2232       IsDerivedFrom(ToClass, FromClass)) {
2233     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2234                                                  ToClass.getTypePtr());
2235     return true;
2236   }
2237
2238   return false;
2239 }
2240
2241 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2242 /// expression From to the type ToType. This routine checks for ambiguous or
2243 /// virtual or inaccessible base-to-derived member pointer conversions
2244 /// for which IsMemberPointerConversion has already returned true. It returns
2245 /// true and produces a diagnostic if there was an error, or returns false
2246 /// otherwise.
2247 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2248                                         CastKind &Kind,
2249                                         CXXCastPath &BasePath,
2250                                         bool IgnoreBaseAccess) {
2251   QualType FromType = From->getType();
2252   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2253   if (!FromPtrType) {
2254     // This must be a null pointer to member pointer conversion
2255     assert(From->isNullPointerConstant(Context,
2256                                        Expr::NPC_ValueDependentIsNull) &&
2257            "Expr must be null pointer constant!");
2258     Kind = CK_NullToMemberPointer;
2259     return false;
2260   }
2261
2262   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2263   assert(ToPtrType && "No member pointer cast has a target type "
2264                       "that is not a member pointer.");
2265
2266   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2267   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2268
2269   // FIXME: What about dependent types?
2270   assert(FromClass->isRecordType() && "Pointer into non-class.");
2271   assert(ToClass->isRecordType() && "Pointer into non-class.");
2272
2273   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2274                      /*DetectVirtual=*/true);
2275   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2276   assert(DerivationOkay &&
2277          "Should not have been called if derivation isn't OK.");
2278   (void)DerivationOkay;
2279
2280   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2281                                   getUnqualifiedType())) {
2282     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2283     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2284       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2285     return true;
2286   }
2287
2288   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2289     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2290       << FromClass << ToClass << QualType(VBase, 0)
2291       << From->getSourceRange();
2292     return true;
2293   }
2294
2295   if (!IgnoreBaseAccess)
2296     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2297                          Paths.front(),
2298                          diag::err_downcast_from_inaccessible_base);
2299
2300   // Must be a base to derived member conversion.
2301   BuildBasePathArray(Paths, BasePath);
2302   Kind = CK_BaseToDerivedMemberPointer;
2303   return false;
2304 }
2305
2306 /// IsQualificationConversion - Determines whether the conversion from
2307 /// an rvalue of type FromType to ToType is a qualification conversion
2308 /// (C++ 4.4).
2309 ///
2310 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2311 /// when the qualification conversion involves a change in the Objective-C
2312 /// object lifetime.
2313 bool
2314 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2315                                 bool CStyle, bool &ObjCLifetimeConversion) {
2316   FromType = Context.getCanonicalType(FromType);
2317   ToType = Context.getCanonicalType(ToType);
2318   ObjCLifetimeConversion = false;
2319   
2320   // If FromType and ToType are the same type, this is not a
2321   // qualification conversion.
2322   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2323     return false;
2324
2325   // (C++ 4.4p4):
2326   //   A conversion can add cv-qualifiers at levels other than the first
2327   //   in multi-level pointers, subject to the following rules: [...]
2328   bool PreviousToQualsIncludeConst = true;
2329   bool UnwrappedAnyPointer = false;
2330   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2331     // Within each iteration of the loop, we check the qualifiers to
2332     // determine if this still looks like a qualification
2333     // conversion. Then, if all is well, we unwrap one more level of
2334     // pointers or pointers-to-members and do it all again
2335     // until there are no more pointers or pointers-to-members left to
2336     // unwrap.
2337     UnwrappedAnyPointer = true;
2338
2339     Qualifiers FromQuals = FromType.getQualifiers();
2340     Qualifiers ToQuals = ToType.getQualifiers();
2341     
2342     // Objective-C ARC:
2343     //   Check Objective-C lifetime conversions.
2344     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2345         UnwrappedAnyPointer) {
2346       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2347         ObjCLifetimeConversion = true;
2348         FromQuals.removeObjCLifetime();
2349         ToQuals.removeObjCLifetime();
2350       } else {
2351         // Qualification conversions cannot cast between different
2352         // Objective-C lifetime qualifiers.
2353         return false;
2354       }
2355     }
2356     
2357     // Allow addition/removal of GC attributes but not changing GC attributes.
2358     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2359         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2360       FromQuals.removeObjCGCAttr();
2361       ToQuals.removeObjCGCAttr();
2362     }
2363     
2364     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2365     //      2,j, and similarly for volatile.
2366     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2367       return false;
2368
2369     //   -- if the cv 1,j and cv 2,j are different, then const is in
2370     //      every cv for 0 < k < j.
2371     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2372         && !PreviousToQualsIncludeConst)
2373       return false;
2374
2375     // Keep track of whether all prior cv-qualifiers in the "to" type
2376     // include const.
2377     PreviousToQualsIncludeConst
2378       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2379   }
2380
2381   // We are left with FromType and ToType being the pointee types
2382   // after unwrapping the original FromType and ToType the same number
2383   // of types. If we unwrapped any pointers, and if FromType and
2384   // ToType have the same unqualified type (since we checked
2385   // qualifiers above), then this is a qualification conversion.
2386   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2387 }
2388
2389 /// Determines whether there is a user-defined conversion sequence
2390 /// (C++ [over.ics.user]) that converts expression From to the type
2391 /// ToType. If such a conversion exists, User will contain the
2392 /// user-defined conversion sequence that performs such a conversion
2393 /// and this routine will return true. Otherwise, this routine returns
2394 /// false and User is unspecified.
2395 ///
2396 /// \param AllowExplicit  true if the conversion should consider C++0x
2397 /// "explicit" conversion functions as well as non-explicit conversion
2398 /// functions (C++0x [class.conv.fct]p2).
2399 static OverloadingResult
2400 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2401                         UserDefinedConversionSequence& User,
2402                         OverloadCandidateSet& CandidateSet,
2403                         bool AllowExplicit) {
2404   // Whether we will only visit constructors.
2405   bool ConstructorsOnly = false;
2406
2407   // If the type we are conversion to is a class type, enumerate its
2408   // constructors.
2409   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2410     // C++ [over.match.ctor]p1:
2411     //   When objects of class type are direct-initialized (8.5), or
2412     //   copy-initialized from an expression of the same or a
2413     //   derived class type (8.5), overload resolution selects the
2414     //   constructor. [...] For copy-initialization, the candidate
2415     //   functions are all the converting constructors (12.3.1) of
2416     //   that class. The argument list is the expression-list within
2417     //   the parentheses of the initializer.
2418     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2419         (From->getType()->getAs<RecordType>() &&
2420          S.IsDerivedFrom(From->getType(), ToType)))
2421       ConstructorsOnly = true;
2422
2423     S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2424     // RequireCompleteType may have returned true due to some invalid decl
2425     // during template instantiation, but ToType may be complete enough now
2426     // to try to recover.
2427     if (ToType->isIncompleteType()) {
2428       // We're not going to find any constructors.
2429     } else if (CXXRecordDecl *ToRecordDecl
2430                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
2431       DeclContext::lookup_iterator Con, ConEnd;
2432       for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
2433            Con != ConEnd; ++Con) {
2434         NamedDecl *D = *Con;
2435         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2436
2437         // Find the constructor (which may be a template).
2438         CXXConstructorDecl *Constructor = 0;
2439         FunctionTemplateDecl *ConstructorTmpl
2440           = dyn_cast<FunctionTemplateDecl>(D);
2441         if (ConstructorTmpl)
2442           Constructor
2443             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2444         else
2445           Constructor = cast<CXXConstructorDecl>(D);
2446
2447         if (!Constructor->isInvalidDecl() &&
2448             Constructor->isConvertingConstructor(AllowExplicit)) {
2449           if (ConstructorTmpl)
2450             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2451                                            /*ExplicitArgs*/ 0,
2452                                            &From, 1, CandidateSet,
2453                                            /*SuppressUserConversions=*/
2454                                              !ConstructorsOnly);
2455           else
2456             // Allow one user-defined conversion when user specifies a
2457             // From->ToType conversion via an static cast (c-style, etc).
2458             S.AddOverloadCandidate(Constructor, FoundDecl,
2459                                    &From, 1, CandidateSet,
2460                                    /*SuppressUserConversions=*/
2461                                      !ConstructorsOnly);
2462         }
2463       }
2464     }
2465   }
2466
2467   // Enumerate conversion functions, if we're allowed to.
2468   if (ConstructorsOnly) {
2469   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2470                                    S.PDiag(0) << From->getSourceRange())) {
2471     // No conversion functions from incomplete types.
2472   } else if (const RecordType *FromRecordType
2473                                    = From->getType()->getAs<RecordType>()) {
2474     if (CXXRecordDecl *FromRecordDecl
2475          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2476       // Add all of the conversion functions as candidates.
2477       const UnresolvedSetImpl *Conversions
2478         = FromRecordDecl->getVisibleConversionFunctions();
2479       for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2480              E = Conversions->end(); I != E; ++I) {
2481         DeclAccessPair FoundDecl = I.getPair();
2482         NamedDecl *D = FoundDecl.getDecl();
2483         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2484         if (isa<UsingShadowDecl>(D))
2485           D = cast<UsingShadowDecl>(D)->getTargetDecl();
2486
2487         CXXConversionDecl *Conv;
2488         FunctionTemplateDecl *ConvTemplate;
2489         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2490           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2491         else
2492           Conv = cast<CXXConversionDecl>(D);
2493
2494         if (AllowExplicit || !Conv->isExplicit()) {
2495           if (ConvTemplate)
2496             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2497                                              ActingContext, From, ToType,
2498                                              CandidateSet);
2499           else
2500             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2501                                      From, ToType, CandidateSet);
2502         }
2503       }
2504     }
2505   }
2506
2507   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2508
2509   OverloadCandidateSet::iterator Best;
2510   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2511   case OR_Success:
2512     // Record the standard conversion we used and the conversion function.
2513     if (CXXConstructorDecl *Constructor
2514           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2515       S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2516
2517       // C++ [over.ics.user]p1:
2518       //   If the user-defined conversion is specified by a
2519       //   constructor (12.3.1), the initial standard conversion
2520       //   sequence converts the source type to the type required by
2521       //   the argument of the constructor.
2522       //
2523       QualType ThisType = Constructor->getThisType(S.Context);
2524       if (Best->Conversions[0].isEllipsis())
2525         User.EllipsisConversion = true;
2526       else {
2527         User.Before = Best->Conversions[0].Standard;
2528         User.EllipsisConversion = false;
2529       }
2530       User.HadMultipleCandidates = HadMultipleCandidates;
2531       User.ConversionFunction = Constructor;
2532       User.FoundConversionFunction = Best->FoundDecl;
2533       User.After.setAsIdentityConversion();
2534       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2535       User.After.setAllToTypes(ToType);
2536       return OR_Success;
2537     } else if (CXXConversionDecl *Conversion
2538                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
2539       S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2540
2541       // C++ [over.ics.user]p1:
2542       //
2543       //   [...] If the user-defined conversion is specified by a
2544       //   conversion function (12.3.2), the initial standard
2545       //   conversion sequence converts the source type to the
2546       //   implicit object parameter of the conversion function.
2547       User.Before = Best->Conversions[0].Standard;
2548       User.HadMultipleCandidates = HadMultipleCandidates;
2549       User.ConversionFunction = Conversion;
2550       User.FoundConversionFunction = Best->FoundDecl;
2551       User.EllipsisConversion = false;
2552
2553       // C++ [over.ics.user]p2:
2554       //   The second standard conversion sequence converts the
2555       //   result of the user-defined conversion to the target type
2556       //   for the sequence. Since an implicit conversion sequence
2557       //   is an initialization, the special rules for
2558       //   initialization by user-defined conversion apply when
2559       //   selecting the best user-defined conversion for a
2560       //   user-defined conversion sequence (see 13.3.3 and
2561       //   13.3.3.1).
2562       User.After = Best->FinalConversion;
2563       return OR_Success;
2564     } else {
2565       llvm_unreachable("Not a constructor or conversion function?");
2566       return OR_No_Viable_Function;
2567     }
2568
2569   case OR_No_Viable_Function:
2570     return OR_No_Viable_Function;
2571   case OR_Deleted:
2572     // No conversion here! We're done.
2573     return OR_Deleted;
2574
2575   case OR_Ambiguous:
2576     return OR_Ambiguous;
2577   }
2578
2579   return OR_No_Viable_Function;
2580 }
2581
2582 bool
2583 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
2584   ImplicitConversionSequence ICS;
2585   OverloadCandidateSet CandidateSet(From->getExprLoc());
2586   OverloadingResult OvResult =
2587     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
2588                             CandidateSet, false);
2589   if (OvResult == OR_Ambiguous)
2590     Diag(From->getSourceRange().getBegin(),
2591          diag::err_typecheck_ambiguous_condition)
2592           << From->getType() << ToType << From->getSourceRange();
2593   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2594     Diag(From->getSourceRange().getBegin(),
2595          diag::err_typecheck_nonviable_condition)
2596     << From->getType() << ToType << From->getSourceRange();
2597   else
2598     return false;
2599   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
2600   return true;
2601 }
2602
2603 /// CompareImplicitConversionSequences - Compare two implicit
2604 /// conversion sequences to determine whether one is better than the
2605 /// other or if they are indistinguishable (C++ 13.3.3.2).
2606 static ImplicitConversionSequence::CompareKind
2607 CompareImplicitConversionSequences(Sema &S,
2608                                    const ImplicitConversionSequence& ICS1,
2609                                    const ImplicitConversionSequence& ICS2)
2610 {
2611   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2612   // conversion sequences (as defined in 13.3.3.1)
2613   //   -- a standard conversion sequence (13.3.3.1.1) is a better
2614   //      conversion sequence than a user-defined conversion sequence or
2615   //      an ellipsis conversion sequence, and
2616   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
2617   //      conversion sequence than an ellipsis conversion sequence
2618   //      (13.3.3.1.3).
2619   //
2620   // C++0x [over.best.ics]p10:
2621   //   For the purpose of ranking implicit conversion sequences as
2622   //   described in 13.3.3.2, the ambiguous conversion sequence is
2623   //   treated as a user-defined sequence that is indistinguishable
2624   //   from any other user-defined conversion sequence.
2625   if (ICS1.getKindRank() < ICS2.getKindRank())
2626     return ImplicitConversionSequence::Better;
2627   else if (ICS2.getKindRank() < ICS1.getKindRank())
2628     return ImplicitConversionSequence::Worse;
2629
2630   // The following checks require both conversion sequences to be of
2631   // the same kind.
2632   if (ICS1.getKind() != ICS2.getKind())
2633     return ImplicitConversionSequence::Indistinguishable;
2634
2635   // Two implicit conversion sequences of the same form are
2636   // indistinguishable conversion sequences unless one of the
2637   // following rules apply: (C++ 13.3.3.2p3):
2638   if (ICS1.isStandard())
2639     return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
2640   else if (ICS1.isUserDefined()) {
2641     // User-defined conversion sequence U1 is a better conversion
2642     // sequence than another user-defined conversion sequence U2 if
2643     // they contain the same user-defined conversion function or
2644     // constructor and if the second standard conversion sequence of
2645     // U1 is better than the second standard conversion sequence of
2646     // U2 (C++ 13.3.3.2p3).
2647     if (ICS1.UserDefined.ConversionFunction ==
2648           ICS2.UserDefined.ConversionFunction)
2649       return CompareStandardConversionSequences(S,
2650                                                 ICS1.UserDefined.After,
2651                                                 ICS2.UserDefined.After);
2652   }
2653
2654   return ImplicitConversionSequence::Indistinguishable;
2655 }
2656
2657 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2658   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2659     Qualifiers Quals;
2660     T1 = Context.getUnqualifiedArrayType(T1, Quals);
2661     T2 = Context.getUnqualifiedArrayType(T2, Quals);
2662   }
2663
2664   return Context.hasSameUnqualifiedType(T1, T2);
2665 }
2666
2667 // Per 13.3.3.2p3, compare the given standard conversion sequences to
2668 // determine if one is a proper subset of the other.
2669 static ImplicitConversionSequence::CompareKind
2670 compareStandardConversionSubsets(ASTContext &Context,
2671                                  const StandardConversionSequence& SCS1,
2672                                  const StandardConversionSequence& SCS2) {
2673   ImplicitConversionSequence::CompareKind Result
2674     = ImplicitConversionSequence::Indistinguishable;
2675
2676   // the identity conversion sequence is considered to be a subsequence of
2677   // any non-identity conversion sequence
2678   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2679     return ImplicitConversionSequence::Better;
2680   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2681     return ImplicitConversionSequence::Worse;
2682
2683   if (SCS1.Second != SCS2.Second) {
2684     if (SCS1.Second == ICK_Identity)
2685       Result = ImplicitConversionSequence::Better;
2686     else if (SCS2.Second == ICK_Identity)
2687       Result = ImplicitConversionSequence::Worse;
2688     else
2689       return ImplicitConversionSequence::Indistinguishable;
2690   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
2691     return ImplicitConversionSequence::Indistinguishable;
2692
2693   if (SCS1.Third == SCS2.Third) {
2694     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2695                              : ImplicitConversionSequence::Indistinguishable;
2696   }
2697
2698   if (SCS1.Third == ICK_Identity)
2699     return Result == ImplicitConversionSequence::Worse
2700              ? ImplicitConversionSequence::Indistinguishable
2701              : ImplicitConversionSequence::Better;
2702
2703   if (SCS2.Third == ICK_Identity)
2704     return Result == ImplicitConversionSequence::Better
2705              ? ImplicitConversionSequence::Indistinguishable
2706              : ImplicitConversionSequence::Worse;
2707
2708   return ImplicitConversionSequence::Indistinguishable;
2709 }
2710
2711 /// \brief Determine whether one of the given reference bindings is better
2712 /// than the other based on what kind of bindings they are.
2713 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2714                                        const StandardConversionSequence &SCS2) {
2715   // C++0x [over.ics.rank]p3b4:
2716   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2717   //      implicit object parameter of a non-static member function declared
2718   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
2719   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
2720   //      lvalue reference to a function lvalue and S2 binds an rvalue
2721   //      reference*.
2722   //
2723   // FIXME: Rvalue references. We're going rogue with the above edits,
2724   // because the semantics in the current C++0x working paper (N3225 at the
2725   // time of this writing) break the standard definition of std::forward
2726   // and std::reference_wrapper when dealing with references to functions.
2727   // Proposed wording changes submitted to CWG for consideration.
2728   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2729       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2730     return false;
2731
2732   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2733           SCS2.IsLvalueReference) ||
2734          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2735           !SCS2.IsLvalueReference);
2736 }
2737
2738 /// CompareStandardConversionSequences - Compare two standard
2739 /// conversion sequences to determine whether one is better than the
2740 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
2741 static ImplicitConversionSequence::CompareKind
2742 CompareStandardConversionSequences(Sema &S,
2743                                    const StandardConversionSequence& SCS1,
2744                                    const StandardConversionSequence& SCS2)
2745 {
2746   // Standard conversion sequence S1 is a better conversion sequence
2747   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2748
2749   //  -- S1 is a proper subsequence of S2 (comparing the conversion
2750   //     sequences in the canonical form defined by 13.3.3.1.1,
2751   //     excluding any Lvalue Transformation; the identity conversion
2752   //     sequence is considered to be a subsequence of any
2753   //     non-identity conversion sequence) or, if not that,
2754   if (ImplicitConversionSequence::CompareKind CK
2755         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
2756     return CK;
2757
2758   //  -- the rank of S1 is better than the rank of S2 (by the rules
2759   //     defined below), or, if not that,
2760   ImplicitConversionRank Rank1 = SCS1.getRank();
2761   ImplicitConversionRank Rank2 = SCS2.getRank();
2762   if (Rank1 < Rank2)
2763     return ImplicitConversionSequence::Better;
2764   else if (Rank2 < Rank1)
2765     return ImplicitConversionSequence::Worse;
2766
2767   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2768   // are indistinguishable unless one of the following rules
2769   // applies:
2770
2771   //   A conversion that is not a conversion of a pointer, or
2772   //   pointer to member, to bool is better than another conversion
2773   //   that is such a conversion.
2774   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2775     return SCS2.isPointerConversionToBool()
2776              ? ImplicitConversionSequence::Better
2777              : ImplicitConversionSequence::Worse;
2778
2779   // C++ [over.ics.rank]p4b2:
2780   //
2781   //   If class B is derived directly or indirectly from class A,
2782   //   conversion of B* to A* is better than conversion of B* to
2783   //   void*, and conversion of A* to void* is better than conversion
2784   //   of B* to void*.
2785   bool SCS1ConvertsToVoid
2786     = SCS1.isPointerConversionToVoidPointer(S.Context);
2787   bool SCS2ConvertsToVoid
2788     = SCS2.isPointerConversionToVoidPointer(S.Context);
2789   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2790     // Exactly one of the conversion sequences is a conversion to
2791     // a void pointer; it's the worse conversion.
2792     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2793                               : ImplicitConversionSequence::Worse;
2794   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2795     // Neither conversion sequence converts to a void pointer; compare
2796     // their derived-to-base conversions.
2797     if (ImplicitConversionSequence::CompareKind DerivedCK
2798           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
2799       return DerivedCK;
2800   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2801              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
2802     // Both conversion sequences are conversions to void
2803     // pointers. Compare the source types to determine if there's an
2804     // inheritance relationship in their sources.
2805     QualType FromType1 = SCS1.getFromType();
2806     QualType FromType2 = SCS2.getFromType();
2807
2808     // Adjust the types we're converting from via the array-to-pointer
2809     // conversion, if we need to.
2810     if (SCS1.First == ICK_Array_To_Pointer)
2811       FromType1 = S.Context.getArrayDecayedType(FromType1);
2812     if (SCS2.First == ICK_Array_To_Pointer)
2813       FromType2 = S.Context.getArrayDecayedType(FromType2);
2814
2815     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2816     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
2817
2818     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2819       return ImplicitConversionSequence::Better;
2820     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2821       return ImplicitConversionSequence::Worse;
2822
2823     // Objective-C++: If one interface is more specific than the
2824     // other, it is the better one.
2825     const ObjCObjectPointerType* FromObjCPtr1
2826       = FromType1->getAs<ObjCObjectPointerType>();
2827     const ObjCObjectPointerType* FromObjCPtr2
2828       = FromType2->getAs<ObjCObjectPointerType>();
2829     if (FromObjCPtr1 && FromObjCPtr2) {
2830       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 
2831                                                           FromObjCPtr2);
2832       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 
2833                                                            FromObjCPtr1);
2834       if (AssignLeft != AssignRight) {
2835         return AssignLeft? ImplicitConversionSequence::Better
2836                          : ImplicitConversionSequence::Worse;
2837       }
2838     }
2839   }
2840
2841   // Compare based on qualification conversions (C++ 13.3.3.2p3,
2842   // bullet 3).
2843   if (ImplicitConversionSequence::CompareKind QualCK
2844         = CompareQualificationConversions(S, SCS1, SCS2))
2845     return QualCK;
2846
2847   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
2848     // Check for a better reference binding based on the kind of bindings.
2849     if (isBetterReferenceBindingKind(SCS1, SCS2))
2850       return ImplicitConversionSequence::Better;
2851     else if (isBetterReferenceBindingKind(SCS2, SCS1))
2852       return ImplicitConversionSequence::Worse;
2853
2854     // C++ [over.ics.rank]p3b4:
2855     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
2856     //      which the references refer are the same type except for
2857     //      top-level cv-qualifiers, and the type to which the reference
2858     //      initialized by S2 refers is more cv-qualified than the type
2859     //      to which the reference initialized by S1 refers.
2860     QualType T1 = SCS1.getToType(2);
2861     QualType T2 = SCS2.getToType(2);
2862     T1 = S.Context.getCanonicalType(T1);
2863     T2 = S.Context.getCanonicalType(T2);
2864     Qualifiers T1Quals, T2Quals;
2865     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2866     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
2867     if (UnqualT1 == UnqualT2) {
2868       // Objective-C++ ARC: If the references refer to objects with different
2869       // lifetimes, prefer bindings that don't change lifetime.
2870       if (SCS1.ObjCLifetimeConversionBinding != 
2871                                           SCS2.ObjCLifetimeConversionBinding) {
2872         return SCS1.ObjCLifetimeConversionBinding
2873                                            ? ImplicitConversionSequence::Worse
2874                                            : ImplicitConversionSequence::Better;
2875       }
2876       
2877       // If the type is an array type, promote the element qualifiers to the
2878       // type for comparison.
2879       if (isa<ArrayType>(T1) && T1Quals)
2880         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
2881       if (isa<ArrayType>(T2) && T2Quals)
2882         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
2883       if (T2.isMoreQualifiedThan(T1))
2884         return ImplicitConversionSequence::Better;
2885       else if (T1.isMoreQualifiedThan(T2))
2886         return ImplicitConversionSequence::Worse;      
2887     }
2888   }
2889
2890   // In Microsoft mode, prefer an integral conversion to a
2891   // floating-to-integral conversion if the integral conversion
2892   // is between types of the same size.
2893   // For example:
2894   // void f(float);
2895   // void f(int);
2896   // int main {
2897   //    long a;
2898   //    f(a);
2899   // }
2900   // Here, MSVC will call f(int) instead of generating a compile error
2901   // as clang will do in standard mode.
2902   if (S.getLangOptions().MicrosoftMode &&
2903       SCS1.Second == ICK_Integral_Conversion &&
2904       SCS2.Second == ICK_Floating_Integral && 
2905       S.Context.getTypeSize(SCS1.getFromType()) ==
2906       S.Context.getTypeSize(SCS1.getToType(2)))
2907     return ImplicitConversionSequence::Better;
2908
2909   return ImplicitConversionSequence::Indistinguishable;
2910 }
2911
2912 /// CompareQualificationConversions - Compares two standard conversion
2913 /// sequences to determine whether they can be ranked based on their
2914 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2915 ImplicitConversionSequence::CompareKind
2916 CompareQualificationConversions(Sema &S,
2917                                 const StandardConversionSequence& SCS1,
2918                                 const StandardConversionSequence& SCS2) {
2919   // C++ 13.3.3.2p3:
2920   //  -- S1 and S2 differ only in their qualification conversion and
2921   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
2922   //     cv-qualification signature of type T1 is a proper subset of
2923   //     the cv-qualification signature of type T2, and S1 is not the
2924   //     deprecated string literal array-to-pointer conversion (4.2).
2925   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2926       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2927     return ImplicitConversionSequence::Indistinguishable;
2928
2929   // FIXME: the example in the standard doesn't use a qualification
2930   // conversion (!)
2931   QualType T1 = SCS1.getToType(2);
2932   QualType T2 = SCS2.getToType(2);
2933   T1 = S.Context.getCanonicalType(T1);
2934   T2 = S.Context.getCanonicalType(T2);
2935   Qualifiers T1Quals, T2Quals;
2936   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2937   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
2938
2939   // If the types are the same, we won't learn anything by unwrapped
2940   // them.
2941   if (UnqualT1 == UnqualT2)
2942     return ImplicitConversionSequence::Indistinguishable;
2943
2944   // If the type is an array type, promote the element qualifiers to the type
2945   // for comparison.
2946   if (isa<ArrayType>(T1) && T1Quals)
2947     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
2948   if (isa<ArrayType>(T2) && T2Quals)
2949     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
2950
2951   ImplicitConversionSequence::CompareKind Result
2952     = ImplicitConversionSequence::Indistinguishable;
2953   
2954   // Objective-C++ ARC:
2955   //   Prefer qualification conversions not involving a change in lifetime
2956   //   to qualification conversions that do not change lifetime.
2957   if (SCS1.QualificationIncludesObjCLifetime != 
2958                                       SCS2.QualificationIncludesObjCLifetime) {
2959     Result = SCS1.QualificationIncludesObjCLifetime
2960                ? ImplicitConversionSequence::Worse
2961                : ImplicitConversionSequence::Better;
2962   }
2963   
2964   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
2965     // Within each iteration of the loop, we check the qualifiers to
2966     // determine if this still looks like a qualification
2967     // conversion. Then, if all is well, we unwrap one more level of
2968     // pointers or pointers-to-members and do it all again
2969     // until there are no more pointers or pointers-to-members left
2970     // to unwrap. This essentially mimics what
2971     // IsQualificationConversion does, but here we're checking for a
2972     // strict subset of qualifiers.
2973     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2974       // The qualifiers are the same, so this doesn't tell us anything
2975       // about how the sequences rank.
2976       ;
2977     else if (T2.isMoreQualifiedThan(T1)) {
2978       // T1 has fewer qualifiers, so it could be the better sequence.
2979       if (Result == ImplicitConversionSequence::Worse)
2980         // Neither has qualifiers that are a subset of the other's
2981         // qualifiers.
2982         return ImplicitConversionSequence::Indistinguishable;
2983
2984       Result = ImplicitConversionSequence::Better;
2985     } else if (T1.isMoreQualifiedThan(T2)) {
2986       // T2 has fewer qualifiers, so it could be the better sequence.
2987       if (Result == ImplicitConversionSequence::Better)
2988         // Neither has qualifiers that are a subset of the other's
2989         // qualifiers.
2990         return ImplicitConversionSequence::Indistinguishable;
2991
2992       Result = ImplicitConversionSequence::Worse;
2993     } else {
2994       // Qualifiers are disjoint.
2995       return ImplicitConversionSequence::Indistinguishable;
2996     }
2997
2998     // If the types after this point are equivalent, we're done.
2999     if (S.Context.hasSameUnqualifiedType(T1, T2))
3000       break;
3001   }
3002
3003   // Check that the winning standard conversion sequence isn't using
3004   // the deprecated string literal array to pointer conversion.
3005   switch (Result) {
3006   case ImplicitConversionSequence::Better:
3007     if (SCS1.DeprecatedStringLiteralToCharPtr)
3008       Result = ImplicitConversionSequence::Indistinguishable;
3009     break;
3010
3011   case ImplicitConversionSequence::Indistinguishable:
3012     break;
3013
3014   case ImplicitConversionSequence::Worse:
3015     if (SCS2.DeprecatedStringLiteralToCharPtr)
3016       Result = ImplicitConversionSequence::Indistinguishable;
3017     break;
3018   }
3019
3020   return Result;
3021 }
3022
3023 /// CompareDerivedToBaseConversions - Compares two standard conversion
3024 /// sequences to determine whether they can be ranked based on their
3025 /// various kinds of derived-to-base conversions (C++
3026 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3027 /// conversions between Objective-C interface types.
3028 ImplicitConversionSequence::CompareKind
3029 CompareDerivedToBaseConversions(Sema &S,
3030                                 const StandardConversionSequence& SCS1,
3031                                 const StandardConversionSequence& SCS2) {
3032   QualType FromType1 = SCS1.getFromType();
3033   QualType ToType1 = SCS1.getToType(1);
3034   QualType FromType2 = SCS2.getFromType();
3035   QualType ToType2 = SCS2.getToType(1);
3036
3037   // Adjust the types we're converting from via the array-to-pointer
3038   // conversion, if we need to.
3039   if (SCS1.First == ICK_Array_To_Pointer)
3040     FromType1 = S.Context.getArrayDecayedType(FromType1);
3041   if (SCS2.First == ICK_Array_To_Pointer)
3042     FromType2 = S.Context.getArrayDecayedType(FromType2);
3043
3044   // Canonicalize all of the types.
3045   FromType1 = S.Context.getCanonicalType(FromType1);
3046   ToType1 = S.Context.getCanonicalType(ToType1);
3047   FromType2 = S.Context.getCanonicalType(FromType2);
3048   ToType2 = S.Context.getCanonicalType(ToType2);
3049
3050   // C++ [over.ics.rank]p4b3:
3051   //
3052   //   If class B is derived directly or indirectly from class A and
3053   //   class C is derived directly or indirectly from B,
3054   //
3055   // Compare based on pointer conversions.
3056   if (SCS1.Second == ICK_Pointer_Conversion &&
3057       SCS2.Second == ICK_Pointer_Conversion &&
3058       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3059       FromType1->isPointerType() && FromType2->isPointerType() &&
3060       ToType1->isPointerType() && ToType2->isPointerType()) {
3061     QualType FromPointee1
3062       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3063     QualType ToPointee1
3064       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3065     QualType FromPointee2
3066       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3067     QualType ToPointee2
3068       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3069
3070     //   -- conversion of C* to B* is better than conversion of C* to A*,
3071     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3072       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3073         return ImplicitConversionSequence::Better;
3074       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3075         return ImplicitConversionSequence::Worse;
3076     }
3077
3078     //   -- conversion of B* to A* is better than conversion of C* to A*,
3079     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3080       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3081         return ImplicitConversionSequence::Better;
3082       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3083         return ImplicitConversionSequence::Worse;
3084     }
3085   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3086              SCS2.Second == ICK_Pointer_Conversion) {
3087     const ObjCObjectPointerType *FromPtr1
3088       = FromType1->getAs<ObjCObjectPointerType>();
3089     const ObjCObjectPointerType *FromPtr2
3090       = FromType2->getAs<ObjCObjectPointerType>();
3091     const ObjCObjectPointerType *ToPtr1
3092       = ToType1->getAs<ObjCObjectPointerType>();
3093     const ObjCObjectPointerType *ToPtr2
3094       = ToType2->getAs<ObjCObjectPointerType>();
3095     
3096     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3097       // Apply the same conversion ranking rules for Objective-C pointer types
3098       // that we do for C++ pointers to class types. However, we employ the
3099       // Objective-C pseudo-subtyping relationship used for assignment of
3100       // Objective-C pointer types.
3101       bool FromAssignLeft
3102         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3103       bool FromAssignRight
3104         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3105       bool ToAssignLeft
3106         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3107       bool ToAssignRight
3108         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3109       
3110       // A conversion to an a non-id object pointer type or qualified 'id' 
3111       // type is better than a conversion to 'id'.
3112       if (ToPtr1->isObjCIdType() &&
3113           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3114         return ImplicitConversionSequence::Worse;
3115       if (ToPtr2->isObjCIdType() &&
3116           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3117         return ImplicitConversionSequence::Better;
3118       
3119       // A conversion to a non-id object pointer type is better than a 
3120       // conversion to a qualified 'id' type 
3121       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3122         return ImplicitConversionSequence::Worse;
3123       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3124         return ImplicitConversionSequence::Better;
3125   
3126       // A conversion to an a non-Class object pointer type or qualified 'Class' 
3127       // type is better than a conversion to 'Class'.
3128       if (ToPtr1->isObjCClassType() &&
3129           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3130         return ImplicitConversionSequence::Worse;
3131       if (ToPtr2->isObjCClassType() &&
3132           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3133         return ImplicitConversionSequence::Better;
3134       
3135       // A conversion to a non-Class object pointer type is better than a 
3136       // conversion to a qualified 'Class' type.
3137       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3138         return ImplicitConversionSequence::Worse;
3139       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3140         return ImplicitConversionSequence::Better;
3141
3142       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3143       if (S.Context.hasSameType(FromType1, FromType2) && 
3144           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3145           (ToAssignLeft != ToAssignRight))
3146         return ToAssignLeft? ImplicitConversionSequence::Worse
3147                            : ImplicitConversionSequence::Better;
3148
3149       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3150       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3151           (FromAssignLeft != FromAssignRight))
3152         return FromAssignLeft? ImplicitConversionSequence::Better
3153         : ImplicitConversionSequence::Worse;
3154     }
3155   }
3156   
3157   // Ranking of member-pointer types.
3158   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3159       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3160       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3161     const MemberPointerType * FromMemPointer1 =
3162                                         FromType1->getAs<MemberPointerType>();
3163     const MemberPointerType * ToMemPointer1 =
3164                                           ToType1->getAs<MemberPointerType>();
3165     const MemberPointerType * FromMemPointer2 =
3166                                           FromType2->getAs<MemberPointerType>();
3167     const MemberPointerType * ToMemPointer2 =
3168                                           ToType2->getAs<MemberPointerType>();
3169     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3170     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3171     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3172     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3173     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3174     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3175     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3176     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3177     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3178     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3179       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3180         return ImplicitConversionSequence::Worse;
3181       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3182         return ImplicitConversionSequence::Better;
3183     }
3184     // conversion of B::* to C::* is better than conversion of A::* to C::*
3185     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3186       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3187         return ImplicitConversionSequence::Better;
3188       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3189         return ImplicitConversionSequence::Worse;
3190     }
3191   }
3192
3193   if (SCS1.Second == ICK_Derived_To_Base) {
3194     //   -- conversion of C to B is better than conversion of C to A,
3195     //   -- binding of an expression of type C to a reference of type
3196     //      B& is better than binding an expression of type C to a
3197     //      reference of type A&,
3198     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3199         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3200       if (S.IsDerivedFrom(ToType1, ToType2))
3201         return ImplicitConversionSequence::Better;
3202       else if (S.IsDerivedFrom(ToType2, ToType1))
3203         return ImplicitConversionSequence::Worse;
3204     }
3205
3206     //   -- conversion of B to A is better than conversion of C to A.
3207     //   -- binding of an expression of type B to a reference of type
3208     //      A& is better than binding an expression of type C to a
3209     //      reference of type A&,
3210     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3211         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3212       if (S.IsDerivedFrom(FromType2, FromType1))
3213         return ImplicitConversionSequence::Better;
3214       else if (S.IsDerivedFrom(FromType1, FromType2))
3215         return ImplicitConversionSequence::Worse;
3216     }
3217   }
3218
3219   return ImplicitConversionSequence::Indistinguishable;
3220 }
3221
3222 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3223 /// determine whether they are reference-related,
3224 /// reference-compatible, reference-compatible with added
3225 /// qualification, or incompatible, for use in C++ initialization by
3226 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3227 /// type, and the first type (T1) is the pointee type of the reference
3228 /// type being initialized.
3229 Sema::ReferenceCompareResult
3230 Sema::CompareReferenceRelationship(SourceLocation Loc,
3231                                    QualType OrigT1, QualType OrigT2,
3232                                    bool &DerivedToBase,
3233                                    bool &ObjCConversion,
3234                                    bool &ObjCLifetimeConversion) {
3235   assert(!OrigT1->isReferenceType() &&
3236     "T1 must be the pointee type of the reference type");
3237   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3238
3239   QualType T1 = Context.getCanonicalType(OrigT1);
3240   QualType T2 = Context.getCanonicalType(OrigT2);
3241   Qualifiers T1Quals, T2Quals;
3242   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3243   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3244
3245   // C++ [dcl.init.ref]p4:
3246   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3247   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3248   //   T1 is a base class of T2.
3249   DerivedToBase = false;
3250   ObjCConversion = false;
3251   ObjCLifetimeConversion = false;
3252   if (UnqualT1 == UnqualT2) {
3253     // Nothing to do.
3254   } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
3255            IsDerivedFrom(UnqualT2, UnqualT1))
3256     DerivedToBase = true;
3257   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3258            UnqualT2->isObjCObjectOrInterfaceType() &&
3259            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3260     ObjCConversion = true;
3261   else
3262     return Ref_Incompatible;
3263
3264   // At this point, we know that T1 and T2 are reference-related (at
3265   // least).
3266
3267   // If the type is an array type, promote the element qualifiers to the type
3268   // for comparison.
3269   if (isa<ArrayType>(T1) && T1Quals)
3270     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3271   if (isa<ArrayType>(T2) && T2Quals)
3272     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3273
3274   // C++ [dcl.init.ref]p4:
3275   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3276   //   reference-related to T2 and cv1 is the same cv-qualification
3277   //   as, or greater cv-qualification than, cv2. For purposes of
3278   //   overload resolution, cases for which cv1 is greater
3279   //   cv-qualification than cv2 are identified as
3280   //   reference-compatible with added qualification (see 13.3.3.2).
3281   //
3282   // Note that we also require equivalence of Objective-C GC and address-space
3283   // qualifiers when performing these computations, so that e.g., an int in
3284   // address space 1 is not reference-compatible with an int in address
3285   // space 2.
3286   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3287       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3288     T1Quals.removeObjCLifetime();
3289     T2Quals.removeObjCLifetime();    
3290     ObjCLifetimeConversion = true;
3291   }
3292     
3293   if (T1Quals == T2Quals)
3294     return Ref_Compatible;
3295   else if (T1Quals.compatiblyIncludes(T2Quals))
3296     return Ref_Compatible_With_Added_Qualification;
3297   else
3298     return Ref_Related;
3299 }
3300
3301 /// \brief Look for a user-defined conversion to an value reference-compatible
3302 ///        with DeclType. Return true if something definite is found.
3303 static bool
3304 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3305                          QualType DeclType, SourceLocation DeclLoc,
3306                          Expr *Init, QualType T2, bool AllowRvalues,
3307                          bool AllowExplicit) {
3308   assert(T2->isRecordType() && "Can only find conversions of record types.");
3309   CXXRecordDecl *T2RecordDecl
3310     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3311
3312   OverloadCandidateSet CandidateSet(DeclLoc);
3313   const UnresolvedSetImpl *Conversions
3314     = T2RecordDecl->getVisibleConversionFunctions();
3315   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3316          E = Conversions->end(); I != E; ++I) {
3317     NamedDecl *D = *I;
3318     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3319     if (isa<UsingShadowDecl>(D))
3320       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3321
3322     FunctionTemplateDecl *ConvTemplate
3323       = dyn_cast<FunctionTemplateDecl>(D);
3324     CXXConversionDecl *Conv;
3325     if (ConvTemplate)
3326       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3327     else
3328       Conv = cast<CXXConversionDecl>(D);
3329
3330     // If this is an explicit conversion, and we're not allowed to consider
3331     // explicit conversions, skip it.
3332     if (!AllowExplicit && Conv->isExplicit())
3333       continue;
3334
3335     if (AllowRvalues) {
3336       bool DerivedToBase = false;
3337       bool ObjCConversion = false;
3338       bool ObjCLifetimeConversion = false;
3339       
3340       // If we are initializing an rvalue reference, don't permit conversion
3341       // functions that return lvalues.
3342       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3343         const ReferenceType *RefType
3344           = Conv->getConversionType()->getAs<LValueReferenceType>();
3345         if (RefType && !RefType->getPointeeType()->isFunctionType())
3346           continue;
3347       }
3348       
3349       if (!ConvTemplate &&
3350           S.CompareReferenceRelationship(
3351             DeclLoc,
3352             Conv->getConversionType().getNonReferenceType()
3353               .getUnqualifiedType(),
3354             DeclType.getNonReferenceType().getUnqualifiedType(),
3355             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
3356           Sema::Ref_Incompatible)
3357         continue;
3358     } else {
3359       // If the conversion function doesn't return a reference type,
3360       // it can't be considered for this conversion. An rvalue reference
3361       // is only acceptable if its referencee is a function type.
3362
3363       const ReferenceType *RefType =
3364         Conv->getConversionType()->getAs<ReferenceType>();
3365       if (!RefType ||
3366           (!RefType->isLValueReferenceType() &&
3367            !RefType->getPointeeType()->isFunctionType()))
3368         continue;
3369     }
3370
3371     if (ConvTemplate)
3372       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
3373                                        Init, DeclType, CandidateSet);
3374     else
3375       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
3376                                DeclType, CandidateSet);
3377   }
3378
3379   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3380
3381   OverloadCandidateSet::iterator Best;
3382   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3383   case OR_Success:
3384     // C++ [over.ics.ref]p1:
3385     //
3386     //   [...] If the parameter binds directly to the result of
3387     //   applying a conversion function to the argument
3388     //   expression, the implicit conversion sequence is a
3389     //   user-defined conversion sequence (13.3.3.1.2), with the
3390     //   second standard conversion sequence either an identity
3391     //   conversion or, if the conversion function returns an
3392     //   entity of a type that is a derived class of the parameter
3393     //   type, a derived-to-base Conversion.
3394     if (!Best->FinalConversion.DirectBinding)
3395       return false;
3396
3397     if (Best->Function)
3398       S.MarkDeclarationReferenced(DeclLoc, Best->Function);
3399     ICS.setUserDefined();
3400     ICS.UserDefined.Before = Best->Conversions[0].Standard;
3401     ICS.UserDefined.After = Best->FinalConversion;
3402     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
3403     ICS.UserDefined.ConversionFunction = Best->Function;
3404     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
3405     ICS.UserDefined.EllipsisConversion = false;
3406     assert(ICS.UserDefined.After.ReferenceBinding &&
3407            ICS.UserDefined.After.DirectBinding &&
3408            "Expected a direct reference binding!");
3409     return true;
3410
3411   case OR_Ambiguous:
3412     ICS.setAmbiguous();
3413     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3414          Cand != CandidateSet.end(); ++Cand)
3415       if (Cand->Viable)
3416         ICS.Ambiguous.addConversion(Cand->Function);
3417     return true;
3418
3419   case OR_No_Viable_Function:
3420   case OR_Deleted:
3421     // There was no suitable conversion, or we found a deleted
3422     // conversion; continue with other checks.
3423     return false;
3424   }
3425
3426   return false;
3427 }
3428
3429 /// \brief Compute an implicit conversion sequence for reference
3430 /// initialization.
3431 static ImplicitConversionSequence
3432 TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3433                  SourceLocation DeclLoc,
3434                  bool SuppressUserConversions,
3435                  bool AllowExplicit) {
3436   assert(DeclType->isReferenceType() && "Reference init needs a reference");
3437
3438   // Most paths end in a failed conversion.
3439   ImplicitConversionSequence ICS;
3440   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3441
3442   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3443   QualType T2 = Init->getType();
3444
3445   // If the initializer is the address of an overloaded function, try
3446   // to resolve the overloaded function. If all goes well, T2 is the
3447   // type of the resulting function.
3448   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3449     DeclAccessPair Found;
3450     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3451                                                                 false, Found))
3452       T2 = Fn->getType();
3453   }
3454
3455   // Compute some basic properties of the types and the initializer.
3456   bool isRValRef = DeclType->isRValueReferenceType();
3457   bool DerivedToBase = false;
3458   bool ObjCConversion = false;
3459   bool ObjCLifetimeConversion = false;
3460   Expr::Classification InitCategory = Init->Classify(S.Context);
3461   Sema::ReferenceCompareResult RefRelationship
3462     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3463                                      ObjCConversion, ObjCLifetimeConversion);
3464
3465
3466   // C++0x [dcl.init.ref]p5:
3467   //   A reference to type "cv1 T1" is initialized by an expression
3468   //   of type "cv2 T2" as follows:
3469
3470   //     -- If reference is an lvalue reference and the initializer expression
3471   if (!isRValRef) {
3472     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3473     //        reference-compatible with "cv2 T2," or
3474     //
3475     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3476     if (InitCategory.isLValue() &&
3477         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3478       // C++ [over.ics.ref]p1:
3479       //   When a parameter of reference type binds directly (8.5.3)
3480       //   to an argument expression, the implicit conversion sequence
3481       //   is the identity conversion, unless the argument expression
3482       //   has a type that is a derived class of the parameter type,
3483       //   in which case the implicit conversion sequence is a
3484       //   derived-to-base Conversion (13.3.3.1).
3485       ICS.setStandard();
3486       ICS.Standard.First = ICK_Identity;
3487       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3488                          : ObjCConversion? ICK_Compatible_Conversion
3489                          : ICK_Identity;
3490       ICS.Standard.Third = ICK_Identity;
3491       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3492       ICS.Standard.setToType(0, T2);
3493       ICS.Standard.setToType(1, T1);
3494       ICS.Standard.setToType(2, T1);
3495       ICS.Standard.ReferenceBinding = true;
3496       ICS.Standard.DirectBinding = true;
3497       ICS.Standard.IsLvalueReference = !isRValRef;
3498       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3499       ICS.Standard.BindsToRvalue = false;
3500       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3501       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
3502       ICS.Standard.CopyConstructor = 0;
3503
3504       // Nothing more to do: the inaccessibility/ambiguity check for
3505       // derived-to-base conversions is suppressed when we're
3506       // computing the implicit conversion sequence (C++
3507       // [over.best.ics]p2).
3508       return ICS;
3509     }
3510
3511     //       -- has a class type (i.e., T2 is a class type), where T1 is
3512     //          not reference-related to T2, and can be implicitly
3513     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
3514     //          is reference-compatible with "cv3 T3" 92) (this
3515     //          conversion is selected by enumerating the applicable
3516     //          conversion functions (13.3.1.6) and choosing the best
3517     //          one through overload resolution (13.3)),
3518     if (!SuppressUserConversions && T2->isRecordType() &&
3519         !S.RequireCompleteType(DeclLoc, T2, 0) &&
3520         RefRelationship == Sema::Ref_Incompatible) {
3521       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3522                                    Init, T2, /*AllowRvalues=*/false,
3523                                    AllowExplicit))
3524         return ICS;
3525     }
3526   }
3527
3528   //     -- Otherwise, the reference shall be an lvalue reference to a
3529   //        non-volatile const type (i.e., cv1 shall be const), or the reference
3530   //        shall be an rvalue reference.
3531   //
3532   // We actually handle one oddity of C++ [over.ics.ref] at this
3533   // point, which is that, due to p2 (which short-circuits reference
3534   // binding by only attempting a simple conversion for non-direct
3535   // bindings) and p3's strange wording, we allow a const volatile
3536   // reference to bind to an rvalue. Hence the check for the presence
3537   // of "const" rather than checking for "const" being the only
3538   // qualifier.
3539   // This is also the point where rvalue references and lvalue inits no longer
3540   // go together.
3541   if (!isRValRef && !T1.isConstQualified())
3542     return ICS;
3543
3544   //       -- If the initializer expression
3545   //
3546   //            -- is an xvalue, class prvalue, array prvalue or function
3547   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
3548   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3549       (InitCategory.isXValue() ||
3550       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3551       (InitCategory.isLValue() && T2->isFunctionType()))) {
3552     ICS.setStandard();
3553     ICS.Standard.First = ICK_Identity;
3554     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3555                       : ObjCConversion? ICK_Compatible_Conversion
3556                       : ICK_Identity;
3557     ICS.Standard.Third = ICK_Identity;
3558     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3559     ICS.Standard.setToType(0, T2);
3560     ICS.Standard.setToType(1, T1);
3561     ICS.Standard.setToType(2, T1);
3562     ICS.Standard.ReferenceBinding = true;
3563     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3564     // binding unless we're binding to a class prvalue.
3565     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3566     // allow the use of rvalue references in C++98/03 for the benefit of
3567     // standard library implementors; therefore, we need the xvalue check here.
3568     ICS.Standard.DirectBinding =
3569       S.getLangOptions().CPlusPlus0x ||
3570       (InitCategory.isPRValue() && !T2->isRecordType());
3571     ICS.Standard.IsLvalueReference = !isRValRef;
3572     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3573     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
3574     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3575     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
3576     ICS.Standard.CopyConstructor = 0;
3577     return ICS;
3578   }
3579
3580   //            -- has a class type (i.e., T2 is a class type), where T1 is not
3581   //               reference-related to T2, and can be implicitly converted to
3582   //               an xvalue, class prvalue, or function lvalue of type
3583   //               "cv3 T3", where "cv1 T1" is reference-compatible with
3584   //               "cv3 T3",
3585   //
3586   //          then the reference is bound to the value of the initializer
3587   //          expression in the first case and to the result of the conversion
3588   //          in the second case (or, in either case, to an appropriate base
3589   //          class subobject).
3590   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3591       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3592       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3593                                Init, T2, /*AllowRvalues=*/true,
3594                                AllowExplicit)) {
3595     // In the second case, if the reference is an rvalue reference
3596     // and the second standard conversion sequence of the
3597     // user-defined conversion sequence includes an lvalue-to-rvalue
3598     // conversion, the program is ill-formed.
3599     if (ICS.isUserDefined() && isRValRef &&
3600         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3601       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3602
3603     return ICS;
3604   }
3605
3606   //       -- Otherwise, a temporary of type "cv1 T1" is created and
3607   //          initialized from the initializer expression using the
3608   //          rules for a non-reference copy initialization (8.5). The
3609   //          reference is then bound to the temporary. If T1 is
3610   //          reference-related to T2, cv1 must be the same
3611   //          cv-qualification as, or greater cv-qualification than,
3612   //          cv2; otherwise, the program is ill-formed.
3613   if (RefRelationship == Sema::Ref_Related) {
3614     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3615     // we would be reference-compatible or reference-compatible with
3616     // added qualification. But that wasn't the case, so the reference
3617     // initialization fails.
3618     //
3619     // Note that we only want to check address spaces and cvr-qualifiers here.
3620     // ObjC GC and lifetime qualifiers aren't important.
3621     Qualifiers T1Quals = T1.getQualifiers();
3622     Qualifiers T2Quals = T2.getQualifiers();
3623     T1Quals.removeObjCGCAttr();
3624     T1Quals.removeObjCLifetime();
3625     T2Quals.removeObjCGCAttr();
3626     T2Quals.removeObjCLifetime();
3627     if (!T1Quals.compatiblyIncludes(T2Quals))
3628       return ICS;
3629   }
3630
3631   // If at least one of the types is a class type, the types are not
3632   // related, and we aren't allowed any user conversions, the
3633   // reference binding fails. This case is important for breaking
3634   // recursion, since TryImplicitConversion below will attempt to
3635   // create a temporary through the use of a copy constructor.
3636   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3637       (T1->isRecordType() || T2->isRecordType()))
3638     return ICS;
3639
3640   // If T1 is reference-related to T2 and the reference is an rvalue
3641   // reference, the initializer expression shall not be an lvalue.
3642   if (RefRelationship >= Sema::Ref_Related &&
3643       isRValRef && Init->Classify(S.Context).isLValue())
3644     return ICS;
3645
3646   // C++ [over.ics.ref]p2:
3647   //   When a parameter of reference type is not bound directly to
3648   //   an argument expression, the conversion sequence is the one
3649   //   required to convert the argument expression to the
3650   //   underlying type of the reference according to
3651   //   13.3.3.1. Conceptually, this conversion sequence corresponds
3652   //   to copy-initializing a temporary of the underlying type with
3653   //   the argument expression. Any difference in top-level
3654   //   cv-qualification is subsumed by the initialization itself
3655   //   and does not constitute a conversion.
3656   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3657                               /*AllowExplicit=*/false,
3658                               /*InOverloadResolution=*/false,
3659                               /*CStyle=*/false,
3660                               /*AllowObjCWritebackConversion=*/false);
3661
3662   // Of course, that's still a reference binding.
3663   if (ICS.isStandard()) {
3664     ICS.Standard.ReferenceBinding = true;
3665     ICS.Standard.IsLvalueReference = !isRValRef;
3666     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3667     ICS.Standard.BindsToRvalue = true;
3668     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3669     ICS.Standard.ObjCLifetimeConversionBinding = false;
3670   } else if (ICS.isUserDefined()) {
3671     // Don't allow rvalue references to bind to lvalues.
3672     if (DeclType->isRValueReferenceType()) {
3673       if (const ReferenceType *RefType
3674             = ICS.UserDefined.ConversionFunction->getResultType()
3675                 ->getAs<LValueReferenceType>()) {
3676         if (!RefType->getPointeeType()->isFunctionType()) {
3677           ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 
3678                      DeclType);
3679           return ICS;
3680         }
3681       }
3682     }
3683     
3684     ICS.UserDefined.After.ReferenceBinding = true;
3685     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3686     ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3687     ICS.UserDefined.After.BindsToRvalue = true;
3688     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3689     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
3690   }
3691
3692   return ICS;
3693 }
3694
3695 /// TryCopyInitialization - Try to copy-initialize a value of type
3696 /// ToType from the expression From. Return the implicit conversion
3697 /// sequence required to pass this argument, which may be a bad
3698 /// conversion sequence (meaning that the argument cannot be passed to
3699 /// a parameter of this type). If @p SuppressUserConversions, then we
3700 /// do not permit any user-defined conversion sequences.
3701 static ImplicitConversionSequence
3702 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3703                       bool SuppressUserConversions,
3704                       bool InOverloadResolution,
3705                       bool AllowObjCWritebackConversion) {
3706   if (ToType->isReferenceType())
3707     return TryReferenceInit(S, From, ToType,
3708                             /*FIXME:*/From->getLocStart(),
3709                             SuppressUserConversions,
3710                             /*AllowExplicit=*/false);
3711
3712   return TryImplicitConversion(S, From, ToType,
3713                                SuppressUserConversions,
3714                                /*AllowExplicit=*/false,
3715                                InOverloadResolution,
3716                                /*CStyle=*/false,
3717                                AllowObjCWritebackConversion);
3718 }
3719
3720 static bool TryCopyInitialization(const CanQualType FromQTy,
3721                                   const CanQualType ToQTy,
3722                                   Sema &S,
3723                                   SourceLocation Loc,
3724                                   ExprValueKind FromVK) {
3725   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3726   ImplicitConversionSequence ICS =
3727     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3728
3729   return !ICS.isBad();
3730 }
3731
3732 /// TryObjectArgumentInitialization - Try to initialize the object
3733 /// parameter of the given member function (@c Method) from the
3734 /// expression @p From.
3735 static ImplicitConversionSequence
3736 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3737                                 Expr::Classification FromClassification,
3738                                 CXXMethodDecl *Method,
3739                                 CXXRecordDecl *ActingContext) {
3740   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
3741   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3742   //                 const volatile object.
3743   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3744     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3745   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
3746
3747   // Set up the conversion sequence as a "bad" conversion, to allow us
3748   // to exit early.
3749   ImplicitConversionSequence ICS;
3750
3751   // We need to have an object of class type.
3752   QualType FromType = OrigFromType;
3753   if (const PointerType *PT = FromType->getAs<PointerType>()) {
3754     FromType = PT->getPointeeType();
3755
3756     // When we had a pointer, it's implicitly dereferenced, so we
3757     // better have an lvalue.
3758     assert(FromClassification.isLValue());
3759   }
3760
3761   assert(FromType->isRecordType());
3762
3763   // C++0x [over.match.funcs]p4:
3764   //   For non-static member functions, the type of the implicit object
3765   //   parameter is
3766   //
3767   //     - "lvalue reference to cv X" for functions declared without a
3768   //        ref-qualifier or with the & ref-qualifier
3769   //     - "rvalue reference to cv X" for functions declared with the &&
3770   //        ref-qualifier
3771   //
3772   // where X is the class of which the function is a member and cv is the
3773   // cv-qualification on the member function declaration.
3774   //
3775   // However, when finding an implicit conversion sequence for the argument, we
3776   // are not allowed to create temporaries or perform user-defined conversions
3777   // (C++ [over.match.funcs]p5). We perform a simplified version of
3778   // reference binding here, that allows class rvalues to bind to
3779   // non-constant references.
3780
3781   // First check the qualifiers.
3782   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
3783   if (ImplicitParamType.getCVRQualifiers()
3784                                     != FromTypeCanon.getLocalCVRQualifiers() &&
3785       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
3786     ICS.setBad(BadConversionSequence::bad_qualifiers,
3787                OrigFromType, ImplicitParamType);
3788     return ICS;
3789   }
3790
3791   // Check that we have either the same type or a derived type. It
3792   // affects the conversion rank.
3793   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
3794   ImplicitConversionKind SecondKind;
3795   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3796     SecondKind = ICK_Identity;
3797   } else if (S.IsDerivedFrom(FromType, ClassType))
3798     SecondKind = ICK_Derived_To_Base;
3799   else {
3800     ICS.setBad(BadConversionSequence::unrelated_class,
3801                FromType, ImplicitParamType);
3802     return ICS;
3803   }
3804
3805   // Check the ref-qualifier.
3806   switch (Method->getRefQualifier()) {
3807   case RQ_None:
3808     // Do nothing; we don't care about lvalueness or rvalueness.
3809     break;
3810
3811   case RQ_LValue:
3812     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3813       // non-const lvalue reference cannot bind to an rvalue
3814       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
3815                  ImplicitParamType);
3816       return ICS;
3817     }
3818     break;
3819
3820   case RQ_RValue:
3821     if (!FromClassification.isRValue()) {
3822       // rvalue reference cannot bind to an lvalue
3823       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
3824                  ImplicitParamType);
3825       return ICS;
3826     }
3827     break;
3828   }
3829
3830   // Success. Mark this as a reference binding.
3831   ICS.setStandard();
3832   ICS.Standard.setAsIdentityConversion();
3833   ICS.Standard.Second = SecondKind;
3834   ICS.Standard.setFromType(FromType);
3835   ICS.Standard.setAllToTypes(ImplicitParamType);
3836   ICS.Standard.ReferenceBinding = true;
3837   ICS.Standard.DirectBinding = true;
3838   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
3839   ICS.Standard.BindsToFunctionLvalue = false;
3840   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3841   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3842     = (Method->getRefQualifier() == RQ_None);
3843   return ICS;
3844 }
3845
3846 /// PerformObjectArgumentInitialization - Perform initialization of
3847 /// the implicit object parameter for the given Method with the given
3848 /// expression.
3849 ExprResult
3850 Sema::PerformObjectArgumentInitialization(Expr *From,
3851                                           NestedNameSpecifier *Qualifier,
3852                                           NamedDecl *FoundDecl,
3853                                           CXXMethodDecl *Method) {
3854   QualType FromRecordType, DestType;
3855   QualType ImplicitParamRecordType  =
3856     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
3857
3858   Expr::Classification FromClassification;
3859   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
3860     FromRecordType = PT->getPointeeType();
3861     DestType = Method->getThisType(Context);
3862     FromClassification = Expr::Classification::makeSimpleLValue();
3863   } else {
3864     FromRecordType = From->getType();
3865     DestType = ImplicitParamRecordType;
3866     FromClassification = From->Classify(Context);
3867   }
3868
3869   // Note that we always use the true parent context when performing
3870   // the actual argument initialization.
3871   ImplicitConversionSequence ICS
3872     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3873                                       Method, Method->getParent());
3874   if (ICS.isBad()) {
3875     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3876       Qualifiers FromQs = FromRecordType.getQualifiers();
3877       Qualifiers ToQs = DestType.getQualifiers();
3878       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3879       if (CVR) {
3880         Diag(From->getSourceRange().getBegin(),
3881              diag::err_member_function_call_bad_cvr)
3882           << Method->getDeclName() << FromRecordType << (CVR - 1)
3883           << From->getSourceRange();
3884         Diag(Method->getLocation(), diag::note_previous_decl)
3885           << Method->getDeclName();
3886         return ExprError();
3887       }
3888     }
3889
3890     return Diag(From->getSourceRange().getBegin(),
3891                 diag::err_implicit_object_parameter_init)
3892        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
3893   }
3894
3895   if (ICS.Standard.Second == ICK_Derived_To_Base) {
3896     ExprResult FromRes =
3897       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3898     if (FromRes.isInvalid())
3899       return ExprError();
3900     From = FromRes.take();
3901   }
3902
3903   if (!Context.hasSameType(From->getType(), DestType))
3904     From = ImpCastExprToType(From, DestType, CK_NoOp,
3905                       From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3906   return Owned(From);
3907 }
3908
3909 /// TryContextuallyConvertToBool - Attempt to contextually convert the
3910 /// expression From to bool (C++0x [conv]p3).
3911 static ImplicitConversionSequence
3912 TryContextuallyConvertToBool(Sema &S, Expr *From) {
3913   // FIXME: This is pretty broken.
3914   return TryImplicitConversion(S, From, S.Context.BoolTy,
3915                                // FIXME: Are these flags correct?
3916                                /*SuppressUserConversions=*/false,
3917                                /*AllowExplicit=*/true,
3918                                /*InOverloadResolution=*/false,
3919                                /*CStyle=*/false,
3920                                /*AllowObjCWritebackConversion=*/false);
3921 }
3922
3923 /// PerformContextuallyConvertToBool - Perform a contextual conversion
3924 /// of the expression From to bool (C++0x [conv]p3).
3925 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
3926   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
3927   if (!ICS.isBad())
3928     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
3929
3930   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
3931     return Diag(From->getSourceRange().getBegin(),
3932                 diag::err_typecheck_bool_condition)
3933                   << From->getType() << From->getSourceRange();
3934   return ExprError();
3935 }
3936
3937 /// dropPointerConversions - If the given standard conversion sequence
3938 /// involves any pointer conversions, remove them.  This may change
3939 /// the result type of the conversion sequence.
3940 static void dropPointerConversion(StandardConversionSequence &SCS) {
3941   if (SCS.Second == ICK_Pointer_Conversion) {
3942     SCS.Second = ICK_Identity;
3943     SCS.Third = ICK_Identity;
3944     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
3945   }
3946 }
3947
3948 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
3949 /// convert the expression From to an Objective-C pointer type.
3950 static ImplicitConversionSequence
3951 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
3952   // Do an implicit conversion to 'id'.
3953   QualType Ty = S.Context.getObjCIdType();
3954   ImplicitConversionSequence ICS
3955     = TryImplicitConversion(S, From, Ty,
3956                             // FIXME: Are these flags correct?
3957                             /*SuppressUserConversions=*/false,
3958                             /*AllowExplicit=*/true,
3959                             /*InOverloadResolution=*/false,
3960                             /*CStyle=*/false,
3961                             /*AllowObjCWritebackConversion=*/false);
3962
3963   // Strip off any final conversions to 'id'.
3964   switch (ICS.getKind()) {
3965   case ImplicitConversionSequence::BadConversion:
3966   case ImplicitConversionSequence::AmbiguousConversion:
3967   case ImplicitConversionSequence::EllipsisConversion:
3968     break;
3969
3970   case ImplicitConversionSequence::UserDefinedConversion:
3971     dropPointerConversion(ICS.UserDefined.After);
3972     break;
3973
3974   case ImplicitConversionSequence::StandardConversion:
3975     dropPointerConversion(ICS.Standard);
3976     break;
3977   }
3978
3979   return ICS;
3980 }
3981
3982 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
3983 /// conversion of the expression From to an Objective-C pointer type.
3984 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
3985   QualType Ty = Context.getObjCIdType();
3986   ImplicitConversionSequence ICS =
3987     TryContextuallyConvertToObjCPointer(*this, From);
3988   if (!ICS.isBad())
3989     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3990   return ExprError();
3991 }
3992
3993 /// \brief Attempt to convert the given expression to an integral or
3994 /// enumeration type.
3995 ///
3996 /// This routine will attempt to convert an expression of class type to an
3997 /// integral or enumeration type, if that class type only has a single
3998 /// conversion to an integral or enumeration type.
3999 ///
4000 /// \param Loc The source location of the construct that requires the
4001 /// conversion.
4002 ///
4003 /// \param FromE The expression we're converting from.
4004 ///
4005 /// \param NotIntDiag The diagnostic to be emitted if the expression does not
4006 /// have integral or enumeration type.
4007 ///
4008 /// \param IncompleteDiag The diagnostic to be emitted if the expression has
4009 /// incomplete class type.
4010 ///
4011 /// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4012 /// explicit conversion function (because no implicit conversion functions
4013 /// were available). This is a recovery mode.
4014 ///
4015 /// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4016 /// showing which conversion was picked.
4017 ///
4018 /// \param AmbigDiag The diagnostic to be emitted if there is more than one
4019 /// conversion function that could convert to integral or enumeration type.
4020 ///
4021 /// \param AmbigNote The note to be emitted with \p AmbigDiag for each
4022 /// usable conversion function.
4023 ///
4024 /// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4025 /// function, which may be an extension in this case.
4026 ///
4027 /// \returns The expression, converted to an integral or enumeration type if
4028 /// successful.
4029 ExprResult
4030 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
4031                                          const PartialDiagnostic &NotIntDiag,
4032                                        const PartialDiagnostic &IncompleteDiag,
4033                                      const PartialDiagnostic &ExplicitConvDiag,
4034                                      const PartialDiagnostic &ExplicitConvNote,
4035                                          const PartialDiagnostic &AmbigDiag,
4036                                          const PartialDiagnostic &AmbigNote,
4037                                          const PartialDiagnostic &ConvDiag) {
4038   // We can't perform any more checking for type-dependent expressions.
4039   if (From->isTypeDependent())
4040     return Owned(From);
4041
4042   // If the expression already has integral or enumeration type, we're golden.
4043   QualType T = From->getType();
4044   if (T->isIntegralOrEnumerationType())
4045     return Owned(From);
4046
4047   // FIXME: Check for missing '()' if T is a function type?
4048
4049   // If we don't have a class type in C++, there's no way we can get an
4050   // expression of integral or enumeration type.
4051   const RecordType *RecordTy = T->getAs<RecordType>();
4052   if (!RecordTy || !getLangOptions().CPlusPlus) {
4053     Diag(Loc, NotIntDiag)
4054       << T << From->getSourceRange();
4055     return Owned(From);
4056   }
4057
4058   // We must have a complete class type.
4059   if (RequireCompleteType(Loc, T, IncompleteDiag))
4060     return Owned(From);
4061
4062   // Look for a conversion to an integral or enumeration type.
4063   UnresolvedSet<4> ViableConversions;
4064   UnresolvedSet<4> ExplicitConversions;
4065   const UnresolvedSetImpl *Conversions
4066     = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
4067
4068   bool HadMultipleCandidates = (Conversions->size() > 1);
4069
4070   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4071                                    E = Conversions->end();
4072        I != E;
4073        ++I) {
4074     if (CXXConversionDecl *Conversion
4075           = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4076       if (Conversion->getConversionType().getNonReferenceType()
4077             ->isIntegralOrEnumerationType()) {
4078         if (Conversion->isExplicit())
4079           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4080         else
4081           ViableConversions.addDecl(I.getDecl(), I.getAccess());
4082       }
4083   }
4084
4085   switch (ViableConversions.size()) {
4086   case 0:
4087     if (ExplicitConversions.size() == 1) {
4088       DeclAccessPair Found = ExplicitConversions[0];
4089       CXXConversionDecl *Conversion
4090         = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4091
4092       // The user probably meant to invoke the given explicit
4093       // conversion; use it.
4094       QualType ConvTy
4095         = Conversion->getConversionType().getNonReferenceType();
4096       std::string TypeStr;
4097       ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
4098
4099       Diag(Loc, ExplicitConvDiag)
4100         << T << ConvTy
4101         << FixItHint::CreateInsertion(From->getLocStart(),
4102                                       "static_cast<" + TypeStr + ">(")
4103         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4104                                       ")");
4105       Diag(Conversion->getLocation(), ExplicitConvNote)
4106         << ConvTy->isEnumeralType() << ConvTy;
4107
4108       // If we aren't in a SFINAE context, build a call to the
4109       // explicit conversion function.
4110       if (isSFINAEContext())
4111         return ExprError();
4112
4113       CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
4114       ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4115                                                  HadMultipleCandidates);
4116       if (Result.isInvalid())
4117         return ExprError();
4118
4119       From = Result.get();
4120     }
4121
4122     // We'll complain below about a non-integral condition type.
4123     break;
4124
4125   case 1: {
4126     // Apply this conversion.
4127     DeclAccessPair Found = ViableConversions[0];
4128     CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
4129
4130     CXXConversionDecl *Conversion
4131       = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4132     QualType ConvTy
4133       = Conversion->getConversionType().getNonReferenceType();
4134     if (ConvDiag.getDiagID()) {
4135       if (isSFINAEContext())
4136         return ExprError();
4137
4138       Diag(Loc, ConvDiag)
4139         << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4140     }
4141
4142     ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4143                                                HadMultipleCandidates);
4144     if (Result.isInvalid())
4145       return ExprError();
4146
4147     From = Result.get();
4148     break;
4149   }
4150
4151   default:
4152     Diag(Loc, AmbigDiag)
4153       << T << From->getSourceRange();
4154     for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4155       CXXConversionDecl *Conv
4156         = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4157       QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4158       Diag(Conv->getLocation(), AmbigNote)
4159         << ConvTy->isEnumeralType() << ConvTy;
4160     }
4161     return Owned(From);
4162   }
4163
4164   if (!From->getType()->isIntegralOrEnumerationType())
4165     Diag(Loc, NotIntDiag)
4166       << From->getType() << From->getSourceRange();
4167
4168   return Owned(From);
4169 }
4170
4171 /// AddOverloadCandidate - Adds the given function to the set of
4172 /// candidate functions, using the given function call arguments.  If
4173 /// @p SuppressUserConversions, then don't allow user-defined
4174 /// conversions via constructors or conversion operators.
4175 ///
4176 /// \para PartialOverloading true if we are performing "partial" overloading
4177 /// based on an incomplete set of function arguments. This feature is used by
4178 /// code completion.
4179 void
4180 Sema::AddOverloadCandidate(FunctionDecl *Function,
4181                            DeclAccessPair FoundDecl,
4182                            Expr **Args, unsigned NumArgs,
4183                            OverloadCandidateSet& CandidateSet,
4184                            bool SuppressUserConversions,
4185                            bool PartialOverloading) {
4186   const FunctionProtoType* Proto
4187     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
4188   assert(Proto && "Functions without a prototype cannot be overloaded");
4189   assert(!Function->getDescribedFunctionTemplate() &&
4190          "Use AddTemplateOverloadCandidate for function templates");
4191
4192   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
4193     if (!isa<CXXConstructorDecl>(Method)) {
4194       // If we get here, it's because we're calling a member function
4195       // that is named without a member access expression (e.g.,
4196       // "this->f") that was either written explicitly or created
4197       // implicitly. This can happen with a qualified call to a member
4198       // function, e.g., X::f(). We use an empty type for the implied
4199       // object argument (C++ [over.call.func]p3), and the acting context
4200       // is irrelevant.
4201       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
4202                          QualType(), Expr::Classification::makeSimpleLValue(),
4203                          Args, NumArgs, CandidateSet,
4204                          SuppressUserConversions);
4205       return;
4206     }
4207     // We treat a constructor like a non-member function, since its object
4208     // argument doesn't participate in overload resolution.
4209   }
4210
4211   if (!CandidateSet.isNewCandidate(Function))
4212     return;
4213
4214   // Overload resolution is always an unevaluated context.
4215   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4216
4217   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4218     // C++ [class.copy]p3:
4219     //   A member function template is never instantiated to perform the copy
4220     //   of a class object to an object of its class type.
4221     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
4222     if (NumArgs == 1 &&
4223         Constructor->isSpecializationCopyingObject() &&
4224         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4225          IsDerivedFrom(Args[0]->getType(), ClassType)))
4226       return;
4227   }
4228
4229   // Add this candidate
4230   CandidateSet.push_back(OverloadCandidate());
4231   OverloadCandidate& Candidate = CandidateSet.back();
4232   Candidate.FoundDecl = FoundDecl;
4233   Candidate.Function = Function;
4234   Candidate.Viable = true;
4235   Candidate.IsSurrogate = false;
4236   Candidate.IgnoreObjectArgument = false;
4237   Candidate.ExplicitCallArguments = NumArgs;
4238
4239   unsigned NumArgsInProto = Proto->getNumArgs();
4240
4241   // (C++ 13.3.2p2): A candidate function having fewer than m
4242   // parameters is viable only if it has an ellipsis in its parameter
4243   // list (8.3.5).
4244   if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
4245       !Proto->isVariadic()) {
4246     Candidate.Viable = false;
4247     Candidate.FailureKind = ovl_fail_too_many_arguments;
4248     return;
4249   }
4250
4251   // (C++ 13.3.2p2): A candidate function having more than m parameters
4252   // is viable only if the (m+1)st parameter has a default argument
4253   // (8.3.6). For the purposes of overload resolution, the
4254   // parameter list is truncated on the right, so that there are
4255   // exactly m parameters.
4256   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
4257   if (NumArgs < MinRequiredArgs && !PartialOverloading) {
4258     // Not enough arguments.
4259     Candidate.Viable = false;
4260     Candidate.FailureKind = ovl_fail_too_few_arguments;
4261     return;
4262   }
4263
4264   // (CUDA B.1): Check for invalid calls between targets.
4265   if (getLangOptions().CUDA)
4266     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4267       if (CheckCUDATarget(Caller, Function)) {
4268         Candidate.Viable = false;
4269         Candidate.FailureKind = ovl_fail_bad_target;
4270         return;
4271       }
4272
4273   // Determine the implicit conversion sequences for each of the
4274   // arguments.
4275   Candidate.Conversions.resize(NumArgs);
4276   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4277     if (ArgIdx < NumArgsInProto) {
4278       // (C++ 13.3.2p3): for F to be a viable function, there shall
4279       // exist for each argument an implicit conversion sequence
4280       // (13.3.3.1) that converts that argument to the corresponding
4281       // parameter of F.
4282       QualType ParamType = Proto->getArgType(ArgIdx);
4283       Candidate.Conversions[ArgIdx]
4284         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4285                                 SuppressUserConversions,
4286                                 /*InOverloadResolution=*/true,
4287                                 /*AllowObjCWritebackConversion=*/
4288                                   getLangOptions().ObjCAutoRefCount);
4289       if (Candidate.Conversions[ArgIdx].isBad()) {
4290         Candidate.Viable = false;
4291         Candidate.FailureKind = ovl_fail_bad_conversion;
4292         break;
4293       }
4294     } else {
4295       // (C++ 13.3.2p2): For the purposes of overload resolution, any
4296       // argument for which there is no corresponding parameter is
4297       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4298       Candidate.Conversions[ArgIdx].setEllipsis();
4299     }
4300   }
4301 }
4302
4303 /// \brief Add all of the function declarations in the given function set to
4304 /// the overload canddiate set.
4305 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
4306                                  Expr **Args, unsigned NumArgs,
4307                                  OverloadCandidateSet& CandidateSet,
4308                                  bool SuppressUserConversions) {
4309   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
4310     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4311     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4312       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
4313         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
4314                            cast<CXXMethodDecl>(FD)->getParent(),
4315                            Args[0]->getType(), Args[0]->Classify(Context),
4316                            Args + 1, NumArgs - 1,
4317                            CandidateSet, SuppressUserConversions);
4318       else
4319         AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
4320                              SuppressUserConversions);
4321     } else {
4322       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
4323       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4324           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
4325         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
4326                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
4327                                    /*FIXME: explicit args */ 0,
4328                                    Args[0]->getType(),
4329                                    Args[0]->Classify(Context),
4330                                    Args + 1, NumArgs - 1,
4331                                    CandidateSet,
4332                                    SuppressUserConversions);
4333       else
4334         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
4335                                      /*FIXME: explicit args */ 0,
4336                                      Args, NumArgs, CandidateSet,
4337                                      SuppressUserConversions);
4338     }
4339   }
4340 }
4341
4342 /// AddMethodCandidate - Adds a named decl (which is some kind of
4343 /// method) as a method candidate to the given overload set.
4344 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
4345                               QualType ObjectType,
4346                               Expr::Classification ObjectClassification,
4347                               Expr **Args, unsigned NumArgs,
4348                               OverloadCandidateSet& CandidateSet,
4349                               bool SuppressUserConversions) {
4350   NamedDecl *Decl = FoundDecl.getDecl();
4351   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
4352
4353   if (isa<UsingShadowDecl>(Decl))
4354     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
4355
4356   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4357     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4358            "Expected a member function template");
4359     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4360                                /*ExplicitArgs*/ 0,
4361                                ObjectType, ObjectClassification, Args, NumArgs,
4362                                CandidateSet,
4363                                SuppressUserConversions);
4364   } else {
4365     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
4366                        ObjectType, ObjectClassification, Args, NumArgs,
4367                        CandidateSet, SuppressUserConversions);
4368   }
4369 }
4370
4371 /// AddMethodCandidate - Adds the given C++ member function to the set
4372 /// of candidate functions, using the given function call arguments
4373 /// and the object argument (@c Object). For example, in a call
4374 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4375 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4376 /// allow user-defined conversions via constructors or conversion
4377 /// operators.
4378 void
4379 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
4380                          CXXRecordDecl *ActingContext, QualType ObjectType,
4381                          Expr::Classification ObjectClassification,
4382                          Expr **Args, unsigned NumArgs,
4383                          OverloadCandidateSet& CandidateSet,
4384                          bool SuppressUserConversions) {
4385   const FunctionProtoType* Proto
4386     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
4387   assert(Proto && "Methods without a prototype cannot be overloaded");
4388   assert(!isa<CXXConstructorDecl>(Method) &&
4389          "Use AddOverloadCandidate for constructors");
4390
4391   if (!CandidateSet.isNewCandidate(Method))
4392     return;
4393
4394   // Overload resolution is always an unevaluated context.
4395   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4396
4397   // Add this candidate
4398   CandidateSet.push_back(OverloadCandidate());
4399   OverloadCandidate& Candidate = CandidateSet.back();
4400   Candidate.FoundDecl = FoundDecl;
4401   Candidate.Function = Method;
4402   Candidate.IsSurrogate = false;
4403   Candidate.IgnoreObjectArgument = false;
4404   Candidate.ExplicitCallArguments = NumArgs;
4405
4406   unsigned NumArgsInProto = Proto->getNumArgs();
4407
4408   // (C++ 13.3.2p2): A candidate function having fewer than m
4409   // parameters is viable only if it has an ellipsis in its parameter
4410   // list (8.3.5).
4411   if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4412     Candidate.Viable = false;
4413     Candidate.FailureKind = ovl_fail_too_many_arguments;
4414     return;
4415   }
4416
4417   // (C++ 13.3.2p2): A candidate function having more than m parameters
4418   // is viable only if the (m+1)st parameter has a default argument
4419   // (8.3.6). For the purposes of overload resolution, the
4420   // parameter list is truncated on the right, so that there are
4421   // exactly m parameters.
4422   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4423   if (NumArgs < MinRequiredArgs) {
4424     // Not enough arguments.
4425     Candidate.Viable = false;
4426     Candidate.FailureKind = ovl_fail_too_few_arguments;
4427     return;
4428   }
4429
4430   Candidate.Viable = true;
4431   Candidate.Conversions.resize(NumArgs + 1);
4432
4433   if (Method->isStatic() || ObjectType.isNull())
4434     // The implicit object argument is ignored.
4435     Candidate.IgnoreObjectArgument = true;
4436   else {
4437     // Determine the implicit conversion sequence for the object
4438     // parameter.
4439     Candidate.Conversions[0]
4440       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4441                                         Method, ActingContext);
4442     if (Candidate.Conversions[0].isBad()) {
4443       Candidate.Viable = false;
4444       Candidate.FailureKind = ovl_fail_bad_conversion;
4445       return;
4446     }
4447   }
4448
4449   // Determine the implicit conversion sequences for each of the
4450   // arguments.
4451   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4452     if (ArgIdx < NumArgsInProto) {
4453       // (C++ 13.3.2p3): for F to be a viable function, there shall
4454       // exist for each argument an implicit conversion sequence
4455       // (13.3.3.1) that converts that argument to the corresponding
4456       // parameter of F.
4457       QualType ParamType = Proto->getArgType(ArgIdx);
4458       Candidate.Conversions[ArgIdx + 1]
4459         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4460                                 SuppressUserConversions,
4461                                 /*InOverloadResolution=*/true,
4462                                 /*AllowObjCWritebackConversion=*/
4463                                   getLangOptions().ObjCAutoRefCount);
4464       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
4465         Candidate.Viable = false;
4466         Candidate.FailureKind = ovl_fail_bad_conversion;
4467         break;
4468       }
4469     } else {
4470       // (C++ 13.3.2p2): For the purposes of overload resolution, any
4471       // argument for which there is no corresponding parameter is
4472       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4473       Candidate.Conversions[ArgIdx + 1].setEllipsis();
4474     }
4475   }
4476 }
4477
4478 /// \brief Add a C++ member function template as a candidate to the candidate
4479 /// set, using template argument deduction to produce an appropriate member
4480 /// function template specialization.
4481 void
4482 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
4483                                  DeclAccessPair FoundDecl,
4484                                  CXXRecordDecl *ActingContext,
4485                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
4486                                  QualType ObjectType,
4487                                  Expr::Classification ObjectClassification,
4488                                  Expr **Args, unsigned NumArgs,
4489                                  OverloadCandidateSet& CandidateSet,
4490                                  bool SuppressUserConversions) {
4491   if (!CandidateSet.isNewCandidate(MethodTmpl))
4492     return;
4493
4494   // C++ [over.match.funcs]p7:
4495   //   In each case where a candidate is a function template, candidate
4496   //   function template specializations are generated using template argument
4497   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
4498   //   candidate functions in the usual way.113) A given name can refer to one
4499   //   or more function templates and also to a set of overloaded non-template
4500   //   functions. In such a case, the candidate functions generated from each
4501   //   function template are combined with the set of non-template candidate
4502   //   functions.
4503   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4504   FunctionDecl *Specialization = 0;
4505   if (TemplateDeductionResult Result
4506       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
4507                                 Args, NumArgs, Specialization, Info)) {
4508     CandidateSet.push_back(OverloadCandidate());
4509     OverloadCandidate &Candidate = CandidateSet.back();
4510     Candidate.FoundDecl = FoundDecl;
4511     Candidate.Function = MethodTmpl->getTemplatedDecl();
4512     Candidate.Viable = false;
4513     Candidate.FailureKind = ovl_fail_bad_deduction;
4514     Candidate.IsSurrogate = false;
4515     Candidate.IgnoreObjectArgument = false;
4516     Candidate.ExplicitCallArguments = NumArgs;
4517     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4518                                                           Info);
4519     return;
4520   }
4521
4522   // Add the function template specialization produced by template argument
4523   // deduction as a candidate.
4524   assert(Specialization && "Missing member function template specialization?");
4525   assert(isa<CXXMethodDecl>(Specialization) &&
4526          "Specialization is not a member function?");
4527   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
4528                      ActingContext, ObjectType, ObjectClassification,
4529                      Args, NumArgs, CandidateSet, SuppressUserConversions);
4530 }
4531
4532 /// \brief Add a C++ function template specialization as a candidate
4533 /// in the candidate set, using template argument deduction to produce
4534 /// an appropriate function template specialization.
4535 void
4536 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
4537                                    DeclAccessPair FoundDecl,
4538                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
4539                                    Expr **Args, unsigned NumArgs,
4540                                    OverloadCandidateSet& CandidateSet,
4541                                    bool SuppressUserConversions) {
4542   if (!CandidateSet.isNewCandidate(FunctionTemplate))
4543     return;
4544
4545   // C++ [over.match.funcs]p7:
4546   //   In each case where a candidate is a function template, candidate
4547   //   function template specializations are generated using template argument
4548   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
4549   //   candidate functions in the usual way.113) A given name can refer to one
4550   //   or more function templates and also to a set of overloaded non-template
4551   //   functions. In such a case, the candidate functions generated from each
4552   //   function template are combined with the set of non-template candidate
4553   //   functions.
4554   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4555   FunctionDecl *Specialization = 0;
4556   if (TemplateDeductionResult Result
4557         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4558                                   Args, NumArgs, Specialization, Info)) {
4559     CandidateSet.push_back(OverloadCandidate());
4560     OverloadCandidate &Candidate = CandidateSet.back();
4561     Candidate.FoundDecl = FoundDecl;
4562     Candidate.Function = FunctionTemplate->getTemplatedDecl();
4563     Candidate.Viable = false;
4564     Candidate.FailureKind = ovl_fail_bad_deduction;
4565     Candidate.IsSurrogate = false;
4566     Candidate.IgnoreObjectArgument = false;
4567     Candidate.ExplicitCallArguments = NumArgs;
4568     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4569                                                           Info);
4570     return;
4571   }
4572
4573   // Add the function template specialization produced by template argument
4574   // deduction as a candidate.
4575   assert(Specialization && "Missing function template specialization?");
4576   AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
4577                        SuppressUserConversions);
4578 }
4579
4580 /// AddConversionCandidate - Add a C++ conversion function as a
4581 /// candidate in the candidate set (C++ [over.match.conv],
4582 /// C++ [over.match.copy]). From is the expression we're converting from,
4583 /// and ToType is the type that we're eventually trying to convert to
4584 /// (which may or may not be the same type as the type that the
4585 /// conversion function produces).
4586 void
4587 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
4588                              DeclAccessPair FoundDecl,
4589                              CXXRecordDecl *ActingContext,
4590                              Expr *From, QualType ToType,
4591                              OverloadCandidateSet& CandidateSet) {
4592   assert(!Conversion->getDescribedFunctionTemplate() &&
4593          "Conversion function templates use AddTemplateConversionCandidate");
4594   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
4595   if (!CandidateSet.isNewCandidate(Conversion))
4596     return;
4597
4598   // Overload resolution is always an unevaluated context.
4599   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4600
4601   // Add this candidate
4602   CandidateSet.push_back(OverloadCandidate());
4603   OverloadCandidate& Candidate = CandidateSet.back();
4604   Candidate.FoundDecl = FoundDecl;
4605   Candidate.Function = Conversion;
4606   Candidate.IsSurrogate = false;
4607   Candidate.IgnoreObjectArgument = false;
4608   Candidate.FinalConversion.setAsIdentityConversion();
4609   Candidate.FinalConversion.setFromType(ConvType);
4610   Candidate.FinalConversion.setAllToTypes(ToType);
4611   Candidate.Viable = true;
4612   Candidate.Conversions.resize(1);
4613   Candidate.ExplicitCallArguments = 1;
4614
4615   // C++ [over.match.funcs]p4:
4616   //   For conversion functions, the function is considered to be a member of
4617   //   the class of the implicit implied object argument for the purpose of
4618   //   defining the type of the implicit object parameter.
4619   //
4620   // Determine the implicit conversion sequence for the implicit
4621   // object parameter.
4622   QualType ImplicitParamType = From->getType();
4623   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4624     ImplicitParamType = FromPtrType->getPointeeType();
4625   CXXRecordDecl *ConversionContext
4626     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
4627
4628   Candidate.Conversions[0]
4629     = TryObjectArgumentInitialization(*this, From->getType(),
4630                                       From->Classify(Context),
4631                                       Conversion, ConversionContext);
4632
4633   if (Candidate.Conversions[0].isBad()) {
4634     Candidate.Viable = false;
4635     Candidate.FailureKind = ovl_fail_bad_conversion;
4636     return;
4637   }
4638
4639   // We won't go through a user-define type conversion function to convert a
4640   // derived to base as such conversions are given Conversion Rank. They only
4641   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4642   QualType FromCanon
4643     = Context.getCanonicalType(From->getType().getUnqualifiedType());
4644   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4645   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4646     Candidate.Viable = false;
4647     Candidate.FailureKind = ovl_fail_trivial_conversion;
4648     return;
4649   }
4650
4651   // To determine what the conversion from the result of calling the
4652   // conversion function to the type we're eventually trying to
4653   // convert to (ToType), we need to synthesize a call to the
4654   // conversion function and attempt copy initialization from it. This
4655   // makes sure that we get the right semantics with respect to
4656   // lvalues/rvalues and the type. Fortunately, we can allocate this
4657   // call on the stack and we don't need its arguments to be
4658   // well-formed.
4659   DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
4660                             VK_LValue, From->getLocStart());
4661   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4662                                 Context.getPointerType(Conversion->getType()),
4663                                 CK_FunctionToPointerDecay,
4664                                 &ConversionRef, VK_RValue);
4665
4666   QualType ConversionType = Conversion->getConversionType();
4667   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
4668     Candidate.Viable = false;
4669     Candidate.FailureKind = ovl_fail_bad_final_conversion;
4670     return;
4671   }
4672
4673   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
4674
4675   // Note that it is safe to allocate CallExpr on the stack here because
4676   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4677   // allocator).
4678   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
4679   CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
4680                 From->getLocStart());
4681   ImplicitConversionSequence ICS =
4682     TryCopyInitialization(*this, &Call, ToType,
4683                           /*SuppressUserConversions=*/true,
4684                           /*InOverloadResolution=*/false,
4685                           /*AllowObjCWritebackConversion=*/false);
4686
4687   switch (ICS.getKind()) {
4688   case ImplicitConversionSequence::StandardConversion:
4689     Candidate.FinalConversion = ICS.Standard;
4690
4691     // C++ [over.ics.user]p3:
4692     //   If the user-defined conversion is specified by a specialization of a
4693     //   conversion function template, the second standard conversion sequence
4694     //   shall have exact match rank.
4695     if (Conversion->getPrimaryTemplate() &&
4696         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4697       Candidate.Viable = false;
4698       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4699     }
4700
4701     // C++0x [dcl.init.ref]p5:
4702     //    In the second case, if the reference is an rvalue reference and
4703     //    the second standard conversion sequence of the user-defined
4704     //    conversion sequence includes an lvalue-to-rvalue conversion, the
4705     //    program is ill-formed.
4706     if (ToType->isRValueReferenceType() &&
4707         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4708       Candidate.Viable = false;
4709       Candidate.FailureKind = ovl_fail_bad_final_conversion;
4710     }
4711     break;
4712
4713   case ImplicitConversionSequence::BadConversion:
4714     Candidate.Viable = false;
4715     Candidate.FailureKind = ovl_fail_bad_final_conversion;
4716     break;
4717
4718   default:
4719     llvm_unreachable(
4720            "Can only end up with a standard conversion sequence or failure");
4721   }
4722 }
4723
4724 /// \brief Adds a conversion function template specialization
4725 /// candidate to the overload set, using template argument deduction
4726 /// to deduce the template arguments of the conversion function
4727 /// template from the type that we are converting to (C++
4728 /// [temp.deduct.conv]).
4729 void
4730 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
4731                                      DeclAccessPair FoundDecl,
4732                                      CXXRecordDecl *ActingDC,
4733                                      Expr *From, QualType ToType,
4734                                      OverloadCandidateSet &CandidateSet) {
4735   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4736          "Only conversion function templates permitted here");
4737
4738   if (!CandidateSet.isNewCandidate(FunctionTemplate))
4739     return;
4740
4741   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4742   CXXConversionDecl *Specialization = 0;
4743   if (TemplateDeductionResult Result
4744         = DeduceTemplateArguments(FunctionTemplate, ToType,
4745                                   Specialization, Info)) {
4746     CandidateSet.push_back(OverloadCandidate());
4747     OverloadCandidate &Candidate = CandidateSet.back();
4748     Candidate.FoundDecl = FoundDecl;
4749     Candidate.Function = FunctionTemplate->getTemplatedDecl();
4750     Candidate.Viable = false;
4751     Candidate.FailureKind = ovl_fail_bad_deduction;
4752     Candidate.IsSurrogate = false;
4753     Candidate.IgnoreObjectArgument = false;
4754     Candidate.ExplicitCallArguments = 1;
4755     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4756                                                           Info);
4757     return;
4758   }
4759
4760   // Add the conversion function template specialization produced by
4761   // template argument deduction as a candidate.
4762   assert(Specialization && "Missing function template specialization?");
4763   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
4764                          CandidateSet);
4765 }
4766
4767 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4768 /// converts the given @c Object to a function pointer via the
4769 /// conversion function @c Conversion, and then attempts to call it
4770 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
4771 /// the type of function that we'll eventually be calling.
4772 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
4773                                  DeclAccessPair FoundDecl,
4774                                  CXXRecordDecl *ActingContext,
4775                                  const FunctionProtoType *Proto,
4776                                  Expr *Object,
4777                                  Expr **Args, unsigned NumArgs,
4778                                  OverloadCandidateSet& CandidateSet) {
4779   if (!CandidateSet.isNewCandidate(Conversion))
4780     return;
4781
4782   // Overload resolution is always an unevaluated context.
4783   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4784
4785   CandidateSet.push_back(OverloadCandidate());
4786   OverloadCandidate& Candidate = CandidateSet.back();
4787   Candidate.FoundDecl = FoundDecl;
4788   Candidate.Function = 0;
4789   Candidate.Surrogate = Conversion;
4790   Candidate.Viable = true;
4791   Candidate.IsSurrogate = true;
4792   Candidate.IgnoreObjectArgument = false;
4793   Candidate.Conversions.resize(NumArgs + 1);
4794   Candidate.ExplicitCallArguments = NumArgs;
4795
4796   // Determine the implicit conversion sequence for the implicit
4797   // object parameter.
4798   ImplicitConversionSequence ObjectInit
4799     = TryObjectArgumentInitialization(*this, Object->getType(),
4800                                       Object->Classify(Context),
4801                                       Conversion, ActingContext);
4802   if (ObjectInit.isBad()) {
4803     Candidate.Viable = false;
4804     Candidate.FailureKind = ovl_fail_bad_conversion;
4805     Candidate.Conversions[0] = ObjectInit;
4806     return;
4807   }
4808
4809   // The first conversion is actually a user-defined conversion whose
4810   // first conversion is ObjectInit's standard conversion (which is
4811   // effectively a reference binding). Record it as such.
4812   Candidate.Conversions[0].setUserDefined();
4813   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
4814   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
4815   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
4816   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
4817   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
4818   Candidate.Conversions[0].UserDefined.After
4819     = Candidate.Conversions[0].UserDefined.Before;
4820   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4821
4822   // Find the
4823   unsigned NumArgsInProto = Proto->getNumArgs();
4824
4825   // (C++ 13.3.2p2): A candidate function having fewer than m
4826   // parameters is viable only if it has an ellipsis in its parameter
4827   // list (8.3.5).
4828   if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4829     Candidate.Viable = false;
4830     Candidate.FailureKind = ovl_fail_too_many_arguments;
4831     return;
4832   }
4833
4834   // Function types don't have any default arguments, so just check if
4835   // we have enough arguments.
4836   if (NumArgs < NumArgsInProto) {
4837     // Not enough arguments.
4838     Candidate.Viable = false;
4839     Candidate.FailureKind = ovl_fail_too_few_arguments;
4840     return;
4841   }
4842
4843   // Determine the implicit conversion sequences for each of the
4844   // arguments.
4845   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4846     if (ArgIdx < NumArgsInProto) {
4847       // (C++ 13.3.2p3): for F to be a viable function, there shall
4848       // exist for each argument an implicit conversion sequence
4849       // (13.3.3.1) that converts that argument to the corresponding
4850       // parameter of F.
4851       QualType ParamType = Proto->getArgType(ArgIdx);
4852       Candidate.Conversions[ArgIdx + 1]
4853         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4854                                 /*SuppressUserConversions=*/false,
4855                                 /*InOverloadResolution=*/false,
4856                                 /*AllowObjCWritebackConversion=*/
4857                                   getLangOptions().ObjCAutoRefCount);
4858       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
4859         Candidate.Viable = false;
4860         Candidate.FailureKind = ovl_fail_bad_conversion;
4861         break;
4862       }
4863     } else {
4864       // (C++ 13.3.2p2): For the purposes of overload resolution, any
4865       // argument for which there is no corresponding parameter is
4866       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4867       Candidate.Conversions[ArgIdx + 1].setEllipsis();
4868     }
4869   }
4870 }
4871
4872 /// \brief Add overload candidates for overloaded operators that are
4873 /// member functions.
4874 ///
4875 /// Add the overloaded operator candidates that are member functions
4876 /// for the operator Op that was used in an operator expression such
4877 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
4878 /// CandidateSet will store the added overload candidates. (C++
4879 /// [over.match.oper]).
4880 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4881                                        SourceLocation OpLoc,
4882                                        Expr **Args, unsigned NumArgs,
4883                                        OverloadCandidateSet& CandidateSet,
4884                                        SourceRange OpRange) {
4885   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4886
4887   // C++ [over.match.oper]p3:
4888   //   For a unary operator @ with an operand of a type whose
4889   //   cv-unqualified version is T1, and for a binary operator @ with
4890   //   a left operand of a type whose cv-unqualified version is T1 and
4891   //   a right operand of a type whose cv-unqualified version is T2,
4892   //   three sets of candidate functions, designated member
4893   //   candidates, non-member candidates and built-in candidates, are
4894   //   constructed as follows:
4895   QualType T1 = Args[0]->getType();
4896
4897   //     -- If T1 is a class type, the set of member candidates is the
4898   //        result of the qualified lookup of T1::operator@
4899   //        (13.3.1.1.1); otherwise, the set of member candidates is
4900   //        empty.
4901   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
4902     // Complete the type if it can be completed. Otherwise, we're done.
4903     if (RequireCompleteType(OpLoc, T1, PDiag()))
4904       return;
4905
4906     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4907     LookupQualifiedName(Operators, T1Rec->getDecl());
4908     Operators.suppressDiagnostics();
4909
4910     for (LookupResult::iterator Oper = Operators.begin(),
4911                              OperEnd = Operators.end();
4912          Oper != OperEnd;
4913          ++Oper)
4914       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
4915                          Args[0]->Classify(Context), Args + 1, NumArgs - 1,
4916                          CandidateSet,
4917                          /* SuppressUserConversions = */ false);
4918   }
4919 }
4920
4921 /// AddBuiltinCandidate - Add a candidate for a built-in
4922 /// operator. ResultTy and ParamTys are the result and parameter types
4923 /// of the built-in candidate, respectively. Args and NumArgs are the
4924 /// arguments being passed to the candidate. IsAssignmentOperator
4925 /// should be true when this built-in candidate is an assignment
4926 /// operator. NumContextualBoolArguments is the number of arguments
4927 /// (at the beginning of the argument list) that will be contextually
4928 /// converted to bool.
4929 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
4930                                Expr **Args, unsigned NumArgs,
4931                                OverloadCandidateSet& CandidateSet,
4932                                bool IsAssignmentOperator,
4933                                unsigned NumContextualBoolArguments) {
4934   // Overload resolution is always an unevaluated context.
4935   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4936
4937   // Add this candidate
4938   CandidateSet.push_back(OverloadCandidate());
4939   OverloadCandidate& Candidate = CandidateSet.back();
4940   Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
4941   Candidate.Function = 0;
4942   Candidate.IsSurrogate = false;
4943   Candidate.IgnoreObjectArgument = false;
4944   Candidate.BuiltinTypes.ResultTy = ResultTy;
4945   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4946     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4947
4948   // Determine the implicit conversion sequences for each of the
4949   // arguments.
4950   Candidate.Viable = true;
4951   Candidate.Conversions.resize(NumArgs);
4952   Candidate.ExplicitCallArguments = NumArgs;
4953   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4954     // C++ [over.match.oper]p4:
4955     //   For the built-in assignment operators, conversions of the
4956     //   left operand are restricted as follows:
4957     //     -- no temporaries are introduced to hold the left operand, and
4958     //     -- no user-defined conversions are applied to the left
4959     //        operand to achieve a type match with the left-most
4960     //        parameter of a built-in candidate.
4961     //
4962     // We block these conversions by turning off user-defined
4963     // conversions, since that is the only way that initialization of
4964     // a reference to a non-class type can occur from something that
4965     // is not of the same type.
4966     if (ArgIdx < NumContextualBoolArguments) {
4967       assert(ParamTys[ArgIdx] == Context.BoolTy &&
4968              "Contextual conversion to bool requires bool type");
4969       Candidate.Conversions[ArgIdx]
4970         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
4971     } else {
4972       Candidate.Conversions[ArgIdx]
4973         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
4974                                 ArgIdx == 0 && IsAssignmentOperator,
4975                                 /*InOverloadResolution=*/false,
4976                                 /*AllowObjCWritebackConversion=*/
4977                                   getLangOptions().ObjCAutoRefCount);
4978     }
4979     if (Candidate.Conversions[ArgIdx].isBad()) {
4980       Candidate.Viable = false;
4981       Candidate.FailureKind = ovl_fail_bad_conversion;
4982       break;
4983     }
4984   }
4985 }
4986
4987 /// BuiltinCandidateTypeSet - A set of types that will be used for the
4988 /// candidate operator functions for built-in operators (C++
4989 /// [over.built]). The types are separated into pointer types and
4990 /// enumeration types.
4991 class BuiltinCandidateTypeSet  {
4992   /// TypeSet - A set of types.
4993   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
4994
4995   /// PointerTypes - The set of pointer types that will be used in the
4996   /// built-in candidates.
4997   TypeSet PointerTypes;
4998
4999   /// MemberPointerTypes - The set of member pointer types that will be
5000   /// used in the built-in candidates.
5001   TypeSet MemberPointerTypes;
5002
5003   /// EnumerationTypes - The set of enumeration types that will be
5004   /// used in the built-in candidates.
5005   TypeSet EnumerationTypes;
5006
5007   /// \brief The set of vector types that will be used in the built-in
5008   /// candidates.
5009   TypeSet VectorTypes;
5010
5011   /// \brief A flag indicating non-record types are viable candidates
5012   bool HasNonRecordTypes;
5013
5014   /// \brief A flag indicating whether either arithmetic or enumeration types
5015   /// were present in the candidate set.
5016   bool HasArithmeticOrEnumeralTypes;
5017
5018   /// \brief A flag indicating whether the nullptr type was present in the
5019   /// candidate set.
5020   bool HasNullPtrType;
5021   
5022   /// Sema - The semantic analysis instance where we are building the
5023   /// candidate type set.
5024   Sema &SemaRef;
5025
5026   /// Context - The AST context in which we will build the type sets.
5027   ASTContext &Context;
5028
5029   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5030                                                const Qualifiers &VisibleQuals);
5031   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
5032
5033 public:
5034   /// iterator - Iterates through the types that are part of the set.
5035   typedef TypeSet::iterator iterator;
5036
5037   BuiltinCandidateTypeSet(Sema &SemaRef)
5038     : HasNonRecordTypes(false),
5039       HasArithmeticOrEnumeralTypes(false),
5040       HasNullPtrType(false),
5041       SemaRef(SemaRef),
5042       Context(SemaRef.Context) { }
5043
5044   void AddTypesConvertedFrom(QualType Ty,
5045                              SourceLocation Loc,
5046                              bool AllowUserConversions,
5047                              bool AllowExplicitConversions,
5048                              const Qualifiers &VisibleTypeConversionsQuals);
5049
5050   /// pointer_begin - First pointer type found;
5051   iterator pointer_begin() { return PointerTypes.begin(); }
5052
5053   /// pointer_end - Past the last pointer type found;
5054   iterator pointer_end() { return PointerTypes.end(); }
5055
5056   /// member_pointer_begin - First member pointer type found;
5057   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5058
5059   /// member_pointer_end - Past the last member pointer type found;
5060   iterator member_pointer_end() { return MemberPointerTypes.end(); }
5061
5062   /// enumeration_begin - First enumeration type found;
5063   iterator enumeration_begin() { return EnumerationTypes.begin(); }
5064
5065   /// enumeration_end - Past the last enumeration type found;
5066   iterator enumeration_end() { return EnumerationTypes.end(); }
5067
5068   iterator vector_begin() { return VectorTypes.begin(); }
5069   iterator vector_end() { return VectorTypes.end(); }
5070
5071   bool hasNonRecordTypes() { return HasNonRecordTypes; }
5072   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
5073   bool hasNullPtrType() const { return HasNullPtrType; }
5074 };
5075
5076 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
5077 /// the set of pointer types along with any more-qualified variants of
5078 /// that type. For example, if @p Ty is "int const *", this routine
5079 /// will add "int const *", "int const volatile *", "int const
5080 /// restrict *", and "int const volatile restrict *" to the set of
5081 /// pointer types. Returns true if the add of @p Ty itself succeeded,
5082 /// false otherwise.
5083 ///
5084 /// FIXME: what to do about extended qualifiers?
5085 bool
5086 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5087                                              const Qualifiers &VisibleQuals) {
5088
5089   // Insert this type.
5090   if (!PointerTypes.insert(Ty))
5091     return false;
5092
5093   QualType PointeeTy;
5094   const PointerType *PointerTy = Ty->getAs<PointerType>();
5095   bool buildObjCPtr = false;
5096   if (!PointerTy) {
5097     if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
5098       PointeeTy = PTy->getPointeeType();
5099       buildObjCPtr = true;
5100     }
5101     else
5102       llvm_unreachable("type was not a pointer type!");
5103   }
5104   else
5105     PointeeTy = PointerTy->getPointeeType();
5106
5107   // Don't add qualified variants of arrays. For one, they're not allowed
5108   // (the qualifier would sink to the element type), and for another, the
5109   // only overload situation where it matters is subscript or pointer +- int,
5110   // and those shouldn't have qualifier variants anyway.
5111   if (PointeeTy->isArrayType())
5112     return true;
5113   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5114   if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
5115     BaseCVR = Array->getElementType().getCVRQualifiers();
5116   bool hasVolatile = VisibleQuals.hasVolatile();
5117   bool hasRestrict = VisibleQuals.hasRestrict();
5118
5119   // Iterate through all strict supersets of BaseCVR.
5120   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5121     if ((CVR | BaseCVR) != CVR) continue;
5122     // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5123     // in the types.
5124     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5125     if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
5126     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
5127     if (!buildObjCPtr)
5128       PointerTypes.insert(Context.getPointerType(QPointeeTy));
5129     else
5130       PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
5131   }
5132
5133   return true;
5134 }
5135
5136 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5137 /// to the set of pointer types along with any more-qualified variants of
5138 /// that type. For example, if @p Ty is "int const *", this routine
5139 /// will add "int const *", "int const volatile *", "int const
5140 /// restrict *", and "int const volatile restrict *" to the set of
5141 /// pointer types. Returns true if the add of @p Ty itself succeeded,
5142 /// false otherwise.
5143 ///
5144 /// FIXME: what to do about extended qualifiers?
5145 bool
5146 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5147     QualType Ty) {
5148   // Insert this type.
5149   if (!MemberPointerTypes.insert(Ty))
5150     return false;
5151
5152   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5153   assert(PointerTy && "type was not a member pointer type!");
5154
5155   QualType PointeeTy = PointerTy->getPointeeType();
5156   // Don't add qualified variants of arrays. For one, they're not allowed
5157   // (the qualifier would sink to the element type), and for another, the
5158   // only overload situation where it matters is subscript or pointer +- int,
5159   // and those shouldn't have qualifier variants anyway.
5160   if (PointeeTy->isArrayType())
5161     return true;
5162   const Type *ClassTy = PointerTy->getClass();
5163
5164   // Iterate through all strict supersets of the pointee type's CVR
5165   // qualifiers.
5166   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5167   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5168     if ((CVR | BaseCVR) != CVR) continue;
5169
5170     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
5171     MemberPointerTypes.insert(
5172       Context.getMemberPointerType(QPointeeTy, ClassTy));
5173   }
5174
5175   return true;
5176 }
5177
5178 /// AddTypesConvertedFrom - Add each of the types to which the type @p
5179 /// Ty can be implicit converted to the given set of @p Types. We're
5180 /// primarily interested in pointer types and enumeration types. We also
5181 /// take member pointer types, for the conditional operator.
5182 /// AllowUserConversions is true if we should look at the conversion
5183 /// functions of a class type, and AllowExplicitConversions if we
5184 /// should also include the explicit conversion functions of a class
5185 /// type.
5186 void
5187 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
5188                                                SourceLocation Loc,
5189                                                bool AllowUserConversions,
5190                                                bool AllowExplicitConversions,
5191                                                const Qualifiers &VisibleQuals) {
5192   // Only deal with canonical types.
5193   Ty = Context.getCanonicalType(Ty);
5194
5195   // Look through reference types; they aren't part of the type of an
5196   // expression for the purposes of conversions.
5197   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
5198     Ty = RefTy->getPointeeType();
5199
5200   // If we're dealing with an array type, decay to the pointer.
5201   if (Ty->isArrayType())
5202     Ty = SemaRef.Context.getArrayDecayedType(Ty);
5203
5204   // Otherwise, we don't care about qualifiers on the type.
5205   Ty = Ty.getLocalUnqualifiedType();
5206
5207   // Flag if we ever add a non-record type.
5208   const RecordType *TyRec = Ty->getAs<RecordType>();
5209   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5210
5211   // Flag if we encounter an arithmetic type.
5212   HasArithmeticOrEnumeralTypes =
5213     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5214
5215   if (Ty->isObjCIdType() || Ty->isObjCClassType())
5216     PointerTypes.insert(Ty);
5217   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
5218     // Insert our type, and its more-qualified variants, into the set
5219     // of types.
5220     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
5221       return;
5222   } else if (Ty->isMemberPointerType()) {
5223     // Member pointers are far easier, since the pointee can't be converted.
5224     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5225       return;
5226   } else if (Ty->isEnumeralType()) {
5227     HasArithmeticOrEnumeralTypes = true;
5228     EnumerationTypes.insert(Ty);
5229   } else if (Ty->isVectorType()) {
5230     // We treat vector types as arithmetic types in many contexts as an
5231     // extension.
5232     HasArithmeticOrEnumeralTypes = true;
5233     VectorTypes.insert(Ty);
5234   } else if (Ty->isNullPtrType()) {
5235     HasNullPtrType = true;
5236   } else if (AllowUserConversions && TyRec) {
5237     // No conversion functions in incomplete types.
5238     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5239       return;
5240
5241     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5242     const UnresolvedSetImpl *Conversions
5243       = ClassDecl->getVisibleConversionFunctions();
5244     for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5245            E = Conversions->end(); I != E; ++I) {
5246       NamedDecl *D = I.getDecl();
5247       if (isa<UsingShadowDecl>(D))
5248         D = cast<UsingShadowDecl>(D)->getTargetDecl();
5249
5250       // Skip conversion function templates; they don't tell us anything
5251       // about which builtin types we can convert to.
5252       if (isa<FunctionTemplateDecl>(D))
5253         continue;
5254
5255       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5256       if (AllowExplicitConversions || !Conv->isExplicit()) {
5257         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5258                               VisibleQuals);
5259       }
5260     }
5261   }
5262 }
5263
5264 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5265 /// the volatile- and non-volatile-qualified assignment operators for the
5266 /// given type to the candidate set.
5267 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5268                                                    QualType T,
5269                                                    Expr **Args,
5270                                                    unsigned NumArgs,
5271                                     OverloadCandidateSet &CandidateSet) {
5272   QualType ParamTypes[2];
5273
5274   // T& operator=(T&, T)
5275   ParamTypes[0] = S.Context.getLValueReferenceType(T);
5276   ParamTypes[1] = T;
5277   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5278                         /*IsAssignmentOperator=*/true);
5279
5280   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5281     // volatile T& operator=(volatile T&, T)
5282     ParamTypes[0]
5283       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
5284     ParamTypes[1] = T;
5285     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5286                           /*IsAssignmentOperator=*/true);
5287   }
5288 }
5289
5290 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5291 /// if any, found in visible type conversion functions found in ArgExpr's type.
5292 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5293     Qualifiers VRQuals;
5294     const RecordType *TyRec;
5295     if (const MemberPointerType *RHSMPType =
5296         ArgExpr->getType()->getAs<MemberPointerType>())
5297       TyRec = RHSMPType->getClass()->getAs<RecordType>();
5298     else
5299       TyRec = ArgExpr->getType()->getAs<RecordType>();
5300     if (!TyRec) {
5301       // Just to be safe, assume the worst case.
5302       VRQuals.addVolatile();
5303       VRQuals.addRestrict();
5304       return VRQuals;
5305     }
5306
5307     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5308     if (!ClassDecl->hasDefinition())
5309       return VRQuals;
5310
5311     const UnresolvedSetImpl *Conversions =
5312       ClassDecl->getVisibleConversionFunctions();
5313
5314     for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5315            E = Conversions->end(); I != E; ++I) {
5316       NamedDecl *D = I.getDecl();
5317       if (isa<UsingShadowDecl>(D))
5318         D = cast<UsingShadowDecl>(D)->getTargetDecl();
5319       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
5320         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5321         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5322           CanTy = ResTypeRef->getPointeeType();
5323         // Need to go down the pointer/mempointer chain and add qualifiers
5324         // as see them.
5325         bool done = false;
5326         while (!done) {
5327           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5328             CanTy = ResTypePtr->getPointeeType();
5329           else if (const MemberPointerType *ResTypeMPtr =
5330                 CanTy->getAs<MemberPointerType>())
5331             CanTy = ResTypeMPtr->getPointeeType();
5332           else
5333             done = true;
5334           if (CanTy.isVolatileQualified())
5335             VRQuals.addVolatile();
5336           if (CanTy.isRestrictQualified())
5337             VRQuals.addRestrict();
5338           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5339             return VRQuals;
5340         }
5341       }
5342     }
5343     return VRQuals;
5344 }
5345
5346 namespace {
5347
5348 /// \brief Helper class to manage the addition of builtin operator overload
5349 /// candidates. It provides shared state and utility methods used throughout
5350 /// the process, as well as a helper method to add each group of builtin
5351 /// operator overloads from the standard to a candidate set.
5352 class BuiltinOperatorOverloadBuilder {
5353   // Common instance state available to all overload candidate addition methods.
5354   Sema &S;
5355   Expr **Args;
5356   unsigned NumArgs;
5357   Qualifiers VisibleTypeConversionsQuals;
5358   bool HasArithmeticOrEnumeralCandidateType;
5359   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
5360   OverloadCandidateSet &CandidateSet;
5361
5362   // Define some constants used to index and iterate over the arithemetic types
5363   // provided via the getArithmeticType() method below.
5364   // The "promoted arithmetic types" are the arithmetic
5365   // types are that preserved by promotion (C++ [over.built]p2).
5366   static const unsigned FirstIntegralType = 3;
5367   static const unsigned LastIntegralType = 18;
5368   static const unsigned FirstPromotedIntegralType = 3,
5369                         LastPromotedIntegralType = 9;
5370   static const unsigned FirstPromotedArithmeticType = 0,
5371                         LastPromotedArithmeticType = 9;
5372   static const unsigned NumArithmeticTypes = 18;
5373
5374   /// \brief Get the canonical type for a given arithmetic type index.
5375   CanQualType getArithmeticType(unsigned index) {
5376     assert(index < NumArithmeticTypes);
5377     static CanQualType ASTContext::* const
5378       ArithmeticTypes[NumArithmeticTypes] = {
5379       // Start of promoted types.
5380       &ASTContext::FloatTy,
5381       &ASTContext::DoubleTy,
5382       &ASTContext::LongDoubleTy,
5383
5384       // Start of integral types.
5385       &ASTContext::IntTy,
5386       &ASTContext::LongTy,
5387       &ASTContext::LongLongTy,
5388       &ASTContext::UnsignedIntTy,
5389       &ASTContext::UnsignedLongTy,
5390       &ASTContext::UnsignedLongLongTy,
5391       // End of promoted types.
5392
5393       &ASTContext::BoolTy,
5394       &ASTContext::CharTy,
5395       &ASTContext::WCharTy,
5396       &ASTContext::Char16Ty,
5397       &ASTContext::Char32Ty,
5398       &ASTContext::SignedCharTy,
5399       &ASTContext::ShortTy,
5400       &ASTContext::UnsignedCharTy,
5401       &ASTContext::UnsignedShortTy,
5402       // End of integral types.
5403       // FIXME: What about complex?
5404     };
5405     return S.Context.*ArithmeticTypes[index];
5406   }
5407
5408   /// \brief Gets the canonical type resulting from the usual arithemetic
5409   /// converions for the given arithmetic types.
5410   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5411     // Accelerator table for performing the usual arithmetic conversions.
5412     // The rules are basically:
5413     //   - if either is floating-point, use the wider floating-point
5414     //   - if same signedness, use the higher rank
5415     //   - if same size, use unsigned of the higher rank
5416     //   - use the larger type
5417     // These rules, together with the axiom that higher ranks are
5418     // never smaller, are sufficient to precompute all of these results
5419     // *except* when dealing with signed types of higher rank.
5420     // (we could precompute SLL x UI for all known platforms, but it's
5421     // better not to make any assumptions).
5422     enum PromotedType {
5423                   Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL, Dep=-1
5424     };
5425     static PromotedType ConversionsTable[LastPromotedArithmeticType]
5426                                         [LastPromotedArithmeticType] = {
5427       /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
5428       /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
5429       /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5430       /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL },
5431       /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL,  Dep,   UL,  ULL },
5432       /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL,  Dep,  Dep,  ULL },
5433       /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep,   UI,   UL,  ULL },
5434       /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep,   UL,   UL,  ULL },
5435       /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL,  ULL,  ULL,  ULL },
5436     };
5437
5438     assert(L < LastPromotedArithmeticType);
5439     assert(R < LastPromotedArithmeticType);
5440     int Idx = ConversionsTable[L][R];
5441
5442     // Fast path: the table gives us a concrete answer.
5443     if (Idx != Dep) return getArithmeticType(Idx);
5444
5445     // Slow path: we need to compare widths.
5446     // An invariant is that the signed type has higher rank.
5447     CanQualType LT = getArithmeticType(L),
5448                 RT = getArithmeticType(R);
5449     unsigned LW = S.Context.getIntWidth(LT),
5450              RW = S.Context.getIntWidth(RT);
5451
5452     // If they're different widths, use the signed type.
5453     if (LW > RW) return LT;
5454     else if (LW < RW) return RT;
5455
5456     // Otherwise, use the unsigned type of the signed type's rank.
5457     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5458     assert(L == SLL || R == SLL);
5459     return S.Context.UnsignedLongLongTy;
5460   }
5461
5462   /// \brief Helper method to factor out the common pattern of adding overloads
5463   /// for '++' and '--' builtin operators.
5464   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5465                                            bool HasVolatile) {
5466     QualType ParamTypes[2] = {
5467       S.Context.getLValueReferenceType(CandidateTy),
5468       S.Context.IntTy
5469     };
5470
5471     // Non-volatile version.
5472     if (NumArgs == 1)
5473       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5474     else
5475       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5476
5477     // Use a heuristic to reduce number of builtin candidates in the set:
5478     // add volatile version only if there are conversions to a volatile type.
5479     if (HasVolatile) {
5480       ParamTypes[0] =
5481         S.Context.getLValueReferenceType(
5482           S.Context.getVolatileType(CandidateTy));
5483       if (NumArgs == 1)
5484         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5485       else
5486         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5487     }
5488   }
5489
5490 public:
5491   BuiltinOperatorOverloadBuilder(
5492     Sema &S, Expr **Args, unsigned NumArgs,
5493     Qualifiers VisibleTypeConversionsQuals,
5494     bool HasArithmeticOrEnumeralCandidateType,
5495     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5496     OverloadCandidateSet &CandidateSet)
5497     : S(S), Args(Args), NumArgs(NumArgs),
5498       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
5499       HasArithmeticOrEnumeralCandidateType(
5500         HasArithmeticOrEnumeralCandidateType),
5501       CandidateTypes(CandidateTypes),
5502       CandidateSet(CandidateSet) {
5503     // Validate some of our static helper constants in debug builds.
5504     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
5505            "Invalid first promoted integral type");
5506     assert(getArithmeticType(LastPromotedIntegralType - 1)
5507              == S.Context.UnsignedLongLongTy &&
5508            "Invalid last promoted integral type");
5509     assert(getArithmeticType(FirstPromotedArithmeticType)
5510              == S.Context.FloatTy &&
5511            "Invalid first promoted arithmetic type");
5512     assert(getArithmeticType(LastPromotedArithmeticType - 1)
5513              == S.Context.UnsignedLongLongTy &&
5514            "Invalid last promoted arithmetic type");
5515   }
5516
5517   // C++ [over.built]p3:
5518   //
5519   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
5520   //   is either volatile or empty, there exist candidate operator
5521   //   functions of the form
5522   //
5523   //       VQ T&      operator++(VQ T&);
5524   //       T          operator++(VQ T&, int);
5525   //
5526   // C++ [over.built]p4:
5527   //
5528   //   For every pair (T, VQ), where T is an arithmetic type other
5529   //   than bool, and VQ is either volatile or empty, there exist
5530   //   candidate operator functions of the form
5531   //
5532   //       VQ T&      operator--(VQ T&);
5533   //       T          operator--(VQ T&, int);
5534   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
5535     if (!HasArithmeticOrEnumeralCandidateType)
5536       return;
5537
5538     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5539          Arith < NumArithmeticTypes; ++Arith) {
5540       addPlusPlusMinusMinusStyleOverloads(
5541         getArithmeticType(Arith),
5542         VisibleTypeConversionsQuals.hasVolatile());
5543     }
5544   }
5545
5546   // C++ [over.built]p5:
5547   //
5548   //   For every pair (T, VQ), where T is a cv-qualified or
5549   //   cv-unqualified object type, and VQ is either volatile or
5550   //   empty, there exist candidate operator functions of the form
5551   //
5552   //       T*VQ&      operator++(T*VQ&);
5553   //       T*VQ&      operator--(T*VQ&);
5554   //       T*         operator++(T*VQ&, int);
5555   //       T*         operator--(T*VQ&, int);
5556   void addPlusPlusMinusMinusPointerOverloads() {
5557     for (BuiltinCandidateTypeSet::iterator
5558               Ptr = CandidateTypes[0].pointer_begin(),
5559            PtrEnd = CandidateTypes[0].pointer_end();
5560          Ptr != PtrEnd; ++Ptr) {
5561       // Skip pointer types that aren't pointers to object types.
5562       if (!(*Ptr)->getPointeeType()->isObjectType())
5563         continue;
5564
5565       addPlusPlusMinusMinusStyleOverloads(*Ptr,
5566         (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5567          VisibleTypeConversionsQuals.hasVolatile()));
5568     }
5569   }
5570
5571   // C++ [over.built]p6:
5572   //   For every cv-qualified or cv-unqualified object type T, there
5573   //   exist candidate operator functions of the form
5574   //
5575   //       T&         operator*(T*);
5576   //
5577   // C++ [over.built]p7:
5578   //   For every function type T that does not have cv-qualifiers or a
5579   //   ref-qualifier, there exist candidate operator functions of the form
5580   //       T&         operator*(T*);
5581   void addUnaryStarPointerOverloads() {
5582     for (BuiltinCandidateTypeSet::iterator
5583               Ptr = CandidateTypes[0].pointer_begin(),
5584            PtrEnd = CandidateTypes[0].pointer_end();
5585          Ptr != PtrEnd; ++Ptr) {
5586       QualType ParamTy = *Ptr;
5587       QualType PointeeTy = ParamTy->getPointeeType();
5588       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5589         continue;
5590
5591       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5592         if (Proto->getTypeQuals() || Proto->getRefQualifier())
5593           continue;
5594
5595       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5596                             &ParamTy, Args, 1, CandidateSet);
5597     }
5598   }
5599
5600   // C++ [over.built]p9:
5601   //  For every promoted arithmetic type T, there exist candidate
5602   //  operator functions of the form
5603   //
5604   //       T         operator+(T);
5605   //       T         operator-(T);
5606   void addUnaryPlusOrMinusArithmeticOverloads() {
5607     if (!HasArithmeticOrEnumeralCandidateType)
5608       return;
5609
5610     for (unsigned Arith = FirstPromotedArithmeticType;
5611          Arith < LastPromotedArithmeticType; ++Arith) {
5612       QualType ArithTy = getArithmeticType(Arith);
5613       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5614     }
5615
5616     // Extension: We also add these operators for vector types.
5617     for (BuiltinCandidateTypeSet::iterator
5618               Vec = CandidateTypes[0].vector_begin(),
5619            VecEnd = CandidateTypes[0].vector_end();
5620          Vec != VecEnd; ++Vec) {
5621       QualType VecTy = *Vec;
5622       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5623     }
5624   }
5625
5626   // C++ [over.built]p8:
5627   //   For every type T, there exist candidate operator functions of
5628   //   the form
5629   //
5630   //       T*         operator+(T*);
5631   void addUnaryPlusPointerOverloads() {
5632     for (BuiltinCandidateTypeSet::iterator
5633               Ptr = CandidateTypes[0].pointer_begin(),
5634            PtrEnd = CandidateTypes[0].pointer_end();
5635          Ptr != PtrEnd; ++Ptr) {
5636       QualType ParamTy = *Ptr;
5637       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5638     }
5639   }
5640
5641   // C++ [over.built]p10:
5642   //   For every promoted integral type T, there exist candidate
5643   //   operator functions of the form
5644   //
5645   //        T         operator~(T);
5646   void addUnaryTildePromotedIntegralOverloads() {
5647     if (!HasArithmeticOrEnumeralCandidateType)
5648       return;
5649
5650     for (unsigned Int = FirstPromotedIntegralType;
5651          Int < LastPromotedIntegralType; ++Int) {
5652       QualType IntTy = getArithmeticType(Int);
5653       S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5654     }
5655
5656     // Extension: We also add this operator for vector types.
5657     for (BuiltinCandidateTypeSet::iterator
5658               Vec = CandidateTypes[0].vector_begin(),
5659            VecEnd = CandidateTypes[0].vector_end();
5660          Vec != VecEnd; ++Vec) {
5661       QualType VecTy = *Vec;
5662       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5663     }
5664   }
5665
5666   // C++ [over.match.oper]p16:
5667   //   For every pointer to member type T, there exist candidate operator
5668   //   functions of the form
5669   //
5670   //        bool operator==(T,T);
5671   //        bool operator!=(T,T);
5672   void addEqualEqualOrNotEqualMemberPointerOverloads() {
5673     /// Set of (canonical) types that we've already handled.
5674     llvm::SmallPtrSet<QualType, 8> AddedTypes;
5675
5676     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5677       for (BuiltinCandidateTypeSet::iterator
5678                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5679              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5680            MemPtr != MemPtrEnd;
5681            ++MemPtr) {
5682         // Don't add the same builtin candidate twice.
5683         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5684           continue;
5685
5686         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5687         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5688                               CandidateSet);
5689       }
5690     }
5691   }
5692
5693   // C++ [over.built]p15:
5694   //
5695   //   For every T, where T is an enumeration type, a pointer type, or 
5696   //   std::nullptr_t, there exist candidate operator functions of the form
5697   //
5698   //        bool       operator<(T, T);
5699   //        bool       operator>(T, T);
5700   //        bool       operator<=(T, T);
5701   //        bool       operator>=(T, T);
5702   //        bool       operator==(T, T);
5703   //        bool       operator!=(T, T);
5704   void addRelationalPointerOrEnumeralOverloads() {
5705     // C++ [over.built]p1:
5706     //   If there is a user-written candidate with the same name and parameter
5707     //   types as a built-in candidate operator function, the built-in operator
5708     //   function is hidden and is not included in the set of candidate
5709     //   functions.
5710     //
5711     // The text is actually in a note, but if we don't implement it then we end
5712     // up with ambiguities when the user provides an overloaded operator for
5713     // an enumeration type. Note that only enumeration types have this problem,
5714     // so we track which enumeration types we've seen operators for. Also, the
5715     // only other overloaded operator with enumeration argumenst, operator=,
5716     // cannot be overloaded for enumeration types, so this is the only place
5717     // where we must suppress candidates like this.
5718     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5719       UserDefinedBinaryOperators;
5720
5721     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5722       if (CandidateTypes[ArgIdx].enumeration_begin() !=
5723           CandidateTypes[ArgIdx].enumeration_end()) {
5724         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5725                                          CEnd = CandidateSet.end();
5726              C != CEnd; ++C) {
5727           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5728             continue;
5729
5730           QualType FirstParamType =
5731             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5732           QualType SecondParamType =
5733             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5734
5735           // Skip if either parameter isn't of enumeral type.
5736           if (!FirstParamType->isEnumeralType() ||
5737               !SecondParamType->isEnumeralType())
5738             continue;
5739
5740           // Add this operator to the set of known user-defined operators.
5741           UserDefinedBinaryOperators.insert(
5742             std::make_pair(S.Context.getCanonicalType(FirstParamType),
5743                            S.Context.getCanonicalType(SecondParamType)));
5744         }
5745       }
5746     }
5747
5748     /// Set of (canonical) types that we've already handled.
5749     llvm::SmallPtrSet<QualType, 8> AddedTypes;
5750
5751     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5752       for (BuiltinCandidateTypeSet::iterator
5753                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5754              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5755            Ptr != PtrEnd; ++Ptr) {
5756         // Don't add the same builtin candidate twice.
5757         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5758           continue;
5759
5760         QualType ParamTypes[2] = { *Ptr, *Ptr };
5761         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5762                               CandidateSet);
5763       }
5764       for (BuiltinCandidateTypeSet::iterator
5765                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5766              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5767            Enum != EnumEnd; ++Enum) {
5768         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5769
5770         // Don't add the same builtin candidate twice, or if a user defined
5771         // candidate exists.
5772         if (!AddedTypes.insert(CanonType) ||
5773             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5774                                                             CanonType)))
5775           continue;
5776
5777         QualType ParamTypes[2] = { *Enum, *Enum };
5778         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5779                               CandidateSet);
5780       }
5781       
5782       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5783         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5784         if (AddedTypes.insert(NullPtrTy) &&
5785             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 
5786                                                              NullPtrTy))) {
5787           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5788           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 
5789                                 CandidateSet);
5790         }
5791       }
5792     }
5793   }
5794
5795   // C++ [over.built]p13:
5796   //
5797   //   For every cv-qualified or cv-unqualified object type T
5798   //   there exist candidate operator functions of the form
5799   //
5800   //      T*         operator+(T*, ptrdiff_t);
5801   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
5802   //      T*         operator-(T*, ptrdiff_t);
5803   //      T*         operator+(ptrdiff_t, T*);
5804   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
5805   //
5806   // C++ [over.built]p14:
5807   //
5808   //   For every T, where T is a pointer to object type, there
5809   //   exist candidate operator functions of the form
5810   //
5811   //      ptrdiff_t  operator-(T, T);
5812   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5813     /// Set of (canonical) types that we've already handled.
5814     llvm::SmallPtrSet<QualType, 8> AddedTypes;
5815
5816     for (int Arg = 0; Arg < 2; ++Arg) {
5817       QualType AsymetricParamTypes[2] = {
5818         S.Context.getPointerDiffType(),
5819         S.Context.getPointerDiffType(),
5820       };
5821       for (BuiltinCandidateTypeSet::iterator
5822                 Ptr = CandidateTypes[Arg].pointer_begin(),
5823              PtrEnd = CandidateTypes[Arg].pointer_end();
5824            Ptr != PtrEnd; ++Ptr) {
5825         QualType PointeeTy = (*Ptr)->getPointeeType();
5826         if (!PointeeTy->isObjectType())
5827           continue;
5828
5829         AsymetricParamTypes[Arg] = *Ptr;
5830         if (Arg == 0 || Op == OO_Plus) {
5831           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5832           // T* operator+(ptrdiff_t, T*);
5833           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5834                                 CandidateSet);
5835         }
5836         if (Op == OO_Minus) {
5837           // ptrdiff_t operator-(T, T);
5838           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5839             continue;
5840
5841           QualType ParamTypes[2] = { *Ptr, *Ptr };
5842           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5843                                 Args, 2, CandidateSet);
5844         }
5845       }
5846     }
5847   }
5848
5849   // C++ [over.built]p12:
5850   //
5851   //   For every pair of promoted arithmetic types L and R, there
5852   //   exist candidate operator functions of the form
5853   //
5854   //        LR         operator*(L, R);
5855   //        LR         operator/(L, R);
5856   //        LR         operator+(L, R);
5857   //        LR         operator-(L, R);
5858   //        bool       operator<(L, R);
5859   //        bool       operator>(L, R);
5860   //        bool       operator<=(L, R);
5861   //        bool       operator>=(L, R);
5862   //        bool       operator==(L, R);
5863   //        bool       operator!=(L, R);
5864   //
5865   //   where LR is the result of the usual arithmetic conversions
5866   //   between types L and R.
5867   //
5868   // C++ [over.built]p24:
5869   //
5870   //   For every pair of promoted arithmetic types L and R, there exist
5871   //   candidate operator functions of the form
5872   //
5873   //        LR       operator?(bool, L, R);
5874   //
5875   //   where LR is the result of the usual arithmetic conversions
5876   //   between types L and R.
5877   // Our candidates ignore the first parameter.
5878   void addGenericBinaryArithmeticOverloads(bool isComparison) {
5879     if (!HasArithmeticOrEnumeralCandidateType)
5880       return;
5881
5882     for (unsigned Left = FirstPromotedArithmeticType;
5883          Left < LastPromotedArithmeticType; ++Left) {
5884       for (unsigned Right = FirstPromotedArithmeticType;
5885            Right < LastPromotedArithmeticType; ++Right) {
5886         QualType LandR[2] = { getArithmeticType(Left),
5887                               getArithmeticType(Right) };
5888         QualType Result =
5889           isComparison ? S.Context.BoolTy
5890                        : getUsualArithmeticConversions(Left, Right);
5891         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5892       }
5893     }
5894
5895     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5896     // conditional operator for vector types.
5897     for (BuiltinCandidateTypeSet::iterator
5898               Vec1 = CandidateTypes[0].vector_begin(),
5899            Vec1End = CandidateTypes[0].vector_end();
5900          Vec1 != Vec1End; ++Vec1) {
5901       for (BuiltinCandidateTypeSet::iterator
5902                 Vec2 = CandidateTypes[1].vector_begin(),
5903              Vec2End = CandidateTypes[1].vector_end();
5904            Vec2 != Vec2End; ++Vec2) {
5905         QualType LandR[2] = { *Vec1, *Vec2 };
5906         QualType Result = S.Context.BoolTy;
5907         if (!isComparison) {
5908           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5909             Result = *Vec1;
5910           else
5911             Result = *Vec2;
5912         }
5913
5914         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5915       }
5916     }
5917   }
5918
5919   // C++ [over.built]p17:
5920   //
5921   //   For every pair of promoted integral types L and R, there
5922   //   exist candidate operator functions of the form
5923   //
5924   //      LR         operator%(L, R);
5925   //      LR         operator&(L, R);
5926   //      LR         operator^(L, R);
5927   //      LR         operator|(L, R);
5928   //      L          operator<<(L, R);
5929   //      L          operator>>(L, R);
5930   //
5931   //   where LR is the result of the usual arithmetic conversions
5932   //   between types L and R.
5933   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
5934     if (!HasArithmeticOrEnumeralCandidateType)
5935       return;
5936
5937     for (unsigned Left = FirstPromotedIntegralType;
5938          Left < LastPromotedIntegralType; ++Left) {
5939       for (unsigned Right = FirstPromotedIntegralType;
5940            Right < LastPromotedIntegralType; ++Right) {
5941         QualType LandR[2] = { getArithmeticType(Left),
5942                               getArithmeticType(Right) };
5943         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5944             ? LandR[0]
5945             : getUsualArithmeticConversions(Left, Right);
5946         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5947       }
5948     }
5949   }
5950
5951   // C++ [over.built]p20:
5952   //
5953   //   For every pair (T, VQ), where T is an enumeration or
5954   //   pointer to member type and VQ is either volatile or
5955   //   empty, there exist candidate operator functions of the form
5956   //
5957   //        VQ T&      operator=(VQ T&, T);
5958   void addAssignmentMemberPointerOrEnumeralOverloads() {
5959     /// Set of (canonical) types that we've already handled.
5960     llvm::SmallPtrSet<QualType, 8> AddedTypes;
5961
5962     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5963       for (BuiltinCandidateTypeSet::iterator
5964                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5965              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5966            Enum != EnumEnd; ++Enum) {
5967         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5968           continue;
5969
5970         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5971                                                CandidateSet);
5972       }
5973
5974       for (BuiltinCandidateTypeSet::iterator
5975                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5976              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5977            MemPtr != MemPtrEnd; ++MemPtr) {
5978         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5979           continue;
5980
5981         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5982                                                CandidateSet);
5983       }
5984     }
5985   }
5986
5987   // C++ [over.built]p19:
5988   //
5989   //   For every pair (T, VQ), where T is any type and VQ is either
5990   //   volatile or empty, there exist candidate operator functions
5991   //   of the form
5992   //
5993   //        T*VQ&      operator=(T*VQ&, T*);
5994   //
5995   // C++ [over.built]p21:
5996   //
5997   //   For every pair (T, VQ), where T is a cv-qualified or
5998   //   cv-unqualified object type and VQ is either volatile or
5999   //   empty, there exist candidate operator functions of the form
6000   //
6001   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
6002   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
6003   void addAssignmentPointerOverloads(bool isEqualOp) {
6004     /// Set of (canonical) types that we've already handled.
6005     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6006
6007     for (BuiltinCandidateTypeSet::iterator
6008               Ptr = CandidateTypes[0].pointer_begin(),
6009            PtrEnd = CandidateTypes[0].pointer_end();
6010          Ptr != PtrEnd; ++Ptr) {
6011       // If this is operator=, keep track of the builtin candidates we added.
6012       if (isEqualOp)
6013         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
6014       else if (!(*Ptr)->getPointeeType()->isObjectType())
6015         continue;
6016
6017       // non-volatile version
6018       QualType ParamTypes[2] = {
6019         S.Context.getLValueReferenceType(*Ptr),
6020         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6021       };
6022       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6023                             /*IsAssigmentOperator=*/ isEqualOp);
6024
6025       if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6026           VisibleTypeConversionsQuals.hasVolatile()) {
6027         // volatile version
6028         ParamTypes[0] =
6029           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6030         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6031                               /*IsAssigmentOperator=*/isEqualOp);
6032       }
6033     }
6034
6035     if (isEqualOp) {
6036       for (BuiltinCandidateTypeSet::iterator
6037                 Ptr = CandidateTypes[1].pointer_begin(),
6038              PtrEnd = CandidateTypes[1].pointer_end();
6039            Ptr != PtrEnd; ++Ptr) {
6040         // Make sure we don't add the same candidate twice.
6041         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6042           continue;
6043
6044         QualType ParamTypes[2] = {
6045           S.Context.getLValueReferenceType(*Ptr),
6046           *Ptr,
6047         };
6048
6049         // non-volatile version
6050         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6051                               /*IsAssigmentOperator=*/true);
6052
6053         if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6054             VisibleTypeConversionsQuals.hasVolatile()) {
6055           // volatile version
6056           ParamTypes[0] =
6057             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6058           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6059                                 CandidateSet, /*IsAssigmentOperator=*/true);
6060         }
6061       }
6062     }
6063   }
6064
6065   // C++ [over.built]p18:
6066   //
6067   //   For every triple (L, VQ, R), where L is an arithmetic type,
6068   //   VQ is either volatile or empty, and R is a promoted
6069   //   arithmetic type, there exist candidate operator functions of
6070   //   the form
6071   //
6072   //        VQ L&      operator=(VQ L&, R);
6073   //        VQ L&      operator*=(VQ L&, R);
6074   //        VQ L&      operator/=(VQ L&, R);
6075   //        VQ L&      operator+=(VQ L&, R);
6076   //        VQ L&      operator-=(VQ L&, R);
6077   void addAssignmentArithmeticOverloads(bool isEqualOp) {
6078     if (!HasArithmeticOrEnumeralCandidateType)
6079       return;
6080
6081     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6082       for (unsigned Right = FirstPromotedArithmeticType;
6083            Right < LastPromotedArithmeticType; ++Right) {
6084         QualType ParamTypes[2];
6085         ParamTypes[1] = getArithmeticType(Right);
6086
6087         // Add this built-in operator as a candidate (VQ is empty).
6088         ParamTypes[0] =
6089           S.Context.getLValueReferenceType(getArithmeticType(Left));
6090         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6091                               /*IsAssigmentOperator=*/isEqualOp);
6092
6093         // Add this built-in operator as a candidate (VQ is 'volatile').
6094         if (VisibleTypeConversionsQuals.hasVolatile()) {
6095           ParamTypes[0] =
6096             S.Context.getVolatileType(getArithmeticType(Left));
6097           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6098           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6099                                 CandidateSet,
6100                                 /*IsAssigmentOperator=*/isEqualOp);
6101         }
6102       }
6103     }
6104
6105     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6106     for (BuiltinCandidateTypeSet::iterator
6107               Vec1 = CandidateTypes[0].vector_begin(),
6108            Vec1End = CandidateTypes[0].vector_end();
6109          Vec1 != Vec1End; ++Vec1) {
6110       for (BuiltinCandidateTypeSet::iterator
6111                 Vec2 = CandidateTypes[1].vector_begin(),
6112              Vec2End = CandidateTypes[1].vector_end();
6113            Vec2 != Vec2End; ++Vec2) {
6114         QualType ParamTypes[2];
6115         ParamTypes[1] = *Vec2;
6116         // Add this built-in operator as a candidate (VQ is empty).
6117         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6118         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6119                               /*IsAssigmentOperator=*/isEqualOp);
6120
6121         // Add this built-in operator as a candidate (VQ is 'volatile').
6122         if (VisibleTypeConversionsQuals.hasVolatile()) {
6123           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6124           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6125           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6126                                 CandidateSet,
6127                                 /*IsAssigmentOperator=*/isEqualOp);
6128         }
6129       }
6130     }
6131   }
6132
6133   // C++ [over.built]p22:
6134   //
6135   //   For every triple (L, VQ, R), where L is an integral type, VQ
6136   //   is either volatile or empty, and R is a promoted integral
6137   //   type, there exist candidate operator functions of the form
6138   //
6139   //        VQ L&       operator%=(VQ L&, R);
6140   //        VQ L&       operator<<=(VQ L&, R);
6141   //        VQ L&       operator>>=(VQ L&, R);
6142   //        VQ L&       operator&=(VQ L&, R);
6143   //        VQ L&       operator^=(VQ L&, R);
6144   //        VQ L&       operator|=(VQ L&, R);
6145   void addAssignmentIntegralOverloads() {
6146     if (!HasArithmeticOrEnumeralCandidateType)
6147       return;
6148
6149     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6150       for (unsigned Right = FirstPromotedIntegralType;
6151            Right < LastPromotedIntegralType; ++Right) {
6152         QualType ParamTypes[2];
6153         ParamTypes[1] = getArithmeticType(Right);
6154
6155         // Add this built-in operator as a candidate (VQ is empty).
6156         ParamTypes[0] =
6157           S.Context.getLValueReferenceType(getArithmeticType(Left));
6158         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6159         if (VisibleTypeConversionsQuals.hasVolatile()) {
6160           // Add this built-in operator as a candidate (VQ is 'volatile').
6161           ParamTypes[0] = getArithmeticType(Left);
6162           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6163           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6164           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6165                                 CandidateSet);
6166         }
6167       }
6168     }
6169   }
6170
6171   // C++ [over.operator]p23:
6172   //
6173   //   There also exist candidate operator functions of the form
6174   //
6175   //        bool        operator!(bool);
6176   //        bool        operator&&(bool, bool);
6177   //        bool        operator||(bool, bool);
6178   void addExclaimOverload() {
6179     QualType ParamTy = S.Context.BoolTy;
6180     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6181                           /*IsAssignmentOperator=*/false,
6182                           /*NumContextualBoolArguments=*/1);
6183   }
6184   void addAmpAmpOrPipePipeOverload() {
6185     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6186     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6187                           /*IsAssignmentOperator=*/false,
6188                           /*NumContextualBoolArguments=*/2);
6189   }
6190
6191   // C++ [over.built]p13:
6192   //
6193   //   For every cv-qualified or cv-unqualified object type T there
6194   //   exist candidate operator functions of the form
6195   //
6196   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
6197   //        T&         operator[](T*, ptrdiff_t);
6198   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
6199   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
6200   //        T&         operator[](ptrdiff_t, T*);
6201   void addSubscriptOverloads() {
6202     for (BuiltinCandidateTypeSet::iterator
6203               Ptr = CandidateTypes[0].pointer_begin(),
6204            PtrEnd = CandidateTypes[0].pointer_end();
6205          Ptr != PtrEnd; ++Ptr) {
6206       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6207       QualType PointeeType = (*Ptr)->getPointeeType();
6208       if (!PointeeType->isObjectType())
6209         continue;
6210
6211       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6212
6213       // T& operator[](T*, ptrdiff_t)
6214       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6215     }
6216
6217     for (BuiltinCandidateTypeSet::iterator
6218               Ptr = CandidateTypes[1].pointer_begin(),
6219            PtrEnd = CandidateTypes[1].pointer_end();
6220          Ptr != PtrEnd; ++Ptr) {
6221       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6222       QualType PointeeType = (*Ptr)->getPointeeType();
6223       if (!PointeeType->isObjectType())
6224         continue;
6225
6226       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6227
6228       // T& operator[](ptrdiff_t, T*)
6229       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6230     }
6231   }
6232
6233   // C++ [over.built]p11:
6234   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6235   //    C1 is the same type as C2 or is a derived class of C2, T is an object
6236   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6237   //    there exist candidate operator functions of the form
6238   //
6239   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6240   //
6241   //    where CV12 is the union of CV1 and CV2.
6242   void addArrowStarOverloads() {
6243     for (BuiltinCandidateTypeSet::iterator
6244              Ptr = CandidateTypes[0].pointer_begin(),
6245            PtrEnd = CandidateTypes[0].pointer_end();
6246          Ptr != PtrEnd; ++Ptr) {
6247       QualType C1Ty = (*Ptr);
6248       QualType C1;
6249       QualifierCollector Q1;
6250       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6251       if (!isa<RecordType>(C1))
6252         continue;
6253       // heuristic to reduce number of builtin candidates in the set.
6254       // Add volatile/restrict version only if there are conversions to a
6255       // volatile/restrict type.
6256       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6257         continue;
6258       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6259         continue;
6260       for (BuiltinCandidateTypeSet::iterator
6261                 MemPtr = CandidateTypes[1].member_pointer_begin(),
6262              MemPtrEnd = CandidateTypes[1].member_pointer_end();
6263            MemPtr != MemPtrEnd; ++MemPtr) {
6264         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6265         QualType C2 = QualType(mptr->getClass(), 0);
6266         C2 = C2.getUnqualifiedType();
6267         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6268           break;
6269         QualType ParamTypes[2] = { *Ptr, *MemPtr };
6270         // build CV12 T&
6271         QualType T = mptr->getPointeeType();
6272         if (!VisibleTypeConversionsQuals.hasVolatile() &&
6273             T.isVolatileQualified())
6274           continue;
6275         if (!VisibleTypeConversionsQuals.hasRestrict() &&
6276             T.isRestrictQualified())
6277           continue;
6278         T = Q1.apply(S.Context, T);
6279         QualType ResultTy = S.Context.getLValueReferenceType(T);
6280         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6281       }
6282     }
6283   }
6284
6285   // Note that we don't consider the first argument, since it has been
6286   // contextually converted to bool long ago. The candidates below are
6287   // therefore added as binary.
6288   //
6289   // C++ [over.built]p25:
6290   //   For every type T, where T is a pointer, pointer-to-member, or scoped
6291   //   enumeration type, there exist candidate operator functions of the form
6292   //
6293   //        T        operator?(bool, T, T);
6294   //
6295   void addConditionalOperatorOverloads() {
6296     /// Set of (canonical) types that we've already handled.
6297     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6298
6299     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6300       for (BuiltinCandidateTypeSet::iterator
6301                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6302              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6303            Ptr != PtrEnd; ++Ptr) {
6304         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6305           continue;
6306
6307         QualType ParamTypes[2] = { *Ptr, *Ptr };
6308         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6309       }
6310
6311       for (BuiltinCandidateTypeSet::iterator
6312                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6313              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6314            MemPtr != MemPtrEnd; ++MemPtr) {
6315         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6316           continue;
6317
6318         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6319         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6320       }
6321
6322       if (S.getLangOptions().CPlusPlus0x) {
6323         for (BuiltinCandidateTypeSet::iterator
6324                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6325                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6326              Enum != EnumEnd; ++Enum) {
6327           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6328             continue;
6329
6330           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6331             continue;
6332
6333           QualType ParamTypes[2] = { *Enum, *Enum };
6334           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6335         }
6336       }
6337     }
6338   }
6339 };
6340
6341 } // end anonymous namespace
6342
6343 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
6344 /// operator overloads to the candidate set (C++ [over.built]), based
6345 /// on the operator @p Op and the arguments given. For example, if the
6346 /// operator is a binary '+', this routine might add "int
6347 /// operator+(int, int)" to cover integer addition.
6348 void
6349 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6350                                    SourceLocation OpLoc,
6351                                    Expr **Args, unsigned NumArgs,
6352                                    OverloadCandidateSet& CandidateSet) {
6353   // Find all of the types that the arguments can convert to, but only
6354   // if the operator we're looking at has built-in operator candidates
6355   // that make use of these types. Also record whether we encounter non-record
6356   // candidate types or either arithmetic or enumeral candidate types.
6357   Qualifiers VisibleTypeConversionsQuals;
6358   VisibleTypeConversionsQuals.addConst();
6359   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6360     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
6361
6362   bool HasNonRecordCandidateType = false;
6363   bool HasArithmeticOrEnumeralCandidateType = false;
6364   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
6365   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6366     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6367     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6368                                                  OpLoc,
6369                                                  true,
6370                                                  (Op == OO_Exclaim ||
6371                                                   Op == OO_AmpAmp ||
6372                                                   Op == OO_PipePipe),
6373                                                  VisibleTypeConversionsQuals);
6374     HasNonRecordCandidateType = HasNonRecordCandidateType ||
6375         CandidateTypes[ArgIdx].hasNonRecordTypes();
6376     HasArithmeticOrEnumeralCandidateType =
6377         HasArithmeticOrEnumeralCandidateType ||
6378         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
6379   }
6380
6381   // Exit early when no non-record types have been added to the candidate set
6382   // for any of the arguments to the operator.
6383   //
6384   // We can't exit early for !, ||, or &&, since there we have always have
6385   // 'bool' overloads.
6386   if (!HasNonRecordCandidateType && 
6387       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
6388     return;
6389
6390   // Setup an object to manage the common state for building overloads.
6391   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6392                                            VisibleTypeConversionsQuals,
6393                                            HasArithmeticOrEnumeralCandidateType,
6394                                            CandidateTypes, CandidateSet);
6395
6396   // Dispatch over the operation to add in only those overloads which apply.
6397   switch (Op) {
6398   case OO_None:
6399   case NUM_OVERLOADED_OPERATORS:
6400     llvm_unreachable("Expected an overloaded operator");
6401
6402   case OO_New:
6403   case OO_Delete:
6404   case OO_Array_New:
6405   case OO_Array_Delete:
6406   case OO_Call:
6407     llvm_unreachable(
6408                     "Special operators don't use AddBuiltinOperatorCandidates");
6409
6410   case OO_Comma:
6411   case OO_Arrow:
6412     // C++ [over.match.oper]p3:
6413     //   -- For the operator ',', the unary operator '&', or the
6414     //      operator '->', the built-in candidates set is empty.
6415     break;
6416
6417   case OO_Plus: // '+' is either unary or binary
6418     if (NumArgs == 1)
6419       OpBuilder.addUnaryPlusPointerOverloads();
6420     // Fall through.
6421
6422   case OO_Minus: // '-' is either unary or binary
6423     if (NumArgs == 1) {
6424       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
6425     } else {
6426       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6427       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6428     }
6429     break;
6430
6431   case OO_Star: // '*' is either unary or binary
6432     if (NumArgs == 1)
6433       OpBuilder.addUnaryStarPointerOverloads();
6434     else
6435       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6436     break;
6437
6438   case OO_Slash:
6439     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6440     break;
6441
6442   case OO_PlusPlus:
6443   case OO_MinusMinus:
6444     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6445     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
6446     break;
6447
6448   case OO_EqualEqual:
6449   case OO_ExclaimEqual:
6450     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
6451     // Fall through.
6452
6453   case OO_Less:
6454   case OO_Greater:
6455   case OO_LessEqual:
6456   case OO_GreaterEqual:
6457     OpBuilder.addRelationalPointerOrEnumeralOverloads();
6458     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6459     break;
6460
6461   case OO_Percent:
6462   case OO_Caret:
6463   case OO_Pipe:
6464   case OO_LessLess:
6465   case OO_GreaterGreater:
6466     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6467     break;
6468
6469   case OO_Amp: // '&' is either unary or binary
6470     if (NumArgs == 1)
6471       // C++ [over.match.oper]p3:
6472       //   -- For the operator ',', the unary operator '&', or the
6473       //      operator '->', the built-in candidates set is empty.
6474       break;
6475
6476     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6477     break;
6478
6479   case OO_Tilde:
6480     OpBuilder.addUnaryTildePromotedIntegralOverloads();
6481     break;
6482
6483   case OO_Equal:
6484     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
6485     // Fall through.
6486
6487   case OO_PlusEqual:
6488   case OO_MinusEqual:
6489     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
6490     // Fall through.
6491
6492   case OO_StarEqual:
6493   case OO_SlashEqual:
6494     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
6495     break;
6496
6497   case OO_PercentEqual:
6498   case OO_LessLessEqual:
6499   case OO_GreaterGreaterEqual:
6500   case OO_AmpEqual:
6501   case OO_CaretEqual:
6502   case OO_PipeEqual:
6503     OpBuilder.addAssignmentIntegralOverloads();
6504     break;
6505
6506   case OO_Exclaim:
6507     OpBuilder.addExclaimOverload();
6508     break;
6509
6510   case OO_AmpAmp:
6511   case OO_PipePipe:
6512     OpBuilder.addAmpAmpOrPipePipeOverload();
6513     break;
6514
6515   case OO_Subscript:
6516     OpBuilder.addSubscriptOverloads();
6517     break;
6518
6519   case OO_ArrowStar:
6520     OpBuilder.addArrowStarOverloads();
6521     break;
6522
6523   case OO_Conditional:
6524     OpBuilder.addConditionalOperatorOverloads();
6525     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6526     break;
6527   }
6528 }
6529
6530 /// \brief Add function candidates found via argument-dependent lookup
6531 /// to the set of overloading candidates.
6532 ///
6533 /// This routine performs argument-dependent name lookup based on the
6534 /// given function name (which may also be an operator name) and adds
6535 /// all of the overload candidates found by ADL to the overload
6536 /// candidate set (C++ [basic.lookup.argdep]).
6537 void
6538 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
6539                                            bool Operator,
6540                                            Expr **Args, unsigned NumArgs,
6541                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6542                                            OverloadCandidateSet& CandidateSet,
6543                                            bool PartialOverloading,
6544                                            bool StdNamespaceIsAssociated) {
6545   ADLResult Fns;
6546
6547   // FIXME: This approach for uniquing ADL results (and removing
6548   // redundant candidates from the set) relies on pointer-equality,
6549   // which means we need to key off the canonical decl.  However,
6550   // always going back to the canonical decl might not get us the
6551   // right set of default arguments.  What default arguments are
6552   // we supposed to consider on ADL candidates, anyway?
6553
6554   // FIXME: Pass in the explicit template arguments?
6555   ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6556                           StdNamespaceIsAssociated);
6557
6558   // Erase all of the candidates we already knew about.
6559   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6560                                    CandEnd = CandidateSet.end();
6561        Cand != CandEnd; ++Cand)
6562     if (Cand->Function) {
6563       Fns.erase(Cand->Function);
6564       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
6565         Fns.erase(FunTmpl);
6566     }
6567
6568   // For each of the ADL candidates we found, add it to the overload
6569   // set.
6570   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
6571     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
6572     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
6573       if (ExplicitTemplateArgs)
6574         continue;
6575
6576       AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
6577                            false, PartialOverloading);
6578     } else
6579       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
6580                                    FoundDecl, ExplicitTemplateArgs,
6581                                    Args, NumArgs, CandidateSet);
6582   }
6583 }
6584
6585 /// isBetterOverloadCandidate - Determines whether the first overload
6586 /// candidate is a better candidate than the second (C++ 13.3.3p1).
6587 bool
6588 isBetterOverloadCandidate(Sema &S,
6589                           const OverloadCandidate &Cand1,
6590                           const OverloadCandidate &Cand2,
6591                           SourceLocation Loc,
6592                           bool UserDefinedConversion) {
6593   // Define viable functions to be better candidates than non-viable
6594   // functions.
6595   if (!Cand2.Viable)
6596     return Cand1.Viable;
6597   else if (!Cand1.Viable)
6598     return false;
6599
6600   // C++ [over.match.best]p1:
6601   //
6602   //   -- if F is a static member function, ICS1(F) is defined such
6603   //      that ICS1(F) is neither better nor worse than ICS1(G) for
6604   //      any function G, and, symmetrically, ICS1(G) is neither
6605   //      better nor worse than ICS1(F).
6606   unsigned StartArg = 0;
6607   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6608     StartArg = 1;
6609
6610   // C++ [over.match.best]p1:
6611   //   A viable function F1 is defined to be a better function than another
6612   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
6613   //   conversion sequence than ICSi(F2), and then...
6614   unsigned NumArgs = Cand1.Conversions.size();
6615   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6616   bool HasBetterConversion = false;
6617   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
6618     switch (CompareImplicitConversionSequences(S,
6619                                                Cand1.Conversions[ArgIdx],
6620                                                Cand2.Conversions[ArgIdx])) {
6621     case ImplicitConversionSequence::Better:
6622       // Cand1 has a better conversion sequence.
6623       HasBetterConversion = true;
6624       break;
6625
6626     case ImplicitConversionSequence::Worse:
6627       // Cand1 can't be better than Cand2.
6628       return false;
6629
6630     case ImplicitConversionSequence::Indistinguishable:
6631       // Do nothing.
6632       break;
6633     }
6634   }
6635
6636   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
6637   //       ICSj(F2), or, if not that,
6638   if (HasBetterConversion)
6639     return true;
6640
6641   //     - F1 is a non-template function and F2 is a function template
6642   //       specialization, or, if not that,
6643   if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
6644       Cand2.Function && Cand2.Function->getPrimaryTemplate())
6645     return true;
6646
6647   //   -- F1 and F2 are function template specializations, and the function
6648   //      template for F1 is more specialized than the template for F2
6649   //      according to the partial ordering rules described in 14.5.5.2, or,
6650   //      if not that,
6651   if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
6652       Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
6653     if (FunctionTemplateDecl *BetterTemplate
6654           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6655                                          Cand2.Function->getPrimaryTemplate(),
6656                                          Loc,
6657                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
6658                                                              : TPOC_Call,
6659                                          Cand1.ExplicitCallArguments))
6660       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
6661   }
6662
6663   //   -- the context is an initialization by user-defined conversion
6664   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
6665   //      from the return type of F1 to the destination type (i.e.,
6666   //      the type of the entity being initialized) is a better
6667   //      conversion sequence than the standard conversion sequence
6668   //      from the return type of F2 to the destination type.
6669   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
6670       isa<CXXConversionDecl>(Cand1.Function) &&
6671       isa<CXXConversionDecl>(Cand2.Function)) {
6672     switch (CompareStandardConversionSequences(S,
6673                                                Cand1.FinalConversion,
6674                                                Cand2.FinalConversion)) {
6675     case ImplicitConversionSequence::Better:
6676       // Cand1 has a better conversion sequence.
6677       return true;
6678
6679     case ImplicitConversionSequence::Worse:
6680       // Cand1 can't be better than Cand2.
6681       return false;
6682
6683     case ImplicitConversionSequence::Indistinguishable:
6684       // Do nothing
6685       break;
6686     }
6687   }
6688
6689   return false;
6690 }
6691
6692 /// \brief Computes the best viable function (C++ 13.3.3)
6693 /// within an overload candidate set.
6694 ///
6695 /// \param CandidateSet the set of candidate functions.
6696 ///
6697 /// \param Loc the location of the function name (or operator symbol) for
6698 /// which overload resolution occurs.
6699 ///
6700 /// \param Best f overload resolution was successful or found a deleted
6701 /// function, Best points to the candidate function found.
6702 ///
6703 /// \returns The result of overload resolution.
6704 OverloadingResult
6705 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
6706                                          iterator &Best,
6707                                          bool UserDefinedConversion) {
6708   // Find the best viable function.
6709   Best = end();
6710   for (iterator Cand = begin(); Cand != end(); ++Cand) {
6711     if (Cand->Viable)
6712       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
6713                                                      UserDefinedConversion))
6714         Best = Cand;
6715   }
6716
6717   // If we didn't find any viable functions, abort.
6718   if (Best == end())
6719     return OR_No_Viable_Function;
6720
6721   // Make sure that this function is better than every other viable
6722   // function. If not, we have an ambiguity.
6723   for (iterator Cand = begin(); Cand != end(); ++Cand) {
6724     if (Cand->Viable &&
6725         Cand != Best &&
6726         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
6727                                    UserDefinedConversion)) {
6728       Best = end();
6729       return OR_Ambiguous;
6730     }
6731   }
6732
6733   // Best is the best viable function.
6734   if (Best->Function &&
6735       (Best->Function->isDeleted() ||
6736        S.isFunctionConsideredUnavailable(Best->Function)))
6737     return OR_Deleted;
6738
6739   return OR_Success;
6740 }
6741
6742 namespace {
6743
6744 enum OverloadCandidateKind {
6745   oc_function,
6746   oc_method,
6747   oc_constructor,
6748   oc_function_template,
6749   oc_method_template,
6750   oc_constructor_template,
6751   oc_implicit_default_constructor,
6752   oc_implicit_copy_constructor,
6753   oc_implicit_move_constructor,
6754   oc_implicit_copy_assignment,
6755   oc_implicit_move_assignment,
6756   oc_implicit_inherited_constructor
6757 };
6758
6759 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6760                                                 FunctionDecl *Fn,
6761                                                 std::string &Description) {
6762   bool isTemplate = false;
6763
6764   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6765     isTemplate = true;
6766     Description = S.getTemplateArgumentBindingsText(
6767       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6768   }
6769
6770   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
6771     if (!Ctor->isImplicit())
6772       return isTemplate ? oc_constructor_template : oc_constructor;
6773
6774     if (Ctor->getInheritedConstructor())
6775       return oc_implicit_inherited_constructor;
6776
6777     if (Ctor->isDefaultConstructor())
6778       return oc_implicit_default_constructor;
6779
6780     if (Ctor->isMoveConstructor())
6781       return oc_implicit_move_constructor;
6782
6783     assert(Ctor->isCopyConstructor() &&
6784            "unexpected sort of implicit constructor");
6785     return oc_implicit_copy_constructor;
6786   }
6787
6788   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6789     // This actually gets spelled 'candidate function' for now, but
6790     // it doesn't hurt to split it out.
6791     if (!Meth->isImplicit())
6792       return isTemplate ? oc_method_template : oc_method;
6793
6794     if (Meth->isMoveAssignmentOperator())
6795       return oc_implicit_move_assignment;
6796
6797     assert(Meth->isCopyAssignmentOperator()
6798            && "implicit method is not copy assignment operator?");
6799     return oc_implicit_copy_assignment;
6800   }
6801
6802   return isTemplate ? oc_function_template : oc_function;
6803 }
6804
6805 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6806   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6807   if (!Ctor) return;
6808
6809   Ctor = Ctor->getInheritedConstructor();
6810   if (!Ctor) return;
6811
6812   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6813 }
6814
6815 } // end anonymous namespace
6816
6817 // Notes the location of an overload candidate.
6818 void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
6819   std::string FnDesc;
6820   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6821   Diag(Fn->getLocation(), diag::note_ovl_candidate)
6822     << (unsigned) K << FnDesc;
6823   MaybeEmitInheritedConstructorNote(*this, Fn);
6824 }
6825
6826 //Notes the location of all overload candidates designated through 
6827 // OverloadedExpr
6828 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6829   assert(OverloadedExpr->getType() == Context.OverloadTy);
6830
6831   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6832   OverloadExpr *OvlExpr = Ovl.Expression;
6833
6834   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6835                             IEnd = OvlExpr->decls_end(); 
6836        I != IEnd; ++I) {
6837     if (FunctionTemplateDecl *FunTmpl = 
6838                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6839       NoteOverloadCandidate(FunTmpl->getTemplatedDecl());   
6840     } else if (FunctionDecl *Fun 
6841                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6842       NoteOverloadCandidate(Fun);
6843     }
6844   }
6845 }
6846
6847 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
6848 /// "lead" diagnostic; it will be given two arguments, the source and
6849 /// target types of the conversion.
6850 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6851                                  Sema &S,
6852                                  SourceLocation CaretLoc,
6853                                  const PartialDiagnostic &PDiag) const {
6854   S.Diag(CaretLoc, PDiag)
6855     << Ambiguous.getFromType() << Ambiguous.getToType();
6856   for (AmbiguousConversionSequence::const_iterator
6857          I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6858     S.NoteOverloadCandidate(*I);
6859   }
6860 }
6861
6862 namespace {
6863
6864 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6865   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6866   assert(Conv.isBad());
6867   assert(Cand->Function && "for now, candidate must be a function");
6868   FunctionDecl *Fn = Cand->Function;
6869
6870   // There's a conversion slot for the object argument if this is a
6871   // non-constructor method.  Note that 'I' corresponds the
6872   // conversion-slot index.
6873   bool isObjectArgument = false;
6874   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
6875     if (I == 0)
6876       isObjectArgument = true;
6877     else
6878       I--;
6879   }
6880
6881   std::string FnDesc;
6882   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6883
6884   Expr *FromExpr = Conv.Bad.FromExpr;
6885   QualType FromTy = Conv.Bad.getFromType();
6886   QualType ToTy = Conv.Bad.getToType();
6887
6888   if (FromTy == S.Context.OverloadTy) {
6889     assert(FromExpr && "overload set argument came from implicit argument?");
6890     Expr *E = FromExpr->IgnoreParens();
6891     if (isa<UnaryOperator>(E))
6892       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
6893     DeclarationName Name = cast<OverloadExpr>(E)->getName();
6894
6895     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6896       << (unsigned) FnKind << FnDesc
6897       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6898       << ToTy << Name << I+1;
6899     MaybeEmitInheritedConstructorNote(S, Fn);
6900     return;
6901   }
6902
6903   // Do some hand-waving analysis to see if the non-viability is due
6904   // to a qualifier mismatch.
6905   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6906   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6907   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6908     CToTy = RT->getPointeeType();
6909   else {
6910     // TODO: detect and diagnose the full richness of const mismatches.
6911     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6912       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6913         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6914   }
6915
6916   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6917       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6918     // It is dumb that we have to do this here.
6919     while (isa<ArrayType>(CFromTy))
6920       CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6921     while (isa<ArrayType>(CToTy))
6922       CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6923
6924     Qualifiers FromQs = CFromTy.getQualifiers();
6925     Qualifiers ToQs = CToTy.getQualifiers();
6926
6927     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6928       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6929         << (unsigned) FnKind << FnDesc
6930         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6931         << FromTy
6932         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6933         << (unsigned) isObjectArgument << I+1;
6934       MaybeEmitInheritedConstructorNote(S, Fn);
6935       return;
6936     }
6937
6938     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
6939       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
6940         << (unsigned) FnKind << FnDesc
6941         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6942         << FromTy
6943         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6944         << (unsigned) isObjectArgument << I+1;
6945       MaybeEmitInheritedConstructorNote(S, Fn);
6946       return;
6947     }
6948
6949     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6950       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6951       << (unsigned) FnKind << FnDesc
6952       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6953       << FromTy
6954       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6955       << (unsigned) isObjectArgument << I+1;
6956       MaybeEmitInheritedConstructorNote(S, Fn);
6957       return;
6958     }
6959
6960     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6961     assert(CVR && "unexpected qualifiers mismatch");
6962
6963     if (isObjectArgument) {
6964       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6965         << (unsigned) FnKind << FnDesc
6966         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6967         << FromTy << (CVR - 1);
6968     } else {
6969       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6970         << (unsigned) FnKind << FnDesc
6971         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6972         << FromTy << (CVR - 1) << I+1;
6973     }
6974     MaybeEmitInheritedConstructorNote(S, Fn);
6975     return;
6976   }
6977
6978   // Special diagnostic for failure to convert an initializer list, since
6979   // telling the user that it has type void is not useful.
6980   if (FromExpr && isa<InitListExpr>(FromExpr)) {
6981     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
6982       << (unsigned) FnKind << FnDesc
6983       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6984       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6985     MaybeEmitInheritedConstructorNote(S, Fn);
6986     return;
6987   }
6988
6989   // Diagnose references or pointers to incomplete types differently,
6990   // since it's far from impossible that the incompleteness triggered
6991   // the failure.
6992   QualType TempFromTy = FromTy.getNonReferenceType();
6993   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6994     TempFromTy = PTy->getPointeeType();
6995   if (TempFromTy->isIncompleteType()) {
6996     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6997       << (unsigned) FnKind << FnDesc
6998       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6999       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7000     MaybeEmitInheritedConstructorNote(S, Fn);
7001     return;
7002   }
7003
7004   // Diagnose base -> derived pointer conversions.
7005   unsigned BaseToDerivedConversion = 0;
7006   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7007     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7008       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7009                                                FromPtrTy->getPointeeType()) &&
7010           !FromPtrTy->getPointeeType()->isIncompleteType() &&
7011           !ToPtrTy->getPointeeType()->isIncompleteType() &&
7012           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
7013                           FromPtrTy->getPointeeType()))
7014         BaseToDerivedConversion = 1;
7015     }
7016   } else if (const ObjCObjectPointerType *FromPtrTy
7017                                     = FromTy->getAs<ObjCObjectPointerType>()) {
7018     if (const ObjCObjectPointerType *ToPtrTy
7019                                         = ToTy->getAs<ObjCObjectPointerType>())
7020       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7021         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7022           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7023                                                 FromPtrTy->getPointeeType()) &&
7024               FromIface->isSuperClassOf(ToIface))
7025             BaseToDerivedConversion = 2;
7026   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7027       if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7028           !FromTy->isIncompleteType() &&
7029           !ToRefTy->getPointeeType()->isIncompleteType() &&
7030           S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7031         BaseToDerivedConversion = 3;
7032     }
7033
7034   if (BaseToDerivedConversion) {
7035     S.Diag(Fn->getLocation(),
7036            diag::note_ovl_candidate_bad_base_to_derived_conv)
7037       << (unsigned) FnKind << FnDesc
7038       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7039       << (BaseToDerivedConversion - 1)
7040       << FromTy << ToTy << I+1;
7041     MaybeEmitInheritedConstructorNote(S, Fn);
7042     return;
7043   }
7044
7045   if (isa<ObjCObjectPointerType>(CFromTy) &&
7046       isa<PointerType>(CToTy)) {
7047       Qualifiers FromQs = CFromTy.getQualifiers();
7048       Qualifiers ToQs = CToTy.getQualifiers();
7049       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7050         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7051         << (unsigned) FnKind << FnDesc
7052         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7053         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7054         MaybeEmitInheritedConstructorNote(S, Fn);
7055         return;
7056       }
7057   }
7058   
7059   // Emit the generic diagnostic and, optionally, add the hints to it.
7060   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7061   FDiag << (unsigned) FnKind << FnDesc
7062     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7063     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7064     << (unsigned) (Cand->Fix.Kind);
7065
7066   // If we can fix the conversion, suggest the FixIts.
7067   for (SmallVector<FixItHint, 1>::iterator
7068       HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7069       HI != HE; ++HI)
7070     FDiag << *HI;
7071   S.Diag(Fn->getLocation(), FDiag);
7072
7073   MaybeEmitInheritedConstructorNote(S, Fn);
7074 }
7075
7076 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7077                            unsigned NumFormalArgs) {
7078   // TODO: treat calls to a missing default constructor as a special case
7079
7080   FunctionDecl *Fn = Cand->Function;
7081   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7082
7083   unsigned MinParams = Fn->getMinRequiredArguments();
7084
7085   // With invalid overloaded operators, it's possible that we think we
7086   // have an arity mismatch when it fact it looks like we have the
7087   // right number of arguments, because only overloaded operators have
7088   // the weird behavior of overloading member and non-member functions.
7089   // Just don't report anything.
7090   if (Fn->isInvalidDecl() && 
7091       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7092     return;
7093
7094   // at least / at most / exactly
7095   unsigned mode, modeCount;
7096   if (NumFormalArgs < MinParams) {
7097     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7098            (Cand->FailureKind == ovl_fail_bad_deduction &&
7099             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
7100     if (MinParams != FnTy->getNumArgs() ||
7101         FnTy->isVariadic() || FnTy->isTemplateVariadic())
7102       mode = 0; // "at least"
7103     else
7104       mode = 2; // "exactly"
7105     modeCount = MinParams;
7106   } else {
7107     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7108            (Cand->FailureKind == ovl_fail_bad_deduction &&
7109             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
7110     if (MinParams != FnTy->getNumArgs())
7111       mode = 1; // "at most"
7112     else
7113       mode = 2; // "exactly"
7114     modeCount = FnTy->getNumArgs();
7115   }
7116
7117   std::string Description;
7118   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7119
7120   S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
7121     << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
7122     << modeCount << NumFormalArgs;
7123   MaybeEmitInheritedConstructorNote(S, Fn);
7124 }
7125
7126 /// Diagnose a failed template-argument deduction.
7127 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7128                           Expr **Args, unsigned NumArgs) {
7129   FunctionDecl *Fn = Cand->Function; // pattern
7130
7131   TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
7132   NamedDecl *ParamD;
7133   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7134   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7135   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
7136   switch (Cand->DeductionFailure.Result) {
7137   case Sema::TDK_Success:
7138     llvm_unreachable("TDK_success while diagnosing bad deduction");
7139
7140   case Sema::TDK_Incomplete: {
7141     assert(ParamD && "no parameter found for incomplete deduction result");
7142     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7143       << ParamD->getDeclName();
7144     MaybeEmitInheritedConstructorNote(S, Fn);
7145     return;
7146   }
7147
7148   case Sema::TDK_Underqualified: {
7149     assert(ParamD && "no parameter found for bad qualifiers deduction result");
7150     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7151
7152     QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7153
7154     // Param will have been canonicalized, but it should just be a
7155     // qualified version of ParamD, so move the qualifiers to that.
7156     QualifierCollector Qs;
7157     Qs.strip(Param);
7158     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
7159     assert(S.Context.hasSameType(Param, NonCanonParam));
7160
7161     // Arg has also been canonicalized, but there's nothing we can do
7162     // about that.  It also doesn't matter as much, because it won't
7163     // have any template parameters in it (because deduction isn't
7164     // done on dependent types).
7165     QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7166
7167     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7168       << ParamD->getDeclName() << Arg << NonCanonParam;
7169     MaybeEmitInheritedConstructorNote(S, Fn);
7170     return;
7171   }
7172
7173   case Sema::TDK_Inconsistent: {
7174     assert(ParamD && "no parameter found for inconsistent deduction result");
7175     int which = 0;
7176     if (isa<TemplateTypeParmDecl>(ParamD))
7177       which = 0;
7178     else if (isa<NonTypeTemplateParmDecl>(ParamD))
7179       which = 1;
7180     else {
7181       which = 2;
7182     }
7183
7184     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
7185       << which << ParamD->getDeclName()
7186       << *Cand->DeductionFailure.getFirstArg()
7187       << *Cand->DeductionFailure.getSecondArg();
7188     MaybeEmitInheritedConstructorNote(S, Fn);
7189     return;
7190   }
7191
7192   case Sema::TDK_InvalidExplicitArguments:
7193     assert(ParamD && "no parameter found for invalid explicit arguments");
7194     if (ParamD->getDeclName())
7195       S.Diag(Fn->getLocation(),
7196              diag::note_ovl_candidate_explicit_arg_mismatch_named)
7197         << ParamD->getDeclName();
7198     else {
7199       int index = 0;
7200       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7201         index = TTP->getIndex();
7202       else if (NonTypeTemplateParmDecl *NTTP
7203                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7204         index = NTTP->getIndex();
7205       else
7206         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
7207       S.Diag(Fn->getLocation(),
7208              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7209         << (index + 1);
7210     }
7211     MaybeEmitInheritedConstructorNote(S, Fn);
7212     return;
7213
7214   case Sema::TDK_TooManyArguments:
7215   case Sema::TDK_TooFewArguments:
7216     DiagnoseArityMismatch(S, Cand, NumArgs);
7217     return;
7218
7219   case Sema::TDK_InstantiationDepth:
7220     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
7221     MaybeEmitInheritedConstructorNote(S, Fn);
7222     return;
7223
7224   case Sema::TDK_SubstitutionFailure: {
7225     std::string ArgString;
7226     if (TemplateArgumentList *Args
7227                             = Cand->DeductionFailure.getTemplateArgumentList())
7228       ArgString = S.getTemplateArgumentBindingsText(
7229                     Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7230                                                     *Args);
7231     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7232       << ArgString;
7233     MaybeEmitInheritedConstructorNote(S, Fn);
7234     return;
7235   }
7236
7237   // TODO: diagnose these individually, then kill off
7238   // note_ovl_candidate_bad_deduction, which is uselessly vague.
7239   case Sema::TDK_NonDeducedMismatch:
7240   case Sema::TDK_FailedOverloadResolution:
7241     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
7242     MaybeEmitInheritedConstructorNote(S, Fn);
7243     return;
7244   }
7245 }
7246
7247 /// CUDA: diagnose an invalid call across targets.
7248 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7249   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7250   FunctionDecl *Callee = Cand->Function;
7251
7252   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7253                            CalleeTarget = S.IdentifyCUDATarget(Callee);
7254
7255   std::string FnDesc;
7256   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7257
7258   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7259       << (unsigned) FnKind << CalleeTarget << CallerTarget;
7260 }
7261
7262 /// Generates a 'note' diagnostic for an overload candidate.  We've
7263 /// already generated a primary error at the call site.
7264 ///
7265 /// It really does need to be a single diagnostic with its caret
7266 /// pointed at the candidate declaration.  Yes, this creates some
7267 /// major challenges of technical writing.  Yes, this makes pointing
7268 /// out problems with specific arguments quite awkward.  It's still
7269 /// better than generating twenty screens of text for every failed
7270 /// overload.
7271 ///
7272 /// It would be great to be able to express per-candidate problems
7273 /// more richly for those diagnostic clients that cared, but we'd
7274 /// still have to be just as careful with the default diagnostics.
7275 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7276                            Expr **Args, unsigned NumArgs) {
7277   FunctionDecl *Fn = Cand->Function;
7278
7279   // Note deleted candidates, but only if they're viable.
7280   if (Cand->Viable && (Fn->isDeleted() ||
7281       S.isFunctionConsideredUnavailable(Fn))) {
7282     std::string FnDesc;
7283     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7284
7285     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
7286       << FnKind << FnDesc << Fn->isDeleted();
7287     MaybeEmitInheritedConstructorNote(S, Fn);
7288     return;
7289   }
7290
7291   // We don't really have anything else to say about viable candidates.
7292   if (Cand->Viable) {
7293     S.NoteOverloadCandidate(Fn);
7294     return;
7295   }
7296
7297   switch (Cand->FailureKind) {
7298   case ovl_fail_too_many_arguments:
7299   case ovl_fail_too_few_arguments:
7300     return DiagnoseArityMismatch(S, Cand, NumArgs);
7301
7302   case ovl_fail_bad_deduction:
7303     return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7304
7305   case ovl_fail_trivial_conversion:
7306   case ovl_fail_bad_final_conversion:
7307   case ovl_fail_final_conversion_not_exact:
7308     return S.NoteOverloadCandidate(Fn);
7309
7310   case ovl_fail_bad_conversion: {
7311     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7312     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
7313       if (Cand->Conversions[I].isBad())
7314         return DiagnoseBadConversion(S, Cand, I);
7315
7316     // FIXME: this currently happens when we're called from SemaInit
7317     // when user-conversion overload fails.  Figure out how to handle
7318     // those conditions and diagnose them well.
7319     return S.NoteOverloadCandidate(Fn);
7320   }
7321
7322   case ovl_fail_bad_target:
7323     return DiagnoseBadTarget(S, Cand);
7324   }
7325 }
7326
7327 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7328   // Desugar the type of the surrogate down to a function type,
7329   // retaining as many typedefs as possible while still showing
7330   // the function type (and, therefore, its parameter types).
7331   QualType FnType = Cand->Surrogate->getConversionType();
7332   bool isLValueReference = false;
7333   bool isRValueReference = false;
7334   bool isPointer = false;
7335   if (const LValueReferenceType *FnTypeRef =
7336         FnType->getAs<LValueReferenceType>()) {
7337     FnType = FnTypeRef->getPointeeType();
7338     isLValueReference = true;
7339   } else if (const RValueReferenceType *FnTypeRef =
7340                FnType->getAs<RValueReferenceType>()) {
7341     FnType = FnTypeRef->getPointeeType();
7342     isRValueReference = true;
7343   }
7344   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7345     FnType = FnTypePtr->getPointeeType();
7346     isPointer = true;
7347   }
7348   // Desugar down to a function type.
7349   FnType = QualType(FnType->getAs<FunctionType>(), 0);
7350   // Reconstruct the pointer/reference as appropriate.
7351   if (isPointer) FnType = S.Context.getPointerType(FnType);
7352   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7353   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7354
7355   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7356     << FnType;
7357   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
7358 }
7359
7360 void NoteBuiltinOperatorCandidate(Sema &S,
7361                                   const char *Opc,
7362                                   SourceLocation OpLoc,
7363                                   OverloadCandidate *Cand) {
7364   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7365   std::string TypeStr("operator");
7366   TypeStr += Opc;
7367   TypeStr += "(";
7368   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7369   if (Cand->Conversions.size() == 1) {
7370     TypeStr += ")";
7371     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7372   } else {
7373     TypeStr += ", ";
7374     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7375     TypeStr += ")";
7376     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7377   }
7378 }
7379
7380 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7381                                   OverloadCandidate *Cand) {
7382   unsigned NoOperands = Cand->Conversions.size();
7383   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7384     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
7385     if (ICS.isBad()) break; // all meaningless after first invalid
7386     if (!ICS.isAmbiguous()) continue;
7387
7388     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
7389                               S.PDiag(diag::note_ambiguous_type_conversion));
7390   }
7391 }
7392
7393 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7394   if (Cand->Function)
7395     return Cand->Function->getLocation();
7396   if (Cand->IsSurrogate)
7397     return Cand->Surrogate->getLocation();
7398   return SourceLocation();
7399 }
7400
7401 static unsigned
7402 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
7403   switch ((Sema::TemplateDeductionResult)DFI.Result) {
7404   case Sema::TDK_Success:
7405     llvm_unreachable("TDK_success while diagnosing bad deduction");
7406
7407   case Sema::TDK_Incomplete:
7408     return 1;
7409
7410   case Sema::TDK_Underqualified:
7411   case Sema::TDK_Inconsistent:
7412     return 2;
7413
7414   case Sema::TDK_SubstitutionFailure:
7415   case Sema::TDK_NonDeducedMismatch:
7416     return 3;
7417
7418   case Sema::TDK_InstantiationDepth:
7419   case Sema::TDK_FailedOverloadResolution:
7420     return 4;
7421
7422   case Sema::TDK_InvalidExplicitArguments:
7423     return 5;
7424
7425   case Sema::TDK_TooManyArguments:
7426   case Sema::TDK_TooFewArguments:
7427     return 6;
7428   }
7429   llvm_unreachable("Unhandled deduction result");
7430 }
7431
7432 struct CompareOverloadCandidatesForDisplay {
7433   Sema &S;
7434   CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
7435
7436   bool operator()(const OverloadCandidate *L,
7437                   const OverloadCandidate *R) {
7438     // Fast-path this check.
7439     if (L == R) return false;
7440
7441     // Order first by viability.
7442     if (L->Viable) {
7443       if (!R->Viable) return true;
7444
7445       // TODO: introduce a tri-valued comparison for overload
7446       // candidates.  Would be more worthwhile if we had a sort
7447       // that could exploit it.
7448       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7449       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
7450     } else if (R->Viable)
7451       return false;
7452
7453     assert(L->Viable == R->Viable);
7454
7455     // Criteria by which we can sort non-viable candidates:
7456     if (!L->Viable) {
7457       // 1. Arity mismatches come after other candidates.
7458       if (L->FailureKind == ovl_fail_too_many_arguments ||
7459           L->FailureKind == ovl_fail_too_few_arguments)
7460         return false;
7461       if (R->FailureKind == ovl_fail_too_many_arguments ||
7462           R->FailureKind == ovl_fail_too_few_arguments)
7463         return true;
7464
7465       // 2. Bad conversions come first and are ordered by the number
7466       // of bad conversions and quality of good conversions.
7467       if (L->FailureKind == ovl_fail_bad_conversion) {
7468         if (R->FailureKind != ovl_fail_bad_conversion)
7469           return true;
7470
7471         // The conversion that can be fixed with a smaller number of changes,
7472         // comes first.
7473         unsigned numLFixes = L->Fix.NumConversionsFixed;
7474         unsigned numRFixes = R->Fix.NumConversionsFixed;
7475         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7476         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
7477         if (numLFixes != numRFixes) {
7478           if (numLFixes < numRFixes)
7479             return true;
7480           else
7481             return false;
7482         }
7483
7484         // If there's any ordering between the defined conversions...
7485         // FIXME: this might not be transitive.
7486         assert(L->Conversions.size() == R->Conversions.size());
7487
7488         int leftBetter = 0;
7489         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7490         for (unsigned E = L->Conversions.size(); I != E; ++I) {
7491           switch (CompareImplicitConversionSequences(S,
7492                                                      L->Conversions[I],
7493                                                      R->Conversions[I])) {
7494           case ImplicitConversionSequence::Better:
7495             leftBetter++;
7496             break;
7497
7498           case ImplicitConversionSequence::Worse:
7499             leftBetter--;
7500             break;
7501
7502           case ImplicitConversionSequence::Indistinguishable:
7503             break;
7504           }
7505         }
7506         if (leftBetter > 0) return true;
7507         if (leftBetter < 0) return false;
7508
7509       } else if (R->FailureKind == ovl_fail_bad_conversion)
7510         return false;
7511
7512       if (L->FailureKind == ovl_fail_bad_deduction) {
7513         if (R->FailureKind != ovl_fail_bad_deduction)
7514           return true;
7515
7516         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7517           return RankDeductionFailure(L->DeductionFailure)
7518                < RankDeductionFailure(R->DeductionFailure);
7519       } else if (R->FailureKind == ovl_fail_bad_deduction)
7520         return false;
7521
7522       // TODO: others?
7523     }
7524
7525     // Sort everything else by location.
7526     SourceLocation LLoc = GetLocationForCandidate(L);
7527     SourceLocation RLoc = GetLocationForCandidate(R);
7528
7529     // Put candidates without locations (e.g. builtins) at the end.
7530     if (LLoc.isInvalid()) return false;
7531     if (RLoc.isInvalid()) return true;
7532
7533     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
7534   }
7535 };
7536
7537 /// CompleteNonViableCandidate - Normally, overload resolution only
7538 /// computes up to the first. Produces the FixIt set if possible.
7539 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7540                                 Expr **Args, unsigned NumArgs) {
7541   assert(!Cand->Viable);
7542
7543   // Don't do anything on failures other than bad conversion.
7544   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7545
7546   // We only want the FixIts if all the arguments can be corrected.
7547   bool Unfixable = false;
7548   // Use a implicit copy initialization to check conversion fixes.
7549   Cand->Fix.setConversionChecker(TryCopyInitialization);
7550
7551   // Skip forward to the first bad conversion.
7552   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
7553   unsigned ConvCount = Cand->Conversions.size();
7554   while (true) {
7555     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7556     ConvIdx++;
7557     if (Cand->Conversions[ConvIdx - 1].isBad()) {
7558       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
7559       break;
7560     }
7561   }
7562
7563   if (ConvIdx == ConvCount)
7564     return;
7565
7566   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7567          "remaining conversion is initialized?");
7568
7569   // FIXME: this should probably be preserved from the overload
7570   // operation somehow.
7571   bool SuppressUserConversions = false;
7572
7573   const FunctionProtoType* Proto;
7574   unsigned ArgIdx = ConvIdx;
7575
7576   if (Cand->IsSurrogate) {
7577     QualType ConvType
7578       = Cand->Surrogate->getConversionType().getNonReferenceType();
7579     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7580       ConvType = ConvPtrType->getPointeeType();
7581     Proto = ConvType->getAs<FunctionProtoType>();
7582     ArgIdx--;
7583   } else if (Cand->Function) {
7584     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7585     if (isa<CXXMethodDecl>(Cand->Function) &&
7586         !isa<CXXConstructorDecl>(Cand->Function))
7587       ArgIdx--;
7588   } else {
7589     // Builtin binary operator with a bad first conversion.
7590     assert(ConvCount <= 3);
7591     for (; ConvIdx != ConvCount; ++ConvIdx)
7592       Cand->Conversions[ConvIdx]
7593         = TryCopyInitialization(S, Args[ConvIdx],
7594                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
7595                                 SuppressUserConversions,
7596                                 /*InOverloadResolution*/ true,
7597                                 /*AllowObjCWritebackConversion=*/
7598                                   S.getLangOptions().ObjCAutoRefCount);
7599     return;
7600   }
7601
7602   // Fill in the rest of the conversions.
7603   unsigned NumArgsInProto = Proto->getNumArgs();
7604   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7605     if (ArgIdx < NumArgsInProto) {
7606       Cand->Conversions[ConvIdx]
7607         = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
7608                                 SuppressUserConversions,
7609                                 /*InOverloadResolution=*/true,
7610                                 /*AllowObjCWritebackConversion=*/
7611                                   S.getLangOptions().ObjCAutoRefCount);
7612       // Store the FixIt in the candidate if it exists.
7613       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
7614         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
7615     }
7616     else
7617       Cand->Conversions[ConvIdx].setEllipsis();
7618   }
7619 }
7620
7621 } // end anonymous namespace
7622
7623 /// PrintOverloadCandidates - When overload resolution fails, prints
7624 /// diagnostic messages containing the candidates in the candidate
7625 /// set.
7626 void OverloadCandidateSet::NoteCandidates(Sema &S,
7627                                           OverloadCandidateDisplayKind OCD,
7628                                           Expr **Args, unsigned NumArgs,
7629                                           const char *Opc,
7630                                           SourceLocation OpLoc) {
7631   // Sort the candidates by viability and position.  Sorting directly would
7632   // be prohibitive, so we make a set of pointers and sort those.
7633   SmallVector<OverloadCandidate*, 32> Cands;
7634   if (OCD == OCD_AllCandidates) Cands.reserve(size());
7635   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
7636     if (Cand->Viable)
7637       Cands.push_back(Cand);
7638     else if (OCD == OCD_AllCandidates) {
7639       CompleteNonViableCandidate(S, Cand, Args, NumArgs);
7640       if (Cand->Function || Cand->IsSurrogate)
7641         Cands.push_back(Cand);
7642       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
7643       // want to list every possible builtin candidate.
7644     }
7645   }
7646
7647   std::sort(Cands.begin(), Cands.end(),
7648             CompareOverloadCandidatesForDisplay(S));
7649
7650   bool ReportedAmbiguousConversions = false;
7651
7652   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
7653   const DiagnosticsEngine::OverloadsShown ShowOverloads = 
7654       S.Diags.getShowOverloads();
7655   unsigned CandsShown = 0;
7656   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7657     OverloadCandidate *Cand = *I;
7658
7659     // Set an arbitrary limit on the number of candidate functions we'll spam
7660     // the user with.  FIXME: This limit should depend on details of the
7661     // candidate list.
7662     if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
7663       break;
7664     }
7665     ++CandsShown;
7666
7667     if (Cand->Function)
7668       NoteFunctionCandidate(S, Cand, Args, NumArgs);
7669     else if (Cand->IsSurrogate)
7670       NoteSurrogateCandidate(S, Cand);
7671     else {
7672       assert(Cand->Viable &&
7673              "Non-viable built-in candidates are not added to Cands.");
7674       // Generally we only see ambiguities including viable builtin
7675       // operators if overload resolution got screwed up by an
7676       // ambiguous user-defined conversion.
7677       //
7678       // FIXME: It's quite possible for different conversions to see
7679       // different ambiguities, though.
7680       if (!ReportedAmbiguousConversions) {
7681         NoteAmbiguousUserConversions(S, OpLoc, Cand);
7682         ReportedAmbiguousConversions = true;
7683       }
7684
7685       // If this is a viable builtin, print it.
7686       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
7687     }
7688   }
7689
7690   if (I != E)
7691     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
7692 }
7693
7694 // [PossiblyAFunctionType]  -->   [Return]
7695 // NonFunctionType --> NonFunctionType
7696 // R (A) --> R(A)
7697 // R (*)(A) --> R (A)
7698 // R (&)(A) --> R (A)
7699 // R (S::*)(A) --> R (A)
7700 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7701   QualType Ret = PossiblyAFunctionType;
7702   if (const PointerType *ToTypePtr = 
7703     PossiblyAFunctionType->getAs<PointerType>())
7704     Ret = ToTypePtr->getPointeeType();
7705   else if (const ReferenceType *ToTypeRef = 
7706     PossiblyAFunctionType->getAs<ReferenceType>())
7707     Ret = ToTypeRef->getPointeeType();
7708   else if (const MemberPointerType *MemTypePtr =
7709     PossiblyAFunctionType->getAs<MemberPointerType>()) 
7710     Ret = MemTypePtr->getPointeeType();   
7711   Ret = 
7712     Context.getCanonicalType(Ret).getUnqualifiedType();
7713   return Ret;
7714 }
7715
7716 // A helper class to help with address of function resolution
7717 // - allows us to avoid passing around all those ugly parameters
7718 class AddressOfFunctionResolver 
7719 {
7720   Sema& S;
7721   Expr* SourceExpr;
7722   const QualType& TargetType; 
7723   QualType TargetFunctionType; // Extracted function type from target type 
7724    
7725   bool Complain;
7726   //DeclAccessPair& ResultFunctionAccessPair;
7727   ASTContext& Context;
7728
7729   bool TargetTypeIsNonStaticMemberFunction;
7730   bool FoundNonTemplateFunction;
7731
7732   OverloadExpr::FindResult OvlExprInfo; 
7733   OverloadExpr *OvlExpr;
7734   TemplateArgumentListInfo OvlExplicitTemplateArgs;
7735   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
7736
7737 public:
7738   AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 
7739                             const QualType& TargetType, bool Complain)
7740     : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 
7741       Complain(Complain), Context(S.getASTContext()), 
7742       TargetTypeIsNonStaticMemberFunction(
7743                                     !!TargetType->getAs<MemberPointerType>()),
7744       FoundNonTemplateFunction(false),
7745       OvlExprInfo(OverloadExpr::find(SourceExpr)),
7746       OvlExpr(OvlExprInfo.Expression)
7747   {
7748     ExtractUnqualifiedFunctionTypeFromTargetType();
7749     
7750     if (!TargetFunctionType->isFunctionType()) {        
7751       if (OvlExpr->hasExplicitTemplateArgs()) {
7752         DeclAccessPair dap;
7753         if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
7754                                             OvlExpr, false, &dap) ) {
7755
7756           if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7757             if (!Method->isStatic()) {
7758               // If the target type is a non-function type and the function
7759               // found is a non-static member function, pretend as if that was
7760               // the target, it's the only possible type to end up with.
7761               TargetTypeIsNonStaticMemberFunction = true;
7762
7763               // And skip adding the function if its not in the proper form.
7764               // We'll diagnose this due to an empty set of functions.
7765               if (!OvlExprInfo.HasFormOfMemberPointer)
7766                 return;
7767             }
7768           }
7769
7770           Matches.push_back(std::make_pair(dap,Fn));
7771         }
7772       }
7773       return;
7774     }
7775     
7776     if (OvlExpr->hasExplicitTemplateArgs())
7777       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
7778
7779     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7780       // C++ [over.over]p4:
7781       //   If more than one function is selected, [...]
7782       if (Matches.size() > 1) {
7783         if (FoundNonTemplateFunction)
7784           EliminateAllTemplateMatches();
7785         else
7786           EliminateAllExceptMostSpecializedTemplate();
7787       }
7788     }
7789   }
7790   
7791 private:
7792   bool isTargetTypeAFunction() const {
7793     return TargetFunctionType->isFunctionType();
7794   }
7795
7796   // [ToType]     [Return]
7797
7798   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7799   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7800   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7801   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7802     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7803   }
7804
7805   // return true if any matching specializations were found
7806   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 
7807                                    const DeclAccessPair& CurAccessFunPair) {
7808     if (CXXMethodDecl *Method
7809               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7810       // Skip non-static function templates when converting to pointer, and
7811       // static when converting to member pointer.
7812       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7813         return false;
7814     } 
7815     else if (TargetTypeIsNonStaticMemberFunction)
7816       return false;
7817
7818     // C++ [over.over]p2:
7819     //   If the name is a function template, template argument deduction is
7820     //   done (14.8.2.2), and if the argument deduction succeeds, the
7821     //   resulting template argument list is used to generate a single
7822     //   function template specialization, which is added to the set of
7823     //   overloaded functions considered.
7824     FunctionDecl *Specialization = 0;
7825     TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7826     if (Sema::TemplateDeductionResult Result
7827           = S.DeduceTemplateArguments(FunctionTemplate, 
7828                                       &OvlExplicitTemplateArgs,
7829                                       TargetFunctionType, Specialization, 
7830                                       Info)) {
7831       // FIXME: make a note of the failed deduction for diagnostics.
7832       (void)Result;
7833       return false;
7834     } 
7835     
7836     // Template argument deduction ensures that we have an exact match.
7837     // This function template specicalization works.
7838     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7839     assert(TargetFunctionType
7840                       == Context.getCanonicalType(Specialization->getType()));
7841     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7842     return true;
7843   }
7844   
7845   bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 
7846                                       const DeclAccessPair& CurAccessFunPair) {
7847     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7848       // Skip non-static functions when converting to pointer, and static
7849       // when converting to member pointer.
7850       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7851         return false;
7852     } 
7853     else if (TargetTypeIsNonStaticMemberFunction)
7854       return false;
7855
7856     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
7857       if (S.getLangOptions().CUDA)
7858         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
7859           if (S.CheckCUDATarget(Caller, FunDecl))
7860             return false;
7861
7862       QualType ResultTy;
7863       if (Context.hasSameUnqualifiedType(TargetFunctionType, 
7864                                          FunDecl->getType()) ||
7865           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7866                                  ResultTy)) {
7867         Matches.push_back(std::make_pair(CurAccessFunPair,
7868           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
7869         FoundNonTemplateFunction = true;
7870         return true;
7871       }
7872     }
7873     
7874     return false;
7875   }
7876   
7877   bool FindAllFunctionsThatMatchTargetTypeExactly() {
7878     bool Ret = false;
7879     
7880     // If the overload expression doesn't have the form of a pointer to
7881     // member, don't try to convert it to a pointer-to-member type.
7882     if (IsInvalidFormOfPointerToMemberFunction())
7883       return false;
7884
7885     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7886                                E = OvlExpr->decls_end(); 
7887          I != E; ++I) {
7888       // Look through any using declarations to find the underlying function.
7889       NamedDecl *Fn = (*I)->getUnderlyingDecl();
7890
7891       // C++ [over.over]p3:
7892       //   Non-member functions and static member functions match
7893       //   targets of type "pointer-to-function" or "reference-to-function."
7894       //   Nonstatic member functions match targets of
7895       //   type "pointer-to-member-function."
7896       // Note that according to DR 247, the containing class does not matter.
7897       if (FunctionTemplateDecl *FunctionTemplate
7898                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
7899         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7900           Ret = true;
7901       }
7902       // If we have explicit template arguments supplied, skip non-templates.
7903       else if (!OvlExpr->hasExplicitTemplateArgs() &&
7904                AddMatchingNonTemplateFunction(Fn, I.getPair()))
7905         Ret = true;
7906     }
7907     assert(Ret || Matches.empty());
7908     return Ret;
7909   }
7910
7911   void EliminateAllExceptMostSpecializedTemplate() {
7912     //   [...] and any given function template specialization F1 is
7913     //   eliminated if the set contains a second function template
7914     //   specialization whose function template is more specialized
7915     //   than the function template of F1 according to the partial
7916     //   ordering rules of 14.5.5.2.
7917
7918     // The algorithm specified above is quadratic. We instead use a
7919     // two-pass algorithm (similar to the one used to identify the
7920     // best viable function in an overload set) that identifies the
7921     // best function template (if it exists).
7922
7923     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7924     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7925       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
7926
7927     UnresolvedSetIterator Result =
7928       S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7929                            TPOC_Other, 0, SourceExpr->getLocStart(),
7930                            S.PDiag(),
7931                            S.PDiag(diag::err_addr_ovl_ambiguous)
7932                              << Matches[0].second->getDeclName(),
7933                            S.PDiag(diag::note_ovl_candidate)
7934                              << (unsigned) oc_function_template,
7935                            Complain);
7936
7937     if (Result != MatchesCopy.end()) {
7938       // Make it the first and only element
7939       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7940       Matches[0].second = cast<FunctionDecl>(*Result);
7941       Matches.resize(1);
7942     }
7943   }
7944
7945   void EliminateAllTemplateMatches() {
7946     //   [...] any function template specializations in the set are
7947     //   eliminated if the set also contains a non-template function, [...]
7948     for (unsigned I = 0, N = Matches.size(); I != N; ) {
7949       if (Matches[I].second->getPrimaryTemplate() == 0)
7950         ++I;
7951       else {
7952         Matches[I] = Matches[--N];
7953         Matches.set_size(N);
7954       }
7955     }
7956   }
7957
7958 public:
7959   void ComplainNoMatchesFound() const {
7960     assert(Matches.empty());
7961     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7962         << OvlExpr->getName() << TargetFunctionType
7963         << OvlExpr->getSourceRange();
7964     S.NoteAllOverloadCandidates(OvlExpr);
7965   } 
7966   
7967   bool IsInvalidFormOfPointerToMemberFunction() const {
7968     return TargetTypeIsNonStaticMemberFunction &&
7969       !OvlExprInfo.HasFormOfMemberPointer;
7970   }
7971   
7972   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7973       // TODO: Should we condition this on whether any functions might
7974       // have matched, or is it more appropriate to do that in callers?
7975       // TODO: a fixit wouldn't hurt.
7976       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7977         << TargetType << OvlExpr->getSourceRange();
7978   }
7979   
7980   void ComplainOfInvalidConversion() const {
7981     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7982       << OvlExpr->getName() << TargetType;
7983   }
7984
7985   void ComplainMultipleMatchesFound() const {
7986     assert(Matches.size() > 1);
7987     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7988       << OvlExpr->getName()
7989       << OvlExpr->getSourceRange();
7990     S.NoteAllOverloadCandidates(OvlExpr);
7991   }
7992   
7993   int getNumMatches() const { return Matches.size(); }
7994   
7995   FunctionDecl* getMatchingFunctionDecl() const {
7996     if (Matches.size() != 1) return 0;
7997     return Matches[0].second;
7998   }
7999   
8000   const DeclAccessPair* getMatchingFunctionAccessPair() const {
8001     if (Matches.size() != 1) return 0;
8002     return &Matches[0].first;
8003   }
8004 };
8005   
8006 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8007 /// an overloaded function (C++ [over.over]), where @p From is an
8008 /// expression with overloaded function type and @p ToType is the type
8009 /// we're trying to resolve to. For example:
8010 ///
8011 /// @code
8012 /// int f(double);
8013 /// int f(int);
8014 ///
8015 /// int (*pfd)(double) = f; // selects f(double)
8016 /// @endcode
8017 ///
8018 /// This routine returns the resulting FunctionDecl if it could be
8019 /// resolved, and NULL otherwise. When @p Complain is true, this
8020 /// routine will emit diagnostics if there is an error.
8021 FunctionDecl *
8022 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
8023                                     bool Complain,
8024                                     DeclAccessPair &FoundResult) {
8025
8026   assert(AddressOfExpr->getType() == Context.OverloadTy);
8027   
8028   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
8029   int NumMatches = Resolver.getNumMatches();
8030   FunctionDecl* Fn = 0;
8031   if ( NumMatches == 0 && Complain) {
8032     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8033       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8034     else
8035       Resolver.ComplainNoMatchesFound();
8036   }
8037   else if (NumMatches > 1 && Complain)
8038     Resolver.ComplainMultipleMatchesFound();
8039   else if (NumMatches == 1) {
8040     Fn = Resolver.getMatchingFunctionDecl();
8041     assert(Fn);
8042     FoundResult = *Resolver.getMatchingFunctionAccessPair();
8043     MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
8044     if (Complain)
8045       CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
8046   }
8047   
8048   return Fn;
8049 }
8050
8051 /// \brief Given an expression that refers to an overloaded function, try to
8052 /// resolve that overloaded function expression down to a single function.
8053 ///
8054 /// This routine can only resolve template-ids that refer to a single function
8055 /// template, where that template-id refers to a single template whose template
8056 /// arguments are either provided by the template-id or have defaults,
8057 /// as described in C++0x [temp.arg.explicit]p3.
8058 FunctionDecl *
8059 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 
8060                                                   bool Complain,
8061                                                   DeclAccessPair *FoundResult) {
8062   // C++ [over.over]p1:
8063   //   [...] [Note: any redundant set of parentheses surrounding the
8064   //   overloaded function name is ignored (5.1). ]
8065   // C++ [over.over]p1:
8066   //   [...] The overloaded function name can be preceded by the &
8067   //   operator.
8068
8069   // If we didn't actually find any template-ids, we're done.
8070   if (!ovl->hasExplicitTemplateArgs())
8071     return 0;
8072
8073   TemplateArgumentListInfo ExplicitTemplateArgs;
8074   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
8075
8076   // Look through all of the overloaded functions, searching for one
8077   // whose type matches exactly.
8078   FunctionDecl *Matched = 0;
8079   for (UnresolvedSetIterator I = ovl->decls_begin(),
8080          E = ovl->decls_end(); I != E; ++I) {
8081     // C++0x [temp.arg.explicit]p3:
8082     //   [...] In contexts where deduction is done and fails, or in contexts
8083     //   where deduction is not done, if a template argument list is
8084     //   specified and it, along with any default template arguments,
8085     //   identifies a single function template specialization, then the
8086     //   template-id is an lvalue for the function template specialization.
8087     FunctionTemplateDecl *FunctionTemplate
8088       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
8089
8090     // C++ [over.over]p2:
8091     //   If the name is a function template, template argument deduction is
8092     //   done (14.8.2.2), and if the argument deduction succeeds, the
8093     //   resulting template argument list is used to generate a single
8094     //   function template specialization, which is added to the set of
8095     //   overloaded functions considered.
8096     FunctionDecl *Specialization = 0;
8097     TemplateDeductionInfo Info(Context, ovl->getNameLoc());
8098     if (TemplateDeductionResult Result
8099           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8100                                     Specialization, Info)) {
8101       // FIXME: make a note of the failed deduction for diagnostics.
8102       (void)Result;
8103       continue;
8104     }
8105
8106     assert(Specialization && "no specialization and no error?");
8107
8108     // Multiple matches; we can't resolve to a single declaration.
8109     if (Matched) {
8110       if (Complain) {
8111         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8112           << ovl->getName();
8113         NoteAllOverloadCandidates(ovl);
8114       }
8115       return 0;
8116     }
8117     
8118     Matched = Specialization;
8119     if (FoundResult) *FoundResult = I.getPair();    
8120   }
8121
8122   return Matched;
8123 }
8124
8125
8126
8127
8128 // Resolve and fix an overloaded expression that can be resolved
8129 // because it identifies a single function template specialization.
8130 //
8131 // Last three arguments should only be supplied if Complain = true
8132 //
8133 // Return true if it was logically possible to so resolve the
8134 // expression, regardless of whether or not it succeeded.  Always
8135 // returns true if 'complain' is set.
8136 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8137                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
8138                    bool complain, const SourceRange& OpRangeForComplaining, 
8139                                            QualType DestTypeForComplaining, 
8140                                             unsigned DiagIDForComplaining) {
8141   assert(SrcExpr.get()->getType() == Context.OverloadTy);
8142
8143   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
8144
8145   DeclAccessPair found;
8146   ExprResult SingleFunctionExpression;
8147   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8148                            ovl.Expression, /*complain*/ false, &found)) {
8149     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8150       SrcExpr = ExprError();
8151       return true;
8152     }
8153
8154     // It is only correct to resolve to an instance method if we're
8155     // resolving a form that's permitted to be a pointer to member.
8156     // Otherwise we'll end up making a bound member expression, which
8157     // is illegal in all the contexts we resolve like this.
8158     if (!ovl.HasFormOfMemberPointer &&
8159         isa<CXXMethodDecl>(fn) &&
8160         cast<CXXMethodDecl>(fn)->isInstance()) {
8161       if (!complain) return false;
8162
8163       Diag(ovl.Expression->getExprLoc(),
8164            diag::err_bound_member_function)
8165         << 0 << ovl.Expression->getSourceRange();
8166
8167       // TODO: I believe we only end up here if there's a mix of
8168       // static and non-static candidates (otherwise the expression
8169       // would have 'bound member' type, not 'overload' type).
8170       // Ideally we would note which candidate was chosen and why
8171       // the static candidates were rejected.
8172       SrcExpr = ExprError();
8173       return true;
8174     }
8175
8176     // Fix the expresion to refer to 'fn'.
8177     SingleFunctionExpression =
8178       Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
8179
8180     // If desired, do function-to-pointer decay.
8181     if (doFunctionPointerConverion) {
8182       SingleFunctionExpression =
8183         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
8184       if (SingleFunctionExpression.isInvalid()) {
8185         SrcExpr = ExprError();
8186         return true;
8187       }
8188     }
8189   }
8190
8191   if (!SingleFunctionExpression.isUsable()) {
8192     if (complain) {
8193       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8194         << ovl.Expression->getName()
8195         << DestTypeForComplaining
8196         << OpRangeForComplaining 
8197         << ovl.Expression->getQualifierLoc().getSourceRange();
8198       NoteAllOverloadCandidates(SrcExpr.get());
8199
8200       SrcExpr = ExprError();
8201       return true;
8202     }
8203
8204     return false;
8205   }
8206
8207   SrcExpr = SingleFunctionExpression;
8208   return true;
8209 }
8210
8211 /// \brief Add a single candidate to the overload set.
8212 static void AddOverloadedCallCandidate(Sema &S,
8213                                        DeclAccessPair FoundDecl,
8214                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8215                                        Expr **Args, unsigned NumArgs,
8216                                        OverloadCandidateSet &CandidateSet,
8217                                        bool PartialOverloading,
8218                                        bool KnownValid) {
8219   NamedDecl *Callee = FoundDecl.getDecl();
8220   if (isa<UsingShadowDecl>(Callee))
8221     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8222
8223   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
8224     if (ExplicitTemplateArgs) {
8225       assert(!KnownValid && "Explicit template arguments?");
8226       return;
8227     }
8228     S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
8229                            false, PartialOverloading);
8230     return;
8231   }
8232
8233   if (FunctionTemplateDecl *FuncTemplate
8234       = dyn_cast<FunctionTemplateDecl>(Callee)) {
8235     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8236                                    ExplicitTemplateArgs,
8237                                    Args, NumArgs, CandidateSet);
8238     return;
8239   }
8240
8241   assert(!KnownValid && "unhandled case in overloaded call candidate");
8242 }
8243
8244 /// \brief Add the overload candidates named by callee and/or found by argument
8245 /// dependent lookup to the given overload set.
8246 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
8247                                        Expr **Args, unsigned NumArgs,
8248                                        OverloadCandidateSet &CandidateSet,
8249                                        bool PartialOverloading) {
8250
8251 #ifndef NDEBUG
8252   // Verify that ArgumentDependentLookup is consistent with the rules
8253   // in C++0x [basic.lookup.argdep]p3:
8254   //
8255   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
8256   //   and let Y be the lookup set produced by argument dependent
8257   //   lookup (defined as follows). If X contains
8258   //
8259   //     -- a declaration of a class member, or
8260   //
8261   //     -- a block-scope function declaration that is not a
8262   //        using-declaration, or
8263   //
8264   //     -- a declaration that is neither a function or a function
8265   //        template
8266   //
8267   //   then Y is empty.
8268
8269   if (ULE->requiresADL()) {
8270     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8271            E = ULE->decls_end(); I != E; ++I) {
8272       assert(!(*I)->getDeclContext()->isRecord());
8273       assert(isa<UsingShadowDecl>(*I) ||
8274              !(*I)->getDeclContext()->isFunctionOrMethod());
8275       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
8276     }
8277   }
8278 #endif
8279
8280   // It would be nice to avoid this copy.
8281   TemplateArgumentListInfo TABuffer;
8282   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
8283   if (ULE->hasExplicitTemplateArgs()) {
8284     ULE->copyTemplateArgumentsInto(TABuffer);
8285     ExplicitTemplateArgs = &TABuffer;
8286   }
8287
8288   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8289          E = ULE->decls_end(); I != E; ++I)
8290     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
8291                                Args, NumArgs, CandidateSet,
8292                                PartialOverloading, /*KnownValid*/ true);
8293
8294   if (ULE->requiresADL())
8295     AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8296                                          Args, NumArgs,
8297                                          ExplicitTemplateArgs,
8298                                          CandidateSet,
8299                                          PartialOverloading,
8300                                          ULE->isStdAssociatedNamespace());
8301 }
8302
8303 /// Attempt to recover from an ill-formed use of a non-dependent name in a
8304 /// template, where the non-dependent name was declared after the template
8305 /// was defined. This is common in code written for a compilers which do not
8306 /// correctly implement two-stage name lookup.
8307 ///
8308 /// Returns true if a viable candidate was found and a diagnostic was issued.
8309 static bool
8310 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8311                        const CXXScopeSpec &SS, LookupResult &R,
8312                        TemplateArgumentListInfo *ExplicitTemplateArgs,
8313                        Expr **Args, unsigned NumArgs) {
8314   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8315     return false;
8316
8317   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8318     SemaRef.LookupQualifiedName(R, DC);
8319
8320     if (!R.empty()) {
8321       R.suppressDiagnostics();
8322
8323       if (isa<CXXRecordDecl>(DC)) {
8324         // Don't diagnose names we find in classes; we get much better
8325         // diagnostics for these from DiagnoseEmptyLookup.
8326         R.clear();
8327         return false;
8328       }
8329
8330       OverloadCandidateSet Candidates(FnLoc);
8331       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8332         AddOverloadedCallCandidate(SemaRef, I.getPair(),
8333                                    ExplicitTemplateArgs, Args, NumArgs,
8334                                    Candidates, false, /*KnownValid*/ false);
8335
8336       OverloadCandidateSet::iterator Best;
8337       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
8338         // No viable functions. Don't bother the user with notes for functions
8339         // which don't work and shouldn't be found anyway.
8340         R.clear();
8341         return false;
8342       }
8343
8344       // Find the namespaces where ADL would have looked, and suggest
8345       // declaring the function there instead.
8346       Sema::AssociatedNamespaceSet AssociatedNamespaces;
8347       Sema::AssociatedClassSet AssociatedClasses;
8348       SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8349                                                  AssociatedNamespaces,
8350                                                  AssociatedClasses);
8351       // Never suggest declaring a function within namespace 'std'. 
8352       Sema::AssociatedNamespaceSet SuggestedNamespaces;
8353       if (DeclContext *Std = SemaRef.getStdNamespace()) {
8354         for (Sema::AssociatedNamespaceSet::iterator
8355                it = AssociatedNamespaces.begin(),
8356                end = AssociatedNamespaces.end(); it != end; ++it) {
8357           if (!Std->Encloses(*it))
8358             SuggestedNamespaces.insert(*it);
8359         }
8360       } else {
8361         // Lacking the 'std::' namespace, use all of the associated namespaces.
8362         SuggestedNamespaces = AssociatedNamespaces;
8363       }
8364
8365       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8366         << R.getLookupName();
8367       if (SuggestedNamespaces.empty()) {
8368         SemaRef.Diag(Best->Function->getLocation(),
8369                      diag::note_not_found_by_two_phase_lookup)
8370           << R.getLookupName() << 0;
8371       } else if (SuggestedNamespaces.size() == 1) {
8372         SemaRef.Diag(Best->Function->getLocation(),
8373                      diag::note_not_found_by_two_phase_lookup)
8374           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
8375       } else {
8376         // FIXME: It would be useful to list the associated namespaces here,
8377         // but the diagnostics infrastructure doesn't provide a way to produce
8378         // a localized representation of a list of items.
8379         SemaRef.Diag(Best->Function->getLocation(),
8380                      diag::note_not_found_by_two_phase_lookup)
8381           << R.getLookupName() << 2;
8382       }
8383
8384       // Try to recover by calling this function.
8385       return true;
8386     }
8387
8388     R.clear();
8389   }
8390
8391   return false;
8392 }
8393
8394 /// Attempt to recover from ill-formed use of a non-dependent operator in a
8395 /// template, where the non-dependent operator was declared after the template
8396 /// was defined.
8397 ///
8398 /// Returns true if a viable candidate was found and a diagnostic was issued.
8399 static bool
8400 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8401                                SourceLocation OpLoc,
8402                                Expr **Args, unsigned NumArgs) {
8403   DeclarationName OpName =
8404     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8405   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8406   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8407                                 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8408 }
8409
8410 /// Attempts to recover from a call where no functions were found.
8411 ///
8412 /// Returns true if new candidates were found.
8413 static ExprResult
8414 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
8415                       UnresolvedLookupExpr *ULE,
8416                       SourceLocation LParenLoc,
8417                       Expr **Args, unsigned NumArgs,
8418                       SourceLocation RParenLoc,
8419                       bool EmptyLookup) {
8420
8421   CXXScopeSpec SS;
8422   SS.Adopt(ULE->getQualifierLoc());
8423
8424   TemplateArgumentListInfo TABuffer;
8425   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
8426   if (ULE->hasExplicitTemplateArgs()) {
8427     ULE->copyTemplateArgumentsInto(TABuffer);
8428     ExplicitTemplateArgs = &TABuffer;
8429   }
8430
8431   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8432                  Sema::LookupOrdinaryName);
8433   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8434                               ExplicitTemplateArgs, Args, NumArgs) &&
8435       (!EmptyLookup ||
8436        SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
8437                                    ExplicitTemplateArgs, Args, NumArgs)))
8438     return ExprError();
8439
8440   assert(!R.empty() && "lookup results empty despite recovery");
8441
8442   // Build an implicit member call if appropriate.  Just drop the
8443   // casts and such from the call, we don't really care.
8444   ExprResult NewFn = ExprError();
8445   if ((*R.begin())->isCXXClassMember())
8446     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8447                                                     ExplicitTemplateArgs);
8448   else if (ExplicitTemplateArgs)
8449     NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8450   else
8451     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8452
8453   if (NewFn.isInvalid())
8454     return ExprError();
8455
8456   // This shouldn't cause an infinite loop because we're giving it
8457   // an expression with viable lookup results, which should never
8458   // end up here.
8459   return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
8460                                MultiExprArg(Args, NumArgs), RParenLoc);
8461 }
8462
8463 /// ResolveOverloadedCallFn - Given the call expression that calls Fn
8464 /// (which eventually refers to the declaration Func) and the call
8465 /// arguments Args/NumArgs, attempt to resolve the function call down
8466 /// to a specific function. If overload resolution succeeds, returns
8467 /// the function declaration produced by overload
8468 /// resolution. Otherwise, emits diagnostics, deletes all of the
8469 /// arguments and Fn, and returns NULL.
8470 ExprResult
8471 Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
8472                               SourceLocation LParenLoc,
8473                               Expr **Args, unsigned NumArgs,
8474                               SourceLocation RParenLoc,
8475                               Expr *ExecConfig) {
8476 #ifndef NDEBUG
8477   if (ULE->requiresADL()) {
8478     // To do ADL, we must have found an unqualified name.
8479     assert(!ULE->getQualifier() && "qualified name with ADL");
8480
8481     // We don't perform ADL for implicit declarations of builtins.
8482     // Verify that this was correctly set up.
8483     FunctionDecl *F;
8484     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8485         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8486         F->getBuiltinID() && F->isImplicit())
8487       llvm_unreachable("performing ADL for builtin");
8488
8489     // We don't perform ADL in C.
8490     assert(getLangOptions().CPlusPlus && "ADL enabled in C");
8491   } else
8492     assert(!ULE->isStdAssociatedNamespace() &&
8493            "std is associated namespace but not doing ADL");
8494 #endif
8495
8496   OverloadCandidateSet CandidateSet(Fn->getExprLoc());
8497
8498   // Add the functions denoted by the callee to the set of candidate
8499   // functions, including those from argument-dependent lookup.
8500   AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
8501
8502   // If we found nothing, try to recover.
8503   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8504   // out if it fails.
8505   if (CandidateSet.empty()) {
8506     // In Microsoft mode, if we are inside a template class member function then
8507     // create a type dependent CallExpr. The goal is to postpone name lookup
8508     // to instantiation time to be able to search into type dependent base
8509     // classes.
8510     if (getLangOptions().MicrosoftExt && CurContext->isDependentContext() && 
8511         isa<CXXMethodDecl>(CurContext)) {
8512       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8513                                           Context.DependentTy, VK_RValue,
8514                                           RParenLoc);
8515       CE->setTypeDependent(true);
8516       return Owned(CE);
8517     }
8518     return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
8519                                  RParenLoc, /*EmptyLookup=*/true);
8520   }
8521
8522   OverloadCandidateSet::iterator Best;
8523   switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
8524   case OR_Success: {
8525     FunctionDecl *FDecl = Best->Function;
8526     MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
8527     CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
8528     DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8529                       ULE->getNameLoc());
8530     Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8531     return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8532                                  ExecConfig);
8533   }
8534
8535   case OR_No_Viable_Function: {
8536     // Try to recover by looking for viable functions which the user might
8537     // have meant to call.
8538     ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8539                                                 Args, NumArgs, RParenLoc,
8540                                                 /*EmptyLookup=*/false);
8541     if (!Recovery.isInvalid())
8542       return Recovery;
8543
8544     Diag(Fn->getSourceRange().getBegin(),
8545          diag::err_ovl_no_viable_function_in_call)
8546       << ULE->getName() << Fn->getSourceRange();
8547     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8548     break;
8549   }
8550
8551   case OR_Ambiguous:
8552     Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
8553       << ULE->getName() << Fn->getSourceRange();
8554     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
8555     break;
8556
8557   case OR_Deleted:
8558     {
8559       Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8560         << Best->Function->isDeleted()
8561         << ULE->getName()
8562         << getDeletedOrUnavailableSuffix(Best->Function)
8563         << Fn->getSourceRange();
8564       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8565     }
8566     break;
8567   }
8568
8569   // Overload resolution failed.
8570   return ExprError();
8571 }
8572
8573 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
8574   return Functions.size() > 1 ||
8575     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8576 }
8577
8578 /// \brief Create a unary operation that may resolve to an overloaded
8579 /// operator.
8580 ///
8581 /// \param OpLoc The location of the operator itself (e.g., '*').
8582 ///
8583 /// \param OpcIn The UnaryOperator::Opcode that describes this
8584 /// operator.
8585 ///
8586 /// \param Functions The set of non-member functions that will be
8587 /// considered by overload resolution. The caller needs to build this
8588 /// set based on the context using, e.g.,
8589 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8590 /// set should not contain any member functions; those will be added
8591 /// by CreateOverloadedUnaryOp().
8592 ///
8593 /// \param input The input argument.
8594 ExprResult
8595 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8596                               const UnresolvedSetImpl &Fns,
8597                               Expr *Input) {
8598   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
8599
8600   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8601   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8602   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8603   // TODO: provide better source location info.
8604   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
8605
8606   if (Input->getObjectKind() == OK_ObjCProperty) {
8607     ExprResult Result = ConvertPropertyForRValue(Input);
8608     if (Result.isInvalid())
8609       return ExprError();
8610     Input = Result.take();
8611   }
8612
8613   Expr *Args[2] = { Input, 0 };
8614   unsigned NumArgs = 1;
8615
8616   // For post-increment and post-decrement, add the implicit '0' as
8617   // the second argument, so that we know this is a post-increment or
8618   // post-decrement.
8619   if (Opc == UO_PostInc || Opc == UO_PostDec) {
8620     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
8621     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8622                                      SourceLocation());
8623     NumArgs = 2;
8624   }
8625
8626   if (Input->isTypeDependent()) {
8627     if (Fns.empty())
8628       return Owned(new (Context) UnaryOperator(Input,
8629                                                Opc,
8630                                                Context.DependentTy,
8631                                                VK_RValue, OK_Ordinary,
8632                                                OpLoc));
8633
8634     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
8635     UnresolvedLookupExpr *Fn
8636       = UnresolvedLookupExpr::Create(Context, NamingClass,
8637                                      NestedNameSpecifierLoc(), OpNameInfo,
8638                                      /*ADL*/ true, IsOverloaded(Fns),
8639                                      Fns.begin(), Fns.end());
8640     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
8641                                                   &Args[0], NumArgs,
8642                                                    Context.DependentTy,
8643                                                    VK_RValue,
8644                                                    OpLoc));
8645   }
8646
8647   // Build an empty overload set.
8648   OverloadCandidateSet CandidateSet(OpLoc);
8649
8650   // Add the candidates from the given function set.
8651   AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
8652
8653   // Add operator candidates that are member functions.
8654   AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8655
8656   // Add candidates from ADL.
8657   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8658                                        Args, NumArgs,
8659                                        /*ExplicitTemplateArgs*/ 0,
8660                                        CandidateSet);
8661
8662   // Add builtin operator candidates.
8663   AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8664
8665   bool HadMultipleCandidates = (CandidateSet.size() > 1);
8666
8667   // Perform overload resolution.
8668   OverloadCandidateSet::iterator Best;
8669   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
8670   case OR_Success: {
8671     // We found a built-in operator or an overloaded operator.
8672     FunctionDecl *FnDecl = Best->Function;
8673
8674     if (FnDecl) {
8675       // We matched an overloaded operator. Build a call to that
8676       // operator.
8677
8678       MarkDeclarationReferenced(OpLoc, FnDecl);
8679
8680       // Convert the arguments.
8681       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
8682         CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
8683
8684         ExprResult InputRes =
8685           PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8686                                               Best->FoundDecl, Method);
8687         if (InputRes.isInvalid())
8688           return ExprError();
8689         Input = InputRes.take();
8690       } else {
8691         // Convert the arguments.
8692         ExprResult InputInit
8693           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
8694                                                       Context,
8695                                                       FnDecl->getParamDecl(0)),
8696                                       SourceLocation(),
8697                                       Input);
8698         if (InputInit.isInvalid())
8699           return ExprError();
8700         Input = InputInit.take();
8701       }
8702
8703       DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8704
8705       // Determine the result type.
8706       QualType ResultTy = FnDecl->getResultType();
8707       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8708       ResultTy = ResultTy.getNonLValueExprType(Context);
8709
8710       // Build the actual expression node.
8711       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
8712                                                 HadMultipleCandidates);
8713       if (FnExpr.isInvalid())
8714         return ExprError();
8715
8716       Args[0] = Input;
8717       CallExpr *TheCall =
8718         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
8719                                           Args, NumArgs, ResultTy, VK, OpLoc);
8720
8721       if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
8722                               FnDecl))
8723         return ExprError();
8724
8725       return MaybeBindToTemporary(TheCall);
8726     } else {
8727       // We matched a built-in operator. Convert the arguments, then
8728       // break out so that we will build the appropriate built-in
8729       // operator node.
8730       ExprResult InputRes =
8731         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8732                                   Best->Conversions[0], AA_Passing);
8733       if (InputRes.isInvalid())
8734         return ExprError();
8735       Input = InputRes.take();
8736       break;
8737     }
8738   }
8739
8740   case OR_No_Viable_Function:
8741     // This is an erroneous use of an operator which can be overloaded by
8742     // a non-member function. Check for non-member operators which were
8743     // defined too late to be candidates.
8744     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8745       // FIXME: Recover by calling the found function.
8746       return ExprError();
8747
8748     // No viable function; fall through to handling this as a
8749     // built-in operator, which will produce an error message for us.
8750     break;
8751
8752   case OR_Ambiguous:
8753     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
8754         << UnaryOperator::getOpcodeStr(Opc)
8755         << Input->getType()
8756         << Input->getSourceRange();
8757     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
8758                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8759     return ExprError();
8760
8761   case OR_Deleted:
8762     Diag(OpLoc, diag::err_ovl_deleted_oper)
8763       << Best->Function->isDeleted()
8764       << UnaryOperator::getOpcodeStr(Opc)
8765       << getDeletedOrUnavailableSuffix(Best->Function)
8766       << Input->getSourceRange();
8767     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8768                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8769     return ExprError();
8770   }
8771
8772   // Either we found no viable overloaded operator or we matched a
8773   // built-in operator. In either case, fall through to trying to
8774   // build a built-in operation.
8775   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8776 }
8777
8778 /// \brief Create a binary operation that may resolve to an overloaded
8779 /// operator.
8780 ///
8781 /// \param OpLoc The location of the operator itself (e.g., '+').
8782 ///
8783 /// \param OpcIn The BinaryOperator::Opcode that describes this
8784 /// operator.
8785 ///
8786 /// \param Functions The set of non-member functions that will be
8787 /// considered by overload resolution. The caller needs to build this
8788 /// set based on the context using, e.g.,
8789 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8790 /// set should not contain any member functions; those will be added
8791 /// by CreateOverloadedBinOp().
8792 ///
8793 /// \param LHS Left-hand argument.
8794 /// \param RHS Right-hand argument.
8795 ExprResult
8796 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
8797                             unsigned OpcIn,
8798                             const UnresolvedSetImpl &Fns,
8799                             Expr *LHS, Expr *RHS) {
8800   Expr *Args[2] = { LHS, RHS };
8801   LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
8802
8803   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8804   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8805   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8806
8807   // If either side is type-dependent, create an appropriate dependent
8808   // expression.
8809   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8810     if (Fns.empty()) {
8811       // If there are no functions to store, just build a dependent
8812       // BinaryOperator or CompoundAssignment.
8813       if (Opc <= BO_Assign || Opc > BO_OrAssign)
8814         return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
8815                                                   Context.DependentTy,
8816                                                   VK_RValue, OK_Ordinary,
8817                                                   OpLoc));
8818
8819       return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8820                                                         Context.DependentTy,
8821                                                         VK_LValue,
8822                                                         OK_Ordinary,
8823                                                         Context.DependentTy,
8824                                                         Context.DependentTy,
8825                                                         OpLoc));
8826     }
8827
8828     // FIXME: save results of ADL from here?
8829     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
8830     // TODO: provide better source location info in DNLoc component.
8831     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
8832     UnresolvedLookupExpr *Fn
8833       = UnresolvedLookupExpr::Create(Context, NamingClass, 
8834                                      NestedNameSpecifierLoc(), OpNameInfo, 
8835                                      /*ADL*/ true, IsOverloaded(Fns),
8836                                      Fns.begin(), Fns.end());
8837     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
8838                                                    Args, 2,
8839                                                    Context.DependentTy,
8840                                                    VK_RValue,
8841                                                    OpLoc));
8842   }
8843
8844   // Always do property rvalue conversions on the RHS.
8845   if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8846     ExprResult Result = ConvertPropertyForRValue(Args[1]);
8847     if (Result.isInvalid())
8848       return ExprError();
8849     Args[1] = Result.take();
8850   }
8851
8852   // The LHS is more complicated.
8853   if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8854
8855     // There's a tension for assignment operators between primitive
8856     // property assignment and the overloaded operators.
8857     if (BinaryOperator::isAssignmentOp(Opc)) {
8858       const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8859
8860       // Is the property "logically" settable?
8861       bool Settable = (PRE->isExplicitProperty() ||
8862                        PRE->getImplicitPropertySetter());
8863
8864       // To avoid gratuitously inventing semantics, use the primitive
8865       // unless it isn't.  Thoughts in case we ever really care:
8866       // - If the property isn't logically settable, we have to
8867       //   load and hope.
8868       // - If the property is settable and this is simple assignment,
8869       //   we really should use the primitive.
8870       // - If the property is settable, then we could try overloading
8871       //   on a generic lvalue of the appropriate type;  if it works
8872       //   out to a builtin candidate, we would do that same operation
8873       //   on the property, and otherwise just error.
8874       if (Settable)
8875         return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8876     }
8877
8878     ExprResult Result = ConvertPropertyForRValue(Args[0]);
8879     if (Result.isInvalid())
8880       return ExprError();
8881     Args[0] = Result.take();
8882   }
8883
8884   // If this is the assignment operator, we only perform overload resolution
8885   // if the left-hand side is a class or enumeration type. This is actually
8886   // a hack. The standard requires that we do overload resolution between the
8887   // various built-in candidates, but as DR507 points out, this can lead to
8888   // problems. So we do it this way, which pretty much follows what GCC does.
8889   // Note that we go the traditional code path for compound assignment forms.
8890   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
8891     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8892
8893   // If this is the .* operator, which is not overloadable, just
8894   // create a built-in binary operator.
8895   if (Opc == BO_PtrMemD)
8896     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8897
8898   // Build an empty overload set.
8899   OverloadCandidateSet CandidateSet(OpLoc);
8900
8901   // Add the candidates from the given function set.
8902   AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
8903
8904   // Add operator candidates that are member functions.
8905   AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8906
8907   // Add candidates from ADL.
8908   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8909                                        Args, 2,
8910                                        /*ExplicitTemplateArgs*/ 0,
8911                                        CandidateSet);
8912
8913   // Add builtin operator candidates.
8914   AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8915
8916   bool HadMultipleCandidates = (CandidateSet.size() > 1);
8917
8918   // Perform overload resolution.
8919   OverloadCandidateSet::iterator Best;
8920   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
8921     case OR_Success: {
8922       // We found a built-in operator or an overloaded operator.
8923       FunctionDecl *FnDecl = Best->Function;
8924
8925       if (FnDecl) {
8926         // We matched an overloaded operator. Build a call to that
8927         // operator.
8928
8929         MarkDeclarationReferenced(OpLoc, FnDecl);
8930
8931         // Convert the arguments.
8932         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
8933           // Best->Access is only meaningful for class members.
8934           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
8935
8936           ExprResult Arg1 =
8937             PerformCopyInitialization(
8938               InitializedEntity::InitializeParameter(Context,
8939                                                      FnDecl->getParamDecl(0)),
8940               SourceLocation(), Owned(Args[1]));
8941           if (Arg1.isInvalid())
8942             return ExprError();
8943
8944           ExprResult Arg0 =
8945             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8946                                                 Best->FoundDecl, Method);
8947           if (Arg0.isInvalid())
8948             return ExprError();
8949           Args[0] = Arg0.takeAs<Expr>();
8950           Args[1] = RHS = Arg1.takeAs<Expr>();
8951         } else {
8952           // Convert the arguments.
8953           ExprResult Arg0 = PerformCopyInitialization(
8954             InitializedEntity::InitializeParameter(Context,
8955                                                    FnDecl->getParamDecl(0)),
8956             SourceLocation(), Owned(Args[0]));
8957           if (Arg0.isInvalid())
8958             return ExprError();
8959
8960           ExprResult Arg1 =
8961             PerformCopyInitialization(
8962               InitializedEntity::InitializeParameter(Context,
8963                                                      FnDecl->getParamDecl(1)),
8964               SourceLocation(), Owned(Args[1]));
8965           if (Arg1.isInvalid())
8966             return ExprError();
8967           Args[0] = LHS = Arg0.takeAs<Expr>();
8968           Args[1] = RHS = Arg1.takeAs<Expr>();
8969         }
8970
8971         DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8972
8973         // Determine the result type.
8974         QualType ResultTy = FnDecl->getResultType();
8975         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8976         ResultTy = ResultTy.getNonLValueExprType(Context);
8977
8978         // Build the actual expression node.
8979         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
8980                                                   HadMultipleCandidates, OpLoc);
8981         if (FnExpr.isInvalid())
8982           return ExprError();
8983
8984         CXXOperatorCallExpr *TheCall =
8985           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
8986                                             Args, 2, ResultTy, VK, OpLoc);
8987
8988         if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
8989                                 FnDecl))
8990           return ExprError();
8991
8992         return MaybeBindToTemporary(TheCall);
8993       } else {
8994         // We matched a built-in operator. Convert the arguments, then
8995         // break out so that we will build the appropriate built-in
8996         // operator node.
8997         ExprResult ArgsRes0 =
8998           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8999                                     Best->Conversions[0], AA_Passing);
9000         if (ArgsRes0.isInvalid())
9001           return ExprError();
9002         Args[0] = ArgsRes0.take();
9003
9004         ExprResult ArgsRes1 =
9005           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9006                                     Best->Conversions[1], AA_Passing);
9007         if (ArgsRes1.isInvalid())
9008           return ExprError();
9009         Args[1] = ArgsRes1.take();
9010         break;
9011       }
9012     }
9013
9014     case OR_No_Viable_Function: {
9015       // C++ [over.match.oper]p9:
9016       //   If the operator is the operator , [...] and there are no
9017       //   viable functions, then the operator is assumed to be the
9018       //   built-in operator and interpreted according to clause 5.
9019       if (Opc == BO_Comma)
9020         break;
9021
9022       // For class as left operand for assignment or compound assigment
9023       // operator do not fall through to handling in built-in, but report that
9024       // no overloaded assignment operator found
9025       ExprResult Result = ExprError();
9026       if (Args[0]->getType()->isRecordType() &&
9027           Opc >= BO_Assign && Opc <= BO_OrAssign) {
9028         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
9029              << BinaryOperator::getOpcodeStr(Opc)
9030              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9031       } else {
9032         // This is an erroneous use of an operator which can be overloaded by
9033         // a non-member function. Check for non-member operators which were
9034         // defined too late to be candidates.
9035         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9036           // FIXME: Recover by calling the found function.
9037           return ExprError();
9038
9039         // No viable function; try to create a built-in operation, which will
9040         // produce an error. Then, show the non-viable candidates.
9041         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9042       }
9043       assert(Result.isInvalid() &&
9044              "C++ binary operator overloading is missing candidates!");
9045       if (Result.isInvalid())
9046         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9047                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
9048       return move(Result);
9049     }
9050
9051     case OR_Ambiguous:
9052       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
9053           << BinaryOperator::getOpcodeStr(Opc)
9054           << Args[0]->getType() << Args[1]->getType()
9055           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9056       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9057                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
9058       return ExprError();
9059
9060     case OR_Deleted:
9061       Diag(OpLoc, diag::err_ovl_deleted_oper)
9062         << Best->Function->isDeleted()
9063         << BinaryOperator::getOpcodeStr(Opc)
9064         << getDeletedOrUnavailableSuffix(Best->Function)
9065         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9066       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9067                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
9068       return ExprError();
9069   }
9070
9071   // We matched a built-in operator; build it.
9072   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9073 }
9074
9075 ExprResult
9076 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9077                                          SourceLocation RLoc,
9078                                          Expr *Base, Expr *Idx) {
9079   Expr *Args[2] = { Base, Idx };
9080   DeclarationName OpName =
9081       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9082
9083   // If either side is type-dependent, create an appropriate dependent
9084   // expression.
9085   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9086
9087     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9088     // CHECKME: no 'operator' keyword?
9089     DeclarationNameInfo OpNameInfo(OpName, LLoc);
9090     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
9091     UnresolvedLookupExpr *Fn
9092       = UnresolvedLookupExpr::Create(Context, NamingClass,
9093                                      NestedNameSpecifierLoc(), OpNameInfo,
9094                                      /*ADL*/ true, /*Overloaded*/ false,
9095                                      UnresolvedSetIterator(),
9096                                      UnresolvedSetIterator());
9097     // Can't add any actual overloads yet
9098
9099     return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9100                                                    Args, 2,
9101                                                    Context.DependentTy,
9102                                                    VK_RValue,
9103                                                    RLoc));
9104   }
9105
9106   if (Args[0]->getObjectKind() == OK_ObjCProperty) {
9107     ExprResult Result = ConvertPropertyForRValue(Args[0]);
9108     if (Result.isInvalid())
9109       return ExprError();
9110     Args[0] = Result.take();
9111   }
9112   if (Args[1]->getObjectKind() == OK_ObjCProperty) {
9113     ExprResult Result = ConvertPropertyForRValue(Args[1]);
9114     if (Result.isInvalid())
9115       return ExprError();
9116     Args[1] = Result.take();
9117   }
9118
9119   // Build an empty overload set.
9120   OverloadCandidateSet CandidateSet(LLoc);
9121
9122   // Subscript can only be overloaded as a member function.
9123
9124   // Add operator candidates that are member functions.
9125   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9126
9127   // Add builtin operator candidates.
9128   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9129
9130   bool HadMultipleCandidates = (CandidateSet.size() > 1);
9131
9132   // Perform overload resolution.
9133   OverloadCandidateSet::iterator Best;
9134   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
9135     case OR_Success: {
9136       // We found a built-in operator or an overloaded operator.
9137       FunctionDecl *FnDecl = Best->Function;
9138
9139       if (FnDecl) {
9140         // We matched an overloaded operator. Build a call to that
9141         // operator.
9142
9143         MarkDeclarationReferenced(LLoc, FnDecl);
9144
9145         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
9146         DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
9147
9148         // Convert the arguments.
9149         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
9150         ExprResult Arg0 =
9151           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9152                                               Best->FoundDecl, Method);
9153         if (Arg0.isInvalid())
9154           return ExprError();
9155         Args[0] = Arg0.take();
9156
9157         // Convert the arguments.
9158         ExprResult InputInit
9159           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
9160                                                       Context,
9161                                                       FnDecl->getParamDecl(0)),
9162                                       SourceLocation(),
9163                                       Owned(Args[1]));
9164         if (InputInit.isInvalid())
9165           return ExprError();
9166
9167         Args[1] = InputInit.takeAs<Expr>();
9168
9169         // Determine the result type
9170         QualType ResultTy = FnDecl->getResultType();
9171         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9172         ResultTy = ResultTy.getNonLValueExprType(Context);
9173
9174         // Build the actual expression node.
9175         DeclarationNameLoc LocInfo;
9176         LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9177         LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
9178         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9179                                                   HadMultipleCandidates,
9180                                                   LLoc, LocInfo);
9181         if (FnExpr.isInvalid())
9182           return ExprError();
9183
9184         CXXOperatorCallExpr *TheCall =
9185           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
9186                                             FnExpr.take(), Args, 2,
9187                                             ResultTy, VK, RLoc);
9188
9189         if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
9190                                 FnDecl))
9191           return ExprError();
9192
9193         return MaybeBindToTemporary(TheCall);
9194       } else {
9195         // We matched a built-in operator. Convert the arguments, then
9196         // break out so that we will build the appropriate built-in
9197         // operator node.
9198         ExprResult ArgsRes0 =
9199           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9200                                     Best->Conversions[0], AA_Passing);
9201         if (ArgsRes0.isInvalid())
9202           return ExprError();
9203         Args[0] = ArgsRes0.take();
9204
9205         ExprResult ArgsRes1 =
9206           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9207                                     Best->Conversions[1], AA_Passing);
9208         if (ArgsRes1.isInvalid())
9209           return ExprError();
9210         Args[1] = ArgsRes1.take();
9211
9212         break;
9213       }
9214     }
9215
9216     case OR_No_Viable_Function: {
9217       if (CandidateSet.empty())
9218         Diag(LLoc, diag::err_ovl_no_oper)
9219           << Args[0]->getType() << /*subscript*/ 0
9220           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9221       else
9222         Diag(LLoc, diag::err_ovl_no_viable_subscript)
9223           << Args[0]->getType()
9224           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9225       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9226                                   "[]", LLoc);
9227       return ExprError();
9228     }
9229
9230     case OR_Ambiguous:
9231       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
9232           << "[]"
9233           << Args[0]->getType() << Args[1]->getType()
9234           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9235       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9236                                   "[]", LLoc);
9237       return ExprError();
9238
9239     case OR_Deleted:
9240       Diag(LLoc, diag::err_ovl_deleted_oper)
9241         << Best->Function->isDeleted() << "[]"
9242         << getDeletedOrUnavailableSuffix(Best->Function)
9243         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9244       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9245                                   "[]", LLoc);
9246       return ExprError();
9247     }
9248
9249   // We matched a built-in operator; build it.
9250   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
9251 }
9252
9253 /// BuildCallToMemberFunction - Build a call to a member
9254 /// function. MemExpr is the expression that refers to the member
9255 /// function (and includes the object parameter), Args/NumArgs are the
9256 /// arguments to the function call (not including the object
9257 /// parameter). The caller needs to validate that the member
9258 /// expression refers to a non-static member function or an overloaded
9259 /// member function.
9260 ExprResult
9261 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9262                                 SourceLocation LParenLoc, Expr **Args,
9263                                 unsigned NumArgs, SourceLocation RParenLoc) {
9264   assert(MemExprE->getType() == Context.BoundMemberTy ||
9265          MemExprE->getType() == Context.OverloadTy);
9266
9267   // Dig out the member expression. This holds both the object
9268   // argument and the member function we're referring to.
9269   Expr *NakedMemExpr = MemExprE->IgnoreParens();
9270
9271   // Determine whether this is a call to a pointer-to-member function.
9272   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9273     assert(op->getType() == Context.BoundMemberTy);
9274     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9275
9276     QualType fnType =
9277       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9278
9279     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9280     QualType resultType = proto->getCallResultType(Context);
9281     ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9282
9283     // Check that the object type isn't more qualified than the
9284     // member function we're calling.
9285     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9286
9287     QualType objectType = op->getLHS()->getType();
9288     if (op->getOpcode() == BO_PtrMemI)
9289       objectType = objectType->castAs<PointerType>()->getPointeeType();
9290     Qualifiers objectQuals = objectType.getQualifiers();
9291
9292     Qualifiers difference = objectQuals - funcQuals;
9293     difference.removeObjCGCAttr();
9294     difference.removeAddressSpace();
9295     if (difference) {
9296       std::string qualsString = difference.getAsString();
9297       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9298         << fnType.getUnqualifiedType()
9299         << qualsString
9300         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9301     }
9302               
9303     CXXMemberCallExpr *call
9304       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9305                                         resultType, valueKind, RParenLoc);
9306
9307     if (CheckCallReturnType(proto->getResultType(),
9308                             op->getRHS()->getSourceRange().getBegin(),
9309                             call, 0))
9310       return ExprError();
9311
9312     if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9313       return ExprError();
9314
9315     return MaybeBindToTemporary(call);
9316   }
9317
9318   MemberExpr *MemExpr;
9319   CXXMethodDecl *Method = 0;
9320   DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
9321   NestedNameSpecifier *Qualifier = 0;
9322   if (isa<MemberExpr>(NakedMemExpr)) {
9323     MemExpr = cast<MemberExpr>(NakedMemExpr);
9324     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
9325     FoundDecl = MemExpr->getFoundDecl();
9326     Qualifier = MemExpr->getQualifier();
9327   } else {
9328     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
9329     Qualifier = UnresExpr->getQualifier();
9330
9331     QualType ObjectType = UnresExpr->getBaseType();
9332     Expr::Classification ObjectClassification
9333       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9334                             : UnresExpr->getBase()->Classify(Context);
9335
9336     // Add overload candidates
9337     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
9338
9339     // FIXME: avoid copy.
9340     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9341     if (UnresExpr->hasExplicitTemplateArgs()) {
9342       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9343       TemplateArgs = &TemplateArgsBuffer;
9344     }
9345
9346     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9347            E = UnresExpr->decls_end(); I != E; ++I) {
9348
9349       NamedDecl *Func = *I;
9350       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9351       if (isa<UsingShadowDecl>(Func))
9352         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9353
9354
9355       // Microsoft supports direct constructor calls.
9356       if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
9357         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9358                              CandidateSet);
9359       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
9360         // If explicit template arguments were provided, we can't call a
9361         // non-template member function.
9362         if (TemplateArgs)
9363           continue;
9364
9365         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
9366                            ObjectClassification,
9367                            Args, NumArgs, CandidateSet,
9368                            /*SuppressUserConversions=*/false);
9369       } else {
9370         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
9371                                    I.getPair(), ActingDC, TemplateArgs,
9372                                    ObjectType,  ObjectClassification,
9373                                    Args, NumArgs, CandidateSet,
9374                                    /*SuppressUsedConversions=*/false);
9375       }
9376     }
9377
9378     DeclarationName DeclName = UnresExpr->getMemberName();
9379
9380     OverloadCandidateSet::iterator Best;
9381     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
9382                                             Best)) {
9383     case OR_Success:
9384       Method = cast<CXXMethodDecl>(Best->Function);
9385       MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
9386       FoundDecl = Best->FoundDecl;
9387       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
9388       DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
9389       break;
9390
9391     case OR_No_Viable_Function:
9392       Diag(UnresExpr->getMemberLoc(),
9393            diag::err_ovl_no_viable_member_function_in_call)
9394         << DeclName << MemExprE->getSourceRange();
9395       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9396       // FIXME: Leaking incoming expressions!
9397       return ExprError();
9398
9399     case OR_Ambiguous:
9400       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
9401         << DeclName << MemExprE->getSourceRange();
9402       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9403       // FIXME: Leaking incoming expressions!
9404       return ExprError();
9405
9406     case OR_Deleted:
9407       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
9408         << Best->Function->isDeleted()
9409         << DeclName 
9410         << getDeletedOrUnavailableSuffix(Best->Function)
9411         << MemExprE->getSourceRange();
9412       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9413       // FIXME: Leaking incoming expressions!
9414       return ExprError();
9415     }
9416
9417     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
9418
9419     // If overload resolution picked a static member, build a
9420     // non-member call based on that function.
9421     if (Method->isStatic()) {
9422       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9423                                    Args, NumArgs, RParenLoc);
9424     }
9425
9426     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
9427   }
9428
9429   QualType ResultType = Method->getResultType();
9430   ExprValueKind VK = Expr::getValueKindForType(ResultType);
9431   ResultType = ResultType.getNonLValueExprType(Context);
9432
9433   assert(Method && "Member call to something that isn't a method?");
9434   CXXMemberCallExpr *TheCall =
9435     new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9436                                     ResultType, VK, RParenLoc);
9437
9438   // Check for a valid return type.
9439   if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
9440                           TheCall, Method))
9441     return ExprError();
9442
9443   // Convert the object argument (for a non-static member function call).
9444   // We only need to do this if there was actually an overload; otherwise
9445   // it was done at lookup.
9446   if (!Method->isStatic()) {
9447     ExprResult ObjectArg =
9448       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9449                                           FoundDecl, Method);
9450     if (ObjectArg.isInvalid())
9451       return ExprError();
9452     MemExpr->setBase(ObjectArg.take());
9453   }
9454
9455   // Convert the rest of the arguments
9456   const FunctionProtoType *Proto =
9457     Method->getType()->getAs<FunctionProtoType>();
9458   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
9459                               RParenLoc))
9460     return ExprError();
9461
9462   if (CheckFunctionCall(Method, TheCall))
9463     return ExprError();
9464
9465   if ((isa<CXXConstructorDecl>(CurContext) || 
9466        isa<CXXDestructorDecl>(CurContext)) && 
9467       TheCall->getMethodDecl()->isPure()) {
9468     const CXXMethodDecl *MD = TheCall->getMethodDecl();
9469
9470     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
9471       Diag(MemExpr->getLocStart(), 
9472            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9473         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9474         << MD->getParent()->getDeclName();
9475
9476       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
9477     }
9478   }
9479   return MaybeBindToTemporary(TheCall);
9480 }
9481
9482 /// BuildCallToObjectOfClassType - Build a call to an object of class
9483 /// type (C++ [over.call.object]), which can end up invoking an
9484 /// overloaded function call operator (@c operator()) or performing a
9485 /// user-defined conversion on the object argument.
9486 ExprResult
9487 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
9488                                    SourceLocation LParenLoc,
9489                                    Expr **Args, unsigned NumArgs,
9490                                    SourceLocation RParenLoc) {
9491   ExprResult Object = Owned(Obj);
9492   if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9493     Object = ConvertPropertyForRValue(Object.take());
9494     if (Object.isInvalid())
9495       return ExprError();
9496   }
9497
9498   assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9499   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
9500
9501   // C++ [over.call.object]p1:
9502   //  If the primary-expression E in the function call syntax
9503   //  evaluates to a class object of type "cv T", then the set of
9504   //  candidate functions includes at least the function call
9505   //  operators of T. The function call operators of T are obtained by
9506   //  ordinary lookup of the name operator() in the context of
9507   //  (E).operator().
9508   OverloadCandidateSet CandidateSet(LParenLoc);
9509   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
9510
9511   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
9512                           PDiag(diag::err_incomplete_object_call)
9513                           << Object.get()->getSourceRange()))
9514     return true;
9515
9516   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9517   LookupQualifiedName(R, Record->getDecl());
9518   R.suppressDiagnostics();
9519
9520   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
9521        Oper != OperEnd; ++Oper) {
9522     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9523                        Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
9524                        /*SuppressUserConversions=*/ false);
9525   }
9526
9527   // C++ [over.call.object]p2:
9528   //   In addition, for each (non-explicit in C++0x) conversion function 
9529   //   declared in T of the form
9530   //
9531   //        operator conversion-type-id () cv-qualifier;
9532   //
9533   //   where cv-qualifier is the same cv-qualification as, or a
9534   //   greater cv-qualification than, cv, and where conversion-type-id
9535   //   denotes the type "pointer to function of (P1,...,Pn) returning
9536   //   R", or the type "reference to pointer to function of
9537   //   (P1,...,Pn) returning R", or the type "reference to function
9538   //   of (P1,...,Pn) returning R", a surrogate call function [...]
9539   //   is also considered as a candidate function. Similarly,
9540   //   surrogate call functions are added to the set of candidate
9541   //   functions for each conversion function declared in an
9542   //   accessible base class provided the function is not hidden
9543   //   within T by another intervening declaration.
9544   const UnresolvedSetImpl *Conversions
9545     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
9546   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
9547          E = Conversions->end(); I != E; ++I) {
9548     NamedDecl *D = *I;
9549     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9550     if (isa<UsingShadowDecl>(D))
9551       D = cast<UsingShadowDecl>(D)->getTargetDecl();
9552
9553     // Skip over templated conversion functions; they aren't
9554     // surrogates.
9555     if (isa<FunctionTemplateDecl>(D))
9556       continue;
9557
9558     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9559     if (!Conv->isExplicit()) {
9560       // Strip the reference type (if any) and then the pointer type (if
9561       // any) to get down to what might be a function type.
9562       QualType ConvType = Conv->getConversionType().getNonReferenceType();
9563       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9564         ConvType = ConvPtrType->getPointeeType();
9565
9566       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9567       {
9568         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9569                               Object.get(), Args, NumArgs, CandidateSet);
9570       }
9571     }
9572   }
9573
9574   bool HadMultipleCandidates = (CandidateSet.size() > 1);
9575
9576   // Perform overload resolution.
9577   OverloadCandidateSet::iterator Best;
9578   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
9579                              Best)) {
9580   case OR_Success:
9581     // Overload resolution succeeded; we'll build the appropriate call
9582     // below.
9583     break;
9584
9585   case OR_No_Viable_Function:
9586     if (CandidateSet.empty())
9587       Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9588         << Object.get()->getType() << /*call*/ 1
9589         << Object.get()->getSourceRange();
9590     else
9591       Diag(Object.get()->getSourceRange().getBegin(),
9592            diag::err_ovl_no_viable_object_call)
9593         << Object.get()->getType() << Object.get()->getSourceRange();
9594     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9595     break;
9596
9597   case OR_Ambiguous:
9598     Diag(Object.get()->getSourceRange().getBegin(),
9599          diag::err_ovl_ambiguous_object_call)
9600       << Object.get()->getType() << Object.get()->getSourceRange();
9601     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
9602     break;
9603
9604   case OR_Deleted:
9605     Diag(Object.get()->getSourceRange().getBegin(),
9606          diag::err_ovl_deleted_object_call)
9607       << Best->Function->isDeleted()
9608       << Object.get()->getType() 
9609       << getDeletedOrUnavailableSuffix(Best->Function)
9610       << Object.get()->getSourceRange();
9611     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9612     break;
9613   }
9614
9615   if (Best == CandidateSet.end())
9616     return true;
9617
9618   if (Best->Function == 0) {
9619     // Since there is no function declaration, this is one of the
9620     // surrogate candidates. Dig out the conversion function.
9621     CXXConversionDecl *Conv
9622       = cast<CXXConversionDecl>(
9623                          Best->Conversions[0].UserDefined.ConversionFunction);
9624
9625     CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
9626     DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
9627
9628     // We selected one of the surrogate functions that converts the
9629     // object parameter to a function pointer. Perform the conversion
9630     // on the object argument, then let ActOnCallExpr finish the job.
9631
9632     // Create an implicit member expr to refer to the conversion operator.
9633     // and then call it.
9634     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
9635                                              Conv, HadMultipleCandidates);
9636     if (Call.isInvalid())
9637       return ExprError();
9638
9639     return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
9640                          RParenLoc);
9641   }
9642
9643   MarkDeclarationReferenced(LParenLoc, Best->Function);
9644   CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
9645   DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
9646
9647   // We found an overloaded operator(). Build a CXXOperatorCallExpr
9648   // that calls this method, using Object for the implicit object
9649   // parameter and passing along the remaining arguments.
9650   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
9651   const FunctionProtoType *Proto =
9652     Method->getType()->getAs<FunctionProtoType>();
9653
9654   unsigned NumArgsInProto = Proto->getNumArgs();
9655   unsigned NumArgsToCheck = NumArgs;
9656
9657   // Build the full argument list for the method call (the
9658   // implicit object parameter is placed at the beginning of the
9659   // list).
9660   Expr **MethodArgs;
9661   if (NumArgs < NumArgsInProto) {
9662     NumArgsToCheck = NumArgsInProto;
9663     MethodArgs = new Expr*[NumArgsInProto + 1];
9664   } else {
9665     MethodArgs = new Expr*[NumArgs + 1];
9666   }
9667   MethodArgs[0] = Object.get();
9668   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9669     MethodArgs[ArgIdx + 1] = Args[ArgIdx];
9670
9671   ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
9672                                            HadMultipleCandidates);
9673   if (NewFn.isInvalid())
9674     return true;
9675
9676   // Once we've built TheCall, all of the expressions are properly
9677   // owned.
9678   QualType ResultTy = Method->getResultType();
9679   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9680   ResultTy = ResultTy.getNonLValueExprType(Context);
9681
9682   CXXOperatorCallExpr *TheCall =
9683     new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
9684                                       MethodArgs, NumArgs + 1,
9685                                       ResultTy, VK, RParenLoc);
9686   delete [] MethodArgs;
9687
9688   if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
9689                           Method))
9690     return true;
9691
9692   // We may have default arguments. If so, we need to allocate more
9693   // slots in the call for them.
9694   if (NumArgs < NumArgsInProto)
9695     TheCall->setNumArgs(Context, NumArgsInProto + 1);
9696   else if (NumArgs > NumArgsInProto)
9697     NumArgsToCheck = NumArgsInProto;
9698
9699   bool IsError = false;
9700
9701   // Initialize the implicit object parameter.
9702   ExprResult ObjRes =
9703     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9704                                         Best->FoundDecl, Method);
9705   if (ObjRes.isInvalid())
9706     IsError = true;
9707   else
9708     Object = move(ObjRes);
9709   TheCall->setArg(0, Object.take());
9710
9711   // Check the argument types.
9712   for (unsigned i = 0; i != NumArgsToCheck; i++) {
9713     Expr *Arg;
9714     if (i < NumArgs) {
9715       Arg = Args[i];
9716
9717       // Pass the argument.
9718
9719       ExprResult InputInit
9720         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
9721                                                     Context,
9722                                                     Method->getParamDecl(i)),
9723                                     SourceLocation(), Arg);
9724
9725       IsError |= InputInit.isInvalid();
9726       Arg = InputInit.takeAs<Expr>();
9727     } else {
9728       ExprResult DefArg
9729         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9730       if (DefArg.isInvalid()) {
9731         IsError = true;
9732         break;
9733       }
9734
9735       Arg = DefArg.takeAs<Expr>();
9736     }
9737
9738     TheCall->setArg(i + 1, Arg);
9739   }
9740
9741   // If this is a variadic call, handle args passed through "...".
9742   if (Proto->isVariadic()) {
9743     // Promote the arguments (C99 6.5.2.2p7).
9744     for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
9745       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9746       IsError |= Arg.isInvalid();
9747       TheCall->setArg(i + 1, Arg.take());
9748     }
9749   }
9750
9751   if (IsError) return true;
9752
9753   if (CheckFunctionCall(Method, TheCall))
9754     return true;
9755
9756   return MaybeBindToTemporary(TheCall);
9757 }
9758
9759 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
9760 ///  (if one exists), where @c Base is an expression of class type and
9761 /// @c Member is the name of the member we're trying to find.
9762 ExprResult
9763 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
9764   assert(Base->getType()->isRecordType() &&
9765          "left-hand side must have class type");
9766
9767   if (Base->getObjectKind() == OK_ObjCProperty) {
9768     ExprResult Result = ConvertPropertyForRValue(Base);
9769     if (Result.isInvalid())
9770       return ExprError();
9771     Base = Result.take();
9772   }
9773
9774   SourceLocation Loc = Base->getExprLoc();
9775
9776   // C++ [over.ref]p1:
9777   //
9778   //   [...] An expression x->m is interpreted as (x.operator->())->m
9779   //   for a class object x of type T if T::operator->() exists and if
9780   //   the operator is selected as the best match function by the
9781   //   overload resolution mechanism (13.3).
9782   DeclarationName OpName =
9783     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
9784   OverloadCandidateSet CandidateSet(Loc);
9785   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
9786
9787   if (RequireCompleteType(Loc, Base->getType(),
9788                           PDiag(diag::err_typecheck_incomplete_tag)
9789                             << Base->getSourceRange()))
9790     return ExprError();
9791
9792   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9793   LookupQualifiedName(R, BaseRecord->getDecl());
9794   R.suppressDiagnostics();
9795
9796   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
9797        Oper != OperEnd; ++Oper) {
9798     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9799                        0, 0, CandidateSet, /*SuppressUserConversions=*/false);
9800   }
9801
9802   bool HadMultipleCandidates = (CandidateSet.size() > 1);
9803
9804   // Perform overload resolution.
9805   OverloadCandidateSet::iterator Best;
9806   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
9807   case OR_Success:
9808     // Overload resolution succeeded; we'll build the call below.
9809     break;
9810
9811   case OR_No_Viable_Function:
9812     if (CandidateSet.empty())
9813       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
9814         << Base->getType() << Base->getSourceRange();
9815     else
9816       Diag(OpLoc, diag::err_ovl_no_viable_oper)
9817         << "operator->" << Base->getSourceRange();
9818     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
9819     return ExprError();
9820
9821   case OR_Ambiguous:
9822     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
9823       << "->" << Base->getType() << Base->getSourceRange();
9824     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
9825     return ExprError();
9826
9827   case OR_Deleted:
9828     Diag(OpLoc,  diag::err_ovl_deleted_oper)
9829       << Best->Function->isDeleted()
9830       << "->" 
9831       << getDeletedOrUnavailableSuffix(Best->Function)
9832       << Base->getSourceRange();
9833     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
9834     return ExprError();
9835   }
9836
9837   MarkDeclarationReferenced(OpLoc, Best->Function);
9838   CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
9839   DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9840
9841   // Convert the object parameter.
9842   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
9843   ExprResult BaseResult =
9844     PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9845                                         Best->FoundDecl, Method);
9846   if (BaseResult.isInvalid())
9847     return ExprError();
9848   Base = BaseResult.take();
9849
9850   // Build the operator call.
9851   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
9852                                             HadMultipleCandidates);
9853   if (FnExpr.isInvalid())
9854     return ExprError();
9855
9856   QualType ResultTy = Method->getResultType();
9857   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9858   ResultTy = ResultTy.getNonLValueExprType(Context);
9859   CXXOperatorCallExpr *TheCall =
9860     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
9861                                       &Base, 1, ResultTy, VK, OpLoc);
9862
9863   if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
9864                           Method))
9865           return ExprError();
9866
9867   return MaybeBindToTemporary(TheCall);
9868 }
9869
9870 /// FixOverloadedFunctionReference - E is an expression that refers to
9871 /// a C++ overloaded function (possibly with some parentheses and
9872 /// perhaps a '&' around it). We have resolved the overloaded function
9873 /// to the function declaration Fn, so patch up the expression E to
9874 /// refer (possibly indirectly) to Fn. Returns the new expr.
9875 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
9876                                            FunctionDecl *Fn) {
9877   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
9878     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9879                                                    Found, Fn);
9880     if (SubExpr == PE->getSubExpr())
9881       return PE;
9882
9883     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
9884   }
9885
9886   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9887     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9888                                                    Found, Fn);
9889     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
9890                                SubExpr->getType()) &&
9891            "Implicit cast type cannot be determined from overload");
9892     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
9893     if (SubExpr == ICE->getSubExpr())
9894       return ICE;
9895
9896     return ImplicitCastExpr::Create(Context, ICE->getType(),
9897                                     ICE->getCastKind(),
9898                                     SubExpr, 0,
9899                                     ICE->getValueKind());
9900   }
9901
9902   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
9903     assert(UnOp->getOpcode() == UO_AddrOf &&
9904            "Can only take the address of an overloaded function");
9905     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9906       if (Method->isStatic()) {
9907         // Do nothing: static member functions aren't any different
9908         // from non-member functions.
9909       } else {
9910         // Fix the sub expression, which really has to be an
9911         // UnresolvedLookupExpr holding an overloaded member function
9912         // or template.
9913         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9914                                                        Found, Fn);
9915         if (SubExpr == UnOp->getSubExpr())
9916           return UnOp;
9917
9918         assert(isa<DeclRefExpr>(SubExpr)
9919                && "fixed to something other than a decl ref");
9920         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9921                && "fixed to a member ref with no nested name qualifier");
9922
9923         // We have taken the address of a pointer to member
9924         // function. Perform the computation here so that we get the
9925         // appropriate pointer to member type.
9926         QualType ClassType
9927           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9928         QualType MemPtrType
9929           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9930
9931         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9932                                            VK_RValue, OK_Ordinary,
9933                                            UnOp->getOperatorLoc());
9934       }
9935     }
9936     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9937                                                    Found, Fn);
9938     if (SubExpr == UnOp->getSubExpr())
9939       return UnOp;
9940
9941     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
9942                                      Context.getPointerType(SubExpr->getType()),
9943                                        VK_RValue, OK_Ordinary,
9944                                        UnOp->getOperatorLoc());
9945   }
9946
9947   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9948     // FIXME: avoid copy.
9949     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9950     if (ULE->hasExplicitTemplateArgs()) {
9951       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9952       TemplateArgs = &TemplateArgsBuffer;
9953     }
9954
9955     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
9956                                            ULE->getQualifierLoc(),
9957                                            Fn,
9958                                            ULE->getNameLoc(),
9959                                            Fn->getType(),
9960                                            VK_LValue,
9961                                            Found.getDecl(),
9962                                            TemplateArgs);
9963     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
9964     return DRE;
9965   }
9966
9967   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
9968     // FIXME: avoid copy.
9969     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9970     if (MemExpr->hasExplicitTemplateArgs()) {
9971       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9972       TemplateArgs = &TemplateArgsBuffer;
9973     }
9974
9975     Expr *Base;
9976
9977     // If we're filling in a static method where we used to have an
9978     // implicit member access, rewrite to a simple decl ref.
9979     if (MemExpr->isImplicitAccess()) {
9980       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9981         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
9982                                                MemExpr->getQualifierLoc(),
9983                                                Fn,
9984                                                MemExpr->getMemberLoc(),
9985                                                Fn->getType(),
9986                                                VK_LValue,
9987                                                Found.getDecl(),
9988                                                TemplateArgs);
9989         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
9990         return DRE;
9991       } else {
9992         SourceLocation Loc = MemExpr->getMemberLoc();
9993         if (MemExpr->getQualifier())
9994           Loc = MemExpr->getQualifierLoc().getBeginLoc();
9995         Base = new (Context) CXXThisExpr(Loc,
9996                                          MemExpr->getBaseType(),
9997                                          /*isImplicit=*/true);
9998       }
9999     } else
10000       Base = MemExpr->getBase();
10001
10002     ExprValueKind valueKind;
10003     QualType type;
10004     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10005       valueKind = VK_LValue;
10006       type = Fn->getType();
10007     } else {
10008       valueKind = VK_RValue;
10009       type = Context.BoundMemberTy;
10010     }
10011
10012     MemberExpr *ME = MemberExpr::Create(Context, Base,
10013                                         MemExpr->isArrow(),
10014                                         MemExpr->getQualifierLoc(),
10015                                         Fn,
10016                                         Found,
10017                                         MemExpr->getMemberNameInfo(),
10018                                         TemplateArgs,
10019                                         type, valueKind, OK_Ordinary);
10020     ME->setHadMultipleCandidates(true);
10021     return ME;
10022   }
10023
10024   llvm_unreachable("Invalid reference to overloaded function");
10025   return E;
10026 }
10027
10028 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
10029                                                 DeclAccessPair Found,
10030                                                 FunctionDecl *Fn) {
10031   return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
10032 }
10033
10034 } // end namespace clang