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